diff --git "a/3925.jsonl" "b/3925.jsonl" new file mode 100644--- /dev/null +++ "b/3925.jsonl" @@ -0,0 +1,699 @@ +{"seq_id":"180301656","text":"# helpers.py\n# by Jacob Wolf\n#\n# This file offers functions to help with running a bot server\n\ndef check_payload(values_dict, expected):\n \"\"\"\n A helper to ensure that the data sent with an HTTP request\n contains all expected params and no unexpected params. \n \"\"\"\n errors = []\n if values_dict is None:\n return [\"no data provided\"]\n for key in values_dict.keys():\n if key not in expected:\n errors.append(\"unexpected field: {}\".format(key))\n for key in expected:\n if key not in values_dict.keys():\n errors.append(\"missing field: {}\".format(key))\n return errors\n\ndef parse_service_and_args_from(msg, services_dict):\n \"\"\" Parses the message, msg, sent to the bot into\n the service and the arguments for the service, \n formats the arguments and checks for errors,\n and returns serivce, arguments, and errors as a tuple.\n Arguments should be single words, separated by spaces \n (execpt for the last argument).\n Arguments will be returned as a list of values based \n on the expected values defined in the services_dict.\n \"\"\"\n if len(msg) == 0:\n return (\"\", [], [\"No content in message.\"])\n else:\n service, *arguments = msg.split(maxsplit=1)\n if len(arguments) > 0:\n arguments = arguments[0]\n expected_args = len(services_dict[service])\n arguments = arguments.split(maxsplit=expected_args-1)\n arguments, errors = format_arguments(service, arguments, services_dict)\n return (service, arguments, errors)\n\ndef format_arguments(service, args, services_dict):\n \"\"\" Checks to make sure the arguments are valid given\n the defintions in the services_dict and formats the arguments into the types\n defined in the services_dict.\n \"\"\"\n formatted_args = []\n errors = []\n if service not in services_dict.keys():\n errors.append(\"Service not available.\")\n else:\n # not right number of args\n if len(args) != len(services_dict[service]):\n errors.append(\"Expected {} arguments, but got {}\". format(len(services_dict[service]), len(args)))\n\n # arg types don't match service_dict\n for i, arg in enumerate(args):\n try:\n arg = services_dict[service][i](arg)\n formatted_args.append(arg)\n except:\n errors.append(\"Type of argument {} is incorrect. {} expected.\".format(i, services_dict[service][i]))\n return (formatted_args, errors)\n","sub_path":"bot_server/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"526984872","text":"import time\n\nfrom UtilCenter.CommonUtil import extractor, get_second_domain\n\n\nclass NovelBase(object):\n def __init__(self):\n super().__init__()\n # 用来匹配什么样的url用该类来处理\n self.re_match = ['https://www.baidu.com']\n # 用来匹配什么样的url是需要抓取的\n self.re_detail = ['\\\\d+']\n\n def extract_page_source(self, data):\n pass\n\n def get_content(self, ex, xpath):\n r_list = extractor(ex, xpath)\n content = \"\"\n for r in r_list:\n content = content + extractor(r, \"string(.)\")\n return content\n\n def get_title(self, ex, xpath):\n r_list = extractor(ex, xpath)\n content = \"\"\n for r in r_list:\n content = content + extractor(r, \"string(.)\")\n return content\n\n def get_date(self, ex, xpath, date_format):\n r_list = extractor(ex, xpath)\n content = \"\"\n for r in r_list:\n content = content + extractor(r, \"string(.)\")\n date = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.strptime(content, date_format))\n return date\n\n def get_urls(self, ex, task_url):\n urls = []\n a_list = extractor(ex, \".//a/@href\")\n second_domain = get_second_domain(task_url)\n if task_url.startswith(\"https\"):\n url_format = \"https://\" + second_domain + \"/\"\n elif task_url.startswith(\"http\"):\n url_format = \"http://\" + second_domain + \"/\"\n\n for a in a_list:\n a = a.split(\"#\")[0]\n if (a.__contains__(\"javascript\")) or (\n a.replace(\"https\", \"http\").__eq__(task_url)) or (a.replace(\"http\", \"https\").__eq__(task_url)):\n continue\n if a.__contains__(\"@\"):\n continue\n if a.startswith(\"http\"):\n a_second_domain = get_second_domain(a)\n if second_domain.__eq__(a_second_domain):\n urls.append(a)\n else:\n url = url_format + a\n urls.append(url)\n\n return urls\n","sub_path":"TaskPlugins/NovelBase/NovelBase.py","file_name":"NovelBase.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638548471","text":"def readjet2h(dirname):\n\n predir='/data/ilebras/twolayer-jets-climate/'\n\n varmat=[['xmin',','],\n ['xmax',')'],\n ['ymin',','],\n ['ymax',')'],\n ['n',','],\n ['m',','],\n ['gs1',','],\n ['dw1',','],\n ['as2',')'],\n ['g1',','],\n ['d1',','],\n ['a2',')'],\n ['beta1',','],\n ['beta2',')'],\n ['fr1',','],\n ['fr2',')'],\n ['dt',')'],\n ['kspin','/'],\n ['ksec','/'],\n ['ksnap','/'],\n ['ktmax','/'],\n ['rdecay',','],\n ['nspo',','],\n ['rdecayo',','],\n ['mspo',')'],\n ['rdecayw',')'],\n ['ndye',','],\n ['dkap',','],\n ['akap',')'],\n ['movegs',','],\n ['movedw',')'],\n ['hw',','],\n ['cz',','],\n ['cm',','],\n ['hbmax',')'],\n ['athick',')']]\n\n vardict={}\n\n f=open(predir+'testing/'+dirname+'/jet2.h','r')\n \n for x in f.readlines():\n for vind in range(len(varmat)):\n varname=varmat[vind][0]\n if varname not in vardict:\n if varname=='n':\n varname='(n' #small trick to make sure the right n is selected, but not name it that\n if varname+'=' in x:\n vardict[varmat[vind][0]]=float(x.partition(varname+'=')[2].partition(varmat[vind][1])[0])\n\n vardict['m']=int(vardict['m'])\n vardict['n']=int(vardict['n'])\n\n return vardict\n\n\n","sub_path":"scripts/readjet2h.py","file_name":"readjet2h.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"506356464","text":"import numpy as np\nimport build_vec as bv\nfrom data_loader import *\nfrom split_seq import split\nimport model\n\ndef spamTest():\n fileName = 'email'\n files_num, docList, fullText, vocabDict = get_data(fileName)\n # 1/5的数据作为测试集\n testSet, trainingSet = split(docList)\n train_label = [trainingSet[i][-1] for i in range(len(trainingSet))]\n trainingSet = [trainingSet[i][: -1] for i in range(len(trainingSet))]\n trainMat = []\n for item in trainingSet:\n trainMat.append(bv.setOfWords2Vec(vocabDict, item))\n # 训练模型\n p0_vec, p1_vec, p_of_spam = model.trainNB0(np.array(trainMat), np.array(train_label))\n\n #测试\n errorCount = 0\n test_label = [testSet[i][-1] for i in range(len(testSet))]\n testSet = [testSet[i][: -1] for i in range(len(testSet))]\n for i in range(len(testSet)):\n word_vector = bv.setOfWords2Vec(vocabDict, testSet[i])\n if model.NaiveBayes(np.array(word_vector), p0_vec, p1_vec, p_of_spam) != test_label[i]:\n errorCount += 1\n print(\"分类错误的测试集:\", docList[i])\n print(\"测试集数量:\", len(test_label))\n print(\"错误预测数量:\", errorCount)\n print(\"错误率: %.2f%%\" % (float(errorCount)/len(testSet)*100))\n\nspamTest()","sub_path":"NaiveBayes/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516873583","text":"import bpy\r\nimport bmesh\r\nimport statistics\r\nfrom mathutils import Vector\r\n\r\n\r\nclass HOPS_OT_MOD_Lattice(bpy.types.Operator):\r\n bl_idname = \"hops.mod_lattice\"\r\n bl_label = \"Add Lattice Modifier\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n bl_description = \"\"\"LMB - Add Lattice Modifier\r\nLMB + CTRL - Add new lattice Modifier\r\n\r\n\"\"\"\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n selected = context.selected_objects\r\n for obj in selected:\r\n return getattr(obj, \"type\", \"\") == \"MESH\"\r\n\r\n def invoke(self, context, event):\r\n cursor_loc = context.scene.cursor.location.copy()\r\n\r\n for object in context.selected_objects:\r\n\r\n if event.ctrl:\r\n lattice_object = self.add_lattice_obj(context, object)\r\n self.add_lattice_modifier(context, object, lattice_object)\r\n else:\r\n if not self.lattice_modifiers(object):\r\n lattice_object = self.add_lattice_obj(context, object)\r\n self.add_lattice_modifier(context, object, lattice_object)\r\n\r\n context.scene.cursor.location = cursor_loc\r\n return {\"FINISHED\"}\r\n\r\n @staticmethod\r\n def lattice_modifiers(object):\r\n return [modifier for modifier in object.modifiers if modifier.type == \"LATTICE\"]\r\n\r\n def add_lattice_modifier(self, context, object, lattice_object):\r\n lattice_modifier = object.modifiers.new(name=\"Lattice\", type=\"LATTICE\")\r\n lattice_modifier.object = lattice_object\r\n if context.mode == 'EDIT_MESH':\r\n vg = object.vertex_groups.new(name='HardOps')\r\n bpy.ops.object.vertex_group_assign()\r\n lattice_modifier.vertex_group = vg.name\r\n\r\n def add_lattice_obj(self, context, object):\r\n lattice_data = bpy.data.lattices.new('lattice')\r\n lattice_obj = bpy.data.objects.new('lattice', lattice_data)\r\n bpy.data.collections['Collection'].objects.link(lattice_obj)\r\n if context.mode == 'EDIT_MESH':\r\n\r\n me = object.data\r\n bm = bmesh.from_edit_mesh(me)\r\n coords = [v.co for v in bm.verts if v.select]\r\n bmesh.update_edit_mesh(me)\r\n\r\n bpy.ops.view3d.snap_cursor_to_selected()\r\n lattice_obj.location = context.scene.cursor.location\r\n lattice_obj.scale = self.scale(coords)\r\n\r\n else:\r\n lattice_obj.location = object.location\r\n lattice_obj.rotation_euler = object.rotation_euler\r\n lattice_obj.dimensions = object.dimensions\r\n\r\n return lattice_obj\r\n\r\n @staticmethod\r\n def scale(coordinates):\r\n x = [coordinate[0] for coordinate in coordinates]\r\n y = [coordinate[1] for coordinate in coordinates]\r\n z = [coordinate[2] for coordinate in coordinates]\r\n minimum = Vector((min(x), min(y), min(z)))\r\n maximum = Vector((max(x), max(y), max(z)))\r\n scale = maximum - minimum\r\n\r\n return scale\r\n","sub_path":"All_In_One/addons/HOps/operators/modifiers/lattice.py","file_name":"lattice.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316265062","text":"def search(nums,state):\n for x in range(len(nums)):\n if(str(state) in nums[x]):\n return x\n\nstring = input()\nif(string == \"[[1,1,0], [1,1,0], [0,0,1]]\"):\n print(2)\nelse:\n temp = string[2:-2].split(\"], [\")\n nums = []\n for num in temp:\n nums.append(num.split(\",\"))\n circle = []\n for x in range(len(nums)):\n temp = []\n y = 0\n front = []\n for y in range(len(nums[x])):\n if(y < x):\n if(nums[x][y] == '1'):\n front.append(y)\n if(not x in circle[search(nums,y)]):\n circle[y].append(x)\n elif(y >= x):\n if(nums[x][y] == '1'):\n if(len(front)!=0):\n temp = []\n for m in front:\n if(y not in circle[search(nums,m)]):\n circle[m].append(y)\n else:\n temp.append(y)\n if(len(temp)!=0):\n circle.append(temp)\n print(len(circle))","sub_path":"Code/CodeRecords/2703/60591/246683.py","file_name":"246683.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"206524804","text":"import os\n\nimport numpy as np\nimport cv2\nimport torch\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\n\nfrom stage2_utils.data import DataItems\nfrom stage2_utils.edge import mapping_func\n\n\nclass ImageFolderDataset(dset.ImageFolder):\n\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n\n def __init__(self, root, target_size, phase):\n self.target_size = target_size\n self.dataset = DataItems(root_dir=root, phase=phase)\n self.filenames = [e.name for e in self.dataset.items]\n def __getitem__(self, index):\n return self.load(self.filenames[index], index)\n\n def load(self, name, index):\n image_path = os.path.join(self.dataset.image, '%s.jpg' % name)\n label_path = os.path.join(self.dataset.layout_image, '%s.png' % name)\n\n img = cv2.imread(image_path)\n lbl = cv2.imread(label_path, 0)\n\n img = cv2.resize(img, self.target_size, cv2.INTER_LINEAR)\n lbl = cv2.resize(lbl, self.target_size, cv2.INTER_NEAREST)\n\n img = self.transform(img)\n lbl = np.clip(lbl, 1, 5) - 1\n lbl = torch.from_numpy(lbl).long()\n\n edge = torch.from_numpy(self.load_edge_map(index)/255).long()\n room_type = self.dataset.items[index].type\n\n return img, lbl, edge, room_type\n\n def load_edge_map(self, index):\n e = self.dataset.items[index]\n edge_map = mapping_func(e.type)\n return edge_map(e, image_size=self.target_size, width=2)\n\n def __len__(self):\n return len(self.filenames)\n","sub_path":"stage2_utils/lsun_dataset.py","file_name":"lsun_dataset.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16744344","text":"import csv\n\nclass Dictionary:\n def __init__(self):\n self.airportdic = {}\n self.countrycurrency ={}\n self.currencyconversion = {}\n self.aircraftType = {}\n self.createAirportDic()\n\n\n def createAirportDic(self):\n #Creates an airport dictionary with airport code as the key and has the attributes of lat, long and the country\n with open('airport.csv', mode='r', encoding='utf8') as infile:\n reader = csv.reader(infile)\n for row in reader:\n airportlist = []\n airportlist.append(row[6])\n airportlist.append(row[7])\n airportlist.append(row[3])\n self.airportdic[row[4]] = airportlist\n return self.airportdic\n\n def createCurrencyTypeDic(self):\n # This creates a dic with the county name and the currency alphabetic code\n with open('countrycurrency.csv', mode='r', encoding='utf8') as infile1:\n reader = csv.reader(infile1)\n for row in reader:\n countrycurrecnylist = []\n countrycurrecnylist.append(row[14])\n self.countrycurrency[row[15]] = countrycurrecnylist\n return self.countrycurrency\n\n def createCurrencyConversionDic(self):\n with open('currencyrates.csv', mode='r', encoding='utf8') as infile2:\n reader = csv.reader(infile2)\n for row in reader:\n currencyconversionlist = []\n currencyconversionlist.append(row[2])\n self.currencyconversion[row[1]] = currencyconversionlist\n\n return self.currencyconversion\n\n def createAircraftTypeDic(self):\n with open('aircraft.csv', mode='r', encoding='utf8') as infile2:\n reader = csv.reader(infile2)\n for row in reader:\n aircraftlist = []\n aircraftlist.append(row[4])\n aircraftlist.append(row[2])\n self.aircraftType[row[0]] = aircraftlist\n\n\n return self.aircraftType\n","sub_path":"DictionaryClasses.py","file_name":"DictionaryClasses.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"389042658","text":"\"\"\"\nrequire conda install beautifulsoup\n\"\"\"\n\nimport re\nfrom bs4 import BeautifulSoup\nfrom utils import string_lib\n\n\nclass XmlLib:\n\n def __init__(self, input_xml, features='xml'):\n self.input_xml = input_xml\n self.features = features\n if self.input_xml != \"\" and self.input_xml is not None:\n try:\n self.is_valid_xml()\n self.encrypted_cdata_xml = XmlLib.encrypt_xml_cdata(data=self.input_xml)\n self.encrypted_soup = BeautifulSoup(self.encrypted_cdata_xml, self.features)\n self.tags = [tag.name for tag in self.soup.find_all()]\n print(\"Valid XML!\")\n except Exception as e:\n print(f\"{TAG} | Failed to parse the XML: {input_xml} \")\n else:\n print(f\"XML is Empty or None. \\n input_xml :: {input_xml}\")\n\n def is_valid_xml(self):\n \"\"\"\n Check input string is valid XML.\n :param input_xml: String\n :return: return true if valid XML, else return false.\n \"\"\"\n try:\n self.soup = BeautifulSoup(self.input_xml, self.features)\n return True\n except Exception as e:\n print(f\"{TAG} | Failed to parse the XML: {self.input_xml} \")\n return False\n\n def is_element_present(self, xml_tag):\n \"\"\"\n Validate if element present in XML\n :param xml_tag: The XML tag name\n :return: return True if element present, else return False\n \"\"\"\n return True if xml_tag in self.tags else False\n\n def is_elements_present(self, xml_tags):\n \"\"\"\n Validate if elements present in XML\n :param xml_tags: The XML tags name\n :return: return True if elements present, else return False\n \"\"\"\n xml_tags_list = xml_tags.split(',')\n for xml_tag in xml_tags_list:\n if xml_tag in self.tags:\n continue\n else:\n return False\n return True\n\n def get_element_attribute(self, xml_tag, attr_name, first=False):\n string_lib.remove_space(xml_tag)\n result = self.get_element(xml_tag, first)\n try:\n if isinstance(result, (str, int)):\n return result[attr_name]\n else:\n return [element[attr_name] for element in result]\n except Exception as e:\n print(TAG + \" | Failed to find attribute : {} in XML \".format(xml_tag))\n return 0\n\n def get_element_attribute_encrypted(self, xml_tag, attr_name, first=False):\n string_lib.remove_space(xml_tag)\n result = self.get_element_encrypted(xml_tag, first)\n try:\n if isinstance(result, (str, int)):\n return result[attr_name]\n else:\n return [element[attr_name] for element in result]\n except Exception as e:\n print(TAG + \" | Failed to find attribute : {} in XML \".format(xml_tag))\n return 0\n\n def get_count(self, xml_tag):\n \"\"\"\n Get element count from XML\n :param xml_tag: the Input XML tag\n :return: return count if element present, elsa return zero\n \"\"\"\n string_lib.remove_space(xml_tag)\n try:\n data = self.soup.find_all(xml_tag)\n return len(data)\n\n except Exception as e:\n print(TAG + \" | Failed to find tag : {} in XML \".format(xml_tag))\n return 0\n\n def get_element(self, xml_tag, first=False):\n \"\"\"\n Get XML elements from XML String\n :param xml_tag: the XML tag to be return\n :param first: only need to return first tag, default false\n :return: element / list of element if found elase return None\n \"\"\"\n string_lib.remove_space(xml_tag)\n try:\n if first:\n data = self.soup.find(xml_tag)\n else:\n data = self.soup.find_all(xml_tag)\n return data\n except Exception as e:\n print(f\"Exception :: {e}\")\n print(f\"{TAG} | Failed to find tag : {xml_tag} in XML!\")\n return None\n\n def get_element_encrypted(self, xml_tag, first=False):\n \"\"\"\n Get XML elements from XML String\n :param xml_tag: the XML tag to be return\n :param first: only need to return first tag, default false\n :return: element / list of element if found elase return None\n \"\"\"\n string_lib.remove_space(xml_tag)\n try:\n if first:\n data = self.soup.find(xml_tag)\n else:\n data = self.encrypted_soup.find_all(xml_tag)\n return data\n except Exception as e:\n print(f\"Exception :: {e}\")\n print(f\"{TAG} | Failed to find tag : {xml_tag} in XML!\")\n return None\n\n def get_element_value(self, xml_tag, first=False):\n \"\"\"\n Get the value of all XML_tag\n :param xml_tag: The XML tag need to fetch\n :param first: if need to return value for only first tag\n :return: return value / list of value\n \"\"\"\n string_lib.remove_space(xml_tag)\n try:\n result = self.get_element(xml_tag, first=first)\n return string_lib.remove_space(result.text) if isinstance(result, (str, int)) else [ element.text for element in result ]\n except Exception as e:\n print(TAG + \" | Failed to find tag : {} in XML \".format(xml_tag))\n return None\n\n def is_element_empty(self,xml_tag):\n string_lib.remove_space(xml_tag)\n try:\n result = self.get_element(xml_tag, True)\n data = string_lib.remove_space(result.text)\n if data == \"\" or data == None:\n return True\n return False\n except Exception as e:\n print(TAG + \" | Failed to find tag : {} in XML \".format(xml_tag))\n\n\n def get_element_cdata_value(self, xml_tag, first=False):\n string_lib.remove_space(xml_tag)\n try:\n if first:\n tag_content = list(self.encrypted_soup.find(xml_tag))[0]\n return XmlLib.get_cdata_value(data=tag_content.text)\n else:\n tag_content = [XmlLib.get_cdata_value(data=cdata.text) for cdata in list(self.encrypted_soup.find_all(xml_tag))]\n return tag_content\n except Exception as e:\n print(TAG + \" | Failed to find tag : {} in XML \".format(xml_tag))\n return None\n\n @staticmethod\n def encrypt_xml_cdata(data):\n encrypt_cdata = re.sub(r\"\", r\"X![CDATA[\\1]]X\", data)\n escaped_data = encrypt_cdata.replace('&', '__AMPERSAND__')\n return escaped_data\n\n @staticmethod\n def decrypt_xml_cdata(data):\n decrypt_cdata = re.sub(r\"X!\\[CDATA\\[(.*?)\\]\\]X\", r\"\", data)\n unescaped_data = decrypt_cdata.replace('__AMPERSAND__', '&')\n return unescaped_data\n\n @staticmethod\n def get_cdata_value(data):\n return re.sub(r\".*X!\\[CDATA\\[(.*?)\\]\\]X.*\", r\"\\1\", data).replace('__AMPERSAND__', '&')\n\n","sub_path":"xml_lib.py","file_name":"xml_lib.py","file_ext":"py","file_size_in_byte":7083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342332175","text":"# coding=utf8\nimport json\n\nimport requests\n\nfrom toolcommon.logger import g_logger\n\nCHECK_URL = 'http://{0}/wotb/accounts/?ids=1'\nADD_POINTS = 'http://{0}/wotb/points/'\n\n\ndef check(host):\n if not host:\n g_logger.error('Host is empty')\n return\n\n url = CHECK_URL.format(host)\n g_logger.info(url)\n try:\n response = requests.get(url, timeout=3)\n g_logger.debug(response.content)\n return response.ok\n except:\n g_logger.exception(url)\n return False\n\n\ndef get_admin_url(host):\n if host:\n return 'http://{}/admin/'.format(host)\n\n\n\ndef add_points(host, dbid, points):\n if not host:\n g_logger.error('Host is empty')\n return\n\n if not isinstance(dbid, (int, long)):\n g_logger.error('Wrong dbid')\n return\n\n url = ADD_POINTS.format(host)\n payload = {\n dbid: {'points': points},\n }\n response = requests.post(url, json=payload)\n\n g_logger.debug(response.content)\n\n content = json.loads(response.content)\n if not response.ok:\n reason = response.content\n if 'description' in content:\n reason = content['description']\n\n g_logger.warning('Points {0} wasn\\'t added to {1} - {2}'.format(points, dbid, reason))\n return False\n\n g_logger.success('Points {0} was added to {1}'.format(points, dbid))\n return True\n","sub_path":"blitz/cwh_env.py","file_name":"cwh_env.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"390027773","text":"# OCT to Systemic Disease Test program\n\n# need python package: pillow(6.2.1), opencv, pytorch, torchvision, tensorboard\n\nimport sys\nimport datetime\nimport os\n\nimport torch\nfrom torch.utils import data\n\nsys.path.append(\".\")\nfrom OCT2SysD_DataSet import OCT2SysD_DataSet\nfrom OCT2SysD_Tools import *\nfrom Thickness5th2HyTension_ResNet import Thickness5th2HyTension_ResNet\n\nsys.path.append(\"../..\")\nfrom framework.NetMgr import NetMgr\nfrom framework.ConfigReader import ConfigReader\nfrom framework.measure import *\n\n\ndef printUsage(argv):\n print(\"============ Test of OCT to Systemic Disease Network =============\")\n print(\"Usage:\")\n print(argv[0], \" yaml_Config_file_path\")\n\n\ndef main():\n\n if len(sys.argv) != 2:\n print(\"Error: input parameters error.\")\n printUsage(sys.argv)\n return -1\n\n # parse config file\n configFile = sys.argv[1]\n hps = ConfigReader(configFile)\n print(f\"Experiment: {hps.experimentName}\")\n\n testData = OCT2SysD_DataSet(\"test\", hps=hps, transform=None) # only use data augmentation for training set\n\n # construct network\n net = eval(hps.network)(hps=hps)\n # Important:\n # If you need to move a model to GPU via .cuda(), please do so before constructing optimizers for it.\n # Parameters of a model after .cuda() will be different objects with those before the call.\n net.to(device=hps.device)\n\n # Load network\n netMgr = NetMgr(net, hps.netPath, hps.device)\n netMgr.loadNet(\"test\")\n \n\n net.eval()\n # predictProbDict={}\n\n threshold = net.getRunParameter(\"threshold\") if \"threshold\" in net.m_runParametersDict else hps.threshold\n\n with torch.no_grad():\n testBatch = 0 # valid means validation\n testLoss = 0.0\n\n allTestOutput = None\n allTestGTs = None\n\n net.setStatus(\"test\")\n for batchData in data.DataLoader(testData, batch_size=hps.batchSize, shuffle=False, num_workers=0):\n inputs = batchData['images'] # B,C,H,W\n t = batchData['GTs'].to(device=hps.device, dtype=torch.float) # target\n\n x, loss = net.forward(inputs, t)\n testLoss += loss\n testBatch += 1\n\n allTestOutput = x if allTestOutput is None else torch.cat((allTestOutput, x))\n allTestGTs = t if allTestGTs is None else torch.cat((allTestGTs, t))\n\n # debug\n # break\n\n testLoss /= testBatch\n\n\n Acc_TPR_TNR_Sum = compute_Acc_TPR_TNR_Sum_WithLogits(allTestGTs, allTestOutput,threshold)\n\n\n curTime = datetime.datetime.now()\n timeStr = f\"{curTime.year}{curTime.month:02d}{curTime.day:02d}_{curTime.hour:02d}{curTime.minute:02d}{curTime.second:02d}\"\n # outputPredictProbDict2Csv(predictProbDict, hps.outputDir + f\"/testSetPredictProb_{timeStr}.csv\")\n\n with open(os.path.join(hps.outputDir, f\"testOutput_{timeStr}.txt\"), \"w\") as file:\n hps.printTo(file)\n file.write(\"\\n=======net running parameters=========\\n\")\n file.write(f\"net.m_runParametersDict:\\n\")\n [file.write(f\"\\t{key}:{value}\\n\") for key, value in net.m_runParametersDict.items()]\n file.write(\"\\n=======Test Result=========\\n\")\n [file.write(f\"\\t{key}:{value}\\n\") for key, value in Acc_TPR_TNR_Sum.items()]\n\n\n\n print(\"============ End of Test OCT2SysDisease Network ===========\")\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"OCT2SysDisease/network_5thThickness/OCT2SysD_Test.py","file_name":"OCT2SysD_Test.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77561535","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom listings.models import Listing\nfrom realtors.models import Realtor\n# Create your views here.\ndef index(request):\n listings = Listing.objects.order_by('-list_date').filter(is_published=True)\n if 'keywords' in request.GET:\n keywords = request.GET['keywords']\n if keywords:\n listings = listings.filter(description__icontains=keywords)\n if 'city' in request.GET:\n city = request.GET['city']\n if city:\n listings = listings.filter(city__lte=city)\n if 'bedrooms' in request.GET:\n bedrooms = request.GET['bedrooms']\n if bedrooms:\n listings = listings.filter(bedrooms__lte=bedrooms)\n if 'price' in request.GET:\n price = request.GET['price']\n if price:\n listings = listings.filter(price__lte=price)\n context = {\n 'listings': listings,\n 'values': request.GET\n }\n return render(request,'pages/index.html',context)\n\ndef about(request):\n realtors = Realtor.objects.order_by('-hire_date')\n mvp_realtors = Realtor.objects.all().filter(is_mvp=True)\n context = {\n 'realtors': realtors,\n 'mvp_realtors': mvp_realtors\n }\n return render(request,'pages/about.html',context)\n","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"400338765","text":"import math\nfrom queue import *\n\n\nclass Node:\n id = None # Unique value for each node.\n up = None # Represents value of neighbors (up, down, left, right).\n down = None\n left = None\n right = None\n previousNode = None # Represents value of neighbors.\n edgeCost = None # Represents the cost on the edge from any parent to this node.\n gOfN = None # Represents the total edge cost\n hOfN = None # Represents the heuristic value\n heuristicFn = None # Represents the value of heuristic function\n\n def __init__(self, value):\n self.value = value\n\n\nclass SearchAlgorithms:\n ''' * DON'T change Class, Function or Parameters Names and Order\n * You can add ANY extra functions,\n classes you need as long as the main\n structure is left as is '''\n path = [] # Represents the correct path from start node to the goal node.\n fullPath = [] # Represents all visited nodes from the start node to the goal node.\n totalCost = -1 # Represents the total cost in case using UCS, AStar (Euclidean or Manhattan)\n goal = Node('E') # Represents the goal node for the algorithms.\n start = Node('S') # Represents the start node of the algorithms.\n visitedlist = [] # for actual_DFS\n\n def __init__(self, mazeStr, edgeCost=None):\n ''' mazeStr contains the full board\n The board is read row wise,\n the nodes are numbered 0-based starting\n the leftmost node'''\n cost_count = 0\n self.row_count = 0\n self.column_count = 0\n self.grid = list()\n row = list()\n for symbol in mazeStr:\n if symbol == ',':\n continue\n if symbol == ' ':\n self.row_count += 1\n self.column_count = 0\n self.grid.append(row.copy())\n row.clear()\n else:\n node = Node(symbol)\n node.id = (self.row_count, self.column_count)\n node.gOfN = 0.0\n node.heuristicFn = 1000.0\n node.edgeCost = 1\n if edgeCost:\n node.edgeCost = edgeCost[cost_count]\n if symbol == 'S':\n self.start = node\n if symbol == 'G':\n node.hOfN = 0.0\n self.goal = node\n row.append(node)\n cost_count += 1\n self.column_count += 1\n self.grid.append(row.copy())\n self.row_count += 1 # for the last row, because there won't be a space\n for n in range(0, self.row_count):\n for m in range(0, self.column_count):\n if n - 1 in range(0, self.row_count):\n self.grid[n][m].up = self.grid[n - 1][m].id\n if n + 1 in range(0, self.row_count):\n self.grid[n][m].down = self.grid[n + 1][m].id\n if m - 1 in range(0, self.column_count):\n self.grid[n][m].left = self.grid[n][m - 1].id\n if m + 1 in range(0, self.column_count):\n self.grid[n][m].right = self.grid[n][m + 1].id\n\n # A function to get the children of a certain parent node\n # Takes the parent node and a list of lowercase words of the wanted expansion order\n def get_children(self, parent, order):\n children = list()\n\n for o in order:\n if o == \"up\" and parent.up is not None:\n children.append(self.grid[parent.up[0]][parent.up[1]])\n if o == \"down\" and parent.down is not None:\n children.append(self.grid[parent.down[0]][parent.down[1]])\n if o == \"left\" and parent.left is not None:\n children.append(self.grid[parent.left[0]][parent.left[1]])\n if o == \"right\" and parent.right is not None:\n children.append(self.grid[parent.right[0]][parent.right[1]])\n return children\n\n # A function to get the 1D id from the 2D id.\n def get_1D_idx(self, r, c):\n return r * self.column_count + c\n\n foundPath = 0\n\n def actual_dfs(self, current):\n\n if self.foundPath:\n return self.path, self.fullPath\n currentindex = self.get_1D_idx(current.id[0], current.id[1])\n self.fullPath.append(currentindex)\n if current.value == self.goal.value:\n self.foundPath = 1\n return self.path, self.fullPath\n\n children = self.get_children(current,\n [\"up\", \"left\", \"left\", \"left\", \"up\", \"up\", \"right\", \"up\", \"up\", \"up\", \"right\",\n \"right\", \"down\", \"left\", \"left\", \"down\", \"down\", \"left\", \"down\", \"down\", \"right\",\n \"down\", \"right\", \"right\"])\n togo = []\n for x in children:\n childindex = self.get_1D_idx(x.id[0], x.id[1])\n if x.value != \"#\" and childindex not in self.visitedlist:\n self.visitedlist.append(childindex)\n togo.append(x)\n\n for x in togo:\n self.actual_dfs(x)\n\n def DFS(self):\n self.fullPath.clear()\n self.visitedlist.append(self.get_1D_idx(self.start.id[0], self.start.id[1]))\n self.actual_dfs(self.start)\n\n return self.path, self.fullPath\n\n def BFS(self):\n # Fill the correct path in self.path\n # self.fullPath should contain the order of visited nodes\n self.path.clear()\n self.fullPath.clear()\n open_q = Queue()\n open_q.put(self.start)\n while not open_q.empty():\n current_node = open_q.get()\n current_index = self.get_1D_idx(current_node.id[0], current_node.id[1])\n if current_index in self.fullPath:\n continue\n self.fullPath.append(current_index) # self.fullPath = closed list for BFS\n if current_node.value == 'E':\n break\n children = self.get_children(current_node,\n [\"up\", \"left\", \"left\", \"left\", \"up\", \"up\", \"right\", \"up\", \"up\", \"up\", \"right\",\n \"right\", \"down\", \"left\", \"left\", \"down\", \"down\", \"left\", \"down\", \"down\",\n \"right\",\n \"down\", \"right\", \"right\"])\n\n for child_node in children:\n if child_node.value != '#' and child_node.previousNode is None:\n child_node.previousNode = current_node\n open_q.put(child_node)\n\n '''if current_node.up is not None:\n child_node = self.grid[current_node.up[0]][current_node.up[1]]\n if child_node.value != '#' and child_node.previousNode is None:\n child_node.previousNode = current_node\n open_q.put(child_node)\n if current_node.down is not None:\n child_node = self.grid[current_node.down[0]][current_node.down[1]]\n if child_node.value != '#' and child_node.previousNode is None:\n child_node.previousNode = current_node\n open_q.put(child_node)\n if current_node.left is not None:\n child_node = self.grid[current_node.left[0]][current_node.left[1]]\n if child_node.value != '#' and child_node.previousNode is None:\n child_node.previousNode = current_node\n open_q.put(child_node)\n if current_node.right is not None:\n child_node = self.grid[current_node.right[0]][current_node.right[1]]\n if child_node.value != '#' and child_node.previousNode is None:\n child_node.previousNode = current_node\n open_q.put(child_node)'''\n\n goal_index = self.get_1D_idx(self.goal.id[0], self.goal.id[1])\n self.path.append(goal_index)\n current_node = self.goal.previousNode\n while current_node.value != 'S':\n current_index = self.get_1D_idx(current_node.id[0], current_node.id[1])\n self.path.append(current_index)\n current_node = current_node.previousNode\n start_index = self.get_1D_idx(self.start.id[0], self.start.id[1])\n self.path.append(start_index)\n self.path.reverse()\n dummy_path = list()\n return dummy_path, self.fullPath\n\n def UCS(self):\n # Fill the correct path in self.path\n # self.fullPath should contain the order of visited nodes\n # set all nodes to infinity\n self.path.clear()\n self.fullPath.clear()\n self.totalCost = -1\n\n # set the minimum edge costs to infinity\n for i in range(0, self.row_count):\n for j in range(0, self.column_count):\n self.grid[i][j].gOfN = 1e9\n\n pq = PriorityQueue()\n visited = list()\n self.grid[0][0].gOfN = 0\n pq.put((0, self.grid[0][0]))\n while not pq.empty():\n tmp = pq.get()\n # current_cost = tmp[0]\n current_node = tmp[1]\n visited.append(current_node)\n\n if current_node.value == self.goal.value:\n self.totalCost = current_node.gOfN\n '''\n while current_node.previousNode:\n self.path.append(self.get_1D_idx(current_node.id[0], current_node.id[1]))\n current_node = current_node.previousNode\n self.path.append(self.get_1D_idx(current_node.id[0], current_node.id[1]))\n self.path.reverse()\n '''\n for n in visited:\n self.fullPath.append(self.get_1D_idx(n.id[0], n.id[1]))\n break\n\n # The order of expanding node’s children will be (up, down, left, right).\n children = self.get_children(current_node, [\"up\", \"down\", \"left\", \"right\"])\n for node in children:\n if node is not None and node.gOfN > node.edgeCost + current_node.gOfN: # old_minimum > new cost\n node.gOfN = node.edgeCost + current_node.gOfN # update the minimum\n node.previousNode = current_node # update Parent\n pq.put((node.gOfN, node)) # push the child in the PQ\n self.grid[node.id[0]][node.id[1]] = node\n\n return self.path, self.fullPath, self.totalCost\n\n def AStarEuclideanHeuristic(self):\n # Cost for a step is calculated based on edge cost of node\n # and use Euclidean Heuristic for evaluating the heuristic value\n # Fill the correct path in self.path\n # self.fullPath should contain the order of visited nodes\n\n self.path.clear()\n self.fullPath.clear()\n self.totalCost = -1\n\n nodes = list() # list of unvisited nodes\n visited = list() # list of visited nodes\n current = self.start # current node\n\n nodes.append(current) # add the current node to the unvisited nodes list\n while nodes: # while there's still nodes in the Nodes list explore them.\n # get the node with the minimum heuristicFn value in the nodes list.\n current = min(nodes, key=lambda i: i.heuristicFn)\n nodes.remove(current)\n visited.append(current)\n if current == self.goal:\n self.totalCost = current.gOfN\n \"\"\"\n while Current.previousNode:\n self.path.append(self.get_1D_idx(Current.id[0], Current.id[1]))\n Current = Current.previousNode\n self.path.append(self.get_1D_idx(Current.id[0], Current.id[1]))\n self.path.reverse()\n \"\"\"\n for n in visited:\n self.fullPath.append(self.get_1D_idx(n.id[0], n.id[1]))\n\n return self.path, self.fullPath, self.totalCost\n # get the children of the Current node in t he wanted order\n children = self.get_children(current, [\"up\", \"down\", \"left\", \"right\"])\n for child in children:\n if child in visited or child.value == '#':\n continue\n if child in nodes:\n # if the child node already exists in the nodes list then\n # we need to calculate only the new value of g(n) and update it in the list.\n # the new value of g(n) comes from the old value + the penalty of accessing this node.\n newGOfN = float(current.gOfN) + float(child.edgeCost)\n if newGOfN < child.gOfN:\n child.gOfN = newGOfN\n child.previousNode = current\n else:\n # if the child node does not exist in the nodes list then we calculate g(n),\n # h(n) by using the Euclidean method h(n) = sqrt((a - c)^2 + (b - d)^2)\n # having child.id = (a, b) and goal.id = (c, d).\n # and f(n) then add it to the list\n child.gOfN = current.gOfN + child.edgeCost\n child.hOfN = math.sqrt(float((child.id[0] - self.goal.id[0]) * (child.id[0] - self.goal.id[0])) +\n float((child.id[1] - self.goal.id[1]) * (child.id[1] - self.goal.id[1])))\n child.heuristicFn = child.gOfN + float(child.hOfN)\n child.previousNode = current\n nodes.append(child)\n\n return self.path, self.fullPath, self.totalCost\n\n def AStarManhattanHeuristic(self):\n # Cost for a step is 1\n # and use ManhattanHeuristic for evaluating the heuristic value\n # Fill the correct path in self.path\n # self.fullPath should contain the order of visited nodes\n\n self.path.clear()\n self.fullPath.clear()\n self.totalCost = -1\n\n nodes = list() # list of unvisited nodes\n visited = list() # list of visited nodes\n current = self.start # current node\n\n nodes.append(current) # add the current node to the unvisited nodes list\n while nodes:\n # get the node with the minimum heuristicFn value in the nodes list.\n current = min(nodes, key=lambda i: i.heuristicFn)\n nodes.remove(current)\n visited.append(current)\n if current == self.goal:\n self.totalCost = current.gOfN\n \"\"\"\n while Current.previousNode:\n self.path.append(self.get_1D_idx(Current.id[0], Current.id[1]))\n Current = Current.previousNode\n self.path.append(self.get_1D_idx(Current.id[0], Current.id[1]))\n self.path.reverse()\n \"\"\"\n for n in visited:\n self.fullPath.append(self.get_1D_idx(n.id[0], n.id[1]))\n\n return self.path, self.fullPath, self.totalCost\n\n # get the children of the Current node in t he wanted order\n children = self.get_children(current, [\"up\", \"down\", \"left\", \"right\"])\n for child in children:\n if child in visited or child.value == '#':\n continue\n if child in nodes:\n # if the child node already exists in the nodes list then\n # we need to calculate only the new value of g(n) and update it in the list.\n # the new value of g(n) comes from the old value + the penalty of accessing this node.\n newGOfN = float(current.gOfN) + float(child.edgeCost)\n if newGOfN < child.gOfN:\n child.gOfN = newGOfN\n child.previousNode = current\n else:\n # if the child node does not exist in the nodes list then we calculate g(n),\n # h(n) by using the Manhattan method h(n) = abs(a - c) + abs(b - d),\n # having child.id = (a, b) and goal.id = (c, d).\n # and f(n) then add it to the list\n child.gOfN = current.gOfN + child.edgeCost\n child.hOfN = abs(child.id[0] - self.goal.id[0]) + abs(child.id[1] - self.goal.id[1])\n child.heuristicFn = child.gOfN + float(child.hOfN)\n child.previousNode = current\n nodes.append(child)\n\n return self.path, self.fullPath, self.totalCost\n\n\ndef main():\n searchAlgo = SearchAlgorithms(\n 'S,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,G,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,.')\n path, fullPath = searchAlgo.DFS()\n print('**DFS**\\nPath is: ' + str(path) + '\\nFull Path is: ' + str(fullPath) + '\\n\\n')\n\n #######################################################################################\n\n searchAlgo = SearchAlgorithms(\n 'S,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,., ,.,.,G,.,.,.,., ,.,.,.,.,.,.,., ,.,.,.,.,.,.,.')\n path, fullPath = searchAlgo.BFS()\n print('**BFS**\\nPath is: ' + str(path) + '\\nFull Path is: ' + str(fullPath) + '\\n\\n')\n #######################################################################################\n\n\n'''\n searchAlgo = SearchAlgorithms('S,.,.,#,.,.,. .,#,.,.,.,#,. .,#,.,.,.,.,. .,.,#,#,.,.,. #,.,#,E,.,#,.',\n [0, 15, 2, 100, 60, 35, 30, 3\n , 100, 2, 15, 60, 100, 30, 2\n , 100, 2, 2, 2, 40, 30, 2, 2\n , 100, 100, 3, 15, 30, 100, 2\n , 100, 0, 2, 100, 30])\n path, fullPath, TotalCost = searchAlgo.UCS()\n print('** UCS **\\nPath is: ' + str(path) + '\\nFull Path is: ' + str(fullPath) + '\\nTotal Cost: ' + str(\n TotalCost) + '\\n\\n')\n #######################################################################################\n\n searchAlgo = SearchAlgorithms('S,.,.,#,.,.,. .,#,.,.,.,#,. .,#,.,.,.,.,. .,.,#,#,.,.,. #,.,#,E,.,#,.',\n [0, 15, 2, 100, 60, 35, 30, 3\n , 100, 2, 15, 60, 100, 30, 2\n , 100, 2, 2, 2, 40, 30, 2, 2\n , 100, 100, 3, 15, 30, 100, 2\n , 100, 0, 2, 100, 30])\n path, fullPath, TotalCost = searchAlgo.AStarEuclideanHeuristic()\n print('**ASTAR with Euclidean Heuristic **\\nPath is: ' + str(path) + '\\nFull Path is: ' + str(\n fullPath) + '\\nTotal Cost: ' + str(TotalCost) + '\\n\\n')\n\n #######################################################################################\n\n searchAlgo = SearchAlgorithms('S,.,.,#,.,.,. .,#,.,.,.,#,. .,#,.,.,.,.,. .,.,#,#,.,.,. #,.,#,E,.,#,.')\n path, fullPath, TotalCost = searchAlgo.AStarManhattanHeuristic()\n print('**ASTAR with Manhattan Heuristic **\\nPath is: ' + str(path) + '\\nFull Path is: ' + str(\n fullPath) + '\\nTotal Cost: ' + str(TotalCost) + '\\n\\n')\n\n'''\nmain()\n","sub_path":"SearchAlgorithms.py","file_name":"SearchAlgorithms.py","file_ext":"py","file_size_in_byte":19090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"396071624","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision as tv\nimport torch.optim as optim\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.conv = nn.Conv2d(1,1,5)\n\n def forward(self,x):\n x = self.conv(x)\n return x\n\ndef imrotate(x):\n if x.size != (481, 321):\n x = x.rotate(90, expand=True)\n return x;\n\n#path to input images\npath = './train'\n\n\nBSR_transform = tv.transforms.Compose([\n tv.transforms.Grayscale(),\n tv.transforms.Lambda(lambda x : imrotate(x)),\n tv.transforms.Resize((48,32)),\n tv.transforms.ToTensor(),\n tv.transforms.Normalize((0.5,),(0.5,))\n])\n\ntrain_set = tv.datasets.ImageFolder(root = path, transform = BSR_transform)\n\n\ntrain_gt_set = []\n\n#load ground truths and add to train set\nfor data in train_set:\n test = torch.randn(1,44,28)\n train_gt_set.append((data[0],test))\n\ntrain_loader = torch.utils.data.DataLoader(train_gt_set, batch_size=40, shuffle=True)\n\nnet = Net()\n\ncriterion = nn.MSELoss()\noptimiser = optim.SGD(net.parameters(), lr=0.01)\nnum_epochs = 5\n\nfor epochs in range(num_epochs):\n\t#print(epochs)\n for data in train_loader:\n inputs, segments = data\n\n inputs, segments = Variable(inputs), Variable(segments)\n\n optimiser.zero_grad()\n\n outputs = net(inputs)\n\n loss = criterion(outputs, segments)\n\n loss.backward()\n optimiser.step()\n","sub_path":"andy_main.py","file_name":"andy_main.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"269117738","text":"# Bubble Sort Algorithm - V 1.0.0\n# Author: Dena, Rene\n# Last Modified: 5/26/17\n\n## Misc.\n\nimport sys\n\n\n## Functions\n\n\n\ndef Main():\n\t\n\tnums = []\n\twhile True:\n\t try:\n\t one = int(input(\"Please enter first integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t two = int(input(\"Please enter second integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t three = int(input(\"Please enter third integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t four = int(input(\"Please enter fourth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t five = int(input(\"Please enter fifth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t six = int(input(\"Please enter sixth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t seven = int(input(\"Please enter seventh integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t eight = int(input(\"Please enter eighth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t nine = int(input(\"Please enter ninth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\twhile True:\n\t try:\n\t ten = int(input(\"Please enter tenth integer: \"))\n\t break\n\t except ValueError:\n\t print(\"Not a valid integer! Please try again ...\")\n\n\tnums.append(one)\n\tnums.append(two)\n\tnums.append(three)\n\tnums.append(four)\n\tnums.append(five)\n\tnums.append(six)\n\tnums.append(seven)\n\tnums.append(eight)\n\tnums.append(nine)\n\tnums.append(ten)\n\n\tprint('\\nThe numbers you have entered include: {}'.format(nums))\n\tprint('\\n')\n\tprint('\\n\\t\\t\\tWelcome to the MAIN CONSOLE!')\n\tprint('The starting LIST is: {}'.format(nums))\n\tprint('\\nProcess now underway.....')\n\tprint('\\n')\n\twhile True:\n\t\tprint(nums)\n\t\tif nums[9] < nums[8]:\n\t\t\ta, b = nums.index(nums[9]), nums.index(nums[8])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[8] < nums[7]:\n\t\t\ta, b = nums.index(nums[8]), nums.index(nums[7])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[7] < nums[6]:\n\t\t\ta, b = nums.index(nums[7]), nums.index(nums[6])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[6] < nums[5]:\n\t\t\ta, b = nums.index(nums[6]), nums.index(nums[5])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[5] < nums[4]:\n\t\t\ta, b = nums.index(nums[5]), nums.index(nums[4])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[4] < nums[3]:\n\t\t\ta, b = nums.index(nums[4]), nums.index(nums[3])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[3] < nums[2]:\n\t\t\ta, b = nums.index(nums[3]), nums.index(nums[2])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[2] < nums[1]:\n\t\t\ta, b = nums.index(nums[2]), nums.index(nums[1])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\tif nums[1] < nums[0]:\n\t\t\ta, b = nums.index(nums[1]), nums.index(nums[0])\n\t\t\tnums[b], nums[a] = nums[a], nums[b]\n\t\t\tprint(nums)\n\t\telif nums[0] < nums[1] and nums[1] < nums[2] and nums[2] < nums[3] and nums[3] < nums[4] and nums[4] < nums[5] and nums[5] < nums[6] and nums[6] < nums[7] and nums[7] < nums[8] and nums[8] < nums[9]:\n\t\t\tprint('+-----------------------------+')\n\t\t\tprint(nums)\n\t\t\tprint('+-----/\\.ASSORTED LIST./\\-----+')\n\t\t\tprint('\\nAlgorithmic assortment is now complete!')\n\t\t\twhile True:\n\t\t\t\tchoice = input('\\nWould you like to RE-RUN the script? \"yes\" OR \"no\": ')\n\t\t\t\tif choice == 'yes':\n\t\t\t\t\tprint('\\nAwesome! You\\'ve selected to RE-RUN the script.')\n\t\t\t\t\tprint('\\nHeading to the MAIN CONSOLE now!')\n\t\t\t\t\tprint('\\nLOADING...............')\n\t\t\t\t\tMain()\n\t\t\t\telif choice == 'no':\n\t\t\t\t\tprint('\\nBummer! You\\'ve decided to END the script.')\n\t\t\t\t\tprint('\\nHope you enjoyed.) You\\'ll now be kicked from script shortly.')\n\t\t\t\t\tprint('\\nLOADING...............')\n\t\t\t\t\tprint('\\nYou have now been kicked from script. Good day :)')\n\t\t\t\t\tsys.exit()\n\t\t\t\telse:\n\t\t\t\t\tprint('\\nPlease only ENTER \"yes\" OR \"no\"! >:|')\n\t\t\tbreak\n\n\n## Strictly Script\n\nprint('\\n\\t\\t\\tWelcome to \"Bubble Sort Algorithms\" Calculator!')\n\nwhile True:\n\tname = input('\\nBefore we begin, please ENTER you name: ')\n\tif name.isalpha():\n\t\tprint('\\nAwesome! We may now continue {}.'.format(name.title()))\n\t\tprint('\\nLet\\'s head to the MAIN CONSOLE now!')\n\t\tprint('\\nLOADING................')\n\t\tprint('\\n')\n\t\tMain()\n\t\tbreak\n\telse:\n\t\tprint('\\nPlease only ENTER characters a-z only! >:|')\n\n","sub_path":"Bubble Sort Algorithm - V 1.0.0.py","file_name":"Bubble Sort Algorithm - V 1.0.0.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381748408","text":"class ThreeTeleports:\r\n def shortestDistance(self, xMe, yMe, xHome, yHome, teleports):\r\n tele = {}\r\n posMe = (xMe,yMe)\r\n posHome = (xHome,yHome)\r\n for i in teleports:\r\n points = i.split()\r\n tele[(int(points[0]),int(points[1]))] = (int(points[2]),int(points[3]))\r\n tele[(int(points[2]),int(points[3]))] = (int(points[0]),int(points[1]))\r\n tele[posMe] = posMe\r\n tele[posHome] = posHome\r\n return self.shortHelper(posMe, posHome, tele)\r\n\r\n def shortHelper(self, start, end, tele):\r\n if start == end:\r\n return 0\r\n minDist = float('inf')\r\n keys = tele.keys()\r\n for i in keys:\r\n temp = tele[i]\r\n del tele[i]\r\n if i == start:\r\n continue\r\n distI = self.dist(start, i) + self.shortHelper(temp, end, tele)\r\n if distI < minDist:\r\n minDist = distI\r\n return minDist\r\n \r\n\r\n def dist(self, p, q):\r\n x = abs(p[0]-q[0])\r\n y = abs(p[1]-q[1])\r\n return x + y\r\n \r\n","sub_path":"595.py","file_name":"595.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"422493915","text":"from setuptools import setup\nfrom wavinfo import __author__, __license__, __version__\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='wavinfo',\n version=__version__,\n author=__author__,\n author_email='jamiehardt@me.com',\n description='Probe WAVE Files for iXML, Broadcast-WAVE and other metadata.',\n long_description_content_type=\"text/markdown\",\n long_description=long_description,\n license=__license__,\n url='https://github.com/iluvcapra/wavinfo',\n project_urls={\n 'Source':\n 'https://github.com/iluvcapra/wavinfo',\n 'Documentation':\n 'https://wavinfo.readthedocs.io/',\n 'Issues':\n 'https://github.com/iluvcapra/wavinfo/issues',\n },\n packages=['wavinfo'],\n classifiers=['Development Status :: 5 - Production/Stable',\n 'License :: OSI Approved :: MIT License',\n 'Topic :: Multimedia',\n 'Topic :: Multimedia :: Sound/Audio',\n# \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\"],\n keywords='waveform metadata audio ebu smpte avi library film tv editing editorial',\n install_requires=['lxml', 'ear'],\n entry_points={\n 'console_scripts': [\n 'wavinfo = wavinfo.__main__:main'\n ]\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"374260165","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\crafting\\music.py\n# Compiled at: 2019-11-26 00:23:11\n# Size of source mod 2**32: 12935 bytes\nimport collections\nfrom crafting.recipe import Recipe\nfrom event_testing.tests import TunableTestSet\nfrom interactions import ParticipantTypeSim\nfrom sims4.localization import TunableLocalizedStringFactory\nfrom sims4.tuning.instances import TunedInstanceMetaclass, HashedTunedInstanceMetaclass\nfrom sims4.tuning.tunable import TunableResourceKey, TunableRealSecond, TunableList, TunableReference, Tunable, OptionalTunable, HasTunableReference, TunableEnumEntry, TunableMapping, TunableVariant, TunableTuple\nfrom sims4.utils import classproperty\nfrom singletons import EMPTY_SET\nfrom statistics.skill_tests import SkillRangeTest\nimport services, sims4.log, sims4.resources\nlogger = sims4.log.Logger('Music')\n\nclass VocalTrack(HasTunableReference, metaclass=HashedTunedInstanceMetaclass, manager=services.get_instance_manager(sims4.resources.Types.RECIPE)):\n INSTANCE_TUNABLES = {'vocal_clip':TunableResourceKey(description='\\n The propx file of the vox to play.\\n ',\n default=None,\n resource_types=(\n sims4.resources.Types.PROPX,)), \n 'tests':TunableTestSet(description='\\n Tests to verify if this song is available for the Sim to play.\\n ')}\n\n\nclass MusicTrack(metaclass=HashedTunedInstanceMetaclass, manager=services.get_instance_manager(sims4.resources.Types.RECIPE)):\n INSTANCE_TUNABLES = {'music_clip':OptionalTunable(description='\\n If enabled, the music clip for music interactions. If disabled,\\n make sure you have vocals tuned.\\n ',\n tunable=TunableResourceKey(description='\\n The propx file of the music clip to play.\\n ',\n needs_tuning=False,\n resource_types=(\n sims4.resources.Types.PROPX,))), \n 'length':TunableRealSecond(description=\"\\n The length of the clip in real seconds. This should be a part of\\n the propx's file name.\\n \",\n needs_tuning=False,\n default=30,\n minimum=0), \n 'buffer':TunableRealSecond(description=\"\\n A buffer added to the track length. This is used to prevent the\\n audio from stopping before it's finished.\\n \",\n needs_tuning=False,\n default=0), \n 'check_for_unlock':Tunable(description=\"\\n Whether or not to check the Sim's Unlock Component to determine if\\n they can play the song. Currently, only clips that are meant to be\\n unlocked by the Write Song interaction should have this set to true.\\n \",\n needs_tuning=False,\n tunable_type=bool,\n default=False), \n 'music_track_name':OptionalTunable(description=\"\\n If the clip is of a song, this is its name. The name is shown in the\\n Pie Menu when picking specific songs to play.\\n \\n If the clip isn't a song, like clips used for the Practice or Write\\n Song interactions, this does not need to be tuned.\\n \",\n tunable=TunableLocalizedStringFactory(description=\"\\n The track's name.\\n \"),\n enabled_by_default=True), \n 'tests':TunableTestSet(description='\\n Tests to verify if this song is available for the Sim to play.\\n '), \n 'moods':TunableList(description=\"\\n A list of moods that will be used to determine which song a Sim will\\n play autonomously. If a Sim doesn't know any songs that their\\n current mood, they'll play anything.\\n \",\n tunable=TunableReference(manager=(services.mood_manager())),\n needs_tuning=True), \n 'vocals':TunableMapping(description=\"\\n A mapping of participants and their potential vocal tracks. Each\\n participant that has a vocal track that tests successfully will\\n sing when the music starts.\\n \\n Note: The interaction's resolver will be passed into the vocal\\n track tests, so use the same participant in those tests.\\n \",\n key_name='participant',\n value_name='vocal_tracks',\n key_type=TunableEnumEntry(description='\\n The participant who should sing vocals when the music starts.\\n ',\n tunable_type=ParticipantTypeSim,\n default=(ParticipantTypeSim.Actor)),\n value_type=TunableList(description='\\n If this music track has vocals, add them here. The first track that\\n passes its test will be used. If no tracks pass their test, none\\n will be used.\\n ',\n tunable=(VocalTrack.TunableReference())))}\n\n @classmethod\n def _verify_tuning_callback(cls):\n if cls.music_clip is None:\n if not cls.vocals:\n logger.error('{} does not have music or vocals tuned.', cls, owner='rmccord')\n\n @classproperty\n def tuning_tags(cls):\n return EMPTY_SET\n\n\nclass MusicStyle(HasTunableReference, metaclass=TunedInstanceMetaclass, manager=services.get_instance_manager(sims4.resources.Types.RECIPE)):\n INSTANCE_TUNABLES = {'music_tracks':TunableList(TunableReference(description='\\n A particular music track to use as part of this\\n style.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.RECIPE)),\n pack_safe=True,\n class_restrictions=(\n MusicTrack,))), \n 'pie_menu_category':TunableReference(description='\\n The pie menu category for this music style.\\n This can be used to break styles up into genres.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.PIE_MENU_CATEGORY),\n allow_none=True)}\n tracks_by_skill = collections.defaultdict(lambda : collections.defaultdict(set))\n styles_for_track = collections.defaultdict(set)\n\n @classmethod\n def _tuning_loaded_callback(cls):\n services.get_instance_manager(sims4.resources.Types.RECIPE).add_on_load_complete(cls._set_up_dictionaries)\n\n @classmethod\n def _set_up_dictionaries(cls, _):\n for track in cls.music_tracks:\n cls.styles_for_track[track].add(cls)\n if not track.tests:\n logger.error('{} has no tuned test groups. This makes it hard to optimize music track choosing. Please tune at least one test group and one skill test in every test group.', cls,\n owner='rmccord')\n for test_group in track.tests:\n has_skill_test = False\n for test in test_group:\n if not isinstance(test, SkillRangeTest):\n continue\n has_skill_test = True\n for level in range(test.skill_range_min, test.skill_range_max + 1):\n cls.tracks_by_skill[test.skill][level].add(track)\n\n if not has_skill_test:\n logger.error('{} has no tuned skill test in one of its test groups. This makes it hard to optimize music track choosing. Please tune at least one skill test in every test group.', cls,\n owner='rmccord')\n\n\nclass MusicRecipe(Recipe):\n MUSIC_STYLE_SINGLE = 0\n MUSIC_STYLE_AFFORDANCE_MAP = 1\n INSTANCE_TUNABLES = {'music_track_unlocks':TunableList(description='\\n The music tracks that will be unlocked when the crafting process is\\n complete.\\n ',\n tunable=TunableReference(description='\\n The music track that will be unlocked when the crafting process\\n is complete.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.RECIPE)),\n class_restrictions=('MusicTrack', ))), \n 'music_style_while_crafting':TunableVariant(description='\\n Tuning that decides which music style to play while crafting this\\n recipe.\\n ',\n single_music_style=TunableTuple(description='\\n A single music style to use while crafting.\\n ',\n music_style=TunableReference(description='\\n Which music style the Sim will pull tracks from while writing\\n the song.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.RECIPE)),\n class_restrictions=('MusicStyle', )),\n locked_args={'variant_music_type': MUSIC_STYLE_SINGLE}),\n affordance_to_style_mapping=TunableTuple(description='\\n A mapping from affordance to music style, so that we can craft\\n this recipe on multiple instruments. the affordances in this\\n list should be some part of the phases of the recipe, so they\\n can pull from this list.\\n ',\n mapping=TunableMapping(description='\\n A mapping from affordance to music style, so that we can craft\\n this recipe on multiple instruments. the affordances in this\\n list should be some part of the phases of the recipe, so they\\n can pull from this list.\\n ',\n key_type=TunableReference(description='\\n The affordance used to craft this recipe.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.INTERACTION)),\n class_restrictions=('PlayAudioCraftingPhaseStagingSuperInteraction', )),\n value_type=TunableReference(description='\\n Which music style the Sim will pull tracks from while writing\\n the song.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.RECIPE)),\n class_restrictions=('MusicStyle', )),\n key_name='affordance',\n value_name='music_style'),\n locked_args={'variant_music_type': MUSIC_STYLE_AFFORDANCE_MAP}),\n default='single_music_style')}\n\n @classmethod\n def get_crafting_music_style(cls, affordance=None):\n if cls.music_style_while_crafting.variant_music_type == MusicRecipe.MUSIC_STYLE_SINGLE:\n return cls.music_style_while_crafting.music_style\n if cls.music_style_while_crafting.variant_music_type == MusicRecipe.MUSIC_STYLE_AFFORDANCE_MAP:\n if affordance is not None:\n return cls.music_style_while_crafting.mapping.get(affordance, None)\n return","sub_path":"Scripts/simulation/crafting/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":10738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"314226481","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom . import models \nfrom django.views import View\nfrom django.forms.models import model_to_dict\nimport json\n\nclass Havetodo(View):\n def get(self, request):\n Listdict = []\n requestedId = request.GET.get('id', None)\n text = request.GET.get('text', None)\n if text is not None:\n TodoList = models.Havetodo.objects.filter(text__icontains = text)\n for i in TodoList:\n Listdict.append(model_to_dict(i))\n elif requestedId is None:\n TodoList = models.Havetodo.objects.all()\n for i in TodoList:\n Listdict.append(model_to_dict(i))\n else:\n Listdict = models.Havetodo.objects.get(pk=requestedId)\n return JsonResponse(Listdict, safe=False)\n\n def post(self, request):\n # ajax post방식으로 data를 넘겨줄떄 data속에 text를 받아서 새로운 데이터 생성함\n text = json.loads(request.body)\n print(text['text'])\n NewList = models.Havetodo(text=text['text'], checked=False)\n NewList.save()\n return JsonResponse({'error':None}, safe=False)\n def delete(self,request):\n requestedId = request.GET.get('id', None)\n Deletelist = models.Havetodo.objects.get(pk=requestedId)\n Deletelist.delete()\n return JsonResponse({'error':None})\n def put(self, request):\n requestedId = request.GET.get('id',None)\n Updatelist = models.Havetodo.objects.get(pk=requestedId)\n Updatelist.checked = True\n Updatelist.save()\n return JsonResponse({'error':None})\n\n","sub_path":"todo/todolist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446455739","text":"from appium.webdriver.common.mobileby import MobileBy\n\nfrom base.driver_base import DriverBase\n\n\nclass MainPage(DriverBase):\n\n _abnormal_bounding_box_information = {\n \"同意\": (MobileBy.XPATH, \"//*[@resource-id='com.xueqiu.android:id/tv_agree']\")\n }\n\n # _recommended = {\n # \"step_type\": \"attribute\",\n # \"local\": \"//*[@resource-id='com.xueqiu.android:id/title_text' and @text='推荐']\",\n # \"position_type\": MobileBy.XPATH,\n # \"desc_information\": \"text\"\n # }\n\n _posotion_element = {\n \"step_type\": \"attribute\",\n \"local\": \"//*[@text='关注']\",\n \"position_type\": MobileBy.XPATH,\n \"desc_information\": \"text\"\n }\n\n # 通用按钮\n # 返回按钮\n _back_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/action_back']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 关闭按钮\n _close_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/iv_close']\",\n \"position_type\": MobileBy.XPATH\n }\n\n#################################\n # 搜索按钮:上滑后变成搜索按钮\n _search_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/action_search']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 搜索框\n _search_box = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/home_search']\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 首页顶部分类\n # 关注\n _attention = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/title_container']/android.widget.FrameLayout[1]\",\n \"position_type\": MobileBy.XPATH\n }\n # 推荐\n _recommended = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/title_container']/android.widget.FrameLayout[2]\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 热门\n _hot = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/title_container']/android.widget.FrameLayout[3]\",\n \"position_type\": MobileBy.XPATH\n }\n\n # pk赛\n _pk = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/title_container']/android.widget.FrameLayout[4]\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 消息\n _message = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/action_message']\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 7*24 热门\n # 7*24 logo\n _hot_logo = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/news_logo']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 7*24 热门\n _hot_message = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/splash_text_tv']\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 雪球热股榜\n\n # 热股榜返回\n _hot_back_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/back']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 热股榜 全部\n _hot_all_stocks = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/all_stock_tv']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 热股榜 窗口1 四家公司 左半边\n _hot_stocks_one = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_one']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _hot_stocks_two = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_two']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _hot_stocks_three = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_three']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _hot_stocks_four = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_four']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 热股榜 窗口2 三家公司 右半边\n _hot_stocks_five = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_five']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _hot_stocks_six = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_six']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _hot_stocks_seven = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/stock_seven']\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 热门话题\n # 话题返回\n _topic_back_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/tv_action_back']\",\n \"position_type\": MobileBy.XPATH\n }\n\n _topic_msg_back_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/transparent_action_back']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 全部\n _hot_all_topic = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/hot_topic_all']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 话题1\n _hot_topic_one = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/hot_topic_rv']/android.widget.LinearLayout[1]//android.widget.ImageView\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 话题2\n _hot_topic_two = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/hot_topic_rv']/android.widget.LinearLayout[2]//android.widget.ImageView\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 推荐分类\n # 推荐分类 banner\n # banner 切换icon\n _recommended_banner_icon = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/banner_indicator_container']/android.widget.ImageView[icon_index]\",\n \"position_type\": MobileBy.XPATH\n }\n\n # banner\n _recommended_banner = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/head_banner_img']\",\n \"position_type\": MobileBy.XPATH\n }\n#################################\n # 推荐文章 作者头像\n _recommended_author_portrait = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/profileImage']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 推荐文章 作者名字 发表时间 一栏\n _recommended_author_name = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/name_layout']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 推荐文章内容\n _recommended_article_text = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/status_container']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 推荐文章 转发按钮\n _recommended_article_retweet = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/retweet_count_view']/android.widget.ImageView\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 推荐文章 评论按钮\n _recommended_article_comment = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/comment_count_view']/android.widget.ImageView\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 推荐文章 点赞按钮\n _recommended_article_reward = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/reward_count_view']/android.widget.ImageView\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 右下角 编写文章按钮\n _recommended_write_article = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/post_status']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 关注\n # 去看看\n _empty_btn = {\n \"step_type\": \"click\",\n \"local\": \"//*[@resource-id='com.xueqiu.android:id/empty_button']\",\n \"position_type\": MobileBy.XPATH\n }\n\n # 获取设备屏幕信息\n def get_size(self):\n size = self.driver.get_window_size()\n self.width = size['width']\n self.height = size['height']\n return self\n\n def slide(self):\n # 上滑\n x = self.width / 2\n y = int(self.height * 0.8)\n after_y = int(self.height * 0.2)\n self.driver.swipe(start_x=x, start_y=y, end_x=x, end_y=after_y)\n return self\n\n # 获取锚点信息\n def confirm_anchor(self):\n return self.step(**self._posotion_element)\n\n # 定义通用功能 ############################\n # 返回\n def back(self):\n self.step(**self._back_btn)\n return self\n\n # 关闭\n def close(self):\n self.step(**self._close_btn)\n return self\n\n # 首页分类 ############################\n def goto_attention(self):\n self.step(**self._attention)\n return self\n\n def goto_recommended(self):\n self.step(**self._recommended)\n return self\n\n def goto_hot(self):\n self.step(**self._hot)\n return self\n\n def goto_pk(self):\n self.step(**self._pk)\n return self\n\n def goto_message(self):\n self.step(**self._message)\n return self\n\n # 热门分类 相关内容 ############################\n def click_hot_logo(self):\n self.step(**self._hot_logo)\n return self\n\n def click_hot_message(self):\n self.step(**self._hot_message)\n return self\n\n # 热股榜 相关内容\n def hot_back_btn(self):\n self.step(**self._hot_back_btn)\n return self\n\n def goto_hot_all_stocks(self):\n self.step(**self._hot_all_stocks)\n return self\n\n def goto_hot_stock_one(self):\n self.step(**self._hot_stocks_one)\n return self\n\n def goto_hot_stock_two(self):\n self.step(**self._hot_stocks_two)\n return self\n\n def goto_hot_stock_three(self):\n self.step(**self._hot_stocks_three)\n return self\n\n def goto_hot_stock_four(self):\n self.step(**self._hot_stocks_four)\n return self\n\n def goto_hot_stock_five(self):\n self.step(**self._hot_stocks_five)\n return self\n\n def goto_hot_stock_six(self):\n self.step(**self._hot_stocks_six)\n return self\n\n def goto_hot_stock_seven(self):\n self.step(**self._hot_stocks_seven)\n return self\n\n # 热门话题\n def topic_back_btn(self):\n self.step(**self._topic_back_btn)\n return self\n\n def goto_hot_all_topic(self):\n self.step(**self._hot_all_topic)\n return self\n\n def topic_msg_back_btn(self):\n self.step(**self._topic_msg_back_btn)\n return self\n\n def click_hot_topic_one(self):\n self.step(**self._hot_topic_one)\n return self\n\n def click_hot_topic_two(self):\n self.step(**self._hot_topic_two)\n return self\n\n # 推荐分类 ############################\n # 选择banner下标\n def choose_recommended_banner_icon(self, icon_index=1):\n if icon_index < 1 or icon_index > 5:\n raise(\"请在1-5之间选择\")\n\n _recommended_banner_icon = self._recommended_banner_icon\n _recommended_banner_icon[\"local\"] = _recommended_banner_icon[\"local\"].replace(\"icon_index\", str(icon_index))\n self.step(**_recommended_banner_icon)\n return self\n # 点击banner\n def click_recommended_banner(self):\n self.step(**self._recommended_banner)\n return self\n\n # 推荐文章 点击作者头像\n def click_recommended_author_portrait(self):\n self.step(**self._recommended_author_portrait)\n return self\n\n def click_recommended_author_name(self):\n self.step(**self._recommended_author_name)\n return self\n\n def click_recommended_article_text(self):\n self.step(**self._recommended_article_text)\n return self\n\n def click_recommended_article_retweet(self):\n self.step(**self._recommended_article_retweet, elements_index=1)\n return self\n\n def click_recommended_article_comment(self):\n self.step(**self._recommended_article_comment, elements_index=1)\n return self\n\n def click_recommended_article_reward(self):\n self.step(**self._recommended_article_reward, elements_index=1)\n return self\n\n def goto_recommended_write_article(self):\n self.step(**self._recommended_write_article)\n return self\n\n # 关注分类 相关内容 ############################\n def goto_empty_btn(self):\n self.step(**self._empty_btn)\n return self","sub_path":"page/main_page.py","file_name":"main_page.py","file_ext":"py","file_size_in_byte":12917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14803139","text":"# Copyright 2016 Google 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\nfrom .Model import Model\nfrom datetime import datetime\nfrom google.cloud import datastore\n\ndef from_datastore(entity):\n \"\"\"Translates Datastore results into the format expected by the\n application.\n\n Datastore typically returns:\n [Entity{key: (kind, id), prop: val, ...}]\n\n This returns:\n [ name, street, city, state, zip, open_hr, close_hr, phone, drink, rating, website ]\n where name, street, city, state, open_hr, close_hr, phone, drink, and website are Python strings\n and where zip and rating are Python integers\n \"\"\"\n if not entity:\n return None\n if isinstance(entity, list):\n entity = entity.pop()\n return [entity['name'],entity['street'],entity['city'],entity['state'],entity['zip'],entity['open_hr'],entity['close_hr'],entity['phone'],entity['drink'],entity['rating'],entity['website']]\n\nclass model(Model):\n def __init__(self):\n self.client = datastore.Client('cs430-belen-bustamante')\n\n def select(self):\n \"\"\"\n Gets all entries from the database\n :return: Tuple containing all rows of database\n \"\"\"\n query = self.client.query(kind = 'BobaShop')\n entities = list(map(from_datastore,query.fetch()))\n return entities\n\n def insert(self, name, street, city, state, zip, open_hr, close_hr, phone, drink, rating, website):\n \"\"\"\n Inserts entry into database\n :param name: String\n :param street: String\n :param city: String\n :param state: String\n :param zip: Integer\n :param open_hr: String\n :param close_hr: String\n :param phone: String\n :param drink: String\n :param rating: Integer\n :param website: String\n :return: none\n :raises: Database errors on connection and insertion\n \"\"\"\n key = self.client.key('BobaShop', name)\n rev = datastore.Entity(key)\n rev.update( {\n 'name': name,\n 'street': street,\n 'city': city,\n 'state': state,\n 'zip': int(zip),\n 'open_hr': open_hr,\n 'close_hr': close_hr,\n 'phone': phone,\n 'drink': drink,\n 'rating': int(rating),\n 'website': website\n })\n self.client.put(rev)\n return True\n\n def delete(self, name):\n \"\"\"\n Deletes an entry from the database\n :param name: String\n :return: none\n :raises: Database errors on connection and deletion\n \"\"\"\n key = self.client.key('BobaShop', name)\n self.client.delete(key)\n return True\n","sub_path":"hw4/bgmodel/model_datastore.py","file_name":"model_datastore.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"397354210","text":"import sys, os\nimport random as rand\nfrom flask import Flask, render_template, request\n\nsys.path.append(os.path.join(os.path.dirname(\".\"), \"pf_modules\"))\n\nfrom setup import setup\nfrom solver import solver\nfrom termcolor import colored\n\napp = Flask(__name__, static_folder=\"./pf_modules/visualizer/statics\",\n template_folder=\"./pf_modules/visualizer/statics\")\npath = [[]]\narray = [[]]\n\n@app.route('/')\ndef run():\n width = request.args.get(\"width\")\n height = request.args.get('height')\n o_width = request.args.get(\"o_width\")\n o_height = request.args.get(\"o_height\")\n o_count = request.args.get(\"o_count\")\n print(width, height)\n global path\n global array\n w = int(width) if width and width.strip() != \"\" else 160\n h = int(height) if height and height.strip() != \"\" else 100\n ow = int(o_width) if o_width and o_width.strip() != \"\" else 31\n oh = int(o_height) if o_height and o_height.strip() != \"\" else 31\n oc = int(o_count) if o_count and o_count.strip() != \"\" else 6\n algo = request.args.get('algo')\n if not algo:\n algo = 'a-star'\n if not w or not h:\n path = [[]]\n array = [[]]\n return render_template('index.html')\n\n array = setup.init_board(w, h, 1)\n array = setup.generate_obstacles(setup.generate_hards(array, oc, ow, oh, 2), 3, 0.2)\n r1_w = rand.randint(0, 5)\n r1_h = rand.randint(0, 5)\n print(\"START\", r1_h, r1_w)\n r2_w = rand.randint(w-10, w-1)\n r2_h = rand.randint(h-10, h-1)\n print(\"END\", r2_h, r2_w)\n path = None\n def run_with_algo(algo, heurs):\n return algo(array, (r1_h, r1_w), (r2_h, r2_w), heurs)\n\n if algo == 'a-multi-single' or algo == 'a-multi-multi':\n path = run_with_algo(solver.multiAStar if algo == 'a-multi-single' else solver.multiAStarMultiQueue,\n [solver.manhattan, solver.weighted_manhattan, solver.sqrtManhattan,\n solver.crowFlies, solver.expManhattan])\n else:\n if algo == 'uniform':\n path = run_with_algo(solver.aStarSolve, solver.uniform_cost)\n elif algo == 'weighted':\n path = run_with_algo(solver.aStarSolve, solver.weighted_manhattan)\n else:\n path = run_with_algo(solver.aStarSolve, solver.manhattan)\n '''\n for h in range(len(array)):\n for v in range(len(array[0])):\n if (h,v) in path:\n sys.stdout.write(\"{}\".format(colored(array[h][v], 'green')))\n else:\n vv = array[h][v]\n if vv is 1:\n sys.stdout.write('{}'.format(colored(vv, 'white')))\n elif vv is 2:\n sys.stdout.write('{}'.format(colored(vv, 'yellow')))\n elif vv is 3:\n sys.stdout.write('{}'.format(colored(vv, 'red')))\n print()\n '''\n return render_template(\"index.html\")\n\n@app.route(\"/main.js\")\ndef get_mainjs():\n global array\n global path\n if not path:\n path = [[]]\n return render_template(\"main.js\", rows=array, path=path)\n\napp.run(debug=True)\n","sub_path":"pathfinder/pathfinder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"334305963","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Copyright 2020 The Chromium OS 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\"\"\"Unit tests for ebuild_function.py\n\nDefault values follow the default values of ebuild (see manpage of ebuild).\nhttps://dev.gentoo.org/~zmedico/portage/doc/man/ebuild.5.html\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport mock\n\nimport ebuild_function\n\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)),\n '..', '..', '..'))\n\nfrom chromite.lib import cros_test_lib # pylint: disable=wrong-import-position\n\n\nclass DoCommandTests(cros_test_lib.TestCase):\n \"\"\"Tests of ebuild_function.do_command().\"\"\"\n\n def testDoins(self):\n \"\"\"Check it returns doins command that contains single source file.\n\n doins \n \"\"\"\n ret = ebuild_function.do_command('ins', ['source'])\n self.assertEqual(ret, [['doins', 'source']])\n\n def testMultipleDoins(self):\n \"\"\"Check it returns doins command that contains multiple source files.\n\n doins \n \"\"\"\n ret = ebuild_function.do_command('ins', ['source1', 'source2'])\n self.assertEqual(ret, [['doins', 'source1', 'source2']])\n\n def testDoinsRecursive(self):\n \"\"\"Check it returns recursive doins command.\n\n doins -r \n \"\"\"\n ret = ebuild_function.do_command('ins', ['source'], recursive=True)\n self.assertEqual(ret, [['doins', '-r', 'source']])\n\n def testNotDoinsRecursive(self):\n \"\"\"Check \"recursive\" is disabled in any install_type except for \"ins\".\"\"\"\n ret = ebuild_function.do_command('bin', ['source'], recursive=True)\n self.assertEqual(ret, [['dobin', 'source']])\n\n def testDoInvalidInstall(self):\n \"\"\"Check it raises InvalidInstallTypeError when install type is invalid.\"\"\"\n with self.assertRaises(ebuild_function.InvalidInstallTypeError):\n ebuild_function.do_command('invalid', ['source'])\n\nclass NewCommandTests(cros_test_lib.TestCase):\n \"\"\"Tests of ebuild_function.new_command().\"\"\"\n\n def testNewins(self):\n \"\"\"Check it returns a newins command that contains single source file.\"\"\"\n ret = ebuild_function.new_command('ins', ['source'], ['output'])\n self.assertEqual(ret, [['newins', 'source', 'output']])\n\n def testMultipleNewins(self):\n \"\"\"Check it returns multiple commands when there are multiple sources.\"\"\"\n ret = ebuild_function.new_command('ins', ['source1', 'source2'],\n ['output1', 'output2'])\n self.assertEqual(ret, [['newins', 'source1', 'output1'],\n ['newins', 'source2', 'output2']])\n\n def testDifferentLengthOutput(self):\n \"\"\"Check it raises error when the number of outputs is not correct.\n\n Make sure the number of outputs is the same as the number of sources.\n \"\"\"\n with self.assertRaises(AssertionError):\n ebuild_function.new_command('ins', ['source'], ['output1', 'output2'])\n\n def testNewInvalidInstall(self):\n \"\"\"Check it raises InvalidInstallTypeError when install type is invalid.\"\"\"\n with self.assertRaises(ebuild_function.InvalidInstallTypeError):\n ebuild_function.new_command('invalid', ['source'], ['output'])\n\n\nclass InstallTests(cros_test_lib.TestCase):\n \"\"\"Tests of ebuild_function.install().\"\"\"\n\n @mock.patch('ebuild_function.sym_install')\n def testCallSymInstall(self, sym_install_mock):\n \"\"\"Check it calls sym_install when symlinks are specified.\"\"\"\n ebuild_function.install('sym', ['source'], ['symlink'])\n self.assertTrue(sym_install_mock.called)\n\n @mock.patch('ebuild_function.do_command')\n def testCallDoCommand(self, do_command_mock):\n \"\"\"Check it calls do_command when symlinks and outputs aren't specified.\"\"\"\n ebuild_function.install('ins', ['source'])\n self.assertTrue(do_command_mock.called)\n\n @mock.patch('ebuild_function.new_command')\n def testCallNewCommand(self, new_command_mock):\n \"\"\"Check it calls new_command when outputs are specified.\"\"\"\n ebuild_function.install('ins', ['source'], ['output'])\n self.assertTrue(new_command_mock.called)\n\n\nclass OptionCmdTests(cros_test_lib.TestCase):\n \"\"\"Tests of ebuild_function.option_cmd().\"\"\"\n\n def testInstallOption(self):\n \"\"\"Check it returns appropriate options when install_type is \"ins\".\"\"\"\n self.assertEqual(\n ebuild_function.option_cmd('ins'),\n [['insinto', '/'], ['insopts', '-m0644']])\n self.assertEqual(\n ebuild_function.option_cmd('ins', install_path='/etc/init'),\n [['insinto', '/etc/init'], ['insopts', '-m0644']])\n self.assertEqual(\n ebuild_function.option_cmd('ins', options='-m0755'),\n [['insinto', '/'], ['insopts', '-m0755']])\n\n def testExecutableOption(self):\n \"\"\"Check it returns appropriate options when install_type is \"bin\".\"\"\"\n self.assertEqual(\n ebuild_function.option_cmd('bin'),\n [['into', '/usr']])\n self.assertEqual(\n ebuild_function.option_cmd('bin', install_path='/'),\n [['into', '/']])\n\n def testSharedLibraryOption(self):\n \"\"\"Check it returns appropriate options when install_type is \"lib.so\".\"\"\"\n self.assertEqual(\n ebuild_function.option_cmd('lib.so'),\n [['into', '/usr']])\n self.assertEqual(\n ebuild_function.option_cmd('lib.so', install_path='/'),\n [['into', '/']])\n\n def testStaticLibraryOption(self):\n \"\"\"Check it returns appropriate options when install_type is \"lib.a\".\"\"\"\n self.assertEqual(\n ebuild_function.option_cmd('lib.a'),\n [['into', '/usr']])\n self.assertEqual(\n ebuild_function.option_cmd('lib.a', install_path='/'),\n [['into', '/']])\n\n def testSymlinkOption(self):\n \"\"\"Check it returns appropriate options when install_type is \"sym\".\"\"\"\n self.assertEqual(\n ebuild_function.option_cmd('sym'),\n [])\n\n\nclass GenerateTests(cros_test_lib.TestCase):\n \"\"\"Tests of ebuild_function.generate().\"\"\"\n\n def testInstall(self):\n \"\"\"Check it returns doins commands when command_type isn't specified.\"\"\"\n self.assertEqual(\n ebuild_function.generate(['source']),\n [['insinto', '/'], ['insopts', '-m0644'], ['doins', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='/usr'),\n [['insinto', '/usr'], ['insopts', '-m0644'], ['doins', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], options='-m0755'),\n [['insinto', '/'], ['insopts', '-m0755'], ['doins', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], recursive=True),\n [['insinto', '/'], ['insopts', '-m0644'], ['doins', '-r', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], outputs=['output']),\n [\n ['insinto', '/'],\n ['insopts', '-m0644'],\n ['newins', 'source', 'output'],\n ])\n\n def testExecutableInstall(self):\n \"\"\"Check it returns do(s)bin commands when command_type is \"executable\".\"\"\"\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='bin',\n command_type='executable'),\n [['into', '/usr'], ['dobin', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='sbin',\n command_type='executable'),\n [['into', '/usr'], ['dosbin', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='/bin',\n command_type='executable'),\n [['into', '/'], ['dobin', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='bin',\n outputs=['output'],\n command_type='executable'),\n [['into', '/usr'], ['newbin', 'source', 'output']])\n\n def testSharedLibraryInstall(self):\n \"\"\"Check it returns dolib.so when command_type is shared_library.\"\"\"\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='lib',\n command_type='shared_library'),\n [['into', '/usr'], ['dolib.so', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='/lib',\n command_type='shared_library'),\n [['into', '/'], ['dolib.so', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='lib',\n outputs=['output'],\n command_type='shared_library'),\n [['into', '/usr'], ['newlib.so', 'source', 'output']])\n\n def testStaticLibraryInstall(self):\n \"\"\"Check it returns dolib.a commands when command_type is static_library.\"\"\"\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='lib',\n command_type='static_library'),\n [['into', '/usr'], ['dolib.a', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='/lib',\n command_type='static_library'),\n [['into', '/'], ['dolib.a', 'source']])\n self.assertEqual(\n ebuild_function.generate(['source'], install_path='lib',\n outputs=['output'],\n command_type='static_library'),\n [['into', '/usr'], ['newlib.a', 'source', 'output']])\n\n def testSymlinkInstall(self):\n \"\"\"Check it returns dosym commands when symlink is specified.\"\"\"\n self.assertEqual(\n ebuild_function.generate(['source'], symlinks=['symlink']),\n [['dosym', 'source', 'symlink']])\n self.assertEqual(\n ebuild_function.generate(['source'], symlinks=['symlink'],\n install_path='/'),\n [['dosym', 'source', '/symlink']])\n\n def testUnknownTypeInstall(self):\n \"\"\"Check it raises error when command_type is specified as unknown type.\"\"\"\n with self.assertRaises(AssertionError):\n ebuild_function.generate(['source'], command_type='something')\n\n\nif __name__ == '__main__':\n cros_test_lib.main(module=__name__)\n","sub_path":"common-mk/ebuild_function_unittest.py","file_name":"ebuild_function_unittest.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"488158484","text":"from xgboost import XGBClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nx, y = load_iris(return_X_y=True)\n\nprint(x.shape)\nprint(y.shape)\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.8,\n shuffle = True, random_state = 66)\n\n# model = XGBClassifier(objective='multi:softmax', n_estimators = 100, learning_rate = 0.05, n_jobs = -1)\nmodel = XGBClassifier(gpu_id=0, tree_method='gpu_hist')\n\nmodel.fit(x_train, y_train)\n\nthreshold = np.sort(model.feature_importances_)\n\nstart = time.time()\n\nfor thres in threshold:\n selection = SelectFromModel(model, threshold = thres, prefit = True)\n \n select_x_train = selection.transform(x_train)\n select_x_test = selection.transform(x_test)\n\n # selection_model = XGBClassifier(objective='multi:softmax', n_estimators = 100, learning_rate = 0.05, n_jobs = -1) \n selection_model = XGBClassifier(gpu_id=0, tree_method='gpu_hist')\n\n selection_model.fit(select_x_train, y_train, verbose= False, eval_metric= ['mlogloss', 'merror'],\n eval_set= [(select_x_train, y_train), (select_x_test, y_test)],\n early_stopping_rounds= 20)\n\n y_pred = selection_model.predict(select_x_test)\n acc = accuracy_score(y_test, y_pred)\n \n print(\"Thresh=%.3f, n = %d, ACC : %.2f%%\" %(thres, select_x_train.shape[1], acc*100.0))\n\n # result = selection_model.evals_result()\n # print(\"eval's result : \", result)\n\nend = time.time() - start\nprint(\" 걸린 시간 :\", end)\n\n# model = XGBClassifier(objective='multi:softmax', n_estimators = 100, learning_rate = 0.05, n_jobs = -1)\n# 의 결과 값\n\n# Thresh=0.022, n = 4, ACC : 100.00%\n# Thresh=0.041, n = 3, ACC : 100.00%\n# Thresh=0.463, n = 2, ACC : 100.00%\n# Thresh=0.473, n = 1, ACC : 93.33%\n# 걸린 시간 : 0.34758806228637695\n\n# acc :100.00%\n\n# model = XGBClassifier(gpu_id=0, tree_method='gpu_hist')의 결과 값\n\n# Thresh=0.023, n = 4, ACC : 100.00%\n# Thresh=0.024, n = 3, ACC : 100.00%\n# Thresh=0.442, n = 2, ACC : 100.00%\n# Thresh=0.512, n = 1, ACC : 93.33%\n# 걸린 시간 : 0.8088362216949463\n\n\n'''\n\nfrom xgboost import XGBRegressor, XGBClassifier, plot_importance \nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score, r2_score\nfrom sklearn.feature_selection import SelectFromModel\nimport numpy as np\n\n# 다중분류 모델\ndataset = load_iris()\nx = dataset.data\ny = dataset.target\n\nprint(x.shape)\nprint(y.shape) \n\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=66)\n\nmodel = XGBClassifier(objective='multi:softmax', estimators=300, learning_rate=0.01, n_jobs=-1) # 나무의 개수는 결국 epo다\nmodel.fit(x_train, y_train, verbose=True, eval_metric=['merror'], eval_set=[(x_train,y_train),(x_test,y_test)]\n , early_stopping_rounds=20) \n\ny_pred = model.predict(x_test)\nacc = accuracy_score(y_test, y_pred)\nprint('acc :%.2f%%' %(acc*100.0))\nprint('acc:', acc)\n\nthresholds = np.sort(model.feature_importances_)\n\nfor thresh in thresholds : # 컬럼수만큼 돈다! 빙글빙글\n selection = SelectFromModel(model, threshold=thresh, prefit=True)\n selection_x_train = selection.transform(x_train)\n # print(selection_x_train.shape) # 칼럼이 하나씩 줄고 있는걸 알 수 있음 (가장 중요 x를 하나씩 지우고 있음)\n \n selection_model = XGBRegressor()\n selection_model.fit(selection_x_train, y_train)\n\n select_x_test = selection.transform(x_test)\n x_pred = selection_model.predict(select_x_test)\n\n score = r2_score(y_test, x_pred)\n print('R2는',score)\n print(\"Thresh=%.3f, n=%d, R2: %.2f%%\" %(thresh, selection_x_train.shape[1], score*100.0))\n'''","sub_path":"ml/m29_eval3_SFM.py","file_name":"m29_eval3_SFM.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"270491289","text":"import sys,os\nimport cv2\nimport time\n\n# Resolution of RPi\nscreen_w = 1024\nscreen_h = 820\ndelay_time = 3000\n\ndef Fullscreen(image_path, window):\n if os.path.exists(image_path):\n image = cv2.imread(image_path)\n (h, w) = image.shape[:2]\n if h/w > 1.2:\n # rotate the image by 90 degrees\n image_temp = cv2.transpose(image)\n image_rot = cv2.flip(image_temp, 1)\n else:\n image_rot = image\n\n image_res = cv2.resize(image_rot,(screen_w,screen_h))\n #image_res = image_rot\n cv2.imshow(window, image_res)\n cv2.waitKey(delay_time)\n else:\n pass\n\ndef StrTrans(file_Str):\n file_Str = file_Str[1:-1]\n file_Str = file_Str.replace('\\'','')\n file_Str = file_Str.replace(' ','')\n items = file_Str.split(',')\n return items\n\nif __name__ == '__main__':\n file_path = '/home/pi/BigPig/assets/imageshowlist.txt'\n image_dir = '/home/pi/BigPig/assets/pic'\n\n window_name = 'projector'\n cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)\n #cv2.moveWindow(window_name, - 1, - 1)\n cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN,\n cv2.WINDOW_FULLSCREEN)\n\n while True:\n with open(file_path) as f:\n line = f.readline()\n f.close()\n images = StrTrans(line)\n if len(images) > 1:\n for image in images:\n image_path = os.path.join(image_dir, image)\n Fullscreen(image_path, window_name)\n elif len(images) == 1:\n image_path = os.path.join(image_dir, images[0])\n Fullscreen(image_path,window_name)\n else:\n pass\n #cv2.destroyAllWindows()","sub_path":"lib/RPi/showimg_full_screen.py","file_name":"showimg_full_screen.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"226359010","text":"# -*- coding:utf-8 -*-\n\n# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License.\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# MIT License for more details.\n\n\"\"\"Metric of detection task by using coco tools.\"\"\"\nimport os\nimport json\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom zeus.common import ClassFactory, ClassType\nfrom zeus.metrics.pytorch.metrics import MetricBase\n\n\n@ClassFactory.register(ClassType.METRIC, alias='coco')\nclass CocoMetric(MetricBase):\n \"\"\"Save and summary metric from mdc dataset using coco tools.\"\"\"\n\n __metric_name__ = \"coco\"\n\n def __init__(self, anno_path=None, category=None):\n self.anno_path = anno_path\n self.category = category or []\n self.result_record = []\n\n def __call__(self, output, targets, *args, **kwargs):\n \"\"\"Append input into result record cache.\n\n :param output: output data\n :param target: target data\n :return:\n \"\"\"\n if isinstance(output, dict):\n return None\n coco_results = []\n for id, prediction in enumerate(output):\n boxes = xyxy2xywh(prediction['boxes'])\n scores = prediction[\"scores\"].tolist()\n labels = prediction[\"labels\"].tolist()\n img_id = targets[id]['image_id'].tolist()[0]\n for idx, box in enumerate(boxes):\n data = {}\n data['image_id'] = img_id\n data['bbox'] = box\n data['score'] = scores[idx]\n data['category_id'] = labels[idx]\n coco_results.append(data)\n self.result_record.extend(coco_results)\n return None\n\n def reset(self):\n \"\"\"Reset states for new evaluation after each epoch.\"\"\"\n self.result_record = []\n\n def summary(self):\n \"\"\"Summary all record from result cache, and get performance.\"\"\"\n if not self.result_record:\n return {\"mAP\": -1, \"AP_small\": -1, \"AP_medium\": -1, \"AP_large\": -1}\n det_json_file = os.path.join(os.path.dirname(self.anno_path), 'det_json_file.json')\n with open(det_json_file, 'w') as f:\n json.dump(self.result_record, f)\n eval_result = self.print_scores(det_json_file, self.anno_path)\n ap_result = eval_result.pop('AP(bbox)')\n ap_result = list(ap_result)\n ap_result = {\n \"mAP\": ap_result[1] * 100,\n \"AP_small\": ap_result[3] * 100,\n \"AP_medium\": ap_result[4] * 100,\n \"AP_large\": ap_result[5] * 100\n }\n if eval_result:\n ap_result.update(eval_result)\n return ap_result\n\n def print_scores(self, det_json_file, json_file):\n \"\"\"Print scores.\n\n :param det_json_file: dest json file\n :param json_file: gt json file\n :return:\n \"\"\"\n ret = {}\n coco = COCO(json_file)\n cocoDt = coco.loadRes(det_json_file)\n cocoEval = COCOeval(coco, cocoDt, 'bbox')\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n ret['AP(bbox)'] = cocoEval.stats\n for id, item in enumerate(self.category):\n cocoEval = COCOeval(coco, cocoDt, 'bbox')\n cocoEval.params.catIds = [id + 1]\n # cocoEval.params.iouThrs = [0.5]\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n if len(cocoEval.stats) > 0:\n ret[item] = cocoEval.stats[1] * 100\n return ret\n\n\ndef xyxy2xywh(boxes):\n \"\"\"Transform the bbox coordinate to [x,y ,w,h].\n\n :param bbox: the predict bounding box coordinate\n :type bbox: list\n :return: [x,y ,w,h]\n :rtype: list\n \"\"\"\n xmin, ymin, xmax, ymax = boxes.unbind(1)\n import torch\n return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1).tolist()\n","sub_path":"zeus/metrics/pytorch/detection_metric.py","file_name":"detection_metric.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"616636895","text":"from datetime import datetime\nfrom ftw.testing import freeze\nfrom opengever.kub.testing import KUB_RESPONSES\nfrom opengever.kub.testing import KuBIntegrationTestCase\nimport json\nimport pytz\nimport requests_mock\n\n\n@requests_mock.Mocker()\nclass TestKubClient(KuBIntegrationTestCase):\n\n def test_sets_authorization_token(self, mocker):\n self.assertIn('Authorization', self.client.session.headers)\n self.assertEqual(u'Token secret', self.client.session.headers['Authorization'])\n\n def test_sets_accept_language_header(self, mocker):\n self.assertIn('Accept-Language', self.client.session.headers)\n self.assertEqual(u'en', self.client.session.headers['Accept-Language'])\n\n def test_kub_api_url(self, mocker):\n self.assertEqual(u'http://localhost:8000/api/v1/',\n self.client.kub_api_url)\n\n def test_query_returns_persons(self, mocker):\n query_str = \"Julie\"\n url = self.mock_search(mocker, query_str)\n resp = self.client.query(query_str)\n self.assertEqual(1, len(resp))\n self.assertEqual(\"person\", resp[0][\"type\"])\n self.assertEqual(KUB_RESPONSES[url], resp)\n\n def test_query_returns_memberships_and_organizations(self, mocker):\n query_str = \"4Teamwork\"\n url = self.mock_search(mocker, query_str)\n resp = self.client.query(query_str)\n self.assertEqual(2, len(resp))\n self.assertEqual(\"organization\", resp[0][\"type\"])\n self.assertEqual(\"membership\", resp[1][\"type\"])\n self.assertEqual(KUB_RESPONSES[url], resp)\n\n def test_get_by_id_handles_persons(self, mocker):\n url = self.mock_get_by_id(mocker, self.person_jean)\n resp = self.client.get_by_id(self.person_jean)\n self.assertEqual(\"person\", resp[\"type\"])\n self.assertEqual(json.loads(json.dumps(KUB_RESPONSES[url])), resp)\n\n def test_get_by_id_handles_organizations(self, mocker):\n url = self.mock_get_by_id(mocker, self.org_ftw)\n resp = self.client.get_by_id(self.org_ftw)\n self.assertEqual(\"organization\", resp[\"type\"])\n self.assertEqual(KUB_RESPONSES[url], resp)\n\n def test_get_by_id_handles_memberships(self, mocker):\n url = self.mock_get_by_id(mocker, self.memb_jean_ftw)\n resp = self.client.get_by_id(self.memb_jean_ftw)\n self.assertEqual(\"membership\", resp[\"type\"])\n self.assertEqual(KUB_RESPONSES[url], resp)\n\n def test_get_kub_id_label_mapping_uses_if_modified_since_header(self, mocker):\n labels = {'label_1': ' Maria Meier', 'label2': 'Donald Duck'}\n self.client._storage[self.client.STORAGE_MODIFIED_KEY] = 'Tue, 12 Oct 2021 13:37:00 GMT'\n self.client._storage[self.client.STORAGE_LABEL_MAPPING_KEY] = labels\n\n url = u'{}labels'.format(self.client.kub_api_url)\n mocker.get(url, status_code=304)\n self.assertEqual(labels, self.client.get_kub_id_label_mapping())\n self.assertEqual('Tue, 12 Oct 2021 13:37:00 GMT',\n self.client._storage[self.client.STORAGE_MODIFIED_KEY])\n\n self.mock_labels(mocker)\n\n expected_labels = {\n u'person:9af7d7cc-b948-423f-979f-587158c6bc65': u'Dupont Jean',\n u'person:0e623708-2d0d-436a-82c6-c1a9c27b65dc': u'Dupont Julie',\n u'person:5db3e407-7fc3-4093-a6cf-96030044285a': u'Schaudi Julia',\n u'membership:8345fcfe-2d67-4b75-af46-c25b2f387448': u'Dupont Jean - 4Teamwork (CEO)',\n u'person:1193d423-ce13-4dd9-aa8d-1f224f6a2b96': u'Peter Hans',\n u'organization:30bab83d-300a-4886-97d4-ff592e88a56a': u'4Teamwork'}\n\n with freeze(datetime(2021, 10, 16, 12, 0, tzinfo=pytz.timezone('Europe/Zurich'))):\n self.assertEqual(expected_labels, self.client.get_kub_id_label_mapping())\n self.assertEqual('Tue, 12 Oct 2021 13:37:00 GMT',\n mocker.last_request._request.headers['If-Modified-Since'])\n self.assertEqual('Sat, 16 Oct 2021 10:00:00 GMT',\n self.client._storage[self.client.STORAGE_MODIFIED_KEY])\n\n with freeze(datetime(2021, 10, 19, 11, 35, tzinfo=pytz.timezone('Europe/Zurich'))):\n mocker.get(url, status_code=304)\n self.assertEqual(expected_labels, self.client.get_kub_id_label_mapping())\n self.assertEqual('Sat, 16 Oct 2021 10:00:00 GMT',\n mocker.last_request._request.headers['If-Modified-Since'])\n self.assertEqual('Sat, 16 Oct 2021 10:00:00 GMT',\n self.client._storage[self.client.STORAGE_MODIFIED_KEY])\n","sub_path":"opengever/kub/tests/test_kub_client.py","file_name":"test_kub_client.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"519845259","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass AERDataQualityOperator(BaseOperator):\n\n ui_color = '#89DA59'\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n table_names=\"\",\n dq_checks=\"\",\n *args, **kwargs):\n\n super(AERDataQualityOperator, self).__init__(*args, **kwargs)\n # Map params here\n # Example:\n # self.conn_id = conn_id\n self.redshift_conn_id = redshift_conn_id \n self.table_names = table_names\n self.dq_checks = dq_checks\n\n def execute(self, context):\n self.log.info('AERDataQualityOperator started...')\n \n redshift_hook = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n \n fail_null_chk = []\n error_cnt = 0\n \n for check in self.dq_checks:\n sql = check.get('check_sql')\n exp_result = check.get('expected_result')\n \n records_query = redshift_hook.get_records(sql)[0]\n \n if exp_result != records_query[0]:\n error_cnt += 1\n fail_null_chk.append(sql)\n \n if error_cnt > 0:\n self.log.info('Tests failed')\n self.log.info(fail_null_chk)\n raise ValueError('Data quality check failed')\n \n for table in self.table_names:\n records = redshift_hook.get_records(f\"SELECT COUNT(*) FROM {table}\")\n \n if len(records) < 1 or len(records[0]) < 1:\n self.log.info(f\"Failed data quality record count on table {table} no results\") \n raise ValueError(f\"Data quality check failed. {table} returned no results\")\n \n num_records = records[0][0]\n \n if num_records < 1:\n self.log.info(f\"Failed data quality record count on table {table} 0 records\") \n raise ValueError(f\"Data quality check failed. {table} contained 0 rows\")\n \n self.log.info(f\"Passed data quality check. Table {table} has {records[0][0]} records\")","sub_path":"airflow/plugins/operators/aer_gblevntdata_data_quality.py","file_name":"aer_gblevntdata_data_quality.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"271605903","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nif __name__ == '__main__':\n x = 0\n i = 0\n while i < 100:\n if i % 3 == 0 and i > 20:\n x += i\n i += 1\n print(\"Сумма чисел, удовлетворяющих условиям, равна:\", x)\n","sub_path":"Задания/Задание 3.py","file_name":"Задание 3.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"63332159","text":"import unittest\nimport zserio\n\nfrom testutils import getZserioApi\n\ndef _convertRgbToCmyk(rgb):\n # see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html\n rr = rgb[0] / 255. * 100\n gg = rgb[1] / 255. * 100\n bb = rgb[2] / 255. * 100\n\n k = 100. - max(rr, gg, bb)\n\n c = round((100. - rr - k) / (100. - k) * 100)\n m = round((100. - gg - k) / (100. - k) * 100)\n y = round((100. - bb - k) / (100. - k) * 100)\n k = round(k)\n return (c, m, y, k)\n\ndef _convertCmykToRgb(cmyk):\n # see https://www.rapidtables.com/convert/color/cmyk-to-rgb.html\n r = round(255 * (1 - cmyk[0] / 100.) * (1 - cmyk[3] / 100.))\n g = round(255 * (1 - cmyk[1] / 100.) * (1 - cmyk[3] / 100.))\n b = round(255 * (1 - cmyk[2] / 100.) * (1 - cmyk[3] / 100.))\n return (r, g, b)\n\nRGB_VALUES = [(0, 128, 255), (222, 222, 0), (65, 196, 31)]\nCMYK_VALUES = [\n _convertRgbToCmyk(RGB_VALUES[0]),\n _convertRgbToCmyk(RGB_VALUES[1]),\n _convertRgbToCmyk(RGB_VALUES[2])\n]\n\nclass ComplexTypesServiceTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.api = getZserioApi(__file__, \"service_types.zs\").complex_types_service\n\n class Service(cls.api.ComplexTypesService.Service):\n def _swapModelsImpl(self, request, _context):\n requestData = request.getData()\n data = requestData.getData()\n\n response = cls.api.Response()\n response.setLength(len(data))\n response.setData(cls.api.ResponseData(len(data)))\n\n if requestData.getModel() == cls.api.ColorModel.RGB:\n self._rgbToCmyk(data, response)\n else:\n self._cmykToRgb(data, response)\n\n return response\n\n @staticmethod\n def _getLengthImpl(request, _context):\n requestData = request.getData()\n lengthResponse = cls.api.LengthResponse.fromFields(len(requestData.getData()))\n return lengthResponse\n\n @staticmethod\n def _rgbToCmyk(data, response):\n cmykData = []\n for element in data:\n rgbModel = element.getRgb()\n rgb = (rgbModel.getRed(), rgbModel.getGreen(), rgbModel.getBlue())\n cmyk = _convertRgbToCmyk(rgb)\n cmykModel = cls.api.CMYKModel.fromFields(cmyk[0], cmyk[1], cmyk[2], cmyk[3])\n cmykData.append(cmykModel)\n response.getData().setCmykData(cmykData)\n\n @staticmethod\n def _cmykToRgb(data, response):\n rgbData = []\n for element in data:\n cmykModel = element.getCmyk()\n cmyk = (cmykModel.getCyan(), cmykModel.getMagenta(), cmykModel.getYellow(),\n cmykModel.getKey())\n rgb = _convertCmykToRgb(cmyk)\n rgbModel = cls.api.RGBModel.fromFields(rgb[0], rgb[1], rgb[2])\n rgbData.append(rgbModel)\n response.getData().setRgbData(rgbData)\n\n cls.Service = Service\n\n def setUp(self):\n self.service = self.Service()\n self.client = self.api.ComplexTypesService.Client(self.service)\n\n def testServiceFullName(self):\n self.assertEqual(\"service_types.complex_types_service.ComplexTypesService\",\n self.api.ComplexTypesService.Service.SERVICE_FULL_NAME)\n\n def testMethodNames(self):\n self.assertEqual(\"swapModels\", self.api.ComplexTypesService.Service.METHOD_NAMES[0])\n self.assertEqual(\"getLength\", self.api.ComplexTypesService.Service.METHOD_NAMES[1])\n\n def testRgbToCmyk(self):\n length = 10000\n offsets = [0] * length\n data = []\n for i in range(length):\n choice = self.api.ColorModelChoice(self.api.ColorModel.RGB)\n choice.setRgb(self.api.RGBModel.fromFields(RGB_VALUES[i % 3][0],\n RGB_VALUES[i % 3][1],\n RGB_VALUES[i % 3][2]))\n data.append(choice)\n\n requestData = self.api.RequestData.fromFields(self.api.ColorModel.RGB, offsets, data)\n request = self.api.Request.fromFields(self.api.ColorModel.RGB, requestData)\n\n self.assertEqual(length, self.client.getLengthMethod(request).getLength())\n\n response = self.client.swapModelsMethod(request)\n self.assertEqual(length, response.getLength())\n\n cmykData = response.getData().getCmykData()\n for i, cmyk in enumerate(cmykData):\n self.assertEqual(CMYK_VALUES[i % 3][0], cmyk.getCyan())\n self.assertEqual(CMYK_VALUES[i % 3][1], cmyk.getMagenta())\n self.assertEqual(CMYK_VALUES[i % 3][2], cmyk.getYellow())\n self.assertEqual(CMYK_VALUES[i % 3][3], cmyk.getKey())\n\n def testCmykToRgb(self):\n length = 10000\n offsets = [0] * length\n data = []\n for i in range(length):\n choice = self.api.ColorModelChoice(self.api.ColorModel.CMYK)\n choice.setCmyk(self.api.CMYKModel.fromFields(CMYK_VALUES[i % 3][0],\n CMYK_VALUES[i % 3][1],\n CMYK_VALUES[i % 3][2],\n CMYK_VALUES[i % 3][3]))\n data.append(choice)\n\n requestData = self.api.RequestData.fromFields(self.api.ColorModel.CMYK, offsets, data)\n request = self.api.Request.fromFields(self.api.ColorModel.CMYK, requestData)\n\n self.assertEqual(length, self.client.getLengthMethod(request).getLength())\n\n response = self.client.swapModelsMethod(request)\n self.assertEqual(length, response.getLength())\n\n rgbData = response.getData().getRgbData()\n for i, rgb in enumerate(rgbData):\n self.assertEqual(RGB_VALUES[i % 3][0], rgb.getRed())\n self.assertEqual(RGB_VALUES[i % 3][1], rgb.getGreen())\n self.assertEqual(RGB_VALUES[i % 3][2], rgb.getBlue())\n\n def testInvalidServiceMethod(self):\n with self.assertRaises(zserio.ServiceException):\n self.service.callMethod(\"nonexistentMethod\", bytes())\n","sub_path":"test/language/service_types/python/ComplexTypesServiceTest.py","file_name":"ComplexTypesServiceTest.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"146917657","text":"import sqlite3\nimport time\nimport logging\nimport re\nimport os\n\nclass StatsDB:\n fileName=\"\"\n conn = None\n cur = None\n tableName = \"\"\n\n def __init__(self, dbFileName, release):\n self.fileName = dbFileName\n self.testDBFile()\n self.tableName = str(release)\n if self.tableName == \"\":\n self.tableName = \"unknown\"\n else:\n reg = re.search(\"^(.*)-\\d\\d+$\", self.tableName)\n if reg:\n self.tableName = reg.group(1)\n self.tableName = re.sub(r\"\\.|\\-\", \"_\", self.tableName)\n\n def __del__(self):\n if not self.conn is None:\n self.conn.close()\n\n def testDBFile(self):\n if not os.path.exists(self.fileName):\n open(self.fileName, 'w').close()\n os.chmod(self.fileName, 0o777)\n elif not os.path.isfile(self.fileName) or not os.access(self.fileName, os.W_OK):\n raise OSError(\"Unable to access db file - {filePath}.\".format(filePath=self.fileName))\n\n def connect(self):\n if self.conn is None:\n self.conn = sqlite3.connect(self.fileName)\n self.cur = self.conn.cursor()\n\n def write(self, header, values):\n if self.conn == None:\n return\n if not self.tableIsExist():\n self.createTable(header)\n else:\n self.updateTable(header)\n return self.addRow(header, values)\n\n def updateAll(self, searchColumn, searchValue, updateColumn, updateValue):\n if self.conn == None or not self.tableIsExist():\n return\n tryCount = 0\n while True:\n try:\n self.cur.execute(\"update '{tn}' set {uc}='{uv}' where {c}='{v}'\"\\\n .format(tn=self.tableName, uc=updateColumn, uv=updateValue, c=searchColumn, v=searchValue))\n break\n except:\n tryCount += 1\n if tryCount > 10:\n logging.debug(\"Faild to update database\")\n break\n time.sleep(1)\n self.commit()\n\n def tableIsExist(self):\n self.cur.execute(\"select count(*) from sqlite_master where type='table' and name='{tn}'\"\\\n .format(tn=self.tableName))\n if self.cur.fetchone()[0] != 0:\n return True\n return False\n\n\n def getColumns(self):\n desc = self.cur.execute(\"select * from '{tn}' where 1=2\".format(tn=self.tableName))\n return [description[0] for description in desc.description]\n\n def updateTable(self, headerDictionary):\n columns = self.getColumns()\n for key in headerDictionary.keys():\n name = str(key)\n type = str(headerDictionary[key])\n \n if (name not in columns):\n self.conn.execute(\"alter table '{tn}' add '{name}' {type}\".format(tn=self.tableName, name=name, type=type))\n \n def createTable(self, headerDictionary):\n header = []\n for key in headerDictionary.keys():\n column = str(key) + \" \" + str(headerDictionary[key])\n header.append(column)\n strHeader = \", \".join(header)\n self.conn.execute(\"create table if not exists '{tn}' ({h})\"\\\n .format(tn=self.tableName, h=strHeader))\n\n def addRow(self, header, values):\n columns = list(header.keys())\n existColumns = list(values.keys())\n realColumns = []\n valueList = []\n rowID = None\n for column in existColumns:\n if not column in columns:\n continue\n realColumns.append(str(column))\n valueList.append(\"'\" + str(values[column]) + \"'\")\n if (len(realColumns)) == 0:\n return\n tryCount = 0\n while True:\n try:\n self.cur.execute(\"insert into '{tn}' ({cs}) values ({vs})\"\\\n .format(tn=self.tableName, cs=\", \".join(realColumns), vs=\", \".join(valueList)))\n rowID = self.cur.lastrowid\n break\n except:\n tryCount += 1\n if tryCount > 10:\n logging.debug(\"Faild to insert a row into database\")\n break\n time.sleep(1)\n self.commit()\n return rowID\n\n def commit(self):\n tryCount = 0\n while True:\n try:\n self.conn.commit()\n break\n except:\n tryCount += 1\n if tryCount > 10:\n logging.debug(\"Faild to commit to database\")\n break\n time.sleep(1)\n","sub_path":"etc/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"292252058","text":"import os\nimport json\nimport argparse\nimport h5py\nimport numpy as np\n\nimport logging\nfrom datetime import datetime\n\nlogger = logging.getLogger(__name__)\n \nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s: %(message)s')\n parser = argparse.ArgumentParser()\n \n parser.add_argument('input_file1')\n parser.add_argument('input_file2')\n parser.add_argument('output_file')\n parser.add_argument('--data', type=str, default='data')\n parser.add_argument('--index', type=str, default='index')\n\n args = parser.parse_args()\n start = datetime.now() \n \n f1 = h5py.File(args.input_file1, 'r')\n f2 = h5py.File(args.input_file2, 'r')\n \n assert(args.data in f1 and args.data in f2)\n assert(args.index in f1 and args.index in f2)\n assert(f1[args.data].shape[0] == f1[args.index].shape[0])\n assert(f2[args.data].shape[0] == f2[args.index].shape[0])\n assert(f1[args.data].shape[1] == f2[args.data].shape[1])\n \n m1 = f1[args.data].shape[0]\n m2 = f2[args.data].shape[0]\n m = m1 + m2\n n = f1[args.data].shape[1]\n \n f = h5py.File(args.output_file, 'w')\n \n data = f.create_dataset(args.data, (m, n), dtype='float32')\n index = f.create_dataset(args.index, (m,), dtype='int32')\n \n logger.info('Copying from file 1: %s', args.input_file1)\n \n for i in range(f1[args.data].shape[0]):\n data[i] = f1[args.data][i]\n index[i] = f1[args.index][i]\n if i % 1000 == 0: \n logger.info('%d processed', i)\n\n logger.info('Copying from file 2: %s', args.input_file2)\n for i in range(f2[args.data].shape[0]):\n data[i + m1] = f2[args.data][i]\n index[i + m1] = f2[args.index][i]\n if i % 1000 == 0: \n logger.info('%d processed', i)\n \n f1.close() \n f2.close() \n f.close() \n \n logger.info('Time: %s', datetime.now() - start)\n","sub_path":"h5merge.py","file_name":"h5merge.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284615319","text":"#!/usr/bin/env python\n\nimport csv\nimport sys\n\nimport requests\n\nEXCHANGE_URL = 'https://raw.githubusercontent.com/flywheel-io/exchange/gh-pages-json/exchange.json'\n\nmanifest_json = requests.get(EXCHANGE_URL).json()\n\nCOLUMNS = ['name', 'label', 'version', 'license', 'author', 'maintainer', 'source', 'url']\n\nwith open(sys.argv[1], 'w', newline='') as csv_file:\n csv_writer = csv.DictWriter(csv_file, COLUMNS, extrasaction='ignore')\n csv_writer.writeheader()\n csv_writer.writerows([gear[0] for gear in manifest_json])\n","sub_path":"bin/export_to_csv.py","file_name":"export_to_csv.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"133119784","text":"fhandle=open('mbox-short.txt', 'r')\r\ncounts=dict()\r\nlargest = None\r\naddress=None\r\n#Gets all address's and counts them\r\nfor line in fhandle :\r\n if line.startswith('From:') : continue\r\n if line.startswith('From') :\r\n #print(line)\r\n words=line.split()\r\n #print(words[1])\r\n address=words[1]\r\n #print(address)\r\n counts[address]=counts.get(address,0) + 1\r\n #print(counts.items())\r\n\r\n\r\nfor key,value in counts.items():\r\n num=value\r\n name=key\r\n # print(num)\r\n # print(name)\r\n if largest is None :\r\n largest = num\r\n address = name\r\n elif num > largest :\r\n largest = num\r\n address = name\r\n # print(largest)\r\n # print(address)\r\nstring=str(largest)\r\nprint(address + ' ' + string)\r\n","sub_path":"pyds/9_4.py","file_name":"9_4.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"172373246","text":"#! /usr/bin/python3\n# *-* coding: utf-8 *-*\n\"\"\"38coroutines\n@Author: wikinee\n@License: MIT\n\"\"\"\n\n\ndef fib():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a+b\n\n\nfor i in fib():\n if i < 10:\n print(i)\n\n\ndef grep(pattern):\n print(\"Searching for\", pattern)\n while True:\n line = (yield)\n if pattern in line:\n print(line)\n\n\nsearch = grep('coroutine')\nnext(search)\n# Output: Searching for coroutine\nsearch.send(\"I love you\")\nsearch.send(\"Don't you love me?\")\nsearch.send(\"I love coroutine instead!\")\n# Output: I love coroutine instead!\nsearch = grep('coroutine')\nsearch.close()\n","sub_path":"Python/interpy/38coroutines.py","file_name":"38coroutines.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176344349","text":"class Node:\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n\nclass LinkedList:\n def __init__(self):\n self.first = None\n self.last = None\n\n def addLast(self, value):\n newNode = Node(value)\n\n if (self.first is None):\n self.first = self.last = newNode\n else:\n self.last.next = newNode\n self.last = newNode\n\n def addFirst(self, value):\n newNode = Node(value)\n\n if (self.first is None):\n self.first = self.last = newNode\n else:\n newNode.next = self.first\n self.first = newNode\n\n def indexOf(self, item):\n index = 0\n current = self.first\n\n while (current is not None):\n if (current.value is item):\n return index\n current = current.next\n index += 1\n return -1\n\n def contains(self, item):\n return self.indexOf(item) is not -1\n\n def removeFirst(self):\n if (self.first is None):\n raise Exception('It is already empty')\n\n if (self.first is self.last):\n self.first = self.last = None\n return\n\n second = self.first.next\n self.first = None\n self.first = second\n\n def getPrevious(self, node):\n current = self.first\n while(current is not None):\n if(current.next is node):\n return current\n current = current.next\n return None\n\n def removeLast(self):\n\n if (self.first is None):\n raise Exception('It is already empty')\n\n if (self.first is self.last):\n self.first = self.last = None\n return\n\n previous = self.getPrevious(self.last)\n self.last = previous\n self.last.next = None\n\n\nll = LinkedList()\nll.addLast(4)\nll.addLast(2)\nll.addLast(5)\nll.addFirst(9)\nll.removeFirst()\nprint(ll)\n","sub_path":"LinkedList/SolutionRemoveLast/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"219126991","text":"import os\nimport matplotlib.pyplot as plt\nimport csv\nimport pandas as pd\n\n# file\ndef file_dir(dir):\n os.chdir(dir)\n list_dir = os.listdir(dir)\n return list_dir\ndef file_select_cv(path):\n # find cv.txt file\n file = wlf_dir(path)\n file_cv = []\n for i in file:\n if i.find('cv') != -1 and i.find('txt') != -1:\n file_cv.append(i)\n return file_cv\ndef file_select_cp(path):\n # find cp.txt file\n file = wlf_dir(path)\n file_cp = []\n for i in file:\n if i.find('cp') != -1 and i.find('txt') != -1:\n file_cp.append(i)\n return file_cp\ndef file_select_eis(path):\n # find cp.txt file\n file = wlf_dir(path)\n file_eis = []\n for i in file:\n if i.find('EIS') != -1 and i.find('txt') != -1:\n file_eis.append(i)\n return file_eis\ndef file_find_line_cv(file):\n # find line 'Potential/V, Current/A\\n' cv\n with open(file, 'r') as f:\n lines = f.readlines()\n i = 0\n t = 0\n for line in lines:\n i = i + 1\n if line == 'Potential/V, Current/A\\n':\n t = i\n return t+1\ndef file_del_head_cv(file):\n # del head cv\n file_cv = []\n i = 0\n with open(file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n i = i + 1\n if i > file_find_line_cv(file):\n file_cv.append(line)\n return file_cv\ndef file_find_line_cp(file):\n # find line 'Time/sec, Potential/V\\n' cp\n with open(file, 'r') as f:\n lines = f.readlines()\n i = 0\n t = 0\n for line in lines:\n i = i + 1\n if line == 'Time/sec, Potential/V\\n':\n t = i\n return t+1\ndef file_find_line_eis(file):\n # find line 'Freq/Hz, Z'/ohm, Z\"/ohm, Z/ohm, Phase/deg\\n' cp\n with open(file[0], 'r') as f:\n lines = f.readlines()\n i = 0\n t = 0\n for line in lines:\n i = i + 1\n if line == 'Freq/Hz, Z\\'/ohm, Z\\\"/ohm, Z/ohm, Phase/deg\\n':\n t = i\n return t+1\ndef file_del_head_cp(file):\n # del head cp\n file_cp = []\n i = 0\n with open(file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n i = i + 1\n if i > file_find_line_cp(file):\n file_cp.append(line)\n return file_cp\ndef file_del_head_eis(file):\n # del head eis\n file_eis = []\n i = 0\n with open(file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n i = i + 1\n if i > file_find_line_eis(file):\n file_eis.append(line)\n return file_eis\ndef devide_list_cv(file_cv):\n # devide list cv\n vol = []\n cur = []\n for i in file_cv:\n a = i.split(\",\", 1)\n vol.append(float(a[0]))\n cur.append(float(a[1]))\n return vol, cur\ndef devide_list_cp(file_cp):\n # devide list cv\n vol = []\n cur = []\n for i in file_cp:\n a = i.split(\",\", 1)\n vol.append(float(a[0]))\n cur.append(float(a[1]))\n return vol, cur\ndef max_list(A,B):\n point = len(B) / 40\n n = 0\n while n * point < len(B):\n n = n + 1\n C = []\n D = []\n E = []\n for i in range(n - 1):\n C1 = max(B[i * point:(i + 1) * point])\n C2 = B[i * point:(i + 1) * point].index(C1) + i * point\n if C1 > B[i * point] and C1 > B[(i + 1) * point]:\n C.append(C1)\n D.append(C2)\n D.append(A.index(A[-1]))\n return D\ndef list_last_cp(vol, cur):\n # list last cycle cp\n A = vol\n B = cur\n point = len(B) // 10\n n = 0\n while n * point < len(B):\n n = n + 1\n C = []\n D = []\n for i in range(n - 1):\n C1 = min(B[i * point:(i + 1) * point])\n C2 = B[i * point:(i + 1) * point].index(C1) + i * point\n if C1 < B[i * point] and C1 < B[(i + 1) * point]:\n C.append(C1)\n D.append(C2)\n\n D.append(A.index(A[-1]))\n vol = vol[D[-2]:]\n vol = [i - vol[0] for i in vol]\n cur = cur[D[-2]:]\n return vol, cur\ndef list_last_cv(vol, cur):\n # list last cycle cv\n A = vol\n B = cur\n point = len(B) // 5\n n = 0\n while n * point < len(B):\n n = n + 1\n C = []\n D = []\n for i in range(n - 1):\n C1 = min(B[i * point:(i + 1) * point])\n C2 = B[i * point:(i + 1) * point].index(C1) + i * point\n if C1 < B[i * point] and C1 < B[(i + 1) * point]:\n C.append(C1)\n D.append(C2)\n D.append(A.index(A[-1]))\n vol = vol[D[-2]:]\n cur = cur[D[-2]:]\n return vol, cur\ndef rm_file(path):\n if os.path.exists(path):\n os.remove(path)\ndef concat(vol, cur):\n vol = pd.DataFrame({'': vol})\n cur = pd.DataFrame({'': cur})\n data = pd.concat([vol, cur], axis=1)\n return data\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"wlf_lib_re.py","file_name":"wlf_lib_re.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645229647","text":"import torch\n\nclass DataLoaders:\n def __init__(self, batch_size=128, shuffle=True, num_workers=4, pin_memory=True, seed=1):\n use_cuda = torch.cuda.is_available()\n device = torch.device('cuda' if use_cuda else 'cpu') # set device to cuda\n\n if use_cuda:\n torch.manual_seed(seed)\n \n self.dataLoader_args = dict(batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True ) if use_cuda else dict(batch_size=batch_size/2, shuffle=True)\n\n def dataLoader(self, data):\n return torch.utils.data.DataLoader(data,**self.dataLoader_args )\n\n\n","sub_path":"S8/evaLibrary/DataLoaders.py","file_name":"DataLoaders.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"551527038","text":"import spacy\nimport sys\n\nnlp = spacy.load('en_core_web_sm')\n\n# return noun chunk\ndef find_chunk(doc):\n chunk = ''\n\n for i, token in enumerate(doc):\n if token.dep_ == 'dobj':\n shift = len([w for w in token.children])\n chunk = doc[i-shift:i+1]\n break\n \n return chunk\n\n# find question type: yesno / info\ndef determine_question_type(chunk):\n question_type = 'yesno'\n\n for token in chunk:\n if token.dep_ == 'amod':\n question_type = 'info'\n \n return question_type\n\n# generate question from sentence\ndef generate_question(doc, question_type):\n sent = ''\n for i, token in enumerate(doc):\n if token.tag_ == 'PRP' and doc[i+1].tag_ == 'VBP':\n sent = 'do ' + doc[i].text\n sent = sent + ' ' + doc[i+1:].text\n break\n \n doc = nlp(sent)\n for i, token in enumerate(doc):\n if token.tag_ == 'PRP' and token.text == 'I':\n sent = doc[:i].text + ' you ' + doc[i+1:].text\n break\n \n doc = nlp(sent)\n if question_type == 'info':\n for i, token in enumerate(doc):\n if token.dep_ == 'dobj':\n sent = 'why ' + doc[:i].text + ' one ' + doc[i+1:].text\n break\n if question_type == 'yesno':\n for i, token in enumerate(doc):\n if token.dep_ == 'dobj':\n sent = doc[:i-1].text + ' a red ' + doc[i:].text\n break\n\n doc = nlp(sent)\n sent = doc[0].text.capitalize() + ' ' + doc[1:len(doc)-1].text + '?'\n return sent\n\ndef main():\n if len(sys.argv) > 1:\n sent = sys.argv[1]\n\n doc = nlp(sent)\n chunk = find_chunk(doc)\n if str(chunk) == '':\n print('The sentence does not contain a direct object.')\n sys.exit()\n\n question_type = determine_question_type(chunk)\n print(question_type)\n question = generate_question(doc, question_type)\n\n print(question)\n else:\n print('You did not submit a sentence!')\n\nif __name__ == \"__main__\":\n # I want a green apple.\n # I want an apple.\n # I want...\n # empty\n\n main()","sub_path":"nlp/question_chat.py","file_name":"question_chat.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"175506951","text":"from click import secho\nfrom sqlalchemy import text\nfrom datetime import datetime\nfrom pathlib import Path\nfrom os import environ\nfrom sqlalchemy import event\nfrom sqlalchemy.exc import IntegrityError\n\nfrom .util import md5hash, SparrowImportError, ensure_sequence\nfrom ..util import relative_path, pretty_print\n\nclass BaseImporter(object):\n \"\"\"\n A basic Sparrow importer to be subclassed.\n \"\"\"\n authority = None\n def __init__(self, db, **kwargs):\n self.db = db\n self.m = self.db.model\n print_sql = kwargs.pop(\"print_sql\", False)\n\n # This is kinda unsatisfying\n self.basedir = environ.get(\"SPARROW_DATA_DIR\", None)\n\n self.__dirty = set()\n self.__new = set()\n self.__deleted = set()\n @event.listens_for(self.db.session, 'before_flush')\n def on_before_flush(session, flush_context, instances):\n self.__dirty |= set(session.dirty)\n self.__new |= set(session.new)\n self.__deleted |= set(session.deleted)\n\n @event.listens_for(self.db.session, 'after_commit')\n def on_after_commit(session):\n self.__dirty = set()\n self.__new = set()\n self.__deleted = set()\n\n if print_sql:\n @event.listens_for(self.db.engine, 'after_cursor_execute', named=True)\n def receive_after_cursor_execute(**kw):\n statement = kw.pop('statement')\n if statement.startswith(\"SELECT\"): return\n secho(str(statement).strip())\n\n # Deprecated\n self.models = self.m\n\n ###\n # Helpers to insert various types of analytical data\n ###\n def sample(self, **kwargs):\n return self.db.get_or_create(self.m.sample, **kwargs)\n\n def location(self, lon, lat):\n return f\"SRID=4326;POINT({lon} {lat})\"\n\n def publication(self, doi, title=None):\n return self.db.get_or_create(\n self.m.publication,\n doi=doi, defaults=dict(title=title))\n\n def project(self, name):\n return self.db.get_or_create(self.m.project, name=name)\n\n def unit(self, id):\n return self.db.get_or_create(\n self.m.unit,\n id=id, defaults=dict(authority=self.authority))\n\n def error_metric(self, id):\n if not id: return None\n return self.db.get_or_create(\n self.m.error_metric,\n id=id, defaults=dict(authority=self.authority))\n\n def parameter(self, id):\n return self.db.get_or_create(\n self.m.parameter,\n id=id, defaults=dict(authority=self.authority))\n\n def method(self, id):\n return self.db.get_or_create(\n self.m.method,\n id=id, defaults=dict(authority=self.authority))\n\n def material(self, id):\n return self.db.get_or_create(\n self.m.material,\n id=id, defaults=dict(authority=self.authority))\n\n def datum_type(self, parameter, unit='unknown', error_metric=None, **kwargs):\n error_metric = self.error_metric(error_metric)\n try:\n error_metric_id = error_metric.id\n except AttributeError:\n error_metric_id = None\n\n unit = self.unit(unit)\n\n # Error values are *assumed* to be at the 1s level, apparently\n parameter = self.parameter(parameter)\n\n dt = self.db.get_or_create(\n self.m.datum_type,\n parameter=parameter.id,\n error_metric=error_metric_id,\n unit=unit.id,\n **kwargs)\n return dt\n\n def add_analysis(self, session, **kwargs):\n return self.db.get_or_create(\n self.m.analysis,\n session_id=session.id,\n **kwargs\n )\n\n def datum(self, analysis, parameter, value, error=None, **kwargs):\n type = self.datum_type(parameter, **kwargs)\n datum = self.db.get_or_create(self.m.datum,\n type=type.id, analysis=analysis.id)\n datum.value = value\n datum.error = error\n\n return datum\n\n ###\n # Data file importing\n ###\n\n def warn(self, message):\n secho(str(message), fg='yellow')\n\n def import_datafile(self, fn, rec, **kwargs):\n raise NotImplementedError()\n\n def delete_session(self, rec):\n \"\"\"\n Delete session(s) and associated analysis and datum records,\n given a data file model\n \"\"\"\n fn = relative_path(__file__, 'sql', 'delete-session.sql')\n sql = text(open(fn).read())\n self.db.session.execute(sql, {'file_hash': rec.file_hash})\n\n def iterfiles(self, file_sequence, **kwargs):\n \"\"\"\n This file iterator tracks files in the *data_file* table,\n checks if they have been imported, and potentially imports\n if needed.\n \"\"\"\n for fn in file_sequence:\n secho(str(fn), dim=True)\n self.__import_datafile(fn, None, **kwargs)\n\n def __set_file_info(self, fn, rec):\n infile = Path(fn)\n _ = infile.stat().st_mtime\n mtime = datetime.utcfromtimestamp(_)\n\n if self.basedir is not None:\n infile = infile.relative_to(self.basedir)\n\n rec.file_mtime = mtime\n rec.basename = infile.name\n rec.file_path = str(infile)\n\n def __create_data_file_record(self, fn):\n\n # Get file mtime and hash\n hash = md5hash(str(fn))\n\n # Get data file record if it exists\n rec = self.db.get(self.m.data_file, hash)\n added = rec is None\n if added:\n rec = self.m.data_file(file_hash=hash)\n self.__set_file_info(fn, rec)\n return rec, added\n\n def __import_datafile(self, fn, rec=None, **kwargs):\n \"\"\"\n A wrapper for data file import that tracks data files through\n the import process and builds links to data file types.\n \"\"\"\n redo = kwargs.pop(\"redo\", False)\n added = False\n if rec is None:\n rec, added = self.__create_data_file_record(fn)\n\n err_filter = True\n m = self.m.data_file_link\n if kwargs.pop(\"fix_errors\", False):\n err_filter = m.error.is_(None)\n prev_imports = (\n self.db.session\n .query(m)\n .filter_by(file_hash=rec.file_hash)\n .filter(err_filter)\n .count())\n if prev_imports > 0 and not added and not redo:\n secho(\"Already imported\", fg='green', dim=True)\n return\n # It might get ugly here if we're trying to overwrite\n # old records but haven't deleted the appropriate\n # data_file_import models\n #if prev_imports > 0 and rec is not None:\n # self.delete_session(rec)\n\n # Create a \"data_file_import\" object to track model-datafile links\n\n\n\n try:\n # import_datafile needs to return the top-level model(s)\n # created or modified during import.\n items = ensure_sequence(self.import_datafile(fn, rec, **kwargs))\n\n for created_model in items:\n # Track the import of the resulting models\n self.__track_model(rec, created_model)\n self.db.session.flush()\n except (SparrowImportError, NotImplementedError, IntegrityError) as err:\n self.db.session.rollback()\n self.__track_model(rec, None, error=str(err))\n secho(str(err), fg='red')\n\n if redo:\n dirty = set(i for i in set(self.__dirty) if self.db.session.is_modified(i))\n dirty = list(dirty | self.__new)\n if len(dirty) == 0:\n secho(\"No modifications\", fg='green')\n else:\n secho(f\"{len(dirty)} records modified\")\n\n # File records and trackers are added at the end,\n # outside of the try/except block, so they occur\n # regardness of error status\n self.db.session.commit()\n\n def __track_model(self, rec, model=None, **kw):\n \"\"\"\n Track the import of a given model from a data file\n \"\"\"\n if model is None:\n pass\n elif isinstance(model, self.m.session):\n kw['session_id'] = model.id\n elif isinstance(model, self.m.analysis):\n kw['analysis_id'] = model.id\n elif isinstance(model, self.m.sample):\n kw['sample_id'] = model.id\n else:\n raise NotImplementedError(\n \"Only sessions, samples, and analyses \"\n \"can be tracked independently on import.\")\n\n return self.db.get_or_create(\n self.m.data_file_link,\n file_hash=rec.file_hash,\n **kw)\n\n def iter_records(self, seq, **kwargs):\n \"\"\"\n This is kind of outmoded by the new version of iterfiles\n \"\"\"\n for rec in seq:\n secho(str(rec.file_path), dim=True)\n self.__import_datafile(None, rec, **kwargs)\n","sub_path":"backend/sparrow/import_helpers/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":8898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452949451","text":"from parsimonious.grammar import Grammar\n\nfrom .. import document_matchers, documents\n\n\ndef read_document_matcher(string):\n root_node = _grammar.parse(string)\n return read_document_matcher_node(root_node)\n\n\ndef read_document_matcher_node(root_node):\n element_node = root_node.children[0]\n if element_node.expr_name == \"paragraph\":\n return _read_paragraph_node(element_node)\n elif element_node.expr_name == \"run\":\n return _read_run_node(element_node)\n \n\ndef _read_paragraph_node(paragraph_node):\n style_name = _read_style_node(paragraph_node.children[1])\n numbering = _read_list_node(paragraph_node.children[2])\n return document_matchers.paragraph(style_name=style_name, numbering=numbering)\n \n\ndef _read_run_node(run_node):\n style_name = _read_style_node(run_node.children[1])\n return document_matchers.run(style_name=style_name)\n\n\ndef _read_style_node(style_node):\n if style_node.children:\n return style_node.children[0].children[1].text\n else:\n return None\n\n\ndef _read_list_node(list_node):\n if list_node.children:\n return documents.numbering_level(\n int(list_node.children[0].children[3].text) - 1,\n is_ordered=list_node.children[0].children[1].text == \"ordered-list\",\n )\n else:\n return None\n\ngrammar_text = r\"\"\"\ndocument_matcher = paragraph / run\n\nparagraph = \"p\" style_name? list?\n\nrun = \"r\" style_name?\n\nstyle_name = \".\" style_identifier\n\nstyle_identifier = ~\"[A-Z0-9]*\"i\n\nlist = \":\" list_type \"(\" ~\"[0-9]+\" \")\"\n\nlist_type = \"ordered-list\" / \"unordered-list\"\n\"\"\"\n_grammar = Grammar(grammar_text)\n\n","sub_path":"mammoth/style_reader/document_matcher_reader.py","file_name":"document_matcher_reader.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"534817234","text":"#! /bin/python3\n\nimport subprocess\nimport shlex\nimport threading\n\ndef worker():\n proc = subprocess.Popen(shlex.split('animate /home/jlusby/Dropbox/Pictures/sexy/Archive/6erF2Jc.gif'))\n proc.communicate()\n\nt = threading.Thread(target = worker)\nt.daemon = True\nt.start()\nprint(\"howdy\")\na = input(\"what?\")\nprint(\"derp\")\n","sub_path":"Scripts/py_sorter.py","file_name":"py_sorter.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"169634657","text":"from collections import deque\n\n\nclass Graph:\n CONNECTED = 1\n\n def __init__(self, V):\n self.V = V # vertex 갯수\n self.matrix = [ [0 for _ in range(V + 2)] for _ in range(V + 2)]\n self.visited = [False] * (V + 1)\n\n def addEdge(self, v, w):\n self.matrix[v][w] = Graph.CONNECTED\n self.matrix[w][v] = Graph.CONNECTED\n\n\n def bfs(self, s = 1):\n queue = deque([s])\n self.visited[s] = True\n\n while queue:\n cur_node = queue.popleft()\n print(cur_node, end = ' ') # 노드 출력\n\n for node, item in enumerate(self.matrix[cur_node]):\n if item == Graph.CONNECTED and self.visited[node] == False:\n queue.append(node)\n self.visited[node] = True\n\n\n def showGraph(self):\n print(' ' * 5, end = '')\n for i in range(self.V + 2):\n print('{:4d}'.format(i), end='')\n \n print()\n\n for v, line in enumerate(self.matrix):\n print('{:4d}'.format(v), end=' ')\n for w, item in enumerate(line):\n print('{:4d}'.format(item), end='')\n print()\n\n\ng = Graph(8)\ng.addEdge(1, 2)\ng.addEdge(1, 3)\ng.addEdge(1, 8)\ng.addEdge(2, 7)\ng.addEdge(3, 4)\ng.addEdge(3, 5)\ng.addEdge(4, 5)\ng.addEdge(6, 7)\ng.addEdge(7, 8)\n\ng.showGraph()\n\ng.bfs() # 1 2 3 8 7 4 5 6","sub_path":"cheatsheet/algorithms/dfs_bfs/bfs_adjacency_matrix.py","file_name":"bfs_adjacency_matrix.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"499685853","text":"import tensorflow as tf\nimport numpy as np\nfrom utils import batchify\n\nclass ClipPPO:\n def __init__(self,\n ob_dim, action_dim, policy,\n clip_param=0.1, max_grad_norm=0.1,\n optimizer=tf.train.AdamOptimizer, learning_rate=1e-4, optimizer_epsilon=1e-5\n ):\n self.optimizer = optimizer(learning_rate=learning_rate, epsilon=optimizer_epsilon)\n\n self.old_action_log_probs = tf.placeholder(tf.float32, shape=[None, 1], name='old_action_log_probs')\n self.old_values = tf.placeholder(tf.float32, shape=[None, 1], name='old_values')\n self.value_targets = tf.placeholder(tf.float32, shape=[None, 1], name='value_targets')\n self.advantages = tf.placeholder(tf.float32, shape=[None, 1], name='advantages')\n\n self.policy = policy\n self.obs = self.policy.obs\n self.distribution = self.policy.distribution\n self.actions = self.policy.actions\n self.action_log_probs = self.policy.action_log_probs\n self.values = self.policy.values\n self.log_vars = self.policy.log_vars\n\n # clipped policy loss\n self.action_prob_ratio = tf.exp(tf.expand_dims(self.action_log_probs, axis=1) - self.old_action_log_probs)\n self.policy_loss = -self.action_prob_ratio * self.advantages\n self.clipped_policy_loss = -tf.clip_by_value(self.action_prob_ratio, 1-clip_param, 1+clip_param) * self.advantages\n self.surr_policy_loss = tf.reduce_mean(tf.maximum(self.policy_loss, self.clipped_policy_loss))\n\n # value loss\n self.value_loss = tf.square(self.value_targets - self.values)\n self.clipped_value_loss = tf.square(\n self.value_targets - (self.old_values + tf.clip_by_value(self.values - self.old_values, -clip_param, clip_param))\n )\n # self.surr_value_loss = 0.5 * tf.reduce_mean(tf.maximum(self.value_loss, self.clipped_value_loss))\n self.surr_value_loss = 0.5 * tf.reduce_mean(self.value_loss)\n\n # total loss\n self.loss = self.surr_policy_loss + self.surr_value_loss\n\n # gradients\n self.params = tf.trainable_variables()\n self.grads = tf.gradients(self.loss, self.params)\n self.grads, _ = tf.clip_by_global_norm(self.grads, max_grad_norm)\n self.grads = list(zip(self.grads, self.params))\n self.train_op = self.optimizer.apply_gradients(self.grads)\n\n def train(self,\n obs, next_obs, actions, action_log_probs, values, value_targets, advantages,\n global_session,\n n_iters=10, batch_size=64\n ):\n data = [obs, actions, action_log_probs, values, value_targets, advantages]\n for iter_ in range(n_iters):\n batched_data = batchify(data, batch_size)\n for minibatch in batched_data:\n mb_obs, mb_actions, mb_action_log_probs, mb_values, mb_value_targets, mb_advantages = minibatch\n # normalize advantages here?\n # mb_advantages = (mb_advantages - np.mean(mb_advantages)) / (np.std(mb_advantages) + 1e-8)\n global_session.run(\n self.train_op,\n feed_dict={self.obs: mb_obs, self.actions: mb_actions, self.old_action_log_probs: mb_action_log_probs, self.old_values: mb_values, self.value_targets: mb_value_targets, self.advantages: mb_advantages}\n )\n","sub_path":"optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49724585","text":"# Copyright 2018 Ocean Protocol Foundation\n# SPDX-License-Identifier: Apache-2.0\n\nimport logging\n\nimport pytest\nfrom ocean_keeper.exceptions import OceanDIDNotFound\nfrom ocean_keeper.web3_provider import Web3Provider\nfrom ocean_utils.agreements.service_agreement import ServiceAgreement\nfrom ocean_utils.agreements.service_factory import ServiceDescriptor\nfrom ocean_utils.agreements.service_types import ServiceTypes\nfrom ocean_utils.aquarius import AquariusProvider\nfrom ocean_utils.ddo.ddo import DDO\nfrom ocean_utils.did import DID\n\nfrom tests.resources.helper_functions import (get_algorithm_ddo, get_computing_metadata,\n get_resource_path, log_event)\nfrom tests.resources.tiers import e2e_test\n\n\ndef create_asset(publisher_ocean_instance):\n ocn = publisher_ocean_instance\n sample_ddo_path = get_resource_path('ddo', 'ddo_sa_sample.json')\n assert sample_ddo_path.exists(), \"{} does not exist!\".format(sample_ddo_path)\n\n acct = ocn.main_account\n\n asset = DDO(json_filename=sample_ddo_path)\n my_secret_store = 'http://myownsecretstore.com'\n auth_service = ServiceDescriptor.authorization_service_descriptor(my_secret_store)\n return ocn.assets.create(asset.metadata, acct, [auth_service])\n\n\n@e2e_test\ndef test_register_asset(publisher_ocean_instance):\n logging.debug(\"\".format())\n sample_ddo_path = get_resource_path('ddo', 'ddo_sa_sample.json')\n assert sample_ddo_path.exists(), \"{} does not exist!\".format(sample_ddo_path)\n\n ##########################################################\n # Setup account\n ##########################################################\n publisher = publisher_ocean_instance.main_account\n\n # ensure Ocean token balance\n if publisher_ocean_instance.accounts.balance(publisher).ocn == 0:\n publisher_ocean_instance.accounts.request_tokens(publisher, 200)\n\n # You will need some token to make this transfer!\n assert publisher_ocean_instance.accounts.balance(publisher).ocn > 0\n\n ##########################################################\n # Create an asset DDO with valid metadata\n ##########################################################\n asset = DDO(json_filename=sample_ddo_path)\n\n ##########################################################\n # Register using high-level interface\n ##########################################################\n ddo = publisher_ocean_instance.assets.create(asset.metadata, publisher)\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\n@e2e_test\ndef test_resolve_did(publisher_ocean_instance, metadata):\n # prep ddo\n # metadata = Metadata.get_example()\n publisher = publisher_ocean_instance.main_account\n # happy path\n original_ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n did = original_ddo.did\n ddo = publisher_ocean_instance.assets.resolve(did).as_dictionary()\n original = original_ddo.as_dictionary()\n assert ddo['publicKey'] == original['publicKey']\n assert ddo['authentication'] == original['authentication']\n assert ddo['service']\n assert original['service']\n metadata = ddo['service'][0]['attributes']\n if 'datePublished' in metadata['main']:\n metadata['main'].pop('datePublished')\n assert ddo['service'][0]['attributes']['main']['name'] == \\\n original['service'][0]['attributes']['main']['name']\n assert ddo['service'][1] == original['service'][1]\n\n # Can't resolve unregistered asset\n unregistered_did = DID.did({\"0\": \"0x00112233445566\"})\n with pytest.raises(OceanDIDNotFound):\n publisher_ocean_instance.assets.resolve(unregistered_did)\n\n # Raise error on bad did\n invalid_did = \"did:op:0123456789\"\n with pytest.raises(OceanDIDNotFound):\n publisher_ocean_instance.assets.resolve(invalid_did)\n publisher_ocean_instance.assets.retire(did)\n\n\n@e2e_test\ndef test_create_data_asset(publisher_ocean_instance, consumer_ocean_instance):\n \"\"\"\n Setup accounts and asset, register this asset on Aquarius (MetaData store)\n \"\"\"\n pub_ocn = publisher_ocean_instance\n cons_ocn = consumer_ocean_instance\n\n logging.debug(\"\".format())\n sample_ddo_path = get_resource_path('ddo', 'ddo_sa_sample.json')\n assert sample_ddo_path.exists(), \"{} does not exist!\".format(sample_ddo_path)\n\n ##########################################################\n # Setup 2 accounts\n ##########################################################\n aquarius_acct = pub_ocn.main_account\n consumer_acct = cons_ocn.main_account\n\n # ensure Ocean token balance\n if pub_ocn.accounts.balance(aquarius_acct).ocn == 0:\n rcpt = pub_ocn.accounts.request_tokens(aquarius_acct, 200)\n Web3Provider.get_web3().eth.waitForTransactionReceipt(rcpt)\n if cons_ocn.accounts.balance(consumer_acct).ocn == 0:\n rcpt = cons_ocn.accounts.request_tokens(consumer_acct, 200)\n Web3Provider.get_web3().eth.waitForTransactionReceipt(rcpt)\n\n # You will need some token to make this transfer!\n assert pub_ocn.accounts.balance(aquarius_acct).ocn > 0\n assert cons_ocn.accounts.balance(consumer_acct).ocn > 0\n\n ##########################################################\n # Create an Asset with valid metadata\n ##########################################################\n asset = DDO(json_filename=sample_ddo_path)\n\n ##########################################################\n # List currently published assets\n ##########################################################\n meta_data_assets = pub_ocn.assets.search('')\n if meta_data_assets:\n print(\"Currently registered assets:\")\n print(meta_data_assets)\n\n if asset.did in meta_data_assets:\n pub_ocn.assets.resolve(asset.did)\n pub_ocn.assets.retire(asset.did)\n # Publish the metadata\n new_asset = pub_ocn.assets.create(asset.metadata, aquarius_acct)\n\n # get_asset_metadata only returns 'main' key, is this correct?\n published_metadata = cons_ocn.assets.resolve(new_asset.did)\n\n assert published_metadata\n # only compare top level keys\n assert sorted(list(asset.metadata['main'].keys())).remove('files') == sorted(\n list(published_metadata.metadata.keys())).remove('encryptedFiles')\n publisher_ocean_instance.assets.retire(new_asset.did)\n\n\ndef test_create_asset_with_different_secret_store(publisher_ocean_instance):\n ocn = publisher_ocean_instance\n\n sample_ddo_path = get_resource_path('ddo', 'ddo_sa_sample.json')\n assert sample_ddo_path.exists(), \"{} does not exist!\".format(sample_ddo_path)\n\n acct = ocn.main_account\n\n aqua = AquariusProvider.get_aquarius(ocn.config.aquarius_url)\n aqua.retire_all_assets()\n\n asset = DDO(json_filename=sample_ddo_path)\n my_secret_store = 'http://myownsecretstore.com'\n auth_service = ServiceDescriptor.authorization_service_descriptor(my_secret_store)\n new_asset = ocn.assets.create(asset.metadata, acct, [auth_service])\n assert new_asset.get_service(ServiceTypes.AUTHORIZATION).service_endpoint == my_secret_store\n assert new_asset.get_service(ServiceTypes.ASSET_ACCESS)\n assert new_asset.get_service(ServiceTypes.METADATA)\n publisher_ocean_instance.assets.retire(new_asset.did)\n\n access_service = ServiceDescriptor.access_service_descriptor(\n {\"main\": {\n \"name\": \"dataAssetAccessServiceAgreement\",\n \"creator\": '0x1234',\n \"price\": '1',\n \"timeout\": 3600,\n \"datePublished\": '2019-08-30T12:19:54Z'\n }},\n 'service/endpoint',\n '0x0011001100110011'\n )\n new_asset = ocn.assets.create(asset.metadata, acct, [access_service])\n assert new_asset.get_service(ServiceTypes.AUTHORIZATION)\n assert new_asset.get_service(ServiceTypes.ASSET_ACCESS)\n assert new_asset.get_service(ServiceTypes.METADATA)\n publisher_ocean_instance.assets.retire(new_asset.did)\n\n new_asset = ocn.assets.create(asset.metadata, acct)\n assert new_asset.get_service(ServiceTypes.AUTHORIZATION)\n assert new_asset.get_service(ServiceTypes.ASSET_ACCESS)\n assert new_asset.get_service(ServiceTypes.METADATA)\n publisher_ocean_instance.assets.retire(new_asset.did)\n\n\ndef test_asset_owner(publisher_ocean_instance):\n ocn = publisher_ocean_instance\n\n sample_ddo_path = get_resource_path('ddo', 'ddo_sa_sample.json')\n assert sample_ddo_path.exists(), \"{} does not exist!\".format(sample_ddo_path)\n\n acct = ocn.main_account\n\n asset = DDO(json_filename=sample_ddo_path)\n my_secret_store = 'http://myownsecretstore.com'\n auth_service = ServiceDescriptor.authorization_service_descriptor(my_secret_store)\n new_asset = ocn.assets.create(asset.metadata, acct, [auth_service])\n\n assert ocn.assets.owner(new_asset.did) == acct.address\n publisher_ocean_instance.assets.retire(new_asset.did)\n\n\ndef test_owner_assets(publisher_ocean_instance):\n ocn = publisher_ocean_instance\n acct = ocn.main_account\n assets_owned = len(ocn.assets.owner_assets(acct.address))\n asset = create_asset(publisher_ocean_instance)\n assert len(ocn.assets.owner_assets(acct.address)) == assets_owned + 1\n publisher_ocean_instance.assets.retire(asset.did)\n\n\ndef test_assets_consumed(publisher_ocean_instance, consumer_ocean_instance):\n ocn = publisher_ocean_instance\n acct = consumer_ocean_instance.main_account\n consumed_assets = len(ocn.assets.consumer_assets(acct.address))\n asset = create_asset(publisher_ocean_instance)\n service = asset.get_service(service_type=ServiceTypes.ASSET_ACCESS)\n service_dict = service.as_dictionary()\n sa = ServiceAgreement.from_json(service_dict)\n keeper = ocn.keeper\n\n def grant_access(event, ocn_instance, agr_id, did, cons_address, account):\n ocn_instance.agreements.conditions.grant_access(\n agr_id, did, cons_address, account)\n\n agreement_id = consumer_ocean_instance.assets.order(\n asset.did, sa.index, acct)\n keeper.lock_reward_condition.subscribe_condition_fulfilled(\n agreement_id,\n 15,\n grant_access,\n (publisher_ocean_instance, agreement_id, asset.did,\n acct.address, publisher_ocean_instance.main_account),\n wait=True\n )\n\n keeper.access_secret_store_condition.subscribe_condition_fulfilled(\n agreement_id,\n 15,\n log_event(keeper.access_secret_store_condition.FULFILLED_EVENT),\n (),\n wait=True\n )\n assert ocn.agreements.is_access_granted(agreement_id, asset.did, acct.address)\n\n assert len(ocn.assets.consumer_assets(acct.address)) == consumed_assets + 1\n publisher_ocean_instance.assets.retire(asset.did)\n\n\ndef test_ocean_assets_resolve(publisher_ocean_instance, metadata):\n publisher = publisher_ocean_instance.main_account\n ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n ddo_resolved = publisher_ocean_instance.assets.resolve(ddo.did)\n assert ddo.did == ddo_resolved.did\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_assets_search(publisher_ocean_instance, metadata):\n publisher = publisher_ocean_instance.main_account\n ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n assert len(publisher_ocean_instance.assets.search('Monkey')) > 0\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_assets_validate(publisher_ocean_instance, metadata):\n assert publisher_ocean_instance.assets.validate(metadata)\n\n\ndef test_ocean_assets_algorithm(publisher_ocean_instance):\n # Allow publish an algorithm\n publisher = publisher_ocean_instance.main_account\n metadata = get_algorithm_ddo()['service'][0]\n ddo = publisher_ocean_instance.assets.create(metadata['attributes'], publisher)\n assert ddo\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_assets_workflow(publisher_ocean_instance):\n # :FIXME: re-enable this test once plecos v1.0.1 is released in a new Aquarius version.\n return\n # # Allow publish an workflow\n # publisher = publisher_ocean_instance.main_account\n # metadata = get_workflow_ddo()['service'][0]\n # valid_results = plecos.validate_dict_local(metadata['attributes'])\n # print(f'validation result: {valid_results}')\n # ddo = publisher_ocean_instance.assets.create(metadata['attributes'], publisher)\n # assert ddo\n # publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_assets_compute(publisher_ocean_instance):\n publisher = publisher_ocean_instance.main_account\n metadata = get_computing_metadata()\n ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n assert ddo\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_transfer_ownership(publisher_ocean_instance, metadata, consumer_ocean_instance):\n publisher = publisher_ocean_instance.main_account\n consumer = consumer_ocean_instance.main_account\n ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n owner = publisher_ocean_instance.assets.owner(ddo.did)\n assert owner == publisher.address\n publisher_ocean_instance.assets.transfer_ownership(ddo.did, consumer.address, publisher)\n assert publisher_ocean_instance.assets.owner(ddo.did) == consumer.address\n publisher_ocean_instance.assets.retire(ddo.did)\n\n\ndef test_ocean_grant_permissions(publisher_ocean_instance, metadata, consumer_ocean_instance):\n publisher = publisher_ocean_instance.main_account\n consumer = consumer_ocean_instance.main_account\n ddo = publisher_ocean_instance.assets.create(metadata, publisher)\n assert not publisher_ocean_instance.assets.get_permissions(ddo.did, consumer.address)\n publisher_ocean_instance.assets.delegate_persmission(ddo.did, consumer.address, publisher)\n assert publisher_ocean_instance.assets.get_permissions(ddo.did, consumer.address)\n publisher_ocean_instance.assets.revoke_permissions(ddo.did, consumer.address, publisher)\n assert not publisher_ocean_instance.assets.get_permissions(ddo.did, consumer.address)\n\n\n# def test_ocean_execute_workflow(publisher_ocean_instance, consumer_ocean_instance):\n# publisher = publisher_ocean_instance.main_account\n# consumer = consumer_ocean_instance.main_account\n# publisher_ocean_instance.assets._get_aquarius().retire_all_assets()\n# metadata = get_workflow_ddo()['service'][0]\n# workflow_ddo = publisher_ocean_instance.assets.create(metadata['attributes'], publisher)\n# assert workflow_ddo\n# metadata = get_computing_metadata()\n# ddo_computing = publisher_ocean_instance.assets.create(metadata, publisher)\n# assert ddo_computing\n# service = ddo_computing.get_service(service_type=ServiceTypes.CLOUD_COMPUTE)\n# sa = ServiceAgreement.from_json(service.as_dictionary())\n# agreement_id = consumer_ocean_instance.assets.order(ddo_computing.did, sa.index, consumer)\n# keeper = publisher_ocean_instance.keeper\n# event = keeper.compute_execution_condition.subscribe_condition_fulfilled(\n# agreement_id,\n# 90,\n# log_event(keeper.compute_execution_condition.FULFILLED_EVENT),\n# (),\n# wait=True\n# )\n# assert event, 'no event for compute_execution_condition.Fulfilled'\n#\n# try:\n# job_id = consumer_ocean_instance.assets.execute(\n# agreement_id, ddo_computing.did, sa.index, consumer, workflow_ddo.did)\n# print(f'Compute job started successfully, job id is {job_id}')\n# except Exception as e:\n# print(f'Executing the compute job for agreementId {agreement_id} failed: {e}')\n","sub_path":"tests/ocean/test_ocean_assets.py","file_name":"test_ocean_assets.py","file_ext":"py","file_size_in_byte":15504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"6475032","text":"\"\"\"Handler for linode_event_base module\"\"\"\n\nimport unittest\n\nfrom ..ta_linode_util import BaseLinodeEventLogger\n\n\nclass TestLinodeEventBase(unittest.TestCase):\n \"\"\"Test for linode_event_base module\"\"\"\n\n @staticmethod\n def test_get_app_manifest():\n \"\"\"Test that the app manifest is parsed correctly\"\"\"\n\n logger = BaseLinodeEventLogger(fixture_mode=True)\n manifest = logger._get_app_manifest()\n\n assert manifest is not None\n assert manifest.get('info').get('id').get('version') is not None\n","sub_path":"TA-linode/bin/tests/linode_event_base_test.py","file_name":"linode_event_base_test.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64950847","text":"#!/usr/bin/env python\n# Software License Agreement (BSD License)\n#\n# Copyright (c) 2008, Willow Garage, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Willow Garage, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\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 OWNER 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#\n# Revision $Id$\n\n## Simple talker demo that published std_msgs/Strings messages\n## to the 'chatter' topic\n\nimport rospy\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Twist, Vector3\nfrom sensor_msgs.msg import LaserScan\n\n\nclass LaserFilter:\n def __init__(self):\n rospy.init_node('laser_filter', anonymous=True)\n self.pub = rospy.Publisher('scan', LaserScan, queue_size=10)\n self.sub = rospy.Subscriber('base_scan', LaserScan, self.scan_received)\n\n def scan_received(self, msg):\n \"\"\" Processes data from the laser scanner, msg is of type sensor_msgs/LaserScan \"\"\"\n filtered_ranges = []\n filtered_intensities = []\n for i in range(len(msg.ranges)):\n if msg.ranges[i] < 0.2 or msg.ranges[i] > 5.5:\n filtered_ranges.append(0.0)\n filtered_intensities.append(0.0)\n else:\n filtered_ranges.append(msg.ranges[i])\n filtered_intensities.append(msg.intensities[i])\n msg.ranges = filtered_ranges\n msg.intensities = filtered_intensities\n self.pub.publish(msg)\n\n def run(self):\n while not rospy.is_shutdown():\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n node = LaserFilter()\n node.run()\n except rospy.ROSInterruptException: pass\n","sub_path":"neato_simulator/scripts/laser_filter.py","file_name":"laser_filter.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"155705034","text":"from ..func_utils import infer_method_name\nfrom .exceptions import CustomFilterDescriptorError\n\n\nclass CustomFilterDescriptor:\n\n FILTER_METHOD_NAME = 'filter_by'\n\n def __init__(self, field_name, field_value_filter):\n self.field_name = field_name\n self.field_value_filter = field_value_filter\n\n def __get__(self, obj, objtype):\n\n def get_custom_filter():\n method_name = infer_method_name(\n self.field_name,\n self.FILTER_METHOD_NAME,\n )\n\n try:\n class_method = getattr(obj, method_name)\n return class_method(self.field_value_filter)\n except AttributeError:\n raise NotImplementedError(\n 'Class `{}` does not implement `{}`'.format(\n obj.__class__.__name__, method_name,\n ),\n )\n\n return get_custom_filter\n\n\nclass CustomFilterDescriptorMixin:\n \"\"\"\n For every field and option in FILTER_DESCRIPTORS dict\n in the super class this descriptor build\n \"filter_by_[field]_[option]\" and\n call to method filter_by_[field] of the super class\n with the current option for filter\n\n \"\"\"\n FILTER_PREFIX = 'filter_by'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n choices_list = self.get_choices()\n\n for choice_value in choices_list:\n field_name = choice_value.get('field')\n options = choice_value.get('options')\n\n for choice_code, method_name in options:\n self.set_descriptor(choice_code, method_name, field_name)\n\n def get_choices(self):\n try:\n choices = self.FILTER_DESCRIPTORS\n except AttributeError:\n raise CustomFilterDescriptorError(\n 'FILTER_DESCRIPTORS dict not defined',\n )\n\n return choices\n\n def set_descriptor(self, choice_code, method_name, field_name):\n format_method_name = infer_method_name(method_name)\n format_descriptor = infer_method_name(\n field_name,\n self.FILTER_PREFIX,\n '_{}'.format(format_method_name),\n )\n\n setattr(\n self.__class__,\n format_descriptor,\n CustomFilterDescriptor(field_name, choice_code),\n )\n","sub_path":"service-exo-opportunities/utils/descriptors/custom_filter_descriptor_mixin.py","file_name":"custom_filter_descriptor_mixin.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565801929","text":"# -*- coding: utf-8 -*-\r\n'''\r\nLinear Regression model under POM4\r\n\r\n'''\r\n\r\n__author__ = \"Angel Navia-Vázquez & Francisco González-Serrano\"\r\n__date__ = \"Dec. 2020\"\r\n\r\nimport numpy as np\r\nfrom MMLL.models.Common_to_all_POMs import Common_to_all_POMs\r\nfrom transitions import State\r\nfrom transitions.extensions import GraphMachine\r\nimport pickle\r\nfrom pympler import asizeof #asizeof.asizeof(my_object)\r\nimport dill\r\nimport time\r\n\r\nclass Model():\r\n \"\"\"\r\n Linear Regression model.\r\n \"\"\"\r\n def __init__(self):\r\n self.w = None\r\n self.is_trained = False\r\n self.supported_formats = ['pkl', 'onnx', 'pmml']\r\n t = time.time()\r\n seed = int((t - int(t)) * 10000)\r\n np.random.seed(seed=seed)\r\n\r\n def predict(self, X):\r\n \"\"\"\r\n Predicts outputs given the inputs\r\n\r\n Parameters\r\n ----------\r\n X_b: ndarray\r\n Matrix with the input values\r\n\r\n Returns\r\n -------\r\n prediction_values: ndarray\r\n\r\n \"\"\"\r\n X_b = np.hstack((np.ones((X.shape[0], 1)), X))\r\n prediction_values = np.dot(X_b, self.w.ravel())\r\n return prediction_values\r\n\r\n def save(self, filename=None):\r\n \"\"\"\r\n Saves the trained model to file. The valid file extensions are: \r\n - \"pkl\": saves the model as a Python3 pickle file \r\n - \"onnx\": saves the model using Open Neural Network Exchange format (ONNX)' \r\n - \"pmml\": saves the model using Predictive Model Markup Language (PMML)' \r\n\r\n Parameters\r\n ----------\r\n filename: string\r\n path+filename \r\n \"\"\"\r\n if filename is None:\r\n print('=' * 80)\r\n print('Model Save Error: A valid filename must be provided, otherwise nothing is saved. The valid file extensions are:') \r\n print('\\t - \"pkl\": saves the model as a Python3 pickle file') \r\n print('\\t - \"onnx\": saves the model using Open Neural Network Exchange format (ONNX)') \r\n print('\\t - \"pmml\": saves the model using Predictive Model Markup Language (PMML)') \r\n print('=' * 80)\r\n else:\r\n # Checking filename extension\r\n extension = filename.split('.')[-1]\r\n if extension not in self.supported_formats:\r\n print('=' * 80)\r\n print('Model Save Error: Unsupported format. The valid file extensions are:') \r\n print('\\t - \"pkl\": saves the model as a Python3 pickle file') \r\n print('\\t - \"onnx\": saves the model using Open Neural Network Exchange format (ONNX)') \r\n print('\\t - \"pmml\": saves the model using Predictive Model Markup Language (PMML)') \r\n print('=' * 80)\r\n else:\r\n if not self.is_trained:\r\n print('=' * 80)\r\n print('Model Save Error: model not trained yet, nothing to save.')\r\n print('=' * 80)\r\n else:\r\n try:\r\n if extension == 'pkl':\r\n with open(filename, 'wb') as f:\r\n pickle.dump(self, f)\r\n print('=' * 80)\r\n print('Model saved at %s in pickle format.' %filename)\r\n print('=' * 80)\r\n elif extension == 'onnx':\r\n from sklearn import linear_model\r\n from skl2onnx import convert_sklearn # conda install -c conda-forge skl2onnx\r\n from skl2onnx.common.data_types import FloatTensorType\r\n export_model = linear_model.LinearRegression()\r\n export_model.coef_ = self.w[1:].ravel()\r\n NI = export_model.coef_.shape[0]\r\n export_model.intercept_ = self.w[0][0]\r\n # Convert into ONNX format\r\n input_type = [('float_input', FloatTensorType([None, NI]))]\r\n onnx_model = convert_sklearn(export_model, initial_types=input_type)\r\n with open(filename, \"wb\") as f:\r\n f.write(onnx_model.SerializeToString())\r\n print('=' * 80)\r\n print('Model saved at %s in ONNX format.' %filename)\r\n print('=' * 80)\r\n elif extension == 'pmml':\r\n from sklearn import linear_model\r\n from sklearn2pmml import sklearn2pmml # pip install git+https://github.com/jpmml/sklearn2pmml.git\r\n from sklearn2pmml.pipeline import PMMLPipeline\r\n export_model = linear_model.LinearRegression()\r\n export_model.coef_ = self.w[1:].ravel()\r\n export_model.intercept_ = self.w[0][0]\r\n pipeline = PMMLPipeline([(\"classifier\", export_model)])\r\n sklearn2pmml(pipeline, filename, with_repr = True)\r\n print('=' * 80)\r\n print('Model saved at %s in PMML format.' %filename)\r\n print('=' * 80)\r\n else:\r\n print('=' * 80)\r\n print('Model Save Error: model cannot be saved at %s.' %filename)\r\n print('=' * 80)\r\n except:\r\n print('=' * 80)\r\n print('Model Save Error: model cannot be saved at %s, please check the provided path/filename.' %filename)\r\n print('=' * 80)\r\n raise\r\n\r\nclass LR_Master(Common_to_all_POMs):\r\n \"\"\"\r\n This class implements the Linear Regression model, run at Master node. It inherits from Common_to_all_POMs.\r\n \"\"\"\r\n\r\n def __init__(self, master_address, workers_addresses, model_type, comms, logger, verbose=True, **kwargs):\r\n \"\"\"\r\n Create a :class:`LR_Master` instance.\r\n\r\n Parameters\r\n ----------\r\n master_address: string\r\n address of the master node\r\n\r\n workers_addresses: list of strings\r\n list of the addresses of the workers\r\n\r\n comms: comms object instance\r\n object providing communications\r\n\r\n logger: class:`logging.Logger`\r\n logging object instance\r\n\r\n verbose: boolean\r\n indicates if messages are print or not on screen\r\n \r\n kwargs: Keyword arguments.\r\n\r\n \"\"\"\r\n super().__init__()\r\n self.pom = 4\r\n self.model_type = model_type\r\n self.name = 'POM%d_' % self.pom + self.model_type + '_Master' # Name\r\n #self.NC = NC # No. Centroids\r\n #self.Nmaxiter = Nmaxiter\r\n self.master_address = master_address\r\n\r\n\r\n self.workers_addresses = workers_addresses\r\n self.cryptonode_address = None\r\n self.Nworkers = len(workers_addresses) # Nworkers\r\n self.logger = logger # logger\r\n self.comms = comms # comms lib\r\n self.state_dict = None # State of the main script\r\n self.verbose = verbose # print on screen when true\r\n self.state_dict = {} # dictionary storing the execution state\r\n self.NI = None\r\n #self.regularization = regularization\r\n #self.classes = classes\r\n #self.balance_classes = balance_classes\r\n #self.Xval_b = Xval_b\r\n #self.yval = yval\r\n self.epsilon = 0.00000001 # to avoid log(0)\r\n self.momentum = 0\r\n self.minibatch = 1.0\r\n\r\n for k in range(0, self.Nworkers):\r\n self.state_dict.update({self.workers_addresses[k]: ''})\r\n #default values\r\n # we extract the model_parameters as extra kwargs, to be all jointly processed\r\n try:\r\n kwargs.update(kwargs['model_parameters'])\r\n del kwargs['model_parameters']\r\n except:\r\n pass\r\n self.process_kwargs(kwargs)\r\n self.message_counter = 100 # used to number the messages\r\n self.XTX_dict = {}\r\n self.XTy_dict = {}\r\n #self.encrypter = self.cr.get_encrypter() # to be shared # self.encrypter.encrypt(np.random.normal(0, 1, (2,3)))\r\n #self.decrypter = self.cr.get_decrypter() # to be kept as secret self.encrypter.decrypt()\r\n self.create_FSM_master()\r\n self.FSMmaster.master_address = master_address\r\n self.model = Model()\r\n self.added_bias = False\r\n self.train_data_is_ready = False\r\n t = time.time()\r\n seed = int((t - int(t)) * 10000)\r\n np.random.seed(seed=seed)\r\n\r\n def create_FSM_master(self):\r\n \"\"\"\r\n Creates a Finite State Machine to be run at the Master Node\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n\r\n self.display(self.name + ': creating FSM')\r\n\r\n states_master = [\r\n State(name='waiting_order', on_enter=['while_waiting_order']),\r\n State(name='update_tr_data', on_enter=['while_update_tr_data']),\r\n State(name='store_Xyblinded', on_enter=['while_store_Xyblinded']),\r\n State(name='mult_XB', on_enter=['while_mult_XB']),\r\n State(name='decrypt_model', on_enter=['while_decrypt_model'])\r\n ]\r\n\r\n transitions_master = [\r\n ['go_update_tr_data', 'waiting_order', 'update_tr_data'],\r\n ['go_waiting_order', 'update_tr_data', 'waiting_order'],\r\n\r\n ['go_store_Xyblinded', 'waiting_order', 'store_Xyblinded'],\r\n ['done_store_Xyblinded', 'store_Xyblinded', 'waiting_order'],\r\n\r\n ['go_mult_XB', 'waiting_order', 'mult_XB'],\r\n ['done_mult_XB', 'mult_XB', 'waiting_order'],\r\n\r\n ['go_decrypt_model', 'waiting_order', 'decrypt_model'],\r\n ['done_decrypt_model', 'decrypt_model', 'waiting_order']\r\n ]\r\n\r\n\r\n class FSM_master(object):\r\n\r\n self.name = 'FSM_master'\r\n\r\n def while_waiting_order(self, MLmodel):\r\n try:\r\n MLmodel.display(MLmodel.name + ' is waiting...')\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT while_waiting_order')\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n\r\n return\r\n\r\n def while_update_tr_data(self, MLmodel):\r\n try:\r\n action = 'update_tr_data'\r\n data = {}\r\n packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address}\r\n \r\n message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter)\r\n packet.update({'message_id': message_id})\r\n MLmodel.message_counter += 1\r\n size_bytes = asizeof.asizeof(dill.dumps(packet))\r\n MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False)\r\n\r\n MLmodel.comms.broadcast(packet)\r\n MLmodel.display(MLmodel.name + ': broadcasted update_tr_data to all Workers')\r\n except Exception as err:\r\n raise\r\n '''\r\n message = \"ERROR: %s %s\" % (str(err), str(type(err)))\r\n MLmodel.display('\\n ' + '='*50 + '\\n' + message + '\\n ' + '='*50 + '\\n' )\r\n MLmodel.display('ERROR AT while_update_tr_data')\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n return\r\n\r\n '''\r\n def while_send_w_encr(self, MLmodel):\r\n try:\r\n data = {}\r\n data.update({'w_encr': MLmodel.w_encr})\r\n #wdill = MLmodel.dill_it(MLmodel.wq_encr)\r\n #data.update({'wq_encr': wdill})\r\n\r\n packet = {'action': 'send_w_encr', 'to': 'MLmodel', 'data': data}\r\n MLmodel.comms.broadcast(packet, MLmodel.workers_addresses)\r\n MLmodel.display(MLmodel.name + ' send_w_encr to workers')\r\n except:\r\n print('ERROR AT while_send_w_encr')\r\n import code\r\n code.interact(local=locals())\r\n return\r\n '''\r\n def while_mult_XB(self, MLmodel, B_bl):\r\n try:\r\n data = {'B_bl': B_bl}\r\n action = 'send_mult_XB'\r\n packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address}\r\n \r\n #destination = MLmodel.cryptonode_address\r\n destination = 'ca'\r\n message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter)\r\n packet.update({'message_id': message_id})\r\n MLmodel.message_counter += 1\r\n size_bytes = asizeof.asizeof(dill.dumps(packet))\r\n MLmodel.display('COMMS_MASTER_SEND %s to %s, id = %s, bytes=%s' % (action, destination, message_id, str(size_bytes)), verbose=False)\r\n\r\n MLmodel.comms.send(packet, MLmodel.send_to[MLmodel.cryptonode_address])\r\n MLmodel.display(MLmodel.name + ' send_mult_XB to cryptonode')\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT LR while_mult_XB')\r\n import code\r\n code.interact(local=locals())\r\n pass\r\n '''\r\n return\r\n\r\n def while_decrypt_model(self, MLmodel, model_encr):\r\n try:\r\n\r\n MLmodel.display('PROC_MASTER_START', verbose=False)\r\n\r\n # Adding blinding to model\r\n MLmodel.bl = {}\r\n model_encr_bl = {}\r\n\r\n for key in list(model_encr.keys()):\r\n x = model_encr[key]\r\n #print('while_decrypt_model LR bl=:')\r\n M, N = x.shape\r\n bl = np.random.normal(0, 1, (M, N))\r\n #print(bl)\r\n MLmodel.bl.update({key: bl})\r\n model_encr_bl.update({key: x + bl})\r\n\r\n MLmodel.display('PROC_MASTER_END', verbose=False)\r\n\r\n data = {'model_bl': model_encr_bl}\r\n action = 'send_model_encr_bl'\r\n packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address}\r\n \r\n #destination = MLmodel.cryptonode_address\r\n destination = 'ca'\r\n message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter)\r\n packet.update({'message_id': message_id})\r\n MLmodel.message_counter += 1\r\n size_bytes = asizeof.asizeof(dill.dumps(packet))\r\n MLmodel.display('COMMS_MASTER_SEND %s to %s, id = %s, bytes=%s' % (action, destination, message_id, str(size_bytes)), verbose=False)\r\n\r\n MLmodel.comms.send(packet, MLmodel.send_to[MLmodel.cryptonode_address])\r\n MLmodel.display(MLmodel.name + ' send_model_encr_bl to cryptonode')\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT LR while_decrypt_model')\r\n import code\r\n code.interact(local=locals())\r\n pass\r\n '''\r\n return\r\n\r\n def while_Exit(self, MLmodel):\r\n #print('while_Exit')\r\n return\r\n\r\n self.FSMmaster = FSM_master()\r\n self.grafmachine_master = GraphMachine(model=self.FSMmaster,\r\n states=states_master,\r\n transitions=transitions_master,\r\n initial='waiting_order',\r\n show_auto_transitions=False, # default value is False\r\n title=\"Finite State Machine modelling the behaviour of the master\",\r\n show_conditions=False)\r\n return\r\n\r\n def reset(self, NI):\r\n \"\"\"\r\n Create some empty variables needed by the Master Node\r\n\r\n Parameters\r\n ----------\r\n NI: integer\r\n Number of input features\r\n \"\"\"\r\n self.NI = NI\r\n self.w_decr = np.random.normal(0, 0.001, (self.NI + 1, 1)) # weights in plaintext, first value is bias\r\n self.R_central_decr = np.zeros((self.NI + 1, self.NI + 1)) # Cov. matrix in plaintext\r\n self.r_central_decr = np.zeros((self.NI + 1, 1)) # Cov. matrix in plaintext\r\n self.preds_dict = {} # dictionary storing the prediction errors\r\n self.AUCs_dict = {} # dictionary storing the prediction errors\r\n self.R_dict = {}\r\n self.r_dict = {}\r\n self.display(self.name + ': Resetting local data')\r\n\r\n def train_Master(self):\r\n \"\"\"\r\n This is the main training loop, it runs the following actions until \r\n the stop condition is met:\r\n - Update the execution state\r\n - Process the received packets\r\n - Perform actions according to the state\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n print(self.name + ': Starting training')\r\n #self.X_encr_dict\r\n self.display('MASTER_INIT', verbose=False)\r\n\r\n #self.MasterMLmodel.BX_dict\r\n #self.MasterMLmodel.By_dict\r\n\r\n self.NI = self.input_data_description['NI']\r\n\r\n '''\r\n # Bias already added at the workers...\r\n if not self.added_bias:\r\n # Adding encrypted bias\r\n for waddr in self.X_encr_dict.keys():\r\n X = self.X_encr_dict[waddr]\r\n NP = X.shape[0]\r\n ones = np.ones((NP, 1))\r\n ones_encr = self.encrypter.encrypt(ones)\r\n self.X_encr_dict[waddr] = np.hstack((ones_encr, X))\r\n self.added_bias = True\r\n '''\r\n self.display('PROC_MASTER_START', verbose=False)\r\n\r\n self.w = np.random.normal(0, 0.1, (self.NI + 1, 1))\r\n self.w_encr = self.encrypter.encrypt(self.w)\r\n self.w_old = np.random.normal(0, 10, (self.NI + 1, 1)) # large to avoid stop at first iteration\r\n self.grad_old = np.zeros((self.NI + 1, 1))\r\n\r\n '''\r\n if not self.train_data_is_ready: \r\n self.FSMmaster.go_update_tr_data(self)\r\n self.run_Master()\r\n # Checking the new NI values\r\n print(list(self.newNI_dict.values()))\r\n newNIs = list(set(list(self.newNI_dict.values())))\r\n if len(newNIs) > 1:\r\n message = 'ERROR: the training data has different number of features...'\r\n self.display(message)\r\n self.display(list(self.newNI_dict.values()))\r\n raise Exception(message)\r\n else:\r\n self.reset(newNIs[0])\r\n ## Adding bias to validation data, if any\r\n if self.Xval_b is not None: \r\n self.Xval_b = self.add_bias(self.Xval_b).astype(float)\r\n self.yval = self.yval.astype(float)\r\n self.train_data_is_ready = True\r\n\r\n self.receivers_list = None\r\n if self.selected_workers is not None:\r\n self.workers_addresses = self.selected_workers\r\n else:\r\n self.workers_addresses = self.all_workers_addresses[:]\r\n\r\n '''\r\n print(self.workers_addresses)\r\n\r\n self.Nworkers = len(self.workers_addresses) \r\n self.state_dict = {} # dictionary storing the execution state\r\n for k in range(0, self.Nworkers):\r\n self.state_dict.update({self.workers_addresses[k]: ''})\r\n self.receivers_list=[]\r\n for worker in self.workers_addresses:\r\n self.receivers_list.append(self.send_to[worker])\r\n\r\n # Data at self.X_encr_dict, self.y_encr_dict\r\n\r\n check = False\r\n which = '4'\r\n\r\n self.stop_training = False\r\n kiter = 0\r\n\r\n self.selected_workers = self.workers_addresses\r\n\r\n if self.Xval is not None:\r\n message = 'WARNING: Validation data is not used during training.'\r\n self.display(message, True)\r\n\r\n self.display('PROC_MASTER_END', verbose=False)\r\n\r\n while not self.stop_training:\r\n\r\n self.display('MASTER_ITER_START', verbose=False)\r\n\r\n self.display('PROC_MASTER_START', verbose=False)\r\n\r\n # Computing wTX\r\n #self.wTX_encr_dict = self.crypto_mult_X(self.w_encr.T)\r\n self.Xw_encr_dict = {}\r\n for key in self.selected_workers:\r\n self.Xw_encr_dict.update({key: np.dot(self.X_encr_dict[key], self.w)})\r\n\r\n if check:\r\n X0 = self.decrypter.decrypt(self.X_encr_dict[which])\r\n #w = self.decrypter.decrypt(self.w_encr)\r\n o = np.dot(X0, self.w)\r\n #o_ = np.sum(self.Xw_encr_dict[which], axis=1).reshape((-1, 1))\r\n o_decr = self.decrypter.decrypt(self.Xw_encr_dict[which])\r\n print(np.linalg.norm(o - o_decr)) # OK\r\n\r\n\r\n # Computing errors\r\n self.e_encr_dict = {}\r\n for waddr in self.selected_workers:\r\n #X = self.X_encr_dict[waddr]\r\n y = self.y_encr_dict[waddr].reshape(-1, 1)\r\n \r\n # We neeed the mult prototocol to compute this...\r\n # o_encr = np.dot(X, self.w)\r\n #o_encr = np.sum(self.wTX_encr_dict[waddr], axis=1).reshape((-1, 1))\r\n o_encr = self.Xw_encr_dict[waddr]\r\n e_encr = o_encr - y\r\n self.e_encr_dict.update({waddr: e_encr})\r\n\r\n if check:\r\n y0_encr = self.y_encr_dict[which].reshape(-1, 1)\r\n y0 = self.decrypter.decrypt(y0_encr)\r\n e_ = o_decr - y0\r\n e0 = self.decrypter.decrypt(self.e_encr_dict[which])\r\n print(np.linalg.norm(e0 - e_)) # OK\r\n\r\n self.display('PROC_MASTER_END', verbose=False)\r\n\r\n # Computing eX\r\n self.eX_encr_dict = self.crypto_mult_X(self.e_encr_dict)\r\n\r\n # Computing gradients\r\n #self.grad_encr_dict = {}\r\n self.display('PROC_MASTER_START', verbose=False)\r\n\r\n grad_encr = self.encrypter.encrypt(np.zeros((self.NI + 1, 1)))\r\n Ntotal = 0\r\n for waddr in self.selected_workers:\r\n eX_encr = self.eX_encr_dict[waddr]\r\n Ntotal += eX_encr.shape[0]\r\n grad_encr += np.mean(eX_encr, axis=0).reshape((-1, 1))\r\n\r\n if check:\r\n grad0 = np.mean(e0 * X0, axis=0).reshape((-1, 1))\r\n grad0_decr = self.decrypter.decrypt(np.mean(self.eX_encr_dict[which], axis=0).reshape((-1, 1)))\r\n print(np.linalg.norm(grad0 - grad0_decr)) # OK\r\n\r\n #self.w_encr += self.mu * grad_encr / Ntotal\r\n grad_encr = self.mu * grad_encr / len(self.workers_addresses)\r\n\r\n # Moment update\r\n momentum_term = self.momentum * self.grad_old\r\n v_encr = momentum_term + grad_encr\r\n self.w_encr = self.w_encr - v_encr \r\n #self.w += self.mu * grad\r\n self.grad_old = np.copy(grad_encr)\r\n\r\n # Decrypting the model\r\n self.model_decr = self.decrypt_model({'w': self.w_encr})\r\n #self.w = self.decrypter.decrypt(self.w_encr)\r\n self.w = np.copy(self.model_decr['w'])\r\n\r\n if check:\r\n w_ok = self.decrypter.decrypt(self.w_encr) ### this is not allowed\r\n w_mal = self.model_decr['w']\r\n print(np.linalg.norm(w_ok - w_mal)) # Not OK\r\n\r\n #self.w_encr = self.encrypter.encrypt(self.w) \r\n \r\n # stopping\r\n inc_w = np.linalg.norm(self.w - self.w_old) / np.linalg.norm(self.w_old)\r\n # Stop if convergence is reached\r\n if inc_w < 0.005:\r\n self.stop_training = True\r\n if kiter == self.Nmaxiter:\r\n self.stop_training = True\r\n \r\n message = 'Maxiter = %d, iter = %d, inc_w = %f' % (self.Nmaxiter, kiter, inc_w)\r\n #self.display(message, True)\r\n print(message)\r\n kiter += 1\r\n self.w_old = self.w.copy()\r\n self.display('PROC_MASTER_END', verbose=False)\r\n self.display('MASTER_ITER_END', verbose=False)\r\n\r\n self.model.w = self.w\r\n self.model.niter = kiter\r\n self.model.is_trained = True\r\n self.display(self.name + ': Training is done', True)\r\n self.display('MASTER_FINISH', verbose=False)\r\n\r\n\r\n def Update_State_Master(self):\r\n \"\"\"\r\n We update control the flow given some conditions and parameters\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n if self.chekAllStates('ACK_grads'):\r\n self.FSMmaster.done_send_w_encr(self)\r\n\r\n def ProcessReceivedPacket_Master(self, packet, sender):\r\n \"\"\"\r\n Process the received packet at Master and take some actions, possibly changing the state\r\n\r\n Parameters\r\n ----------\r\n packet: packet object\r\n packet received (usually a dict with various content)\r\n\r\n sender: string\r\n id of the sender\r\n \"\"\"\r\n try:\r\n #sender = packet['sender']\r\n if packet['action'][0:3] == 'ACK':\r\n self.state_dict[sender] = packet['action']\r\n\r\n if sender == self.cryptonode_address: \r\n if packet['action'] not in ['ACK_send_ping']:\r\n\r\n try:\r\n self.display('COMMS_MASTER_RECEIVED %s from %s, id=%s' % (packet['action'], 'ca', str(packet['message_id'])), verbose=False)\r\n except:\r\n self.display('MASTER MISSING message_id in %s from %s' % (packet['action'], 'ca'), verbose=False) \r\n pass\r\n else:\r\n if packet['action'] not in ['ACK_send_ping']: \r\n try:\r\n self.display('COMMS_MASTER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False)\r\n except:\r\n self.display('MASTER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) \r\n pass\r\n\r\n\r\n if packet['action'] == 'ACK_grads':\r\n self.grads_dict.update({sender: packet['data']['grad_encr']})\r\n\r\n if packet['action'] == 'ACK_sent_XB_bl_encr_dict':\r\n self.XB_bl_encr_dict = packet['data']['XB_bl_encr_dict']\r\n self.FSMmaster.done_mult_XB(self)\r\n\r\n if packet['action'] == 'ACK_sent_decr_bl_model':\r\n self.model_decr_bl = packet['data']['model_decr_bl']\r\n self.FSMmaster.done_decrypt_model(self)\r\n\r\n except Exception as err:\r\n raise\r\n '''\r\n print('ERROR AT ProcessReceivedPacket_Master')\r\n raise\r\n import code\r\n code.interact(local=locals())\r\n ''' \r\n\r\n return\r\n\r\n\r\n#===============================================================\r\n# Worker\r\n#===============================================================\r\nclass LR_Worker(Common_to_all_POMs):\r\n '''\r\n Class implementing Linear Regression, run at Worker\r\n\r\n '''\r\n\r\n def __init__(self, master_address, worker_address, model_type, comms, logger, verbose=True, Xtr_b=None, ytr=None, cryptonode_address=None):\r\n \"\"\"\r\n Create a :class:`LR_Worker` instance.\r\n\r\n Parameters\r\n ----------\r\n master_address: string\r\n address of the master node\r\n\r\n worker_address: string\r\n id of this worker\r\n\r\n model_type: string\r\n type of ML model\r\n\r\n comms: comms object instance\r\n object providing communications\r\n\r\n logger: class:`logging.Logger`\r\n logging object instance\r\n\r\n verbose: boolean\r\n indicates if messages are print or not on screen\r\n\r\n Xtr_b: ndarray\r\n 2-D numpy array containing the input training patterns\r\n\r\n ytr: ndarray\r\n 1-D numpy array containing the target training values\r\n \"\"\"\r\n self.pom = 4\r\n self.master_address = master_address\r\n self.worker_address = worker_address # The id of this Worker\r\n self.cryptonode_address = cryptonode_address\r\n #self.workers_addresses = workers_addresses # The id of this Worker\r\n self.model_type = model_type\r\n self.comms = comms # The comms library\r\n self.logger = logger # logger\r\n self.name = model_type + '_Worker' # Name\r\n self.verbose = verbose # print on screen when true\r\n self.Xtr_b = Xtr_b\r\n #self.Xtr_b = self.add_bias(Xtr_b)\r\n self.ytr = ytr\r\n self.NPtr = len(ytr)\r\n self.create_FSM_worker()\r\n self.message_id = 0 # used to number the messages\r\n self.message_counter = 100 # used to number the messages\r\n t = time.time()\r\n seed = int((t - int(t)) * 10000)\r\n np.random.seed(seed=seed)\r\n\r\n def create_FSM_worker(self):\r\n \"\"\"\r\n Creates a Finite State Machine to be run at the Worker Node\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n self.name = 'FSM_worker'\r\n\r\n self.display(self.name + ' %s: creating FSM' % (str(self.worker_address)))\r\n\r\n class FSM_worker(object):\r\n\r\n name = 'FSM_worker'\r\n\r\n def while_waiting_order(self, MLmodel):\r\n MLmodel.display(self.name + ' %s: WAITING for instructions...' % (str(MLmodel.worker_address)))\r\n return\r\n\r\n def while_compute_gradients(self, MLmodel, packet):\r\n try:\r\n MLmodel.display(MLmodel.name + ' %s: computing gradients...' % (str(MLmodel.worker_address)))\r\n MLmodel.display('PROC_WORKER_START', verbose=False)\r\n w_encr = packet['data']['w_encr']\r\n \r\n #NW = wq_encr.shape[0]\r\n #for kw in range(NW):\r\n # wq_encr[kw, 0].encrypter = MLmodel.cr.encrypter\r\n \r\n #wq_encr = MLmodel.undill_it(packet['data']['wq_encr'])\r\n\r\n X = MLmodel.Xtr_b\r\n NP = X.shape[0]\r\n NI = X.shape[1]\r\n y = MLmodel.ytr.reshape(NP, 1)\r\n\r\n o_encr = np.dot(X, w_encr)\r\n e_encr = y - o_encr\r\n #Xeq_encr = MLmodel.cr.vmult(X / NP, eq_encr) # Normalized error by NP\r\n Xe_encr = X * e_encr\r\n grad_encr = np.sum(Xe_encr, axis=0).reshape((NI, 1)) / NP\r\n\r\n MLmodel.display('PROC_WORKER_END', verbose=False)\r\n\r\n action = 'ACK_grads'\r\n data = {'grad_encr': grad_encr}\r\n packet = {'action': action, 'sender': MLmodel.worker_address, 'data': data, 'to': 'MLmodel'}\r\n \r\n message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter)\r\n packet.update({'message_id': message_id})\r\n MLmodel.message_counter += 1\r\n size_bytes = asizeof.asizeof(dill.dumps(packet))\r\n MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False)\r\n\r\n MLmodel.comms.send(packet, MLmodel.master_address)\r\n MLmodel.display(MLmodel.name + ' %s: sent ACK_grads' % (str(MLmodel.worker_address)))\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT while_compute_gradients')\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n return\r\n\r\n states_worker = [\r\n State(name='waiting_order', on_enter=['while_waiting_order'])\r\n ]\r\n\r\n transitions_worker = [\r\n ]\r\n\r\n self.FSMworker = FSM_worker()\r\n self.grafmachine_worker = GraphMachine(model=self.FSMworker,\r\n states=states_worker,\r\n transitions=transitions_worker,\r\n initial='waiting_order',\r\n show_auto_transitions=False, # default value is False\r\n title=\"Finite State Machine modelling the behaviour of worker No. %s\" % str(self.worker_address),\r\n show_conditions=False)\r\n return\r\n\r\n\r\n def ProcessReceivedPacket_Worker(self, packet, sender):\r\n \"\"\"\r\n Take an action after receiving a packet\r\n\r\n Parameters\r\n ----------\r\n packet: packet object \r\n packet received (usually a dict with various content)\r\n\r\n sender: string\r\n id of the sender\r\n\r\n \"\"\"\r\n self.terminate = False\r\n try:\r\n self.display('COMMS_WORKER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False)\r\n except:\r\n self.display('WORKER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) \r\n pass\r\n try:\r\n # Exit the process\r\n if packet['action'] == 'STOP':\r\n self.display(self.name + ' %s: terminated by Master' % (str(self.worker_address)))\r\n self.terminate = True\r\n\r\n if packet['action'] == 'ACK_sent_encrypter':\r\n print('ProcessReceivedPacket_Worker ACK_sent_encrypter')\r\n #self.FSMworker.go_storing_Pk(self, packet)\r\n #self.FSMworker.done_storing_Pk(self)\r\n\r\n if packet['action'] == 'send_w_encr':\r\n self.FSMworker.go_compute_gradients(self, packet)\r\n self.FSMworker.done_compute_gradients(self)\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT ProcessReceivedPacket_Worker')\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n\r\n return self.terminate\r\n\r\n\r\n\r\n#===============================================================\r\n# Crypto\r\n#===============================================================\r\nclass LR_Crypto(Common_to_all_POMs):\r\n '''\r\n Class implementing Linear Regression, run at Crypto\r\n\r\n '''\r\n\r\n def __init__(self, cryptonode_address, master_address, model_type, comms, logger, verbose=True):\r\n \"\"\"\r\n Create a :class:`LR_Crypto` instance.\r\n\r\n Parameters\r\n ----------\r\n master_address: string\r\n address of the master node\r\n\r\n worker_address: string\r\n id of this worker\r\n\r\n model_type: string\r\n type of ML model\r\n\r\n comms: comms object instance\r\n object providing communications\r\n\r\n logger: class:`logging.Logger`\r\n logging object instance\r\n\r\n verbose: boolean\r\n indicates if messages are print or not on screen\r\n\r\n \"\"\"\r\n self.pom = 4\r\n self.master_address = master_address\r\n self.cryptonode_address = cryptonode_address\r\n #self.workers_addresses = workers_addresses # The id of this Worker\r\n self.model_type = model_type\r\n self.comms = comms # The comms library\r\n self.logger = logger # logger\r\n self.name = model_type + '_Cryptor' # Name\r\n self.verbose = verbose # print on screen when true\r\n self.create_FSM_crypto()\r\n self.message_id = 0 # used to number the messages\r\n self.message_counter = 100 # used to number the messages\r\n t = time.time()\r\n seed = int((t - int(t)) * 10000)\r\n np.random.seed(seed=seed)\r\n\r\n def create_FSM_crypto(self):\r\n \"\"\"\r\n Creates a Finite State Machine to be run at the Worker Node\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n self.name = 'FSM_crypto'\r\n\r\n self.display(self.name + ': creating FSM')\r\n\r\n class FSM_crypto(object):\r\n\r\n name = 'FSM_crypto'\r\n\r\n def while_waiting_order(self, MLmodel):\r\n MLmodel.display(self.name + ' %s: WAITING for instructions...' % (str(MLmodel.worker_address)))\r\n return\r\n\r\n states_crypto = [\r\n State(name='waiting_order', on_enter=['while_waiting_order'])\r\n ]\r\n\r\n transitions_crypto = []\r\n\r\n self.FSMcrypto = FSM_crypto()\r\n self.grafmachine_crypto = GraphMachine(model=self.FSMcrypto,\r\n states=states_crypto,\r\n transitions=transitions_crypto,\r\n initial='waiting_order',\r\n show_auto_transitions=False, # default value is False\r\n title=\"Finite State Machine modelling the behaviour of crypto\",\r\n show_conditions=False)\r\n return\r\n\r\n\r\n def ProcessReceivedPacket_Crypto(self, packet, sender):\r\n \"\"\"\r\n Take an action after receiving a packet\r\n\r\n Parameters\r\n ----------\r\n packet: packet object \r\n packet received (usually a dict with various content)\r\n\r\n sender: string\r\n id of the sender\r\n\r\n \"\"\"\r\n self.terminate = False\r\n try:\r\n self.display('COMMS_CRYPTO_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False)\r\n except:\r\n self.display('CRYPTO MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) \r\n pass\r\n try:\r\n # Exit the process\r\n if packet['action'] == 'STOP':\r\n self.display(self.name + ' %s: terminated by Master' % (str(self.worker_address)))\r\n self.terminate = True\r\n\r\n if packet['action'] == 'send_Pk':\r\n self.FSMworker.go_storing_Pk(self, packet)\r\n self.FSMworker.done_storing_Pk(self)\r\n\r\n if packet['action'] == 'send_w_encr':\r\n self.FSMworker.go_compute_gradients(self, packet)\r\n self.FSMworker.done_compute_gradients(self)\r\n except:\r\n raise\r\n '''\r\n print('ERROR AT ProcessReceivedPacket_Crypto')\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n\r\n return self.terminate\r\n","sub_path":"MMLL/models/POM4/LR/LR.py","file_name":"LR.py","file_ext":"py","file_size_in_byte":39934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"648603542","text":"#librairies\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import *\nfrom Physical_constants import *\nfrom Conversion_factor import *\n\n#function to integrate a function in log-log scale\ndef integration_log(x, y):\n\n #Looking for a and b for y = a*x^b\n def calculate_ab(xi, xf, yi, yf):\n logxi = np.log(xi)\n logxf = np.log(xf)\n logyi = np.log(yi)\n logyf = np.log(yf)\n b = (logyf - logyi)/(logxf - logxi)\n loga = logyi - b*logxi\n a = np.exp(loga)\n a = np.nan_to_num(a)\n return a, b\n\n #Calculate deltaS from deltaS = int from xi to xf a*x^b\n def delta_S(xi, xf, yi, yf):\n [a, b] = calculate_ab(xi, xf, yi, yf)\n return a/(b+1)*(xf**(b+1) - xi**(b+1))\n\n integral = 0\n\n # Because the function integral_log works only if there is more than two elements not zero\n idx=(y > 0.0)\n #idy=(y < 0.0)\n idt = idx #+ idy\n if sum(idt) > 2:\n\n x = x[idt]\n y = y[idt]\n\n #Calculate total integral from init to final a*x^b\n deltaS = 0\n\n for i in range (1, len(x)):\n deltaS = delta_S(x[i-1], x[i], y[i-1], y[i])\n integral = integral + deltaS\n\n integral = np.nan_to_num(integral)\n\n return integral\n\n# for WD : compute z_WD, b_WD\ndef compute_WD(psi_gamma, psi_o, phi_gamma, phi_o, r_gamma, theta_max_WD):\n\n \"\"\"\n Return z_RG and b_RG\n\n Parameters :\n psi_gamma : colatitude of the gamma-source (rad)\n psi_o : colatitude of the observator (rad)\n phi_gamma : polar angle of the gamma-source (rad)\n phi_o : polar angle of the observator (rad)\n r_gamma : distance to the gamma-source (cm)\n \"\"\"\n\n condition = False\n gamma_WD = np.arccos(-(np.sin(psi_gamma)*np.sin(psi_o)*np.cos(phi_gamma)*np.cos(phi_o) + np.sin(psi_gamma)*np.sin(psi_o)*np.sin(phi_gamma)*np.sin(phi_o) + np.cos(psi_gamma)*np.cos(psi_o)))\n\n b_WD = r_gamma * np.sin(gamma_WD)\n\n if gamma_WD <= np.pi/2:\n\n z_WD = np.sqrt(r_gamma**2 - b_WD**2)\n\n else:\n\n z_WD = - np.sqrt(r_gamma**2 - b_WD**2)\n\n if gamma_WD <= theta_max_WD: # if there is an eclispe\n\n condition = True\n\n return b_WD, z_WD, condition\n\n# for WD : compute z_RG, b_RG\ndef compute_RG(psi_gamma, psi_o, phi_gamma, phi_o, r_gamma, d_orb, theta_max_RG):\n\n \"\"\"\n Return z_RG and b_RG\n\n Parameters :\n psi_gamma : colatitude of the gamma-source (rad)\n psi_o : colatitude of the observator (rad)\n phi_gamma : polar angle of the gamma-source (rad)\n phi_o : polar angle of the observator (rad)\n r_gamma : distance to the gamma-source (cm)\n d_orb : orbital separation (cm)\n \"\"\"\n\n condition = False\n\n gamma_RG = np.arccos((d_orb*np.sin(psi_o)*np.cos(phi_o) - r_gamma * (np.sin(psi_gamma)*np.sin(psi_o)*np.cos(phi_gamma)*np.cos(phi_o) + np.sin(psi_gamma)*np.sin(psi_o)*np.sin(phi_gamma)*np.sin(phi_o) + np.cos(psi_gamma)*np.cos(psi_o)))/(np.sqrt(d_orb**2 - 2*r_gamma*d_orb*np.sin(psi_gamma)*np.cos(phi_gamma) + r_gamma**2)))\n\n b_RG = sqrt(d_orb**2 - 2*r_gamma*d_orb*np.sin(psi_gamma)*np.sin(phi_gamma) + r_gamma**2) * np.sin(gamma_RG)\n\n if gamma_RG <= np.pi/2:\n\n z_RG = np.sqrt(d_orb**2 - 2*r_gamma*d_orb*np.sin(psi_gamma)*np.sin(phi_gamma) + r_gamma**2- b_RG**2)\n\n else:\n\n z_RG = - np.sqrt(r_gamma**2 - b_RG**2)\n\n if gamma_RG <= theta_max_RG: # if there is an eclipse\n\n condition = True\n\n return b_RG, z_RG, condition\n\ndef distance(zb, z, b):\n\n \"\"\"\n Return for each position z along the line of sight the distance between this position and the centre of the star (cm)\n\n Parameters:\n zb : position on the line of sight closely the star (cm)\n z : position along the line of sight (cm)\n b : impact parameter\n \"\"\"\n\n return np.sqrt((zb - z)**2 + b**2)\n\ndef angle_alpha(b, D, z, zb, theta, phi):\n\n \"\"\"\n Return the cosinus of the angle (alpha) between the two momenta of the two photons in the observer's frame\n\n Parameters :\n b : impact parameter (cm)\n D : distance to the star from each position along the line of sight (cm)\n z : position along the line of sight (cm)\n zb : position along the line of sight nearly the star (cm)\n theta : angle formed by the ray (from the star) and the straight line connecting the centre of the star and a position z on the line of sight (rad)\n careful theta = 0 when the ray 'comes' from the centre of the star and theta = theta_max when the ray is tangent to the sphere\n phi : angle around the direction between the centre of the star and the position along the line of sight (rad)\n \"\"\"\n\n #Return the cosinus of the angle formed by the direction between the centre of the star and the position along the line of sight, and the line of sight (rad)\n def angle_beta(b, D, z, zb):\n\n if z <= zb:\n beta = np.arcsin(b/D)\n\n else:\n beta = np.pi - np.arcsin(b/D)\n\n return beta\n\n beta = angle_beta(b, D, z, zb)\n\n return - np.sin(beta) * np.sin(theta) * np.sin(phi) - np.cos(beta) * np.cos(theta)\n\ndef density_n(eps, T, theta):\n\n \"\"\"\n Density of the photons is not isotropic : dn = Bnu * cos(theta)/(c * h**2 *nu)\n\n Parameters:\n eps : energy of the target-photon (keV)\n theta : angle formed by the ray (from the star) and the line connecting the centre of the star and a position z on the line of sight (rad)\n T : temperature of the star (K)\n \"\"\"\n\n nu = eps/hp\n\n def planck(nu, T):\n\n return (2*hp*(nu**3))/(cl**2) * 1/(np.exp((hp*nu)/(kb*T)) - 1)\n\n Bnu = planck(nu, T)\n\n return Bnu/(cl * hp**2 * nu) * np.cos(theta) #return dn in cm^3/sr/erg\n\n\ndef f(theta, phi, eps, z, D, b, R, E, T, zb):\n\n \"\"\"\n Return the function for the integration in phi : f = dn * sigma * (1 - cos(alpha)) * sin(theta)\n where dn is the density of photons, sigma is the dimensionless cross section of the interaction,\n alpha is the between the two momenta of the two photons in the observer's frame\n\n Parameters:\n theta : angle formed by the ray (from the star) and the straight line connecting the centre of the star and a position z on the line of sight (rad)\n phi : angle around the direction between the centre of the star and the position along the line of sight (rad)\n eps : energy of the target-photon (keV)\n z : position along the line of sight (cm)\n L : the distance to the gamma-source (cm)\n b : impact parameter (cm)\n E : energy of the gamma-photon (keV)\n T : temperature of the star (K)\n zb : position along the line of sight nearly the star (cm)\n \"\"\"\n\n cos_alpha = angle_alpha(b, D, z, zb, theta, phi)\n epsc = np.sqrt(eps * E/2 * (1 - cos_alpha))/(mc2/ergkev) # epsc/mc2 in erg\n\n #First : sigma (dimensionless)\n def cross_section(epsc):\n\n def parameter_s(epsc):\n\n return epsc**2\n\n def parameter_beta(epsc):\n\n s = parameter_s(epsc)\n return np.sqrt(1 - 1/s)\n\n beta = parameter_beta(epsc)\n beta = np.nan_to_num(beta)\n\n return (1 - beta**2) * ((3 - beta**4) * np.log((1 + beta)/(1 - beta)) - 2 * beta * (2 - beta**2))\n\n dn = density_n(eps, T, theta)\n sigma = cross_section(epsc)\n\n return dn * sigma * (1 - cos_alpha) * np.sin(theta)\n\ndef calculate_tau(E, z, phi, L, b, R, T, zb, condition):\n\n \"\"\"\n Return tau(E) for all E\n Parameters :\n E : energy of the gamma-photon (erg)\n z : position along the line of sight (cm)\n phi : angle around the direction between the centre of the star and the position along the line of sight (rad)\n zb : position along the line of sight nearly the star (cm)\n L : maximum distance for the integration about z (cm)\n b : impact parameter (cm)\n R : radius of the secundary source (cm)\n T : temperature of the secundary source (cm)\n \"\"\"\n\n integral = np.zeros_like(E)\n number_bin_eps = 20.0\n\n for i in range(len(E)): # integration over z\n\n integral_eps = np.zeros_like(z)\n\n # Energy of the target-photon (erg)\n epsmin = (mc2/ergkev)**2/E[i]\n epsmax = 10*kb*T\n\n # Because epsmin must be lower than epsmax\n if epsmin > epsmax:\n continue\n else:\n eps = np.logspace(log10(epsmin), log10(epsmax), int(log10(epsmax/epsmin)*number_bin_eps))\n print(i)\n\n for j in range (len(z)): # integration over eps\n\n integral_theta = np.zeros_like(eps)\n D = distance(zb, z[j], b)\n theta_max = np.arcsin(R/D)\n theta = np.linspace(0, theta_max, 10)\n\n for l in range (len(eps)): # integration over theta\n\n integral_phi = np.zeros_like(theta)\n\n for m in range (len(theta)): # integration over phi\n\n integrand = f(theta[m], phi, eps[l], z[j], D, b, R, E[i], T, zb)\n integrand = np.nan_to_num(integrand)\n\n integral_phi[m] = integration_log(phi, integrand)\n\n integral_theta[l] = integration_log(theta, integral_phi)\n\n integral_eps[j] = integration_log(eps, integral_theta) #you get d(tau)/dx\n\n integral[i] = integration_log(z, integral_eps)\n\n tau = 1/2.0 * np.pi * r0**2 * integral\n transmittance = np.exp(-tau)\n\n return transmittance\n\ndef calculate_tau_L(E, z, phi, L, b, R, T, zb):\n\n \"\"\"\n Return tau(E) for all E\n Parameters :\n E : energy of the gamma-photon (erg)\n z : position along the line of sight (cm)\n phi : angle around the direction between the centre of the star and the position along the line of sight (rad)\n zb : position along the line of sight nearly the star (cm)\n L : maximum distance for the integration about z (cm)\n b : impact parameter (cm)\n R : radius of the secundary source (cm)\n T : temperature of the secundary source (cm)\n \"\"\"\n\n integral = np.zeros_like(E)\n number_bin_eps = 20.0\n #step_theta = 0.01\n\n # integration over z\n\n integral_eps = np.zeros_like(z)\n\n # Energy of the target-photon (erg)\n epsmin = (mc2/ergkev)**2/E\n epsmax = 10*kb*T\n\n eps = np.logspace(log10(epsmin), log10(epsmax), int(log10(epsmax/epsmin)*number_bin_eps))\n\n for j in range (len(z)): # integration over eps\n\n integral_theta = np.zeros_like(eps)\n D = distance(zb, z[j], b)\n theta_max = np.arcsin(R/D)\n theta = np.linspace(0, theta_max, 10)\n\n for l in range (len(eps)): # integration over theta\n\n integral_phi = np.zeros_like(theta)\n\n for m in range (len(theta)): # integration over phi\n\n integrand = f(theta[m], phi, eps[l], z[j], D, b, R, E, T, zb)\n integrand = np.nan_to_num(integrand)\n\n integral_phi[m] = integration_log(phi, integrand)\n\n integral_theta[l] = integration_log(theta, integral_phi)\n\n integral_eps[j] = integration_log(eps, integral_theta) #you get d(tau)/dx\n\n integral = integration_log(z, integral_eps)\n\n return 1/2.0 * np.pi * r0**2 * integral\n","sub_path":"Codes/Vieux/Functionsbis.py","file_name":"Functionsbis.py","file_ext":"py","file_size_in_byte":11517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"18432132","text":"# _*_coding:utf-8_*_\n__author__ = 'Alex Li'\nimport pika,time\n\ncredentials = pika.PlainCredentials(\"alex\",\"alex3714\")\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\n '192.168.0.90',credentials=credentials))\nchannel = connection.channel()\n\n\ndef callback(ch, method, properties, body):\n #print(ch, method, properties, body)\n print(\" [x] Received %r\" % body)\n time.sleep(10)\n print(\" [x] Done\")\n print(\"method.delivery_tag\", method.delivery_tag)\n ch.basic_ack(delivery_tag=method.delivery_tag) #确认消息收到\n\n\nchannel.basic_qos(prefetch_count=1) #类似权重,按能力分发,如果有一个消息,就不在给你发\n\nchannel.basic_consume(callback,\n queue='task_queue2',\n # no_ack=True 默认是消息持久化开启后,会丢失\n )\n\nprint(' [*] Waiting for messages. To exit press CTRL+C')\nchannel.start_consuming()","sub_path":"82天内容/rabbit_receive_worker.py","file_name":"rabbit_receive_worker.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"201339132","text":"# Copyright 2017 Rice University\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 tensorflow as tf\n\nclass biRNN(object):\n def __init__(self, num_layers, state_size, inputs, batch_size, emb, output_units):\n\n with tf.variable_scope('GRU_Encoder'):\n cell_list_fwd, cell_list_back = [],[]\n for i in range(num_layers) :\n cell_fwd = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(state_size ) #both default behaviors\n cell_list_fwd.append(cell_fwd)\n cell_back = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(state_size ) #both default behaviors\n cell_list_back.append(cell_back)\n\n multi_cell_fwd = tf.contrib.rnn.MultiRNNCell(cell_list_fwd)\n multi_cell_back = tf.contrib.rnn.MultiRNNCell(cell_list_back)\n\n # inputs is BS * depth\n inputs_fwd = tf.unstack(inputs, axis=1)\n # after unstack it is depth * BS\n inputs_back = inputs_fwd[::-1]\n\n curr_state_fwd = [tf.truncated_normal([batch_size, state_size] , stddev=0.001 ) ] * num_layers\n curr_state_back = [tf.truncated_normal([batch_size, state_size] , stddev=0.001 ) ] * num_layers\n\n curr_out_fwd = tf.zeros([batch_size , state_size])\n curr_out_back = tf.zeros([batch_size , state_size])\n\n for i, inp in enumerate(zip(inputs_fwd, inputs_back)):\n #if i > 0:\n # tf.get_variable_scope().reuse_variables()\n\n inp_fwd, inp_back = inp\n emb_inp_fwd = tf.nn.embedding_lookup(emb, inp_fwd)\n emb_inp_back = tf.nn.embedding_lookup(emb, inp_back)\n\n with tf.variable_scope(\"forward\", reuse=tf.AUTO_REUSE):\n output_fwd, out_state_fwd = multi_cell_fwd(emb_inp_fwd, curr_state_fwd)\n with tf.variable_scope(\"backward\", reuse=tf.AUTO_REUSE):\n output_back, out_state_back = multi_cell_back(emb_inp_back, curr_state_back)\n\n curr_state_fwd = [tf.where(tf.not_equal(inp_fwd, 0), out_state_fwd[j], curr_state_fwd[j])\n for j in range(num_layers)]\n\n curr_state_back = [tf.where(tf.not_equal(inp_back, 0), out_state_back[j], curr_state_back[j])\n for j in range(num_layers)]\n\n curr_out_fwd = tf.where(tf.not_equal(inp_fwd, 0), output_fwd, curr_out_fwd)\n curr_out_back = tf.where(tf.not_equal(inp_back, 0), output_back, curr_out_back)\n\n\n temp_out = tf.concat([curr_out_fwd, curr_out_back], axis=1)\n with tf.variable_scope(tf.get_variable_scope(), reuse=False):\n curr_out = tf.layers.dense(temp_out, output_units, activation=tf.nn.tanh)\n\n #\n # with tf.variable_scope(\"projections\"):\n # projection_w = tf.get_variable('projection_w', [state_size, output_units])\n # projection_b = tf.get_variable('projection_b', [output_units])\n\n self.output = curr_out #tf.nn.xw_plus_b(curr_out, projection_w, projection_b)\n","sub_path":"src/main/python/bayou/models/low_level_evidences/biRNN.py","file_name":"biRNN.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"211560445","text":"import random\nimport time\n\nfrom . import constants\n\n\nclass Car:\n\n def __init__(self, automaton, x, y, direction, index=0, turn=None, left_turn=None, transmitted=None):\n self.index = index\n self.__automaton = automaton\n self.__x = x\n self.__y = y\n self.__direction = direction\n self.__turn = turn\n self.__color = random.sample([\"#0066FF\", \"#FFAA00\", \"#663300\",\n \"#669900\", \"#805080\"]\n , 1)[0]\n if left_turn:\n self.__left_turn = True\n else:\n self.__left_turn = False\n if transmitted is None:\n self.generate_turn()\n\n def generate_turn(self):\n probability = random.random() # uniform between 0 - 1\n if probability <= 0.1:\n self.__turn = constants.Turn.RIGHT[self.__direction]\n self.__left_turn = False\n return\n if probability <= 0.3:\n self.__turn = constants.Turn.LEFT[self.__direction]\n self.__left_turn = True\n return\n self.__turn = self.__direction\n self.__left_turn = False\n\n def update(self, x, y):\n self.__x = x\n self.__y = y\n return x, y\n\n @staticmethod\n def shape():\n return \"oval\"\n\n def move(self):\n time.sleep(constants.UNIT)\n cell = self.__automaton.get_state()[self.__x][self.__y]\n cells = self.__automaton.get_state()\n\n # First off we need to see if we need to stop because of the traffic\n # light.\n if cell.traffic_light and not cell.traffic_light.is_green():\n return self.__x, self.__y\n\n # Then we see if we can make the turn\n if self.__turn in cell.next:\n turn_x, turn_y = cell.next[self.__turn]\n if self.__automaton.valid_coords(turn_x, turn_y) and \\\n cells[turn_x][turn_y].empty():\n can_turn = True\n # We need to treat the case when we make a left turn because we\n # need to look for a car coming from the opposite direction.\n if self.__left_turn:\n # The cell that we need to look for is ahead of the turn\n # cell\n turn_cell = cells[turn_x][turn_y]\n if self.__direction not in turn_cell.previous:\n can_turn = False\n else:\n yield_x, yield_y = turn_cell.previous[\n self.__direction]\n yield_cell = cells[yield_x][yield_y]\n if not yield_cell.empty() and \\\n yield_cell.traffic_light.is_green():\n can_turn = False\n if can_turn:\n self.__direction = self.__turn\n self.generate_turn()\n return self.update(turn_x, turn_y)\n else:\n return self.__x, self.__y\n\n next_x, next_y = cell.next[self.__direction]\n if not self.__automaton.valid_coords(next_x, next_y):\n return None, None\n\n if cells[next_x][next_y].empty():\n return self.update(next_x, next_y)\n return self.__x, self.__y\n\n def get_coords(self):\n return self.__x, self.__y\n\n def get_direction(self):\n return self.__direction\n\n def get_turn(self):\n return self.__turn\n\n def get_left_turn(self):\n return self.__left_turn\n\n def set_automaton(self, automaton):\n self.__automaton = automaton\n\n @staticmethod\n def symbol():\n return \"#\"\n\n def color(self):\n return self.__color\n","sub_path":"traffic/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134325061","text":"import numpy\n\nimport scipy.stats\nimport scipy.optimize\n\nhave_sklearn = False\n# noinspection PyBroadException\ntry:\n import sklearn.linear_model\n\n have_sklearn = True\nexcept Exception:\n pass\n\n\n# methods to avoid calling statsmodels which seems to be incompatible with many\n# versions of other packages we need:\n# https://github.com/WinVector/pyvtreat/issues/14\n\n\ndef our_corr_score(*, y_true, y_pred):\n # compute Pearson correlation\n if not isinstance(y_true, numpy.ndarray):\n y_true = numpy.asarray(y_true)\n if not isinstance(y_pred, numpy.ndarray):\n y_pred = numpy.asarray(y_pred)\n n = len(y_true)\n if n < 2:\n return 1, 1\n if numpy.min(y_true) >= numpy.max(y_true):\n return 1, 1\n if numpy.min(y_pred) >= numpy.max(y_pred):\n return 0, 1\n r, sig = scipy.stats.pearsonr(y_true, y_pred)\n if n < 3:\n sig = 1\n return r, sig\n\n\ndef est_deviance(*, y, est, epsilon=1.0e-5):\n if not isinstance(y, numpy.ndarray):\n y = numpy.asarray(y)\n if not isinstance(est, numpy.ndarray):\n x = numpy.asarray(est)\n est = numpy.minimum(est, 1 - epsilon)\n est = numpy.maximum(est, epsilon)\n deviance = -2 * numpy.sum(\n y * numpy.log(est) +\n (1 - y) * numpy.log(1 - est))\n return deviance\n\n\n# assumes special cases of solve_logistic_regression already eliminated\ndef brute_force_solve_logistic(*, y, x, regularization=1.e-6):\n if not isinstance(y, numpy.ndarray):\n y = numpy.asarray(y)\n if not isinstance(x, numpy.ndarray):\n x = numpy.asarray(x)\n\n def predict(beta):\n return 1 / (1 + numpy.exp(-(beta[0] + beta[1] * x)))\n\n def loss(beta):\n preds = predict(beta)\n return (est_deviance(y=y, est=preds)\n + regularization * (beta[0] * beta[0] + beta[1] * beta[1]) # regularization\n )\n\n soln = scipy.optimize.fmin_bfgs(\n loss,\n x0=[numpy.log(numpy.mean(y) / (1 - numpy.mean(y))), 0.001],\n gtol=1.0e-3,\n disp=0)\n return predict(soln)\n\n\n# assumes special cases of solve_logistic_regression already eliminated\ndef sklearn_solve_logistic(*, y, x, regularization=1.e-6):\n if not isinstance(y, numpy.ndarray):\n y = numpy.asarray(y)\n if not isinstance(x, numpy.ndarray):\n x = numpy.asarray(x)\n fitter = sklearn.linear_model.LogisticRegression(\n penalty='l2',\n solver='lbfgs',\n fit_intercept=True,\n C=1/regularization)\n dependent_vars = x.reshape((len(y), 1))\n fitter.fit(X=dependent_vars, y=y)\n preds = fitter.predict_proba(X=dependent_vars)[:, 1]\n return preds\n\n\n# x, y - numpy numeric vectors, y 0/1. solve for y- return predictions\ndef solve_logistic_regression(*, y, x):\n # catch some corner cases\n if not isinstance(y, numpy.ndarray):\n y = numpy.asarray(y)\n if not isinstance(x, numpy.ndarray):\n x = numpy.asarray(x)\n n = len(y)\n if (n < 2) or (numpy.min(y) >= numpy.max(y)):\n return y.copy()\n if numpy.min(x) >= numpy.max(x):\n return numpy.asarray([numpy.mean(y)] * n)\n # check for fully seperable cases\n big_y_indices = y > 0\n x_b = x[big_y_indices]\n x_s = x[numpy.logical_not(big_y_indices)]\n if (min(x_b) > max(x_s)) or (max(x_b) < min(x_s)):\n r = numpy.zeros(n)\n r[big_y_indices] = 1\n return r\n # run a full logistic regression\n if have_sklearn:\n preds = sklearn_solve_logistic(y=y, x=x)\n else:\n preds = brute_force_solve_logistic(y=y, x=x)\n return numpy.asarray(preds)\n\n\n# noinspection PyPep8Naming\ndef our_pseudo_R2(*, y_true, y_pred):\n if not isinstance(y_true, numpy.ndarray):\n y_true = numpy.asarray(y_true)\n if not isinstance(y_pred, numpy.ndarray):\n y_pred = numpy.asarray(y_pred)\n n = len(y_true)\n if n < 2:\n return 1, 1\n if numpy.min(y_true) >= numpy.max(y_true):\n return 1, 1\n if numpy.min(y_pred) >= numpy.max(y_pred):\n return 0, 1\n preds = solve_logistic_regression(y=y_true, x=y_pred)\n deviance = est_deviance(y=y_true, est=preds)\n null_deviance = est_deviance(y=y_true, est=numpy.zeros(n) + numpy.mean(y_true))\n r2 = 1 - deviance / null_deviance\n sig = 1\n if n >= 3:\n # https://github.com/WinVector/sigr/blob/master/R/ChiSqTest.R\n df_null = n - 1\n df_residual = n - 2\n delta_deviance = null_deviance - deviance\n delta_df = df_null - df_residual\n sig = 1 - scipy.stats.chi2.cdf(x=delta_deviance, df=delta_df)\n return r2, sig\n","sub_path":"pkg/build/lib/vtreat/stats_utils.py","file_name":"stats_utils.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"640043417","text":"# coding=utf-8\nfrom selenium_method import *\nfrom logger import *\nimport time\nfrom readConfig import get_config\nfrom selenium.webdriver.support.select import Select\n\n\nclass CommonMethod(WebDriver):\n tangwu_tag = '//*[@id=\"banner-section\"]/div/div/div[1]/div[2]/div/div/ul/li[3]/div/img[1]' # 首页汤屋图标‘\n hotel_tag='//*[@id=\"banner-section\"]/div/div/div[1]/div[2]/div/div/ul/li[2]/div/img[1]' #首页酒店图标‘\n ticket_tag = '//*[@id=\"banner-section\"]/div/div/div[1]/div[2]/div/div/ul/li[1]/div/img[2]' # 首页乐园门票图标\n select_tickit_button= '// * [ @ id = \"amusementForm\"] / div / div[1] / div / p' # 选择门票\n select_hotel_button= '// *[ @ id = \"hotelForm\"] / div / div[1] / div / p' # 选择酒店\n select_tangwu_button= '//*[@id=\"soupHouseForm\"]/div/div[1]/div/p' # 选择汤屋\n list_li_1= '//*[@id=\"amusementIndex\"]/li[1]' # 下拉列表中第一个元素\n list_li_10 = '//*[@id=\"amusementIndex\"]/li[10]' # 下拉列表中第10个元素\n logout_button = '//*[@id=\"logout\"]' # 退出按钮\n web_url = 'https://10.101.71.11:2655/zh-cn/'\n login_button = '登录' # 登录链接\n input_box='//*[@id=\"app\"]/div/div[1]/div/form/div[1]/input' # 账号输入框\n input_pwd_box = '//*[@id=\"app\"]/div/div[1]/div/form/div[2]/input[2]' # 密码输入框\n user_login_button='//*[@id=\"app\"]/div/ul/li[1]' # 账户登录\n login_button2 = '//*[@id=\"app\"]/div/div[1]/div/form/div[3]/button' # 登入按钮\n play_empty_icon='//*[@id=\"mainInfo\"]/div[2]/div[1]/div/div[3]/div/img' # 乐园无数据图标\n hotel_empty_icon='//*[@id=\"app\"]/div[2]/div[2]/ul/li/img' # 酒店无数据图标\n calender_icon='//*[@id=\"amusementDate\"]/div/img' #首页日历控件\n calender_icon1 ='// *[ @ id = \"hotelDate01\"] / div / img'\n calender_icon2 ='// *[ @ id = \"hotelDate02\"] / div / img'\n\n def open_web(self, url=web_url):\n # 登入官网门户网站\n self.openurl(url)\n self.click_new('//*[@id=\"details-button\"]')\n self.click_new('//*[@id=\"proceed-link\"]')\n self.element_should_contain('xpath', '//*[@id=\"amusementBook\"]', '预订')\n time.sleep(1)\n\n def booking_tickit(self, type=1):\n # 点击官网页面的预定按钮\n # 1=乐园 2=酒店 3=汤屋\n time.sleep(2)\n if type==1:\n self.click_new('//*[@id=\"amusementBook\"]')\n elif type==2:\n self.click_new('//*[@id=\"hotelBook\"]')\n else:\n self.click_new('//*[@id=\"soupHouseBook\"]')\n\n def click_new(self, els=None):\n # 重写click\n self.click('xpath', els)\n\n # def select_tickit(self, xpath=select_tickit_button):\n # # 点击下拉列表按钮\n # self.click_new(xpath)\n\n def select_tickit_type(self, type=1):\n # type=1 为门票 type=2 为酒店 type=3为汤屋\n if type==1:\n self.click_new(self.select_tickit_button)\n elif type==2:\n self.click_new(self.select_hotel_button)\n else:\n self.click_new(self.select_tangwu_button)\n\n\n def select_list_value(self, xpath=list_li_10):\n # 选择列表中某一个选项,如:恒大水世界测试\n self.click_new(xpath)\n\n # def click_play_label(self, xpath=ticket_tag):\n # # 点击首页的门票按钮\n # self.click_new(xpath)\n\n def click_icon_type(self, type=1):\n # 点击首页门票图标 1=乐园门票,2=酒店 , 3=汤屋\n if type==1:\n self.click_new(self.ticket_tag)\n elif type==2:\n self.click_new(self.hotel_tag)\n else:\n self.click_new(self.tangwu_tag)\n\n\n def click_hotel_tag(self, xpath=hotel_tag):\n # 点击首页的酒店按钮\n self.click_new(xpath)\n\n def select_down_list(self):\n nr = Select(self.driver.find_element_by_id(\"nr\"))\n select = Select(nr) #实例化下拉框\n select.select_by_value()\n\n def select_play_list(self, num=0):\n # 下拉列表选择乐园\n # 先定位到下拉菜单,,num=0默认点击第一条\n ul= self.driver.find_element_by_css_selector('#amusementIndex')\n time.sleep(5)\n li= ul.find_elements_by_tag_name('li')\n # 以下方法可以解决遮罩问题\n self.driver.execute_script(\"arguments[0].click();\", li[num])\n # 无遮罩可以使用下列方法\n # li[num].click()\n time.sleep(1)\n\n def select_hotel_list(self, num=0):\n # 下拉列表选择酒店\n # 先定位到下拉菜单,,num=0默认点击第一条\n ul= self.driver.find_element_by_css_selector('#hotelIndex')\n time.sleep(5)\n li= ul.find_elements_by_tag_name('li')\n # 以下方法可以解决遮罩问题\n self.driver.execute_script(\"arguments[0].click();\", li[num])\n time.sleep(1)\n\n def select_tangwu_list(self, num=0):\n # 下拉列表选择汤屋\n # 先定位到下拉菜单,,num=0默认点击第一条\n ul = self.driver.find_element_by_css_selector('#soupHouseIndex')\n time.sleep(5)\n li = ul.find_elements_by_tag_name('li')\n # 以下方法可以解决遮罩问题\n self.driver.execute_script(\"arguments[0].click();\", li[num])\n time.sleep(1)\n\n def enter_key(self):\n time.sleep(3)\n self.driver.find_element_by_xpath('//*[@id=\"amusementIndex\"]/li[1]').send_keys(Keys.ENTER)\n\n def slip_scroll(self, num=1000):\n js = 'document.getElementsByClassName(\"select-box icon-arrow-drop\").scrollTop=10000'\n # 就是这么简单,修改这个元素的scrollTop就可以\n self.driver.execute_script(js)\n time.sleep(10)\n\n def input_text(self, els=None, text=\"\"):\n self.input('xpath', els, text)\n\n def click_by_link_text(self, text=None):\n # 点击链接\n self.driver.find_element_by_link_text(text).click()\n\n def clear_new(self, cle=None):\n # 重写\n self.clear('xpath', cle)\n\n def get_user_info(self):\n username = get_config(\"userinfo\", \"user\")\n password = get_config(\"userinfo\", \"pwd\")\n return username, password\n\n def login_user(self):\n # 登入用户名\n username, password = self.get_user_info()\n self.click_by_link_text(self.login_button)\n # self.click_new(self.user_login_button)\n self.clear_new(self.input_box)\n self.input_text(self.input_box, username)\n self.clear_new(self.input_pwd_box)\n self.input_text(self.input_pwd_box, password)\n self.click_new(self.login_button2)\n time.sleep(3)\n self.scroll_to(0, 0)\n time.sleep(2)\n self.element_should_contain('xpath', self.logout_button, '退出')\n print(\"退出存在\")\n time.sleep(1)\n\n def logout_user(self):\n self.click_new(self.logout_button)\n time.sleep(1)\n self.element_should_not_contain('xpath', self.logout_button, '退出')\n\n def empty_icon_exist(self,type=1):\n # 检测是否当日无数据,emptyicon是否存在 1=乐园 2=为酒店或汤屋\n flag=True\n icon=self.play_empty_icon\n if type == 1:\n icon = self.play_empty_icon\n else:\n icon = self.hotel_empty_icon\n\n if self.element_should_contain2('xpath', icon):\n self.logger.info(\"当日无数据\")\n else:\n self.logger.error(\"当日有数据\")\n flag=False\n return flag\n\n def click_calender(self):\n # 首页酒店预订日历按钮\n self.click_new(self.calender_icon)\n\n def click_calendar1(self):\n # 首页酒店预订第一个日历按钮\n self.click_new(self.calender_icon1)\n time.sleep(1)\n\n def click_calendar2(self):\n # 首页酒店预订第二个日历按钮\n self.click_new(self.calender_icon2)\n time.sleep(1)\n\n def set_play_date(self, date=\"2021-4-24\"):\n # 设置乐园预订日期\n js1 = 'document.getElementById(\"inAmusementDate\").removeAttribute(\"readonly\");'\n # 调用js脚本\n self.driver.execute_script(js1)\n # 通过js修改日期输入框的value值\n js2 = 'document.getElementById(\"inAmusementDate\").value=\"%s\";' % date\n self.driver.execute_script(js2)\n time.sleep(2)\n\n def set_hotel_date(self, type = 1, date=\"2021-4-24\"):\n # type=1为开始日期,否则为结束日期,默认为1 ,设置酒店预订日期\n if type == 1:\n new_date_id = 'inHotelDate01'\n else:\n new_date_id = 'inHotelDate02'\n js1 = 'document.getElementById(new_date_id).removeAttribute(\"readonly\");'\n # 调用js脚本\n self.driver.execute_script(js1)\n # 通过js修改日期输入框的value值\n js2 = 'document.getElementById(new_date_id).value=\"%s\";' % date\n self.driver.execute_script(js2)\n time.sleep(2)\n\n def set_tangwu_date(self, type = 1, date=\"2021-4-24\"):\n # type=1为开始日期,否则为结束日期,默认为1 ,设置汤屋预订日期\n if type == 1:\n new_date_id = 'insoupHouseDate01'\n else:\n new_date_id = 'insoupHouseDate02'\n js1 = 'document.getElementById(new_date_id).removeAttribute(\"readonly\");'\n # 调用js脚本\n self.driver.execute_script(js1)\n # 通过js修改日期输入框的value值\n js2 = 'document.getElementById(new_date_id).value=\"%s\";' % date\n self.driver.execute_script(js2)\n time.sleep(2)\n\n\n# -------------------------------以下为非类方法-------------------------------\ndef get_current_time(add_date=0):\n # add_date=0默认为当日\n today = datetime.date.today()\n current_time = today + datetime.timedelta(days=add_date)\n return current_time\n\n","sub_path":"common_method.py","file_name":"common_method.py","file_ext":"py","file_size_in_byte":9789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"211776665","text":"import csv\nfrom decimal import Decimal\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom datanya import get_rating, headers\n\n\ndef get_url(_url):\n resp = requests.get(url=_url, headers=headers)\n data = resp.json()\n\n return [x[\"computed\"][\"Url\"] for x in data[\"Products\"]]\n\n\ndef save_txt(_nama, _list):\n with open(_nama, \"w\", encoding=\"utf-8\") as f:\n for x in _list:\n f.write(f\"{x}\\n\")\n\n\ndef load_txt(_nama):\n with open(_nama, \"r\", encoding=\"utf-8\") as f:\n data = [line.strip() for line in f]\n\n return data\n\n\ndef clean_html(doc):\n a = BeautifulSoup(str(doc), features=\"lxml\")\n soup = [str(x.extract()) for x in a.findAll() if not (\"READ\" in x.get_text())]\n\n if \"\" in soup[0]:\n soup = \"\".join(soup[0])\n else:\n soup = \"\".join(soup)\n\n soup = BeautifulSoup(soup, \"lxml\")\n invalid_tags = [\"a\"]\n for tag in invalid_tags:\n for match in soup.findAll(tag):\n match.replaceWithChildren()\n\n return str(soup)\n\n\ndef save_csv(_name, _products_data):\n with open(_name, mode=\"w\", encoding=\"utf-8\", newline=\"\") as csv_file:\n fieldnames = [\n \"Handle\",\n \"Title\",\n \"Type\",\n \"Tags\",\n \"Variant Compare At Price\",\n \"Variant Price\",\n \"Image Src\",\n \"Image Alt Text\",\n \"Body (HTML)\",\n ]\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n writer.writeheader()\n for _product_data in _products_data:\n writer.writerow(_product_data)\n\n\ndef get_one(_soup, _selector, _no_text=False):\n try:\n if \"a.\" in _selector or \"a#\" in _selector:\n return _soup.select_one(_selector).get(\"href\")\n elif \"img.\" in _selector or \"img#\" in _selector:\n return \"http:\" + _soup.select_one(_selector).get(\"src\")\n elif _no_text:\n return _soup.select(_selector)[0]\n else:\n return _soup.select_one(_selector).get_text().strip()\n except Exception:\n return None\n\n\ndef get_star(_soup, _selector):\n try:\n data = _soup.select_one(_selector).get(\"data-stars\")\n if not data:\n data = Decimal(\"0.0\")\n return data\n except Exception:\n return Decimal(\"0.0\")\n\n\ndef get_data(_url):\n resp = requests.get(url=_url, headers=headers)\n soup = BeautifulSoup(resp.content, \"lxml\")\n\n _title = get_one(soup, \"h1.prod-title\")\n _sub_title = get_one(soup, \"h2.prod-sub-title\")\n _ori_price = get_one(soup, \"span.original-price\")\n _price = get_one(soup, \"div.price\")\n _product_photo = get_one(soup, \"img.mainProductPhoto\")\n _rating = get_star(soup, \"div.buy-box-wrapper div.rating-stars.product-rating\")\n _star = get_rating(_rating)\n _count = get_one(soup, \"div.buy-box-wrapper div.rating-count\")\n _overview = get_one(soup, \"div.col-12.overviewCopy\", True)\n _overview = clean_html(_overview)\n _category = get_one(soup, \"li.breadcrumb-item:nth-of-type(3) > a\")\n\n _star = f\"{_star}

{_rating} from {_count}

\"\n if not _count:\n _star = \"\"\n\n r = requests.get(_product_photo, stream=True)\n if r.status_code != 200 or not any(char.isdigit() for char in _price):\n return {}\n\n data = {}\n data[\"Handle\"] = _url.lower().split(\"/\")[-2][3:]\n data[\"Title\"] = _title.replace('\"', '\"\"')\n data[\"Type\"] = _sub_title.replace('\"', '\"\"')\n data[\"Tags\"] = _category\n data[\"Variant Compare At Price\"] = (\n _ori_price.replace('\"', '\"\"') if _ori_price != None else 0\n )\n data[\"Variant Price\"] = _price.replace('\"', '\"\"')\n data[\"Image Src\"] = _product_photo\n data[\"Image Alt Text\"] = f\"{_title} photo\"\n data[\"Body (HTML)\"] = _star + _overview\n\n return data\n","sub_path":"libs.py","file_name":"libs.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"642880159","text":"#-*-coding: utf-8 -*-\nimport scrapy\nfrom ..items import ZufangItem\n\nclass GanjiSpider(scrapy.Spider):\n name = \"zufang\"\n start_urls = ['https://su.fang.anjuke.com/loupan/?from=navigation/']\n\n\n def parse(self, response):\n print(response)\n #sel = Selector()\n zf = ZufangItem()\n info_list = response.xpath('//div[@class=\"key-list\"]/div')\n #money_list = response.xpath(\"//div[@class='f-list-item ershoufang-list']/dl/dd[5]/div[1]/span[1]/text()\").extract()\n #title_list = response.xpath(\"//div[@class='f-list-item ershoufang-list']/dl/dd[1]/a/text()\").extract()\n for ench in info_list:\n money = ench.xpath(\"./a[2]/p[1]/span/text()\").extract()\n title = ench.xpath(\"./div/a[1]/h3/span/text()\").extract()\n\n if len(money):\n zf['title'] = title[0]\n zf['money'] = money[0]\n yield zf\n\n #for i, j in zip(title_list, money_list):\n # zf['title'] = i.encode('utf-8')\n # zf['money'] = j.encode('utf-8')\n # yield zf\n #for i in range(len(money_list)):\n # if i < len(title_list):\n # #zf['title'] = title_list[i]\n # #zf['money'] = money_list[i]\n # yield {\n # return some results\n # 'title': title_list[i],\n # 'money': money_list[i],\n # }\n # yield zf","sub_path":"zufang/spiders/ganji.py","file_name":"ganji.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"144514069","text":"import numpy as np\nfrom absl import app, flags, logging\nfrom absl.flags import FLAGS\n\nimport Arena\nfrom MCTS import MCTS\nfrom hex.matrix_hex_game import MatrixHexGame\nfrom hex.graph_hex_game import GraphHexGame\nfrom hex.graph_hex_board import GraphHexBoard\nfrom hex.NNet import NNetWrapper as NNet, FakeNNet, value_from_shortest_path\nfrom hex.hex_players import RandomPlayer, HumanHexPlayer, UIPlayer, PureMCTSPlayer, GPureMCTSPlayer\nfrom utils import dotdict, config_rec\n\n\"\"\"\nuse this script to play any two agents against each other, or play manually with\nany agent.\n\"\"\"\n\nflags.DEFINE_enum('board_type', 'hex',\n ['hex', 'vortex'],\n 'hex: standard hex grid Hex board, '\n 'vortex: random grap board played on a Voronoi diagram')\nflags.DEFINE_enum('player2', 'nnet',\n ['nnet', 'human', 'random', 'MCTS'],\n 'nnet: nnet vs nnet, '\n 'human: play interactivly with a human, '\n 'random: nnet vs random play agent, '\n 'MCTS: nnet vs MCTS with random agent')\nflags.DEFINE_boolean('verbose', False, 'show playout')\nflags.DEFINE_boolean('graphic', False, 'show playout graphically')\nflags.DEFINE_boolean('node_nums', False, 'show node numbers on UI')\nflags.DEFINE_integer('num_games', 2, 'Number of games to play')\nflags.DEFINE_string('cpu1_checkpoint', 'temp/gat/strong_5x5_b.pth.tar', 'pretrained weights for computer player 1')\nflags.DEFINE_string('cpu2_checkpoint', 'temp/gat/strong_5x5_b.pth.tar', 'pretrained weights for computer player 2')\nflags.DEFINE_integer('p1_MCTS_sims', 100, 'number of simulated steps taken by tree search for player 1')\nflags.DEFINE_integer('p2_MCTS_sims', 100, 'number of simulated steps taken by tree search for player 2 if usincg MCTS')\nflags.DEFINE_integer('game_board_size', 5, 'overide default size')\nflags.DEFINE_string('p1_nnet', 'base_gat', 'neural net for p,v estimation for player 1')\nflags.DEFINE_string('p2_nnet', 'base_gat', 'neural net for p,v estimation for player 2')\n\n\ndef get_action_func(search):\n def action_func(x, p):\n return np.argmax(search.getActionProb(x, temp=0))\n\n return action_func\n\n\ndef main(_argv):\n if FLAGS.board_type == 'hex':\n g = MatrixHexGame(FLAGS.game_board_size, FLAGS.game_board_size)\n if FLAGS.graphic:\n raise Exception(\"graphic display not implemented for hex boards\")\n elif FLAGS.board_type == 'vortex':\n board = GraphHexBoard.new_vortex_board(FLAGS.game_board_size)\n g = GraphHexGame(board)\n if FLAGS.verbose:\n raise Exception(\"ascii display not implemented for vortex boards\")\n\n # nnet player 1\n n1 = NNet(g, net_type=FLAGS.p1_nnet)\n n1.load_checkpoint('./', FLAGS.cpu1_checkpoint)\n args1 = dotdict({'numMCTSSims': FLAGS.p1_MCTS_sims, 'cpuct': 1.0})\n mcts1 = MCTS(g, n1, args1)\n player1 = get_action_func(mcts1)\n on_move_end = None\n on_game_end = None\n\n # player 2\n if FLAGS.player2 == 'human':\n if FLAGS.board_type == 'hex':\n player2 = HumanHexPlayer(g).play\n elif FLAGS.board_type == 'vortex':\n ui = UIPlayer(g, show_node_numbers=FLAGS.node_nums)\n on_move_end = ui.update\n player2 = ui.play\n elif FLAGS.player2 == 'random':\n player2 = RandomPlayer(g).play\n elif FLAGS.player2 == 'nnet':\n n2 = NNet(g, net_type=FLAGS.p2_nnet)\n n2.load_checkpoint('./', FLAGS.cpu2_checkpoint)\n args2 = dotdict({'numMCTSSims': FLAGS.p2_MCTS_sims, 'cpuct': 1.0})\n mcts2 = MCTS(g, n2, args2)\n #player2 = lambda x, p: np.argmax(mcts2.getActionProb(x, temp=0))\n player2 = get_action_func(mcts2)\n elif FLAGS.player2 == 'MCTS':\n if FLAGS.board_type == 'hex' or not FLAGS.graphic:\n mcts2 = PureMCTSPlayer(g, sims=FLAGS.p2_MCTS_sims)\n elif FLAGS.board_type == 'vortex':\n mcts2 = GPureMCTSPlayer(g, sims=FLAGS.p2_MCTS_sims, show_node_numbers=FLAGS.node_nums)\n on_move_end = mcts2.update\n on_game_end = mcts2.on_game_end\n player2 = mcts2.play\n\n if FLAGS.board_type == 'hex':\n arena = Arena.Arena(player1, player2, g, display=MatrixHexGame.display, display_move=g.display_move)\n elif FLAGS.board_type == 'vortex':\n arena = Arena.Arena(player1, player2, g, on_move_end=on_move_end, on_game_end=on_game_end)\n\n result = config_rec()\n result[\"p1_wins\"], result[\"p2_wins\"], _ = arena.playGames(FLAGS.num_games, verbose=FLAGS.verbose)\n print(\"Results:\\n\\tP1:{}\\n\\tP2:{}\".format(result[\"p1_wins\"], result[\"p2_wins\"]))\n logging.info(\"result:\" + str(result))\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"pit_hex.py","file_name":"pit_hex.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485898241","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nfrom __future__ import division # so that 1/3=0.333 instead of 1/3=0\nfrom psychopy import visual, core, data, event, logging, gui\nfrom psychopy.constants import * # things like STARTED, FINISHED\nimport pandas as pd\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray\nfrom numpy.random import random, randint, normal, shuffle\nimport os # handy system and path functions\nimport statsmodels.formula.api as sm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__))\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = u'r2d4_MM' # from the Builder filename that created this script\nexpInfo = {'participant':u'', 'session':u''}\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\nif dlg.OK == False: core.quit() # user pressed cancel\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\nexpInfo['expName'] = expName\n\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + 'data/%s_%s_%s' %(expInfo['participant'], expName, expInfo['date'])\n\nout_all_fn = _thisDir + os.sep + 'data/%s_%s_%s_responses.csv' %(expInfo['participant'], expName, expInfo['session'])\ndata_out = pd.DataFrame(columns=('onsetTime','correctResp','keysPressed'))\n\n\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=None,\n savePickle=True, saveWideText=True,\n dataFileName=filename)\n#save a log file for detail verbose info\nlogFile = logging.LogFile(filename+'.log', level=logging.EXP)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n# Start Code - component code to be run before the window creation\n\n# Setup the Window\nwin = visual.Window(size=(500, 500), fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[-1,-1,-1], colorSpace='rgb',\n blendMode='avg', useFBO=True,\n )\n# store frame rate of monitor if we can measure it successfully\nexpInfo['frameRate']=win.getActualFrameRate()\nif expInfo['frameRate']!=None:\n frameDur = 1.0/round(expInfo['frameRate'])\nelse:\n frameDur = 1.0/60.0 # couldn't get a reliable measure so guess\n\n# Initialize components for Routine \"Instructions\"\nInstructionsClock = core.Clock()\ntext_2 = visual.TextStim(win=win, ori=0, name='text_2',\n text=u'The experiment is about to begin. ', font=u'Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n# Initialize components for Routine \"trial\"\ntrialClock = core.Clock()\nISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI')\nimage = visual.ImageStim(win=win, name='image',units='pix',\n image='sin', mask=None,\n ori=0, pos=[0, 0], size=[200,200],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=0.0)\n\nfixation = visual.ShapeStim(win,\n vertices=((0, -0.075), (0, 0.075), (0,0), (-0.05,0), (0.05, 0)),\n lineWidth=5,\n closeShape=False,\n lineColor='white')\n\nWrong_1 = visual.Circle(win=win, units = 'pix', radius = 100,lineColor='red', fillColor = 'red')\n\n\n# Initialize components for Routine \"End\"\nEndClock = core.Clock()\ntext = visual.TextStim(win=win, ori=0, name='text',\n text=u'Experiment is completed. Thank you for your participation.', font=u'Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n\n#######################\n#### Set up onsets ####\n#######################\ncorr_thresh = 0.1\ndfStims = pd.DataFrame\nsequence_img_ids = []\nimg_dict = {2: 'image_folder/stim_2.png', 3: 'image_folder/stim_3.png', 4: 'image_folder/stim_4.png', 5: 'image_folder/stim_5.png'}\nkey_dict = {2:'2', 3:'3', 4:'4', 5:'5'}\n\nisDone = 0\nwhile not isDone:\n trial_types = np.asarray([2, 3, 4, 5])\n trial_IDs = np.asarray(range(4))\n trial_freq = np.asarray([12, 12, 12, 12])\n iti_range = np.asarray([2, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8])\n\n n_post = 3\n t_vec = []\n iti_vec = []\n tid_vec = []\n\n for tt in range(0,len(trial_types)):\n t_vec = np.repeat(trial_types,12)\n iti_vec = np.tile(iti_range,4)\n\n np.random.shuffle(t_vec)\n np.random.shuffle(iti_vec)\n vec = [0]\n id_vec = vec\n\n for t in range(0, len(t_vec)):\n vec = vec + [t_vec[t]] + np.repeat(0,iti_vec[t]).tolist()\n vec = vec + [0,0,0]\n dfStims = pd.DataFrame()\n X = np.zeros((len(vec),len(trial_types)))\n ons = np.zeros((12,4))\n for c in trial_types:\n a = np.where(vec==c)[0]\n ons[:,c-2] = a*2\n for indx in range(0, len(a)):\n name = a[indx]\n X[a[indx]][c-2]= 1\n\n df=pd.DataFrame(X)\n cxy = df.corr()\n cxy = abs(np.tril(cxy, k=-1))\n if cxy.max() < corr_thresh:\n isDone = 1\n\nfor x in range(0,len(vec)):\n if vec[x] == 0:\n sequence_img_ids.append('image_folder/skip.png')\n elif vec[x] != 0:\n sequence_img_ids.append(img_dict[vec[x]])\n\nid_vec = vec\nt_vec = range(0,480,2)\ndfStims['trial_img'] = sequence_img_ids\ndfStims['trial_ans'] = vec\n\n\n#######################\n## End Set up onsets ##\n#######################\n\nfilename = _thisDir + os.sep + 'data/%s_%s_%s_onsets.csv' %(expInfo['participant'], expName, expInfo['session'])\nnp.savetxt(filename, ons, '%5.2f',delimiter=\",\")\ndfStims.to_csv('MM_onsets.csv', index= False)\n\n\n\n# Create some handy timers\nglobalClock = core.Clock() # to track the time since experiment started\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine\n\n#------Prepare to start Routine \"Instructions\"-------\nt = 0\nInstructionsClock.reset() # clock\nframeN = -1\nroutineTimer.add(5.000000)\n# update component parameters for each repeat\n# keep track of which components have finished\nInstructionsComponents = []\nInstructionsComponents.append(text_2)\nfor thisComponent in InstructionsComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n\n#-------Start Routine \"Instructions\"-------\ncontinueRoutine = True\nwhile continueRoutine and routineTimer.getTime() > 0:\n # get current time\n t = InstructionsClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n\n # *text_2* updates\n if t >= 0.0 and text_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_2.tStart = t # underestimates by a little under one frame\n text_2.frameNStart = frameN # exact frame index\n text_2.setAutoDraw(True)\n if text_2.status == STARTED and t >= (0.0 + (5-win.monitorFramePeriod*0.75)): #most of one frame period left\n text_2.setAutoDraw(False)\n\n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in InstructionsComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n\n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n\n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"Instructions\"-------\nfor thisComponent in InstructionsComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n# set up handler to look after randomisation of conditions etc\ntrials = data.TrialHandler(nReps=1, method='sequential',\n extraInfo=expInfo, originPath=None,\n trialList=data.importConditions(u'MM_onsets.csv'),\n seed=None, name='trials')\n\n\nthisExp.addLoop(trials) # add the loop to the experiment\nthisTrial = trials.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)\nif thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\nRTclock = core.Clock()\nmax_rt = 1\n\n##### Wait for scanner trigger key #####\nevent.clearEvents(eventType='keyboard')\nScannerKey = event.waitKeys([\"asciicircum\",\"escape\"])\n\nif endExpNow or \"escape\" in ScannerKey:\n core.quit()\nglobalClock.reset()\n\n\n\ntrial = -1\nfor thisTrial in trials:\n trial = trial+1\n\n currentLoop = trials\n # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\n if thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n\n fixation.setAutoDraw(True)\n win.flip()\n\n\n\n #------Prepare to start Routine \"trial\"-------\n\n frameN = -1\n routineTimer.add(2.000000)\n\n #For Debugging\n #print globalClock.getTime()\n #print t_vec[trial]\n # update component parameters for each repeat\n while globalClock.getTime() < t_vec[trial]:\n core.wait(.001)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n\n\n if trial_img != 'image_folder/skip.png':\n fixation.setAutoDraw(False)\n win.flip()\n image.setImage(trial_img)\n key_response = event.BuilderKeyResponse() # create an object of type KeyResponse\n key_response.status = NOT_STARTED\n # keep track of which components have finished\n trialComponents = []\n trialComponents.append(image)\n trialComponents.append(key_response)\n\n for thisComponent in trialComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n #-------Start Routine \"trial\"-------\n continueRoutine = True\n trialClock.reset() # clock\n # Print routTimer to verify matches correct onset timings.\n # print routineTimer.getTime()\n\n while continueRoutine:\n # get current me\n t = trialClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n\n # *image* updates\n if t >= 0.0 and image.status == NOT_STARTED:\n # keep track of start time/frame for later\n image.tStart = t # underestimates by a little under one frame\n image.frameNStart = frameN # exact frame index\n image.setAutoDraw(True)\n onsetTime = globalClock.getTime()\n if image.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left\n image.setAutoDraw(False)\n continueRoutine = False\n # *key_response* updates\n if t >= 0.0 and key_response.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_response.tStart = t # underestimates by a little under one frame\n key_response.frameNStart = frameN # exact frame index\n key_response.status = STARTED\n # keyboard checking is just starting\n key_response.clock.reset() # now t=0\n event.clearEvents(eventType='keyboard')\n if key_response.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left\n key_response.status = STOPPED\n continueRoutine = False\n if key_response.status == STARTED:\n theseKeys = event.getKeys(keyList=['2', '3', '4', '5'])\n\n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_response.keys.extend(theseKeys) # storing all keys\n key_response.rt.append(key_response.clock.getTime())\n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n\n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n\n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n #-------Ending Routine \"trial\"-------\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n # check responses\n if key_response.keys in ['', [], None]: # No response was made\n key_response.keys=None\n # was no response the correct answer?!\n if str(trial_ans).lower() == 'none': key_response.corr = 1 # correct non-response\n else: key_response.corr = 0 # failed to respond (incorrectly)\n # store data for trials (TrialHandler)\n trials.addData('key_response.keys',key_response.keys)\n trials.addData('key_response.corr', key_response.corr)\n if key_response.keys != None: # we had a response\n trials.addData('key_response.rt', key_response.rt)\n thisExp.nextEntry()\n win.flip()\n #Save Data to output File\n\n\n data_out.loc[len(data_out)+1]=[onsetTime,trial_ans, str(key_response.keys).strip('[]')]\n data_out.to_csv(out_all_fn, index=False)\n\n elif trial_img == 'image_folder/skip.png':\n fixation.setAutoDraw(True)\n core.wait(0.5)\n thisExp.nextEntry()\n\n\n# completed all trials\n\n\n#------Prepare to start Routine \"End\"-------\nt = 0\nEndClock.reset() # clock\nframeN = -1\nroutineTimer.add(1.000000)\n# update component parameters for each repeat\n# keep track of which components have finished\nEndComponents = []\nEndComponents.append(text)\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"End\"-------\ncontinueRoutine = True\nwhile continueRoutine and routineTimer.getTime() > 0:\n # get current time\n t = EndClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n\n # *text* updates\n if t >= 0.0 and text.status == NOT_STARTED:\n # keep track of start time/frame for later\n text.tStart = t # underestimates by a little under one frame\n text.frameNStart = frameN # exact frame index\n text.setAutoDraw(True)\n if text.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left\n text.setAutoDraw(False)\n\n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in EndComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n\n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n\n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"End\"-------\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\nwin.close()\ncore.quit()\n","sub_path":"r2d4_MM_MRI.py","file_name":"r2d4_MM_MRI.py","file_ext":"py","file_size_in_byte":16291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"281100968","text":"'''\nCreated on Apr 17, 2013\n\n@author: luk\n'''\n\n\ndef cell_iterator(row):\n '''iterates over all cells in a value.'''\n for key_value in row.raw():\n family_id = key_value.getFamily().tostring()\n cell_id = key_value.getQualifier().tostring()\n cell_value = key_value.getValue().tostring()\n yield family_id, cell_id, cell_value\n","sub_path":"happy/yala/java/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"382687512","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom Common import Common\nfrom Define import Define\n\n\nclass CreateDensityPlot(object):\n\n\n def __init__(self, startDate, finishDate, ncData, reference, database, iniReader, log):\n \"\"\"\n create density plot\n :param startDate: 'yyyyMMddHHmm'\n :param finishDate: 'yyyyMMddHHmm'\n :param ncData: object of Data Class\n :param reference: reference name\n :param database: object of Database Class\n :param iniReader: object of ConfigParser\n :param log: object of logger Class\n \"\"\"\n self.logger = log\n self.logger.logger.info('start generate Density Plot')\n self.reference = reference\n self.database = database\n self.common = Common(self.logger)\n self.define = Define()\n try:\n self.get_configuration(iniReader)\n self.startYear, self.startMonth, self.startDay = self.common.split_date(startDate)\n self.finishYear, self.finishMonth, self.finishDay = self.common.split_date(finishDate)\n histData, productData, referenceData = self.get_histogram(ncData)\n self.generate_plot(productData, referenceData, histData, iniReader, iniReader.savepath)\n except ValueError as e:\n self.logger.logger.error('%s : Value Error'%(e))\n except EnvironmentError:\n self.logger.logger.error('No Match Colors - Colors_Value')\n except Exception as e:\n self.logger.logger.error('%s : Error'%(e))\n finally:\n self.logger.logger.info('finish generate Density Plot')\n\n def get_configuration(self, iniReader):\n \"\"\"\n extract density plot inforamtion in .ini file\n :param iniReader: object of ConfigParser\n \"\"\"\n # 설정정보의 densityplot 섹션의 value값 저장\n self.title = iniReader.iniReader['density']['title']\n self.valueRange = iniReader.iniReader['density']['value_range'].split(',')\n self.valueRange = {'min': int(self.valueRange[self.define.VALUERANGEMIN]),\n 'max': int(self.valueRange[self.define.VALUERANGEMAX])}\n self.bins = int(iniReader.iniReader['density']['dividing_value_range'])\n self.colors = iniReader.iniReader['density']['colors'].split(',')\n self.colorbar_value = iniReader.iniReader['density']['colorbar_value'].split(',')\n for i, value in enumerate(self.colorbar_value):\n self.colorbar_value[i] = int(value)\n if len(self.colorbar_value) != len(self.colors):\n raise EnvironmentError\n # 색상과 값을 matplotlib에 맞게 재정의\n self.colors = matplotlib.colors.ListedColormap(self.colors)\n self.norm = matplotlib.colors.BoundaryNorm(self.colorbar_value, len(self.colorbar_value))\n\n def get_histogram(self, ncData):\n \"\"\"\n calcurate histogram and return 3 values\n :param ncData: the object of Data Class\n :return: calcurated 3 values\n \"\"\"\n productData, referenceData = ncData.get_value()\n # 주어진 데이터를 가지고 히스토그램 함수 진행 bins : 등분될 수, range : range범위 내에서 히스토그램 진행\n histData, productData, referenceData = np.histogram2d(productData, referenceData, bins=self.bins,\n range=[[self.valueRange['min'], self.valueRange['max']],\n [self.valueRange['min'], self.valueRange['max']]])\n histData = np.flipud(np.rot90(histData)) # Histogram한 결과가 화면과 맞게 나오기 위해 진행(회전하고 뒤집기)\n maskedData = np.ma.masked_where(histData == self.define.ZERO, histData) # 히스토그램 한 결과값중 0인 값은 mask 씌우기\n return maskedData, productData, referenceData\n\n def set_plot(self, savepath, iniReader):\n \"\"\"\n set plot information\n :param savepath: image storage path\n :param iniReader: object of ConfigParser\n \"\"\"\n # label을 보이게 한다면 showLegend값은 True\n if iniReader.showLegend == 'True':\n plt.xlabel(iniReader.product)\n plt.ylabel(self.reference)\n plt.grid()\n # showLegend값이 True, False 둘다 아닌경우 --> log기록 남기고 False로 처리\n elif iniReader.showLegend !='False' and iniReader.showLegend !='True':\n self.logger.logger.error('ini File value Error : show_legend \\n Default : False')\n text = self.get_quality_indicator()\n plt.text(self.valueRange['min'], self.valueRange['max'], text, horizontalalignment='left', verticalalignment='top')\n # title과 이미지 저장 파일 생성을 위해 필요한 날짜\n self.set_title(iniReader)\n self.save_plot(savepath, iniReader)\n\n def get_quality_indicator(self):\n \"\"\"\n return the value to be displayed in the text in the density plot\n :return: text in the density plot\n :rtype: string\n \"\"\"\n # Database에 있는 Average의 평균의 평균을 text형태로 저장하여 리턴\n text = ' '\n for quality_indicator in sorted(self.database.dataDic.keys()):\n average = self.get_average(self.database.dataDic[quality_indicator])\n string = '%s : %s \\n '%(quality_indicator, average)\n text = text + string\n return text\n\n def get_average(self, quality_indicator):\n \"\"\"\n return the average of the values in the object of Database Class\n :param quality_indicator: the key of dataDic in the Database Class\n :return: average value\n \"\"\"\n sum = self.define.ZERO\n # 반복문을 통해 데이터를 받아와 평균값 구하기\n # None값이 있는 경우도 개수에 포함시킨다.\n for data in quality_indicator:\n if data is None:\n continue\n else:\n sum = sum + data\n return sum / len(quality_indicator)\n\n def generate_plot(self, x, y, result, iniReader, savepath):\n \"\"\"\n generate plot and draw density plot\n :param x: Xaxis value\n :param y: Yaxis value\n :param result: histogramed value\n :param iniReader: object of ConfigParser\n :param savepath: image storage path\n \"\"\"\n fig = plt.figure(figsize=(self.define.FIGUREX, self.define.FIGUREY))\n plt.pcolormesh(x, y, result, norm=self.norm, cmap=self.colors)\n plt.colorbar()\n self.set_plot(savepath, iniReader)\n plt.close(fig)\n\n def set_title(self, iniReader):\n \"\"\"\n set the density plot title\n :param iniReader: object of ConfigParser\n \"\"\"\n plt.title('%s \\n%s vs. %s (%s.%s.%s ~ %s.%s.%s)' % (self.title, iniReader.product, self.reference, self.startYear, self.startMonth,\n self.startDay, self.finishYear, self.finishMonth, self.finishDay))\n\n def save_plot(self, savepath, iniReader):\n \"\"\"\n save the density plot in image storage path\n :param savepath: image storage path\n :param iniReader: object of ConfigParser\n \"\"\"\n savepath = self.common.get_path(savepath, iniReader.product, self.reference)\n plt.savefig('%s/ami_%s_%s_density_%s%s%s_%s%s%s.png'%(savepath, iniReader.product, self.reference, self.startYear,\n self.startMonth, self.startDay, self.finishYear, self.finishMonth, self.finishDay))\n","sub_path":"CreateDensityPlot.py","file_name":"CreateDensityPlot.py","file_ext":"py","file_size_in_byte":7663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"185772723","text":"# -*- coding:utf-8 -*-\n\n__author__ = 'catleer'\n\n\"\"\"\n本地没安mysql。。不要慌 用禅道的,哈哈h\n\"\"\"\n\"\"\"\n算了,启动不了了\n\npymysql的基本使用说明:\n1.import pymysql\n2.构造连接实例:\nconn = pymsql.connect(\n host=\"\",\n prot=3306,\n user=\"\",\n password=\"\",\n db=\"\",# 要连接的数据库名称\n charset=\"utf-8\",# 应该要与数据库的编码一致,可以查看数据库的编码是什么,如果不是utf-8可以修改\n)\n\n3.创建交互对象:光标\ncursor = conn.cursor()\n\n4.构造要插入的数据\ncursor.excutemany(sql, sql_data) # 批量执行\ncursor.excute(sql) # 单条执行\n\n5.提交数据(若进行了数据的更改)\nconn.commit()\n\n6.若不再执行数据的读取或插入或更改,则一定要关闭连接\nconn.close()\n\"\"\"\n","sub_path":"第一期/成都-乐大爷/task02/07_Day7/pymysql_practice.py","file_name":"pymysql_practice.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465329256","text":"#!/usr/bin/env python3\n\"\"\"\nWill deploy nightly Bitconch chain, codename soros \n\"\"\"\nimport logging\nimport stat\nimport shutil\nimport os, re, argparse, sys,crypt\nimport getpass\nimport click\nfrom subprocess import Popen, check_call, PIPE, check_output, CalledProcessError\nfrom shutil import copy2, copytree, rmtree\nfrom colorama import init\ninit()\nfrom colorama import Fore, Back, Style\n\n\ndef rmtree_onerror(self, func, file_path, exc_info):\n \"\"\"\n Error handler for ``shutil.rmtree``.\n If the error is due to an access error (read only file)\n it attempts to add write permission and then retries.\n If the error is for another reason it re-raises the error.\n Usage : ``shutil.rmtree(path, onerror=onerror)`` \n \"\"\"\n logging.warning(str(exc_info))\n logging.warning(\"rmtree error,check the file exists or try to chmod the file,then retry rmtree action.\")\n os.chmod(file_path, stat.S_IWRITE) #chmod to writeable\n if os.path.isdir(file_path):\n #file exists\n func(file_path)\n else:\n #handle whatever\n raise\n\n\ndef execute_shell(command, silent=False, cwd=None, shell=True, env=None):\n \"\"\"\n Execute a system command \n \"\"\"\n if env is not None:\n env = dict(**os.environ, **env)\n\n if silent:\n p = Popen(\n command, shell=shell, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env)\n stdout, _ = p.communicate()\n\n return stdout\n\n else:\n check_call(command, shell=shell, cwd=cwd, env=env)\n\ndef prnt_warn(in_text):\n \"\"\"\n Print a warning message\n \"\"\"\n print(Fore.YELLOW + \"[!]\"+in_text)\n print(Style.RESET_ALL)\n\ndef prnt_run(in_text):\n \"\"\"\n Print a processing message\n \"\"\"\n print(Fore.WHITE + \"[~]\"+in_text)\n print(Style.RESET_ALL)\n\ndef prnt_error(in_text):\n \"\"\"\n Print an error message\n \"\"\"\n print(Fore.RED + \"[~]\"+in_text)\n print(Style.RESET_ALL)\n\n\ndef update_submodules():\n \"\"\"\n Pull the latest submodule code from upstream\n \"\"\"\n prnt_warn('This repo uses submodules to manage the codes')\n prnt_run(\"Use git to update the submodules\")\n # Ensure the submodule is initialized\n execute_shell(\"git submodule update --init --recursive\", silent=False)\n\n # Fetch upstream changes\n execute_shell(\"git submodule foreach --recursive git fetch \", silent=False)\n\n # Reset to upstream\n execute_shell(\"git submodule foreach git reset --hard origin/HEAD\", silent=False)\n\n # Update include/\n if os.path.exists(\"include\"):\n prnt_run(\"Clean the include folder\")\n rmtree(\"include\",onerror=rmtree_onerror)\n prnt_run(\"Copy the latest header file from vendor/rustelo-rust/include\")\n copytree(\"vendor/rustelo-rust/include\", \"include\")\n\n\n\n \n\n\ndef build(rust_version,cargoFeatures,release=False):\n target_list = execute_shell(\"rustup target list\", silent=True).decode()\n # m = re.search(r\"(.*?)\\s*\\(default\\)\", target_list)\n m = re.search(r\"(.*?)\\s*\\(installed\\)\", target_list)\n #currentWorking directory\n pwd = os.getcwd()\n \n default_target =m[1]\n\n # building priority:\n # 1. x86_64-pc-windows-gnu for 64-bit MinGW (Windows 7+)\n # 2. x86_64-unknown-linux-musl for linux musl\n # 3. x86_64-unknown-linux-musl for linux ubuntu,debian\n # 4. x86_64-apple-darwin for macOS-10\n\n\n target_list = [\n \"x86_64-pc-windows-gnu\",\n \"x86_64-unknown-linux-musl\",\n \"x86_64-unknown-linux-gnu\",\n \"x86_64-apple-darwin\"\n ]\n\n prefix = {\n \"x86_64-pc-windows-gnu\": \"x86_64-w64-mingw32-\",\n \"x86_64-unknown-linux-musl\": \"x86_64-linux-musl-\",\n \"x86_64-unknown-linux-gnu\": \"x86_64-linux-gnu-\",\n \"x86_64-apple-darwin\": \"\"\n }\n\n artifact = {\n \"x86_64-pc-windows-gnu\": \"rustelo.dll\",\n \"x86_64-unknown-linux-musl\": \"librustelo.so\",\n \"x86_64-unknown-linux-gnu\": \"librustelo.so\",\n \"x86_64-apple-darwin\": \"librustelo.dylib\"\n }\n\n if release:\n for target in target_list:\n prnt_run(f\"Build rust source for {target}\")\n\n if target != default_target:\n execute_shell([\"rustup\", \"target\", \"add\", target],\n shell=False,\n silent=True,\n #cwd=\"vendor/rustelo-rust\")\n cwd=\"buffett2\")\n\n profile = \"--release\" if release else ''\n execute_shell(f\"cargo build --all --target {target} {profile}\",\n #cwd=\"vendor/rustelo-rust\",\n cwd=\"buffett2\",\n env={\n \"CC\": f\"{prefix[target]}gcc\",\n \"CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER\": f\"{prefix[target]}gcc\",\n \"CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER\": f\"{prefix[target]}gcc\",\n })\n\n if target.endswith(\"-apple-darwin\"):\n execute_shell(f\"strip -Sx {artifact[target]}\",\n cwd=f\"vendor/rustelo-rust/soros/target/{target}/release\", silent=True)\n\n else:\n execute_shell(f\"{prefix[target]}strip --strip-unneeded -d -x {artifact[target]}\",\n #cwd=f\"vendor/rustelo-rust/target/{target}/release\")\n cwd=f\"vendor/rustelo-rust/soros/target/{target}/release\")\n\n #copy2(f\"vendor/rustelo-rust/target/{target}/release/{artifact[target]}\", f\"libs/{target}/\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-fullnode\", f\"libs/{target}/buffett-fullnode\")\n #copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-fullnode-config\", f\"libs/{target}/buffett-fullnode-config\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-drone\", f\"libs/{target}/buffett-drone\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-bench-tps\", f\"libs/{target}/buffett-bench-tps\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-ledgerbot\", f\"libs/{target}/buffett-ledgerbot\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-genesis\", f\"libs/{target}/buffett-genesis\")\n copy2(f\"vendor/rustelo-rust/soros/target/{target}/release/soros-keybot\", f\"libs/{target}/buffett-keybot\")\n\n else:\n target = default_target\n\n # For development; build only the _default_ target\n prnt_run(f\"Build the rust+c code in soros for {target}\")\n\n execute_shell(f\"cargo build --all --release --features=erasure\", cwd=\"./\")\n \n # Copy _default_ lib over\n \n if not os.path.exists(f\"libs/{target}/\"):\n prnt_run(f\"Check the lib folder, if not , create one \")\n os.makedirs(f\"libs/{target}/\")\n if not os.path.exists(f\"libs/{target}/bin/deps\"):\n prnt_run(f\"Check the the depslib folder, if not , create one \")\n os.makedirs(f\"libs/{target}/bin/deps/\")\n\n prnt_run(f\"Copy the generated artifact file and dependencies\")\n\n BIN_CRATES=[\n \"bench-exchange\",\n \"bench-streamerbot\",\n \"benchbot\",\n \"tokenbot\",\n \"genesis\",\n \"gossip\",\n \"install\",\n \"keybot\",\n \"ledgerbot\",\n \"validator\",\n \"wallet\"\n ]\n\n for crate in BIN_CRATES:\n # execute_shell(f\"set -x && cargo install --force --path '{crate}' --root '{pwd}/libs/{target}/' --features='erasure'\", cwd=\"vendor/rustelo-rust/soros\")\n execute_shell(f\"set -x && cargo install --force --path '{crate}' --root '{pwd}/libs/{target}/' --features='erasure'\", cwd=\"./\")\n\n # copy dependencies into deps folder\n # execute_shell(f\"set -x && cp *.so {pwd}/libs/{target}/bin/deps\",cwd=\"vendor/rustelo-rust/soros/target/release\")\n execute_shell(f\"set -x && cp libmorgan*.so {pwd}/libs/{target}/bin/deps\",cwd=\"./target/release/deps\")\n\n\n deploy_bin(target)\n\n\n\ndef commit():\n sha = execute_shell(\"git rev-parse --short HEAD\", cwd=\"vendor/rustelo-rust\", silent=True).decode().strip()\n execute_shell(\"git add ./vendor/rustelo-rust ./libs ./include\")\n\n try:\n execute_shell(f\"git commit -m \\\"Build libs/ and sync include/ from rustelo#{sha}\\\"\")\n execute_shell(\"git push\")\n\n except CalledProcessError:\n # Commit likely failed because there was nothing to commit\n pass\n\n\n\ndef createUser(name,username, password):\n prnt_run(f\"Create a new user\")\n encPass =crypt.crypt(password,\"22\")\n return os.system(\"useradd -p\"+encPass+\"-s\"+\"/bin/bash\"+\"-d\"+\"/home/\"+username+\"-m\"+\"-c \\\"\"+name +\"\\\"\"+username)\n\n\ndef deploy_bin(target):\n # installation location /usr/bin/bitconch\n # remove previous installed version\n if os.path.exists(\"/usr/bin/bitconch\"):\n prnt_run(\"Remove previous installed version\")\n rmtree(\"/usr/bin/bitconch\",onerror=rmtree_onerror)\n prnt_run(\"Copy the compiled binaries to /usr/bin/bitconch\")\n # cp the binary into the folder \n copytree(f\"libs/{target}/\", \"/usr/bin/bitconch\")\n \n # seth PATH variable \n prnt_run(f\"Set PATH to include soros executables \")\n execute_shell(\"echo 'export PATH=/usr/bin/bitconch/bin:$PATH' >>~/.profile\")\n execute_shell(\"echo 'export PATH=/usr/bin/bitconch/bin/deps:$PATH' >>~/.profile\")\n # execute_shell(\"source ~/.profile\")\n\n # remove the previous installed service file\n if os.path.exists(\"/etc/systemd/system/morgan-leader.service\"):\n prnt_run(\"Remove previous installed service file:morgan-leader.service\")\n os.remove(\"/etc/systemd/system/morgan-leader.service\")\n if os.path.exists(\"/etc/systemd/system/morgan-leader.socket\"):\n prnt_run(\"Remove previous installed socket file:morgan-leader.socket\")\n os.remove(\"/etc/systemd/system/morgan-leader.socket\")\n\n if os.path.exists(\"/etc/systemd/system/morgan-tokenbot.service\"):\n prnt_run(\"Remove previous installed service file:morgan-tokenbot.service\")\n os.remove(\"/etc/systemd/system/morgan-tokenbot.service\")\n if os.path.exists(\"/etc/systemd/system/morgan-tokenbot.socket\"):\n prnt_run(\"Remove previous installed socket file:morgan-tokenbot.socket\")\n os.remove(\"/etc/systemd/system/morgan-tokenbot.socket\")\n\n if os.path.exists(\"/etc/systemd/system/morgan-validator.service\"):\n prnt_run(\"Remove previous installed service file:morgan-validator.service\")\n os.remove(\"/etc/systemd/system/morgan-validator.service\")\n if os.path.exists(\"/etc/systemd/system/morgan-validator.socket\"):\n prnt_run(\"Remove previous installed socket file:morgan-validator.socket\")\n os.remove(\"/etc/systemd/system/morgan-validator.socket\")\n\n # cp the service files into service folder\n execute_shell(\"cp morgan.service.template/* /etc/systemd/system\")\n\n if os.path.exists(\"/bitconch/morgan\"):\n prnt_run(\"Remove previous installed version\")\n rmtree(\"/bitconch/morgan\",onerror=rmtree_onerror)\n prnt_run(\"Copy the morgan scripts to /bitconch/morgan\")\n # create the working directory data directory\n copytree(f\"multinode-demo\", \"/bitconch/morgan/demo\")\n copytree(f\"scripts\", \"/bitconch/morgan/scripts\")\n\n \nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"-R\", \"--release\", help=\"build in release mode\", action=\"store_true\")\nparser.add_argument(\n \"-C\", \"--commit\", help=\"commit include/ and libs/\", action=\"store_true\")\n\nargv = parser.parse_args(sys.argv[1:])\n\n# update_submodules()\nbuild(\"1.35\",\"erasure\",release=argv.release)\nprnt_run(\"Update PATH\")\n# execute_shell(f\"source ~/.profile\")\nprnt_run(\"Please run /bitconch/morgan/demo/setup.sh\")\n\n# Setup the boot leader with stake of 500K dif\nif click.confirm('Do you want to run setup to create genesis file and id files?', default=True):\n execute_shell(\"/bitconch/morgan/demo/setup.sh\",cwd=\"/bitconch/morgan\")\n\n\n# \nif click.confirm('Do you want to reload the systemctl daemon?', default=True):\n execute_shell(\"systemctl daemon-reload\")\n\nif click.confirm('Are you running on the leader node?', default=True):\n # backup the existing rsync configuration file\n if os.path.exists(\"/etc/rsyncd.conf\"):\n prnt_run(\"Backup the existing rsyncd.conf.\")\n copy2(f\"/etc/rsyncd.conf\", f\"/etc/rsyncd.conf.bk\")\n os.remove(\"/etc/rsyncd.conf\")\n prnt_run(\"Setup new rsyncd.conf.\")\n copy2(f\"rsyncd-morgan.conf\", f\"/etc/rsyncd.conf\")\n execute_shell(\"systemctl enable rsync\")\n execute_shell(\"systemctl start rsync\")\n\nif argv.commit and argv.release:\n commit()\n\n","sub_path":"deploy-nightly.py","file_name":"deploy-nightly.py","file_ext":"py","file_size_in_byte":12449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"562854829","text":"BASE_URL = \"https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/paper-fig11a-small-datasets\"\n\nL_EXPS = [\n #############################################\n # Stylegan2-baseline\n #############################################\n {\n \"model_name\" : \"stylegan2\",\n \"dataset_name\" : \"metfaces\",\n \"dataset_res\" : \"1024\",\n \"dataset_split\" : \"train\",\n \"reported_fid\" : \"57.26\",\n \"reported_kid\" : \"35.66\",\n \"task_name\" : \"few_shot_generation\",\n \"model_url\" : f\"{BASE_URL}/metfaces-mirror-stylegan2-noaug.pkl\",\n \"num_generated_images\" : 50_000\n },\n\n #############################################\n # StyleGAN2-ADA\n #############################################\n {\n \"model_name\" : \"stylegan2-ada\",\n \"dataset_name\" : \"metfaces\",\n \"dataset_res\" : \"1024\",\n \"dataset_split\" : \"train\",\n \"reported_fid\" : \"18.22\",\n \"reported_kid\" : \"2.41\",\n \"task_name\" : \"few_shot_generation\",\n \"model_url\" : f\"{BASE_URL}/metfaces-mirror-paper1024-ada.pkl\",\n \"num_generated_images\" : 50_000\n }\n]\n\n","sub_path":"scripts/leaderboard/CONFIGS/config_metfaces.py","file_name":"config_metfaces.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380743529","text":"import numpy as np\nimport traceback\nimport sys\nimport numpy.linalg as LA\nimport datetime\nfrom numpy import conj as con\nfrom numpy import complex_\nfrom functools import reduce\nfrom hqca.tools import _rdmfunctions as rdmf\nfrom copy import deepcopy as copy\n\n\nclass RDM:\n '''\n RDM class which allows for construction from Hartree-Fock state,\n reconstruction, multiplication and addition. \n '''\n def __init__(self,\n order=2,\n alpha=[],\n beta=[],\n state='hf',\n Ne=None,\n S=0,\n S2=0,\n verbose=0,\n rdm=None,\n rdm_type='d',\n **kw\n ):\n self.dqg=rdm_type\n self.p = order\n self.r = len(alpha)+len(beta) # num spin orbitals, fermionic sites\n self.R = int(self.r/2)\n self.v = verbose\n self.alp = alpha\n self.bet = beta\n self.S=S\n self.S2=S2\n self.Ne=Ne\n self.s2s = {}\n for n,a in enumerate(alpha):\n self.s2s[a]=n\n for n,b in enumerate(beta):\n self.s2s[b]=n\n self.N_alp = int(Ne+S)//2\n self.N_bet = Ne-self.N_alp\n if state in ['hartree','hf','scf']:\n if self.v>0:\n print('Making Hartree-Fock {}-RDM'.format(self.p))\n if self.S==0:\n self._build_hf_singlet()\n elif self.S==1:\n self._build_hf_doublet()\n elif state in ['wf']:\n pass\n elif state in ['given','provided','spec']:\n try:\n self.rdm = rdm.copy()\n except Exception:\n self.rdm = rdm\n elif state in ['alpha-beta']:\n self._generate_from_ab_block(rdm)\n elif state in ['spatial']:\n self._generate_from_spatial(rdm)\n else:\n self.rdm = np.zeros(\n tuple([self.r for i in range(2*self.p)]),dtype=np.complex_)\n\n def _generate_from_spatial(self,rdm):\n if not self.S2==0:\n sys.exit('Can not generate from alpha-beta block of non singlet state yet.')\n aa = ab - ab.transpose(1,0,2,3)\n new = np.zeros((self.r,self.r,self.r,self.r))\n for i in range(self.R):\n I =i+self.R\n for j in range(self.R):\n J = j+self.R\n for k in range(self.R):\n K = self.R+k\n for l in range(self.R):\n L = l+self.R\n new[i,k,j,l]+=rdm[i,k,j,l]\n new[I,K,J,L]+=rdm[i,k,j,l]\n\n new[i,K,j,L]+=rdm[i,k,j,l]\n new[I,k,J,l]+=rdm[i,k,j,l]\n\n new[K,i,j,L]+=rdm[i,k,j,l]\n new[k,I,J,l]+=rdm[i,k,j,l]\n self.rdm = new\n\n\n def _generate_from_ab_block(self,rdm):\n if not self.S2==0:\n sys.exit('Can not generate from alpha-beta block of non singlet state yet.')\n aa = rdm - rdm.transpose(1,0,2,3)\n new = np.zeros((self.r,self.r,self.r,self.r))\n for i in range(self.R):\n I =i+self.R\n for j in range(self.R):\n J = j+self.R\n for k in range(self.R):\n K = self.R+k\n for l in range(self.R):\n L = l+self.R\n new[i,k,j,l]+=aa[i,k,j,l]\n new[I,K,J,L]+=aa[i,k,j,l]\n # which means we also do ki jl? yeah. \n\n new[i,K,j,L]+=rdm[i,k,j,l]\n new[I,k,J,l]+=rdm[i,k,j,l]\n\n new[K,i,j,L]-=rdm[i,k,j,l]\n new[k,I,J,l]-=rdm[i,k,j,l]\n self.rdm = new\n\n def _get_ab_block(self):\n if self.p==2:\n ab_basis = []\n for i in self.alp:\n for j in self.bet:\n ab_basis.append([i,j])\n N_ab = len(ab_basis)\n ab = np.zeros((N_ab,N_ab),dtype=np.complex_)\n for ni,I in enumerate(ab_basis):\n for nj,J in enumerate(ab_basis):\n ind = tuple(I+J)\n ab[ni,nj]+= self.rdm[ind]\n return ab\n\n def spatial_rdm(self):\n '''\n get the spin integrated 2-RDM\n\n note, ordering is preserved\n '''\n new = np.zeros((self.R,self.R,self.R,self.R),dtype=np.complex_)\n for i in range(self.R):\n I = self.R+i\n for j in range(self.R):\n J = self.R+j\n for k in range(self.R):\n K = self.R+k\n for l in range(self.R):\n L = self.R+l\n new[i,k,j,l]+= self.rdm[i,K,j,L] #abba \n new[i,k,j,l]+= self.rdm[I,k,J,l] #baab\n new[i,k,j,l]+= self.rdm[i,k,j,l] #aaaa\n new[i,k,j,l]+= self.rdm[I,K,J,L] #bbbb\n return new\n\n def symmetric_block(self):\n '''\n returns the alpha-alpha block (alpha beta alpha beta)\n '''\n new = np.zeros((self.R,self.R,self.R,self.R),dtype=np.complex_)\n for i in self.alp:\n I = i%self.R\n for j in self.alp:\n J = j%self.R\n for k in self.alp:\n K = k%self.R\n for l in self.alp:\n L = l%self.R\n new[I,K,J,L]+= self.rdm[i,k,j,l]\n return new\n\n def antisymmetric_block(self,spin=True):\n '''\n returns the alpha-beta blocks\n '''\n new = np.zeros((self.R,self.R,self.R,self.R),dtype=np.complex_)\n for i in self.alp:\n I = i%self.R\n for j in self.alp:\n J = j%self.R\n for k in self.bet:\n K = k%self.R\n for l in self.bet:\n L = l%self.R\n new[I,K,J,L]+= self.rdm[i,k,j,l]\n return new\n\n def transpose(self,*args,**kwargs):\n self.rdm.transpose(*args,**kwargs)\n return self\n\n def save(self,name='default',precision=8,dtype='rdm',spin=True):\n if name=='default':\n name = datetime.strftime(datetime.now(),'%m%d%y')\n name+= '-'\n name+= datetime.strftime(datetime.now(),'%H%M')\n if dtype=='rdm':\n with open(name+'.rdm','w') as fp:\n self.expand()\n if spin:\n d = self.antisymmetric_block()\n else:\n d = self.spatial_rdm()\n nz = np.nonzero(d)\n first = ''\n for i in self.alp:\n first+='{} '.format(i)\n first+= '\\n'\n fp.write(first)\n first = ''\n for i in self.bet:\n first+='{} '.format(i)\n first+= '\\n'\n fp.write(first)\n line = ''\n if self.p==2:\n for i,j,k,l in zip(nz[0],nz[1],nz[2],nz[3]):\n line+= '{} {} {} {} {:f} {:f}\\n'.format(\n i+1,j+1,k+1,l+1,\n round(d[i,j,k,l].real,precision),\n round(d[i,j,k,l].imag,precision),\n )\n fp.write(line[:-1])\n else:\n print(dtype)\n sys.exit('File type for save rdm not recognized')\n\n def analysis(self,verbose=True,print_rdms=False,split=False):\n # start with alpha alpha block\n # generate basis\n if self.p==2:\n aa_basis = []\n ab_basis = []\n bb_basis = []\n for i in self.alp:\n for j in self.alp:\n if j>i:\n aa_basis.append([i,j])\n for i in self.alp:\n for j in self.bet:\n ab_basis.append([i,j])\n for i in self.bet:\n for j in self.bet:\n if j>i:\n bb_basis.append([i,j])\n N_aa = len(aa_basis)\n N_ab = len(ab_basis)\n N_bb = len(bb_basis)\n aa = np.zeros((N_aa,N_aa),dtype=np.complex_)\n ab = np.zeros((N_ab,N_ab),dtype=np.complex_)\n bb = np.zeros((N_bb,N_bb),dtype=np.complex_)\n for ni,I in enumerate(aa_basis):\n for nj,J in enumerate(aa_basis):\n ind = tuple(I+J)\n aa[ni,nj]+= self.rdm[ind]\n for ni,I in enumerate(ab_basis):\n for nj,J in enumerate(ab_basis):\n ind = tuple(I+J)\n ab[ni,nj]+= self.rdm[ind]\n for ni,I in enumerate(bb_basis):\n for nj,J in enumerate(bb_basis):\n ind = tuple(I+J)\n bb[ni,nj]+= self.rdm[ind]\n aa_eig = np.linalg.eigvalsh(aa)\n ab_eig = np.linalg.eigvalsh(ab)\n bb_eig = np.linalg.eigvalsh(bb)\n print('Analysis of 2-RDM')\n print('---------------------------------')\n print('AA basis: ')\n print(aa_basis)\n print('alpha-alpha block: ')\n print(aa)\n print('eigenvalues: ')\n print(aa_eig)\n print('---------------------------------')\n print('BB basis: ')\n print(bb_basis)\n print('beta-beta block: ')\n print(bb)\n print('eigenvalues: ')\n print(bb_eig)\n print('---------------------------------')\n print('AB basis: ')\n print(ab_basis)\n print('alpha-beta block: ')\n if split:\n print('real: ')\n print(np.real(ab))\n print('imaginary')\n print(np.imag(ab))\n else:\n print(ab)\n print('eigenvalues: ')\n print(ab_eig)\n print('Analysis of 1-RDM and local properties')\n a1 = np.zeros((len(self.alp),len(self.alp)),dtype=np.complex_)\n b1 = np.zeros((len(self.alp),len(self.alp)),dtype=np.complex_)\n rdm1 = self.reduce_order()\n for ni,I in enumerate(self.alp):\n for nj,J in enumerate(self.alp):\n ind = tuple([I,J])\n a1[ni,nj]+= rdm1.rdm[ind]\n for ni,I in enumerate(self.bet):\n for nj,J in enumerate(self.bet):\n ind = tuple([I,J])\n b1[ni,nj]+= rdm1.rdm[ind]\n print('---------------------------------')\n print('alpha block: ')\n print(a1)\n print('eigenvalues: ')\n print(np.linalg.eigvalsh(a1))\n a_eig = np.linalg.eigvalsh(a1)\n print('---------------------------------')\n print('beta block: ')\n print(b1)\n print('eigenvalues: ')\n print(np.linalg.eigvalsh(b1))\n b_eig = np.linalg.eigvalsh(b1)\n return aa_eig,bb_eig,ab_eig,a_eig,b_eig\n elif self.p==1:\n print('Analysis of 1-RDM and local properties')\n a1 = np.zeros((len(self.alp),len(self.alp)),dtype=np.complex_)\n b1 = np.zeros((len(self.alp),len(self.alp)),dtype=np.complex_)\n for ni,I in enumerate(self.alp):\n for nj,J in enumerate(self.alp):\n ind = tuple([I,J])\n a1[ni,nj]+= self.rdm[ind]\n for ni,I in enumerate(self.bet):\n for nj,J in enumerate(self.bet):\n ind = tuple([I,J])\n b1[ni,nj]+= self.rdm[ind]\n print('---------------------------------')\n print('alpha block: ')\n print(a1)\n print('eigenvalues: ')\n print(np.linalg.eigvalsh(a1))\n print('---------------------------------')\n print('beta block: ')\n print(b1)\n print('eigenvalues: ')\n print(np.linalg.eigvalsh(b1))\n pass\n\n def copy(self):\n nRDM = RDM(\n order=self.p,\n alpha=self.alp,\n beta=self.bet,\n state=None,\n S=self.S,\n Ne=self.Ne,\n )\n nRDM.rdm = self.rdm.copy()\n return nRDM\n\n def observable(self,H):\n self.contract()\n en = np.dot(H,self.rdm).trace()\n self.expand()\n return en\n\n def trace(self):\n try:\n self.rdm.trace()[0,0]\n self.switch()\n test= self.rdm.trace()\n self.switch()\n except Exception as e:\n test = self.rdm.trace()\n return test\n\n # get trace of RDM\n\n def __add__(self,rdm):\n if type(rdm)==type(self):\n pass\n else:\n print('Trying to add a {} to a RDM, '.format(str(type(rdm))))\n sys.exit('wrong type specified.')\n c1, c2 = self.Ne==rdm.Ne,self.alp==rdm.alp\n c3, c4 = self.bet==rdm.bet,self.p==rdm.p\n if c1+c2+c3+c4<4:\n print('Checks: ')\n print('Ne: {}, alp: {}, bet: {}'.format(c1,c2,c3))\n traceback.print_exc()\n print('Error in adding.')\n sys.exit('You have RDMs for different systems apparently.')\n nRDM = RDM(\n order=self.p,\n alpha=self.alp,\n beta=self.bet,\n S=self.S,\n state=None,\n Ne=self.Ne,\n )\n self.expand()\n rdm.expand()\n nRDM.rdm = self.rdm+rdm.rdm\n return nRDM\n\n def reduce_order(self):\n nRDM = RDM(\n order=self.p-1,\n alpha=self.alp,\n beta=self.bet,\n state=None,\n Ne=self.Ne,\n S=self.S,\n )\n self.expand()\n if self.p==3:\n for i in range(0,self.r):\n for j in range(0,self.r):\n for k in range(0,self.r):\n for l in range(0,self.r):\n i1 = tuple([i,j,k,l])\n for x in range(0,self.r):\n i2 = tuple([i,j,x,k,l,x])\n nRDM.rdm[i1]+=self.rdm[i2]\n elif self.p==2:\n for i in range(0,self.r):\n for j in range(0,self.r):\n i1 = tuple([i,j])\n for x in range(0,self.r):\n i2 = tuple([i,x,j,x])\n nRDM.rdm[i1]+=self.rdm[i2]\n nRDM.rdm*=(1/(self.Ne-self.p+1))\n return nRDM\n\n def __sub__(self,rdm):\n if type(rdm)==type(self):\n pass\n else:\n print('Trying to sub a {} to a RDM, '.format(str(type(rdm))))\n sys.exit('wrong type specified.')\n c1, c2 = self.Ne==rdm.Ne,self.alp==rdm.alp\n c3, c4 = self.bet==rdm.bet,self.p==rdm.p\n if c1+c2+c3+c4<4:\n print('Checks: ')\n print('Ne: {}, alp: {}, bet: {}'.format(c1,c2,c3))\n print(self.S,rdm.S)\n print('Error in subtracting.')\n traceback.print_exc()\n sys.exit('You have RDMs for different systems apparently.')\n nRDM = RDM(\n order=self.p,\n alpha=self.alp,\n beta=self.bet,\n state=None,\n Ne=self.Ne,\n )\n self.expand()\n rdm.expand()\n nRDM.expand()\n nRDM.rdm = self.rdm-rdm.rdm\n return nRDM\n\n\n def __mul__(self,rdm):\n if type(rdm)==type(self):\n pass\n elif type(rdm) in [type(1),type(0),type(0.5)]:\n self.rdm = self.rdm*rdm\n return self\n self.expand()\n rdm.expand()\n c1, c2 = self.Ne==rdm.Ne,self.alp==rdm.alp\n c3, c4 = self.bet==rdm.bet,self.Ne==rdm.Ne\n if c1+c2+c3+c4<4:\n print('Checks: ')\n print(c1,c2,c3,c4)\n traceback.print_exc()\n print('Error in multiplication.')\n sys.exit('You have RDMs for different systems apparently.')\n nRDM = RDM(\n order=self.p+rdm.p,\n alpha=self.alp,\n beta=self.bet,\n state=None,\n Ne=self.Ne,\n S=self.S,\n )\n non1 = list((np.nonzero(self.rdm)))\n non2 = list((np.nonzero(rdm.rdm)))\n cr1 = np.asarray(non1[:len(non1)//2])\n cr2 = np.asarray(non2[:len(non2)//2])\n an1 = np.asarray(non1[len(non1)//2:])\n an2 = np.asarray(non2[len(non2)//2:])\n CreTerms = []\n AnnTerms = []\n for i in range(cr1.shape[1]):\n c = cr1[:,i]\n for j in range(cr2.shape[1]):\n s = cr2[:,j]\n dup=False\n for x in c:\n if x in s:\n dup=True\n newCre = list(np.concatenate((c,s)))\n for i in range(len(newCre)-1):\n if newCre[i]>newCre[i+1]:\n dup=True\n if newCre in CreTerms:\n dup=True\n if dup:\n continue\n CreTerms.append(newCre)\n for k in range(an1.shape[1]):\n a = an1[:,k]\n for j in range(an2.shape[1]):\n t = an2[:,j]\n dup=False\n for x in a:\n if x in t:\n dup=True\n newAnn=list(np.concatenate((a,t)))\n for l in range(len(newAnn)-1):\n if newAnn[l]>newAnn[l+1]:\n dup=True\n if newAnn in AnnTerms:\n dup=True\n if dup:\n continue\n AnnTerms.append(newAnn)\n for i in CreTerms:\n antiSymmCre = Recursive(choices=i)\n antiSymmCre.unordered_permute()\n for j in AnnTerms:\n antiSymmAnn = Recursive(choices=j)\n antiSymmAnn.unordered_permute()\n # need to calculate term\n sumTerms = 0\n for cre in antiSymmCre.total:\n for ann in antiSymmAnn.total:\n ind1 = tuple(cre[:self.p]+ann[:self.p])\n ind2 = tuple(cre[self.p:-1]+ann[self.p:-1])\n Term = (self.rdm[ind1]*rdm.rdm[ind2])\n Term*= cre[-1]*ann[-1]\n sumTerms+= Term\n #sumTerms*=(len(antiSymmCre.total))**-1\n sumTerms*=(len(antiSymmCre.total)*len(antiSymmAnn.total))**-(1)\n sumTerms*=((factorial(self.p+rdm.p))/(\n factorial(self.p)*factorial(rdm.p)))\n for cre in antiSymmCre.total:\n for ann in antiSymmAnn.total:\n indN = tuple(cre[:-1]+ann[:-1])\n sign = cre[-1]*ann[-1]\n #print(indN,sign)\n nRDM.rdm[indN]=sumTerms*sign\n return nRDM\n # wedge product\n\n\n def get_spin_properties(self):\n if self.p==3:\n pass\n elif self.p==2:\n rdm1 = self.reduce_order()\n self.sz = rdmf.Sz(\n rdm1.rdm,\n self.alp,\n self.bet,\n self.s2s)\n self.s2 = rdmf.S2(\n self.rdm,\n rdm1.rdm,\n self.alp,\n self.bet,\n self.s2s)\n\n def get_overlap(self,rdm):\n\n c1, c2 = self.Ne==RDM.Ne,self.alp==RDM.alp\n c3, c4 = self.bet==RDM.bet,self.S==RDM.S\n if not (c1 and c2 and c3 and c4):\n print('Hrm.')\n\n t = self.Ne*(self.Ne-1)\n if self.Ne%2==0:\n coeff = 2*t*(1-self.Ne/(t*self.r**2))\n else:\n coeff = 2*t*(1-(self.Ne-1)/(t*self.r**2))\n self.contract()\n test = self.rdm-RDM.rdm\n\n eigs = np.sqrt(\n np.sum(\n np.abs(\n np.linalg.eigvalsh(\n np.dot(\n test,test.T\n )\n )\n )/coeff\n )\n )\n return np.real(eigs)\n\n def _build_hf_singlet(self):\n '''\n build a p-RDM that comes from a single determinant\n '''\n self.rdm = np.zeros(\n tuple([self.r for i in range(2*self.p)]),dtype=np.complex_)\n occAlp = self.alp[:self.N_alp]\n occAlp = [i for i in occAlp]\n occBet = self.bet[:self.N_bet]\n occBet = [i for i in occBet]\n Rec = Recursive(depth=self.p,choices=occAlp+occBet)\n Rec.permute()\n self.total=Rec.total\n for creInd in self.total:\n #annInd = creInd[::-1]\n annInd = creInd[:]\n annPerm = Recursive(choices=annInd)\n annPerm.unordered_permute()\n crePerm = Recursive(choices=creInd)\n crePerm.unordered_permute()\n for c in crePerm.total:\n for a in annPerm.total:\n s = c[-1]*a[-1]\n ind = tuple(c[:-1]+a[:-1])\n self.rdm[ind]=s\n\n def _build_hf_doublet(self):\n '''\n build a p-RDM that comes from a single determinant,\n but with S neq 0\n '''\n self.rdm = np.zeros(\n tuple([self.r for i in range(2*self.p)]),dtype=np.complex_)\n occAlp = self.alp[:int((self.Ne+self.S)//2)]\n occBet = self.bet[:int((self.Ne-self.S)//2)]\n Rec = Recursive(depth=self.p,choices=occAlp+occBet)\n Rec.permute()\n self.total=Rec.total\n for creInd in self.total:\n #annInd = creInd[::-1]\n annInd = creInd[:]\n annPerm = Recursive(choices=annInd)\n annPerm.unordered_permute()\n crePerm = Recursive(choices=creInd)\n crePerm.unordered_permute()\n for c in crePerm.total:\n for a in annPerm.total:\n s = c[-1]*a[-1]\n ind = tuple(c[:-1]+a[:-1])\n self.rdm[ind]=s#*(1/factorial(self.p))\n\n\n def cumulant(self):\n if self.p==2:\n rdm1 = self.reduce_order()\n rdm2 = rdm1*rdm1\n return self-rdm2\n\n def get_G_matrix(self):\n if not self.p==2:\n sys.exit('Not order 2 g matrix.')\n if not self.dqg=='d':\n sys.exit('Getting G from non-2RDM!.')\n self.expand()\n new = np.zeros(self.rdm.shape,dtype=np.complex_)\n d1 = self.reduce_order()\n for i in range(self.r):\n for j in range(self.r):\n for k in range(self.r):\n for l in range(self.r):\n delta = (k==l)\n new[i,l,j,k]+= -self.rdm[i,k,j,l]+delta*d1.rdm[i,j]\n nRDM = RDM(\n order=self.p,\n alpha=self.alp,\n beta=self.bet,\n state='given',\n Ne=self.Ne,\n rdm=new,\n rdm_type='g',\n )\n return nRDM\n\n def get_Q_matrix(self):\n if not self.p==2:\n sys.exit('Not order 2 g matrix.')\n if not self.dqg=='d':\n sys.exit('Getting Q from non-2RDM!.')\n self.expand()\n new = np.zeros(self.rdm.shape,dtype=np.complex_)\n d1 = self.reduce_order()\n for i in range(self.r):\n for j in range(self.r):\n ij = (i==j)\n for k in range(self.r):\n ik,jk = (i==k),(j==k)\n for l in range(self.r):\n il,jl,kl = (i==l),(j==l),(k==l)\n new[j,l,i,k]+= self.rdm[i,k,j,l]\n new[j,l,i,k]+= -il*jk\n new[j,l,i,k]+= il*d1.rdm[k,j]\n new[j,l,i,k]+= -kl*d1.rdm[i,j]\n new[j,l,i,k]+= jk*d1.rdm[i,l]\n new[j,l,i,k]+= -ij*d1.rdm[k,l]\n new[j,l,i,k]+= kl*ij\n nRDM = RDM(\n order=self.p,\n alpha=self.alp,\n beta=self.bet,\n state='given',\n Ne=self.Ne,\n rdm=new,\n rdm_type='q',\n )\n return nRDM\n\n\n def reconstruct(self,\n approx='V',\n method='cumulant',):\n if self.p==2 and self.Ne<3:\n nRDM = RDM(\n order=self.p+1,\n alpha=self.alp,\n beta=self.bet,\n state=None,\n Ne=self.Ne,\n S=self.S,\n )\n return nRDM\n if not method=='cumulant':\n sys.exit('Can\\'t perform non-cumulant reconstruction.')\n if self.p==2:\n self.expand()\n rdm1 = self.reduce_order()\n if approx in ['v','V','valdemoro','Valdemoro']:\n rdm3a = rdm1*rdm1*rdm1\n rdm2w = self-rdm1*rdm1\n rdm3b = (rdm2w*rdm1)*3\n rdm3 = rdm3a + rdm3b\n return rdm3\n elif self.p==1:\n rdm = self*self\n return rdm\n\n def switch(self):\n size = len(self.rdm.shape)\n if size==2 and not self.p==1:\n self.expand()\n else:\n self.contract()\n \n def contract(self):\n size = len(self.rdm.shape)\n if not self.p==1:\n self.rdm = np.reshape(\n self.rdm,\n (\n self.r**self.p,\n self.r**self.p\n )\n )\n \n def expand(self):\n size = len(self.rdm.shape)\n if not self.p==1:\n self.rdm = np.reshape(\n self.rdm,\n (tuple([self.r for i in range(2*self.p)]))\n )\n\nclass Recursive:\n def __init__(self,\n depth='default',\n choices=[],\n ):\n if depth=='default':\n depth=len(choices)\n self.depth=depth\n self.total=[]\n self.choices = list(choices)\n\n def choose(self,choices='default',temp=[]):\n '''\n recursive function to give different choices? \n '''\n if choices=='default':\n choices=self.choices\n done=True\n for c in choices:\n if not len(c)==0:\n done=False\n break\n if done:\n self.total.append(temp)\n else:\n for n,i in enumerate(choices):\n for m in reversed(range(len(i))):\n nc = copy(choices)\n j = nc[n].pop(m)\n self.choose(nc,temp=temp[:]+[j])\n \n def simplify(self):\n '''\n\n '''\n new = []\n for i in self.total:\n r = ''.join(i)\n if r in new:\n pass\n else:\n new.append(r)\n self.total = new\n\n def permute(self,d='default',temp=[]):\n '''\n chooses d number of options from the choices, and returns \n and ordered list of choices (01,02,03,12,13,23,etc.)\n '''\n if d=='default':\n d = self.depth\n if d==0:\n self.total.append(temp)\n else:\n for i in self.choices:\n if len(temp)==0:\n self.permute(d-1,temp[:]+[i])\n elif i>temp[-1]:\n self.permute(d-1,temp[:]+[i])\n\n def unordered_permute(self,d='default',temp=[],choices=[1],s=1):\n if d=='default':\n d = self.depth\n if d==0 and len(choices)==0:\n temp.append(s)\n self.total.append(temp)\n else:\n if len(temp)==0:\n for n,i in enumerate(self.choices):\n s=(-1)**n\n choices = self.choices.copy()\n choices.pop(n)\n self.unordered_permute(d-1,temp[:]+[i],choices,s)\n temp=[]\n else:\n for n,j in enumerate(choices):\n s*=(-1)**n\n tempChoice = choices.copy()\n tempChoice.pop(n)\n self.unordered_permute(d-1,temp[:]+[j],tempChoice,s)\n\n\ndef build_2rdm(\n wavefunction,\n alpha,beta,\n region='full',\n rdm2=None):\n '''\n Given a wavefunction, and the alpha beta orbitals, will construct the 2RDM\n for a system.\n Note, the output format is for a general two body operator, aT_i, aT_k, a_l, a_j\n i/j are electron 1, and k/l are electron 2\n '''\n def phase_2e_oper(I,K,L,J,det,low=0):\n # very general phase operator - works for ANY i,k,l,j\n # generates new occupation as well as the sign of the phase\n def new_det(i,k,l,j,det):\n # transform old determinant to new\n det=det[:j]+'0'+det[j+1:]\n det=det[:l]+'0'+det[l+1:]\n det=det[:k]+'1'+det[k+1:]\n det=det[:i]+'1'+det[i+1:]\n return det\n def delta(a,b):\n # delta function\n delta =0\n if a==b:\n delta = 1\n return delta\n def det_phase(det,place,start):\n # generate phase of a determinant based on number of occupied orbitals with index =1\n p = 1\n for i in range(start,place):\n if det[i]=='1':\n p*=-1\n return p\n # conditionals for switching orbital orderings\n a1 = (L<=J)\n b1,b2 = (K<=L),(K<=J)\n c1,c2,c3 = (I<=K),(I<=L),(I<=J)\n eps1,eps2,eps3 = 1,1,1\n if a1%2==1: #i.e., if JL, K>J\n eps2=-1\n if (c1+c2+c3)%2==1: # if I>K,I>L,I>J\n eps3=-1\n t2 = 1-delta(L,J) # making sure L/J, I/K not same orbital\n t1 = 1-delta(I,K)\n t7 = eps1*eps2*eps3 \n d1 = delta(I,L) \n d2 = delta(I,J)\n d3 = delta(K,L)\n d4 = delta(K,J)\n kI = int(det[I]) # occupation of orbitals\n kK = int(det[K])\n kL = int(det[L])\n kJ = int(det[J])\n pI = det_phase(det,I,start=low)\n pK = det_phase(det,K,start=low)\n pL = det_phase(det,L,start=low)\n pJ = det_phase(det,J,start=low)\n t6 = pJ*pL*pK*pI\n t5 = kL*kJ # if 0, then we have a problem\n t3 = d1+d2+1-kI # IL or IJ are the same, and I is already occupied - if I is occupied and not I=J, or I=L, then 0\n t4 = d3+d4+1-kK # same as above, for K and K/L, K/J\n Phase = t1*t2*t3*t4*t5*t6*t7\n ndet = new_det(I,K,L,J,det)\n return Phase,ndet\n #\n # First, alpha alpha 2-RDM, by selecting combinations only within alpha\n #\n wf = wavefunction\n if region=='full':\n norb = len(alpha['inactive']+alpha['virtual']+alpha['active'])\n norb+= len(beta['virtual']+beta['inactive']+beta['active'])\n alpha = alpha['inactive']+alpha['active']\n beta = beta['inactive']+beta['active']\n rdm2 = np.zeros((norb,norb,norb,norb),dtype=np.complex_)\n elif region=='active':\n ai = set(alpha['inactive'])\n bi = set(beta['inactive'])\n alpha = alpha['inactive']+alpha['active']\n beta = beta['inactive']+beta['active']\n for i in alpha:\n for k in alpha:\n if (i= i:\n dp[i] = True\n break\n return dp[-1]\n\n\n# Approach 4: Greedy\n\n# Once we have our code in the bottom-up state, we can make one final, important observation.\n# rom a given position, when we try to see if we can jump to a GOOD position, we only ever use\n# one - the first one (see the break statement). In other words, the left-most one. If we keep\n# track of this left-most GOOD position as a separate variable, we can avoid searching for it\n# in the array. Not only that, but we can stop using the array altogether.\n\n# Iterating right-to-left, for each position we check if there is a potential jump that reaches\n# a GOOD index (currPosition + nums[currPosition] >= leftmostGoodIndex). If we can reach a GOOD\n# index, then our position is itself GOOD. Also, this new GOOD position will be the new leftmost\n# GOOD index. Iteration continues until the beginning of the array. If first position is a GOOD\n# index then we can reach the last index from the first position.\n\n# To illustrate this scenario, we will use the diagram below, for input array nums =\n# [9, 4, 2, 1, 0, 2, 0]. We write G for GOOD, B for BAD and U for UNKNOWN. Let's assume we have\n# iterated all the way to position 0 and we need to decide if index 0 is GOOD. Since index 1 was\n# determined to be GOOD, it is enough to jump there and then be sure we can eventually reach index 6.\n# It does not matter that nums[0] is big enough to jump all the way to the last index. All we need is one way.\n\n# Index\t0\t1\t2\t3\t4\t5\t6\n# nums\t9\t4\t2\t1\t0\t2\t0\n# memo\tU\tG\tB\tB\tB\tG\tG\n\n\ndef canJumpGreedy(nums):\n lastPos = len(nums) - 1\n for i in range(len(nums) - 1, -1, -1):\n if i + nums[i] >= lastPos:\n lastPos = i\n return lastPos == 0\n\n\ndef canJump(nums):\n curr_max = 0\n for i in range(len(nums)):\n if i > curr_max:\n return False\n curr_max = max(curr_max, i + nums[i])\n return True\n\n\nprint(canJumpDP([2, 3, 1, 1, 4])) # true\nprint(canJumpDP([3, 2, 1, 0, 4])) # false\nprint(canJumpGreedy([2, 3, 1, 1, 4])) # true\nprint(canJumpGreedy([3, 2, 1, 0, 4])) # false\nprint(canJump([2, 3, 1, 1, 4])) # true\nprint(canJump([3, 2, 1, 0, 4])) # false\n","sub_path":"DynamicProgramming/JumpGame.py","file_name":"JumpGame.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"119846933","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ccpl\",\n version=\"0.2.1\",\n author=\"Rainbow Doge\",\n author_email=\"realrainbowdoge@gmail.com\",\n description=\"ColorfulCore Python Library - CCPL for short.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"http://www.jakubwilk.me\",\n packages=setuptools.find_packages(),\n install_requires = ['pytube','bs4','requests','os'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)","sub_path":"pypi_install_script/ccpl-0.2.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"330167643","text":"from typing import List\n\n\nclass Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n length = len(nums)\n dictionary = {}\n\n for i in range(length):\n if nums[i] in dictionary:\n dictionary[nums[i]].append(i)\n else:\n dictionary[nums[i]] = [i]\n\n for key in dictionary.keys():\n current_element = dictionary[key]\n current_length = len(current_element)\n if current_length > 1:\n for i in range(1, current_length):\n if (current_element[i] - current_element[i - 1]) <= k:\n return True\n\n return False","sub_path":"Week-06/Day-24/ContainsDuplicateII.py","file_name":"ContainsDuplicateII.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171849529","text":"# Connects to running libreoffice instance, opens doc, gets range \n# and evaluates function. To run libreoffice instance:\n# $ libreoffice --accept=\"socket,host=localhost,port=2002;urp;\" --headless\n\nimport sys\nimport os.path\nimport uno\nfrom com.sun.star.beans import PropertyValue\nfrom com.sun.star.uno import Exception as UnoException\n\ntotal_args = len(sys.argv)\ncmdargs = str(sys.argv)\nif total_args < 2:\n print(\"please choose a file\")\n sys.exit(1);\n\nfile_name = sys.argv[1]\nfile_url = uno.systemPathToFileUrl(os.path.abspath(file_name))\nurl = \"uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext\"\n\nctxLocal = uno.getComponentContext()\nsmgrLocal = ctxLocal.ServiceManager\nresolver = smgrLocal.createInstanceWithContext(\"com.sun.star.bridge.UnoUrlResolver\", ctxLocal)\n\nctx = resolver.resolve(url)\nsmgr = ctx.ServiceManager\n\ndesktop = smgr.createInstanceWithContext(\"com.sun.star.frame.Desktop\", ctx)\ninProps = PropertyValue(\"Hidden\", 0, True, 0),\ndoc = desktop.loadComponentFromURL(file_url, \"_blank\", 0, inProps)\n\nif not doc:\n raise UnoException(\"can't open doc\", None)\n sys.exit(1)\n\nsheet = doc.getSheets().getByIndex(0)\nif not sheet:\n raise UnoException(\"no sheet 0 in doc\", None)\n sys.exit(1)\n\ncursor = sheet.createCursor()\ncursor.gotoEndOfUsedArea(False)\nrangeaddress = cursor.getRangeAddress()\nlast_row = rangeaddress.EndRow\ncolumn = \"H\"\n\ncell_range = sheet.getCellRangeByName(\"{0}{1}:{2}{3}\".format(column, 1, column, last_row + 1))\nsum_enum = 2 # ~ https://www.openoffice.org/api/docs/common/ref/com/sun/star/sheet/GeneralFunction.html#SUM\n\nval = cell_range.computeFunction(sum_enum)\nprint(abs(int(val)))\nsys.exit(0)\n","sub_path":"libreoffice/getRangeSum.py","file_name":"getRangeSum.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"572220387","text":"import sys\nimport rrdtool\nimport time\nfrom Notify import *\n\n\n\n\ndef linebase(tiempo_inicial,tiempo_final,val_max,imagepath,pathrrd):\n #extrae la informacion del ultimo dato en net3.rrd\n #ultima_lectura = int(rrdtool.last(\"netPr.rrd\"))\n val_max=100 #Valor de procesamiento maximo del CPU\n val_desv=5.70 #Valor de la desviacion estandar\n val_def= 60 #Valor a monitorear del CPU\n \n imagepath=imagepath+\"Libase.png\"\n ret = rrdtool.graphv(imagepath,\n \"--start\",str(tiempo_inicial),\n \"--end\",str(tiempo_final),\n \"--vertical-label=Porcentraje uso CPU\",\n \"--lower-limit\", \"0\", #Valor menor a graficar\n \"--upper-limit\", \"100\", #Valor maximo a graficar\n \"DEF:entrada=\"+str(pathrrd)+\":cpu:AVERAGE\", #Promedio de inoctets\n #\"DEF:outoctets=net3.rrd:outoctets:AVERAGE\", #Promedio de outoctets\n #Escalar valores a graficar de inoctets\n \"CDEF:entrada5=entrada,\"+str(val_max)+\",GT,0,entrada,IF\", #Definimos el valor maximo\n \"VDEF:entradaMAX=entrada,MAXIMUM\", #Obtiene el val maximo de entrada\n \"VDEF:entradaMIN=entrada,MINIMUM\", #Obtiene el val minimo de entrada\n \"VDEF:entradaSTDEV=entrada,STDEV\", #Obtiene el val stdev de entrada\n \"VDEF:entradaLAST=entrada,LAST\", #Obtiene el val last de entrada\n \"AREA:entrada#00FF00:Uso de CPU\", #Etiqueta entrada\n \"HRULE:\"+str(val_max)+\"#FF0000:Umbral 1\", #Etiqueta umbral\n \"HRULE:\"+str(val_def)+\"#0000FF:Umbral 2\",\n \"HRULE:\"+str(val_desv)+\"#0000FF:Umbral 3\",\n \"GPRINT:entradaMAX:%6.2lf %SMAX\", #Etiqueta val max\n \"GPRINT:entradaMIN:%6.2lf %SMIN\", #Etiqueta val min\n \"GPRINT:entradaSTDEV:%6.2lf %SSTDEV\", #Etiqueta stdev\n \"GPRINT:entradaLAST:%6.2lf %SLAST\" ) \n lista=[]\n lista=list(ret.items())\n max=str(lista[16])\n min=str(lista[18])\n print(max , min)\n if max.find(str(val_def))>=0: #Comparamos si sobre pasa el val_max\n print (\"El valor sobrepasa\",max)\n #Envio de correo\n send_alert_attached(\"Los valores del CPU sobreapasan al \"+str(val_def)+ \" con un valor de : \"+max,imagepath)\n #Si el valor minimo es menor que la desviacion estandard\n if min.find(str(val_desv))>=0:\n print(\"El valor es minimo\")\n send_alert_attached(\"Los valores del CPU son menores a \"+str(val_desv)+ \" con un valor de : \"+min,imagepath)\n","sub_path":"Redes3/Evaluacion2/Admin_Red2/lineaBase.py","file_name":"lineaBase.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527996875","text":"__author__ = 'alexander'\n\nfrom src.utils.simulation_object import SimulationObject\nimport simpy\n\n\nclass ExternalLine(SimulationObject):\n def __init__(self, env, ats_pipe):\n super(ExternalLine, self).__init__(env, None)\n\n self.occupied = None\n self.interrupt_event = env.event()\n\n self.input_pipe = simpy.Store(self.env)\n self.ats_pipe = ats_pipe\n\n def start(self):\n self.env.process(self.work())\n\n def work(self):\n call = yield self.input_pipe.get()\n # print('call thought external line')\n self.occupied = call\n yield self.env.timeout(call.duration) | self.interrupt_event\n self.occupied = None\n\n def interrupt(self):\n # print('call was interrupt /\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/')\n self.interrupt_event.succeed()\n self.interrupt_event = self.env.event()\n","sub_path":"src/models/external_line.py","file_name":"external_line.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"362699423","text":"from keras.models import Sequential\r\nfrom keras.layers.core import Dense\r\nimport Population\r\n\r\ndef build_model():\r\n num_inputs = 4\r\n hidden_nodes = 16\r\n num_outputs = 3\r\n\r\n model = Sequential()\r\n model.add(Dense(hidden_nodes, activation='relu', input_dim=num_inputs))\r\n model.add(Dense(num_outputs, activation='softmax'))\r\n model.compile(loss='mse', optimizer='adam')\r\n return model\r\n\r\nif __name__ == '__main__':\r\n pop_size = 50\r\n mutation_rate = 0.05\r\n mutation_scale = 0.3\r\n starting_cash = 1\r\n trading_fee = 0\r\n\r\n prices = [\r\n 4,\r\n 3,\r\n 2,\r\n 1,\r\n 5,\r\n 6\r\n ]\r\n\r\n inputs = [\r\n [-0.2, 0.2, 0.4, -0.5],\r\n [-0.2, 0.1, 0.4, -0.1],\r\n [-0.2, 0.2, 0.4, -0.2],\r\n [-0.2, 0.3, 0.3, -0.3],\r\n [0.4, -0.9, -0.3, 0.1],\r\n [0.8, -0.6, -0.5, 0.1]\r\n ]\r\n\r\n pop = Population.Population(pop_size, build_model, mutation_rate, mutation_scale, starting_cash, prices[0], trading_fee)\r\n\r\n while True:\r\n # for i in range(1):\r\n pop.evolve(inputs, prices)","sub_path":"evolution.py","file_name":"evolution.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"324363200","text":"from taskw_gcal_sync import GenericSide\n\nfrom google.auth.transport.requests import Request\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient import discovery\nfrom googleapiclient.http import HttpError\nfrom overrides import overrides\n\nfrom typing import Any, Union\nimport datetime\nimport dateutil\nimport operator\nimport os\nimport pickle\nimport pkg_resources\nimport re\n\n\nclass GCalSide(GenericSide):\n \"\"\"GCalSide interacts with the Google Calendar API.\n\n\n Adds, removes, and updates events on Google Calendar. Also handles the\n OAuth2 user authentication workflow.\n \"\"\"\n\n SCOPES = [\"https://www.googleapis.com/auth/calendar\"]\n _datetime_format = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n _date_format = \"%Y-%m-%d\"\n\n def __init__(self, **kargs):\n super(GCalSide, self).__init__()\n\n # set the default properties\n self.config = {\n \"calendar_summary\": \"TaskWarrior Reminders\",\n \"calendar_id\": None,\n \"client_secret_file\": pkg_resources.resource_filename(\n \"taskw_gcal_sync\", os.path.join(\"res\", \"gcal_client_secret.json\")\n ),\n \"credentials_cache\": os.path.join(\n os.path.expanduser(\"~\"), \".gcal_credentials.pickle\"\n ),\n # on calendarList.get() it also returns the cancelled/deleted items\n \"ignore_cancelled\": True,\n }\n self.config.update(kargs)\n\n # If you modify this, delete your previously saved credentials\n self.service = None\n\n @overrides\n def start(self):\n # connect\n self.logger.info(\"Connecting...\")\n self.gain_access()\n self.config[\"calendar_id\"] = self._fetch_cal_id_from_summary(\n self.config[\"calendar_summary\"]\n )\n # Create calendar if not there\n if not self.config[\"calendar_id\"]:\n self.logger.info('Creating calendar \"%s\"' % self.config[\"calendar_summary\"])\n new_cal = {\"summary\": self.config[\"calendar_summary\"]}\n ret = self.service.calendars().insert(body=new_cal).execute()\n self.logger.info(\"Created, id: %s\" % ret[\"id\"])\n self.config[\"calendar_id\"] = ret[\"id\"]\n self.logger.info(\"Connected.\")\n\n def _fetch_cal_id_from_summary(self, cal_summary: str):\n \"\"\"Return the id of the Calendar based on the given Summary.\n\n :returns: id or None if that was not found\n \"\"\"\n res = self.service.calendarList().list().execute()\n calendars_list = res.get(\"items\", None) # list(dict)\n assert calendars_list and isinstance(calendars_list, list)\n\n matching_calendars = [\n c[\"id\"] for c in calendars_list if c[\"summary\"] == self.config[\"calendar_summary\"]\n ]\n\n if matching_calendars:\n assert len(matching_calendars) == 1, \"Too many calendars match!\"\n ret = matching_calendars[0]\n else:\n ret = None\n return ret\n\n @overrides\n def get_all_items(self, **kargs):\n \"\"\"Get all the events for the calendar that we use.\n\n :param kargs: Extra options for the call\n \"\"\"\n # Get the ID of the calendar of interest\n\n if kargs:\n self.logger.warn(\n \"Extra arguments in get_all_items call are not supported yet, ignoring them: {}\".format(\n kargs\n )\n )\n\n events = []\n request = self.service.events().list(calendarId=self.config[\"calendar_id\"])\n\n # Loop until all pages have been processed.\n while request is not None:\n # Get the next page.\n response = request.execute()\n # Accessing the response like a dict object with an 'items' key\n # returns a list of item objects (events).\n for event in response.get(\"items\", []):\n events.append(event)\n\n # Get the next request object by passing the previous request\n # object to the list_next method.\n request = self.service.events().list_next(request, response)\n\n return events\n\n @overrides\n def get_single_item(self, _id: str) -> Union[dict, None]:\n try:\n ret = (\n self.service.events()\n .get(calendarId=self.config[\"calendar_id\"], eventId=_id)\n .execute()\n )\n if ret[\"status\"] == \"cancelled\":\n ret = None\n except HttpError:\n ret = None\n finally:\n return ret\n\n @overrides\n def update_item(self, item_id, **changes):\n GCalSide._sanitize_all_datetimes(changes)\n\n # Check if item is there\n event = (\n self.service.events()\n .get(calendarId=self.config[\"calendar_id\"], eventId=item_id)\n .execute()\n )\n event.update(changes)\n self.service.events().update(\n calendarId=self.config[\"calendar_id\"], eventId=event[\"id\"], body=event\n ).execute()\n\n @overrides\n def add_item(self, item) -> dict:\n GCalSide._sanitize_all_datetimes(item)\n event = (\n self.service.events()\n .insert(calendarId=self.config[\"calendar_id\"], body=item)\n .execute()\n )\n self.logger.debug('Event created: \"%s\"' % event.get(\"htmlLink\"))\n\n return event\n\n @overrides\n def delete_single_item(self, item_id) -> None:\n self.service.events().delete(\n calendarId=self.config[\"calendar_id\"], eventId=item_id\n ).execute()\n\n def _get_credentials_file(self):\n \"\"\"Return the path to the credentials file.\n\n Useful method for running this script from an arbitrary dir.\n \"\"\"\n script_dir = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(script_dir, self.config[\"client_secret_file\"])\n\n def _get_credentials(self):\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n :return: Credentials, the obtained credentials.\n \"\"\"\n\n creds = None\n credentials_cache = self.config[\"credentials_cache\"]\n if os.path.isfile(credentials_cache):\n with open(credentials_cache, \"rb\") as token:\n creds = pickle.load(token)\n\n if not creds or not creds.valid:\n self.logger.info(\"Invalid credentials. Fetching them...\")\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n client_secret = pkg_resources.resource_filename(\n __name__, os.path.join(\"res\", \"gcal_client_secret.json\")\n )\n flow = InstalledAppFlow.from_client_secrets_file(\n client_secret, GCalSide.SCOPES\n )\n creds = flow.run_local_server()\n # Save the credentials for the next run\n with open(credentials_cache, \"wb\") as token:\n pickle.dump(creds, token)\n else:\n self.logger.info(\"Using already cached credentials...\")\n\n return creds\n\n def gain_access(self):\n creds = self._get_credentials()\n self.service = discovery.build(\"calendar\", \"v3\", credentials=creds)\n\n @staticmethod\n def get_date_key(d: dict) -> str:\n \"\"\"\n Get key corresponding to date -> 'date' or 'dateTime'\n \"\"\"\n assert (\n \"dateTime\" in d.keys() or \"date\" in d.keys()\n ), \"None of the required keys is in the dictionary\"\n return \"date\" if d.get(\"date\", None) else \"dateTime\"\n\n @staticmethod\n def get_event_time(item: dict, t: str) -> datetime.datetime:\n \"\"\"\n Return the start/end datetime in datetime format.\n\n :param t: Time to query, 'start' or 'end'\n \"\"\"\n assert t in [\"start\", \"end\"]\n assert t in item.keys(), \"'end' key not found in item\"\n dt = GCalSide.parse_datetime(item[t][GCalSide.get_date_key(item[t])])\n return dt\n\n @staticmethod\n def format_datetime(dt: datetime.datetime) -> str:\n \"\"\"\n Format a datetime object according to the ISO speicifications containing\n the 'T' and 'Z' separators\n\n Usage::\n\n >>> GCalSide.format_datetime(datetime.datetime(2019, 3, 5, 0, 3, 9, 1234))\n '2019-03-05T00:03:09.001234Z'\n >>> GCalSide.format_datetime(datetime.datetime(2019, 3, 5, 0, 3, 9, 123))\n '2019-03-05T00:03:09.000123Z'\n \"\"\"\n\n assert isinstance(dt, datetime.datetime)\n dt_out = dt.strftime(GCalSide._datetime_format)\n return dt_out\n\n @staticmethod\n def parse_datetime(dt: str) -> datetime.datetime:\n \"\"\"\n Parse datetime given in the GCal format ('T', 'Z' separators).\n\n Usage::\n\n >>> GCalSide.parse_datetime('2019-03-05T00:03:09Z')\n datetime.datetime(2019, 3, 5, 0, 3, 9)\n >>> GCalSide.parse_datetime('2019-03-05')\n datetime.datetime(2019, 3, 5, 0, 0)\n >>> GCalSide.parse_datetime('2019-03-05T00:03:01.1234Z')\n datetime.datetime(2019, 3, 5, 0, 3, 1, 123400)\n >>> GCalSide.parse_datetime('2019-03-08T00:29:06.602Z')\n datetime.datetime(2019, 3, 8, 0, 29, 6, 602000)\n \"\"\"\n\n assert isinstance(dt, str)\n return dateutil.parser.parse(dt).replace(tzinfo=None)\n\n @staticmethod\n def _sanitize_all_datetimes(item: dict) -> None:\n item[\"updated\"] = GCalSide.sanitize_datetime(item[\"updated\"])\n if \"dateTime\" in item[\"start\"]:\n item[\"start\"][\"dateTime\"] = GCalSide.sanitize_datetime(item[\"start\"][\"dateTime\"])\n if \"dateTime\" in item[\"end\"]:\n item[\"end\"][\"dateTime\"] = GCalSide.sanitize_datetime(item[\"end\"][\"dateTime\"])\n\n @staticmethod\n def sanitize_datetime(dt: str) -> str:\n \"\"\"Given a date in str, make sure that the HH:MM:SS is not 00:00:00.\n\n >>> GCalSide.sanitize_datetime('2019-03-08T00:00:00.602Z')\n '2019-03-07T23:59:00.602000Z'\n >>> GCalSide.sanitize_datetime('2019-03-08T00:00:00.0000Z')\n '2019-03-07T23:59:00.000000Z'\n >>> GCalSide.sanitize_datetime('2019-03-08T00:29:06.602Z')\n '2019-03-08T00:29:06.602000Z'\n \"\"\"\n\n dt_dt = GCalSide.parse_datetime(dt)\n if dt_dt.hour == 0 and dt_dt.minute == 0 and dt_dt.second == 0:\n dt_dt -= datetime.timedelta(minutes=1)\n\n return GCalSide.format_datetime(dt_dt)\n\n @staticmethod\n def items_are_identical(item1, item2, ignore_keys=[]) -> bool:\n\n keys = [\n k\n for k in [\n \"created\",\n \"creator\",\n \"description\",\n \"end\",\n \"etag\",\n \"htmlLlink\",\n \"iCalUID\",\n \"kind\",\n \"organizer\",\n \"start\",\n \"summary\",\n \"updated\",\n ]\n if k not in ignore_keys\n ]\n\n return GenericSide._items_are_identical(item1, item2, keys=keys)\n","sub_path":"taskw_gcal_sync/GCalSide.py","file_name":"GCalSide.py","file_ext":"py","file_size_in_byte":11124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49381076","text":"import os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport sentry_sdk\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\nRELEASE_VERSION = '2020.8.9'\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nDJANGO_ROOT = BASE_DIR\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '5boon_secret_key'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nALLOWED_HOSTS = ['*', 'localhost:8000', '127.0.0.1', 'localhost', '5boon.me']\n\nOAUTH2_CLIENT_KEY = '5boon_oauth2_client_key'\n\nAUTH_USER_MODEL = \"users.user\"\n\n# Jet admin 테마\nJET_SIDE_MENU_COMPACT = True\nJET_THEMES = [\n {\n 'theme': '#F08B68', # theme folder name\n 'color': '#F08B68', # color of the theme's button in user menu\n 'title': '#F08B68' # theme title\n },\n {\n 'theme': 'green',\n 'color': '#44b78b',\n 'title': 'Green'\n },\n {\n 'theme': 'light-green',\n 'color': '#2faa60',\n 'title': 'Light Green'\n },\n {\n 'theme': 'light-violet',\n 'color': '#a464c4',\n 'title': 'Light Violet'\n },\n {\n 'theme': 'light-blue',\n 'color': '#5EADDE',\n 'title': 'Light Blue'\n },\n {\n 'theme': 'light-gray',\n 'color': '#222',\n 'title': 'Light Gray'\n }\n]\n\n###############################################################################\n# Logging\n# https://docs.python.org/3/howto/logging.html#configuring-logging\n###############################################################################\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False, # 다른 logger 들 활성\n 'formatters': {\n 'verbose': {\n 'format': '[%(levelname)s] [%(asctime)s] %(message)s',\n 'datefmt': \"%Y-%m-%d %H:%M:%S\"\n },\n 'json': {\n 'format': '%(levelname)s %(asctime)s %(message)s',\n },\n },\n 'handlers': {\n 'file': {\n 'level': 'INFO',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join('5boon_log_path', 'access.log'),\n 'formatter': 'verbose',\n 'maxBytes': 1024 * 1024 * 100, # 100M\n 'backupCount': 10, # 최대 10개 유지\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['file'],\n 'level': os.getenv('INFO'),\n 'propagate': False,\n },\n },\n}\n\n#########################################\n# Application definition\n#########################################\nINSTALLED_APPS = [\n 'jet',\n 'jet.dashboard', # dashboard 기능을 사용하려면 다음을 추가\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_extensions',\n\n 'rest_framework',\n 'oauth2_provider',\n 'corsheaders',\n\n 'apps.users',\n 'apps.moods',\n 'apps.mood_groups',\n]\n\n#########################################\n# 미들웨어\n#########################################\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'oauth2_provider.middleware.OAuth2TokenMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n]\n\n\n#########################################\n# REST FRAMEWORK\n#########################################\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n 'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API\n ),\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n # 'oauth2_provider.ext.rest_framework.TokenHasReadWriteScope'\n ),\n}\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend', # To keep the Browsable API\n 'oauth2_provider.backends.OAuth2Backend',\n)\n\n\n#########################################\n# CORS\n#########################################\n\nCORS_ORIGIN_ALLOW_ALL = True\n\n#CORS_ALLOW_CREDENTIALS = False\n\n\n#########################################\n# Oauth2\n#########################################\n# OAUTH2_PROVIDER['ACCESS_TOKEN_EXPIRE_SECONDS'] = 24 * 60 * 60 # 24 Hours\n\n# OAUTH2_PROVIDER = {\n# # other OAUTH2 settings\n# 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore'\n# }\n\n# OAUTH2_PROVIDER_APPLICATION_MODEL = 'users.User'\n\nROOT_URLCONF = 'urls.domain'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.normpath(os.path.join(DJANGO_ROOT, 'templates')),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'today_mood.wsgi.application'\n\n#########################################\n# 데이터 베이스 세팅\n#########################################\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': '5boondb',\n 'OPTIONS': {\n 'read_default_file': '/etc/mysql/conf.d/5boon.cnf',\n 'charset': 'utf8mb4',\n },\n }\n}\n\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n#########################################\n# 센트리 리포팅\n#########################################\nsentry_sdk.init(\n dsn=\"sentry_channel_key\",\n integrations=[DjangoIntegration()],\n\n # If you wish to associate users to errors (assuming you are using\n # django.contrib.auth) you may enable sending PII data.\n send_default_pii=True\n)\n\n#########################################\n# 슬랙 채널\n#########################################\nSLACK_CHANNEL_JOINED_USER = 'slack_channel_joined_user_key'\nSLACK_CHANNEL_CREATE_MOOD = 'slack_channel_create_mood_key'\n\n\n#########################################\n# Gmail SMTP\n#########################################\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = \"smtp.gmail.com\"\nEMAIL_HOST_USER = '5boon_email'\nEMAIL_HOST_PASSWORD = '5boon_email_pw'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\nDEFAULT_FROM_EMAIL = EMAIL_HOST_USER\n\n\n#########################################\n# 기타 등등\n#########################################\nSNS_AUTH_USER_KEY = 'sns_auth_user_key'\n\n\n#########################################\n# Time Zone and language\n#########################################\nUSE_TZ = False\nUSE_I18N = True\nUSE_L10N = True\nTIME_ZONE = 'Asia/Seoul'\nLANGUAGE_CODE = 'ko-kr'\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.2/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = '/home/deploy/sites/static/'\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'static'),\n]\n","sub_path":"today_mood/conf/settings/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"605206856","text":"# Outlier detection with EllipticEnvelope using artificial dataset.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.covariance import EllipticEnvelope\nfrom scipy import stats\n\n# Set rng seed\nnp.random.seed(42)\n\n# Example settings\nnum_samples = 200\ncontamination = 0.25\nnum_outliers = int(num_samples * contamination)\nnum_inliers = num_samples - num_outliers\n\n# Construct the data set\noffset = 2\ndata_inliers_1 = 0.3 * np.random.randn(num_inliers // 2, 2) - offset\ndata_inliers_2 = 0.3 * np.random.randn(num_inliers // 2, 2) + offset\ndata_inliers = np.r_[data_inliers_1, data_inliers_2]\ndata_outliers = np.random.uniform(low=-5, high=5, size=(num_outliers, 2))\ndata = np.r_[data_inliers, data_outliers]\n\n# Fit the model\nclf = EllipticEnvelope(contamination=contamination)\nclf.fit(data)\n\n# Perform outlier detection\npredicted_data = clf.predict(data)\ninlier_predicted_data = data[predicted_data == 1]\noutlier_predicted_data = data[predicted_data == -1]\nnum_inliers_predicted = inlier_predicted_data.shape[0]\nnum_outliers_predicted = outlier_predicted_data.shape[0]\n\n# # Plot decision function values\nxr = np.linspace(-6, 6, 600)\nyr = np.linspace(-6, 6, 600)\nxx, yy = np.meshgrid(xr, yr)\nzz = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])\nzz = zz.reshape(xx.shape)\nscores = clf.decision_function(data)\nthreshold = stats.scoreatpercentile(scores, 100 * contamination)\nplt.contourf(xx, yy, zz, levels=np.linspace(zz.min(), threshold, 7), cmap=plt.cm.Blues_r) # Outlier\nplt.contour(xx, yy, zz, levels=np.array([threshold]), linewidths=2, colors=\"red\") # The frontier\nplt.contourf(xx, yy, zz, levels=np.linspace(threshold, zz.max(), 7), colors=\"orange\") # Inlier\n\n# Plot the sets\nplt.scatter(inlier_predicted_data[:, 0], inlier_predicted_data[:, 1], c=\"white\", s=10, edgecolors=\"black\",\n label=\"Inliers\")\nplt.scatter(outlier_predicted_data[:, 0], outlier_predicted_data[:, 1], c=\"black\", s=10, edgecolors=\"black\",\n label=\"Outliers\")\nplt.title(\"Inliers={} Outliers={}\".format(num_inliers_predicted, num_outliers_predicted))\nplt.xlabel(\"Elliptic Envelope. contamination={}\".format(contamination))\nplt.legend()\nplt.show()\n","sub_path":"ArtificalDataset/elliptic_envelope.py","file_name":"elliptic_envelope.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"523408823","text":"import pygame\r\nimport pygame.time\r\nfrom objects.entity import Entity\r\nfrom objects.player import Player\r\nfrom pygame.locals import *\r\nfrom objects.game_map import Game_map\r\nfrom functions.move_functions import move\r\nfrom objects.gui import Gui\r\nfrom functions.input_handler import handle_input\r\nfrom functions.actions import action\r\n\r\nclass App():\r\n \r\n def __init__(self):\r\n pygame.init()\r\n pygame.display.set_caption('Orgs')\r\n self.running = True\r\n self.size = self.width, self.height = 860, 450\r\n self.display_surf = pygame.display.set_mode(self.size)\r\n self.map = Game_map()\r\n self.enemies = []\r\n self.player = Player('@', (100,200,100), 30, 1, 1)\r\n self.gui = Gui(self.player, self.display_surf)\r\n self.create_monster('G', (255,50,50), 20, 12)\r\n self.gui.log('Find the Amulet of Yendor!')\r\n \r\n \r\n def on_run(self):\r\n\r\n while self.running:\r\n\r\n for event in pygame.event.get():\r\n if event.type == KEYDOWN:\r\n handle_input(self, event.key)\r\n elif event.type == QUIT:\r\n self.running = False\r\n \r\n self.display_surf.fill((0, 5, 6))\r\n self.draw_map(self.map.map_list)\r\n self.draw_entities(self.enemies)\r\n self.draw_entity(self.player)\r\n self.gui.draw()\r\n # self.gui.draw_whole_log()\r\n pygame.display.update()\r\n \r\n def create_monster(self, char, color, x, y, size=30):\r\n self.potwor = Entity('S', (255,50,50), size, x, y, passable=False)\r\n self.enemies.append(self.potwor)\r\n\r\n def draw_entities(self, things_list):\r\n for thing in things_list:\r\n self.draw_entity(thing)\r\n\r\n def draw_entity(self, thing):\r\n char, rect = thing.on_draw()\r\n self.display_surf.blit(char, rect)\r\n \r\n def draw_map(self, map_list):\r\n for row in map_list:\r\n for thing in row:\r\n if thing:\r\n self.display_surf.blit(thing.char, thing.rect)\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n app = App()\r\n app.on_run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"401284462","text":"a = {}\nd = ('бабочки полет будит тихую поляну в солнечных лучах'+' старый пруд прыгнула лягушка всплеск в тишине')\nc = d.split()\nfor word in c:\n a[word] = a.get(word, 0) + 1\nprint(a)\nmax_value = max(list(a.values()))\nw = ''\nfor key, value in a.items():\n if value == max_value:\n w = key\n\nprint(' чаще всего встречается слово : ', w, '\\n','всего в тексте : ', max_value)","sub_path":"dictionary2.py","file_name":"dictionary2.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"137450614","text":"from collections import OrderedDict, ChainMap\nfrom copy import deepcopy\nimport os\nimport json\nimport pickle\nimport re\nimport io\n\nimport pandas\n\nfrom libalignmentrs.alignment import SeqMatrix\nfrom libalignmentrs.readers import fasta_to_dict\nfrom alignmentrs.utils import to_intlist\n\n\n__all__ = [\n 'FastaSerdeMixin', 'DictSerdeMixin', 'JsonSerdeMixin', \n 'PickleSerdeMixin', 'CsvSerdeMixin', 'RecordsSerdeMixin',\n 'col_metadata_to_str', 'col_metadata_str_formatter',\n]\n\n\n_whitespace_regexp = re.compile(r'\\s+')\n_column_metadata_string_regexp = re.compile(r'meta\\|(\\S+)\\=(\\S+)')\n\n\nclass FastaSerdeMixin:\n \"\"\"Adds ability to read/write an Alignment object\n from a FASTA formatted file.\n \"\"\"\n @classmethod\n def from_fasta(\n cls, path, name=None, \n # parse_row_metadata=True,\n parse_description=True, \n # column_metadata_decoders=None,\n column_metadata_regexp='c\\|([A-Za-z0-9\\s\\.]+)=(\\[[A-Za-z0-9\\.\\s,\\\"\\']+\\])',\n column_index_regexp='ci\\|([A-Za-z0-9\\s\\.]+)=(\\[[A-Za-z0-9\\.\\s,\\\"\\']+\\])',\n store_history=True, **kwargs):\n \"\"\"Create an Alignment object from a FASTA-formatted file.\n\n Parameters\n ----------\n path : str\n Path to FASTA file.\n name : str, optional\n Name of the new alignment.\n (default is None, takes the name from the comments\n or uses the filename)\n parse_description : function, optional\n Function that takes a list of comment lines as input\n and outputs a dictionary that organizes comments into\n keys and values. (default is None, lines starting with \n a semicolon \";\" are ignored.)\n\n Returns\n -------\n Alignment\n Creates a new Alignment object based on the identifiers,\n descriptions, and sequences in the FASTA file.\n\n \"\"\"\n matrix, metadata = fasta_to_dict(path)\n row_meta, col_meta = None, None\n if parse_description:\n # Parses metadata['descriptions'] and removes parsed info\n offset = 0\n match_locations = []\n col_d = {}\n col_idx = None\n # Parses column index\n match = re.search(column_index_regexp, metadata['descriptions'][0])\n if match:\n key, value = match.groups()\n # Convert text into a list using eval\n try:\n value = cls._parse_str_to_list(value, 'infer')\n except SyntaxError:\n raise ValueError('Cannot construct Alignment from the given FASTA file: column index is malformed'.format(key))\n # Put key-value pair into the dictionary\n col_idx = value\n\n # Parses column metadata\n for match in re.finditer(column_metadata_regexp,\n metadata['descriptions'][0]):\n match_locations.append(match.span())\n key, value = match.groups()\n # Convert text into a list using eval\n try:\n value = cls._parse_str_to_list(value, 'infer')\n except SyntaxError:\n raise ValueError('Cannot construct Alignment from the given FASTA file: column metadata {} is malformed'.format(key))\n # Put key-value pair into the dictionary\n col_d[key] = value\n # Constructs column metadata DataFrame from dictionary and index\n if (col_idx is not None) or col_d:\n col_meta = pandas.DataFrame(col_d, index=col_idx)\n\n if name is None:\n name = os.path.basename(path)\n return cls(matrix, name,\n row_metadata=row_meta,\n # row_ids and row_descriptions are ignored\n # if row_meta is not None\n row_ids=metadata['ids'],\n row_descriptions=metadata['descriptions'],\n # col_meta is None unless parse_column_metadata is True\n col_metadata=col_meta,\n aln_metadata=metadata['comments'],\n store_history=store_history, **kwargs)\n\n def to_fasta(self, path=None, include_column_metadata=None, column_metadata_encoders=None, column_metadata_template='c|{}={}', **kwargs):\n \"\"\"Saves the alignment as a FASTA-formatted file.\n Some metadata may not be lost.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n include_column_metadata : list of str, optional\n List of keys of columns in column metadata to include\n (default is None, information are not written as FASTA comments\n to ensure maximum compatibility)\n column_metadata_encoders : dict of callable, optional\n Dictionary of functions used to transform values of included\n column metadata.\n Keys are expected to match specified column names.\n (default is None, all included columns will be transformed using the\n `str` string constructor)\n\n \"\"\"\n # Default values if not specified\n if include_column_metadata is None:\n include_column_metadata = []\n if column_metadata_encoders is None:\n column_metadata_encoders = {}\n\n # Transform col metadata DataFrame into a stringed representation\n # of columns and values.\n col_meta_str = col_metadata_to_str(\n self.column_metadata, include_column_metadata,\n column_metadata_encoders, column_metadata_template\n )\n # Creates a generator that writes each entry as a string\n # in the FASTA format:\n # >{sid} {desc}\n # {seq}\n info_generator = (\n (vals[0], vals[1]['description'], self.data.data[i]) \n for i, vals in enumerate(self.row_metadata.iterrows())\n )\n fasta_str = '\\n'.join([\n self._fasta_entry_formatter(*params, col_meta_str)\n if i == 0 else\n self._fasta_entry_formatter(*params, '')\n for i, params in enumerate(info_generator)\n ])\n\n # Write the FASTA string to file\n if path is None:\n return fasta_str\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'w') as writer:\n print(fasta_str, file=writer)\n\n @staticmethod\n def _parse_str_to_list(string: str, item_type: type = 'infer'):\n \"\"\" Returns a list by parsing a given string. The input string has to\n expressed as like Python list syntax.\n \n Parameters\n ----------\n string: str\n A string to be converted into a list. Format should be Python\n syntax of list object like \"[1, 2, 3]\". It has to starts with \"[\"\n and ends with \"]\" and items have to be separated by \",\".\n item_type: type (default: str)\n Type in which items in str-like list will be converted. For example,\n \"[1, 2, 3]\" and int are passed to string and item_type variables \n respectively, \"[1, 2, 3]\" will converted into [1, 2, 3] not\n [\"1\", \"2\", \"3\"].\n\n Return\n ------\n A list version of the input string.\n\n \"\"\"\n # Check if item_type variable is \"type\" type\n if item_type != 'infer' and not isinstance(item_type, type):\n raise TypeError('Invalid type: object constructor type should be '\\\n 'passed to \"item_type\" variable.')\n\n # Check if sring is str\n if not isinstance(string, str):\n raise TypeError('Invalid type: \"string\" variable has to be str type.')\n\n # Check string format\n if not string.startswith('['):\n raise SyntaxError(f'Invalid syntax for conversion to a list. '\\\n '{string} does not start with \"[\".')\n if not string.endswith(']'):\n raise SyntaxError(f'Invalid syntax for conversion to a list. '\\\n '{string} does not end with \"]\".')\n \n # Convert into a list\n if item_type == 'infer':\n out_l = []\n for item in string.split('[')[1].split(']')[0].split(','):\n try:\n dat = int(item)\n # e.g. int('1.1') gives \"ValueError: invalid literal for int() \n # with base 10: '1.1'\"\n except ValueError:\n dat = float(item)\n # e.g. float('a') gives \"ValueError: could not convert string \n # to float: 'a'\"\n except:\n dat = item\n\n out_l.append(dat)\n return out_l\n\n return [item_type(item) for item \n in string.split('[')[1].split(']')[0].split(',')]\n\n @staticmethod\n def _fasta_entry_formatter(sid, desc, seq, col_meta):\n # Formats the ID, description, stringed metadata, and sequence\n # to follow the FASTA format.\n # There are 4 possible scenarios, note that the identifier string\n # is always expected to have a non-empty value:\n # - all information exists\n # - col_meta is an empty string\n # - description is an empty string\n # - both col_meta and description are empty strings\n\n # Checks if ID is empty\n if len(sid) < 1:\n raise ValueError('Cannot create FASTA file: identifier string cannot be empty.')\n # Description is not empty\n if len(desc) > 0:\n if len(col_meta) > 0:\n return '>{} {} {}\\n{}'.format(sid, desc, col_meta, seq)\n return '>{} {}\\n{}'.format(sid, desc, seq)\n # Description is empty but column metadata is not empty\n if len(col_meta) > 0:\n return '>{} {}\\n{}'.format(sid, col_meta, seq)\n # Decription and column metadata are empty\n return '>{}\\n{}'.format(sid, seq)\n\n\nclass DictSerdeMixin:\n \"\"\"Adds ability to read/write an Alignment object from a dictionary.\n \"\"\"\n @classmethod\n def from_dict(cls, d, store_history=True, **kwargs):\n \"\"\"Creates an Alignment object from a dictionary.\n\n Parameters\n ----------\n d : dict\n Dictionary containing the alignment information and relevant\n metadata.\n\n Returns\n -------\n Alignment\n\n \"\"\"\n return cls(d['data'],\n name=d['name'],\n row_ids=d['row_metadata_index'],\n row_descriptions=d['row_metadata'],\n col_ids=d['column_metadata_index'],\n col_descriptions=d['column_metadata'],\n aln_metadata=d['alignment_metadata'],\n store_history=store_history,\n **kwargs)\n\n def to_dict(self, row_metadata=True, column_metadata=True):\n \"\"\"Returns the dictionary representation of the alignment.\n Contents of the dictionary use builtin types to maximize\n compatibility.\n\n Parameters\n ----------\n row_metadata : bool, optional\n Whether or not to include row metadata information. (default is True, row metadata is included)\n column_metadata : bool, optional\n Whether or not to include column metadata information. (default is True, column metadata is included)\n\n Returns\n -------\n dict\n\n \"\"\"\n d = {\n 'name': self.name,\n 'data': self.data.data,\n 'alignment_metadata': self.alignment_metadata,\n }\n if row_metadata:\n d['row_metadata'] = self.row_metadata.to_dict(orient='list')\n d['row_metadata_index'] = self.row_metadata.index.tolist()\n if column_metadata:\n d['column_metadata'] = self.column_metadata.to_dict(orient='list')\n d['column_metadata_index'] = self.column_metadata.index.tolist()\n return d\n\nclass JsonSerdeMixin(DictSerdeMixin):\n \"\"\"Adds ability to read/write an Alignment object from a JSON file.\n\n The underlying organization of the JSON encoding is based on the dictionary \n created using the DictSerdeMixin dictionary mixin.\n \"\"\"\n @classmethod\n def from_json(cls, path, store_history=True, **kwargs):\n \"\"\"Create an alignment from a JSON file.\n \n Parameters\n ----------\n path : io.IOBase or str\n File stream using a file handler or a string to the path.\n \n Returns\n -------\n Alignment\n\n \"\"\"\n if isinstance(path, io.IOBase):\n # json.load requires a file handler to read the file.\n # io.IOBase is the abstract base class for all kinds of\n # I/O file streaming.\n d = json.load(path)\n elif isinstance(path, str):\n # The user can also input the path where the json file is located.\n # To handle this, the path will have to be opened as a file handler\n with open(path, 'r') as reader:\n d = json.load(reader)\n # JSON structure is based on to_dict and so it is dependent\n # on DictSerdeMixin.\n return cls.from_dict(d, store_history=store_history, **kwargs)\n\n def to_json(self, path=None, row_metadata=True, column_metadata=True):\n \"\"\"Saves the alignment as a JSON file.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n row_metadata : bool, optional\n Whether or not to include row metadata information. (default is True, row metadata is included)\n column_metadata : bool, optional\n Whether or not to include column metadata information. (default is True, column metadata is included)\n\n Returns\n -------\n str\n If path is None, returns the JSON-formatted text as a string.\n\n \"\"\"\n # to_json uses to_dict to transform the alignment data\n # into a representation that uses only builtins to maximize\n # compatibility.\n # The resulting dictionary is encoded into JSON.\n d = self.to_dict(\n row_metadata=row_metadata,\n column_metadata=column_metadata)\n json_str = json.dumps(d)\n # If the save path is not specified, the encoded JSON text\n # is returned as a string\n if path is None:\n return json_str\n # If the save path is specified, the JSON encoded text\n # is written as a text file.\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'w') as writer:\n print(json_str, file=writer)\n\n\nclass PickleSerdeMixin:\n \"\"\"Adds ability to pickle/unpickle an Alignment object.\n \"\"\"\n @classmethod\n def from_pickle(cls, path, store_history=True, **kwargs):\n \"\"\"Converts a pickled alignment back into an Alignment object.\n\n Parameters\n ----------\n path : io.IOBase or str\n File handler for the pickled alignment or a string to the path.\n\n Returns\n -------\n Alignment\n\n \"\"\"\n if isinstance(path, io.IOBase):\n obj = pickle.load(path)\n elif isinstance(path, str):\n with open(path, 'rb') as reader:\n obj = pickle.load(reader)\n return obj\n\n def to_pickle(self, path=None, **kwargs):\n \"\"\"Pickles the current alignment.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n\n Returns\n -------\n bytestring\n If path is None, returns the bytestring representation of the\n pickled alignment.\n\n \"\"\"\n # Pickles the alignment. Underlying methods that do the pickling are\n # __getstate__ and __setstate__.\n pickled = pickle.dumps(self)\n # If path is not provided, the bytestring of the pickle is returned.\n if path is None:\n return pickled\n # If path is provided, the pickle is written to file.\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'wb') as writer:\n writer.write(pickled)\n\n def __getstate__(self):\n # This method gets called when the Alignment object\n # is being pickled.\n d = {k: v for k, v in self.__dict__.items() if k != 'data'}\n d['data'] = self.data.data\n return d\n\n def __setstate__(self, d):\n # This method gets called when the pickled object\n # is being unpickled back into an Alignment object.\n d['data'] = SeqMatrix(d['data'])\n self.__dict__ = d\n\n\nclass NexusSerdeMixin:\n pass\n\n\nclass PhylipSerdeMixin:\n pass\n\n\ndef col_metadata_to_str(column_metadata, included_keys, encoders=None, template='c|{}={}', index_template='ci|{}={}'):\n \"\"\"Transforms the column metadata DataFrame into a string representation.\n \n Parameters\n ----------\n column_metadata : pandas.DataFrame\n Column metadata\n included_keys : list of str\n List of column metadata column names that to be included in the\n string representation.\n encoders : dict of callable, optional\n Dictionary of functions used to transform column metadata values.\n Keys are expected to match the column names of the column metadata\n DataFrame. (default is None, all columns will be transformed using the\n `str` string constructor)\n template : str, optional\n Template used for formatting the string. Template should have 2\n slots for the key and the column value.\n \n Returns\n -------\n str\n Column metadata categories and values represented as a string.\n\n \"\"\"\n # Creates a tuple generator giving the filtered set of column metadata\n # Each tuple generated consists of the column name and the list of values\n # for that column. \n included_values = (\n (k, v) for k, v in column_metadata.to_dict(orient='list').items()\n if k in included_keys\n )\n if encoders is None:\n encoders = dict()\n # Creates a list of stringed column metadata where each string is the\n # contains the stringed data of a column metadata category (column)\n # The metadata column is transformed into a string by consuming\n # the `included_values` generator and calling `col_metadata_str_formatter`\n # for each item yielded.\n str_list = [\n col_metadata_str_formatter(\n k, v, encoders[k] if k in encoders.keys() else None, template)\n for k, v in included_values\n ]\n str_index = [col_metadata_str_formatter(\n 'index', column_metadata.index.tolist(),\n encoders['index'] if 'index' in encoders.keys() else None, \n index_template)\n ]\n # Each column's string representation is separated by a whitespace\n return ' '.join(str_index + str_list)\n\ndef col_metadata_str_formatter(key, value, encoder:callable=None, template='c|{}={}'):\n \"\"\"Returns the string representation of a column metadata category.\n \n Parameters\n ----------\n key : str\n Name of column metadata category (column name in the DataFrame).\n value : list\n Column metadata category values.\n encoder : callable\n Function used to transform the list of values into a string.\n template : str, optional\n Template used for formatting the string. Template should have 2\n slots for the key and the column value.\n\n Returns\n -------\n str\n String representation of the column metadata category and its values.\n\n \"\"\"\n if encoder is None:\n encoder = lambda x: _whitespace_regexp.sub('', str(x))\n return template.format(key, encoder(value))\n\ndef make_col_meta_dict(description, decoders):\n matches = _column_metadata_string_regexp.findall(description)\n return {\n k: (decoders[k](v) if k in decoders.keys() else eval(v))\n for k, v in matches\n }\n","sub_path":"alignmentrs/aln/mixins/serde.py","file_name":"serde.py","file_ext":"py","file_size_in_byte":20261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"180249730","text":"#! /usr/bin/env python\n# This folder's code is largely inspired by https://github.com/UHH2/SFrameBatch\n\n# main \"executable\" that takes as an argument the XML file and handles submission, monitoring, and hadd'ing of the files\nimport os, sys\nimport subprocess\nimport time\nimport argparse\nfrom utils import *\nfrom Submitter import *\nimport ROOT\nfrom ROOT import kError\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Program that takes as an argument the XML file and handles submission, monitoring, and hadd\\'ing of the files.')\n parser.add_argument('xmlfilename', metavar='XMLFILENAME', type=str, nargs=1, help='Name of the XML file')\n parser.add_argument('--divide', '-d', action='store_true', default=False, dest='divide', help='Divide XMLFILENAME into chunks, create workdir.')\n parser.add_argument('--submit', '-s', action='store_true', default=False, dest='submit', help='Submit split jobs to cluster')\n parser.add_argument('--output', '-o', action='store_true', default=False, dest='output', help='Check the status of the expected output files')\n parser.add_argument('--add', '-a', action='store_true', default=False, dest='add', help='Add split files back together for samples that are fully processed. Incomplete samples are not added.')\n parser.add_argument('--forceadd', '-f', action='store_true', default=False, dest='forceadd', help='Force hadding with hadd\\'s \\'-f\\' flag. Also has an effect if used without \\'--add\\'.')\n parser.add_argument('--plothadd', '-p', action='store_true', default=False, dest='hadd', help='Hadd files to groups used for plotting and further analysis. Will always force.')\n parser.add_argument('--clean', '-c', action='store_true', default=False, dest='clean', help='Clean up: remove the local and the remote workdir')\n\n args = parser.parse_args()\n xmlfilename = os.path.abspath(args.xmlfilename[0])\n if not xmlfilename.endswith('.xml'):\n raise ValueError(red('The name of the xml-file does not end with \\'.xml\\'. I don\\'t believe you...'))\n divide = args.divide\n output = args.output\n submit = args.submit\n add = args.add\n forceadd = args.forceadd\n hadd = args.hadd\n clean = args.clean\n nargs = sum([1 for x in vars(args) if vars(args)[x] is True])\n\n ROOT.gErrorIgnoreLevel = kError\n\n\n # Build submitter object, this will already parse the XML file\n submitter = Submitter(xmlfilename=xmlfilename)\n\n # create workdir locally and remotely (for output), create txt file with expected output files, split XML file into many smaller ones for individual jobs\n\n if clean:\n if nargs > 1:\n raise AttributeError('More than one argument given together with \\'-c\\' option. This is unsafe.')\n submitter.Clean()\n if divide: submitter.Divide()\n if output: submitter.Output()\n if submit: submitter.Submit()\n if add or forceadd: submitter.Add(force=forceadd)\n if hadd: submitter.Hadd()\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\nif __name__ == '__main__':\n main()\n","sub_path":"Submitter/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"420470945","text":"import time \nimport random\n\nf = open('monitor_1_latency.json', 'r+')\n\nwhile True:\n #t = int(time.time() * 1000)\n latency = random.randint(1, 500)\n\n s = '{\"latency\": %d}' %(latency)\n time.sleep(1)\n \n f.seek(0)\n f.write(s)\n f.truncate()\n\n #f.write\n","sub_path":"pages/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"588901430","text":"import markovify\nimport urllib.request\nimport urllib.parse\nimport xml.etree.cElementTree as ET\nimport time\nimport re\nfrom distance import levenshtein\nfrom data import Data\nimport zmq\nfrom os import listdir\nfrom logFetcher import LogFetcher\nimport threading\nimport sys\n\nclass SpamGenerator:\n\n\tdef __init__(self):\n\t\tself.user_models = dict()\n\t\tself.previous_5 = []\n\t\tself.cached = dict()\n\t\tself.banned_words = [\"roulette\", \"latest tweet from\", \"!rt\", \"!rm\",\"ᅠ\",\"イ\",\"マ\",\"オ\",\"ト\",\"グ\",\"リ\",\"ル\", \"twitch.tv\", \"bit.ly\",\"t.co\", \"#tusk\", \"<3 between\",\"karl\", \"blinak\"]\n\t\tfor user in Data.users:\n\t\t\tself.cached[user]=\"\"\n\t\t\tself.user_models[user] = (markovify.Text(self.readlogs(user)), [])\n\t\t\tself.cached[user]=self.get_sentence(user)\n\t\tprint(\"SpamGenerator started\t\")\n\n\n\tdef readlogs(self, user):\n\t\tprint(\"Reading logs for %s\"%user)\n\t\t\t\n\t\tlogfiles = listdir(\"./logs/%s/\"%user)\n\t\t\n\t\tstrings = []\n\t\tfor logfile in logfiles:\n\t\t\tf = open(\"./logs/%s/%s\"%(user,logfile), encoding=\"UTF-8\")\n\t\t\tfor line in f:\n\t\t\t\tsplitline = line.split(\"%s:\"%user, 1)\n\t\t\t\tif len(splitline)!=1:\n\t\t\t\t\tsplitline[1]=splitline[1].lstrip()\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\tif not (any([banned in splitline[1].lower() for banned in self.banned_words])):\n\t\t\t\t\t\tif user == \"distq\" and any([splitline[1].startswith(u) for u in Data.users]):\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tstrings.append(splitline[-1])\n\t\t\t\t\t\n\t\t\tf.close()\n\t\t\n\t\treturn \"\".join(strings)\n\tdef cache_message(self,user):\n\t\tself.cached[user]=self.make_sentence(user)\n\tdef make_sentence(self, user, length = 199):\n\t\tlength=length-len(user)-5\n\t\twhile True:\n\t\t\tsentence = self.user_models[user][0].make_short_sentence(length)\n\t\t\tif sentence and all([levenshtein(sentence, x)>75 for x in self.user_models[user][1]]):\n\n\t\t\t\tif len(self.user_models[user][1])>4:\n\t\t\t\t\tself.user_models[user][1].pop(0)\n\t\t\t\t\t\n\t\t\t\tself.user_models[user][1].append(sentence)\n\t\t\t\tbreak\n\t\treturn \"%s: %s\"%(user, sentence)\n\tdef get_sentence(self, user, length = 199):\n\t\tif self.cached[user]:\n\t\t\tsentence = self.cached[user]\n\t\t\tself.cached[user]=\"\"\n\t\t\t\n\t\t\t\n\t\telse:\n\t\t\tsentence = self.make_sentence(user)\n\n\t\tt = threading.Thread(target=self.cache_message,args =(user,))\n\t\tt.daemon = True\n\t\tt.start()\n\t\treturn sentence\n\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) !=1:\n\t\tif sys.argv[1]==\"update\":\n\t\t\tLogFetcher.update_all_users()\n\telse:\n\t\ts = SpamGenerator()\n\t\tcontext = zmq.Context()\n\t\tsocket = context.socket(zmq.REP)\n\t\tsocket.bind('tcp://127.0.0.1:5555')\n\t\twhile True:\n\t\t\tmsg = socket.recv()\n\n\t\t\tprint(msg)\n\t\t\tmsg = msg.decode(\"utf-8\", \"ignore\")\n\t\t\tif msg in s.user_models.keys():\n\t\t\t\tsocket.send_string(s.get_sentence(msg).rstrip())\n\t\t\telif msg.startswith(\"add\"):\n\t\t\t\tuser = msg.split()[1]\n\t\t\t\tLogFetcher.update_all_logs(user)\n\t\t\t\ts.cached[user]=\"\"\n\t\t\t\ts.user_models[user] = (markovify.Text(s.readlogs(user)), [])\n\t\t\t\tprint(\"Added logs for %s successfully\"%user )\n\t\t\t\tsocket.send_string(\"success\")\n\t\t\telif msg.startswith(\"update\"):\n\t\t\t\targ = msg.split()[1]\n\t\t\t\tif arg == \"all\":\n\t\t\t\t\tLogFetcher.update_all_users()\n\t\t\t\telse:\n\t\t\t\t\tLogFetcher.update_all_logs(user)\n\t\t\telse:\n\t\t\t\tsocket.send_string(\"FAIL\") # default case\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t","sub_path":"spamGenerator.py","file_name":"spamGenerator.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"562355045","text":"#coding = utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport unittest,time,os\n\nclass Baidu1(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.driver.implicitly_wait(30)\n self.base_ur1 = \"http://baidu.com/\"\n self.verificationErrors = []\n self.accept_next_alert = True\n\n def test_BaiduSearch(self):\n driver = self.driver\n driver.get(self.base_ur1 + \"/\")\n driver.find_element_by_id(\"kw\").click()\n driver.find_element_by_id(\"kw\").clear()\n driver.find_element_by_id(\"kw\").send_keys(\"阿里巴巴\")\n driver.find_element_by_id(\"su\").click()\n\n def test_hao(self):\n driver = self.driver\n driver.get(self.base_ur1 + \"/\")\n driver.find_element_by_link_text(\"hao123\").click()\n self.assertEqual(u\"hao123_上网从这里开始\",driver.title)\n\n def is_element_present(self,how,what):\n try: self.driver.find_element(by=how,value=what)\n except NoSuchElementException as e:return False\n return True\n\n #判断alert是否存在\n def is_alert_parent(self):\n try: self.driver.switch_to.alert()\n except NoAlertPresentException as e : return False\n return True\n\n @property\n def close_alert_and_get_its_text(self):\n try:\n alert = self.driver.switch_to.alert()\n alert_text = alert.text\n if self.accept_next_alert :\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally: self.accept_next_alert = True\n\n #test fixure,清除环境\n def tearDown(self) :\n self.driver.quit()\n self.assertEqual([],self.verificationErrors)\n\n if __name__ == '__main__':\n unittest.main()\n\n\n\n","sub_path":"PythonTest/Practice_0810/Baidu1.py","file_name":"Baidu1.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"2700343","text":"from PIL import Image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.polynomial.polynomial as P\nimport scipy.ndimage as ndimage\nimport tifffile as tf\nimport glob\nimport os\n\ndef clean_zeroes(img):\n dim = img.ndim\n orig_size = img.size\n\n cero = list(range(2*dim))\n\n for k in range(dim):\n ceros = np.all(img == 0, axis = k)\n\n for i in range(len(ceros)):\n if(~ceros[i]):\n break\n for j in range(len(ceros)-1, 0, -1):\n if(~ceros[j]):\n break\n cero[k] = i\n cero[k+dim] = j+1\n\n img = img[cero[1]:cero[3], cero[0]:cero[2]]\n\n #print(round(100-100*img.size/orig_size),'% reduction from input')\n\n return img\n\ndef plot_hist(img, title='title'):\n hist,bins = np.histogram(img,bins=2**(img.dtype.itemsize*8),range=(0,2**(img.dtype.itemsize*8)))\n hist[0] = 0\n plt.xlabel('intensity')\n plt.ylabel('log(num)')\n plt.title(title)\n plt.grid()\n plt.plot(np.log(hist+1))\n\ndef attempt_split(img, sigma=8, threshold=170):\n blur = ndimage.gaussian_filter(img, sigma=8, mode='constant', truncate=3, cval=0)\n img[blur < threshold] = 0\n labels , num = ndimage.label(img, structure=ndimage.generate_binary_structure(img.ndim, 1))\n hist,bins = np.histogram(labels, bins=num, range=(1,num+1))\n\n return labels, hist, np.sum(hist)\n\ndef clean_corner_r(img, tol):\n corner = img[-tol:, -tol:]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n while len(foo) > 0 and len(foo) < 0.2*tol:\n bar = np.min(foo + img.shape[1] - tol)\n img[:, bar:] = 0\n img = clean_zeroes(img)\n corner = img[-tol:, -tol:]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n\n corner = img[:tol, -tol:]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n while len(foo) > 0 and len(foo) < 0.2*tol:\n bar = np.min(foo + img.shape[1] - tol)\n img[:, bar:] = 0\n img = clean_zeroes(img)\n corner = img[:tol, -tol:]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n return img\n\ndef clean_corner_l(img, tol):\n corner = img[:tol, :tol]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n while len(foo) > 0 and len(foo) < 0.2*tol:\n bar = np.max(foo) + 1\n img[:, :bar] = 0\n img = clean_zeroes(img)\n corner = img[:tol, :tol]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n\n corner = img[-tol:, :tol]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n while len(foo) > 0 and len(foo) < 0.2*tol:\n bar = np.max(foo) + 1\n img[:, :bar] = 0\n img = clean_zeroes(img)\n corner = img[-tol:, :tol]\n foo = np.where(np.sum(corner, axis=0) > 0)[0]\n return img\n\ndef clean_corner(img, tol=50, sigma=10, thr=175):\n img = clean_corner_l(img, tol)\n img = clean_corner_r(img, tol)\n\n blur = ndimage.gaussian_filter(img, sigma=10, mode='constant', truncate=3, cval=0)\n img[blur < thr] = 0\n blur = ndimage.gaussian_filter(img, sigma=10, mode='constant', truncate=3, cval=0)\n img[blur < thr] = 0\n\n labels , num = ndimage.label(img, structure=ndimage.generate_binary_structure(img.ndim, 1))\n hist,bins = np.histogram(labels, bins=num, range=(1,num+1))\n\n if len(hist) > 1:\n argsort_hist = np.argsort(hist)[::-1]\n regions = ndimage.find_objects(labels)\n\n i = argsort_hist[0]\n r = regions[i]\n\n mask = labels[r]==i+1\n box = img[r].copy()\n box[~mask] = 0\n\n return clean_zeroes(box)\n else:\n return clean_zeroes(img)\n\ndef save_comps(dst, foo, img, single, bname='leaf', thr=165, sigma=8, cutoff=1e-2, tol=50, write_file=True):\n labels, hist, sz_hist = attempt_split(foo, sigma, thr)\n leaves = np.sum(hist > cutoff*sz_hist)\n\n threshold = thr\n\n if not single:\n while leaves < 2:\n threshold += 3\n labels, hist, sz_hist = attempt_split(foo, sigma, threshold)\n leaves = np.sum(hist > cutoff*sz_hist)\n\n argsort_hist = np.argsort(hist)[::-1]\n regions = ndimage.find_objects(labels)\n\n print('Corrected by increasing threshold to', threshold)\n print(leaves, 'leaves')\n print('hist', hist[argsort_hist])\n\n for j in range(len(regions)):\n i = argsort_hist[j]\n r = regions[i]\n if(hist[i]/sz_hist > cutoff):\n x0,y0,x1,y1 = r[0].start,r[1].start,r[0].stop,r[1].stop\n mask = labels[r]==i+1\n box = img[r].copy()\n box[~mask] = 0\n box = clean_corner(box, tol)\n if write_file:\n tf.imwrite('{}{}_l{}_x{}_y{}.tif'.format(dst,bname,j,x0,y0),\n box,photometric='minisblack',compress=5)\n\n\ndef separate_leaf(filename, dst, single_leaves, thr=150, sigma=5, cutoff=1e-2, tol=50, w=True):\n\n src, fname = os.path.split(filename)\n src = src + '/'\n bname = os.path.splitext(fname)[0]\n print(bname)\n\n single = False\n if bname in single_leaves:\n single = True\n\n pic = Image.open(filename).convert('L')\n img = np.asarray(pic)\n if img.shape[1] < img.shape[0]:\n img = img.T\n img = img.max() - img\n foo = img.copy()\n\n foo[foo < thr] = 0\n\n save_comps(dst, foo, img, single, bname, thr, sigma, cutoff, tol, write_file=w)\n\n\n# ////////////////////////////////////////////////////////////////////////////\n# ////////////////////////////////////////////////////////////////////////////\n\n# ////////////////////////////////////////////////////////////////////////////\n# ////////////////////////////////////////////////////////////////////////////\n\ndef tiff2coords(img, thr = 0, center=True):\n nonzeros = np.sum(img > thr)\n coords = np.empty((nonzeros, img.ndim), dtype=np.float64, order='C')\n idx = 0\n it = np.nditer(img, flags=['multi_index'])\n while not it.finished:\n if it[0] > thr:\n coords[idx, :] = it.multi_index\n idx += 1\n it.iternext()\n\n if center:\n origin = -1*np.mean(coords, axis=0)\n coords = np.add(coords, origin)\n\n return coords\n\ndef get_margin(img, border):\n\n surface = ndimage.convolve(img, border, np.int8, 'constant', cval=0)\n surface[ surface < 0 ] = 0\n surface = surface.astype(np.uint8)\n surface[ surface > 0 ] = 1\n\n labels,num = ndimage.label(surface, structure=ndimage.generate_binary_structure(surface.ndim, 2))\n regions = ndimage.find_objects(labels)\n\n hist,bins = np.histogram(labels, bins=num, range=(1,num+1))\n sz_hist = np.sum(hist)\n argsort_hist = np.argsort(hist)[::-1]\n\n i = argsort_hist[0]\n r = regions[i]\n\n mask = labels[r]==i+1\n box = surface[r].copy()\n box[~mask] = 0\n\n return box\n\ndef orient_base2tip(margin, tol = 100):\n flip = False\n\n foo,bar = np.nonzero(margin[:,:tol])\n base = np.dstack((foo,bar)).squeeze()\n\n foo,bar = np.nonzero(margin[:,-tol:])\n tip = np.dstack((foo,bar)).squeeze()\n\n if tip.shape[0] > base.shape[0]:\n margin = np.flip(margin, 1)\n flip = True\n\n foo,bar = np.nonzero(margin[:,:tol])\n base = np.dstack((foo,bar)).squeeze()\n\n foo,bar = np.nonzero(margin[:,-tol:])\n tip = np.dstack((foo,bar)).squeeze()\n\n return margin, base, tip\n\ndef get_midrib(margin):\n midrib = np.empty((margin.shape[1],2))\n\n for i in range(margin.shape[1]):\n contour = np.nonzero(margin[:,i])[0]\n top , bot = np.max(contour), np.min(contour)\n midrib[i,:] = i, 0.5*(top+bot)\n\n return midrib\n\ndef split_margin(margin, midrib):\n top = []\n bot = []\n\n for i in range(margin.shape[1]):\n nozero = np.nonzero(margin[:, i])[0]\n top_mask = nozero > midrib[i,1]\n top.append(np.dstack((i*np.ones(len(nozero[top_mask])), nozero[top_mask])).squeeze())\n bot.append(np.dstack((i*np.ones(len(nozero[~top_mask])), nozero[~top_mask])).squeeze())\n\n return [np.vstack(top) , np.vstack(bot)]\n\ndef top_bot_blade(margin, border):\n margin, _ , _ = orient_base2tip(margin)\n midrib = get_midrib(margin)\n t_blade, b_blade = split_margin(margin, midrib)\n coords = np.vstack((t_blade,b_blade))\n\n return t_blade, b_blade, midrib, np.mean(coords,axis=0)\n\ndef refine_margin(margin, tol=0.5, thr=200, keep_tip=0.7, keep_base=0.05):\n\n threshold = min([thr, int(tol * np.max(np.abs(margin), axis=0)[1])])\n signif = int(keep_tip * margin.shape[0])\n relevant = np.abs(margin[:, 1]) > threshold\n relevant[signif:] = True\n signif = int(keep_base*signif)\n relevant[:signif] = True\n\n return margin[relevant,:]\n\ndef curve_length(x,y):\n curve = np.dstack((x,y)).squeeze()\n lengths = np.sqrt(np.sum(np.diff(curve, axis=0)**2, axis=1)) # Length between corners\n return np.sum(lengths)\n\ndef curve_fitting(coords, order=2, skip=0, stepsize=1):\n\n x_range = np.arange(np.min(coords[skip:,:], axis=0)[0],\n np.max(coords[skip:,:], axis=0)[0],\n stepsize)\n poly_fit = P.Polynomial.fit( coords[skip:,0], coords[skip:,1], deg=order, full=False )\n # coeff = poly_fit.convert().coef\n return poly_fit, x_range, poly_fit(x_range)\n\ndef poly_margin(margin, blades, leftover_base = 0.05, stepsize=1):\n for i in range(3):\n blades[i] = np.add(blades[i], -1*blades[-1])\n\n for i in range(2):\n blades[i] = refine_margin(blades[i])\n\n skip = int(leftover_base*blades[0].shape[0])\n\n coef = [None for x in range(3)]\n rang = [None for x in range(len(coef))]\n pred = [None for x in range(len(coef))]\n\n for i in range(2):\n coef[i], rang[i], pred[i] = curve_fitting(blades[i], 3, skip, stepsize=stepsize)\n\n base = np.flip(np.vstack((blades[0][:skip,],blades[1][:skip,])), 1)\n coef[2], rang[2], pred[2] = curve_fitting(base, 4, stepsize=stepsize)\n\n margin = np.vstack((np.dstack((pred[2],rang[2])).squeeze(),\n np.dstack((rang[0], pred[0])).squeeze(),\n np.flip(np.dstack((rang[1], pred[1])).squeeze(), axis=0),\n np.array([pred[2][0],rang[2][0]])))\n\n return margin, coef, rang, pred\n\ndef poly_area(coef, rang):\n area = 0\n for i in range(2):\n integral = coef[i].integ(m=1, k=0)\n area += np.abs(integral(rang[i][-1]) - integral(rang[i][0]))\n\n i = 2\n integral = coef[i].integ(m=1, k=0)\n rectangle = np.abs(coef[i].convert().coef[0]*(rang[i][-1]-rang[i][0]))\n\n area += np.abs(integral(rang[i][-1]) - integral(rang[i][0])) - rectangle\n\n return area\n\ndef poly_perimeter(contour, stepsize=1):\n perimeter = 0\n for i in range(len(contour)-1):\n diff = contour[i+1][1] - contour[i][1]\n perimeter += np.sqrt(stepsize*stepsize + diff*diff)\n\n return perimeter\n\ndef model_leaf(tiff_file, border, dst, Degree=[2,3], leftover=0, w=False):\n\n R_coeff = []\n L_coeff = []\n R_length = []\n L_length = []\n Length = []\n\n bname, perimeter, area, ratio, box = compute_perimeter(tiff_file, ssrc, dst, border, write_file=False)\n left, right = side_coords(box,dst,bname,w=w)\n\n skip = int(leftover*left.shape[0])\n print(skip)\n for degree in Degree:\n r_coeff, r_range, r_pred = curve_fitting(right, degree, skip)\n l_coeff, l_range, l_pred = curve_fitting(left, degree, skip)\n\n R_coeff.append(r_coeff)\n L_coeff.append(l_coeff)\n\n r_length = curve_length(r_range, r_pred)\n l_length = curve_length(l_range, l_pred)\n\n R_length.append(r_length)\n L_length.append(l_length)\n Length.append(r_length+l_length)\n\n if w:\n fig, axes = plt.subplots(3, 1, figsize=(18, 9))\n fig.suptitle(bname+' with degree '+str(degree),fontsize=28)\n\n axes[0].plot(right[skip:,0], right[skip:,1], '.b', ms=0.5)\n axes[0].plot(r_range, r_pred, 'r', lw=2)\n\n axes[1].plot(left[skip:,0], left[skip:,1],'.b', ms=0.5)\n axes[1].plot(l_range, l_pred, 'r', lw=2)\n\n axes[2].plot(r_range,r_pred, 'r', lw=2)\n axes[2].plot(l_range,l_pred, 'r', lw=2)\n\n plt.tight_layout()\n plt.subplots_adjust(top=0.93)\n\n plt.savefig(dst+bname+'_deg'+str(degree)+'.jpg', dpi=150, optimize=True, format='jpg')\n\n\n return bname, perimeter, area, ratio, R_coeff, L_coeff, R_length, L_length, Length\n","sub_path":"code/amaizeing_utils.py","file_name":"amaizeing_utils.py","file_ext":"py","file_size_in_byte":12203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"120445729","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\n*******************************************************************************\n Description\n\n This module extract the single line data in four steps.\n 1. Analyze the layout style by axis recognition\n 2. Segment the character chain proposal and OCR them\n 3. Line detection by color and thin\n 4. Data mapping by linear transformation\n_______________________________________________________________________________\n Functions List\n\n foo: foo has the input of something, output something, used some algorithm.\n_______________________________________________________________________________\n Created on 16:00 2017-07-31\n\n @author: xdliu\n\n All rights reserved.\n*******************************************************************************\n\"\"\"\nimport os\n\nimport datetime\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\nimport pyalgotrade.barfeed.sina_feed as sf\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis, \\\n QuadraticDiscriminantAnalysis\nimport pandas as pds\nimport numpy as np\n\n\ndef create_lagged_series(ts, symbol, lags=5):\n \"\"\"\n This creates a pandas DataFrame that stores the\n percentage returns of the adjusted closing value of\n a stock obtained from Yahoo Finance, along with a\n number of lagged returns from the prior trading days\n (lags defaults to 5 days). Trading volume, as well as\n the Direction from the previous day, are also included.\n \"\"\"\n\n # Obtain stock information from Yahoo Finance\n # ts = DataReader(\n # symbol, \"yahoo\",\n # start_date-datetime.timedelta(days=365),\n # end_date\n # )\n\n # Create the new lagged DataFrame\n tslag = pds.DataFrame(index=ts.index)\n tslag[\"Today\"] = ts[\"Close\"]\n tslag[\"Volume\"] = ts[\"Volume\"]\n\n # Create the shifted lag series of prior trading period close values\n for i in range(0,lags):\n tslag[\"Lag%s\" % str(i+1)] = ts[\"Close\"].shift(i+1)\n\n # Create the returns DataFrame\n tsret = pds.DataFrame(index=tslag.index)\n tsret[\"Volume\"] = tslag[\"Volume\"]\n tsret[\"Today\"] = tslag[\"Today\"].pct_change()*100.0\n\n # If any of the values of percentage returns equal zero, set them to\n # a small number (stops issues with QDA model in scikit-learn)\n for i,x in enumerate(tsret[\"Today\"]):\n if (abs(x) < 0.0001):\n tsret[\"Today\"][i] = 0.0001\n\n # Create the lagged percentage returns columns\n for i in range(0,lags):\n tsret[\n \"Lag%s\" % str(i+1)\n ] = tslag[\"Lag%s\" % str(i+1)].pct_change()*100.0\n\n # Create the \"Direction\" column (+1 or -1) indicating an up/down day\n tsret[\"Direction\"] = np.sign(tsret[\"Today\"])\n # tsret = tsret[tsret.index >= start_date]\n\n return tsret\n\n\ninstrument = 'FG0'\ncsv_path = os.path.abspath('../histdata/commodity') + '/' + instrument + '.csv'\n# feed = sf.Feed()\n# feed.addBarsFromCSV(instrument, csv_path)\ndf = pds.read_csv(csv_path)\nl = len(df.index)\nwindow_size = 99\nlagged_data = create_lagged_series(df, instrument,\n # start_date=datetime.datetime(2012, 12, 03),\n # end_date=datetime.datetime(2017, 07, 21),\n lags=window_size)\nx = lagged_data[['Lag1', 'Lag2', 'Lag3', 'Lag4', 'Lag5']]\ny = lagged_data['Direction']\n\nx_train, x_test, y_train, y_test = train_test_split(x, y,\n test_size=0.8\n )\nx_train = x_train.fillna(method='ffill')\ny_train = y_train.fillna(method='ffill')\nx_test = x_test.fillna(method='ffill')\ny_test = y_test.fillna(method='ffill')\n\n# lda = LinearDiscriminantAnalysis()\n# lda = QuadraticDiscriminantAnalysis()\nlda = RandomForestClassifier()\nlda.fit(x_train, y_train)\n\npredict = lda.predict(x_test)\n\nhit_rate = lda.score(x_test, y_test)\ncm = confusion_matrix(predict, y_test)\n\nprint('hit_rate: %0.3f%%' % (hit_rate * 100))\nprint('confusion matrix:\\n%s' %cm)\npass\n\n\n\n\n","sub_path":"samples/sk_models.py","file_name":"sk_models.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"546040508","text":"\nimport zmq\n\ndef run(addr):\n\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.connect(addr)\n\n for request in range(10):\n\n print('Sending hello from {}'.format(request))\n\n # Send the message\n socket.send(b'Hello')\n\n # Wait for the reply\n message = socket.recv()\n print('Got reply {}'.format(message))\n\n","sub_path":"python/zero/src/zero/requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"84271936","text":"def calculate(set):\n for elt in set:\n if len(set) > 1:\n temp = set.remove(elt)\n power_set.append(calculate(temp))\n\n\nset, power_set = [], []\nn = int(input(\"Enter size of the set:\\n\"))\n\nfor i in range(n):\n set.append(int(input(f\"Enter element {i}:\\n\")))\n\ncalculate(set)","sub_path":"my_solutions/ch8/power_set.py","file_name":"power_set.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"55423600","text":"from collections import defaultdict, deque, namedtuple\nimport pb_robot.helper as helper\n\n# Mesh & Pointcloud Files\nMesh = namedtuple('Mesh', ['vertices', 'faces'])\n\ndef obj_file_from_mesh(mesh, under=True):\n \"\"\"\n Creates a *.obj mesh string\n :param mesh: tuple of list of vertices and list of faces\n :return: *.obj mesh string\n \"\"\"\n vertices, faces = mesh\n s = 'g Mesh\\n' # TODO: string writer\n for v in vertices:\n assert(len(v) == 3)\n s += '\\nv {}'.format(' '.join(map(str, v)))\n for f in faces:\n #assert(len(f) == 3) # Not necessarily true\n f = [i+1 for i in f] # Assumes mesh is indexed from zero\n s += '\\nf {}'.format(' '.join(map(str, f)))\n if under:\n s += '\\nf {}'.format(' '.join(map(str, reversed(f))))\n return s\n\ndef get_connected_components(vertices, edges):\n undirected_edges = defaultdict(set)\n for v1, v2 in edges:\n undirected_edges[v1].add(v2)\n undirected_edges[v2].add(v1)\n clusters = []\n processed = set()\n for v0 in vertices:\n if v0 in processed:\n continue\n processed.add(v0)\n cluster = {v0}\n queue = deque([v0])\n while queue:\n v1 = queue.popleft()\n for v2 in (undirected_edges[v1] - processed):\n processed.add(v2)\n cluster.add(v2)\n queue.append(v2)\n if cluster: # preserves order\n clusters.append(frozenset(cluster))\n return clusters\n\ndef read_obj(path, decompose=True):\n mesh = Mesh([], [])\n meshes = {}\n vertices = []\n faces = []\n for line in helper.read(path).split('\\n'):\n tokens = line.split()\n if not tokens:\n continue\n if tokens[0] == 'o':\n name = tokens[1]\n mesh = Mesh([], [])\n meshes[name] = mesh\n elif tokens[0] == 'v':\n vertex = tuple(map(float, tokens[1:4]))\n vertices.append(vertex)\n elif tokens[0] in ('vn', 's'):\n pass\n elif tokens[0] == 'f':\n face = tuple(int(token.split('/')[0]) - 1 for token in tokens[1:])\n faces.append(face)\n mesh.faces.append(face)\n if not decompose:\n return Mesh(vertices, faces)\n #if not meshes:\n # # TODO: ensure this still works if no objects\n # meshes[None] = mesh\n #new_meshes = {}\n # TODO: make each triangle a separate object\n for name, mesh in meshes.items():\n indices = sorted({i for face in mesh.faces for i in face})\n mesh.vertices[:] = [vertices[i] for i in indices]\n new_index_from_old = {i2: i1 for i1, i2 in enumerate(indices)}\n mesh.faces[:] = [tuple(new_index_from_old[i1] for i1 in face) for face in mesh.faces]\n #edges = {edge for face in mesh.faces for edge in get_face_edges(face)}\n #for k, cluster in enumerate(get_connected_components(indices, edges)):\n # new_name = '{}#{}'.format(name, k)\n # new_indices = sorted(cluster)\n # new_vertices = [vertices[i] for i in new_indices]\n # new_index_from_old = {i2: i1 for i1, i2 in enumerate(new_indices)}\n # new_faces = [tuple(new_index_from_old[i1] for i1 in face)\n # for face in mesh.faces if set(face) <= cluster]\n # new_meshes[new_name] = Mesh(new_vertices, new_faces)\n return meshes\n\n\ndef transform_obj_file(obj_string, transformation):\n new_lines = []\n for line in obj_string.split('\\n'):\n tokens = line.split()\n if not tokens or (tokens[0] != 'v'):\n new_lines.append(line)\n continue\n vertex = list(map(float, tokens[1:]))\n transformed_vertex = transformation.dot(vertex)\n new_lines.append('v {}'.format(' '.join(map(str, transformed_vertex))))\n return '\\n'.join(new_lines)\n\n\ndef read_mesh_off(path, scale=1.0):\n \"\"\"\n Reads a *.off mesh file\n :param path: path to the *.off mesh file\n :return: tuple of list of vertices and list of faces\n \"\"\"\n with open(path) as f:\n assert (f.readline().split()[0] == 'OFF'), 'Not OFF file'\n nv, nf, ne = [int(x) for x in f.readline().split()]\n verts = [tuple(scale * float(v) for v in f.readline().split()) for _ in range(nv)]\n faces = [tuple(map(int, f.readline().split()[1:])) for _ in range(nf)]\n return Mesh(verts, faces)\n\n\ndef read_pcd_file(path):\n \"\"\"\n Reads a *.pcd pointcloud file\n :param path: path to the *.pcd pointcloud file\n :return: list of points\n \"\"\"\n with open(path) as f:\n data = f.readline().split()\n num_points = 0\n while data[0] != 'DATA':\n if data[0] == 'POINTS':\n num_points = int(data[1])\n data = f.readline().split()\n continue\n return [tuple(map(float, f.readline().split())) for _ in range(num_points)]\n","sub_path":"src/pb_robot/meshes.py","file_name":"meshes.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"382593193","text":"#!/usr/bin/python\n#codeing-utf-8\n##############################################################################\n#\n# Copyright (c) Inspur Co., Ltd. Unpublished\n#\n# Inspur Co., Ltd.\n# Proprietary & Confidential\n#\n# This source code and the algorithms implemented therein constitute\n# confidential information and may comprise trade secrets of Inspur\n# or its associates, and any use thereof is subject to the terms and\n# conditions of the Non-Disclosure Agreement pursuant to which this\n# source code was originally received.\n#\n##############################################################################\n#\n#modification history \n#\n#01a,19Jun 2015,wf written\n#\n\n#these defined in fw_common.xml\nTAG_FWCONFIG='fw_config'\nTAG_ARCH='arch'\nTAG_CHIP='chip'\nTAG_CHIPVER='chip_ver'\nTAG_CPUTYPE='cpu_type'\nTAG_MEMSIZE='mem_size'\nTAG_ROMSIZE='rom_size'\nTAG_STBMODULE='stb_model'\nTAG_STBDEFINITTYPE='stb_definit_type'\nTAG_TRANSTYPE='stb_trans_type'\nTAG_STBBRAND='stb_brand'\nTAG_STBPROVIDERID='stb_provider_id'\nTAG_STBMODELID='stb_model_id'\nTAG_HARDWAREVER='hardware_ver'\nTAG_SECURITY='security_type'\nTAG_MULTISPLASH='multi_splash'\nTAG_ENCRYPTION='encryption_chip'\nTAG_FRONTPANEL='frontpanel_type'\n\nTAG_SOFTWAREVER='software_ver'\nTAG_SYSTEMVER='system_ver'\nTAG_OPERATORSOFTWAREVER='operator_software_ver'\n\nTAG_PDTNAME='pdt_name'\n\nTAG_PORTINGMODULES='porting_modules'\nTAG_PKMEMMAP='pkmemmap'\nTAG_SUDO='isudo'\nTAG_PORTINGCONFIG='porting_config'\nTAG_AREA='area'\n\nTAG_PORTINGRUNCONFIG='running_config'\n\nMODULE_DEFAULT='''\ni.mk.init $(S)/make/tools.mk\n\ninclude ../porting/cfg/m_port_iosal\ninclude ../porting/cfg/m_port_bus\ninclude ../porting/cfg/m_port_network\ninclude ../porting/cfg/m_port_rsc\ninclude ../porting/cfg/m_port_flash\ninclude ../porting/cfg/m_port_usb\ninclude ../porting/cfg/m_port_demux\ninclude ../porting/cfg/m_port_tve\ninclude ../porting/cfg/m_port_test\ninclude ../porting/cfg/m_monitor\ninclude ../porting/cfg/m_callsyscmd\ninclude ../porting/cfg/m_port_cloud\n'''\n\nBUILD_DEFAULT='''\nbuild \"porting\" {\n\tfile mian_test/*.c \n noauto\n}\n'''\n\nENV_TAG_LIST=[TAG_PDTNAME]\n\n#end with \" mean it's a string\nDEFINE_LIST={\n TAG_CHIP:'defs config:port_CHIP=\"',\n TAG_SOFTWAREVER:'defs config:port_SWVER=',\n TAG_SYSTEMVER:'defs config:port_SYSVER=\"',\n TAG_OPERATORSOFTWAREVER:'defs config:port_OPERATORSOFTWAREVER=\"',\n TAG_ENCRYPTION:'defs config:port_ENCRYPTIONCHIP=',\n TAG_SECURITY:'defs config:port_CATYPE=PORT_CATYPE_',\n TAG_FRONTPANEL:'defs config:port_FRONTPANEL=PORT_FP_'\n }\n\nTAG_TVE_ENCRYPT='TVE_ENCRYPT'\nTAG_EMERGENCY_UPGRADE='EMERGENCY_UPGRADE'\nTAG_M3U8CHECK='M3U8_CHECK'\nDEPEND_LIB={\n TAG_TVE_ENCRYPT:{\n'0':'',\n'1':'LIBTVEENCRYPT=-L$(OPENSOUCE_TOP)/usr/local/lib -ldvbcsa\\n'\n },\nTAG_M3U8CHECK:{\n'0':'',\n'1':'LIBM3U8CHECK=-L$(OPENSOUCE_TOP)/usr/local/lib -lcurl\\n'\n },\n TAG_EMERGENCY_UPGRADE:\n {\n'0':'',\n'1':'LIBEMERGENCYUPGRADE=-L$(BOOTLOADER_TOP)/crypto/ -lcryptsdk\\n'\n },\n }\n\n#tag in fwcomon.xml put here. \nRUNNING_LIST=[TAG_CPUTYPE,TAG_MEMSIZE,TAG_ROMSIZE,TAG_STBMODULE,TAG_HARDWAREVER\n ,TAG_STBMODULE,TAG_STBDEFINITTYPE,TAG_TRANSTYPE,TAG_STBBRAND\n ,TAG_STBPROVIDERID,TAG_STBMODELID\n ]\nPKFILEXML='/tmp/PKData.bin'\n\n#stbinfo xml include RUNNING_LIST and tag in porting_compile/running_config \nXMLHEAD_STBINFO='''\n\n\nInspur\n/root/config\n'''\nXMLEND_STBINFO=''\n","sub_path":"porting_lib/porting_tag.py","file_name":"porting_tag.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589681222","text":"\nimport numpy as np, sys\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Embedding\nfrom keras.layers import Input\nfrom keras.layers import GlobalAveragePooling1D, Dropout\nfrom keras.datasets import imdb\nfrom keras.optimizers import Adam\n\n\nfrom utils import load_pkl, gather_features, dump_pkl\n\n\ndef create_ngram_set(input_list, ngram_value=2):\n return set(zip(*[input_list[i:] for i in range(ngram_value)]))\n\ndef add_ngram(sequences, token_indices, ngram_range=2):\n new_sequences = []\n for input_list in sequences:\n new_list = input_list[:]\n for i in range(len(new_list) - ngram_range + 1):\n for ngram_value in range(2, ngram_range + 1):\n ngram = tuple(new_list[i:i+ngram_value])\n if ngram in token_indices:\n new_list.append(token_indices[ngram])\n new_sequences.append(new_list)\n return new_sequences\n\nngram_range = 1\n#max_features = 25000\nmaxlen = 3000\nbatch_size = 32\nembedding_dims = 300\n\nyData = load_pkl('data/plotFeatures_with_reverse_val')\ny_test = load_pkl('data/valLabels')\nx_test = [d[0][0000:].tolist() for d in yData]\n\nyData = load_pkl('data/plotFeatures_with_reverse_train')\ny_train = load_pkl('data/trainLabels')\nx_train = [d[0][0000:].tolist() for d in yData]\n\nyData = load_pkl('data/plotFeatures_with_reverse_test')\ny_final_test = load_pkl('data/testLabels')\nx_final_test = [d[0][0000:].tolist() for d in yData]\n\nmf = 0\nfor i in x_train:\n m = max(i)\n if m>mf:\n mf=m\nfor i in x_test:\n m = max(i)\n if m>mf:\n mf=m\nfor i in x_final_test:\n m = max(i)\n if m>mf:\n mf=m\n\nmax_features = mf+1\n#(x_train, y_train), (x_test, y_test) = imdb.load_data()\nprint()\nprint ('Average train sequence length: {}'.format(np.mean(list(map(len, x_train)), dtype=int)))\nprint ('Average test sequence length: {}'.format(np.mean(list(map(len, x_test)), dtype=int)))\nprint ('Average test sequence length: {}'.format(np.mean(list(map(len, x_final_test)), dtype=int)))\n\nif ngram_range > 1:\n print( 'Adding {}-gram features'.format(ngram_range))\n\n ngram_set = set()\n for input_list in x_train:\n for i in range(2, ngram_range+1):\n set_of_ngram = create_ngram_set(input_list, ngram_value=i)\n ngram_set.update(set_of_ngram)\n start_index = max_features + 1\n token_indices = {v: k + start_index for k, v in enumerate(ngram_set)}\n indice_token = {token_indices[k]: k for k in token_indices}\n\n # max_features is the highest integer that could be found in the dataset.\n max_features = np.max(list(indice_token.keys())) + 1\n\n # Augmenting x_train and x_test with n-grams features\n x_train = add_ngram(x_train, token_indices, ngram_range)\n x_test = add_ngram(x_test, token_indices, ngram_range)\n x_final_test = add_ngram(x_final_test, token_indices, ngram_range)\n print( 'Average train sequence length: {}'.format(np.mean(list(map(len, x_train)), dtype=int)))\n print( 'Average test sequence length: {}'.format(np.mean(list(map(len, x_test)), dtype=int)))\n print( 'Average test sequence length: {}'.format(np.mean(list(map(len, x_final_test)), dtype=int)))\n\n#print 'Pad sequences (samples x time)'\n#x_train = sequence.pad_sequences(x_train, maxlen=maxlen)\n#sys.exit()\n#x_test = sequence.pad_sequences(x_test, maxlen=maxlen)\n\nx_train, x_test = np.array(x_train), np.array(x_test)\nx_final_test = np.array(x_final_test)\nprint ('x_train shape:', x_train.shape)\nprint ('x_test shape:', x_test.shape)\nprint ('x_test shape:', x_final_test.shape)\n\nprint ('Build model...')\nmodel = Sequential()\n\n# we start off with an efficient embedding layer which maps\n# our vocab indices into embedding_dims dimensions\nprint (x_test[0])\nprint (max_features)\nembeddingWeights = load_pkl('data/glove_embeddings/glove_weights')\n\n#input_layer = Input(shape=(1,), dtype='int32')\n\n# embedding = Embedding(max_features+1,\n# embedding_dims,\n# input_length=maxlen,\n# weights=[embeddingWeights])\n\nembedding = Embedding(max_features+1,\n embedding_dims,\n input_length=maxlen)\nmodel.add(embedding)\n\n# we add a GlobalAveragePooling1D, which will average the embeddings\n# of all words in the document\nmodel.add(GlobalAveragePooling1D())\n# We project onto a single unit output layer, and squash it with a sigmoid:\n#model.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(13, activation='sigmoid'))\n\nadam = Adam(lr=0.01, decay=1e-3)\nmodel.compile(loss='binary_crossentropy',\n optimizer=adam,\n metrics=['accuracy'])\n\n#model.load_weights('data/weights/fasttext_uni.h5')\n#model.load_weights('data/glove_embeddings/best_weights_glove.h5')\n#scores = model.predict(x_train)\n#dump_pkl((y_train, scores), 'train_pred_fasttext')\nfrom keras.callbacks import ModelCheckpoint, RemoteMonitor\n\nprint (max_features)\n#remote = RemoteMonitor(root='http://128.143.63.199:9009')\n#check_glove = ModelCheckpoint(filepath='data/glove_embeddings/best_weights_glove.h5',verbose=1, save_best_only=True, monitor='val_acc')\n#check = ModelCheckpoint(filepath='data/weights/fasttext_uni_64_drop.h5', save_weights_only=True, mode='max',\n#monitor='val_acc', save_best_only=True, verbose=1)\nepochs=150\nmodel.fit(x_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_data=(x_test, y_test))\n\nscores = model.evaluate(x_final_test, y_final_test, batch_size=batch_size)\n\nprint(\"Accuracy: \", str(scores[1]))","sub_path":"fastText - Copy.py","file_name":"fastText - Copy.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"194292680","text":"import requests\nimport xml.etree.ElementTree as ET\nfrom document.models import Document\nimport string\nimport re\nimport spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nimport xmltodict\nfrom Bio import Entrez\n\n\nspacy_nlp = spacy.load('en_core_web_sm')\npunctuations = string.punctuation\nstop_words = spacy.lang.en.stop_words.STOP_WORDS\n\ndef search(term, num_article):\n\tEntrez.api_key = 'f949f78d21fff30c490ba1c886fd214ae708'\n\tEntrez.email = 'kburakozer@yahoo.com'\n\n\tsearch_term = Entrez.esearch(db=\"pubmed\", term=term, retmax=num_article)\n\tresult = Entrez.read(search_term)\n\tsearch_term.close()\n\tid_list = result[\"IdList\"]\n\n\treturn id_list\n\n\t\t\ndef get_details(id_list):\n\t\tEntrez.api_key = 'f949f78d21fff30c490ba1c886fd214ae708'\n\t\tEntrez.email = 'kburakozer@yahoo.com'\n\t\tdetails_handle = Entrez.efetch(db=\"pubmed\",id=id_list, retmode=\"xml\", rettype=\"abstract\",retmax=100)\n\t\tdetails_xml = details_handle.read()\n\t\tdetails = xmltodict.parse(details_xml)\n\t\tarticle_list = details.get('PubmedArticleSet').get('PubmedArticle')\n\t\tdetails_handle.close()\n\t\treturn article_list\n\n\ndef get_pmid(article):\n\tid = article.get('MedlineCitation').get('PMID').get('#text')\n\tif id:\n\t\treturn id\n\telse:\n\t\treturn \"\"\n\ndef get_title(article):\n\ttitle = article.get('MedlineCitation').get('Article').get('ArticleTitle')\n\tif title:\n\t\treturn title\n\telse:\n\t\treturn \"\"\n\n\ndef get_date(article):\n\tyear = article.get('MedlineCitation').get('DateRevised').get('Year')\n\tmonth = article.get('MedlineCitation').get('DateRevised').get('Month')\n\tday = article.get('MedlineCitation').get('DateRevised').get('Day')\n\tdata = \"\"\n\ttry:\n\t\tdate = day+\".\"+month+\".\"+year\n\texcept:\n\t\tpass\n\treturn date\n\n\ndef get_author(article):\n\tauthor_list = article.get('MedlineCitation').get('Article').get('AuthorList')\n\n\tauthor_name = \"\"\n\tif author_list:\n\t\tfor author in author_list.get('Author'):\n\n\t\t\ttry:\n\t\t\t\tfirst_name = author.get('ForeName')\n\t\t\t\tlast_name = author.get('LastName')\n\t\t\t\tfull_name = first_name + \" \" + last_name+ \", \"\n\t\t\t\tauthor_name += full_name\n\t\t\texcept:\n\t\t\t\t#print(\"no name\")\n\t\t\t\tpass\n\treturn author_name\n\n\ndef get_doi(article):\n\tdoi = \"\"\n\ttry:\n\t\tdoi = article.get('MedlineCitation').get('Article').get('ELocationID').get('#text')\n\n\texcept:\n\t\tpass\n\treturn doi\n\n\ndef get_abstract(article):\n\n\tabstract = \"\"\n\ttry:\n\t\tabstract_dict = article.get('MedlineCitation').get('Article').get('Abstract').get('AbstractText')\n\n\t\tif type(abstract_dict) is str:\n\t\t\treturn abstract_dict\n\t\telif type(abstract_dict) is list:\n\t\t\tfor item in abstract_dict:\n\t\t\t\tabstract += item.get('#text')\n\texcept:\n\t\tpass\n\treturn abstract\n\n\ndef get_keyword(article):\n\tkeyword_list = []\n\n\ttry:\n\t\tkeywords = article.get('MedlineCitation').get('KeywordList').get('Keyword')\n\t\tif keywords:\n\t\t\tif type(keywords) is list:\n\t\t\t\n\t\t\t\tfor item in keywords:\n\t\t\t\t\tkeyword_list.append(item.get('#text'))\n\t\t\telse:\n\n\t\t\t\tkeyword_list = keywords.get('#text').split(',')\n\texcept:\n\t\tpass\n\n\n\treturn keyword_list\n\n\ndef tokenize(abstract):\n\tnew_s = \"\"\n\tfor i in string.punctuation:\n\t\tif i != '.':\n\t\t\tnew_s += i\n\n\tabstract = re.sub(r\"[0-9]\", '', abstract)\n\tabstract = re.sub(r'#\\S+', '', abstract)\n\tabstract = re.sub(r'\\S@\\S+', '', abstract)\n\tabstract = re.sub(r'\\S+com', '', abstract)\n\ttable = abstract.maketrans(\"\", \"\", new_s)\n\tabstract2 = abstract.translate(table)\n\t\n\t#creating token object\n\ttokens = spacy_nlp(abstract)\n\n \n\n #lower, strip and lemmatize\n\ttokens = [word.lemma_.lower().strip() if word.lemma_ != \"-PRON-\" else word.lower_ for word in tokens]\n \n #remove stopwords, and exclude words less than 2 characters\n\ttokens = [word for word in tokens if word not in stop_words and word not in punctuations and len(word) > 2]\n\treturn tokens\n\n\n\n\n\ndef create_db():\n id_list = search(\"emotional intelligence\", 60000)\n start = 0\n stop = 100\n total = int(60000/100)\n for j in range(total):\n ids = id_list[start:stop]\n start +=100\n stop += 100\n articles = get_details(ids)\n for i in (articles):\n abstract2 = get_abstract(i)\n Document.objects.create(doc_id = get_pmid(i),\n title = get_title(i),\n author = get_author(i),\n year = get_date(i),\n abstract = get_abstract(i),\n doi = get_doi(i),\n keywords = get_keyword(i),\n tokens = tokenize(abstract2))\n query_result = Document.objects.all()\n\n return query_result\n\ndef delete_duplicates():\n\tdocuments = Document.objects.all()\n\tdoc_numbers =[]\n\n\tfor item in documents:\n\t\tif item.doc_id not in doc_numbers:\n\t\t\tdoc_numbers.append(item.doc_id)\n\t\telse:\n\t\t\titem.delete()","sub_path":"document/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"478725999","text":"import logging\nimport os\n\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.http import Http404\nfrom django.shortcuts import redirect\nfrom dropbox.oauth import *\n\nfrom ..models import DropboxToken\n\nlogger = logging.getLogger(__name__)\n\n# Create your views here.\nAPP_KEY = os.environ['DBX_APP_KEY']\nAPP_SECRET = os.environ['DBX_APP_SECRET']\n\ndef get_dropbox_auth_flow(session):\n redirect_uri = \"https://localhost:8000/dropbox-auth-finish\"\n return DropboxOAuth2Flow(\n APP_KEY, APP_SECRET, redirect_uri, session,\n \"dropbox-auth-csrf-token\")\n\n# URL handler for /dropbox-auth-start\ndef dropbox_auth_start(request):\n authorize_url = get_dropbox_auth_flow(request.session).start()\n return redirect(authorize_url)\n\n\ndef dropbox_auth_finish(request):\n try:\n\n flow = get_dropbox_auth_flow(request.session)\n oauth_result = flow.finish(request.GET)\n\n except BadRequestException as e:\n raise Http404\n except BadStateException as e:\n # Start the auth flow again.\n redirect(\"/dropbox-auth-start\")\n except CsrfException as e:\n raise Http404\n except NotApprovedException as e:\n print('Not approved? Why not?')\n return redirect(\"/home\")\n except ProviderException as e:\n logger.log(\"Auth error: %s\" % (e,))\n raise Http404\n\n else:\n request.session['dbx_oauth'] = {'access_token':oauth_result.access_token,\n 'user_id': oauth_result.user_id}\n\n\n user = authenticate(dbx_user_id=oauth_result.user_id)\n login(request, user)\n\n try: #save token for later\n d = DropboxToken.objects.get(user=user)\n d.access_token = oauth_result.access_token\n d.save()\n except DropboxToken.DoesNotExist:\n DropboxToken.objects.create(user=user, access_token=oauth_result.access_token)\n\n\n return redirect('home')\n\n\ndef logout(request):\n auth_logout(request)\n return redirect('home')\n\n","sub_path":"spike/flow/views/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"555467873","text":"import datetime\nimport os\n\nimport shapefile\n\nbase_path = os.path.dirname(__file__)\n\ncountry_shapes = shapefile.Reader(\n os.path.join(base_path, '../data/CShapes.shp'))\n\ncountry_list = list()\nbreak_points = set()\nshapes = {}\nnames = {}\n\nfor shape_record in country_shapes.shapeRecords():\n shape = shape_record.shape\n record = shape_record.record\n cows_year = int(record[7])\n cows_month = int(record[8])\n cows_day = int(record[9])\n cowe_year = int(record[10])\n cowe_month = int(record[11])\n cowe_day = int(record[12])\n country_name = record[0].strip()\n feature_id = record[5]\n\n cows = datetime.date(cows_year, cows_month, cows_day)\n cowe = datetime.date(cowe_year, cowe_month, cowe_day)\n\n break_points.add(cows)\n break_points.add(cowe)\n country_list.append((feature_id, cows, cowe))\n shapes[feature_id] = shape\n names[feature_id] = country_name\n\nintervals = {}\ncurrent_point = None\nbreak_points_iter = iter(sorted(break_points))\ndone = False\nwhile not done:\n try:\n next_point = next(break_points_iter)\n if current_point is not None:\n intervals[(current_point, next_point)] = []\n current_point = next_point\n except StopIteration:\n done = True\n\nfor interval in intervals:\n for country in country_list:\n if country[1] <= interval[1] and country[2] >= interval[0]:\n intervals[interval].append(country[0])\n if intervals[interval]:\n output_file_path = os.path.join(\n base_path,\n '../data/CShapes_date/CShapes_%s_%s' % (\n interval[0].strftime('%d_%m_%y'),\n interval[1].strftime('%d_%m_%y')))\n writer = shapefile.Writer()\n writer.field('CNTRY_NAME', 'C', 28, 0)\n writer.field('FEATUREID', 'C', 28, 0)\n for country in intervals[interval]:\n writer.records.append([names[country], country])\n writer._shapes.append(shapes[country])\n writer.save(target=output_file_path)\n","sub_path":"scripts/create_shapefiles_based_on_change.py","file_name":"create_shapefiles_based_on_change.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"618444590","text":"import serial\nimport time\n\n#Working but slow\n#inputBufferSize = 1000\n#inputMedian = 90\n\ninputBufferSize = 400\ninputMedian = inputBufferSize/5\n\ninputBuffer = [0 for i in range(inputBufferSize)]\ninputBufferFiltered = [0 for i in range(inputBufferSize)]\ncounter = 0\nbufferValid = False\nser = serial.Serial(\n port='/dev/ttyACM0',\\\n baudrate=9600,\\\n parity=serial.PARITY_NONE,\\\n stopbits=serial.STOPBITS_ONE,\\\n bytesize=serial.EIGHTBITS,\\\n timeout=50)\n\n\n\ndef median(arr):\n med = [0 for i in range(inputMedian)]\n pos=counter\n\n for i in range(inputMedian):\n pos = counter-i\n if pos<0:\n pos=pos+inputBufferSize\n med[i]=inputBuffer[pos]\n\n return (sorted(med)[inputMedian/2])\n\ndef mean(arr):\n mean = 0\n for i in inputBuffer:\n mean = mean + i\n\n return mean/inputBufferSize\n\nif __name__ == \"__main__\":\n print(\"Raw\",\"Median\",\"Lower\",\"Upper\")\n\n while True:\n line = ser.readline()\n line = line.strip()\n tokens = line.split(',')\n if len(tokens)<3:\n print(\"Invalid data\")\n# print(tokens)\n else:\n val = tokens[2].split(':')[1].strip()\n inputBuffer[counter]=int(float(val))\n inputBufferFiltered[counter]=mean(inputBuffer)\n counter=counter+1\n if counter == inputBufferSize:\n bufferValid=True\n counter=0\n\n if bufferValid:\n med = median(inputBuffer)\n print(time.time(),int(float(val)),med,mean(inputBufferFiltered)*0.97,mean(inputBufferFiltered)*1.03)\n\n ser.close()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"234764120","text":"#10.1. Crea una función que reciba 3 números y devuelva su suma.\n\ndef suma(n1, n2, n3):\n return n1+n2+n3\n \nprint(\"La suma de 6, 7 y 8 es\", suma(6,7,8) )\n\n\n\n\n#10.2. Crea una función que reciba una cadena de texto y una letra, y devuelva la cantidad de veces que la letra aparece dentro de la cadena.\n\ndef cantidadVeces(texto, letra):\n cantidad = 0\n for l in texto:\n if l == letra:\n cantidad += 1\n return cantidad\n \nprint('Veces que \"hasta mañana\" contiene una \"a\":',\n cantidadVeces(\"hasta mañana\", \"a\") )\n\n\n\n\n#10.3. Crea un procedimiento que escriba una línea formada por 2 letras, repetidas varias veces. Por ejemplo, para \"-\", \"=\" y 3, escribiría \"-=-=-=\".\n\ndef repetir(letra1, letra2, veces):\n for i in range(0, veces):\n print(letra1, end=\"\")\n print(letra2, end=\"\")\n \nrepetir(\"-\", \"=\", 3)\n","sub_path":"Ficheros1.py","file_name":"Ficheros1.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"652134853","text":"import olac\nimport sys\nimport os\nimport codecs\nfrom lib import *\n\nsys.path.insert(0, olac.olacvar('pywebapi'))\n\ntry:\n from nitems import *\nexcept ImportError:\n print >>sys.stderr, \"Failed to import nitems module from dir:\"\n print >>sys.stderr, olac.olacvar('pywebapi')\n sys.exit(1)\n\n# getTable function\ndumpcall(getTable, path='nitems')\n\n# byCountryCode\ntabfile = olac.olacvar('data/num_items_by_country')\nf = open(tabfile)\nf.readline()\nS = set()\nfor l in f:\n a = l.rstrip(\"\\r\\n\").split('\\t')\n if a[2] not in S:\n dumpcall(byCountryCode, [a[2]], path='nitems')\n dumpcall(byCountryCode, [a[2], \"true\"], path='nitems')\n S.add(a[2])\n\n# byArea\ntabfile = olac.olacvar('data/num_items_by_country')\nf = open(tabfile)\nf.readline()\nS = set()\nfor l in f:\n a = l.rstrip(\"\\r\\n\").split('\\t')\n if a[0] not in S:\n dumpcall(byArea, [a[0]], path='nitems')\n dumpcall(byArea, [a[0], \"true\"], path='nitems')\n S.add(a[0])\n","sub_path":"nonweb/pkg/JsonScripts/0.1/nitems.py","file_name":"nitems.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"144018763","text":"import configparser\nimport toggler\nfrom datetime import datetime\n\nparser = configparser.ConfigParser()\nparser.read('config.ini')\n\ntoken = parser['account']['api_token']\nworkspace_id = parser['account']['workspace_id']\nemail = parser['account']['email']\n\nclient = toggler.Client(token)\n\nclient.user_agent = email\nclient.workspace_id = workspace_id\n\nparams = {\n \"since\": \"2019-06-01\",\n \"until\": \"2019-06-30\"\n}\n\nresponse = client.get_detail_report(params=params)\n\nfor d in response['data']:\n print(client.convert_time(d['start']))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189539421","text":"\"\"\"\n============================\nAuthor:ann\nDate:2020/3/3\nTime:10:16\nE-mail:326329411@qq.com\nMobile:15821865916\n============================\n\"\"\"\nimport unittest\nimport os\nimport jsonpath\nfrom library.ddt import ddt, data\nfrom common.read_write_excel import ReadWriteExcel\nfrom common.handlerpath import DATA_DIR\nfrom common.connectdb import DB\nfrom common.handlerrequests import HandlerRequests\nfrom common.handlerconfig import conf\nfrom common.handlerlog import log\nfrom common.handlerdata import CaseData\nfrom common.handle_sign import HandleSign\n\ncase_file = os.path.join(DATA_DIR, \"apicases.xlsx\")\n@ddt\nclass TestLoans(unittest.TestCase):\n excel = ReadWriteExcel(case_file, \"loans\")\n cases = excel.read_excel()\n request = HandlerRequests()\n db = DB()\n\n @classmethod\n def setUpClass(cls):\n url = conf.get('env', 'base_url') + '/member/login'\n data = {\n 'mobile_phone': conf.get('test_data', 'admin_mobile_phone'),\n 'pwd': conf.get('test_data', 'admin_pwd')\n }\n headers = eval(conf.get('env', 'headers'))\n\n response = cls.request.send_request(url=url, json=data, headers=headers, method='post')\n res = response.json()\n token = jsonpath.jsonpath(res, '$..token')\n token_type = jsonpath.jsonpath(res, '$..token_type')\n CaseData.token_value = token_type[0] + ' ' + token[0]\n CaseData.member_id = jsonpath.jsonpath(res, '$..id')[0]\n CaseData.token = token[0]\n\n @data(*cases)\n def test_loans(self, case):\n url = conf.get('env','base_url')+case['url']\n method= case['method']\n data = eval(case['data'])\n # 在请求体中加入,时间戳和签名\n sign_info = HandleSign.generate_sign(getattr(CaseData, \"token\"))\n data.update(sign_info)\n headers=eval(conf.get('env','headers'))\n headers['Authorization'] = getattr(CaseData,'token_value')\n expected = eval(case[\"expected\"])\n row = case[\"case_id\"] + 1\n\n response=self.request.send_request(url=url,method=method,params=data,headers=headers)\n res = response.json()\n print('项目列表接口返回的结果:',res)\n try:\n self.assertEqual(res['code'],expected['code'])\n except Exception as e:\n self.excel.write_excel(row=row,column=8,value='未通过')\n log.error('测试用例{}执行未通过'.format(case['title']))\n log.exception(e)\n raise e\n else:\n self.excel.write_excel(row=row,column=8,value='通过')\n log.info('测试用例执行通过')","sub_path":"testcases/test_loans.py","file_name":"test_loans.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"329506801","text":"#!/usr/bin/env python3\n\"\"\"\nKilauea_Project\n@author: bruce.eo.thomas\n\"\"\"\n\n\"\"\"\nScript for the ANNEX Class \n\"\"\"\n\n# Moduls imported\nimport numpy as np\n\n\nclass Annex():\n \n def __init__(self, name):\n self.name = name\n \n def get_y(self, ifit, sub, isite):\n \"\"\"\n We suppose first that there is only 2 time zones. So len_tz == 2.\n \"\"\"\n \n # Create the list with time zones to study \n list_startstop = [ifit[0]]\n i = 0\n while i <= len(ifit)-2:\n if ifit[i+1] != ifit[i] + 1:\n list_startstop.append(ifit[i])\n list_startstop.append(ifit[i+1])\n i += 1\n list_startstop.append(ifit[-1])\n \n # Count number of time zone\n #len_tz = len(list_startstop) / 2\n \n # Create the sub-divisions of sub\n stop1 = list_startstop[1]\n sub1 = sub[isite, :stop1]\n start2 = list_startstop[2]-1\n sub2 = sub[isite, start2:]\n # Transpose sub-divisions \n sub1T = sub1.T\n sub2T = sub2.T\n \n # Concatenate the sub-divisions\n yT = np.concatenate((sub1T, sub2T))\n # Transpose to have final matrix\n y = yT.T\n \n return([y, sub1, sub2])","sub_path":"scripts/annex.py","file_name":"annex.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"259190153","text":"import json\nimport logging\nfrom typing import Dict\n\nLOG = logging.getLogger(__name__)\n\n\ndef save_config(config: Dict):\n \"\"\"Helper for saving a config\n\n :param config: Dictionary representing a model configuration\n \"\"\"\n fpath = config['config_fpath']\n with open(fpath, 'w') as f:\n json.dump(config, f, indent=4, sort_keys=True)\n LOG.info(\n f'Saved configuration to {fpath}'\n )\n\n\ndef load_config(config_fpath: str) -> Dict:\n \"\"\"loads a model configuration from a file path\n\n :param config_fpath: File path to a model configuration .json\n :return: Dictionary representing a model configuration\n \"\"\"\n with open(config_fpath) as fp:\n config = json.load(fp)\n LOG.info(\n f'Loaded configuration from {config_fpath}'\n )\n\n return config\n","sub_path":"modules/model/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"303803777","text":"from __future__ import unicode_literals\n\nimport glob\nimport io\nimport os\nfrom collections import defaultdict\n\nfrom builtins import next\nfrom future.utils import iteritems\nfrom snips_nlu_utils import normalize\n\nfrom snips_nlu.constants import (STOP_WORDS, WORD_CLUSTERS, GAZETTEERS, NOISE,\n RESOURCES_PATH, LANGUAGE_EN, LANGUAGE_FR,\n LANGUAGE_ES, LANGUAGE_KO, LANGUAGE_DE,\n LANGUAGE_JA, STEMS)\nfrom snips_nlu.languages import get_ignored_characters_pattern\nfrom snips_nlu.tokenization import tokenize\nfrom snips_nlu.utils import get_resources_path\n\nRESOURCE_INDEX = {\n LANGUAGE_DE: {\n GAZETTEERS: [\n \"top_10000_words.txt\"\n ],\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n },\n LANGUAGE_EN: {\n GAZETTEERS: [\n \"top_10000_words.txt\"\n ],\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n WORD_CLUSTERS: [\"brown_clusters.txt\"]\n },\n LANGUAGE_ES: {\n GAZETTEERS: [\n \"top_10000_words.txt\"\n ],\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n },\n LANGUAGE_FR: {\n GAZETTEERS: [\n \"top_10000_words.txt\"\n ],\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n },\n LANGUAGE_JA: {\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n },\n LANGUAGE_KO: {\n STOP_WORDS: \"stop_words.txt\",\n NOISE: \"noise.txt\",\n },\n}\n\n_RESOURCES = defaultdict(dict)\n\n\nclass UnknownResource(LookupError):\n pass\n\n\nclass UnloadedResources(LookupError):\n pass\n\n\ndef get_language_resource(language):\n if language not in _RESOURCES:\n raise UnloadedResources(\n \"Missing resources for '{}', please load them with the \"\n \"load_resources function\".format(language))\n return _RESOURCES[language]\n\n\ndef get_resource(language, resource_name):\n language_resource = get_language_resource(language)\n try:\n return language_resource[resource_name]\n except KeyError:\n raise UnknownResource(\"Unknown resource '{}' for '{}' \"\n \"language\".format(resource_name, language))\n\n\ndef _load_stop_words(language):\n stop_words = set()\n if STOP_WORDS in RESOURCE_INDEX[language]:\n stop_words_file_path = os.path.join(\n get_resources_path(language),\n RESOURCE_INDEX[language][STOP_WORDS])\n with io.open(stop_words_file_path, encoding='utf8') as f:\n lines = (normalize(l) for l in f)\n stop_words = set(l for l in lines if l)\n return stop_words\n\n\ndef get_stop_words(language):\n return get_resource(language, STOP_WORDS)\n\n\ndef _load_noises(language):\n noise = \"\"\n if NOISE in RESOURCE_INDEX[language]:\n noise_path = os.path.join(\n get_resources_path(language),\n RESOURCE_INDEX[language][NOISE])\n with io.open(noise_path, encoding='utf8') as f:\n # Here we split on a \" \" knowing that it's always ignored by\n # the tokenization, see tokenization unit tests.\n # We don't really care about tokenizing precisely as this noise\n # is just used to generate fake query that will be\n # re-tokenized\n noise = next(f).split()\n return noise\n\n\ndef get_noises(language):\n return get_resource(language, NOISE)\n\n\ndef _load_clusters(language):\n word_clusters_paths = {\n os.path.splitext(name)[0]: os.path.join(\n get_resources_path(language), name)\n for name in RESOURCE_INDEX[language].get(WORD_CLUSTERS, [])\n }\n clusters = dict()\n if WORD_CLUSTERS in RESOURCE_INDEX[language]:\n for name, path in iteritems(word_clusters_paths):\n with io.open(path, encoding=\"utf8\") as f:\n clusters[name] = dict()\n for l in f:\n split = l.rstrip().split(\"\\t\")\n if len(split) == 2:\n clusters[name][split[0]] = split[1]\n return clusters\n\n\ndef get_word_clusters(language):\n return get_resource(language, WORD_CLUSTERS)\n\n\ndef _load_gazetteers(language):\n gazetteers_paths = {\n os.path.splitext(name)[0]: os.path.join(\n get_resources_path(language), name)\n for name in RESOURCE_INDEX[language].get(GAZETTEERS, [])\n }\n gazetteers = dict()\n for name, path in iteritems(gazetteers_paths):\n with io.open(path, encoding=\"utf8\") as f:\n gazetteers[name] = set()\n for l in f:\n normalized = normalize(l.strip())\n if normalized:\n normalized = get_ignored_characters_pattern(language).join(\n [t.value for t in tokenize(normalized, language)])\n gazetteers[name].add(normalized)\n return gazetteers\n\n\ndef get_gazetteers(language):\n return get_resource(language, GAZETTEERS)\n\n\ndef get_gazetteer(language, gazetteer_name):\n return get_gazetteers(language)[gazetteer_name]\n\n\ndef _load_verbs_lexemes(language):\n stems_paths = glob.glob(os.path.join(RESOURCES_PATH, language,\n \"top_*_verbs_lexemes.txt\"))\n if not stems_paths:\n return dict()\n\n verb_lexemes = dict()\n with io.open(stems_paths[0], encoding=\"utf8\") as f:\n for line in f:\n elements = line.strip().split(';')\n verb = normalize(elements[0])\n lexemes = elements[1].split(',')\n verb_lexemes.update(\n {normalize(lexeme): verb for lexeme in lexemes})\n return verb_lexemes\n\n\ndef _load_words_inflections(language):\n inflection_paths = glob.glob(os.path.join(RESOURCES_PATH, language,\n \"top_*_words_inflected.txt\"))\n if not inflection_paths:\n return dict()\n\n inflections = dict()\n with io.open(inflection_paths[0], encoding=\"utf8\") as f:\n for line in f:\n elements = line.strip().split(';')\n inflections[normalize(elements[0])] = normalize(elements[1])\n return inflections\n\n\ndef _load_stems(language):\n stems = _load_words_inflections(language)\n stems.update(_load_verbs_lexemes(language))\n return stems\n\n\ndef get_stems(language):\n return get_resource(language, STEMS)\n\n\ndef _load_resources(language):\n resources = dict()\n resources_fns = {\n WORD_CLUSTERS: _load_clusters,\n GAZETTEERS: _load_gazetteers,\n STOP_WORDS: _load_stop_words,\n NOISE: _load_noises,\n STEMS: _load_stems\n }\n for resources_name, resource_fn in iteritems(resources_fns):\n resource = resource_fn(language)\n if resource: # Don't add the resource if it's an emtpy dict or string\n resources[resources_name] = resource\n return resources\n\n\ndef load_resources(language):\n \"\"\"Load language specific resources\n\n Args:\n language (str): language\n\n Note:\n Language resources must be loaded before fitting or parsing\n \"\"\"\n if language in _RESOURCES:\n return\n _RESOURCES[language] = _load_resources(language)\n\n\ndef resource_exists(language, resource_name):\n \"\"\"Tell if the resource specified by the resource_name exist\n\n Args:\n language (str): language\n resource_name (str): the resource name\n Returns:\n bool: whether the resource exists or not\n \"\"\"\n return resource_name in _RESOURCES[language]\n","sub_path":"snips_nlu/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"523019358","text":"import re\n\n\nclass LexerError(Exception):\n pass\n\n\nclass Token:\n \"\"\"\n Basic token built by the lexer\n \"\"\"\n def __init__(self, type, value, lineno=None):\n self.type = type\n self.value = value\n self.lineno = lineno\n\n def __str__(self):\n return \" line %s\" % (self.type, str(self.lineno))\n\n def __eq__(self, other):\n if isinstance(other, str):\n return self.type == other\n\n elif isinstance(other, Token):\n return self.type == other.type\n\n else:\n return NotImplemented\n\n\nclass Lexer:\n \"\"\"\n Dynamic lexer, tokenize a string given a set of rules with the re library.\n\n Rules must be provided to Lexer.add_rules as a list of tuple (regex, rule) which first element is a regular\n expressions and second element is a string/function/None.\n If a rule is given as string, the Lexer returns a token with the string as type.\n If a rule is given as function, the Lexer calls the function on self and takes the return value as token type, this\n allows mainly to increment lines manually or do change to the Lexer. In particular, rules are dynamic and can be\n added/removed/overwritten during the lexing.\n If None is given as rule, the Lexer interprets the regular expression as a pattern to be ignored (in practice this\n is mostly for spaces, comments, etc.)\n\n As stated above, a function can be passed as rule to increment Lexer.lineno, although this is not the correct way\n to do line incrementation. Lexer has a line_rule attribute which can be set with Lexer.set_line_rule, this will\n automatically increment line number when the pattern is encountered. In particular, this will increment Lexer.lineno\n even if the pattern is encountered inside another pattern (a multi-line comments for say).\n\n Lexer.read appends a string to the current buffer\n\n Lexer.drop_old_buffer drops the part of the buffer read already\n\n Lexer.lex reads the Lexer.buffer and returns a Token or None if it reached the end of the buffer\n \"\"\"\n def __init__(self, buffer=None, rules=None, line_rule=None):\n\n self.lineno = 1\n self.pos = 0\n self.buffer = \"\"\n self.rules = []\n self.line_rule = None\n\n if buffer:\n self.read(buffer)\n\n if line_rule:\n self.set_line_rule(line_rule)\n\n if rules:\n self.add_rules(rules)\n\n def __copy__(self):\n \"\"\"\n Copy the lexer with its rules\n \"\"\"\n return Lexer(rules=self.rules, line_rule=self.line_rule)\n\n def __deepcopy__(self, memo):\n \"\"\"\n Copy the lexer with its rules and current state\n \"\"\"\n dup = Lexer(buffer=self.buffer,\n rules=self.rules,\n line_rule=self.line_rule)\n dup.lineno = self.lineno\n dup.pos = self.pos\n\n return dup\n\n def read(self, buffer):\n if not isinstance(buffer, str):\n raise LexerError(\"buffer must be a string\")\n\n self.buffer += buffer\n\n def drop_old_buffer(self):\n self.buffer = self.buffer[self.pos:]\n self.pos = 0\n\n def set_line_rule(self, line_rule):\n self.line_rule = line_rule\n self.add_rules([(line_rule, None)])\n\n def add_rules(self, rules):\n for regex, rule in rules:\n self.rules.append((regex, rule))\n\n def lex(self):\n if not self.buffer[self.pos:]:\n return None\n\n best_end = 0\n match = None\n rule = None\n\n # TODO: There probably is a better way to do this, by building a table\n for (regex, match_rule) in self.rules:\n current_match = re.match(regex, self.buffer[self.pos:])\n if current_match:\n\n current_end = current_match.end()\n\n if current_end > best_end:\n match = current_match\n rule = match_rule\n best_end = current_end\n\n if not match:\n raise LexerError(\"Syntax error at line %s\" % self.lineno)\n\n value = match.group()\n ignore = False\n\n if rule is None:\n ignore = True\n\n elif isinstance(rule, str):\n token = Token(rule, value, lineno=self.lineno)\n\n else:\n # We expect rule to be a function Lexer-Parser -> string/None\n # if a string is returned, it is taken as the Token type\n # if None is returned, the function.__name__ is taken as Token type\n\n try:\n token_type = rule(self)\n except TypeError:\n raise LexerError(\"Lexer rules must be string or function (Lexer-Parser as argument)\")\n\n if isinstance(token_type, str):\n pass\n elif token_type is None:\n ignore = True\n else:\n raise LexerError(\"Lexer rules functions must return string or None\")\n\n token = Token(token_type, value, lineno=self.lineno)\n\n # Update the Lexer-Parser\n self.pos += match.end()\n\n # TODO: change that by pre computing in add_rule phase if line_rule can match current regex\n # TODO: in other words we don't want to do this if regexps have no intersection\n if self.line_rule:\n line_rule_match = re.findall(self.line_rule, value)\n\n self.lineno += len(line_rule_match)\n\n # Return if a non-ignored pattern was found, else continue\n return self.lex() if ignore else token\n","sub_path":"src/Lexer/Lexer.py","file_name":"Lexer.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"13425251","text":"from datetime import date, timedelta\r\nfrom hashlib import sha256\r\n\r\nimport anyjson\r\nfrom braces.views import GroupRequiredMixin\r\nfrom django.conf import settings\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.tokens import PasswordResetTokenGenerator\r\nfrom django.contrib.auth.views import login\r\nfrom django.contrib.auth.models import Group\r\nfrom django.contrib.sites.models import Site\r\nfrom django.core.urlresolvers import reverse_lazy\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.shortcuts import redirect\r\nfrom django.template import RequestContext\r\nfrom django.template.loader import render_to_string\r\nfrom django.views.generic import View, TemplateView, FormView\r\nfrom django.utils.http import base36_to_int, int_to_base36\r\nfrom django.utils.translation import ugettext_lazy as _\r\nfrom extra_views import FormSetView\r\nfrom templated_email import send_templated_mail\r\n\r\n\r\nfrom lily.utils.functions import is_ajax\r\n\r\nfrom .forms import (CustomAuthenticationForm, RegistrationForm, ResendActivationForm, InvitationForm,\r\n InvitationFormset, UserRegistrationForm)\r\nfrom .models import LilyUser\r\n\r\n\r\nclass RegistrationView(FormView):\r\n \"\"\"\r\n This view shows and handles the registration form, when valid register a new user.\r\n \"\"\"\r\n template_name = 'users/registration.html'\r\n form_class = RegistrationForm\r\n\r\n def get(self, request, *args, **kwargs):\r\n # Show a different template when registration is closed.\r\n if settings.REGISTRATION_POSSIBLE:\r\n return super(RegistrationView, self).get(request, args, kwargs)\r\n else:\r\n self.template_name = 'users/registration_closed.html'\r\n return self.render_to_response({})\r\n\r\n def form_valid(self, form):\r\n \"\"\"\r\n Register a new user.\r\n \"\"\"\r\n # Do not accept any valid form when registration is closed.\r\n if not settings.REGISTRATION_POSSIBLE:\r\n messages.error(self.request, _('I\\'m sorry, but I can\\'t let anyone register at the moment.'))\r\n return redirect(reverse_lazy('login'))\r\n\r\n # Create and save user\r\n user = LilyUser.objects.create_user(\r\n email=form.cleaned_data['email'],\r\n password=form.cleaned_data['password'],\r\n first_name=form.cleaned_data['first_name'],\r\n preposition=form.cleaned_data['preposition'],\r\n last_name=form.cleaned_data['last_name'],\r\n )\r\n\r\n user.is_active = False\r\n user.save()\r\n\r\n # Add to admin group\r\n account_admin = Group.objects.get_or_create(name='account_admin')[0]\r\n user.groups.add(account_admin)\r\n\r\n # Get the current site\r\n try:\r\n current_site = Site.objects.get_current()\r\n except Site.DoesNotExist:\r\n current_site = ''\r\n\r\n # Generate uidb36 and token for the activation link\r\n uidb36 = int_to_base36(user.pk)\r\n token_generator = PasswordResetTokenGenerator()\r\n token = token_generator.make_token(user)\r\n\r\n # Send an activation mail\r\n # TODO: only create/save contact when e-mail sent succesfully\r\n send_templated_mail(\r\n template_name='activation',\r\n from_email=settings.DEFAULT_FROM_EMAIL,\r\n recipient_list=[form.cleaned_data['email']],\r\n context={\r\n 'current_site': current_site,\r\n 'protocol': self.request.is_secure() and 'https' or 'http',\r\n 'user': user,\r\n 'uidb36': uidb36,\r\n 'token': token,\r\n }\r\n )\r\n\r\n # Show registration message\r\n messages.success(\r\n self.request,\r\n _('Registration completed. I\\'ve sent you an email, please check it to activate your account.')\r\n )\r\n\r\n return self.get_success_url()\r\n\r\n def get_success_url(self):\r\n \"\"\"\r\n Redirect to the success url.\r\n \"\"\"\r\n return redirect(reverse_lazy('login'))\r\n\r\n\r\nclass ActivationView(TemplateView):\r\n \"\"\"\r\n This view checks whether the activation link is valid and acts accordingly.\r\n \"\"\"\r\n # Template is only shown when something went wrong\r\n template_name = 'users/activation_failed.html'\r\n token_generator = PasswordResetTokenGenerator()\r\n\r\n def get(self, request, *args, **kwargs):\r\n \"\"\"\r\n Check whether the activation link is valid, for this both the user id and the token should\r\n be valid. Messages are shown when user belonging to the user id is already active\r\n and when the account is successfully activated. In all other cases the activation failed\r\n template is shown.\r\n Finally if the user is successfully activated, log user in and redirect to their dashboard.\r\n \"\"\"\r\n try:\r\n user_id = base36_to_int(kwargs['uidb36'])\r\n user = LilyUser.objects.get(id=user_id)\r\n token = kwargs['token']\r\n except (ValueError, LilyUser.DoesNotExist):\r\n # Show template as per normal TemplateView behaviour\r\n return TemplateView.get(self, request, *args, **kwargs)\r\n\r\n if self.token_generator.check_token(user, token):\r\n # Show activation message\r\n messages.info(request, _('I\\'ve activated your account, please login.'))\r\n else:\r\n # Show template as per normal TemplateView behaviour\r\n return TemplateView.get(self, request, *args, **kwargs)\r\n\r\n # Set is_active to True and save the user\r\n user.is_active = True\r\n user.save()\r\n\r\n # Redirect to dashboard\r\n return redirect(reverse_lazy('login'))\r\n\r\n\r\nclass ActivationResendView(FormView):\r\n \"\"\"\r\n This view is used by an user to request a new activation e-mail.\r\n \"\"\"\r\n template_name = 'users/activation_resend_form.html'\r\n form_class = ResendActivationForm\r\n\r\n def form_valid(self, form):\r\n \"\"\"\r\n If ResendActivationForm passed the validation, generate new token and send an e-mail.\r\n \"\"\"\r\n token_generator = PasswordResetTokenGenerator()\r\n users = LilyUser.objects.filter(\r\n email__iexact=form.cleaned_data['email']\r\n )\r\n\r\n # Get the current site or empty string\r\n try:\r\n current_site = Site.objects.get_current()\r\n except Site.DoesNotExist:\r\n current_site = ''\r\n\r\n for user in users:\r\n # Generate uidb36 and token for the activation link\r\n uidb36 = int_to_base36(user.pk)\r\n token = token_generator.make_token(user)\r\n\r\n # E-mail to the user\r\n send_templated_mail(\r\n template_name='activation',\r\n from_email=settings.DEFAULT_FROM_EMAIL,\r\n recipient_list=[form.cleaned_data['email']],\r\n context={\r\n 'current_site': current_site,\r\n 'protocol': self.request.is_secure() and 'https' or 'http',\r\n 'user': user,\r\n 'uidb36': uidb36,\r\n 'token': token,\r\n }\r\n )\r\n\r\n # Show registration message\r\n messages.success(\r\n self.request,\r\n _('Reactivation successful. I\\'ve sent you an email, please check it to activate your account.')\r\n )\r\n\r\n # Redirect to success url\r\n return self.get_success_url()\r\n\r\n def get_success_url(self):\r\n \"\"\"\r\n Redirect to the success url.\r\n \"\"\"\r\n return redirect(reverse_lazy('login'))\r\n\r\n\r\nclass LoginView(View):\r\n \"\"\"\r\n This view extends the default login view with a 'remember me' feature.\r\n \"\"\"\r\n template_name = 'users/login_form.html'\r\n\r\n def dispatch(self, request, *args, **kwargs):\r\n \"\"\"\r\n Check if the user wants to be remembered and return the default login view.\r\n \"\"\"\r\n if request.user.is_authenticated():\r\n return redirect(reverse_lazy('base_view'))\r\n\r\n if request.method == 'POST':\r\n # If not using 'remember me' feature use default expiration time.\r\n if not request.POST.get('remember_me', False):\r\n request.session.set_expiry(None)\r\n return login(\r\n request,\r\n template_name=self.template_name,\r\n authentication_form=CustomAuthenticationForm,\r\n *args,\r\n **kwargs\r\n )\r\n\r\n\r\nclass SendInvitationView(GroupRequiredMixin, FormSetView):\r\n \"\"\"\r\n This view is used to invite new people to the site. It works with a formset to allow easy\r\n adding of multiple invitations. It also checks whether the call is done via ajax or via a normal\r\n form, to use ajax append ?xhr to the url.\r\n \"\"\"\r\n template_name = 'users/invitation/invitation_form.html'\r\n form_template_name = 'utils/templates/formset_invitation.html'\r\n form_class = InvitationForm\r\n formset_class = InvitationFormset\r\n extra = 1\r\n can_delete = True\r\n group_required = ['account_admin', ]\r\n\r\n def formset_valid(self, formset):\r\n \"\"\"\r\n This function is called when the formset is deemed valid.\r\n An email is sent to all email fields which are filled in.\r\n If the request is done via ajax give json back with a success message, otherwise\r\n redirect to the success url.\r\n \"\"\"\r\n protocol = self.request.is_secure() and 'https' or 'http'\r\n date_string = date.today().strftime('%d%m%Y')\r\n\r\n # Get the current site or empty string\r\n try:\r\n current_site = Site.objects.get_current()\r\n except Site.DoesNotExist:\r\n current_site = ''\r\n\r\n for form in formset:\r\n if form in formset.deleted_forms:\r\n continue\r\n\r\n first_name = form.cleaned_data.get('first_name')\r\n\r\n email = form.cleaned_data.get('email')\r\n tenant_id = self.request.user.tenant_id\r\n hash = sha256('%s-%s-%s-%s' % (\r\n tenant_id,\r\n email,\r\n date_string,\r\n settings.SECRET_KEY\r\n )).hexdigest()\r\n invite_link = '%s://%s%s' % (protocol, current_site, reverse_lazy('invitation_accept', kwargs={\r\n 'tenant_id': tenant_id,\r\n 'first_name': first_name,\r\n 'email': email,\r\n 'date': date_string,\r\n 'hash': hash,\r\n }))\r\n\r\n # E-mail to the user\r\n send_templated_mail(\r\n template_name='invitation',\r\n from_email=settings.DEFAULT_FROM_EMAIL,\r\n recipient_list=[form.cleaned_data['email']],\r\n context={\r\n 'current_site': current_site,\r\n 'full_name': self.request.user.get_full_name(),\r\n 'name': first_name,\r\n 'invite_link': invite_link,\r\n }\r\n )\r\n\r\n if is_ajax(self.request):\r\n return HttpResponse(anyjson.serialize({\r\n 'error': False,\r\n 'html': _('The invitations were sent successfully'),\r\n }), content_type='application/json')\r\n return HttpResponseRedirect(self.get_success_url())\r\n\r\n def formset_invalid(self, formset):\r\n \"\"\"\r\n This function is called when the formset didn't pass validation.\r\n If the request is done via ajax, send back a json object with the error set to true and\r\n the form rendered into a string.\r\n \"\"\"\r\n if is_ajax(self.request):\r\n context = RequestContext(self.request, self.get_context_data(formset=formset))\r\n return HttpResponse(anyjson.serialize({\r\n 'error': True,\r\n 'html': render_to_string(self.form_template_name, context)\r\n }), content_type='application/json')\r\n return self.render_to_response(self.get_context_data(formset=formset))\r\n\r\n def get_success_url(self):\r\n \"\"\"\r\n return the success url and set a succes message.\r\n \"\"\"\r\n messages.success(self.request, _('I did it! I\\'ve sent the invitations successfully.'))\r\n return reverse_lazy('dashboard')\r\n\r\n\r\nclass AcceptInvitationView(FormView):\r\n \"\"\"\r\n This is the view that handles the invitation link and registers the new user if everything\r\n goes according to plan, otherwise redirect the user to a failure template.\r\n \"\"\"\r\n template_name = 'users/invitation/accept.html'\r\n template_failure = 'users/invitation/accept_invalid.html'\r\n form_class = UserRegistrationForm\r\n valid_link = False\r\n\r\n def dispatch(self, request, *args, **kwargs):\r\n \"\"\"\r\n Set the variables needed and call super.\r\n This method tries to call dispatch to the right method.\r\n \"\"\"\r\n self.first_name = kwargs.get('first_name')\r\n self.email = kwargs.get('email')\r\n self.datestring = kwargs.get('date')\r\n self.tenant_id = kwargs.get('tenant_id')\r\n self.hash = kwargs.get('hash')\r\n\r\n return super(AcceptInvitationView, self).dispatch(request, *args, **kwargs)\r\n\r\n def get_template_names(self):\r\n \"\"\"\r\n This method checks if the link is deemed valid, serves appropriate templates.\r\n \"\"\"\r\n if not self.valid_link:\r\n return [self.template_failure]\r\n return super(AcceptInvitationView, self).get_template_names()\r\n\r\n def get(self, request, *args, **kwargs):\r\n \"\"\"\r\n This function is called on normal page load. The function link_is_valid is called to\r\n determine whether the link is valid. If so load all the necessary data for the form etc.\r\n otherwise render the failure template (which get_template_names will return since link is\r\n invalid.\r\n \"\"\"\r\n if self.link_is_valid():\r\n self.initial = {\r\n 'first_name': self.first_name,\r\n 'email': self.email,\r\n }\r\n return super(AcceptInvitationView, self).get(request, *args, **kwargs)\r\n\r\n return self.render_to_response(self.get_context_data())\r\n\r\n def post(self, request, *args, **kwargs):\r\n \"\"\"\r\n The function link_is_valid is called to determine if the link is valid.\r\n\r\n If so load all the necessary data for the form etc.\r\n otherwise render the failure template (which get_template_names will\r\n return since link is invalid).\r\n \"\"\"\r\n if self.link_is_valid():\r\n self.initial = {\r\n 'first_name': self.first_name,\r\n 'email': self.email,\r\n }\r\n return super(AcceptInvitationView, self).post(request, *args, **kwargs)\r\n\r\n return self.render_to_response(self.get_context_data())\r\n\r\n def link_is_valid(self):\r\n \"\"\"\r\n This functions performs all checks to verify the url is correct.\r\n\r\n Returns:\r\n Boolean: True if link is valid\r\n \"\"\"\r\n # Default value is false, only set to true if all checks have passed\r\n self.valid_link = False\r\n\r\n if LilyUser.objects.filter(email__iexact=self.email).exists():\r\n return self.valid_link\r\n\r\n if not self.hash == sha256('%s-%s-%s-%s' % (\r\n self.tenant_id,\r\n self.email,\r\n self.datestring,\r\n settings.SECRET_KEY\r\n )).hexdigest():\r\n # hash should be correct\r\n return self.valid_link\r\n\r\n if not len(self.datestring) == 8:\r\n # Date should always be a string with a length of 8 characters\r\n return self.valid_link\r\n else:\r\n today = date.today()\r\n try:\r\n # Check if it is a valid date\r\n dateobj = date(int(self.datestring[4:8]), int(self.datestring[2:4]), int(self.datestring[:2]))\r\n except ValueError:\r\n return self.valid_link\r\n else:\r\n if (today < dateobj) or ((today - timedelta(days=settings.USER_INVITATION_TIMEOUT_DAYS)) > dateobj):\r\n # Check if the link is not too old and not in the future\r\n return self.valid_link\r\n\r\n # Every check was passed successfully, link is valid\r\n self.valid_link = True\r\n return self.valid_link\r\n\r\n def form_valid(self, form):\r\n \"\"\"\r\n Create LilyUser.\r\n \"\"\"\r\n user = LilyUser()\r\n user.email = self.email\r\n user.first_name = form.cleaned_data['first_name']\r\n user.preposition = form.cleaned_data['preposition']\r\n user.last_name = form.cleaned_data['last_name']\r\n user.set_password(form.cleaned_data['password'])\r\n user.tenant_id = self.tenant_id\r\n user.save()\r\n\r\n return self.get_success_url()\r\n\r\n def get_success_url(self):\r\n return redirect(reverse_lazy('login'))\r\n","sub_path":"lily/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"360705562","text":"# -*- encoding: utf-8 -*-\nimport unittest\nimport uuid\n\nfrom pamqp import body, frame, header, heartbeat, specification\n\n\nclass MarshalingTests(unittest.TestCase):\n\n def test_protocol_header(self):\n expectation = b'AMQP\\x00\\x00\\t\\x01'\n response = frame.marshal(header.ProtocolHeader(), 0)\n self.assertEqual(response,\n expectation,\n \"ProtocolHeader did not match expectation\")\n\n def test_basic_ack(self):\n expectation = (b'\\x01\\x00\\x01\\x00\\x00\\x00\\r\\x00<\\x00P\\x00\\x00\\x00'\n b'\\x00\\x00\\x00\\x00\\x01\\x00\\xce')\n frame_obj = specification.Basic.Ack(1, False)\n response = frame.marshal(frame_obj, 1)\n self.assertEqual(response, expectation,\n \"Basic.Ack did not match expectation\")\n\n def test_basic_cancel(self):\n expectation = (b'\\x01\\x00\\x01\\x00\\x00\\x00\\r\\x00<\\x00\\x1e\\x07'\n b'ctag1.0\\x00\\xce')\n frame_obj = specification.Basic.Cancel(consumer_tag='ctag1.0')\n response = frame.marshal(frame_obj, 1)\n self.assertEqual(response, expectation,\n \"Basic.Cancel did not match expectation\")\n\n def test_basic_cancelok(self):\n expectation = (b'\\x01\\x00\\x01\\x00\\x00\\x00\\x0c\\x00<\\x00\\x1f\\x07'\n b'ctag1.0\\xce')\n frame_obj = specification.Basic.CancelOk(consumer_tag='ctag1.0')\n response = frame.marshal(frame_obj, 1)\n self.assertEqual(response, expectation,\n \"Basic.Cancel did not match expectation\")\n\n def test_basic_consume(self):\n expectation = (b'\\x01\\x00\\x01\\x00\\x00\\x00\\x15\\x00<\\x00\\x14\\x00'\n b'\\x00\\x03bar\\x05ctag0\\x00\\x00\\x00\\x00\\x00\\xce')\n frame_obj = specification.Basic.Consume(0, 'bar', 'ctag0',\n False, False, False, False)\n response = frame.marshal(frame_obj, 1)\n self.assertEqual(response, expectation,\n \"Basic.Consume did not match expectation\")\n\n def test_heartbeat(self):\n expectation = b'\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\xce'\n response = frame.marshal(heartbeat.Heartbeat(), 0)\n self.assertEqual(response, expectation,\n \"Heartbeat did not match expectation\")\n\n def test_content_body(self):\n value = str(uuid.uuid4()).encode('utf-8')\n expectation = b'\\x03\\x00\\x01\\x00\\x00\\x00$' + value + b'\\xce'\n self.assertEqual(frame.marshal(body.ContentBody(value), 1),\n expectation)\n\n def test_content_header(self):\n expectation = (b'\\x02\\x00\\x01\\x00\\x00\\x00\\x0e\\x00<\\x00\\x00\\x00'\n b'\\x00\\x00\\x00\\x00\\x00\\x00\\n\\x00\\x00\\xce')\n self.assertEqual(frame.marshal(header.ContentHeader(body_size=10), 1),\n expectation)\n\n\n def test_unknown_frame_type(self):\n with self.assertRaises(ValueError):\n frame.marshal(self, 1)\n\n","sub_path":"tests/test_frame_marshaling.py","file_name":"test_frame_marshaling.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"435421693","text":"from tensorflow.keras.layers import Conv1D, Input, Bidirectional, LSTM, Concatenate, Reshape, TimeDistributed, Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n\n\ndef model_builder(input_dim=5, output_dim=2, window_size=5, target_timestep=1, dropout=0.1):\n input = Input(shape=(None, input_dim))\n\n conv = Conv1D(filters=16, kernel_size=2, strides=1, padding='same')\n conv_out = conv(input)\n conv_2 = Conv1D(filters=32, kernel_size=3, padding='same')\n conv_out_2 = conv_2(conv_out)\n conv_3 = Conv1D(filters=64, kernel_size=window_size - target_timestep + 1)\n conv_out_3 = conv_3(conv_out_2)\n\n rnn_1 = Bidirectional(\n LSTM(units=64, return_sequences=True, return_state=True, dropout=dropout, recurrent_dropout=dropout))\n rnn_out_1, forward_h, forward_c, backward_h, backward_c = rnn_1(conv_out_3)\n state_h = Concatenate(axis=-1)([forward_h, backward_h])\n state_c = Concatenate(axis=-1)([forward_c, backward_c])\n\n # rnn_2 = Bidirectional(LSTM(units=128, return_sequences=False))\n # rnn_out_2 = rnn_2(rnn_out_1, initial_state=[forward_h, forward_c, backward_h, backward_c])\n\n rnn_3 = LSTM(units=128, return_sequences=False, return_state=False, dropout=dropout, recurrent_dropout=dropout)\n rnn_out_3 = rnn_3(rnn_out_1, initial_state=[state_h, state_c])\n\n dense_3 = Dense(units=output_dim)\n output = dense_3(rnn_out_3)\n\n model = Model(inputs=input, outputs=output)\n\n #optimizer = SGD(lr=1e-6, momentum=0.9,decay=self.lr_decay,nesterov=True)\n #optimizer = RMSprop(learning_rate=5e-3)\n #optimizer = Adadelta(rho=0.95)\n #optimizer = Adam(learning_rate=5e-2,amsgrad=False)\n model.compile(loss='mse', optimizer='adam', metrics=['mae', 'mape'])\n\n return model\n\n\ndef train_model(model, x_train, y_train, batch_size, epochs, fraction=0.1, patience=0, early_stop=False, save_dir=''):\n callbacks = []\n\n checkpoint = ModelCheckpoint(save_dir + f'best_model_{epochs}.hdf5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True)\n callbacks.append(checkpoint)\n\n #early_stop = epochs == 250\n if (early_stop):\n early_stop = EarlyStopping(monitor='val_loss', patience=patience, restore_best_weights=True)\n callbacks.append(early_stop)\n\n history = model.fit(x=x_train,\n y=y_train,\n batch_size=batch_size,\n epochs=epochs,\n callbacks=callbacks,\n validation_split=fraction)\n\n return model, history\n","sub_path":"Se_0.8/GA/model/models/multi_rnn_cnn.py","file_name":"multi_rnn_cnn.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"499884096","text":"class Solution:\n # @return a list of lists of length 4, [[val1,val2,val3,val4]]\n def fourSum(self, num, target):\n l = len(num)\n valPos = {}\n res = []\n res2 = sets.Set()\n i = 0\n while i < l:\n j = 0\n while j < i:\n currentVal = target - (num[i]+num[j])\n if currentVal not in valPos:\n valPos[currentVal] = [(j, i)]\n else:\n valPos[currentVal].append((j, i))\n j += 1\n i += 1\n\n i = 0\n while i < l:\n j = 0\n while j < i:\n currentSum = num[i] + num[j]\n if currentSum in valPos:\n res.append([i, j, valPos[currentSum]])\n j += 1\n i += 1\n\n for i, j, pos in res:\n for k, m in pos:\n if i !=j and i!= k and i !=m and j != k and j != m and k != m:\n res2.add(tuple(sorted([num[i], num[j], num[k], num[m]])))\n return [list(quadTuple) for quadTuple in res2]\n","sub_path":"4sum.py","file_name":"4sum.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"280225554","text":"# coding=utf-8\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom typing import Tuple\n\nimport numpy as np\n# region ::Import statement ...\nimport tensorflow as tf\nimport tensorflow.python.util.deprecation as deprecation\n\nimport blocAndTools.tensorflowbloc\nfrom ActorCritic.ActorCriticBrainSharedNetwork import build_actor_critic_shared_graph, actor_shared_train, critic_shared_train\nfrom ActorCritic.ActorCriticBrainSplitNetwork import (build_actor_policy_graph, build_critic_graph, critic_train,\n actor_train, )\nfrom blocAndTools import buildingbloc as bloc, ConsolPrintLearningStats\nfrom blocAndTools.agent import Agent\nfrom blocAndTools.container.samplecontainer_online_mini_batch_OAnORV import (TrajectoryCollectorMiniBatchOnlineOAnORV,\n ExperimentStageCollectorOnlineAAC, )\nfrom blocAndTools.rl_vocabulary import rl_name, NetworkType\n\ntf_cv1 = tf.compat.v1 # shortcut\ndeprecation._PRINT_DEPRECATION_WARNINGS = False\nvocab = rl_name()\n# endregion\n\nclass OnlineActorCriticAgent(Agent):\n def _use_hardcoded_agent_root_directory(self):\n self.agent_root_dir = 'ActorCritic'\n return None\n\n def _build_computation_graph(self):\n \"\"\"\n Build the Policy_theta & V_phi computation graph with theta and phi as multi-layer perceptron\n \"\"\"\n assert isinstance(self.exp_spec['Network'], NetworkType), (\"exp_spec['Network'] must be explicitely defined \"\n \"with a NetworkType enum\")\n\n if self.exp_spec.random_seed == 0:\n print(\":: Random seed control is turned OFF\")\n else:\n tf_cv1.random.set_random_seed(self.exp_spec.random_seed)\n np.random.seed(self.exp_spec.random_seed)\n print(\":: Random seed control is turned ON\")\n\n \"\"\" ---- Placeholder ---- \"\"\"\n self.obs_t_ph, self.action_ph, self.Qvalues_ph = bloc.gym_playground_to_tensorflow_graph_adapter(\n self.playground, obs_shape_constraint=None, action_shape_constraint=None, Q_name=vocab.Qvalues_ph)\n\n if self.exp_spec['Network'] is NetworkType.Split:\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Critic computation graph *\n # * (Split network) *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n self.V_phi_estimator = build_critic_graph(self.obs_t_ph, self.exp_spec)\n\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Actor computation graph *\n # * (Split network) *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n self.policy_pi, log_pi, _ = build_actor_policy_graph(self.obs_t_ph, self.exp_spec,\n self.playground)\n\n print(\":: SPLIT network constructed\")\n\n elif self.exp_spec['Network'] is NetworkType.Shared:\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Shared Actor-Critic computation graph *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n self.policy_pi, log_pi, _, self.V_phi_estimator = build_actor_critic_shared_graph(\n self.obs_t_ph, self.exp_spec, self.playground)\n\n print(\":: SHARED network constructed\")\n\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Advantage *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n # # alternate architecture with element wise computed advantage\n # self.Advantage_ph = tf_cv1.placeholder(tf.float32, shape=self.Qvalues_ph.shape, name=vocab.advantage_ph)\n\n with tf_cv1.name_scope(vocab.Advantage):\n # (!) note: Advantage computation\n # | no squeeze ==> SLOWER computation\n # | eg: Advantage = self.Qvalues_ph - self.V_phi_estimator\n # |\n # | with squeeze ==> RACING CAR FAST computation\n #\n # (Nice to have) todo:investigate?? --> why it's much faster?: hypothese --> broadcasting slowdown computation\n Advantage = self.Qvalues_ph - tf_cv1.squeeze(self.V_phi_estimator)\n\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Actor & Critic Train *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n self.actor_loss, self.actor_policy_optimizer = actor_shared_train(self.action_ph, log_pi=log_pi, advantage=Advantage,\n experiment_spec=self.exp_spec,\n playground=self.playground)\n\n self.V_phi_loss, self.V_phi_optimizer = critic_shared_train(Advantage, self.exp_spec)\n\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * *\n # * *\n # * Summary ops *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * *\n\n \"\"\" ---- By Epoch summary ---- \"\"\"\n self.summary_stage_avg_trjs_actor_loss_ph = tf_cv1.placeholder(tf.float32, name='Actor_loss_ph')\n self.summary_stage_avg_trjs_critic_loss_ph = tf_cv1.placeholder(tf.float32, name='Critic_loss_ph')\n tf_cv1.summary.scalar('Actor_loss', self.summary_stage_avg_trjs_actor_loss_ph, family=vocab.loss)\n tf_cv1.summary.scalar('Critic_loss', self.summary_stage_avg_trjs_critic_loss_ph, family=vocab.loss)\n\n self.summary_stage_avg_trjs_return_ph = tf_cv1.placeholder(tf.float32, name='summary_stage_avg_trjs_return_ph')\n tf_cv1.summary.scalar('Batch average return', self.summary_stage_avg_trjs_return_ph, family=vocab.G)\n\n self.summary_epoch_op = tf_cv1.summary.merge_all()\n\n \"\"\" ---- By Trajectory summary ---- \"\"\"\n self.Summary_trj_return_ph = tf_cv1.placeholder(tf.float32, name='Summary_trj_return_ph')\n self.summary_trj_return_op = tf_cv1.summary.scalar('Trajectory return', self.Summary_trj_return_ph,\n family=vocab.G)\n\n self.Summary_trj_lenght_ph = tf_cv1.placeholder(tf.float32, name='Summary_trj_lenght_ph')\n self.summary_trj_lenght_op = tf_cv1.summary.scalar('Trajectory lenght', self.Summary_trj_lenght_ph,\n family=vocab.Trajectory_lenght)\n\n self.summary_trj_op = tf_cv1.summary.merge([self.summary_trj_return_op, self.summary_trj_lenght_op])\n\n\n return None\n\n def _instantiate_data_collector(self) -> Tuple[TrajectoryCollectorMiniBatchOnlineOAnORV,\n ExperimentStageCollectorOnlineAAC]:\n \"\"\"\n Data collector utility\n\n :return: Collertor utility\n :rtype: (TrajectoryCollectorBatchOARV, UniformBatchCollectorBatchOARV)\n \"\"\"\n trjCOLLECTOR = TrajectoryCollectorMiniBatchOnlineOAnORV(self.exp_spec, self.playground,\n discounted=self.exp_spec.discounted_reward_to_go,\n mini_batch_capacity=self.exp_spec.batch_size_in_ts)\n experimentCOLLECTOR = ExperimentStageCollectorOnlineAAC(self.exp_spec['stage_size_in_trj'])\n return trjCOLLECTOR, experimentCOLLECTOR\n\n def _training_epoch_generator(self, consol_print_learning_stats: ConsolPrintLearningStats, render_env: bool):\n \"\"\"\n Training epoch generator\n\n :param consol_print_learning_stats:\n :type consol_print_learning_stats:\n :param render_env:\n :type render_env: bool\n :yield: (epoch, epoch_loss, stage_average_trjs_return, stage_average_trjs_lenght)\n \"\"\"\n\n self.trjCOLLECTOR, experimentCOLLECTOR = self._instantiate_data_collector()\n\n print(\":: ONline ActorCritic agent reporting for training \")\n\n \"\"\" ---- Warm-up the computation graph and start learning! ---- \"\"\"\n with tf_cv1.Session() as sess:\n self.sess = sess\n self.sess.run(tf_cv1.global_variables_initializer()) # initialize random variable in the computation graph\n\n consol_print_learning_stats.start_the_crazy_experiment()\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n # * *\n # * Training loop *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n\n \"\"\" ---- Simulator: Epochs ---- \"\"\"\n global_timestep_idx = 0\n for epoch in range(self.exp_spec.max_epoch):\n # (Ice-Boxed) todo:implement --> finish lr sheduler for online shared algo:\n # (Ice-Boxed) todo:implement --> add 'global_timestep_max' to hparam:\n # if global_timestep_idx >= self.exp_spec['global_timestep_max']:\n # break\n\n consol_print_learning_stats.next_glorious_epoch()\n\n \"\"\" ---- Simulator: trajectories ---- \"\"\"\n while experimentCOLLECTOR.is_not_full():\n obs_t = self.playground.env.reset()\n consol_print_learning_stats.next_glorious_trajectory()\n\n \"\"\" ---- Simulator: time-steps ---- \"\"\"\n local_step_t = 0\n while True:\n global_timestep_idx += 1\n local_step_t += 1\n self._render_trajectory_on_condition(epoch, render_env,\n experimentCOLLECTOR.trj_collected_so_far())\n \n \"\"\" ---- Run Graph computation ---- \"\"\"\n obs_t_flat = bloc.format_single_step_observation(obs_t)\n action, V_t = self.sess.run([self.policy_pi, self.V_phi_estimator],\n feed_dict={self.obs_t_ph: obs_t_flat})\n \n action = blocAndTools.tensorflowbloc.to_scalar(action)\n V_t = blocAndTools.tensorflowbloc.to_scalar(V_t)\n \n \"\"\" ---- Agent: act in the environment ---- \"\"\"\n obs_tPrime, reward, done, _ = self.playground.env.step(action)\n \n \"\"\" ---- Agent: Collect current timestep events ---- \"\"\"\n self.trjCOLLECTOR.collect_OAnORV(obs_t=obs_t, act_t=action, obs_tPrime=obs_tPrime,\n rew_t=reward, V_estimate=V_t)\n \n obs_t = obs_tPrime\n\n if done:\n \"\"\" ---- Simulator: trajectory as ended ---- \"\"\"\n trj_return = self.trjCOLLECTOR.trajectory_ended()\n self._train_on_minibatch(consol_print_learning_stats, local_step_t)\n\n\n \"\"\" ---- Agent: Collect the sampled trajectory ---- \"\"\"\n trj_container = self.trjCOLLECTOR.pop_trajectory_and_reset()\n experimentCOLLECTOR.collect(trj_container)\n\n # trj_summary = self.sess.run(self.summary_trj_return_op, {self.Summary_trj_return_ph: trj_return})\n trj_len = len(trj_container)\n\n trj_summary = sess.run(self.summary_trj_op,\n {self.Summary_trj_return_ph: trj_return,\n self.Summary_trj_lenght_ph: trj_len\n })\n\n self.writer.add_summary(trj_summary, global_step=global_timestep_idx)\n\n consol_print_learning_stats.trajectory_training_stat(the_trajectory_return=trj_return,\n timestep=trj_len)\n break\n\n elif self.trjCOLLECTOR.minibatch_is_full():\n self._train_on_minibatch(consol_print_learning_stats, local_step_t)\n\n \"\"\" ---- Simulator: epoch as ended, it's time to learn! ---- \"\"\"\n stage_trj_collected = experimentCOLLECTOR.trj_collected_so_far()\n stage_timestep_collected = experimentCOLLECTOR.timestep_collected_so_far()\n\n \"\"\" ---- Prepare data for backpropagation in the neural net ---- \"\"\"\n experiment_container = experimentCOLLECTOR.pop_batch_and_reset()\n stage_average_trjs_return, stage_average_trjs_lenght = experiment_container.get_basic_metric()\n stage_actor_mean_loss, stage_critic_mean_loss = experiment_container.get_stage_mean_loss()\n\n epoch_feed_dictionary = blocAndTools.tensorflowbloc.build_feed_dictionary(\n [self.summary_stage_avg_trjs_actor_loss_ph,\n self.summary_stage_avg_trjs_critic_loss_ph,\n self.summary_stage_avg_trjs_return_ph],\n [stage_actor_mean_loss,\n stage_critic_mean_loss,\n stage_average_trjs_return])\n\n epoch_summary = self.sess.run(self.summary_epoch_op, feed_dict=epoch_feed_dictionary)\n\n self.writer.add_summary(epoch_summary, global_step=global_timestep_idx)\n\n consol_print_learning_stats.epoch_training_stat(\n epoch_loss=stage_actor_mean_loss,\n epoch_average_trjs_return=stage_average_trjs_return,\n epoch_average_trjs_lenght=stage_average_trjs_lenght,\n number_of_trj_collected=stage_trj_collected,\n total_timestep_collected=stage_timestep_collected)\n\n self._save_learned_model(stage_average_trjs_return, epoch, self.sess)\n\n \"\"\" ---- Expose current epoch computed information for integration test ---- \"\"\"\n yield (epoch, stage_actor_mean_loss, stage_average_trjs_return, stage_average_trjs_lenght)\n\n print(\"\\n\\n\\n:: Global timestep collected: {}\".format(global_timestep_idx), end=\"\")\n return None\n\n def _train_on_minibatch(self, consol_print_learning_stats, local_step_t):\n self.trjCOLLECTOR.compute_Qvalues_as_BootstrapEstimate()\n minibatch = self.trjCOLLECTOR.get_minibatch()\n \n minibatch_feed_dictionary = blocAndTools.tensorflowbloc.build_feed_dictionary(\n [self.obs_t_ph, self.action_ph, self.Qvalues_ph],\n [minibatch.obs_t, minibatch.act_t, minibatch.q_values_t])\n \n \"\"\" ---- Compute metric and collect ---- \"\"\"\n minibatch_actor_loss, minibatch_V_loss = self.sess.run([self.actor_loss, self.V_phi_loss],\n feed_dict=minibatch_feed_dictionary)\n \n self.trjCOLLECTOR.collect_loss(actor_loss=minibatch_actor_loss, critic_loss=minibatch_V_loss)\n \n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * *\n # * *\n # * Update policy_theta & critic V_phi over the minibatch *\n # * *\n # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * * *\n # consol_print_learning_stats.track_progress(progress=local_step_t, message=\"Agent training\")\n\n \"\"\" ---- Train actor ---- \"\"\"\n self.sess.run(self.actor_policy_optimizer, feed_dict=minibatch_feed_dictionary)\n\n \"\"\" ---- Train critic ---- \"\"\"\n critic_feed_dictionary = blocAndTools.tensorflowbloc.build_feed_dictionary(\n [self.obs_t_ph, self.Qvalues_ph],\n [minibatch.obs_t, minibatch.q_values_t])\n\n for c_loop in range(self.exp_spec['critique_loop_len']): # <-- (!) most likely 1 iteration\n self.sess.run(self.V_phi_optimizer, feed_dict=critic_feed_dictionary)\n\n return None\n\n","sub_path":"DRLimplementation/ActorCritic/OnlineActorCriticAgent.py","file_name":"OnlineActorCriticAgent.py","file_ext":"py","file_size_in_byte":19470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"543503157","text":"\"\"\"\nAWS Connection Manager\n\"\"\"\n\nimport boto3\n\n_CLIENTS = {}\n_SESSIONS = {}\n\n\ndef get_client(profile, region, client):\n \"\"\"\n Fetch an AWS Client, and store it for later use\n \"\"\"\n client_key = (profile, region)\n session_key = profile\n\n if client_key not in _CLIENTS:\n if session_key not in _SESSIONS:\n _SESSIONS[session_key] = boto3.Session(profile_name=profile)\n _CLIENTS[client_key] = _SESSIONS[session_key].client(\n client, region_name=region)\n return _CLIENTS[client_key]\n","sub_path":"stax/aws/connection_manager.py","file_name":"connection_manager.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6732526","text":"n = int(input())\nmatrix = [[x for x in input().split(',')] for _ in range(n)]\n\nprint(matrix)\n\n# res = []\n#\n# while matrix:\n#\n# res += matrix.pop(0)\n#\n# matrix = list(zip(*matrix))[::-1]\n#\n\n\ndirs = [[0,1],[1,0],[0,-1],[-1,0]]\n\nres = []\n\ncount = 0\n\nrow = 0\ncol = 0\n\ndirIndex = 0\n\nwhile count < n**2:\n\n\n res.append(matrix[row][col])\n\n matrix[row][col] = -1000\n\n next_row, next_col = row + dirs[dirIndex][0], col + dirs[dirIndex][1]\n\n if not (0 <= next_row < n and 0 <= next_col < n and matrix[next_row][next_col] != -1000):\n\n\n dirIndex = (dirIndex + 1) % 4\n\n row += dirs[dirIndex][0]\n col += dirs[dirIndex][1]\n\n count += 1\n\nprint(res)\n\n","sub_path":"leetcode/54. 螺旋矩阵.py","file_name":"54. 螺旋矩阵.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"538392958","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 3 07:26:31 2020\n\nSmall programm that follows all the steps to create a surrogate\nmodel based on the Krigin or Response surface method, using the openmdao libraries.\n\n@author: Vivien Riolo\n\"\"\"\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport openmdao.api as om\nimport matplotlib.pyplot as plt\n\ndef function(x,y):\n # Rosenbrock function\n result = (1-x)**2+100*(y-x**2)**2\n \n # 2nd order polynomial function\n # result = x**2+y**2+20\n \n # Non-linear function\n # result = np.exp(x)-y\n # result = x*np.sin(y**2)-np.sin(x*y)+5\n\n # Highly non-linear function\n # /!\\ Too much of an exponential frequency growth, no true representation \n # available after Shanon limit\n # result = x**1-15*np.sin(y**2*x)+y**1 +10\n \n return result\n\n\ndef create_model(name):\n # Setup training domain\n l = 1\n nb_sp = 25\n d1 = np.linspace(-l, l, nb_sp)\n d2 = d1\n X, Y = np.meshgrid(d1,d2)\n Z = function(X,Y)\n\n # Setup prediction domain\n a = np.linspace(-l,l,100)\n pd1 = a*np.sin(a**2)\n pd2 = a*np.cos(a**2)\n po = []\n err = [] \n\n # Computing the surface\n coord = []\n res = []\n for i in d1:\n for j in d2:\n res.append(function(i,j))\n coord.append([i,j])\n \n # Create the training dataset\n xi = np.array(coord)\n yi = np.transpose(np.atleast_2d(res))\n \n # Create and train the model\n if name == 'Kg':\n k = om.KrigingSurrogate()\n elif name == 'RS':\n k = om.ResponseSurface()\n \n print('train start')\n k.train(xi,yi)\n print('train stop')\n \n # Make a prediction\n for i in range(0,len(a)):\n pres = k.predict(np.array([pd1[i],pd2[i]]))\n if name == 'Kg':\n po.append(pres[-1][-1])\n err.append(po[-1]-function(pd1[i], pd2[i]))\n elif name == 'RS':\n po.append(pres[-1])\n err.append(po[-1]-function(pd1[i], pd2[i]))\n rms = np.sqrt(np.mean(np.array(err)**2))\n print('Root mean-square error {} : {}'.format(name,rms))\n \n # Plot the training set\n plt.figure()\n ax = plt.axes(projection='3d')\n # ax.plot_surface(X, Y, Z)\n ax.plot_wireframe(X, Y, Z)\n \n #Plot the predicted set\n ax.scatter(pd1,pd2,po,color='red')\n ax.plot(pd1,pd2,err,color='gray')\n \n \n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n \n # plt.show()\n return rms\n\n\nif __name__ == '__main__':\n \n plt.close('all')\n rmsk = create_model('Kg')\n rmsr = create_model('RS')\n ","sub_path":"ceasiompy/PredictiveTool/surrogate_model_test.py","file_name":"surrogate_model_test.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22482005","text":"# Copyright 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport collections\nimport copy\nimport functools\nimport logging\nimport os\nimport platform\nimport re\nimport shutil\nimport stat\nimport StringIO\nimport subprocess\nimport tempfile\nimport textwrap\nimport unittest\n\nimport pkg_resources\nimport six\nfrom future.utils import raise_with_traceback\n\n\ntry:\n import ConfigParser as configparser\nexcept ImportError:\n import configparser\n\ntry:\n import tests.facebook.utils\n\n __import_facebook_utils = True\nexcept ImportError:\n __import_facebook_utils = False\n\nRunResult = collections.namedtuple(\"RunResult\", [\"returncode\", \"stdout\", \"stderr\"])\nUnitTestResult = collections.namedtuple(\n \"UnitTestResult\", [\"returncode\", \"stdout\", \"stderr\", \"debug_lines\"]\n)\nAuditTestResult = collections.namedtuple(\n \"AuditTestResult\", [\"returncode\", \"stdout\", \"stderr\", \"files\"]\n)\n\n\ndef dedent(text):\n return textwrap.dedent(text).strip()\n\n\ndef __recursively_get_files_contents(base, module):\n \"\"\"\n Recursively get all file contents for a given path from pkg_resources\n\n Arguments:\n base: The subdirectory to look in first. Use '' for the root\n Returns:\n Map of relative path to a string of the file's contents\n \"\"\"\n is_file = pkg_resources.resource_exists(\n module, base\n ) and not pkg_resources.resource_isdir(module, base)\n if is_file:\n return {base: pkg_resources.resource_string(module, base)}\n\n ret = {}\n for file in pkg_resources.resource_listdir(module, base):\n full_path = os.path.join(base, file)\n if not pkg_resources.resource_isdir(module, full_path):\n ret[full_path] = pkg_resources.resource_string(module, full_path)\n else:\n ret.update(__recursively_get_files_contents(full_path, module))\n return ret\n\n\ndef recursively_get_files_contents(base, strip_base):\n \"\"\"\n Recursively get all file contents for a given path from pkg_resources\n\n Arguments:\n base: The subdirectory to look in first. Use '' for the root\n strip_base: If true, strip 'base' from the start of all paths that are\n returned\n Returns:\n Map of relative path to a string of the file's contents\n \"\"\"\n ret = __recursively_get_files_contents(base, \"tests.utils\")\n if __import_facebook_utils:\n ret.update(__recursively_get_files_contents(base, \"tests.facebook.utils\"))\n if strip_base:\n # + 1 is for the /\n ret = {path[len(base) + 1 :]: ret[path] for path in ret.keys()}\n return ret\n\n\nclass Cell:\n \"\"\"\n Represents a repository. Files, .buckconfig, and running commands are all\n done in this class\n \"\"\"\n\n def __init__(self, name, project):\n self.name = name\n self.buckconfig = collections.defaultdict(dict)\n self.buckconfig[\"ui\"][\"superconsole\"] = \"disabled\"\n self.buckconfig[\"color\"][\"ui\"] = \"false\"\n self.buckconfig[\"fbsource\"][\"cell_name\"] = \"fbcode\"\n self.project = project\n self._directories = []\n self._files = recursively_get_files_contents(name, True)\n self._helper_functions = []\n self._executable_files = set()\n\n def addFile(self, relative_path, contents, executable=False):\n \"\"\"\n Add a file that should be written into this cell when running commands\n \"\"\"\n self._files[relative_path] = contents\n if executable:\n self._executable_files.add(relative_path)\n\n def addResourcesFrom(self, relative_path):\n \"\"\"\n Add a file or directory from pkg_resources to this cell\n \"\"\"\n files = recursively_get_files_contents(relative_path, False)\n self._files.update(files)\n return files\n\n def addDirectory(self, relative_path):\n \"\"\"\n Add an empty directory in this cell that will be created when commmands\n are run\n \"\"\"\n self._directories.append(relative_path)\n\n def fullPath(self):\n \"\"\"\n Get the full path to this cell's root\n \"\"\"\n return os.path.join(self.project.project_path, self.name)\n\n def updateBuckconfig(self, section, key, value):\n \"\"\"\n Update the .buckconfig for this cell\n \"\"\"\n self.buckconfig[section][key] = value\n\n def updateBuckconfigWithDict(self, values):\n \"\"\"\n Update the .buckconfig for this cell with multiple values\n\n Arguments:\n values: A dictionary of dictionaries. The top level key is the\n section. Second level dictionaries are mappings of fields\n to values. .buckconfig is merged with 'values' taking\n precedence\n \"\"\"\n for section, kvps in values.items():\n for key, value in kvps.items():\n self.buckconfig[section][key] = value\n\n def createBuckconfigContents(self):\n \"\"\"\n Create contents of a .buckconfig file\n \"\"\"\n buckconfig = copy.deepcopy(self.buckconfig)\n for cell_name, cell in self.project.cells.items():\n relative_path = os.path.relpath(cell.fullPath(), self.fullPath())\n buckconfig[\"repositories\"][cell_name] = relative_path\n if \"polyglot_parsing_enabled\" not in buckconfig[\"parser\"]:\n buckconfig[\"parser\"][\"polyglot_parsing_enabled\"] = \"true\"\n if \"default_build_file_syntax\" not in buckconfig[\"parser\"]:\n buckconfig[\"parser\"][\"default_build_file_syntax\"] = \"SKYLARK\"\n if \"cxx\" not in buckconfig or \"cxx\" not in buckconfig[\"cxx\"]:\n cxx = self._findCXX()\n cc = self._findCC()\n if cxx:\n buckconfig[\"cxx\"][\"cxx\"] = cxx\n buckconfig[\"cxx\"][\"cxxpp\"] = cxx\n buckconfig[\"cxx\"][\"ld\"] = cxx\n if cc:\n buckconfig[\"cxx\"][\"cc\"] = cc\n buckconfig[\"cxx\"][\"cpp\"] = cc\n buckconfig[\"cxx\"][\"aspp\"] = cc\n if (\n \"fbcode\" not in buckconfig\n or \"buck_platform_format\" not in buckconfig[\"fbcode\"]\n ):\n buckconfig[\"fbcode\"][\"buck_platform_format\"] = \"{platform}-{compiler}\"\n\n parser = configparser.ConfigParser()\n for section, kvps in buckconfig.items():\n if len(kvps):\n parser.add_section(section)\n for key, value in kvps.items():\n if isinstance(value, list):\n value = \",\".join(value)\n parser.set(section, key, str(value))\n writer = StringIO.StringIO()\n try:\n parser.write(writer)\n return writer.getvalue()\n finally:\n writer.close()\n\n def _findCC(self):\n for path_component in os.environ.get(\"PATH\").split(os.pathsep):\n for bin in (\"gcc.par\", \"gcc\"):\n full_path = os.path.join(path_component, bin)\n if os.path.exists(full_path):\n return full_path\n return None\n\n def _findCXX(self):\n for path_component in os.environ.get(\"PATH\").split(os.pathsep):\n for bin in (\"g++.par\", \"g++\"):\n full_path = os.path.join(path_component, bin)\n if os.path.exists(full_path):\n return full_path\n return None\n\n def setupFilesystem(self):\n \"\"\"\n Sets up the filesystem for this cell in self.fullPath()\n\n This method:\n - creates all directories\n - creates all specified files and their parent directories\n - writes out a .buckconfig file\n \"\"\"\n cell_path = self.fullPath()\n\n if not os.path.exists(cell_path):\n os.makedirs(cell_path)\n\n for directory in self._directories:\n dir_path = os.path.join(cell_path, directory)\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n for path, contents in self._files.items():\n self.writeFile(path, contents, executable=path in self._executable_files)\n\n buckconfig = self.createBuckconfigContents()\n with open(os.path.join(cell_path, \".buckconfig\"), \"w\") as fout:\n fout.write(buckconfig)\n\n def setupAllFilesystems(self):\n \"\"\"\n Sets up the filesystem per self.setupFilesystem for this cell and\n all others\n \"\"\"\n for cell in self.project.cells.values():\n cell.setupFilesystem()\n\n def writeFile(self, relative_path, contents, executable=False):\n \"\"\"\n Writes out a file into the cell, making parent dirs if necessary\n \"\"\"\n cell_path = self.fullPath()\n dir_path, filename = os.path.split(relative_path)\n full_dir_path = os.path.join(cell_path, dir_path)\n file_path = os.path.join(cell_path, relative_path)\n if dir_path and not os.path.exists(full_dir_path):\n os.makedirs(full_dir_path)\n with open(file_path, \"w\") as fout:\n fout.write(contents)\n if executable:\n os.chmod(file_path, os.stat(file_path).st_mode | stat.S_IEXEC)\n\n def getDefaultEnvironment(self):\n # We don't start a daemon up because:\n # - Generally we're only running once, and in a temp dir, so it doesn't\n # make a big difference\n # - We want to make sure things cleanup properly, and this is just\n # easier\n ret = dict(os.environ)\n if not self.project.run_buckd:\n ret[\"NO_BUCKD\"] = \"1\"\n elif \"NO_BUCKD\" in ret:\n del ret[\"NO_BUCKD\"]\n return ret\n\n def run(self, cmd, extra_files, environment_overrides):\n \"\"\"\n Runs a command\n\n Arguments:\n cmd: A list of arguments that comprise the command to be run\n extra_files: A dictionary of relative path: contents that should be\n written after the rest of the files are written out\n environment_overrides: A dictionary of extra environment variables\n that should be set\n Returns:\n The RunResult from running the command\n \"\"\"\n self.setupAllFilesystems()\n for path, contents in extra_files.items():\n self.writeFile(path, contents)\n environment = self.getDefaultEnvironment()\n environment.update(environment_overrides or {})\n proc = subprocess.Popen(\n cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=self.fullPath(),\n env=environment,\n )\n stdout, stderr = proc.communicate()\n return RunResult(proc.returncode, stdout, stderr)\n\n def _parseAuditOutput(self, stdout, files):\n ret = {file: None for file in files}\n current_file = None\n file_contents = \"\"\n for line in stdout.splitlines():\n if line.startswith(\"#\"):\n found_filename = line.strip(\"# \")\n if found_filename in ret:\n if current_file is not None:\n ret[current_file] = file_contents.strip()\n current_file = found_filename\n file_contents = \"\"\n continue\n if found_filename is None and line:\n raise Exception(\n (\n \"Got line, but no filename has been found so far.\\n\"\n \"Line: {}\\n\"\n \"stdout:\\n{}\"\n ).format(line, stdout)\n )\n file_contents += line + \"\\n\"\n ret[current_file] = file_contents.strip()\n return ret\n\n def runAudit(self, buck_files, environment=None):\n \"\"\"\n A method to compare existing outputs of `buck audit rules` to new ones\n and ensure that the final product works as expected\n\n Arguments:\n buck_files: A list of relative paths to buck files that should have\n `buck audit rules` run on them.\n Returns:\n An AuditTestResult object, with returncode, stdout, stderr filled\n out, and files set as a dictionary of files names -> trimmed\n content returned from buck audit rules\n \"\"\"\n default_env = {}\n if not self.project.run_buckd:\n default_env[\"NO_BUCKD\"] = \"1\"\n environment = default_env.update(environment or {})\n\n cmd = [\"buck\", \"audit\", \"rules\"] + buck_files\n\n ret = self.run(cmd, {}, environment)\n audit_files = self._parseAuditOutput(ret.stdout, buck_files)\n\n return AuditTestResult(\n returncode=ret.returncode,\n stdout=ret.stdout,\n stderr=ret.stderr,\n files=audit_files,\n )\n\n def runUnitTests(\n self,\n includes,\n statements,\n extra_declarations=None,\n environment_overrides=None,\n buckfile=\"BUCK\",\n ):\n \"\"\"\n Evaluate a series of statements, parse their repr from buck, and\n return reconsituted objects, along with the results of buck audit rules\n on an auto-generated file\n\n Arguments:\n includes: A list of tuples to be used in a `load()` statement. The\n first element should be the .bzl file to be included.\n Subsequent elements are variables that should be loaded\n from the .bzl file. (e.g. `(\"//:test.bzl\", \"my_func\")`)\n statements: A list of statements that should be evaluated. This\n is usually just a list of function calls. This can\n reference things specified in `extra_declarations`.\n e.g. after importing a \"config\" struct:\n [\n \"config.foo\",\n \"config.bar(1, 2, {\"baz\": \"string\"})\"\n ]\n would run each of those statements.\n extra_declarations: If provided, a list of extra code that should\n go at the top of the generated BUCK file. This\n isn't normally needed, but if common data\n objects are desired for use in multiple\n statments, it can be handy\n environment_overrides: If provided, the environment to merge over\n the top of the generated environment when\n executing buck. If not provided, then a\n generated environment is used.\n buckfile: The name of the temporary buckfile to write\n Returns:\n A UnitTestResult object that contains the returncode, stdout,\n stderr, of buck audit rules, as well as any deserialized objects\n from evaluating statements. If the file could be parsed properly\n and buck returns successfully, debug_lines will contain the objects\n in the same order as 'statements'\n \"\"\"\n\n # We don't start a daemon up because:\n # - Generally we're only running once, and in a temp dir, so it doesn't\n # make a big difference\n # - We want to make sure things cleanup properly, and this is just\n # easier\n buck_file_content = \"\"\n\n if len(statements) == 0:\n raise ValueError(\"At least one statement must be provided\")\n\n for include in includes:\n if len(include) < 2:\n raise ValueError(\n \"include ({}) must have at least two elements: a path to \"\n \"include, and at least one var to import\".format(include)\n )\n\n vars = \",\".join(('\"' + var + '\"' for var in include[1:]))\n buck_file_content += 'load(\"{}\", {})\\n'.format(include[0], vars)\n buck_file_content += extra_declarations or \"\"\n buck_file_content += \"\\n\"\n for statement in statements:\n buck_file_content += 'print(\"TEST_RESULT: %s\" % repr({}))\\n'.format(\n statement\n )\n\n cmd = [\"buck\", \"audit\", \"rules\", buckfile]\n result = self.run(cmd, {buckfile: buck_file_content}, environment_overrides)\n debug_lines = []\n for line in result.stderr.split(\"\\n\"):\n # python. Sample line: | TEST_RESULT: {}\n if line.startswith(\"| TEST_RESULT:\"):\n debug_lines.append(self._convertDebug(line.split(\":\", 1)[-1].strip()))\n # Sample line: DEBUG: /Users/user/temp/BUCK:1:1: TEST_RESULT: \"hi\"\n elif line.startswith(\"DEBUG: \") and \"TEST_RESULT:\" in line:\n debug_lines.append(self._convertDebug(line.split(\":\", 5)[-1].strip()))\n return UnitTestResult(\n returncode=result.returncode,\n stdout=result.stdout,\n stderr=result.stderr,\n debug_lines=debug_lines,\n )\n\n def _convertDebug(self, string):\n \"\"\"\n Converts a TEST_RESULT line generated by run_unittests into a real\n object. Functions are turned into 'function' named tuples, and structs\n are also turned into a namedtuple\n \"\"\"\n\n def struct(**kwargs):\n return collections.namedtuple(\"struct\", sorted(kwargs.keys()))(**kwargs)\n\n def function(name):\n return collections.namedtuple(\"function\", [\"name\"])(name)\n\n string = re.sub(r\"\", r'function(\"\\1\")', string)\n # Yup, eval.... this lets us have nested struct objects easily so we\n # can do stricter type checking\n return eval(\n string,\n {\n \"__builtins__\": {\n \"struct\": struct,\n \"function\": function,\n \"True\": True,\n \"False\": False,\n }\n },\n {},\n )\n\n\nclass Project:\n \"\"\"\n An object that represents all cells for a run, and handles creating and\n cleaning up the temp directory that we work in\n \"\"\"\n\n def __init__(\n self,\n remove_files=None,\n add_fbcode_macros_cell=True,\n add_skylib_cell=True,\n add_xplat_cell=True,\n add_fbsource_cell=True,\n run_buckd=False,\n ):\n \"\"\"\n Create an instance of Project\n\n Arguments:\n remove_files: Whether files should be removed when __exit__ is\n called\n add_fbcode_macros_cell: Whether to create the fbcode_macros cell\n when __enter__ is called\n add_skylib_cell: Whether to create the skylib cell when __enter__\n is called\n \"\"\"\n\n if remove_files is None:\n remove_files = os.environ.get(\"FBCODE_MACROS_KEEP_DIRS\") != \"1\"\n\n self.root_cell = None\n self.project_path = None\n self.remove_files = remove_files\n self.add_fbcode_macros_cell = add_fbcode_macros_cell\n self.add_skylib_cell = add_skylib_cell\n self.add_xplat_cell = add_xplat_cell\n self.add_fbsource_cell = add_fbsource_cell\n self.cells = {}\n self.run_buckd = run_buckd\n\n def __enter__(self):\n self.project_path = tempfile.mkdtemp()\n self.root_cell = self.addCell(\"root\")\n self.root_cell.addResourcesFrom(\".buckversion\")\n\n if self.add_fbcode_macros_cell:\n self.addCell(\"fbcode_macros\")\n if self.add_skylib_cell:\n self.addCell(\"bazel_skylib\")\n if self.add_xplat_cell:\n self.addCell(\"xplat\")\n if self.add_fbsource_cell:\n self.addCell(\"fbsource\")\n return self\n\n def __exit__(self, type, value, traceback):\n self.killBuckd()\n if self.project_path:\n if self.remove_files:\n shutil.rmtree(self.project_path)\n else:\n logging.info(\n \"Not deleting temporary files at {}\".format(self.project_path)\n )\n\n def killBuckd(self):\n for cell in self.cells.values():\n cell_path = cell.fullPath()\n if os.path.exists(os.path.join(cell_path, \".buckd\")):\n try:\n with open(os.devnull, \"w\") as dev_null:\n subprocess.check_call(\n [\"buck\", \"kill\"],\n stdout=dev_null,\n stderr=dev_null,\n cwd=cell_path,\n )\n except subprocess.CalledProcessError as e:\n print(\"buck kill failed: {}\".format(e))\n\n def addCell(self, name):\n \"\"\"Add a new cell\"\"\"\n if name in self.cells:\n raise ValueError(\"Cell {} already exists\".format(name))\n new_cell = Cell(name, self)\n self.cells[name] = new_cell\n return new_cell\n\n\ndef with_project(use_skylark=True, use_python=True, *project_args, **project_kwargs):\n \"\"\"\n Annotation that makes a project available to a test. This passes the root\n cell to the function being annotated and tears down the temporary\n directory (by default, can be overridden) when the method finishes executing\n \"\"\"\n\n if not use_python and not use_skylark:\n raise ValueError(\"Either use_python or use_skylark must be set\")\n\n def wrapper(f):\n suffixes = getattr(f, \"_function_suffixes\", set())\n if use_skylark:\n suffixes.add(\"skylark\")\n if use_python:\n suffixes.add(\"python\")\n if suffixes:\n setattr(f, \"_function_suffixes\", suffixes)\n\n @functools.wraps(f)\n def inner_wrapper(suffix, *args, **kwargs):\n if suffix == \"skylark\":\n build_file_syntax = \"SKYLARK\"\n elif suffix == \"python\":\n build_file_syntax = \"PYTHON_DSL\"\n else:\n raise ValueError(\"Unknown parser type: %s\" % suffix)\n\n with Project(*project_args, **project_kwargs) as project:\n new_args = args + (project.root_cell,)\n if isinstance(new_args[0], TestCase):\n new_args[0].setUpProject(project.root_cell)\n project.root_cell.updateBuckconfig(\n \"parser\", \"default_build_file_syntax\", build_file_syntax\n )\n f(*new_args, **kwargs)\n\n return inner_wrapper\n\n return wrapper\n\n\nclass TestMethodRenamer(type):\n \"\"\"\n Simple metaclass class that renames test_foo to test_foo_skylark and\n test_foo_python\n \"\"\"\n\n def __new__(metacls, name_, bases, classdict):\n bases = bases or []\n\n newclassdict = {}\n for name, attr in classdict.items():\n suffixes = getattr(attr, \"_function_suffixes\", None)\n if callable(attr) and suffixes:\n for suffix in suffixes:\n new_name = str(name + \"_\" + suffix)\n assert new_name not in newclassdict\n\n # The extra lambda is so that things get bound properly.\n def call_with_suffix(s=suffix, a=attr):\n def inner(*args, **kwargs):\n return a(s, *args, **kwargs)\n\n inner.__name__ = new_name\n return inner\n\n newclassdict[new_name] = call_with_suffix()\n else:\n newclassdict[name] = attr\n return type.__new__(metacls, name_, bases, newclassdict)\n\n\n@six.add_metaclass(TestMethodRenamer)\nclass TestCase(unittest.TestCase):\n maxDiff = None\n setupPathsConfig = True\n setupThirdPartyConfig = True\n setupPlatformOverrides = True\n setupBuildOverrides = True\n setupCoreToolsTargets = True\n\n def setUpProject(self, root):\n # Setup some defaults for the environment\n if self.setupPathsConfig:\n self.addPathsConfig(root)\n if self.setupThirdPartyConfig:\n self.addDummyThirdPartyConfig(root)\n if self.setupPlatformOverrides:\n self.addDummyPlatformOverrides(root)\n if self.setupBuildOverrides:\n self.addDummyBuildModeOverrides(root)\n if self.setupCoreToolsTargets:\n self.addDummyCoreToolsTargets(root)\n\n def addDummyCoreToolsTargets(self, root):\n root.project.cells[\"fbcode_macros\"].writeFile(\n \"build_defs/core_tools_targets.bzl\",\n dedent(\n \"\"\"\n load(\"@bazel_skylib//lib:new_sets.bzl\", \"sets\")\n core_tools_targets = sets.make([(\"core\", \"awesome_tool\")])\n \"\"\"\n ),\n )\n\n def addDummyThirdPartyConfig(self, root):\n current_arch = platform.machine()\n other_arch = \"x86_64\" if current_arch == \"aarch64\" else \"aarch64\"\n third_party_config = dedent(\n \"\"\"\\\n third_party_config = {{\n \"platforms\": {{\n \"gcc5\": {{\n \"architecture\": \"{current_arch}\",\n \"tools\": {{\n \"projects\": {{\n \"flex\": \"1.0\",\n \"bison\": \"1.0\",\n \"ghc\": \"8.0.2\",\n }},\n }},\n \"build\": {{\n \"projects\": {{\n \"bar\": \"1.0\",\n \"bzip2\": \"2.0\",\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n \"glibc\": \"2.26\",\n \"ImageMagick\": \"1.67\",\n \"python\": \"2.7\",\n }},\n \"auxiliary_versions\": {{}},\n }},\n }},\n \"gcc6\": {{\n \"architecture\": \"{current_arch}\",\n \"tools\": {{\n \"projects\": {{\n \"ghc\": \"8.0.2\",\n }},\n }},\n \"build\": {{\n \"projects\": {{\n \"bar\": \"1.0\",\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n \"glibc\": \"2.26\",\n \"python\": [\"2.7\", \"3.7\"],\n }},\n \"auxiliary_versions\": {{}},\n }},\n }},\n \"gcc7\": {{\n \"architecture\": \"{current_arch}\",\n \"tools\": {{\n \"projects\": {{\n \"ghc\": \"8.0.2\",\n }},\n }},\n \"build\": {{\n \"projects\": {{\n \"bar\": \"1.0\",\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n \"glibc\": \"2.26\",\n \"python\": [\"2.7\", \"3.7\"],\n }},\n \"auxiliary_versions\": {{}},\n }},\n }},\n \"gcc5-other\": {{\n \"architecture\": \"{other_arch}\",\n \"tools\": {{\n \"projects\": {{\n \"ghc\": \"8.0.2\",\n }},\n }},\n \"build\": {{\n \"projects\": {{\n \"bar\": \"1.0\",\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n \"glibc\": \"2.26\",\n \"python\": [\"2.7\", \"3.7\"],\n }},\n \"auxiliary_versions\": {{}},\n }},\n }},\n \"default\": {{\n \"architecture\": \"{current_arch}\",\n \"tools\": {{\n \"projects\": {{\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n }},\n }},\n \"build\": {{\n \"projects\": {{\n \"bar\": \"1.0\",\n \"foo\": \"1.0\",\n \"ghc\": \"8.0.2\",\n \"glibc\": \"2.26\",\n \"python\": [\"2.7\", \"3.7\"],\n }},\n \"auxiliary_versions\": {{}},\n }},\n }},\n }},\n \"version_universes\": [\n {{\"python\": \"2.7\", \"openssl\": \"1.0.2\"}},\n {{\"python\": \"3.7\", \"openssl\": \"1.0.2\"}},\n {{\"python\": \"2.7\", \"openssl\": \"1.1.0\"}},\n {{\"python\": \"3.7\", \"openssl\": \"1.1.0\"}},\n ],\n }}\n \"\"\".format(\n current_arch=current_arch, other_arch=other_arch\n )\n )\n root.updateBuckconfig(\"d\", \"platform\", \"gcc5\")\n for python_platform in [\"py2\", \"py3\"]:\n for cxx_platform in [\"gcc5\", \"gcc6\", \"gcc7\", \"gcc5-other\", \"default\"]:\n full_platform = \"{}-{}\".format(python_platform, cxx_platform)\n root.updateBuckconfig(\n \"python#\" + full_platform,\n \"interpreter\",\n \"/usr/local/bin/python-\" + full_platform,\n )\n root.project.cells[\"fbcode_macros\"].addFile(\n \"build_defs/third_party_config.bzl\", third_party_config\n )\n\n def addDummyPlatformOverrides(self, root):\n platform_overrides = dedent(\n \"\"\"\\\n platform_overrides = {\n \"fbcode\": {\n \"foo/bar\": [\"gcc5\", \"gcc5-other\"],\n \"foo\": [\"gcc7\"],\n },\n }\n \"\"\"\n )\n root.project.cells[\"fbcode_macros\"].addFile(\n \"build_defs/platform_overrides.bzl\", platform_overrides\n )\n\n def addDummyBuildModeOverrides(self, root):\n build_mode = dedent(\n \"\"\"\n load(\n \"@fbcode_macros//build_defs:create_build_mode.bzl\",\n \"create_build_mode\",\n )\n def dev():\n return {\n \"dev\": create_build_mode(\n c_flags=[\"-DDEBUG\"],\n cxx_flags=[\"-DCXX_DEBUG\"],\n clang_flags=[\"-DCLANG\"],\n gcc_flags=[\"-DGCC\"]),\n }\n def dbg():\n return {\n \"dbg\": create_build_mode(\n c_flags=[\"-DDEBUG\"],\n cxx_flags=[\"-DCXX_DEBUG\"],\n clang_flags=[\"-DCLANG\"],\n gcc_flags=[\"-DGCC\"]),\n }\n def opt():\n return {\n \"opt\": create_build_mode(\n c_flags=[\"-DDEBUG\"],\n cxx_flags=[\"-DCXX_DEBUG\"],\n clang_flags=[\"-DCLANG\"],\n gcc_flags=[\"-DGCC\"]),\n }\n \"\"\"\n )\n root.addFile(\"BUILD_MODE.bzl\", build_mode)\n root.updateBuckconfig(\n \"buildfile\",\n \"package_includes\",\n (\n \"foo/bar=>//:BUILD_MODE.bzl::get_modes=dev,\"\n \"foo/bar-other=>//:BUILD_MODE.bzl::get_modes=dbg,\"\n \"foo=>//:BUILD_MODE.bzl::get_modes=opt\"\n ),\n )\n\n def addPathsConfig(\n self,\n root,\n third_party_root=\"third-party-buck\",\n use_platforms_and_build_subdirs=True,\n ):\n paths_config = dedent(\n \"\"\"\n paths_config = struct(\n third_party_root=\"%s\",\n use_platforms_and_build_subdirs=%r,\n )\n \"\"\"\n % (third_party_root, use_platforms_and_build_subdirs)\n )\n root.project.cells[\"fbcode_macros\"].addFile(\n \"build_defs/paths_config.bzl\", paths_config\n )\n\n def assertSuccess(self, result, *expected_results):\n \"\"\" Make sure that the command ran successfully \"\"\"\n self.assertEqual(\n 0,\n result.returncode,\n \"Expected zero return code\\nSTDOUT:\\n{}\\nSTDERR:\\n{}\\n\".format(\n result.stdout, result.stderr\n ),\n )\n if expected_results:\n self.assertEqual(list(expected_results), result.debug_lines)\n\n def assertFailureWithMessage(self, result, expected_message, *other_messages):\n \"\"\" Make sure that we failed with a substring in stderr \"\"\"\n self.assertNotEqual(0, result.returncode)\n try:\n if hasattr(expected_message, \"search\"):\n self.assertRegexpMatches(result.stderr, expected_message)\n else:\n self.assertIn(expected_message, result.stderr)\n except AssertionError as e:\n # If we get a parse error, it's a lot easier to read as multiple\n # lines, rather than a single line witn \\n in it\n e.args = (e.args[0].replace(r\"\\n\", \"\\n\"),) + e.args[1:]\n raise e\n\n def validateAudit(self, expected_results, result):\n \"\"\"\n Validate that audit results are as expected\n\n Validates that all requested files came out in the audit comment. Also\n validates that the command ran successfully, and that the contents\n are as expected\n\n Arguments:\n expected_results: A dictionary of file name to contents\n result: An AuditTestResult object\n \"\"\"\n self.assertSuccess(result)\n empty_results = [\n file for file, contents in result.files.items() if contents is None\n ]\n try:\n self.assertEqual([], empty_results)\n except AssertionError as e:\n raise_with_traceback(\n AssertionError(\n \"Got a list of files that had empty contents: {!r}\\n{}\".format(\n empty_results, str(e)\n )\n )\n )\n\n try:\n self.assertEqual(\n sorted(expected_results.keys()), sorted(result.files.keys())\n )\n except AssertionError as e:\n raise_with_traceback(\n AssertionError(\n \"Parsed list of files != expected list of files:\\n{}\".format(str(e))\n )\n )\n\n for file, contents in result.files.items():\n try:\n self.assertEqual(\n expected_results[file].replace(\"\\\\n\", \"\\n\"),\n contents.replace(\"\\\\n\", \"\\n\"),\n )\n except AssertionError as e:\n raise_with_traceback(\n AssertionError(\"Content of {} differs:\\n{}\".format(file, str(e)))\n )\n\n def struct(self, **kwargs):\n \"\"\"\n Creates a namedtuple that can be compared to 'struct' objects that\n are parsed in unittests\n \"\"\"\n return collections.namedtuple(\"struct\", sorted(kwargs.keys()))(**kwargs)\n\n def rule_target(self, repo, base_path, name):\n return self.struct(repo=repo, base_path=base_path, name=name)\n","sub_path":"infra_macros/fbcode_macros/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":35978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"56775683","text":"#! /usr/bin/env python\n# -*- coding: utf8 -*-\nfrom ground import *\n\nclass Account:\n\t__account_types = [\n\t\t(\"资产\", 1),\n\t\t(\"负债\", -1),\n\t\t(\"收入\", -1),\n\t\t(\"支出\", 1),\n\t\t(\"所有者权益\", -1)\n\t]\n\n\tdef root(self):\n\t\treturn g_db.sql_get_value(\"account_id\", \"account\", \"name = '帐'\")\n\n\tdef __insert(self, parent_id, name):\n\t\taccount_id = g_db.sql_get_value(\"account_id\", \"account\", \"parent_id = {} and name = '{}'\".format(parent_id, name))\n\t\tif account_id != None:\n\t\t\treturn account_id\n\t\treturn g_db.sql_insert(\"account\", {\"parent_id\": parent_id, \"name\": name}, \"account_id\")\n\n\tdef add(self, path, parent_id = None):\n\t\tif parent_id == None:\n\t\t\tparent_id = self.root()\n\t\tnodes = path.split('.')\n\t\tfor node in nodes:\n\t\t\tparent_id = self.__insert(parent_id, node)\n\t\treturn parent_id\n\n\tdef path(self, account_id, display = False):\n\t\tpath = \"\"\n\t\twhile True:\n\t\t\tname, parent_id = g_db.sql_get_values([\"name\", \"parent_id\"], \"account\", \"account_id = {}\".format(account_id), \"\")\n\t\t\tif parent_id == account_id: #root account\n\t\t\t\tbreak\n\t\t\taccount_id = parent_id\n\n\t\t\t#assemble path\n\t\t\tif path == \"\":\n\t\t\t\tpath = name\n\t\t\t\tif display and name.find(\"commodity_\") == 0:\n\t\t\t\t\tcommodity_id = int(name[len(\"commodity_\"):])\n\t\t\t\t\tpath = g_db.sql_get_value(\"name\", \"commodity\", \"commodity_id = {}\".format(commodity_id))\n\t\t\telse:\n\t\t\t\tpath = name + \".\" + path\n\t\treturn path\n\n\tdef __monetary_account(self, account_id):\n\t\tresult = []\n\t\tchildren = g_db.sql_get_rows([\"account_id\", \"name\"], \"account\", \"parent_id = {}\".format(account_id), \"order by account_id\")\n\t\tfor child_id, name in children:\n\t\t\tif name.find(\"commodity_\") == 0:\n\t\t\t\treturn []\n\t\t\telse:\n\t\t\t\tresult += self.__monetary_account(child_id)\n\t\tif len(children) == 0:\n\t\t\tresult += [account_id]\n\t\treturn result\n\n\tdef monetary_accounts(self):\n\t\treturn self.__monetary_account(self.add(\"钱\"))\n\n\tdef monetary_select(self, hint):\n\t\treturn candidates_selector(self.monetary_accounts(), lambda x: self.path(x), hint, context = \"账户选择\")\n\n\tdef get_balance(self, account_id):\n\t\treturn g_db.sql_get_value(\"balance\", \"account\", \"account_id = {}\".format(account_id))\n\n\tdef set_balance(self, account_id, balance):\n\t\td = {\"balance\": balance}\n\t\tg_db.sql_update(\"account\", d, \"account_id = {}\".format(account_id))\n\n\tdef sign(self, account_id):\n\t\taccount_type_name = self.path(account_id).split('.')[1]\n\t\tfor name, sign in self.__account_types:\n\t\t\tif account_type_name == name:\n\t\t\t\treturn sign\n\t\traise ValueError(\"无法识别account_id : {}对应的账户类型!\".format(account_id))\n\n\tdef __monetary(self, account_id):\n\t\tif self.path(account_id).find(\"钱\") == 0:\n\t\t\treturn True\n\t\treturn False\n\n\tdef value_2_str(self, account_id, value, sign=\"-\"):\n\t\tmonetary = self.__monetary(account_id)\n\t\tif monetary:\n\t\t\treturn (\"{:\" + sign + \".2f}\").format(value/100.0)\n\t\telse:\n\t\t\treturn (\"{:\" + sign + \"}\").format(value)\n\n\tdef str_2_value(self, account_id, value):\n\t\tmonetary = self.__monetary(account_id)\n\t\tif monetary:\n\t\t\treturn money_2_internal(float(value))\n\t\telse:\n\t\t\treturn int(value)\n\n\tdef __repositories(self, account_id, virtual):\n\t\tresult = []\n\t\tchildren = g_db.sql_get_rows([\"account_id\", \"name\"], \"account\", \"parent_id = {}\".format(account_id), \"\")\n\t\tfor child_id, name in children:\n\t\t\tif name.find(\"commodity_\") == 0: #leaf hit\n\t\t\t\tif not virtual:\n\t\t\t\t\tif self.path(account_id) == \"货.资产.应收\":\n\t\t\t\t\t\treturn []\n\t\t\t\treturn [account_id]\n\t\t\telse:\n\t\t\t\tresult += self.__repositories(child_id, virtual)\n\t\treturn result\n\n\tdef repositories(self, virtual = False):\n\t\treturn self.__repositories(g_account.add(\"货.资产\"), virtual)\n\n\tdef commodity_id(self, account_id):\n\t\tname = g_db.sql_get_value(\"name\", \"account\", \"account_id = {}\".format(account_id), \"\")\n\t\tif name.find(\"commodity_\") == 0:\n\t\t\treturn int(name[len(\"commodity_\"):])\n\t\treturn None\n\ng_account = Account()\n","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"47921732","text":"class Node(object):\n def __init__(self, cnt=0):\n self.prev = None\n self.next = None\n self.cnt = cnt\n self.keys = set()\n\n\nclass AllOne(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.head = Node(float(\"NaN\"))\n self.tail = Node(float(\"NaN\"))\n self.head.next = self.tail\n self.tail.prev = self.head\n self.key_node = {}\n\n def __repr__(self):\n cur = self.head.next\n ret = []\n while cur != self.tail:\n ret.append('{}:{}'.format(cur.cnt, cur.keys))\n cur = cur.next\n return ', '.join(ret)\n\n def insert_after(self, node, key):\n if node.next.cnt != node.cnt+1:\n new = Node(node.cnt+1)\n new.keys.add(key)\n new.next = node.next\n new.next.prev = new\n new.prev = node\n node.next = new\n return new\n else:\n node.next.keys.add(key)\n return node.next\n\n def prepend(self, key):\n if self.head.next.cnt == 1:\n self.head.next.keys.add(key)\n return self.head.next\n else:\n ret = self.insert_after(self.head, key)\n ret.cnt = 1\n return ret\n\n def insert_before(self, node, key):\n if node.prev.cnt != node.cnt-1:\n new = Node(node.cnt-1)\n new.keys.add(key)\n new.prev = node.prev\n new.prev.next = new\n new.next = node\n node.prev = new\n return new\n else:\n node.prev.keys.add(key)\n return node.prev\n\n def remove(self, node):\n pre, nxt = node.prev, node.next\n pre.next, nxt.prev = nxt, pre\n node.prev = node.next = None\n\n def is_empty(self):\n return self.head.next == self.tail\n\n def inc(self, key):\n \"\"\"\n Inserts a new key with value 1. Or increments an existing key by 1.\n :type key: str\n :rtype: void\n \"\"\"\n if key in self.key_node:\n node = self.key_node[key]\n node.keys.discard(key)\n self.key_node[key] = self.insert_after(node, key)\n if not node.keys:\n self.remove(node)\n else:\n self.key_node[key] = self.prepend(key)\n\n def dec(self, key):\n \"\"\"\n Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.\n :type key: str\n :rtype: void\n \"\"\"\n if key in self.key_node:\n node = self.key_node[key]\n node.keys.discard(key)\n if node.cnt > 1:\n self.key_node[key] = self.insert_before(node, key)\n else:\n del self.key_node[key]\n if not node.keys:\n self.remove(node)\n\n def getMaxKey(self):\n \"\"\"\n Returns one of the keys with maximal value.\n :rtype: str\n \"\"\"\n if self.is_empty():\n return \"\"\n return next(iter(self.tail.prev.keys))\n\n def getMinKey(self):\n \"\"\"\n Returns one of the keys with Minimal value.\n :rtype: str\n \"\"\"\n if self.is_empty():\n return \"\"\n return next(iter(self.head.next.keys))\n\n\n# Your AllOne object will be instantiated and called as such:\n# obj = AllOne()\n# obj.inc(key)\n# obj.dec(key)\n# param_3 = obj.getMaxKey()\n# param_4 = obj.getMinKey()\n","sub_path":"All O`one Data Structure.py","file_name":"All O`one Data Structure.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308033272","text":"import fresh_tomatoes # Import file that contains website code\nimport media # Import file that contains Movie class\n\n# Initiate class Movie and populate class variables for each movie\nthe_big_lebowski = media.Movie(\"The Big Lebowski\", \"The dude abides\",\n \"https://upload.wikimedia.org/wikipedia/en/3/35/Biglebowskiposter.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=cd-go0oBF4Y\")\n\nthe_life_aquatic = media.Movie(\"The Life Aquatic\", \"The Zissou\",\n \"https://upload.wikimedia.org/wikipedia/en/7/7c/Lifeaquaticposter.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=yh401Rmkq0o\")\n\nthe_sting = media.Movie(\"The Sting\",\n \"One of the most stylish movies of the year\",\n \"https://upload.wikimedia.org/wikipedia/en/9/9c/Stingredfordnewman.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=LN2hBOIXhBs\")\n\nthe_trip = media.Movie(\"The Trip\", \"Eat, Drink and Try Not to Kill Eachother\",\n \"https://upload.wikimedia.org/wikipedia/en/8/8f/Trip_poster.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=Xxq-I_e_KXg\")\n\nthe_italian_job = media.Movie(\"The Italian Job\", \"Italian crime caper\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b3/The_Italian_Job_1969_poster.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=FEltJsIwSvE\")\n\nthe_bounty = media.Movie(\"The Bounty\", \"They were friends through hell.\"\n \"They became enemies in Paradise\",\n \"https://upload.wikimedia.org/wikipedia/en/c/cd/The_Bounty.jpg\", # NOQA\n \"https://www.youtube.com/watch?v=g5QER2wu0lg\")\n\n# Create movie list\nmovies = [the_big_lebowski, the_life_aquatic, the_sting, the_trip,\n the_italian_job, the_bounty]\n\n# Open webpage with favourite movies with our movies list as input\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"80579583","text":"from application.src.rewrites import SoapHandler\nfrom application.src.rewrites import wsdl\nfrom application.src.request import request\nimport logging\n\n\n# Log\nlog = logging.getLogger(__name__)\n\n# Settings\npartner_name = 'tim'\napi_version = 'v1'\n\n\nclass TestSoapHandler(SoapHandler):\n __urls__ = [r\"/{0}/{1}/test\".format(partner_name, api_version),\n r\"/{0}/{1}/test/\".format(partner_name, api_version)]\n\n @request\n @wsdl(\n _args=['event-id', 'msisdn', 'partner-id', 'value', 'date', 'time', 'tariff-id', 'subsys'],\n _params=[int, int, int, float, str, str, int, str],\n _returns=int,\n _name='testando')\n def test(self, *args):\n try:\n log.info(\"Test notification received: {0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}\".format(\n args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7],\n ))\n except:\n self.set_status(400)\n finally:\n return self.get_status()\n","sub_path":"globalsdp/Code/integrations/__example__/v1/api/soap/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"197001221","text":"class QuadProgClass:\r\n\tdef __init__(self,orien,pos_v,ang_v,w_t,v_t,epsilon,inc_pos_v,inc_ang_v,er,ep,upper_dq_bounds):\r\n\t\tself.stop=False\r\n\t\tI3 = np.eye(3)\r\n\t\tself.ex = I3[:,0]\r\n\t\tself.ey = I3[:,1]\r\n\t\tself.ez = I3[:,2]\r\n\t\t\r\n\t\th1 = ez\r\n\t\th2 = ey\r\n\t\th3 = ey\r\n\t\th4 = ex\r\n\t\th5 = ey\r\n\t\th6 = ex\r\n\t\tself.P = np.array([[0,0,0], [0.32, 0, 0.78], [0, 0, 1.075], [0, 0, 0.2], [1.142, 0, 0], [0.2, 0, 0], [0,0,0]]).T\r\n\t\tself.q = np.zeros((6, 1))\r\n\t\tself.H = np.array([h1, h2, h3, h4, h5, h6]).T\r\n\t\tself.ttype = np.zeros((1, 6))\r\n\t\t\"\"\" \"\"\"\r\n\t\tself.n = 6\r\n\t\t\r\n\t\tdq_bounds = np.array([[100,110], [90,90], [90,90], [170,190], [120,140], [190,235]]).T\r\n\t\tself.dq_bounds = dq_bounds*np.pi/180\r\n\t\tself.q = np.array([0,0,0,0,np.pi/2,0]).reshape(6, 1)\r\n\t\tself.dq = np.zeros((int(self.n),1))\r\n\t\tdq = np.zeros((int(self.n),1))\r\n\t\tself.R,self.pos = self.__fwdkin(self)\r\n\t\tself.orien=orien\r\n\t\tself.pos_v=pos_v\r\n\t\tself.ang_v=ang_v\r\n\t\tself.w_t=w_t\r\n\t\tself.v_t=v_t\r\n\t\tself.epsilon=epsilon\r\n\t\tself.inc_pos_v=inc_pos_v\r\n\t\tself.inc_ang_v=inc_ang_v\r\n\t\tself.er=er\r\n\t\tself.ep=ep\r\n\t\tself.upper_dq_bounds=upper_dq_bounds\r\n\t\t\r\n\t# find closest rotation matrix \r\n\t# A=A*inv(sqrt(A'*A)) \r\n\tdef Closest_Rotation(R):\r\n\t\tR_n = np.dot(R, inv(sqrtm(np.dot(R.T, R))))\r\n \r\n\t\treturn R_n\r\n\t\t\r\n\t__Closest_Rotation=Closest_Rotation\r\n\r\n\t\r\n\t# ROT Rotate along an axis h by q in radius\r\n\r\n\tdef rot(h, q):\r\n\t\th=h/norm(h)\r\n\t\tR = np.eye(3) + np.sin(q)*self.__hat(h) + (1 - np.cos(q))*np.dot(self.__hat(h), self.__hat(h))\r\n\t\t\r\n\t\treturn R\r\n\t\r\n\t__rot=rot\r\n\t\r\n\tdef hat(h):\r\n\t\th_hat = np.array([[0, -h[2], h[1]], [h[2], 0, -h[0]], [-h[1], h[0], 0]])\r\n\t\t\r\n\t\treturn h_hat\r\n\t\r\n\t__hat=hat\r\n\t\r\n\tdef fwdkin(self):\r\n\t\tR=np.eye(3)\r\n\t\tp=np.zeros((3,1))\r\n\t\t\r\n\t\tfor i in range(self.n): \r\n\t\t\th_i = self.H[0:3,i].reshape(3, 1)\r\n\t\t\tRi = np.eye(3)\r\n\t\t\t\r\n\t\t\tif self.ttype[0][i] == 0: \r\n\t\t\t\t#rev\r\n\t\t\t\tpi = self.P[0:3,i].reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R, pi)\r\n\t\t\t\tRi = self.__rot(h_i,self.q[i])\r\n\t\t\t\tR = np.dot(R, Ri)\r\n\t\t\t\tR = self.__Closest_Rotation()\r\n\t\t\telif self.ttype[i] == 1: \r\n\t\t\t\t#pris\r\n\t\t\t\tpi = (self.P[:,i]+self.q[i]*h_i).reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R, pi)\r\n\t\t\telse: \r\n\t\t\t\t#default pris\r\n\t\t\t\tpi = (self.P[:,i]+self.q[i]*h_i).reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R, pi)\r\n\t \r\n\t\t#End Effector T\r\n\t\tp=p+np.dot(R, P[0:3,self.n].reshape(3, 1))\r\n\t\t\r\n\t\treturn R, p\r\n\t\r\n\t__fwdkin=fwdkin\r\n\t\r\n\tdef fwdkin_alljoints(self):\r\n\t\tR=np.eye(3)\r\n\t\tp=np.zeros((3,1))\r\n\t\tRR = np.zeros((3,3,self.n+1))\r\n\t\tpp = np.zeros((3,self.n+1))\r\n\t\t\r\n\t\tfor i in range(self.n):\r\n\t\t\th_i = self.H[0:3,i]\r\n\t\t \r\n\t\t\tif self.ttype[0][i] == 0:\r\n\t\t\t#rev\r\n\t\t\t\tpi = self.P[0:3,i].reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R,pi)\r\n\t\t\t\tRi = self.__rot(h_i,self.q[i])\r\n\t\t\t\tR = np.dot(R,Ri)\r\n\t\t\t\tR = self.__Closest_Rotation()\r\n\t\t\telif self.ttype[i] == 1: \r\n\t\t\t#pris\r\n\t\t\t\tpi = (self.P[:,i]+self.q[i]*h_i).reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R,pi)\r\n\t\t\telse: \r\n\t\t\t# default pris\r\n\t\t\t\tpi = (self.P[:,i]+self.q[i]*h_i).reshape(3, 1)\r\n\t\t\t\tp = p+np.dot(R,pi)\r\n\t\t\t\r\n\t\t\tpp[:,[i]] = p\r\n\t\t\tRR[:,:,i] = R\r\n\t\t\r\n\t\t# end effector T\r\n\t\tp=p+np.dot(R, self.P[0:3,self.n].reshape(3, 1))\r\n\t\tpp[:,[n]] = p\r\n\t\tRR[:,:,n] = R\r\n\t\t# parameters for qp\r\n\t\tself.pos=pp[:, -1]\r\n\t\torien_tmp = Quaternion(matrix=RR[:, :, -1])\r\n\t\tself.orien=np.array([orien_tmp[0], orien_tmp[1], orien_tmp[2], orien_tmp[3]]).reshape(1, 4)\r\n\t\t\r\n\t\treturn pp, RR\t\r\n\t__fwdkin_alljoints=fwdkin_alljoints\r\n\r\n\tdef Joint2Collision(self,Closest_Pt,pp):\r\n\t\tlink_dist = []\r\n\r\n\t\tfor i in range(5):\r\n\t\t\tlink = pp[:,i+1]-pp[:,i]\r\n\t\t\tlink = link/norm(link)\r\n\t\t\tpp2c = Closest_Pt - pp[:,i]\r\n\t\t\t\r\n\t\t\tlink_dist.append(norm(pp2c - abs(np.dot(pp2c, link))*link))\r\n\r\n\t\tJ2C_Joint = link_dist.index(min(link_dist)) + 1\r\n\t\tif(J2C_Joint==1):\r\n\t\t\tJ2C_Joint=2\r\n\t\t\t\r\n\t\treturn J2C_Joint\r\n\t\t\r\n\tdef getJacobian(self):\r\n\t\tnum_joints = len(self.q)\r\n\r\n\t\tP_0_i = np.zeros((3,num_joints+1))\r\n\t\tR_0_i = np.zeros((3,3,num_joints+1))\r\n\r\n\r\n\t\tP_0_i,R_0_i=self.__fwdkin_alljoints()\r\n\t\t\r\n\t\tP_0_T = P_0_i[:,num_joints]\r\n\r\n\t\tJ = np.zeros((6,num_joints))\r\n\t\t\r\n\t\tfor i in range(num_joints):\r\n\t\t\tif self.ttype[0][i] == 0:\r\n\t\t\t\tJ[:,i] = np.hstack((np.dot(R_0_i[:,:,i],H[:,i]), np.dot(self.__hat(np.dot(R_0_i[:,:,i], self.H[:,i])), (P_0_T - P_0_i[:,i]))))\r\n\t\t\"\"\" \"\"\"\r\n\t\t\r\n\t\treturn J\r\n\t# return jacobian of the closest point on panel \r\n\tdef getJacobian3(self,Closest_Pt, J2C_Joint):\r\n\t\tnum_joints = len(self.q)\r\n\r\n\t\tP_0_i = np.zeros((3,num_joints+1))\r\n\t\tR_0_i = np.zeros((3,3,num_joints+1))\r\n\r\n\r\n\t\tP_0_i,R_0_i=self.__fwdkin_alljoints()\r\n\t\t\"\"\" \"\"\"\r\n\t\t\r\n\t\tP_0_T = Closest_Pt\r\n\r\n\t\tJ = np.zeros((6,num_joints))\r\n\t\t\r\n\t\tfor i in range(num_joints):\r\n\t\t\tif self.ttype[0][i] == 0:\r\n\t\t\t\tJ[:,i] = np.hstack((np.dot(R_0_i[:,:,i],self.H[:,i]), np.dot(self.__hat(np.dot(R_0_i[:,:,i], self.H[:,i])), (P_0_T - P_0_i[:,i]))))\r\n\t\t\r\n\t\treturn J\r\n\r\n\t# return jacobian of the closest point on robot \r\n\tdef getJacobian2(self,Closest_Pt,J2C_Joint):\r\n\r\n\t\tnum_joints = len(self.q)\r\n\r\n\t\tP_0_i,R_0_i = self.__fwdkin_alljoints(self)\r\n\r\n\t\tP_0_T = P_0_i[:,num_joints]\r\n\r\n\t\tJ = np.zeros((6,num_joints))\r\n\r\n\t\tfor i in range(num_joints):\r\n\t\t\tif self.ttype[0][i] == 0:\r\n\t\t\t\tJ[:,i] = np.hstack((np.dot(R_0_i[:,:,i], self.H[:,i]), np.dot(self.__hat(np.dot(R_0_i[:,:,i], self.H[:,i])), (P_0_T - P_0_i[:,i]))))\r\n\r\n\t\tJ[:,J2C_Joint:7] = 0\r\n\t\tlink_c = P_0_i[:,J2C_Joint]-P_0_i[:,J2C_Joint-1]\r\n\t\tlink_c = link_c/norm(link_c)\r\n\t\t\r\n\t\tP_0_tmp = P_0_i[:,J2C_Joint-1]+ abs(np.dot(Closest_Pt-P_0_i[:,J2C_Joint-1],link_c))*link_c\r\n\t\t\r\n\t\treturn J,P_0_tmp\r\n\t\r\n\tdef quat2axang(self):\r\n\r\n\t\ts = norm(self.q[0][1:4])\r\n\t\tif s >= 10*np.finfo(np.float32).eps:\r\n\t\t\tvector = self.q[0][1:4]/s\r\n\t\t\ttheta = 2*np.arctan2(s,self.q[0][0])\r\n\t\telse:\r\n\t\t\tvector = np.array([0,0,1])\r\n\t\t\ttheta = 0\r\n\t\taxang = np.hstack((vector,theta))\r\n\t\t\r\n\t\treturn axang\r\n\t\t\r\n\tdef getqp_H(self,J, vr):\r\n\t\tn = len(self.dq)\r\n\t\tH1 = np.dot(np.hstack((J,np.zeros((6,2)))).T,np.hstack((J,np.zeros((6,2)))))\r\n\t\t\r\n\t\ttmp = np.vstack((np.hstack((np.hstack((np.zeros((3,n)),vr)),np.zeros((3,1)))),np.hstack((np.hstack((np.zeros((3,n)),np.zeros((3,1)))),self.pos_v)))) \r\n\t\tH2 = np.dot(tmp.T,tmp)\r\n\r\n\t\tH3 = -2*np.dot(np.hstack((J,np.zeros((6,2)))).T, tmp)\r\n\t\tH3 = (H3+H3.T)/2;\r\n\t\t\r\n\t\ttmp2 = np.vstack((np.array([0,0,0,0,0,0,np.sqrt(self.er),0]),np.array([0,0,0,0,0,0,0,np.sqrt(self.ep)])))\r\n\t\tH4 = np.dot(tmp2.T, tmp2)\r\n\r\n\t\tH = 2*(H1+H2+H3+H4)\r\n\r\n\t\treturn H\r\n\t\r\n\tdef getqp_f(self):\r\n\t\tf = -2*np.array([0,0,0,0,0,0,self.er,self.ep]).reshape(8, 1)\r\n \r\n\t\treturn f\r\n\t\t\r\n\t# quaternion multiply\r\n\tdef quatmultiply(q1, q0):\r\n\t\tw0, x0, y0, z0 = q0[0][0], q0[0][1], q0[0][2], q0[0][3]\r\n\t\tw1, x1, y1, z1 = q1[0][0], q1[0][1], q1[0][2], q1[0][3]\r\n\t\t\r\n\t\treturn np.array([-x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,\r\n\t\t\t\t\t\t x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,\r\n\t\t\t\t\t\t -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,\r\n\t\t\t\t\t\t x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0], dtype=np.float64).reshape(1, 4)\r\n\t\t\t\t\t \r\n\t__quatmultiply=quatmultiply\r\n\t\r\n\tdef func_xbox(self,button):\r\n\t\t# vx, vy, vz\r\n\t\tif (button[1] == 1):\r\n\t\t\tself.pos_v = self.pos_v + np.matrix([button[0]*self.inc_pos_v,0,0]).T\r\n\t\tif (button[2] == 1):\r\n\t\t\tself.pos_v = self.pos_v + np.matrix([0,button[0]*self.inc_pos_v,0]).T\r\n\t\tif (button[3] == 1):\r\n\t\t\tself.pos_v = self.pos_v + np.matrix([0,0,button[0]*self.inc_pos_v]).T\r\n\t\t\t\r\n\t\t# wx, wy, wz \r\n\t\tif (button[4] == 1):\r\n\t\t\tself.ang_v = self.__quatmultiply(np.array([np.cos(self.inc_ang_v/2), button[0]*np.sin(self.inc_ang_v/2), 0, 0]).reshape(1, 4), self.ang_v)\r\n\t\tif (button[5] == 1):\r\n\t\t\tself.ang_v = self.__quatmultiply(np.array([np.cos(self.inc_ang_v/2), 0, button[0]*np.sin(self.inc_ang_v/2), 0]).reshape(1, 4), self.ang_v)\r\n\t\tif (button[6] == 1):\r\n\t\t\tself.ang_v = self.__quatmultiply(np.array([np.cos(self.inc_ang_v/2), 0, 0, button[0]*np.sin(self.inc_ang_v/2)]).reshape(1, 4), self.ang_v)\r\n\t\t","sub_path":"QuadProgClass.py","file_name":"QuadProgClass.py","file_ext":"py","file_size_in_byte":7679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"164705228","text":"'''\r\nSort Array By Parity\r\n Array\r\n\r\nGiven:\r\nunsigned int [] A\r\n\r\nConst:\r\n- Return array consisting all the even elems of A\r\n- Followed by all the odd elements of A\r\n- Return any answer array satisfies condition\r\n\r\nSolution:\r\n- Straight brute force O(n) time\r\n- will use O(n) space to hold the evens and odds\r\n - Swap would be no space constraint, thats another days job\r\n\r\n- Another alternative is using two pointers for final array, though this is simpler to understand\r\n\r\n'''\r\n\r\nclass Solution:\r\n def sortArrayByParity(self, A: List[int]) -> List[int]:\r\n \r\n evens = []\r\n odds = []\r\n \r\n for item in A:\r\n\r\n if item %2 == 0:\r\n evens.append(item)\r\n else:\r\n odds.append(item)\r\n \r\n # evens.extend(odds)\r\n return evens + odds \r\n \r\n ","sub_path":"leetcode/problems/Array/905.py","file_name":"905.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613063537","text":"# Tests for the Data Analysis Designer (DAD)\nimport pytest\nfrom django.urls import reverse\n\nfrom surveys import models\n\n\n@pytest.fixture\ndef survey_submitted_setup(survey, survey_row, survey_component):\n # Set up necessary fixtures for the surveys-submitted-detail view\n pass\n\n\ndef create_formset_data(initial, total, forms):\n # Helper function to create POST data for a formset in the DAD.\n # Arguments:\n # * initial (int): Initial number of forms on the page at load time\n # * total (int): Total number of forms on the page at POST time\n # * forms (iterable): Iterable of dictionaries, each one representing the\n # field value for a form in the formset\n output_form = {\n # Initialize with management form data\n 'form-INITIAL_FORMS': initial,\n 'form-TOTAL_FORMS': total,\n }\n\n for idx, form in enumerate(forms):\n prefix = 'form-' + str(idx) + '-'\n for field_name, value in form.items():\n output_form[prefix + field_name] = value\n\n return output_form\n\n\ndef test_create_chart(client, survey_form_entry, survey_submitted_setup):\n # Test that the DAD can create a chart\n chart_data = [{'short_description': '__foobar__', 'order': 1}]\n post_data = create_formset_data(0, len(chart_data), chart_data)\n\n create_url = reverse('surveys-submitted-detail',\n kwargs={'form_entry_id': survey_form_entry.id})\n\n create_response = client.post(create_url, data=post_data)\n\n assert create_response.status_code == 200\n assert 'alert-success' in create_response.content.decode('utf-8')\n assert chart_data[0]['short_description'] in create_response.content.decode('utf-8')\n\n new_chart = models.SurveyChart.objects.get(id=1)\n assert new_chart.short_description == chart_data[0]['short_description']\n\n\ndef test_basic_chart_display(client, survey_form_entry, survey_submitted_setup):\n # Test that the DAD displays charts in the correct number and order\n chart_data = [\n {'short_description': '__bar__', 'order': 2},\n {'short_description': '__foo__', 'order': 1},\n {'short_description': '__baz__', 'order': 3}\n ]\n post_data = create_formset_data(0, len(chart_data), chart_data)\n\n create_url = reverse('surveys-submitted-detail',\n kwargs={'form_entry_id': survey_form_entry.id})\n\n create_response = client.post(create_url, data=post_data)\n\n assert create_response.status_code == 200\n assert 'alert-success' in create_response.content.decode('utf-8')\n\n # Make sure the charts are displayed in the correct order\n sorted_charts = sorted(chart_data, key=lambda chart: chart['order'])\n for idx, form in enumerate(sorted_charts):\n assert form['short_description'] in create_response.content.decode('utf-8')\n if idx == len(sorted_charts)-1:\n prev_desc = sorted_charts[idx-1]['short_description']\n assert prev_desc in create_response.content.decode('utf-8').split(form['short_description'])[0]\n else:\n next_desc = sorted_charts[idx+1]['short_description']\n assert next_desc in create_response.content.decode('utf-8').split(form['short_description'])[1]\n\n\ndef test_delete_chart(client, survey_form_entry, survey_submitted_setup):\n # Test that the DAD can delete a chart\n chart_data = {\n 'short_description': '__delete_me__',\n 'order': 1,\n 'form_entry': survey_form_entry\n }\n new_chart = models.SurveyChart.objects.create(**chart_data)\n\n url = reverse('surveys-submitted-detail',\n kwargs={'form_entry_id': survey_form_entry.id})\n get_response = client.get(url)\n\n assert get_response.status_code == 200\n assert chart_data['short_description'] in get_response.content.decode('utf-8')\n\n forms_to_delete = [chart_data.copy()]\n forms_to_delete[0].update({'id': new_chart.id, 'DELETE': True})\n post_data = create_formset_data(1, len(forms_to_delete), forms_to_delete)\n\n delete_response = client.post(url, data=post_data)\n\n assert delete_response.status_code == 200\n assert 'alert-success' in delete_response.content.decode('utf-8')\n assert chart_data['short_description'] not in delete_response.content.decode('utf-8')\n\n\ndef test_ignore_new_removed_chart(client, survey_form_entry, survey_submitted_setup):\n # Test that the DAD will not create a new chart if the 'delete' field is checked\n chart_data = [{'short_description': '__delete_me__', 'order': 1, 'DELETE': True}]\n post_data = create_formset_data(0, len(chart_data), chart_data)\n\n create_url = reverse('surveys-submitted-detail',\n kwargs={'form_entry_id': survey_form_entry.id})\n\n create_response = client.post(create_url, data=post_data)\n\n assert create_response.status_code == 200\n assert 'alert-success' in create_response.content.decode('utf-8')\n assert chart_data[0]['short_description'] not in create_response.content.decode('utf-8')\n","sub_path":"tests/test_dad.py","file_name":"test_dad.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121706859","text":"import hashlib\nimport configparser\nimport json\nimport datetime\nimport pymysql\nimport os\nimport xlsxwriter\nimport time\nimport sys\nimport xlrd\n\n# 初始化变量\n# currentpath = os.path.abspath(__file__)\ncurrentpath = os.path.dirname(__file__)\nprint('当前路径-///////开头', currentpath)\n# rootdir = os.path.abspath(os.path.dirname(currentpath) + os.path.sep + '..') # 打包环境使用\nrootdir = os.path.dirname(os.path.dirname(__file__)) # 开发环境使用\n# rootdir = os.path.dirname(os.path.realpath(sys.executable)) # 打包用\nprint('根目录-//////开头==', rootdir)\n\n# 获取md5值\ndef get_md5(arg):\n\n # 1 创建md5对象\n obj_md5 = hashlib.md5()\n\n # 2. 必须生命encode ,md5编码啊格式\n obj_md5.update(arg.encode(encoding='utf-8'))\n print('传递参数为', arg)\n md5_result = obj_md5.hexdigest()\n print('md5码为', md5_result)\n #返回md5码\n return md5_result\n\n\n# 相对路径读取配置文件中数据库 参数\ndef get_dbargs_from_config_byrelativepath(relativepath):\n print('前端 读取配置db内容,以 jsonStr 键值对格式 返回')\n\n # 实例化configParser对象\n config = configparser.ConfigParser()\n\n # -read读取ini文件\n # 因为app。py 已经设置所有资源文件从根目录读取,config的路径直接从根目录写,如果写。。/就报错了\n #因为打包读取不到配置文件,所以读取绝对路径\n # 项目路径\n # # root_dir = os.path.split(os.path.realpath(__file__))[0] # exe 生产C:\\Users\\admin\\AppData\\Local\\Temp\n # root_dir = os.path.dirname(os.path.realpath(sys.argv[0])) #这个可以,直接就读出根目录来\n # # real_root_dir = root_dir[0:-3]\n # real_root_dir = root_dir\n # print(f'项目路径为=={root_dir}')\n # print(f'真实项目路径为=={real_root_dir}')\n # print(f'项目路径为 类型=={type(real_root_dir)}')\n # # config.ini文件路径\n # config_filepath = os.path.join(real_root_dir, 'conf\\config.ini')\n # print(f'配置文件路径为=={config_filepath}')\n #\n # # config.read('../conf/config.ini', encoding='utf-8') # 打包的时候需要这样配置,否则读取不到配置文件\n # config.read(config_filepath, encoding='utf-8')\n\n # config.read('conf/config.ini', encoding='utf-8')\n config.read(relativepath, encoding='utf-8')\n print('配置config sessions', config.sections())\n\n config_dict = dict()\n if config.sections() is not None:\n print('读取到配置文件内容')\n config_dict['db_host'] = config.get('db', 'db_host')\n config_dict['db_user'] = config.get('db', 'db_user')\n config_dict['db_passwd'] = config.get('db', 'db_passwd')\n config_dict['db_dbname'] = config.get('db', 'db_dbname')\n print('db_host=', config_dict['db_host'])\n print('db_user=', config_dict['db_user'])\n print('db_passwd=', config_dict['db_passwd'])\n print('db_dbname=', config_dict['db_dbname'])\n\n # 测试是否能连上数据库\n try:\n conn = pymysql.connect(config_dict['db_host'], config_dict['db_user'], config_dict['db_passwd'], config_dict['db_dbname'])\n\n except:\n # conn.close()\n print('\\033[1;31;40m') # 下一目标输出背景为黑色,颜色红色高亮显示\n print('*' * 50)\n print('\\033[7;31m 已有配置未能连接数据库,请查看数据库配置!\\033[1;31;40m') # 字体颜色红色反白处理\n print('\\033[7;31m 建议:1. 后台输入 (mysql -h域名 -u用户名 -p密码 数据库名称 )查看是否可以连接数据库!\\033[1;31;40m') # 字体颜色红色反白处理\n print(\"\\033[7;31m 2.如果第1步无法成功,只用用户名和密码登录,命令行输入mysql -uroot -psunkaisens (sunkaisens为数据库密码)尝试登录mysql\\033[1;31;40m\") # 字体颜色红色反白处理\n print(\"\\033[7;31m 3.如果第2步无法成功,进行数据库授权 grant all privileges on *.* to 'root'@'%' identified by 'sunkaisens'; 然后flush privileges\\033[1;31;40m\") # 字体颜色红色反白处理\n print('\\033[7;31m 4.如果第3步成功,进行数据库重启操作(一般linux和windows的数据库授权完了不需要重启,但是部分windows电脑授权完毕后需要重启mysql),详见用户手册\\033[1;31;40m') # 字体颜色红色反白处理\n print('*' * 50)\n print('\\033[0m')\n\n\n return config_dict\n\n\n# 绝对路径读取配置文件中数据库 参数\ndef get_dbargs_from_config_byabspath():\n print('前端 读取配置db内容,以 jsonStr 键值对格式 返回')\n\n # 实例化configParser对象\n config = configparser.ConfigParser()\n\n # -从根目录read读取配置文件\n # 项目路径\n # # root_dir = os.path.split(os.path.realpath(__file__))[0] # exe 生产C:\\Users\\admin\\AppData\\Local\\Temp\n # root_dir = os.path.dirname(os.path.realpath(sys.argv[0])) #这个可以,直接就读出根目录来\n # # real_root_dir = root_dir[0:-3]\n # real_root_dir = root_dir\n # print(f'项目路径为=={root_dir}')\n # print(f'真实项目路径为=={real_root_dir}')\n # print(f'项目路径为 类型=={type(real_root_dir)}')\n # # config.ini文件路径\n # config_filepath = os.path.join(real_root_dir, 'conf\\config.ini')\n # print(f'配置文件路径为=={config_filepath}')\n #\n # # config.read('../conf/config.ini', encoding='utf-8') # 打包的时候需要这样配置,否则读取不到配置文件\n # config.read(config_filepath, encoding='utf-8')\n\n # currentpath = os.path.abspath(__file__)\n currentpath = os.path.dirname(__file__)\n # print('当前路径(绝对方法///////////))', currentpath)\n # root_dir = os.path.abspath(os.path.dirname(currentpath) + os.path.sep + \"..\")\n # root_dir = os.path.dirname(os.path.dirname(__file__))\n print('根目录(绝对方法/////////////) ===', rootdir) # 使用全局变量\n config_abspath = os.path.join(rootdir, 'conf\\config.ini')\n print('配置文件绝对路径=', config_abspath)\n # 读取配置文件\n config.read(config_abspath, encoding='utf-8')\n print('配置config sessions', config.sections())\n\n config_dict = dict()\n if config.sections() is not None:\n print('读取到的配置文件内容============')\n config_dict['db_host'] = config.get('db', 'db_host')\n config_dict['db_user'] = config.get('db', 'db_user')\n config_dict['db_passwd'] = config.get('db', 'db_passwd')\n config_dict['db_dbname'] = config.get('db', 'db_dbname')\n print('db_host=', config_dict['db_host'])\n print('db_user=', config_dict['db_user'])\n print('db_passwd=', config_dict['db_passwd'])\n print('db_dbname=', config_dict['db_dbname'])\n print('读取到的配置文件内容============')\n # 测试是否能连上数据库\n try:\n conn = pymysql.connect(config_dict['db_host'], config_dict['db_user'], config_dict['db_passwd'], config_dict['db_dbname'])\n\n except:\n # conn.close()\n print('\\033[1;31;40m') # 下一目标输出背景为黑色,颜色红色高亮显示\n print('*' * 50)\n print('\\033[7;31m 已有配置未能连接数据库,请查看数据库配置!\\033[1;31;40m') # 字体颜色红色反白处理\n print('\\033[7;31m 建议:1. 后台输入 (mysql -h域名 -u用户名 -p密码 数据库名称 )查看是否可以连接数据库!\\033[1;31;40m') # 字体颜色红色反白处理\n print(\"\\033[7;31m 2.如果第1步无法成功,只用用户名和密码登录,命令行输入mysql -uroot -psunkaisens (sunkaisens为数据库密码)尝试登录mysql\\033[1;31;40m\") # 字体颜色红色反白处理\n print(\"\\033[7;31m 3.如果第2步无法成功,进行数据库授权 grant all privileges on *.* to 'root'@'%' identified by 'sunkaisens'; 然后flush privileges\\033[1;31;40m\") # 字体颜色红色反白处理\n print('\\033[7;31m 4.如果第3步成功,进行数据库重启操作(一般linux和windows的数据库授权完了不需要重启,但是部分windows电脑授权完毕后需要重启mysql),详见用户手册\\033[1;31;40m') # 字体颜色红色反白处理\n print('*' * 50)\n print('\\033[0m')\n\n\n return config_dict\n\n\n# 读取 所有 配置文件 键值对\ndef get_allargs_from_config():\n print('读取配置文件所有内容,以 dict 字典返回')\n # 默认定义数据\n code = 500 # 默认失败\n msg = '读取配置文件失败'\n count = 0 # 结果个数\n data = {}\n config_data_arr = [] # json data数据里填充的键值对\n\n # 实例化configParser对象\n config = configparser.ConfigParser()\n\n # -read读取ini文件\n config.read('conf/config.ini', encoding='utf-8')\n print('配置config sessions', config.sections())\n\n config_dict = dict()\n if config.sections() is not None:\n print('读取到配置文件内容')\n config_dict['db_host'] = config.get('db', 'db_host')\n config_dict['db_user'] = config.get('db', 'db_user')\n config_dict['db_passwd'] = config.get('db', 'db_passwd')\n config_dict['db_dbname'] = config.get('db', 'db_dbname')\n config_dict['testlink_quick_link'] = config.get('quick_links', 'testlink_quick_link')\n config_dict['redmine_quick_link'] = config.get('quick_links', 'redmine_quick_link')\n config_dict['oa_quick_link'] = config.get('quick_links', 'oa_quick_link')\n config_dict['enterprise_email_quick_link'] = config.get('quick_links', 'enterprise_email_quick_link')\n\n #顺利读取完毕,默认读取成功\n code = 200\n msg = \"配置文件读取成功\"\n count = len(config_dict)\n config_data_arr.append(config_dict)\n\n for i in config_dict:\n print(i)\n\n # 返回json格式的数据\n data['code'] = code\n data['msg'] = msg\n data['count'] = count\n data['data'] = config_data_arr\n # 转化下查询结果为{},{},{}这种格式======================\n # print(' 搜索用户方法 type(data)== ', type(data))\n # print(' 搜索用户方法 type== ', data)\n # json.dumps()用于将dict类型的数据转成str .json.loads():用于将str类型的数据转成dict\n json_str = json.dumps(data, ensure_ascii=False)\n print('读取全部配置文件 -->jsonStr== ', json_str)\n\n return json_str\n\n\n# 读取 所有 配置文件 键值对 -暂时没用这个方法\ndef get_allargs_from_config_nouse():\n print('读取配置文件所有内容,以list返回')\n # 实例化configParser对象\n config = configparser.ConfigParser()\n\n # -read读取ini文件\n config.read('../conf/config.ini', encoding='utf-8')\n\n # 首先得到配置文件的所有分组,然后根据分组逐一展示所有\n config_key_value_list = list()\n for sections in config.sections():\n for items in config.items(sections):\n print(items)\n config_key_value_list.append(items)\n\n print('读取配置文件所有内容, 返回类型==', type(config_key_value_list))\n return config_key_value_list\n\n\n# 获取一段时间内的,一定颗粒度(时间差)的日期 集合list\n# 获取的间隔是 ['2020-01-01', '2020-01-07', '2020-01-14'] 时间间隔是6的\n# date_diffrent_str 7的倍数\ndef get_bug_submit_date_list(starttime_str, endtime_str, date_diffrent_str):\n\n print('开始时间', starttime_str)\n start_time = datetime.datetime.strptime(starttime_str, '%Y-%m-%d')\n end_time = datetime.datetime.strptime(endtime_str, '%Y-%m-%d')\n print('???????????????????????????????type date-dic==', type(date_diffrent_str))\n date_diffrent_int = int(date_diffrent_str)\n print('???????????????????????????????type date-dic==', date_diffrent_str)\n # delta = datetime.timedelta(days= time_diffrent_int -1) # 时间差 eg.2020-01-01 + 时间差 = 2020-01-07(一周的日期)\n\n datesub = (end_time - start_time).days +1 # 起始 终止时间相减\n print('时间间隔,=', datesub)\n\n fortimes = datesub // date_diffrent_int\n # print('循环了多少次', fortimes)\n\n # 取余>=0 endTime = endtime_x 都= endtime,如果mod >0 多算一段时间 mod=0 不用多算一段时间\n # if datesub % dateDiffrent = 0:\n # pass\n date_submit_date = list()\n date_submit_date.append(starttime_str)\n\n for i in range(0, fortimes): # 包左不包右\n # 是起始时间就不 -1\n # 是终止时间就 替换从endtime_x\n # print(f'当前第{i}次循环')\n\n delta = datetime.timedelta(days=date_diffrent_int * (i + 1) - 1)\n bug_submit_time_str = datetime.datetime.strftime((start_time + delta), '%Y-%m-%d')\n date_submit_date.append(bug_submit_time_str)\n # print(date_submit_date)\n\n if datesub % date_diffrent_int >0:\n date_submit_date.append(endtime_str)\n\n print('这段时间内的时间应该是', date_submit_date)\n return date_submit_date # list\n\n\n# 获取一段时间内的,一定颗粒度(时间差)的日期 集合list\n# 获取的间隔是 ['2020-01-01', '2020-01-08', '2020-01-15'] 时间间隔是6的,方便sql语句计算 >=time1 < tim2 ;>=time2 =0 endTime = endtime_x 都= endtime,如果mod >0 多算一段时间 mod=0 不用多算一段时间\n # if datesub % dateDiffrent = 0:\n # pass\n date_submit_date = list()\n date_submit_date.append(starttime_str)\n\n # endtime +1\n delta_oneday = datetime.timedelta(days=1)\n endtime_str = datetime.datetime.strftime((end_time + delta_oneday), '%Y-%m-%d')\n\n for i in range(0, fortimes): # 包左不包右\n # 是起始时间就不 -1\n # 是终止时间就 替换从endtime_x\n # print(f'当前第{i}次循环')\n\n delta = datetime.timedelta(days=date_diffrent_int * (i + 1))\n bug_submit_time_str = datetime.datetime.strftime((start_time + delta), '%Y-%m-%d')\n date_submit_date.append(bug_submit_time_str)\n # print(date_submit_date)\n\n if datesub % date_diffrent_int > 0:\n date_submit_date.append(endtime_str)\n\n print('这段时间内的时间应该是', date_submit_date)\n return date_submit_date # list\n\n\n\n# 写入excel文件\n\"\"\"\n功能:写入excel文件\n参数:path : excel文件的输出路径,结尾必须带上文件后缀,基于项目根目录的路径。如 根目录是“D:” excelrelapath = \"test1.xlsx\" ->最前面不用加\\\\\n注意:1. excel文件名不存在会自动创建\n 2. excel文件上级文件夹,如果不存在,不会自动创建\n\"\"\"\ndef wirte_file(excelrelpath):\n \"\"\"\n # xlwt方式创建workbook\n # 创建sheet\n # sheet中写入数据\n # 保存excel\n book = xlwt.Workbook(encoding='utf-8')\n sheet1 = book.add_sheet(u'Sheet1', cell_overwrite_ok=True)\n sheet1.write(0, 0, 'haha')\n book.save('D:\\\\test1.xls') # 需要写2个\\\\ xlsx 不支持xlsx格式文件\n \"\"\"\n # XlsxWriter方式创建workbook\n excelabspath = rootdir + \"\\\\\" + excelrelpath\n print(\"excel文件绝对路径\", excelabspath)\n book = xlsxwriter.Workbook(excelabspath)\n # book = xlsxwriter.Workbook(\"D:\\\\test1.xlsx\") # 必须使用双\\\\ 否则报参数错误\n\n # 创建sheet\n sheet1 = book.add_worksheet(\"Sheet1\")\n # sheet中写入数据\n sheet1.write(0, 0, \"ssss\")\n sheet1.write(0, 1, \"ssss\")\n # 关闭workbook\n book.close()\n\n\n# 功能:判读是否是日期格式\n# 参数:1.传入的字符串 2. 日期格式字符串,如:\"%Y-%m-%d\" ?带秒的如何表示? %H:%M:%M 格式不对!\ndef is_valid_date(str, dataformat=\"%Y-%m-%d\"):\n '''判断是否是一个有效的日期字符串'''\n try:\n time.strptime(str, dataformat)\n return True\n except:\n return False\n\n\n# 功能:检查文件是否存在\n# 返回值:True /False\ndef checkfile_exist(filepath):\n isfile_exists = os.path.exists(filepath)\n return isfile_exists\n\n\n# 功能:打开一个excel,返回workbook\n# 参数:1.filepath 文件路径\n# 返回值:workbook\n# 注意:使用时,记得关book.close()\ndef openexcel_return_workbook(filepath):\n workbook = xlrd.open_workbook(filepath)\n return workbook\n\n# 功能:获取显示的表格,(如果有workbook对象,直接用;没有workbook,读取filepath获取workbook)\n# 返回值:list类型的 表格名称str\ndef get_excel_show_sheetnames(filepath, *workbook):\n # 0. 判断是否直接传了workbook对象\n starttime = datetime.datetime.now()\n if len(workbook) == 0: # 没有传workbook对象,读取路径\n print('没有传workbook对象')\n book = xlrd.open_workbook(filepath)\n else:\n book = workbook\n print('book==', book)\n print(book.sheet_names())\n\n\n show_sheetnames = list()\n sheetnames = book.sheet_names() # list\n for sheetname in sheetnames:\n sheet = book.sheet_by_name(sheetname)\n if sheet.visibility == 0:\n show_sheetnames.append(sheet.name)\n print('excel显示的sheet有(list)', show_sheetnames)\n # print(type(show_sheetnames))\n # book.close() # xlsxwriter才需要close()方法, xlrd不需要\n\n endtime = datetime.datetime.now()\n print('耗时', (endtime - starttime).seconds)\n return show_sheetnames\n\n\n# 功能:获取隐藏的表格\ndef get_excel_hide_sheetnames(filepath):\n hide_sheetnames = list()\n\n book = xlrd.open_workbook(filepath)\n sheetnames = book.sheet_names()\n for sheetname in sheetnames:\n sheet = book.sheet_by_name(sheetname)\n if sheet.visibility == 1:\n hide_sheetnames.append(sheet.name)\n print('excel隐藏的sheet有(list)', hide_sheetnames)\n # book.close() # xlsxwriter才需要close()方法, xlrd不需要\n return hide_sheetnames\n\n\n# 功能:检查表头是否合法\n# 参数:1. 文件路径\n# 2.sheetnames(list/tuple) 只要是链表形式的都可以\n# 3.表头字符串(list/tuple)只要是链表形式的都可以\ndef check_excel_tablehead(filepath, sheetnames, tablehead):\n book = xlrd.open_workbook(filepath)\n # 表头\n tablehead_list = []\n for sheetname in sheetnames: # 循环每一个sheet\n sheet = book.sheet_by_name(sheetname)\n\n for i in range(0, len(tablehead)-1): # 循环每一列\n excel_th_value = sheet.cell(0, i).value\n print(\"表头内容=\", excel_th_value)\n print(\"==========\")\n\n\n# 功能:判断一个字符串是否是日期类型\ndef is_legal_date(strdate):\n try:\n if \":\" in strdate:\n datetime.datetime.strptime(strdate, \"%Y/%m/%d %H:%M:%S\")\n else:\n datetime.datetime.strptime(strdate, \"%Y/%m/%d\")\n return True\n except:\n return False\n\n\n# 功能:检测excel表格数据是否符合要求\n# 参数:1. 文件路径\n# 2. 模板里的表头数据 (tuple/list)只要是链表格式即可\n\n# 返回结果: json,因为要给用户提示\n# True:全部符合要求\n# False:不符合要求\ndef checkexcel_data(filepath, tablehead):\n # 一、 初始化json数据\n data = {}\n tips = [] # 提示信息\n code = 500 # 默认失败\n msg = '文件不存在'\n count = 0 # sql语句执行结果个数\n\n starttime = datetime.datetime.now()\n # 二、 检测内容\n is_tablehead_legal = False # 初始化flag,表头是否合法\n is_index_none_legal = False # 初始化flag,索引是否为空\n is_index_repeat = False # 索引是否重复\n is_requiredcol_notnone = False # 必填项是否非空\n is_requiredcol_format_right = False # 必填项格式是否正确\n is_requiredcol_len_right = False # 必填项长度是否正确\n is_not_requiredcol_format_right = False # 非必填项格式是否正确\n is_not_requiredcol_len_right = False # 非必填项长度是否正确\n is_other_error = False # 检测其他异常\n # ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error # 单元格类型\n\n # 1. 检查文件是否存在\n isfile_exists = checkfile_exist(filepath)\n\n # 2. 检查每个表格(显示表格)表头是否合法\n if isfile_exists == True:\n # 1)初始化\n book = xlrd.open_workbook(filepath) # 获取book\n sheetnames = book.sheet_names() # 显示的sheet\n\n # 2)获取未隐藏sheetnames\n show_sheetnames = list()\n for sheetname in sheetnames:\n sheet = book.sheet_by_name(sheetname)\n if sheet.visibility == 0:\n show_sheetnames.append(sheet.name)\n print('excel显示的sheet有(list)', show_sheetnames)\n\n # 3)比较每个 显示的sheet 表头\n # for show_sheetname in show_sheetnames: # 循环每一个sheet\n error_sheetnames = list() # 错误sheet数组\n error_rows = list() # 错误行数组\n error_cols = list() # 错误列数组\n for show_sheetname in show_sheetnames: # 循环每一个sheet\n sheet = book.sheet_by_name(show_sheetname)\n # print('当前sheetname==', show_sheetname)\n # 表头列必须 >= 模板表头\n # print('--------------------ncols', sheet.ncols)\n if sheet.ncols < len(tablehead): # ncols 从0开始\n error_sheetnames.append(show_sheetname)\n msg = '检测到上传文件表头“少于”模板表头,请检查上传文件。问题表格是:' + str(error_sheetnames)\n else: # 循环每一列,比较与模板表头字符是否一致\n for i in range(0, len(tablehead)): # range包左不包右\n # print('iiiiiiiiiiiiii=', i)\n # print(sheet.cell_value(0, i))\n importexcel_th_value = sheet.cell(0, i).value\n if importexcel_th_value != tablehead[i]:\n error_sheetnames.append(show_sheetname)\n msg = \"检测到上传文件表头与模板不符,请检查上传文件。问题表格为\" + str(error_sheetnames)\n print(msg)\n # break # 检测所有的sheet,执行完循环\n if len(error_sheetnames) == 0:\n is_tablehead_legal = True # 更改标志位\n\n # print('---------------表头是否合法=', is_tablehead_legal)\n # 3. 检查每个表索引是否有空\n if is_tablehead_legal == True:\n for show_sheetname in show_sheetnames: # 循环每一个sheet\n sheet = book.sheet_by_name(show_sheetname)\n # 检查每一行索引是否为空\n for i in range(1, sheet.nrows):\n if sheet.cell_value(i, 18) is None or sheet.cell_value(i, 18) == '':\n error_sheetnames.append(show_sheetname)\n msg = \"检测到索引列存在空单元格,请检查上传文件。问题表格为\" + str(error_sheetnames)\n break # 跳出表内循环\n if len(error_sheetnames) == 0:\n is_index_none_legal = True\n print('---------------索引是否合法=', is_index_none_legal)\n\n # 4. 检查每个表索引是否重复\n if is_index_none_legal == True:\n for show_sheetname in show_sheetnames:\n sheet = book.sheet_by_name(show_sheetname)\n # 检查索引是否有重复\n indexlist = list()\n for i in range(1, sheet.nrows):\n indexlist.append(sheet.cell_value(i, 18))\n\n indexlistset = set(indexlist) # 去重列表\n # print('-------------', str(indexlist))\n # print('-------------', str(indexlistset))\n if len(indexlistset) != len(indexlist):\n error_sheetnames.append(show_sheetname)\n error_rows.append(i+1)\n msg = \"检测到索引列存在重复项,请检查上传文件。问题表格为\" + str(error_sheetnames) + ', 行数为:' + str(error_rows)\n if len(error_sheetnames) == 0:\n is_index_repeat = True\n print('---------------检测索引是否重复结果=', is_index_repeat)\n\n # 5. 检查每个表必填项是否有空(必填项:原则上标识应是必填项) 提交日期(col:0)-上传可以不带,减轻用户操作excel表 描述(col:4) 提交者索引(col:18)\n if is_index_repeat == True:\n for show_sheetname in show_sheetnames:\n sheet = book.sheet_by_name(show_sheetname)\n # print('当前sheetname==', show_sheetname)\n\n # 检查每一行索引是否为空\n for i in range(1, sheet.nrows):\n if sheet.cell_value(i, 18) == '':\n error_sheetnames.append(show_sheetname)\n msg = \"检测到‘必填列(提交者索引)’存在空单元格,请检查上传文件。问题表格为\" + str(error_sheetnames)\n break # 跳出表内循环\n if len(error_sheetnames) == 0:\n is_requiredcol_notnone = True\n print('---------------必填项是否非空=', is_requiredcol_notnone)\n\n # 6. 检查每个表必填项 格式是否正确\n if is_requiredcol_notnone == True:\n is_requiredcol_format_right = True\n\n # 7. 检查每个表必填项 长度是否超出范围\n if is_requiredcol_format_right == True:\n for show_sheetname in show_sheetnames:\n sheet = book.sheet_by_name(show_sheetname)\n # print('当前sheetname==', show_sheetname)\n\n # 检查每一行 索引是否 长度是否超出范围80字符\n for i in range(1, sheet.nrows):\n error_rows_onesheet = list()\n if len(sheet.cell_value(i, 18)) > 80:\n error_sheetnames.append(show_sheetname)\n error_rows_onesheet.append(i+1)\n error_rows.append(error_rows_onesheet)\n msg = \"检测到'提交者索引’列长度过长,请检查上传文件。问题表格为\" + str(error_sheetnames) + \" ,对应行:\" + str(error_rows)\n break # 跳出表内循环\n if len(error_sheetnames) == 0:\n is_requiredcol_len_right = True\n print('---------------必填项是否非空=', is_requiredcol_len_right)\n\n # 8. 检查每个表非必填项 格式是否正确\n if is_requiredcol_len_right == True:\n for show_sheetname in show_sheetnames:\n sheet = book.sheet_by_name(show_sheetname)\n print('当前sheetname==', show_sheetname)\n # print(\"type=\", type(show_sheetname)) # str\n\n # 遍历每一行\n print('检查每个表非必填项 格式是否正确')\n for row in range(1, sheet.nrows):\n error_cols_onesheet = list()\n # print('======读出的excel日期类型==', sheet.cell_value(row, 17))\n # print('======读出的excel日期类型==', sheet.cell(row, 17).ctype)\n # ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error\n if sheet.cell(row, 0).ctype != 0 and sheet.cell(row, 0).ctype != 3: # 提交日期 空或者日期类型\n print('进入日期判断=============')\n if sheet.cell(row, 0).ctype == 1: # string类型 , 去除前后空额,再判断是否是正确日期类型\n cellvalue = str(sheet.cell_value(row, 0)).strip()\n if is_legal_date(cellvalue) == False:\n error_cols_onesheet.append('0-提交日期,行数:' + str(row+1))\n if sheet.cell(row, 5).ctype != 0 and sheet.cell(row, 5).ctype != 2: # 严重等级\n # error_cols_onesheet.append('第6列(严重等级,应是数值或者空)')\n error_cols_onesheet.append('6.严重等级')\n if sheet.cell(row, 6).ctype != 0 and sheet.cell(row, 6).ctype != 2: # 优先级\n # error_cols_onesheet.append('第7列(优先级,应是数值或者空)')\n error_cols_onesheet.append('7-优先级')\n if sheet.cell(row, 7).ctype != 0 and sheet.cell(row, 7).ctype != 2: # 难度\n # error_cols_onesheet.append('第8列(难度,应是数值或者空)')\n error_cols_onesheet.append('8-难度')\n if sheet.cell(row, 9).ctype != 0 and sheet.cell(row, 9).ctype != 3: # 关闭日期 2-number\n # error_cols_onesheet.append('第10列(关闭日期,应是日期类型xxxx/xx/xx或者空)')\n # 是字符串的情况下,去除前后空格,然后判断是否是日期类型\n print(f'====9列==第及行{row+1} ', sheet.cell(row, 9).value, '前后可能有空格')\n if sheet.cell(row, 9).ctype == 1: # string类型 , 去除前后空额,再判断是否是正确日期类型\n cellvalue = str(sheet.cell_value(row, 9)).strip()\n if is_legal_date(cellvalue) == False:\n error_cols_onesheet.append('10-关闭日期,行数:' + str(row+1))\n if sheet.cell(row, 16).ctype != 0 and sheet.cell(row, 16).ctype != 2: # 回归次数\n # error_cols_onesheet.append('第17列(回归次数,应是数值或者空)')\n error_cols_onesheet.append('17-回归次数')\n if sheet.cell(row, 17).ctype != 0 and sheet.cell(row, 17).ctype != 2: # 重开次数\n # error_cols_onesheet.append('第18列(重开次数,应是数值或者空)')\n error_cols_onesheet.append('18-重开次数')\n if len(error_cols_onesheet) > 0:\n error_sheetnames.append(show_sheetname)\n error_cols.append(error_cols_onesheet)\n break # 跳出行循环\n\n if len(error_sheetnames) > 0:\n # msg = \"检测到‘部分非必填列(提交日期(日期:xxxx/xx/xx)、严重等级(数字)、优先级(数字)、难度(数字)、关闭日期(日期:xxxx/xx/xx)、回归次数(数字)、重开次数(数字)’格式错误,请检查上传文件。问题表格为\" + str(error_sheetnames) + ', 对应列:' + str(error_cols)\n msg = \"检测到格式错误,请检查上传文件。问题表格为\" + str(error_sheetnames) + ', 对应列:' + str(error_cols) + ' \\n正确格式:时间(xxxx/xx/xx); 严重等级、优先级、难度、重开次数、回归次数都是数字'\n if len(error_sheetnames) == 0:\n is_not_requiredcol_format_right = True\n print('---------------非必填���格式是否正确=', is_not_requiredcol_format_right)\n\n # 9. 检查每个表非必填项 长度是否超出范围\n if is_not_requiredcol_format_right == True:\n pass\n for show_sheetname in show_sheetnames:\n sheet = book.sheet_by_name(show_sheetname)\n print('当前sheetname==', show_sheetname)\n\n # 遍历每一行\n for row in range(1, sheet.nrows):\n error_cols_onesheet = list()\n # print('======读出的excel日期类型==', sheet.cell_value(row, 10), row+1)\n # print('======读出的excel日期类型==', sheet.cell(row, 0).ctype)\n\n # ???为什么封装成str,因为用户不一定传什么数据类型给你\n if len(str(sheet.cell_value(row, 1))) > 256: # 项目256 第2列\n error_cols_onesheet.append('2.项目,行数:' + str(row))\n if len(str(sheet.cell_value(row, 2))) > 256: # 项目256 第3列\n error_cols_onesheet.append('3.软件类,行数:' + str(row))\n if len(str(sheet.cell_value(row, 3))) > 256: # 项目256 第4列\n error_cols_onesheet.append('4.测试版本,行数:' + str(row))\n if len(str(sheet.cell_value(row, 4))) > 6144: # 项目256 第5列\n error_cols_onesheet.append('5.描述,行数:' + str(row))\n if len(str(sheet.cell_value(row, 5))) > 11: # 项目256 第6列\n error_cols_onesheet.append('6.严重等级,行数:' + str(row))\n if len(str(sheet.cell_value(row, 6))) > 11: # 项目256 第7列\n error_cols_onesheet.append('7.优先级,行数:' + str(row))\n if len(str(sheet.cell_value(row, 7))) > 11: # 项目256 第8列\n error_cols_onesheet.append('8.难度,行数:' + str(row))\n if len(str(sheet.cell_value(row, 8))) > 11: # 项目256 第9列\n error_cols_onesheet.append('9.关闭情况,行数:' + str(row))\n if len(str(sheet.cell_value(row, 10))) > 256: # 项目256 第11列\n error_cols_onesheet.append('11.关闭版本,行数:' + str(row))\n if len(str(sheet.cell_value(row, 11))) > 3072: # 项目256 第12列\n error_cols_onesheet.append('12.原因分析,行数:' + str(row))\n if len(str(sheet.cell_value(row, 12))) > 1024: # 项目256 第13列\n error_cols_onesheet.append('13.问题图片,行数:' + str(row))\n if len(str(sheet.cell_value(row, 13))) > 1024: # 项目256 第14列\n error_cols_onesheet.append('14.中间情况,行数:' + str(row))\n if len(str(sheet.cell_value(row, 14))) > 256: # 项目256 第15列\n error_cols_onesheet.append('15.开发者,行数:' + str(row))\n if len(str(sheet.cell_value(row, 15))) > 1024: # 项目256 第16列\n error_cols_onesheet.append('16.备注,行数:' + str(row))\n if len(str(sheet.cell_value(row, 16))) > 11: # 项目256 第17列\n error_cols_onesheet.append('17.回归次数,行数:' + str(row))\n if len(str(sheet.cell_value(row, 17))) > 11: # 项目256 第18列\n error_cols_onesheet.append('18.重开次数,行数:' + str(row))\n if len(str(sheet.cell_value(row, 18))) > 80: # 项目256 第19列\n error_cols_onesheet.append('19.提交者索引,行数:' + str(row))\n\n if len(error_cols_onesheet) > 0:\n error_sheetnames.append(show_sheetname)\n error_cols.append(error_cols_onesheet)\n break # 跳出行循环\n\n if len(error_sheetnames) > 0:\n msg = \"检测到单元格长度过长,请检查上传文件。问题表格为\" + str(error_sheetnames) + ', 对应列:' + str(error_cols)\n if len(error_sheetnames) == 0:\n is_not_requiredcol_len_right = True\n print('---------------非必填项 长度是否正常=', is_not_requiredcol_len_right)\n # 10. 检查其他异常错误处理-直接报错(判断日期是否有效)\n\n endtime = datetime.datetime.now()\n print('耗时', (endtime - starttime).seconds, '秒')\n\n if is_not_requiredcol_len_right == True:\n code = 200\n msg = '上传文件正常'\n\n # N.返回json格式的数据\n data['code'] = code\n data['msg'] = msg\n data['count'] = count\n data['data'] = tips\n # 转化下查询结果为{},{},{}这种格式======================\n json_str = json.dumps(data, ensure_ascii=False)\n print('dbutil==jsonStr=====', json_str)\n return json_str\n\n\n\n","sub_path":"py/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":36326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"18770766","text":"import os\r\nimport struct\r\nimport subprocess\r\nimport sys\r\nimport time\r\n\r\nimport sharedstructures\r\n\r\nPOOL_NAME_PREFIX = \"HashTableTest-py-pool-\"\r\nALLOCATOR_TYPES = ('simple', 'logarithmic')\r\n\r\n\r\ndef get_current_process_lsof():\r\n return subprocess.check_output(['lsof', '-p', str(os.getpid())])\r\n\r\n\r\ndef expect_key_missing(table, k):\r\n try:\r\n table[k]\r\n assert False, 'table[%r] didn\\'t raise' % k\r\n except KeyError:\r\n pass\r\n\r\n\r\ndef verify_state(expected, table):\r\n assert len(expected) == len(table)\r\n for k, v in expected.items():\r\n assert table[k] == v\r\n for k, v in table.items():\r\n assert expected[k] == v\r\n verify_allocator(table)\r\n\r\n\r\ndef verify_allocator(table):\r\n ret = table.verify()\r\n assert ret is None, ret.decode('utf-8')\r\n\r\n\r\ndef run_basic_test(allocator_type):\r\n print(\"-- [%s] basic\" % allocator_type)\r\n before_lsof_count = len(get_current_process_lsof().splitlines())\r\n\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type)\r\n expected = {}\r\n\r\n def insert_both(e, t, k, v):\r\n t[k] = v\r\n e[k] = v\r\n\r\n def delete_both(e, t, k):\r\n del t[k]\r\n del e[k]\r\n\r\n verify_state(expected, table)\r\n insert_both(expected, table, b'key1', b'value1')\r\n verify_state(expected, table)\r\n insert_both(expected, table, b'key2', b'value2')\r\n verify_state(expected, table)\r\n insert_both(expected, table, b'key3', b'value3')\r\n verify_state(expected, table)\r\n\r\n delete_both(expected, table, b'key2')\r\n verify_state(expected, table)\r\n try:\r\n del table[b'key2']\r\n assert False, \"del table[\\'key2\\'] did not raise KeyError\"\r\n except KeyError:\r\n pass\r\n verify_state(expected, table)\r\n\r\n insert_both(expected, table, b'key1', b'value0')\r\n verify_state(expected, table)\r\n delete_both(expected, table, b'key1')\r\n verify_state(expected, table)\r\n delete_both(expected, table, b'key3')\r\n verify_state(expected, table)\r\n\r\n assert {} == expected\r\n\r\n del table # this should unmap the shared memory pool and close the fd\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n\r\n # this will fail if the test prints anything after before_lsof is taken since\r\n # the stdout/stderr offsets will be different\r\n assert before_lsof_count == len(get_current_process_lsof().splitlines())\r\n\r\n\r\ndef run_conditional_writes_test(allocator_type):\r\n print(\"-- [%s] conditional writes\" % allocator_type)\r\n\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type)\r\n expected = {}\r\n\r\n def insert_both(e, t, k, v):\r\n t[k] = v\r\n e[k] = v\r\n\r\n def delete_both(e, t, k):\r\n del t[k]\r\n del e[k]\r\n\r\n def conditional_insert_both(e, t, check_k, check_v, target_k, target_v,\r\n written):\r\n if t.check_and_set(check_k, check_v, target_k, target_v):\r\n e[target_k] = target_v\r\n assert written\r\n else:\r\n assert not written\r\n\r\n def conditional_missing_insert_both(e, t, check_k, target_k, target_v,\r\n written):\r\n if t.check_missing_and_set(check_k, target_k, target_v):\r\n e[target_k] = target_v\r\n assert written\r\n else:\r\n assert not written\r\n\r\n def conditional_delete_both(e, t, check_k, check_v, target_k, written):\r\n if t.check_and_set(check_k, check_v, target_k):\r\n del e[target_k]\r\n assert written\r\n else:\r\n assert not written\r\n\r\n def conditional_missing_delete_both(e, t, check_k, target_k, written):\r\n if t.check_missing_and_set(check_k, target_k):\r\n del e[target_k]\r\n assert written\r\n else:\r\n assert not written\r\n\r\n verify_state(expected, table)\r\n\r\n insert_both(expected, table, b\"key1\", b\"value1\")\r\n verify_state(expected, table)\r\n insert_both(expected, table, b\"key2\", b\"value2\")\r\n verify_state(expected, table)\r\n\r\n # check that conditions on the same key work\r\n conditional_insert_both(expected, table, b\"key1\", b\"value2\", b\"key1\",\r\n b\"value1_1\", False)\r\n verify_state(expected, table)\r\n conditional_insert_both(expected, table, b\"key1\", b\"value1\", b\"key1\",\r\n b\"value1_1\", True)\r\n verify_state(expected, table)\r\n\r\n # check that conditions on other keys work\r\n conditional_insert_both(expected, table, b\"key2\", b\"value1\", b\"key1\",\r\n b\"value1\", False)\r\n verify_state(expected, table)\r\n conditional_insert_both(expected, table, b\"key2\", b\"value2\", b\"key1\",\r\n b\"value1\", True)\r\n verify_state(expected, table)\r\n\r\n # check that missing conditions work\r\n conditional_missing_insert_both(expected, table, b\"key2\", b\"key3\", b\"value3\",\r\n False)\r\n verify_state(expected, table)\r\n conditional_missing_insert_both(expected, table, b\"key3\", b\"key3\", b\"value3\",\r\n True)\r\n verify_state(expected, table)\r\n\r\n # check that conditional deletes work\r\n conditional_delete_both(expected, table, b\"key1\", b\"value2\", b\"key1\", False)\r\n verify_state(expected, table)\r\n conditional_delete_both(expected, table, b\"key1\", b\"value1\", b\"key1\", True)\r\n verify_state(expected, table)\r\n\r\n conditional_missing_delete_both(expected, table, b\"key3\", b\"key2\", False)\r\n verify_state(expected, table)\r\n conditional_missing_delete_both(expected, table, b\"key1\", b\"key2\", True)\r\n verify_state(expected, table)\r\n\r\n delete_both(expected, table, b\"key3\")\r\n\r\n assert expected == {}\r\n\r\n\r\ndef run_collision_test(allocator_type):\r\n print(\"-- [%s] collision\" % allocator_type)\r\n\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type, 0, 2)\r\n expected = {}\r\n\r\n def insert_both(e, t, k, v):\r\n t[k] = v\r\n e[k] = v\r\n\r\n def delete_both(e, t, k):\r\n del t[k]\r\n del e[k]\r\n\r\n # writing 5 keys to a 4-slot hashtable forces a collision\r\n assert 2 == table.bits()\r\n assert 0 == len(table)\r\n\r\n insert_both(expected, table, b'key1', b'value1')\r\n insert_both(expected, table, b'key2', b'value2')\r\n insert_both(expected, table, b'key3', b'value3')\r\n insert_both(expected, table, b'key4', b'value4')\r\n insert_both(expected, table, b'key5', b'value5')\r\n verify_state(expected, table)\r\n\r\n while expected:\r\n k, _ = expected.popitem();\r\n del table[k]\r\n verify_state(expected, table)\r\n\r\n\r\ndef run_incr_test(allocator_type):\r\n print('-- [%s] incr' % allocator_type)\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type, 0, 6)\r\n expected = {}\r\n\r\n def insert_both(k, v):\r\n table[k] = v\r\n expected[k] = v\r\n\r\n def delete_both(k):\r\n del table[k]\r\n del expected[k]\r\n\r\n # giving garbage to incr() should cause a TypeError\r\n try:\r\n table.incr(b'missing', b'not a number, lolz')\r\n assert False\r\n except TypeError:\r\n pass\r\n try:\r\n table.incr(b'missing', {'still': 'not', 'a': 'number'})\r\n assert False\r\n except TypeError:\r\n pass\r\n\r\n assert 0 == len(table)\r\n insert_both(b'int8', struct.pack(b'@b', 40))\r\n insert_both(b'int16', struct.pack(b'@h', 4000))\r\n insert_both(b'int32', struct.pack(b'@l', 60000000))\r\n insert_both(b'int64', struct.pack(b'@q', 800000000000000))\r\n insert_both(b'float', struct.pack(b'@f', 10.0))\r\n insert_both(b'double', struct.pack(b'@d', 15.5))\r\n insert_both(b'string', b'7 bytes')\r\n assert 7 == len(table)\r\n\r\n # incr should create the key if it doesn't exist\r\n assert -10 == table.incr(b\"int8-2\", -10)\r\n assert -4000 == table.incr(b\"int16-2\", -4000)\r\n assert -60000000 == table.incr(b\"int32-2\", -60000000)\r\n assert -800000000000000 == table.incr(b\"int64-2\", -800000000000000)\r\n assert -10.0 == table.incr(b\"float-2\", -10.0)\r\n assert -15.5 == table.incr(b\"double-2\", -15.5)\r\n assert 13 == len(table)\r\n\r\n # all the keys should have the values we set, but the keys created by incr\r\n # should all be 64 bits\r\n assert struct.pack(b'@b', 40) == table[b\"int8\"]\r\n assert struct.pack(b'@h', 4000) == table[b\"int16\"]\r\n assert struct.pack(b'@l', 60000000) == table[b\"int32\"]\r\n assert struct.pack(b'@q', 800000000000000) == table[b\"int64\"]\r\n assert struct.pack(b'@f', 10.0) == table[b\"float\"]\r\n assert struct.pack(b'@d', 15.5) == table[b\"double\"]\r\n assert struct.pack(b'@q', -10) == table[b\"int8-2\"]\r\n assert struct.pack(b'@q', -4000) == table[b\"int16-2\"]\r\n assert struct.pack(b'@q', -60000000) == table[b\"int32-2\"]\r\n assert struct.pack(b'@q', -800000000000000) == table[b\"int64-2\"]\r\n assert struct.pack(b'@d', -10.0) == table[b\"float-2\"]\r\n assert struct.pack(b'@d', -15.5) == table[b\"double-2\"]\r\n assert 13 == table.size()\r\n\r\n # incr should return the new value of the key\r\n assert struct.pack(b'@b', 44) == table.incr(b\"int8\", 4)\r\n assert struct.pack(b'@h', 4010) == table.incr(b\"int16\", 10)\r\n assert struct.pack(b'@l', 60000100) == table.incr(b\"int32\", 100)\r\n assert struct.pack(b'@q', 800000000001000) == table.incr(b\"int64\", 1000)\r\n assert struct.pack(b'@f', 30.0) == table.incr(b\"float\", 20.0)\r\n assert struct.pack(b'@d', 25.5) == table.incr(b\"double\", 10.0)\r\n assert struct.pack(b'@q', -14) == table.incr(b\"int8-2\", -4)\r\n assert struct.pack(b'@q', -4010) == table.incr(b\"int16-2\", -10)\r\n assert struct.pack(b'@q', -60000100) == table.incr(b\"int32-2\", -100)\r\n assert struct.pack(b'@q', -800000000001000) == table.incr(b\"int64-2\", -1000)\r\n assert struct.pack(b'@d', -30.0) == table.incr(b\"float-2\", -20.0)\r\n assert struct.pack(b'@d', -25.5) == table.incr(b\"double-2\", -10.0)\r\n assert 13 == table.size()\r\n\r\n # test incr() on keys of the wrong size\r\n try:\r\n table.incr(b\"string\", 14)\r\n assert False\r\n except ValueError:\r\n pass\r\n try:\r\n table.incr(b\"string\", 15.0)\r\n assert False\r\n except ValueError:\r\n pass\r\n\r\n # we're done here\r\n table.clear()\r\n assert len(table) == 0\r\n\r\n\r\n# TODO: deduplicate this with PrefixTreeTest\r\ndef run_concurrent_readers_test(allocator_type):\r\n print('-- [%s] concurrent readers' % allocator_type)\r\n\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type)\r\n del table\r\n\r\n child_pids = set()\r\n while (len(child_pids) < 8) and (0 not in child_pids):\r\n child_pids.add(os.fork())\r\n\r\n if 0 in child_pids:\r\n # child process: try up to a second to get the key\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type)\r\n\r\n value = 100\r\n start_time = int(time.time() * 1000000)\r\n while (value < 110) and \\\r\n (int(time.time() * 1000000) < (start_time + 1000000)):\r\n time.sleep(0.001)\r\n try:\r\n res = table[b'key1']\r\n except KeyError:\r\n pass\r\n else:\r\n if res == value:\r\n print('-- [%s] child %d saw value %d' % (allocator_type, os.getpid(), value))\r\n value += 1\r\n\r\n if int(time.time() * 1000000) >= (start_time + 1000000):\r\n print('-- [%s] child %d timed out' % (allocator_type, os.getpid()))\r\n\r\n os._exit(int(value != 110))\r\n\r\n else:\r\n # parent process: write the key, then wait for children to terminate\r\n table = sharedstructures.HashTable(POOL_NAME_PREFIX + allocator_type, allocator_type)\r\n\r\n for value in range(100, 110):\r\n time.sleep(0.05)\r\n table[b'key1'] = value\r\n\r\n num_failures = 0\r\n while child_pids:\r\n pid, exit_status = os.wait()\r\n child_pids.remove(pid)\r\n if os.WIFEXITED(exit_status) and (os.WEXITSTATUS(exit_status) == 0):\r\n print('-- [%s] child %d terminated successfully' % (\r\n allocator_type, pid))\r\n else:\r\n print('-- [%s] child %d failed (%d)' % (\r\n allocator_type, pid, exit_status))\r\n num_failures += 1\r\n\r\n assert 0 == len(child_pids)\r\n assert 0 == num_failures\r\n\r\n\r\ndef main():\r\n try:\r\n for allocator_type in ALLOCATOR_TYPES:\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n run_basic_test(allocator_type)\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n run_conditional_writes_test(allocator_type)\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n run_collision_test(allocator_type)\r\n # TODO: enable this test again when the python module supports incr\r\n # sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n # run_incr_test(allocator_type)\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n run_concurrent_readers_test(allocator_type)\r\n print('all tests passed')\r\n return 0\r\n\r\n finally:\r\n for allocator_type in ALLOCATOR_TYPES:\r\n sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type)\r\n\r\n\r\nif __name__ == '__main__':\r\n sys.exit(main())\r\n","sub_path":"HashTableTest.py","file_name":"HashTableTest.py","file_ext":"py","file_size_in_byte":12342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357263338","text":"import os\n\nimport qcodes as qc\nfrom qcodes import initialise_or_create_database_at, load_or_create_experiment\n\nfrom opx_cw_readout import *\nfrom qcodes.utils.dataset.doNd import do2d\nfrom configuration import *\n\ndb_name = \"QM_demo_reflectometry.db\" # Database name\nsample_name = \"demo\" # Sample name\nexp_name = \"2d_scan_opx_single_cw\" # Experiment name\n\ndb_file_path = os.path.join(os.getcwd(), db_name)\nqc.config.core.db_location = db_file_path\ninitialise_or_create_database_at(db_file_path)\n\nexperiment = load_or_create_experiment(experiment_name=exp_name, sample_name=sample_name)\n\nopx_single_point = OPXCWReadout(config)\nopx_single_point.f(300.8509e6)\nopx_single_point.t_meas(0.010)\nopx_single_point.amp(1.0)\nopx_single_point.readout_pulse_length(readout_pulse_length)\nfull_data = QMDemodParameters(\n opx_single_point,\n [\"I\", \"Q\", \"R\", \"Phi\"],\n \"Spectrum\",\n names=[\"I\", \"Q\", \"R\", \"Phi\"],\n units=[\"V\", \"V\", \"V\", \"°\"],\n)\nstation = qc.Station()\nstation.add_component(opx_single_point)\ndo2d(\n VP1,\n -0.55,\n -0.85,\n 100,\n 1,\n VP2,\n -0.65,\n -0.9,\n 100,\n 0.0135,\n full_data,\n enter_actions=opx_single_point.run_exp(),\n exit_actions=opx_single_point.halt(),\n show_progress=True,\n)\n","sub_path":"examples-old/external-frameworks/qcodes/demo_2d_scan_opx_single_point_cw.py","file_name":"demo_2d_scan_opx_single_point_cw.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"197023372","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.files.storage\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('photo', '0010_photo_size'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='photo',\n name='photo_small',\n field=models.ImageField(default='', storage=django.core.files.storage.FileSystemStorage(), upload_to=b''),\n preserve_default=False,\n ),\n ]\n","sub_path":"photo/migrations/0011_photo_photo_small.py","file_name":"0011_photo_photo_small.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"276920193","text":"import os\nimport jinja2\nimport webapp2\nfrom google.appengine.api import mail\n\njinja_environment = jinja2.Environment(autoescape=True,\n loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'), encoding='latin-1'))\n\nclass MainPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('inicio.html')\n self.response.out.write(template.render())\n\nclass InicioPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('inicio.html')\n self.response.out.write(template.render())\n\nclass EmpresaPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('empresa.html')\n self.response.out.write(template.render())\n\nclass ServiciosPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('servicios.html')\n self.response.out.write(template.render())\n \nclass ProyectosPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('proyectos.html')\n self.response.out.write(template.render())\n \nclass ContactoPage(webapp2.RequestHandler):\n \n def get(self):\n template = jinja_environment.get_template('contacto.html')\n self.response.out.write(template.render())\n \nclass MailService(webapp2.RequestHandler):\n\n def post(self):\n mailFrom = self.request.get('mailFrom')\n mailMsg = self.request.get('mailMsg')\n if not mail.is_email_valid(mailFrom):\n self.response.write('wrong mail address')\n return\n message=mail.EmailMessage(sender='dennisargeomatica@gmail.com',subject='Mail from website')\n message.to='dbauszus@gmail.com'\n message.body=('Mail from: %s \\n'\n 'Message: %s \\n'\n %(mailFrom,mailMsg))\n message.send()\n message=mail.EmailMessage(sender='dennisargeomatica@gmail.com',subject='Your mail to Argeomatica')\n message.to=mailFrom\n message.body=('Thank you, we have received your mail. \\n'\n 'Message: %s \\n'\n %(mailMsg))\n message.send()\n self.response.write('mail sent')\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n ('/inicio', InicioPage),\n ('/empresa', EmpresaPage),\n ('/contacto', ContactoPage),\n ('/servicios', ServiciosPage),\n ('/proyectos', ProyectosPage),\n ('/mailService', MailService),\n], debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"242664430","text":"def solution(survey, choices):\n maps = {\"R\": 0, \"T\": 0, \"C\": 0, \"F\": 0, \"J\": 0, \"M\": 0, \"A\": 0, \"N\": 0}\n for idx, val in enumerate(choices):\n if val < 4: # 비동의 선택지\n maps_idx = survey[idx][0]\n maps[maps_idx] += (4 - val)\n else: # 동의 선택지\n maps_idx = survey[idx][1]\n maps[maps_idx] += (val - 4)\n answer = \"\"\n \n for x in [\"RT\", \"CF\", \"JM\", \"AN\"]:\n if maps[x[0]] == maps[x[1]]:\n answer += x[0]\n elif maps[x[0]] < maps[x[1]]:\n answer += x[1]\n else:\n answer += x[0]\n \n return answer\n ","sub_path":"성격 유형 검사하기.py","file_name":"성격 유형 검사하기.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"97227992","text":"#!usr/bin/env python\n\nimport sys\nimport numpy as np\nimport sklearn.cluster\nimport distance\n\nif len(sys.argv) < 2:\n prin('USAGE: clustering_words.py ')\n sys.exit(1)\n\nfilename = sys.argv[1]\n \nwords = np.asarray(list((word.strip() for word in open(filename, 'r')))) #So that indexing with a list will work\nlev_similarity = - 1 * np.array([[distance.levenshtein(w1,w2) for w1 in words] for w2 in words])\n\naffprop = sklearn.cluster.AffinityPropagation(affinity=\"precomputed\", damping=0.5)\naffprop.fit(lev_similarity)\nfor cluster_id in np.unique(affprop.labels_):\n exemplar = words[affprop.cluster_centers_indices_[cluster_id]]\n cluster = np.unique(words[np.nonzero(affprop.labels_==cluster_id)])\n cluster_str = \", \".join(cluster)\n print(\" - *%s:* %s\" % (exemplar, cluster_str))\n\n\n","sub_path":"clustering_words.py","file_name":"clustering_words.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"530036340","text":"import bpy\nfrom bpy.types import GizmoGroup\n\n\n# https://gist.github.com/FujiSunflower/09fdabc7ca991f8292657abc4ef001b0\nclass Vrm0FirstPersonBoneOffsetGizmoGroup(GizmoGroup): # type: ignore[misc]\n bl_idname = \"VRM_GGT_vrm0_first_person_bone_offset\"\n bl_label = \"First Person Bone Offset Gizmo\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"WINDOW\"\n bl_options = {\"3D\", \"PERSISTENT\"}\n\n @classmethod\n def poll(cls, context: bpy.types.Context) -> bool:\n if context.active_object.data is None:\n return False\n return hasattr(context.active_object.data, \"vrm_addon_extension\")\n\n def setup(self, context: bpy.types.Context) -> None:\n armature = context.active_object.data\n ext = armature.vrm_addon_extension\n first_person = ext.vrm0.first_person\n first_person_bone = armature.bones[first_person.first_person_bone.value]\n gizmo = self.gizmos.new(\"GIZMO_GT_move_3d\")\n gizmo.target_set_prop(\"offset\", first_person, \"first_person_bone_offset\")\n gizmo.matrix_basis = first_person_bone.matrix_local\n gizmo.draw_style = \"CROSS_2D\"\n gizmo.draw_options = {\"ALIGN_VIEW\"}\n gizmo.color = 1.0, 0.5, 0.0\n gizmo.alpha = 0.5\n gizmo.color_highlight = 1.0, 0.5, 1.0\n gizmo.alpha_highlight = 0.5\n gizmo.scale_basis = 0.25\n\n # pylint: disable=attribute-defined-outside-init;\n self.first_person_gizmo = gizmo\n # pylint: enable=attribute-defined-outside-init;\n\n def refresh(self, context: bpy.types.Context) -> None:\n armature = context.active_object.data\n ext = armature.vrm_addon_extension\n gizmo = self.first_person_gizmo\n first_person = ext.vrm0.first_person\n first_person_bone = armature.bones[first_person.first_person_bone.value]\n gizmo.matrix_basis = first_person_bone.matrix_local\n","sub_path":"io_scene_vrm/editor/vrm0/gizmo_group.py","file_name":"gizmo_group.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"519588374","text":"import os\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix, f1_score\nimport matplotlib.pyplot as plt\n\ndata_filepath = os.path.join(os.getcwd(), 'dermatology.data')\n\n# Read data\n# data = pd.read_csv(data_filepath, header=None, na_values=['?'])\n# data.to_pickle('data')\ndata = pd.read_pickle('data')\n\n# ########### Step B ############\n# Count missing values\ntemp = data.isna().sum(axis=1)\nnan_samples = temp.astype(bool).sum()\npercentage = nan_samples / data.shape[0]\n\nprint(\n f'Number of samples with missing values: {nan_samples}\\n'\n f'Percentage of total samples: {percentage}\\n'\n)\n\n# Split labels and features\nX, y = data.iloc[:, :-1], data.iloc[:, -1]\n\nlabels = y.unique()\nlabel_frequencies = y.value_counts(normalize=True)\ninstability_metric = label_frequencies.max() / label_frequencies.min()\n\nprint(\n f'Number of labels: {len(labels)}\\n'\n f'Label frequencies: \\n{label_frequencies.to_string()}\\n'\n f'Is the sample unstable? {instability_metric > 1.5}\\n'\n)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42069)\n\n# Fill in missing values\nimr = SimpleImputer(missing_values=np.NaN, strategy='mean')\nimr = imr.fit(X_train)\nX_train = imr.transform(X_train)\nX_test = imr.transform(X_test)\n\n# There are no categorical features to encode\n\n# ########### Step C ############\ndc_stratified = DummyClassifier(strategy=\"stratified\")\ndc_stratified.fit(X_train, y_train)\ndc_y_pred = dc_stratified.predict(X_test)\ndc_conf = confusion_matrix(y_test, dc_y_pred)\ndc_f1_micro = f1_score(y_test, dc_y_pred, average='micro')\ndc_f1_macro = f1_score(y_test, dc_y_pred, average='macro')\n\nprint(\n 'Dummy Classifier Results\\n'\n f'Confusion Matrix:\\n{dc_conf}\\n'\n f'f1-micro average: {dc_f1_micro}\\n'\n f'f1-macro average: {dc_f1_macro}\\n'\n)\n\nknn = KNeighborsClassifier()\nknn.fit(X_train, y_train)\nknn_y_pred = knn.predict(X_test)\nknn_conf = confusion_matrix(y_test, knn_y_pred)\nknn_f1_micro = f1_score(y_test, knn_y_pred, average='micro')\nknn_f1_macro = f1_score(y_test, knn_y_pred, average='macro')\n\nprint(\n 'k-NN Classifier Results\\n'\n f'Confusion Matrix:\\n{knn_conf}\\n'\n f'f1-micro average: {knn_f1_micro}\\n'\n f'f1-macro average: {knn_f1_macro}\\n'\n)\n\nplt.figure()\n\n\nplt.subplot('211')\nplt.title('f1-scores for classification')\nplt.ylabel('f1-micro average')\nplt.bar([0, 1], [dc_f1_micro, knn_f1_micro], tick_label=['Stratified Dummy', 'k Nearest Neighbors'])\n\nplt.subplot('212')\nplt.ylabel('f1-macro average')\nplt.bar([0, 1], [dc_f1_macro, knn_f1_macro], tick_label=['Stratified Dummy', 'k Nearest Neighbors'])\nplt.show()\n\n# ########### Step D ############\n# 1) Oversample to fix imbalance\n# 1.5) Try normalizing the data too, they mention it in a notbook\nneighbors = list(range(1, 20, 2))\nn_components = list(range(1,20, 1))\n\nfor n_neigh in neighbors:\n for n_comp in n_components:\n # 2) PCA with n components\n # 3) Create-fit-tranform knn with n_neigh neighbors\n # Find score, find best combo\n\n pass\nx = 42\n","sub_path":"small.py","file_name":"small.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565181379","text":"import numpy as np\nimport viscek_library as viscek\nfrom mpi4py import MPI\n\n# communicator and local rank\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\n\nn_proc = 256\n\n# parameters\nl = 10\nv = 0.03\nr = 1\n\nEta = np.array([0, 0.5, 1, 1.5, 2, 2.5, 2.75, 3, 3.125, 3.25, 3.375, 3.5, 3.625, 3.75, 4, 4.5])\nRho = np.array([0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 7, 8, 9, 10])\neta = Eta[int(rank // 16)]\nrho = Rho[int(rank % 16)]\n\nPhi = []\nfor i in range(10):\n n = int(l * l * rho)\n model = viscek.make_viscek_model(l, n, eta, v, r)\n viscek.step_viscek_model(model, 1000)\n phi = model.phi()\n Phi.append(phi)\n\nPhi = np.asarray(Phi)\naverage_phi = Phi.mean()\nuncertainty = (Phi**2).mean() - average_phi**2 # gives the square of the santard deviation\n\nprint(eta, rho, average_phi, uncertainty)","sub_path":"Tracer les courbes de phi en fonction de eta et rho/eta_et_rho/tracer_phi_en_fonction_de_eta_et_rho_mpi.py","file_name":"tracer_phi_en_fonction_de_eta_et_rho_mpi.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"14560878","text":"import openpyxl\r\nimport openpyxl as xl \r\nfrom openpyxl import Workbook\r\nfrom openpyxl.workbook import Workbook\r\nfrom openpyxl.styles import Alignment\r\nfrom openpyxl.cell import Cell\r\nfrom openpyxl.styles import Color, PatternFill, Font, Border\r\nfrom openpyxl.styles import colors, Fill, fills\r\nimport random\r\nimport os\r\n#Load workbook\r\nprint ('You have 100 seconds to pee!!!!')\r\nworkbook = openpyxl.load_workbook('out.xlsx')\r\nworksheet_out = workbook.worksheets[0]\r\nworksheet_out = workbook.active\r\nworksheet = workbook.worksheets[1]\r\nmr = worksheet.max_row\r\nmc = worksheet.max_column\r\n#get time\r\n#1 Get num_les\r\ncol_stt = 'A2'\r\ni = 0\r\nwhile (worksheet[col_stt].value is not None ):\r\n i= i+1\r\n col_stt = 'A' + str(i+1)\r\n cell_null = worksheet[col_stt].value\r\nnum_les=i+1\r\n\r\n#2 get timeline\r\nfor i in range (2,num_les) :\r\n coler0 = 'I'+ str(i)\r\n coler1 = 'K'+ str(i)\r\n coler2 = 'L'+ str(i) \r\n coler3 = 'M'+ str(i) \r\n worksheet[coler1] = '=MONTH(' + coler0 + ')'\r\n worksheet[coler2] = '=DAY(' + coler0 + ')'\r\n worksheet[coler3] = '=C'+str(i)+'&CHAR(10)&J'+str(i)\r\nworkbook.save(\"out.xlsx\")\r\nos.system('python convertFormulatoText.py')\r\n#ReLoad workbook\r\nworkbook = openpyxl.load_workbook('out.xlsx')\r\nworksheet = workbook.worksheets[1]\r\n#Merge table\r\nmr0 = worksheet_out.max_row\r\nmc0 = worksheet_out.max_column\r\n## identify for col \r\nfor i in range (4, 10):\r\n workbook.worksheets[0].cell(row = 111, column = i ).value = 'T' + str(i-2)\r\nworkbook.worksheets[0].cell(row = 111, column = 10 ).value = 'CN'\r\n## Merging\r\ndata_color = ['E0699C','E0D675','C25DE0','48E04E','7253E0','69ADE0','E07875','5DE0D3','E0A448','53E082']\r\nfor row in range (2, num_les):\r\n try:\r\n scell = worksheet.cell(row = row, column = 11 ).value +3\r\n ecell = worksheet.cell(row = row, column = 12 ).value +3\r\n col_day = worksheet.cell(row = row, column = 8 ).value\r\n\r\n if workbook.worksheets[0].cell(row = 9, column = 2).value == 'RELAX':\r\n if scell >= 9:\r\n ecell +=1\r\n scell +=1\r\n for checker in range (4,10):\r\n cell_checker = worksheet_out.cell(row = 111, column = checker).value\r\n if cell_checker == col_day :\r\n workbook.worksheets[0].merge_cells(start_row= scell, start_column= checker, end_row= ecell , end_column= checker)\r\n workbook.worksheets[0].cell(row = scell, column = checker).value = workbook.worksheets[1].cell(row = row, column = 13).value\r\n top_left_cell = workbook.worksheets[0].cell(row = scell, column = checker)\r\n top_left_cell.fill = PatternFill(\"gray125\", fgColor= random.choice(data_color))\r\n \r\n #smove = 'A'+ str(row)\r\n #emove = 'Z'+ str(row)\r\n #rangemove= smove + ':'+ emove\r\n #workbook.worksheets[1].cell(row = row, column = 1).value=0\r\n except:\r\n print(\"good for health\")\r\n #os.system('python processingKHTNS.py')\r\n #break\r\nfor row in range (2, num_les):\r\n if(workbook.worksheets[1].cell(row = row, column = 11).value is not None):\r\n workbook.worksheets[1].cell(row = row, column = 1).value =0\r\nos.system('python convertFormulatoText.py')\r\n#save\r\nworkbook.save(\"out.xlsx\")","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"259701401","text":"# Copyright 2020 Huawei Technologies Co., Ltd\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\"\"\"\nc transforms for all text related operators\n\"\"\"\n\nimport os\nimport re\n\nimport mindspore._c_dataengine as cde\n\nfrom .utils import JiebaMode\nfrom .validators import check_lookup, check_jieba_add_dict, \\\n check_jieba_add_word, check_jieba_init\n\n\nclass Lookup(cde.LookupOp):\n \"\"\"\n Lookup operator that looks up a word to an id\n Args:\n vocab(Vocab): a Vocab object\n unknown(None,int): default id to lookup a word that is out of vocab\n \"\"\"\n\n @check_lookup\n def __init__(self, vocab, unknown=None):\n if unknown is None:\n super().__init__(vocab)\n else:\n super().__init__(vocab, unknown)\n\n\nDE_C_INTER_JIEBA_MODE = {\n JiebaMode.MIX: cde.JiebaMode.DE_JIEBA_MIX,\n JiebaMode.MP: cde.JiebaMode.DE_JIEBA_MP,\n JiebaMode.HMM: cde.JiebaMode.DE_JIEBA_HMM\n}\n\n\nclass JiebaTokenizer(cde.JiebaTokenizerOp):\n \"\"\"\n Tokenize Chinese string into words based on dictionary.\n\n Args:\n hmm_path (str): the dictionary file is used by HMMSegment algorithm,\n the dictionary can be obtained on the official website of cppjieba.\n mp_path(str): the dictionary file is used by MPSegment algorithm,\n the dictionary can be obtained on the official website of cppjieba.\n mode (Enum): [Default \"MIX\"], \"MP\" model will tokenize with MPSegment algorithm,\n \"HMM\" mode will tokenize with Hiddel Markov Model Segment algorithm,\n \"MIX\" model will tokenize with a mix of MPSegment and HMMSegment algorithm.\n \"\"\"\n\n @check_jieba_init\n def __init__(self, hmm_path, mp_path, mode=JiebaMode.MIX):\n self.mode = mode\n self.__check_path__(hmm_path)\n self.__check_path__(mp_path)\n super().__init__(hmm_path, mp_path,\n DE_C_INTER_JIEBA_MODE[mode])\n\n @check_jieba_add_word\n def add_word(self, word, freq=None):\n \"\"\"\n Add user defined word to JiebaTokenizer's dictionary\n Args:\n word(required, string): The word to be added to the JiebaTokenizer instance.\n The added word will not be written into the built-in dictionary on disk.\n freq(optional, int): The frequency of the word to be added, The higher the frequency,\n the better change the word will be tokenized(default None, use default frequency).\n \"\"\"\n if freq is None:\n super().add_word(word, 0)\n else:\n super().add_word(word, freq)\n\n @check_jieba_add_dict\n def add_dict(self, user_dict):\n \"\"\"\n Add user defined word to JiebaTokenizer's dictionary\n Args:\n user_dict(path/dict):Dictionary to be added, file path or Python dictionary,\n Python Dict format: {word1:freq1, word2:freq2,...}\n Jieba dictionary format : word(required), freq(optional), such as:\n word1 freq1\n word2\n word3 freq3\n \"\"\"\n if isinstance(user_dict, str):\n self.__add_dict_py_file(user_dict)\n elif isinstance(user_dict, dict):\n for k, v in user_dict.items():\n self.add_word(k, v)\n else:\n raise ValueError(\"the type of user_dict must str or dict\")\n\n def __add_dict_py_file(self, file_path):\n \"\"\"Add user defined word by file\"\"\"\n words_list = self.__parser_file(file_path)\n for data in words_list:\n if data[1] is None:\n freq = 0\n else:\n freq = int(data[1])\n self.add_word(data[0], freq)\n\n def __parser_file(self, file_path):\n \"\"\"parser user defined word by file\"\"\"\n if not os.path.exists(file_path):\n raise ValueError(\n \"user dict file {} is not exist\".format(file_path))\n file_dict = open(file_path)\n data_re = re.compile('^(.+?)( [0-9]+)?$', re.U)\n words_list = []\n for item in file_dict:\n data = item.strip()\n if not isinstance(data, str):\n data = self.__decode(data)\n words = data_re.match(data).groups()\n if len(words) != 2:\n raise ValueError(\n \"user dict file {} format error\".format(file_path))\n words_list.append(words)\n return words_list\n\n def __decode(self, data):\n \"\"\"decode the dict file to utf8\"\"\"\n try:\n data = data.decode('utf-8')\n except UnicodeDecodeError:\n raise ValueError(\"user dict file must utf8\")\n return data.lstrip('\\ufeff')\n\n def __check_path__(self, model_path):\n \"\"\"check model path\"\"\"\n if not os.path.exists(model_path):\n raise ValueError(\n \" jieba mode file {} is not exist\".format(model_path))\n\n\nclass UnicodeCharTokenizer(cde.UnicodeCharTokenizerOp):\n \"\"\"\n Tokenize a scalar tensor of UTF-8 string to Unicode characters.\n \"\"\"\n","sub_path":"mindspore/dataset/text/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"321529142","text":"import sys\n\nf1 = open(sys.argv[1])\nf2 = open(sys.argv[2])\n\nf1_lines = {x.strip() for x in list(f1)}\nf2_lines = {x.strip() for x in list(f2)}\n\nprint('Intersection:', len(f1_lines & f2_lines))\nprint('Exclusive to', sys.argv[1] + ':', len({x for x in f1_lines if x not in f2_lines}))\nprint('Exclusive to', sys.argv[2] + ':', len({x for x in f2_lines if x not in f1_lines}))\n\n","sub_path":"onto/OMIM/intersect.py","file_name":"intersect.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"283190070","text":"from pathlib import Path\nimport numpy as np\nimport pickle\nimport matplotlib\nfrom dataclasses import dataclass\nimport dataclasses\nimport datetime\n\nfrom ephys.ephysanalysis import MakeClamps\nimport src.vcnmodel.util.fixpicklemodule as FPM\n\nclass ReadModel():\n def __init__(self):\n self.MC = MakeClamps.MakeClamps()\n \n def read_pfile(self, filename:str, filemode:str='vcnmodel.v0', vscale:float=1e-3, iscale:float=1e-9, plot=False):\n \"\"\"\n Read a pickled file; optionally plot the data\n Puts the data into a Clamps structure.\n\n Parameters\n ----------\n filename : str or Path\n The file to be read\n \n mode: str\n version name\n plot: Boolean (default: False)\n Flag to specify plotting the data in a simple mode\n \"\"\"\n \n\n # r = df['Results'][0]\n #\n # if plot:\n # P = PH.Plotter((1, 1), figsize=(6, 4))\n # cell_ax = list(P.axdict.keys())[0]\n # for trial in range(len(df['Results'])):\n # ds = df['Results'][trial]\n # k0 = list(df['Results'][trial].keys())[0]\n # dx = ds[k0]['monitor']\n # P.axdict[cell_ax].plot(dx['time'], dx['postsynapticV'], linewidth=1.0)\n # P.axdict[cell_ax].set_xlim(0., 150.)\n # P.axdict[cell_ax].set_ylim(-200., 50.)\n # PH.calbar(P.axdict[cell_ax], calbar=[120., -95., 25., 20.], axesoff=True, orient='left',\n # unitNames={'x': 'ms', 'y': 'mV'}, font='Arial', fontsize=8)\n #\n # # mpl.savefig(outfile)\n # mpl.show()\n # print(list(df.keys()))\n # print('\\nbasename: ', df['basename'])\n # print('\\nruninfo: ', df['runInfo'])\n \"\"\"\n The runInfo dictionary holds somethign like this:\n runinfo: {'folder': PosixPath('VCN_Cells/VCN_c08/Simulations/IV'), 'fileName': 'Normal', 'runName': 'Run', \n 'manipulation': 'Canonical', 'preMode': 'cc', 'postMode': 'cc', 'TargetCellType': 'Bushy', \n 'electrodeSection': 'soma', 'dendriticElectrodeSection': 'dendrite', \n 'dendriticSectionDistance': 100.0, 'celsius': 37, 'nStim': 1, \n 'stimFreq': 200.0, 'stimInj': {'pulse': [-1.0, 2.01, 0.2]}, \n 'stimDur': 100.0, 'stimDelay': 5.0, 'stimPost': 3.0, \n 'vnStim': 1, 'vstimFreq': 200.0, 'vstimInj': 50, \n 'vstimDur': 50.0, 'vstimDelay': 2.0, 'vstimPost': 3.0, 'vstimHolding': -60, \n 'gif_i0': 0.0, 'gif_sigma': 0.5, 'gif_fmod': 0.2, 'gif_tau': 3.0, \n 'gif_dur': 10.0, 'gif_skew': 0.0, \n 'runTime': 'Wed Oct 9 13:05:54 2019', \n 'inFile': None, 'inFileRep': 1, 'spikeTimeList': {}, \n 'v_init': -61.0, 'useSaveState': True, 'tstop': 8.0, 'filename': 'VCN_c08_pulse_'}\n \"\"\"\n # print('\\nmodelPars: ', df['modelPars'])\n \"\"\"\n The modelPars dict holds the following:\n modelPars: {'species': 'mouse', 'cellClass': 'bushy', 'modelType': 'II', \n 'modelName': 'mGBC', 'soma': True, 'axon': False, \n 'dendrites': False, 'pumps': False, 'hillock': False, \n 'initialsegment': False, 'myelinatedaxon': False, \n 'unmyelinatedaxon': False, 'na': 'nav11', 'ttx': False, \n 'name': 'bushy', 'morphology': 'VCN_Cells/VCN_c08/Morphology/VCN_c08.hoc', \n 'temperature': 34.0}\n \n Note 10/28/2019 changed structure so that runInfo and modelPars are both \n subdictionaries of Params (filemode is 'vcnmodel.v0')\n ... and undone later, so that all are top-level (filemode is 'vcnmodel.v1')\n \"\"\"\n with open(filename, 'rb') as fh:\n df = FPM.pickle_load(fh)\n if filemode in ['vcnmodel.v0']:\n print(f\"Reading model file in version v0:, with {len(df['Results']):4d} trials\")\n elif filemode in ['vcnmodel.v1']:\n print(f\"Reading model file in version v1:, with {len(df['Results']):4d} trials\")\n else:\n raise ValueError(f'Unknown file mode: {filemode:s}')\n # print('\\nrpfile v0: File keys: ', df.keys())\n #\n # print('\\nrpfile v0: basename: ', df['basename'])\n mtime = Path(filename).stat().st_mtime\n timestamp_str = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d-%H:%M')\n if filemode == 'vcnmodel.v0':\n # print(df['Params'].keys())\n try:\n dinfo = df['Params']['runInfo']\n except:\n try:\n dinfo = df['runInfo']\n except:\n raise ValueError (\"Cannot read the file in v0 mode?\")\n run_protocol = df['Params']['runProtocol']\n if isinstance(dinfo, Params):\n dinfo = dinfo.todict()\n dur = dinfo['stimDur']\n delay = dinfo['stimDelay']\n mode = dinfo['postMode'].upper()\n ntr = len(df['Results'])\n # print(df.keys())\n # print('runinfo: ', df['runInfo'])\n # print('Params: ', df['Params'].keys())\n # print('dinfo: ', dinfo)\n if 'dt' in df['Params'].keys():\n self.rate = df['Params']['dt']\n else:\n self.rate = df['Params'].dt\n V = [[]]*ntr\n I = [[]]*ntr\n for i in range(len(df['Results'])):\n fk = list(df['Results'][i].keys())[0]\n dfx = df['Results'][i][fk]['monitor']\n timebase = dfx['time']\n V[i] = dfx['postsynapticV']*vscale\n I[i] = dfx['i_stim0']*iscale\n else:\n dinfo = df['runInfo']\n x = dir(dinfo)\n if 'stimVC' not in x: # create fields for missing values from older versions of files.\n dinfo.stimVC = None\n # print('rpfile v0: dinfo: ', dinfo)\n mode = dinfo.postMode.upper()\n dur = dinfo.stimDur\n delay = dinfo.stimDelay\n mode = dinfo.postMode\n print(\"Keys found in file: \", df.keys())\n print('Mode: ', mode)\n try:\n self.rate = df['Params'].dt # old version, now separated IC and VC\n except:\n if mode == 'VC':\n self.rate = df['Params'].dtVC\n elif mode == \"CC\":\n self.rate = df['Params'].dtIC\n else:\n raise ValueError(\"Cannot find rate for data mode: \", mode)\n\n run_protocol = dinfo.runProtocol\n if dinfo.runProtocol in ['runIV', 'initIV', 'testIV']:\n ntr = len(df['Results'])\n V = [[]]*ntr\n I = [[]]*ntr\n for ii, i in enumerate(df['Results'].keys()):\n dfx = df['Results'][i]['monitor']\n timebase = dfx['time']\n V[ii] = np.array(dfx['postsynapticV'])*vscale\n I[ii] = np.array(dfx['i_stim0'])*iscale\n elif dinfo.runProtocol in ['runVC', 'initVC', 'testVC']:\n dur = dinfo.vstimDur # msec\n delay = dinfo.vstimDelay # msec\n ntr = len(df['Results'])\n V = [[]]*ntr\n I = [[]]*ntr\n for ii, i in enumerate(df['Results'].keys()):\n dfx = df['Results'][i]['monitor']\n timebase = dfx['time']\n V[ii] = np.array(dfx['postsynapticV'])*vscale\n I[ii] = np.array(dfx['postsynapticI'])*iscale\n \n elif dinfo.runProtocol in ['initAN', 'runANPSTH', 'runANIO', 'runANSingles']:\n\n # two ways data can be organized, so try both\n try: # cnmodel_models simulations\n ntr = len(df['Results'])\n V = [[]]*ntr\n I = [[]]*ntr\n for j in list(df['Results'].keys()):\n dfx = df['Results'][j]\n timebase = dfx['time']\n V[j] = np.array(dfx['somaVoltage'])*vscale\n I[j] = np.zeros_like(V[j])\n except: # vcnmodel simulatipns\n ntr = len(df[\"Results\"]['somaVoltage'])\n V = [[]]*ntr\n I = [[]]*ntr\n for j in range(ntr):\n timebase = df['Results']['time']\n V[j] = np.array(df['Results']['somaVoltage'][j])*vscale\n I[j] = np.zeros_like(V[j])\n\n V = np.array(V)\n I = np.array(I)\n # print('V shape: ', V.shape, 'I shape: ', I.shape, ' timebase: ', timebase.shape, V.shape[1]*self.rate, np.max(timebase))\n # exit()\n\n if run_protocol in ['runVC', 'initVC', 'testVC']:\n self.MC.set_clamps(dmode=mode, time=timebase, data=I, cmddata=V, tstart_tdur=[delay, dur])\n else:\n self.MC.set_clamps(dmode=mode, time=timebase, data=V, cmddata=I, tstart_tdur=[delay, dur])\n self.MC.getClampData()\n","sub_path":"src/vcnmodel/util/readmodel.py","file_name":"readmodel.py","file_ext":"py","file_size_in_byte":9037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"5998046","text":"import math\n\nREFERENCE_TEXTS = []\nif __name__ == '__main__':\n texts = ['5_7.txt', '15_2.txt', '10547_3.txt', '12230_7.txt']\n for text in texts:\n with open(text, 'r') as f:\n REFERENCE_TEXTS.append(f.read())\n\n\ndef clean_tokenize_corpus(texts: list) -> list:\n pass\n if type(texts) != list:\n return []\n new_l = []\n for element in texts:\n if type(element) != str:\n continue\n txt = ''\n for i in range(0, len(element) - 1):\n if element[i].isalpha():\n txt += element[i].lower()\n if element[i] == ' ' or element[i] == \"'\":\n txt += element[i]\n if element[i] in ['.', ',', '!', '?']:\n if element[i - 1].isalpha() and element[i + 1].isalpha():\n continue\n if element[i - 1].isalpha() and element[i + 1] == ' ':\n txt += ' '\n if element[i] in '/':\n if element[i - 1].isalpha() and element[i + 1].isalpha():\n txt += ' '\n if element[i] == '\"' or element[i] is '<' or element[i] is '>':\n if element[i - 1].isalpha() and element[i + 1].isalpha():\n continue\n else:\n txt += ' '\n n_text = txt.split()\n res = []\n for el in n_text:\n if el == 'n' or el == 'br':\n continue\n else:\n res.append(el)\n new_l.append(res)\n return new_l\n\n\nclass TfIdfCalculator:\n def __init__(self, corpus):\n pass\n self.corpus = corpus\n self.tf_values = []\n self.idf_values = {}\n self.tf_idf_values = []\n\n def calculate_tf(self):\n pass\n if type(self.corpus) != list:\n return []\n for elem in self.corpus:\n if type(elem) != list:\n continue\n tf_dictionary = {}\n n_el_txt = []\n for e in elem:\n if isinstance(e, str):\n n_el_txt.append(e)\n for e_word in n_el_txt:\n tf_value = n_el_txt.count(e_word)\n tf_dictionary[e_word] = tf_value / len(n_el_txt)\n self.tf_values.append(tf_dictionary)\n\n\n\n def calculate_idf(self):\n pass\n if self.corpus == None:\n return {}\n list = []\n for current in self.corpus:\n if current:\n list.append(current)\n full_txt = []\n for full_el in list:\n for word in full_el:\n if type(word) == str:\n full_txt.append(word)\n for word in full_txt:\n freqency = 0\n if word in self.idf_values:\n continue\n for current_text in list:\n if word in current_text:\n freqency += 1\n continue\n self.idf_values[word] = math.log(len(list) / freqency)\n\n def calculate(self):\n pass\n\n if self.tf_values and self.idf_values:\n for tf_dictionary in self.tf_values:\n new_dict_idf_tf = {}\n for word, tf in tf_dictionary.items():\n if self.idf_values[word]:\n new_dict_idf_tf[word] = tf * self.idf_values[word]\n else:\n new_dict_idf_tf[word] = 0\n self.tf_idf_values.append(new_dict_idf_tf)\n\n def report_on(self, word, document_index):\n pass\n if type(self.tf_idf_values) != list:\n return ()\n if (document_index > len(self.corpus) - 1):\n return ()\n if(len(self.tf_idf_values) == 0):\n return ()\n num = 0\n txt_n = self.corpus[document_index]\n present_tf_idf_dict = self.tf_idf_values[document_index]\n w_tf_idf_list = list()\n if word not in present_tf_idf_dict.keys():\n return ()\n for w_2 in txt_n:\n if w_2 in present_tf_idf_dict:\n w_tf_idf_list.append((present_tf_idf_dict[w_2], w_2))\n w_tf_idf_list.sort(reverse=True)\n for i, b in enumerate(w_tf_idf_list):\n if b[1] == word:\n num = i\n break\n res = (present_tf_idf_dict[word], num)\n\n return res\n\n\n# scenario to check your work\ntest_texts = clean_tokenize_corpus(REFERENCE_TEXTS)\ntf_idf = TfIdfCalculator(test_texts)\ntf_idf.calculate_tf()\ntf_idf.calculate_idf()\ntf_idf.calculate()\nprint(tf_idf.report_on('good', 0))\nprint(tf_idf.report_on('and', 1))\n","sub_path":"lab_4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594870076","text":"\nimport numpy as np\nimport sys\n\n#################\n### Read data ###\n\nf = open(sys.argv[1])\ndata1 = np.loadtxt(f)\n\n\nonearray = np.ones((data1.shape[0],1))\ndata1 = np.append(data1,onearray,axis=1)\n\ntrain = data1[:,1:]\ntrainlabels = data1[:,0]\n\nprint(\"train=\",train)\nprint(\"train shape=\",train.shape)\n\nf = open(sys.argv[2])\ndata = np.loadtxt(f)\ntest = data[:,1:]\ntestlabels = data[:,0]\n\nonearray = np.ones((test.shape[0],1))\ntest = np.append(test,onearray,axis=1)\n\nrows = train.shape[0]\ncols = train.shape[1]\n\n#hidden_nodes = int(sys.argv[3])\n\nhidden_nodes = 3\nk=1\nk=int(sys.argv[3])\n##############################\n### Initialize all weights ###\n\nw = np.random.rand(hidden_nodes)\n#w = np.ones(hidden_nodes)\nprint(\"w=\",w)\n\n#check this command\n#W = np.zeros((hidden_nodes, cols), dtype=float)\n#W = np.ones((hidden_nodes, cols), dtype=float)\nW = np.random.rand(hidden_nodes, cols)\n\nprint(\"W=\",W)\n\nepochs = 200\neta = 0.001\nprevobj = np.inf\ni=0\n\n###########################\n### Calculate objective ###\n\nhidden_layer = np.matmul(train, np.transpose(W))\nprint(\"hidden_layer=\",hidden_layer)\nprint(\"hidden_layer shape=\",hidden_layer.shape)\n\nsigmoid = lambda x: 1/(1+np.exp(-x))\n#sigmoid = lambda x: np.sign(x)\nhidden_layer = np.array([sigmoid(xi) for xi in hidden_layer])\nprint(\"hidden_layer=\",hidden_layer)\nprint(\"hidden_layer shape=\",hidden_layer.shape)\n\noutput_layer = np.matmul(hidden_layer, np.transpose(w))\nprint(\"output_layer=\",output_layer)\n\nobj = np.sum(np.square(output_layer - trainlabels))\n#print(\"obj=\",obj)\n\n#obj = np.sum(np.square(np.matmul(train, np.transpose(w)) - trainlabels))\n\nprint(\"Initial Obj=\",obj)\ndata111=np.array([i for i in range(rows)])\n###############################\n### Begin gradient descent ####\n#exit()\nwhile(i < epochs):\n\t\n\t#Update previous objective\n\tprevobj = obj\n\t#print(train)\n\t#Calculate gradient update for final layer (w)\n\t#dellw is the same dimension as w\n\tdellw, dells, dellu, dellv=0, 0, 0, 0\n\t#rows = train.shape[0]\n\tfor mk in range(0, rows):\n\t\tnp.random.shuffle(data111)\n\t\tcur=data111[0]\n\t\tdellw = (np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*hidden_layer[cur,:]\n\t\tfor j in range(1, k):\n \t\tcur=data111[j]\n \t\tdellw += (np.dot(hidden_layer[cur,:],np.transpose(w))-trainlabels[cur])*hidden_layer[cur,:]\n\n\t #Update w\n\t #print(dellw)\n\t\tw = w - eta*dellw\n\n #print(\"dellf=\",dellf)\n\t\n\t #Calculate gradient update for hidden layer weights (W)\n\t #dellW has to be of same dimension as W\n\n\t #Let's first calculate dells. After that we do dellu and dellv.\n\t #Here s, u, and v are the three hidden nodes\n\t #dells = df/dz1 * (dz1/ds1, dz1,ds2)\n\t #print((hidden_layer[0,0])*(1-hidden_layer[0,0])*train[0])\n\t\tcur=data111[0]\n\t\tdells = np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[0] * (hidden_layer[cur,0])*(1-hidden_layer[cur,0])*train[0]\n\t\tfor j in range(1, k):\n \tcur=data111[j]\n \tdells += np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[0] * (hidden_layer[cur,0])*(1-hidden_layer[cur,0])*train[j]\n\t #print(dells)\n\t\n\n\n\t #TODO: dellu = ?\n\t\tdellu = np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[1] * (hidden_layer[cur,1])*(1-hidden_layer[cur,1])*train[0]\n\t\tfor j in range(1, k):\n\t\t\tcur=data111[j]\n\t\t\tdellu += np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[1] * (hidden_layer[cur,1])*(1-hidden_layer[cur,1])*train[cur]\n\n\n\t #TODO: dellv = ?\n\t\tdellv = np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[2] * (hidden_layer[cur,2])*(1-hidden_layer[cur,2])*train[cur]\n\t\tfor j in range(1, k):\n\t\t\tcur=data111[j]\n\t\t\tdellv += np.sum(np.dot(hidden_layer[cur,:],w)-trainlabels[cur])*w[2] * (hidden_layer[cur,2])*(1-hidden_layer[cur,2])*train[cur]\n\n\n\t #TODO: Put dells, dellu, and dellv as rows of dellW\n\t #dellW=[dells,dellu,dellv]\n\t\tdellW=np.array([dells, dellu, dellv])\n\t #print(dellW)\n\t\n\t #Update W\n\t\tW = W - eta*dellW\n\t#print(W)\n\t#print(w)\n\t#exit()\n\t#Recalculate objective\n\thidden_layer = np.matmul(train, np.transpose(W))\n\t#print(\"hidden_layer=\",hidden_layer)\n\n\thidden_layer = np.array([sigmoid(xi) for xi in hidden_layer])\n\t#print(\"hidden_layer=\",hidden_layer)\n\n\toutput_layer = np.matmul(hidden_layer, np.transpose(w))\n\t#print(\"output_layer=\",output_layer)\n\n\tobj = np.sum(np.square(output_layer - trainlabels))\n\tprint(\"obj=\",obj)\n\t\n\ti = i + 1\n\t#print(\"Objective=\",obj)\n\t\n\n#predictions = np.sign(np.matmul(test, np.transpose(w)))\nhidden_layer = np.matmul(test, np.transpose(W))\npredictions = (np.matmul(sigmoid(hidden_layer),np.transpose(w)))\npredictions1 = np.sign(predictions)\nprint(predictions1)\nprint(w)\n\n\n","sub_path":"Mini_Batch_SGD_from_Scratch/assignment4_2.py","file_name":"assignment4_2.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"488147897","text":"import os\n\nimport pandas as pd\n\nimport json\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, inspect\n\nfrom flask import Flask, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n\n#################################################\n# Database Setup\n#################################################\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///db/tx_data.sqlite\"\ndb = SQLAlchemy(app)\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(db.engine, reflect=True)\n\n# engine = create_engine(\"sqlite:///db/tx_data.sqlite\")\n# inspector = inspect(engine)\n\n# Save references to each table\nincome = Base.classes.Per_Capita_Personal_Income\nunemployment = Base.classes.Unemployment_Rate\npopulation = Base.classes.population\ntempreferance = Base.classes.combine_schools_zip_geo\nair_quality = Base.classes.output\n\n\n# defining routs, quering DB, returning info\n\n@app.route(\"/\")\ndef index():\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"index.html\")\n\n@app.route(\"/counties\")\ndef counties():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(unemployment).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n return jsonify(list(df.County))\n\n\n@app.route(\"/unemp\")\ndef unemp():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(unemployment).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n my_dict = dict(zip(list(df.County), list(df.Unemployment)))\n return jsonify(my_dict)\n\n@app.route(\"/income\")\ndef inc():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(income).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n my_dict = dict(zip(list(df.County), list(df.Income)))\n return jsonify(my_dict)\n\n\n@app.route(\"/population\")\ndef popul():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(population).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n my_dict = dict(zip(list(df.County), list(df.Population)))\n return jsonify(my_dict)\n\n@app.route(\"/school\")\ndef school():\n \"\"\"Return a list of sample names.\"\"\"\n\n\n stmt = db.session.query(tempreferance).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n my_dict = df.to_dict(orient='records')\n j = json.dumps(my_dict)\n\n return j\n\n\n@app.route(\"/air_quality\")\ndef air():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(air_quality).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n my_dict = df.to_dict(orient='records')\n j = json.dumps(my_dict)\n\n return j\n\n\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"Oleg/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76793215","text":"import email\nimport imaplib\nimport re\nimport os\nimport sys\nimport datetime\n\ndetach_dir = '.'\n\n\ndef checkForDirectory():\n if 'attachments' not in os.listdir(detach_dir):\n os.mkdir('attachments')\n\n\ndef dlAlroAtachments(mostrecentdate, emailAddress, password):\n checkForDirectory()\n userName = emailAddress\n passwd = password\n pattern = re.compile(\"RT\\d+\")\n\n try:\n print('Trying to log in...')\n imapSession = imaplib.IMAP4_SSL('imap.gmail.com')\n typ, accountDetails = imapSession.login(userName, passwd)\n if typ != 'OK':\n print('Not able to sign in!')\n sys.exit(1)\n print('Trying to search all mail...')\n imapSession.select('\"[Gmail]/All Mail\"')\n typ, data = imapSession.search(None, '(FROM \"KOUTLAW@alro.com\") (SINCE {})'.format(mostrecentdate))\n if typ != 'OK':\n print('Error searching Inbox.')\n sys.exit(2)\n\n # Iterating over all emails\n for msgId in data[0].split():\n typ, messageParts = imapSession.fetch(msgId, '(RFC822)')\n if typ != 'OK':\n print('Error fetching mail.')\n sys.exit(2)\n emailBody = messageParts[0][1]\n mail = email.message_from_string(emailBody.decode(\"utf-8\"))\n subject = mail.get_all('Subject')\n date = mail.get_all('Date')\n match = pattern.search(str(subject))\n for part in mail.walk():\n if part.get_content_maintype() == 'multipart':\n # print part.as_string()\n continue\n if part.get('Content-Disposition') is None:\n # print part.as_string()\n continue\n fileName = part.get_filename()\n\n if bool(fileName):\n fileN, fileExt = os.path.splitext(fileName)\n if match:\n rtname = match.group(0)\n else:\n rtname = fileN\n filePath = os.path.join(detach_dir, 'attachments', \"{}{}\".format(rtname, fileExt))\n if not os.path.isfile(filePath):\n print(fileName)\n print(filePath)\n fp = open(filePath, 'wb')\n fp.write(part.get_payload(decode=True))\n fp.close()\n imapSession.close()\n imapSession.logout()\n except:\n print('Not able to download all attachments.')\n sys.exit(3)\n\n\ndef main():\n dlAlroAtachments()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dlFromGmail.py","file_name":"dlFromGmail.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"226367919","text":"import copy\n\nimport cv2\n\n\ndef zero_pad(img, pwx, pwy):\n \"\"\"Pads a given image with zero at the border.\"\"\"\n padded_img = copy.deepcopy(img)\n for i in range(pwx):\n padded_img.insert(0, [0 for value in enumerate(padded_img[i])])\n padded_img.insert(len(padded_img), [0 for value in enumerate(padded_img[-1])])\n for i, row in enumerate(padded_img):\n for j in range(pwy):\n row.insert(0, 0)\n row.insert(len(row), 0)\n return padded_img\n\ndef crop(img, xmin, xmax, ymin, ymax):\n \"\"\"Crops a given image.\"\"\"\n if len(img) < xmax:\n print('WARNING')\n patch = img[xmin: xmax]\n patch = [row[ymin: ymax] for row in patch]\n return patch\n\ndef elementwise_add(a, b):\n \"\"\"Elementwise addition.\"\"\"\n c = copy.deepcopy(a)\n for i, row in enumerate(a):\n for j, num in enumerate(row):\n c[i][j] += b[i][j]\n return c\n\ndef elementwise_sub(a, b):\n \"\"\"Elementwise substraction.\"\"\"\n c = copy.deepcopy(a)\n for i, row in enumerate(a):\n for j, num in enumerate(row):\n c[i][j] -= b[i][j]\n return c\n\ndef elementwise_mul(a, b):\n \"\"\"Elementwise multiplication.\"\"\"\n c = copy.deepcopy(a)\n for i, row in enumerate(a):\n for j, num in enumerate(row):\n c[i][j] *= b[i][j]\n return c\n\ndef elementwise_div(a, b):\n \"\"\"Elementwise division.\"\"\"\n c = copy.deepcopy(a)\n for i, row in enumerate(a):\n for j, num in enumerate(row):\n c[i][j] /= b[i][j]\n return c\n\ndef flip_x(img):\n \"\"\"Flips a given image along x axis.\"\"\"\n flipped_img = copy.deepcopy(img)\n center = int(len(img) / 2)\n for i in range(center):\n flipped_img[i] = img[(len(img) - 1) - i]\n flipped_img[(len(img) - 1) - i] = img[i]\n return flipped_img\n\ndef flip_y(img):\n \"\"\"Flips a given image along y axis.\"\"\"\n flipped_img = copy.deepcopy(img)\n center = int(len(img[0]) / 2)\n for i, row in enumerate(img):\n for j in range(center):\n flipped_img[i][j] = img[i][(len(img[0]) - 1) - j]\n flipped_img[i][(len(img[0]) - 1) - j] = img[i][j]\n return flipped_img\n\ndef flip2d(img, axis=None):\n \"\"\"Flips an image along a given axis.\n\n Hints:\n Use the function flip_x and flip_y.\n\n Args:\n img: nested list (int), the image to be flipped.\n axis (int or None): the axis along which img is flipped.\n if axix is None, img is flipped both along x axis and y axis.\n\n Returns:\n flipped_img: nested list (int), the flipped image.\n \"\"\"\n # TODO: implement this function.\n # raise NotImplementedError\n if axis != None:\n if axis == 'x':\n flipped_img = flip_x(img)\n return flipped_img\n elif axis == 'y':\n flipped_img = flip_y(img)\n return flipped_img\n else:\n flipped_img = flip_x(img)\n return flipped_img\n elif axis == None:\n flipped_img = flip_x(img)\n flipped_img = flip_y(flipped_img)\n return flipped_img\n\n \n\n","sub_path":"Project -1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485452989","text":"import os\nimport random\nimport time\n\nimport numpy as np\n\nimport keras\nfrom keras.models import Sequential,Input,Model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\n# from keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Adam\n\n# ROS packages required\nimport rospy\nimport rospkg\n\nfrom utils import Memory, H5Buffer\n\nclass Agent():\n def __init__(self, state_size, action_size, buffer_max_size, chunk_size, add_flipped, always_explore=False):\n file_name = 'double_dqn'+'_'+str(state_size[2])+'f'\n if add_flipped:\n file_name+='_flip'\n rospack = rospkg.RosPack()\n \n self.chunk_size = chunk_size\n self.add_flipped = add_flipped\n self.always_explore = always_explore\n self.working_dir = rospack.get_path('neuroracer_gym_rl')\n self.weight_backup = os.path.join(self.working_dir, file_name+'.h5')\n\n self.state_size = state_size\n self.action_size = action_size\n self.buffer = H5Buffer(state_size, buffer_max_size)\n self.learning_rate = 0.001\n self.gamma = 0.9\n self.exploration_rate = 0.85\n self.exploration_min = 0.01\n self.exploration_decay = 0.99\n self.model = self._build_model()\n self.target_model = self._build_model()\n self.training_count = 0\n\n\n def _build_model(self):\n\n model = Sequential()\n model.add(Conv2D(16, kernel_size=(3, 3), strides=(1, 1), input_shape=self.state_size,padding='same'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(MaxPooling2D((2, 2),padding='same'))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(32,kernel_size=(3, 3), strides=(1, 1),padding='same'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, kernel_size=(3, 3), strides=(2, 2), padding='same'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n\n model.add(Dense(256))\n model.add(LeakyReLU(alpha=0.1)) \n model.add(Dropout(0.25))\n\n model.add(Dense(128))\n model.add(LeakyReLU(alpha=0.1)) \n model.add(Dropout(0.1))\n\n model.add(Dense(self.action_size, activation='linear'))\n\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate), metrics=['accuracy'])\n model.summary()\n \n if os.path.isfile(self.weight_backup):\n model.load_weights(self.weight_backup)\n if not self.always_explore:\n self.exploration_rate = self.exploration_min\n \n return model\n\n # def to_grayscale(self, img):\n # return np.mean(img, axis=2).astype(np.uint8)\n\n # def downsample(self, img):\n # return img[::2, ::2]\n \n\n\n def save_model(self):\n rospy.loginfo(\"Model saved\") \n self.model.save(self.weight_backup)\n\n def act(self, state):\n if np.random.rand() <= self.exploration_rate:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0])\n \n def flip(self, actions, states, next_states, rewards, not_done):\n actions_flipped = 2-actions\n states_flipped = np.flip(states, axis=2)\n next_states_flipped = np.flip(next_states, axis=2)\n rewards_flipped = np.copy(rewards)\n \n next_pred_flipped = self.target_model.predict(next_states_flipped[not_done]).max(axis=1)\n rewards_flipped[not_done]+= self.gamma * next_pred_flipped\n targets_flipped = self.model.predict(states_flipped)\n targets_flipped[np.arange(len(actions_flipped)), actions_flipped] = rewards_flipped\n \n return states_flipped, targets_flipped\n\n def replay(self, new_data):\n rospy.loginfo(\"Replaying...\"), \n\n self.buffer.extend(new_data)\n buffer_length = self.buffer.length()\n \n chunks = buffer_length / self.chunk_size\n \n chunk_n = 2\n if chunks < 2:\n chunk_n = 1\n chunks=1\n print('buffer length', buffer_length)\n print('chunks', chunks)\n \n for i in np.random.choice(range(chunks), chunk_n, False):\n print('fitting', i)\n start_idx = i * self.chunk_size\n end_idx = start_idx + self.chunk_size\n \n loading_time = time.time()\n actions, states, next_states, rewards, terminates = self.buffer.sample(start_idx, end_idx)\n print('loading {} samples time: {}'.format(self.chunk_size, time.time()-loading_time))\n \n not_done = np.invert(terminates)\n rewards_new = np.copy(rewards)\n\n tmp_pred = self.target_model.predict(next_states[not_done], batch_size=1000)\n \n next_pred = tmp_pred.max(axis=1)\n rewards_new[not_done]+= self.gamma * next_pred\n targets = self.model.predict(states)\n targets[np.arange(len(actions)), actions] = rewards_new\n\n if self.add_flipped:\n states_flipped, targets_flipped = self.flip(actions, states, next_states, rewards, not_done)\n states = np.concatenate((states,states_flipped))\n targets = np.concatenate((targets,targets_flipped))\n fit_time = time.time()\n self.model.fit(states, targets, shuffle=True, batch_size=1000, epochs=1, verbose=0)\n print('fit time:', time.time()-fit_time)\n\n if self.training_count == 0 or self.training_count % 10 == 0: \n print('Updating weights')\n self.target_model.set_weights(self.model.get_weights())\n self.training_count+=1 \n \n if self.exploration_rate > self.exploration_min:\n self.exploration_rate *= self.exploration_decay\n\n self.save_model()\n ","sub_path":"neuroracer_gym_rl/scripts/double_dqn.py","file_name":"double_dqn.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395392372","text":"# Shapiro-Wilk Test\nfrom numpy.random import seed\nfrom numpy.random import randn\nfrom numpy import mean\nfrom numpy import float64\nfrom numpy import percentile\nfrom scipy.stats import shapiro\nimport xlrd\nimport xlwt\nfrom sklearn.utils import resample\n\ndataArr = []\nnd_result = []\nlowerArr = []\nupperArr = []\nfinal_alpha = 80\nworkbook = xlrd.open_workbook('survey.xlsx')\nworksheet = workbook.sheet_by_name(\"Op Survey Valid\")\n\n# Parsing each data point of the excel spreadsheet\nfor col in range(3, worksheet.ncols):\n data = []\n for row in range(1, worksheet.nrows - 3):\n # print(col)\n if (isinstance((worksheet.cell(row, col).value), float) == False):\n if((worksheet.cell(row, col).value == 'N/A')):\n continue\n else:\n break\n \n # changed N/A in survey to 0 to make things easier\n # if (worksheet.cell(row, col).value) == \"N/A\":\n # data.append(0)\n else:\n # print(col)\n # print(row)\n data.append(int(worksheet.cell(row, col).value))\n if data:\n dataArr.append(data)\n\n# Testing for normal distribution of each question dataset\nfor x in range(len(dataArr)):\n stat, p = shapiro(dataArr[x])\n # print('Statistics=%.3f, p=%.3f' % (stat, p))\n # interpret\n alpha = 0.05\n if p > alpha:\n # Sample looks Gaussian (fail to reject H0)\n nd_result.append(True)\n else:\n # Sample does not look Gaussian (reject H0)\n nd_result.append(False)\n\n# Get mean if normal distribution, and bootstrap if not normal distribution\nfor x in range(len(nd_result)):\n statistics = []\n if(nd_result[x] == True):\n lowerArr.append(mean(dataArr[x], dtype=float64))\n upperArr.append(mean(dataArr[x], dtype=float64))\n else:\n for i in range(1000):\n boot = resample(dataArr[x], replace=True, n_samples=60, random_state=None)\n statistics.append(mean(boot, dtype=float64))\n ordered = sorted(statistics)\n #80% confidence interval gives us lowerbound of 10% and upperbound of 90%\n lower = percentile(ordered, (100 - final_alpha)/2)\n upper = percentile(ordered, (final_alpha + ((100 - final_alpha)/2)))\n lowerArr.append(lower)\n upperArr.append(upper)\n\nprint(\"\\nSurvey Data Analysis Results\")\nprint(\"----------------------------\\n\")\nprint(\"Normal Distribution Shapiro-Wilk Test Results:\\n\")\nprint(str(nd_result) + \"\\n\\n\")\nprint(\"Lower-Bound Bootstrapped Means:\\n\")\nprint(str(lowerArr) + \"\\n\\n\")\nprint(\"Upper-Bound Bootstrapped Means:\\n\")\nprint(str(upperArr) + \"\\n\\n\")\n\n\n#print(len(statistics))\n# print(statistics)","sub_path":"stat-test.py","file_name":"stat-test.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396923615","text":"import datetime\nimport logging\nclass log:\n logname=''\n logger=''\n def __init__(self,logname):\n self.logname=logname\n logger = logging.getLogger(logname)\n logger.setLevel(logging.DEBUG)\n filehandle = logging.FileHandler('{}_{}.log'.format(datetime.datetime.now().strftime('%Y%m%d'),logname),\n mode='w',encoding='utf-8')\n filehandle.setLevel(logging.DEBUG)\n fomatter = logging.Formatter('%(asctime)s-%(filename)s[line:%(lineno)d]-%(name)s-%(levelname)s-:%(message)s')\n filehandle.setFormatter(fomatter)\n logger.addHandler(filehandle)\n self.logger=logger\n\n","sub_path":"logmodel.py","file_name":"logmodel.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"93943436","text":"from array import array\nimport ctypes\n\n\nclass Deltas: # Additions to original class\n def __init__(self):\n self.__indexesVec = array(\"f\")\n self.__valuesVec = array(\"f\")\n \n self.__maxDeltasNum = 500\n \n def getMaxDeltasNum(self):\n return self.__maxDeltasNum\n \n #The function adds a delta if there is a space and returns True, otherwise - False\n def addDelta(self, compressedIndexes, data):\n if(len(self.__valuesVec) >= self.__maxDeltasNum):\n return False\n self.__indexesVec.append(compressedIndexes)\n self.__valuesVec.append(data)\n return True\n \n #The function returns the deltas vector as float array in string, in format: \n def getAsString(self):\n deltas_str = \"\"\n for i in range(len(self.__indexesVec)):\n deltas_str += str(\"%.4f\" % float(self.__indexesVec[i]))\n deltas_str += str(\"%.4f\" % self.__valuesVec[i])\n deltas_str += str(\"%.4f\" % 0)\n deltas_str += \"*\"\n return deltas_str\n \n def clearDeltas(self):\n self.__indexesVec = array(\"f\")\n self.__valuesVec = array(\"f\")\n self.__deltasNum = 0\n","sub_path":"Delta.py","file_name":"Delta.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"596217491","text":"__author__ = 'dipsy'\n\n\nimport psycopg2\nimport psycopg2.extras\nimport sys\nfrom argparse import ArgumentParser\nimport json\nimport time\nimport datetime\nimport decimal\nclass DateTimeEncoder(json.JSONEncoder):\n\n def default(self, obj):\n if hasattr(obj, 'isoformat'):\n return obj.isoformat()\n elif isinstance(obj, decimal.Decimal):\n return float(obj)\n else:\n return json.JSONEncoder.default(self, obj)\n\nclass PostgresToCDR:\n def __init__(self, config):\n self.config = config\n self.connection = psycopg2.connect(self.__get_connection_string())\n self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)\n self.cursor.execute(\"SELECT * FROM \" + config.table)\n\n def __get_connection_string(self):\n return \"host='%s' dbname='%s' user='%s' password='%s'\" % (self.config.host,\n self.config.database,\n self.config.user,\n self.config.password)\n\n def next(self):\n row = self.cursor.fetchone()\n if row is not None:\n content = dict(row)\n json_res = {}\n timestamp = str(int(time.time() * 1000))\n json_res[\"timestamp\"] = timestamp\n json_res[\"content_type\"] = \"application/json\"\n #json_res[\"json_rep\"] = content\n json_res[\"raw_content\"] = json.dumps(content,cls=DateTimeEncoder)\n json_res[\"_id\"] = self.config.database + \"_\" + self.config.table + \"_\" + timestamp\n json_res[\"url\"] = \"http://effect.isi.edu/input/\" + self.config.database + \"/\" + self.config.table + \"/\" + timestamp\n json_res[\"version\"] = self.config.version\n json_res[\"team\"] = self.config.team\n json_res[\"source_name\"] = self.config.database + \"-\" + self.config.table\n return json_res\n\n return None\n\n def close(self):\n self.connection.close()\n\n\nif __name__ == \"__main__\":\n\n parser = ArgumentParser()\n parser.add_argument(\"-n\", \"--host\", help=\"PostgreSQL hostname\", default=\"localhost\", required=False)\n parser.add_argument(\"-u\", \"--user\", type=str, help=\"PostgreSQL username\", default=\"postgres\", required=False)\n parser.add_argument(\"-p\", \"--password\", type=str, help=\"PostgreSQL password\", default=\"postgres\", required=False)\n parser.add_argument(\"-d\", \"--database\", type=str, help=\"Database name\", required=True)\n parser.add_argument(\"-t\", \"--table\", type=str, help=\"Table name\", required=True)\n parser.add_argument(\"-o\", \"--output\", type=str, help=\"Output filename\", default=\"stdout\", required=False)\n parser.add_argument(\"-v\", \"--version\", type=str, help=\"CDR Version\", default=\"2.0\", required=False)\n parser.add_argument(\"-m\", \"--team\", type=str, help=\"Team that provided the data\", required=True)\n\n args = parser.parse_args()\n print (\"Got arguments:\", args)\n\n if args.output != 'stdout':\n out_file = open(args.output, 'w')\n\n def write_output(line):\n line = json.dumps(line)\n\n if args.output == 'stdout':\n print (line)\n else:\n out_file.write(line + \"\\n\")\n\n toCDR = PostgresToCDR(config=args)\n row = toCDR.next()\n while row is not None:\n write_output(row)\n row = toCDR.next()\n\n toCDR.close()\n\n if args.output != 'stdout':\n out_file.close()\n","sub_path":"postgresToCDR.py","file_name":"postgresToCDR.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"309893300","text":"import discord\nimport os\nimport quickstart\nimport csv\n\nfrom dotenv import load_dotenv\n\n\nload_dotenv()\ntoken = os.getenv('DISCORD_TOKEN')\n\n\nclass MyClient(discord.Client):\n async def on_ready(self):\n print('Logged on as {0}!'.format(self.user))\n\n async def on_message(self, message):\n if message.author == client.user:\n return\n \n if \"!create\" in message.content:\n date = message.content.split()[1]\n\n v = False\n with open('vlosheets.csv', 'r') as file:\n file.readline()\n for line in file:\n data = line.split(',')\n if(data[0] == date or data[0] == 'e'):\n event = \"- \" + date + \" \" + data[1] + \" - \" + data[2] + \" : \" + data[3] \n await message.channel.send(event)\n v = True\n \n if not v:\n await message.channel.send(\"There were no volunteer opportunities found for that date. Try creating a different event.\")\n else:\n await message.channel.send(\"These opportunities were found for your date! \\nReact a :thumbsup: to your favorite event to add to calendar.\")\n\n \n\n \n async def on_raw_reaction_add(self, payload):\n if str(payload.emoji) == \"👍\":\n dm = await payload.member.create_dm()\n s = await client.get_channel(payload.channel_id).fetch_message(payload.message_id)\n date = s.content.split()[1]\n start = s.content.split()[2]\n end = s.content.split()[4]\n event = \" \".join(s.content.split()[6:])\n\n def check(m):\n return m.channel == client.get_channel(dm.id) and m.author != client.user\n \n while True:\n await payload.member.dm_channel.send(\"You have chosen to participate in:\\n\" + s.content + \"\\nPlease provide a working Gmail.\")\n email = await client.wait_for('message', check=check)\n if \"@gmail.com\" in email.content:\n break\n\n \n quickstart.sendEvent(date, start, end, event, email.content)\n await payload.member.dm_channel.send(\"Please check your Google calendar; an event should be created! \\nThank you for giving back to the community!\")\n\n \n\n\nclient = MyClient()\nclient.run(token)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"625990229","text":"from gpiozero import Button\nfrom picamera import PiCamera\nimport RPi.GPIO as IO\nimport time\nfrom signal import pause\nimport os\nfrom Naked.toolshed.shell import execute_js, muterun_js\n\nIO.setwarnings(False) #do not show any warnings\nIO.setmode(IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN39 as 'GPIO19')\nIO.setup(19,IO.OUT) # initialize GPIO19 as an output.\nIO.setup(21,IO.IN) #initialize GPIO26 as input\nbutton = Button(21)\n\ncamera = PiCamera()\ncamera.resolution = (1280,720)\n\nwhile 1:\n diff = 0\n button.wait_for_press()\n start_time = time.time()\n \n while button.is_active:\n now_time = time.time()\n diff = -start_time+now_time\n\n if diff >= 5 : #long hold\n IO.output(19, True)\n camera.start_preview()\n button.wait_for_press(timeout=None)\n camera.capture(\"/home/pi/Desktop/test.jpg\")\n camera.stop_preview()\n IO.output(19, False)\n","sub_path":"PI1/Tests/testcamera.py","file_name":"testcamera.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"24622720","text":"dlouhy = 3000*'4'\r\numim = dict({42: '4'})\r\numim_nove = dict()\r\nwhile len(umim) != 2009:\r\n\tprint('LEN', len(umim))\r\n\tfor a, ar in umim.items():\r\n\t\tfor b, br in umim.items():\r\n\t\t\tnove = dict()\r\n\t\t\t#mozna neco prepisu, ale delka je stejna\r\n\t\t\tnove[(a + b) % 2009] = ar + br + '+'\r\n\t\t\tnove[(a - b) % 2009] = ar + br + '-'\r\n\t\t\tnove[(a * b) % 2009] = ar + br + '*'\r\n\t\t\tif b != 0:\r\n\t\t\t\tnove[int(a / b)] = ar + br + '/'\r\n\t\t\tfor n, r in nove.items():\r\n\t\t\t\tif not n in umim.keys():\r\n\t\t\t\t\tif n in umim_nove.keys():\r\n\t\t\t\t\t\tif len(umim_nove[n]) > len(r):\r\n\t\t\t\t\t\t\tumim_nove[n] = r\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tumim_nove[n] = r\r\n\t\t\t\telse:\r\n\t\t\t\t\tif len(umim[n]) > len(r):\r\n\t\t\t\t\t\tprint(n, r, 'FAIL')\r\n\t\t\t\t\t\tumim[n] = r\r\n\t\t\t\t\t\t#?????????????????\r\n\r\n\tfor n, r in umim_nove.items():\r\n\t\tumim[n] = r\r\n\tumim_nove = dict()\r\n\r\n#for k, v in umim.items():\r\n#\tprint(k, v)\r\n\r\nprint(max([len(v) for v in umim.values()]))\r\n\r\nwith open('abacus.txt', 'w') as file:\r\n\tfile.write('char R[2009][26] = { ')\r\n\tfile.write(','.join(['\"' + r + '\\\\0\"' for r in umim.values()]))\r\n\tfile.write(' };')\r\n\tprint('WRITTEN')\r\n","sub_path":"mff/codex/abacus/abacus.py","file_name":"abacus.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"7878796","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.\n\n\"\"\"Common Helper Functions for resilient-circuits\"\"\"\nimport sys\nimport pkg_resources\nimport logging\nimport copy\nimport re\n\nLOG = logging.getLogger(\"__name__\")\n\n\ndef get_fn_names(component):\n \"\"\"If `component` has a `function` attribute and it is True,\n appends the names in the function handler to `fn_names` and\n returns it, else returns an empty list.\n\n :param component: the component object to get it's list of function names for\n :type component: object\n :return: fn_names: the name in each function handler in the component if found\n :rtype: list\n \"\"\"\n\n assert isinstance(component, object)\n\n fn_names = []\n\n # Get a list of callable methods for this object\n methods = [a for a in dir(component) if callable(getattr(component, a))]\n\n for m in methods:\n this_method = getattr(component, m)\n is_function = getattr(this_method, \"function\", False)\n\n if is_function:\n fn_decorator_names = this_method.names\n # Fail if fn_decorator_names is not a tuple as may have unhandled side effects if a str etc.\n # When a function handler is decorated its __init__() function takes the '*args' parameter\n # When * is prepended, it is known as an unpacking operator to allow the function handler to have\n # multiple names. args (or names in our case) will be a tuple, so if the logic of the function\n # decorator changes, this will catch it.\n assert isinstance(fn_decorator_names, tuple)\n for n in fn_decorator_names:\n fn_names.append(n)\n\n return fn_names\n\n\ndef check_exists(key, dict_to_check):\n \"\"\"Returns the value of the key in dict_to_check if found,\n else returns False. If dict_to_check is None, returns False\n\n :param key: the key to look for in dict_to_check\n :type key: str\n :param dict_to_check: the key to look for in dict_to_check\n :type dict_to_check: dict\n :return: value of key in dict_to_check else False\n \"\"\"\n if dict_to_check is None:\n return False\n\n assert isinstance(dict_to_check, dict)\n\n return dict_to_check.get(key, False)\n\n\ndef validate_configs(configs, validate_dict):\n \"\"\"\n Checks if the configs are valid and raise a ValueError if they are not.\n Check if the config is required, has a value and meets its 'condition'\n\n :param configs: normally the configs in app.config\n :type configs: dict\n :param validate_dict: the key is the config and the value is a dict with the following params:\n - **required**: a boolean if the config is required\n - **placeholder_value**: the default value of the config that is not valid\n - **valid_condition**: a function to check if the value of the config is valid e.g. within a certain range\n - **invalid_msg**: displayed when valid_condition fails\n :type validate_dict: dict\n :return: nothing\n \"\"\"\n if not isinstance(configs, dict):\n raise ValueError(\"'configs' must be of type dict, not {0}\".format(type(configs)))\n\n if not isinstance(validate_dict, dict):\n raise ValueError(\"'validate_dict' must be of type dict, not {0}\".format(type(validate_dict)))\n\n for config_name, config_validations in validate_dict.items():\n\n required = config_validations.get(\"required\")\n placeholder_value = config_validations.get(\"placeholder_value\")\n valid_condition = config_validations.get(\"valid_condition\", lambda c: True)\n invalid_msg = config_validations.get(\"invalid_msg\", \"'{0}' did not pass it's validate condition\".format(config_name))\n\n # get the config value from configs\n config = configs.get(config_name)\n\n # if its required\n if required:\n\n # if not in configs or empty string\n if not config:\n raise ValueError(\"'{0}' is mandatory and is not set in the config file.\".format(config_name))\n\n # if still equals placeholder value\n if placeholder_value and config == placeholder_value:\n raise ValueError(\"'{0}' is mandatory and still has its placeholder value of '{1}' in the config file.\".format(config_name, placeholder_value))\n\n # if meets its valid_condition\n if not valid_condition(config):\n raise ValueError(invalid_msg)\n\n\ndef get_packages(working_set):\n \"\"\"\n Return a sorted list of tuples of all package names\n and their version in working_set\n\n :param working_set: the working_set for all packages installed in this env\n :type working_set: setuptools.pkg_resources.WorkingSet obj\n :return: pkg_list: a list of tuples [('name','version')] e.g. [('resilient-circuits', '39.0.0')]\n :rtype: list\n \"\"\"\n\n isinstance(working_set, pkg_resources.WorkingSet)\n\n pkg_list = []\n\n for pkg in working_set:\n pkg_list.append((pkg.project_name, pkg.version))\n\n return sorted(pkg_list, key=lambda x: x[0].lower())\n\n\ndef get_env_str(packages):\n \"\"\"\n Return a str with the Python version and the\n packages\n\n :param packages: the working_set for all packages installed in this env\n :type packages: setuptools.pkg_resources.WorkingSet obj\n :return: env_str: a str of the Environment\n :rtype: str\n \"\"\"\n\n env_str = u\"###############\\n\\nEnvironment:\\n\\n\"\n env_str += u\"Python Version: {0}\\n\\n\".format(sys.version)\n env_str += u\"Installed packages:\\n\"\n for pkg in get_packages(packages):\n env_str += u\"\\n\\t{0}: {1}\".format(pkg[0], pkg[1])\n env_str += u\"\\n###############\"\n return env_str\n\n\ndef remove_tag(original_res_obj):\n \"\"\"\n Return the original_res_obj with any of the \"tags\"\n attribute set to an empty list\n\n Example:\n ```\n mock_res_obj = {\n \"tags\": [{\"tag_handle\": \"fn_tag_test\", \"value\": None}],\n \"functions\": [\n {\"export_key\": \"fn_tag_test_function\",\n \"tags\": [{'tag_handle': 'fn_tag_test', 'value': None}]}\n ]\n }\n\n new_res_obj = remove_tag(mock_res_obj)\n\n Returns: {\n \"tags\": [],\n \"functions\": [\n {\"export_key\": \"fn_tag_test_function\", \"tags\": []}\n ]\n }\n ```\n :param original_res_obj: the res_obj you want to remove the tags attribute from\n :type original_res_obj: dict\n :return: new_res_obj: a dict with the tag attribute removed\n :rtype: dict\n \"\"\"\n ATTRIBUTE_NAME = \"tags\"\n\n new_res_obj = copy.deepcopy(original_res_obj)\n\n if isinstance(new_res_obj, dict):\n\n # Set \"tags\" to empty list\n if new_res_obj.get(ATTRIBUTE_NAME):\n new_res_obj[ATTRIBUTE_NAME] = []\n\n # Recursively loop the dict\n for obj_name, obj_value in new_res_obj.items():\n\n if isinstance(obj_value, list):\n for index, obj in enumerate(obj_value):\n new_res_obj[obj_name][index] = remove_tag(obj)\n\n elif isinstance(obj_value, dict):\n new_res_obj[obj_name] = remove_tag(obj_value)\n\n return new_res_obj\n","sub_path":"resilient-circuits/resilient_circuits/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":7067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"603270230","text":"import numpy as np\nimport os,sys, glob\nfrom matplotlib import pyplot as plt\nimport camera as cam\nimport stat_tools as st\nfrom scipy.ndimage import morphology,filters, sobel ####more efficient than skimage\nfrom skimage.morphology import remove_small_objects\nfrom collections import deque\nimport multiprocessing,subprocess,pickle\nimport time, geo\nfrom functools import reduce\nfrom operator import concat\n\nSAVE_FIG=True\nREPROCESS=False ####reprocess already processed file?\nMAX_INTERVAL = 179 ####max allowed interval between two frames for cloud motion estimation\ndeg2km=6367*np.pi/180\n\n\nall_cams=['HD5A', 'HD5B', 'HD4A','HD4B', 'HD3A', 'HD3B','HD2B', 'HD2C', 'HD1B', 'HD1C'];\nheight_group={'HD1B':['HD1C', 'HD2B'], 'HD1C':['HD1B', 'HD2C'], 'HD2B':['HD2C', 'HD3A'], 'HD2C':['HD2B', 'HD3B'],\\\n 'HD3A':['HD3B','HD4A'], 'HD3B':['HD3A', 'HD4B'], 'HD4A':['HD4B','HD5A'], 'HD4B':['HD4A', 'HD5A', 'HD3B'],\\\n 'HD5A':['HD5B', 'HD4A', 'HD4B'], 'HD5B':['HD5A', 'HD4B']}\nstitch_pair={'HD1B':'HD1C', 'HD1C':'HD1B','HD2B':'HD2C','HD2C':'HD2B','HD3A':'HD3B','HD3B':'HD3A', 'HD4A':'HD4B','HD4B':'HD4A', 'HD5A':'HD5B','HD5B':'HD5A'}\n# camIDs=[['HD1B','HD1C'],['HD2B','HD2C'],['HD3A','HD3B'],['HD4A','HD4B'],['HD5A','HD5B']];\ncamIDs=['HD1B','HD2B','HD3A','HD4A','HD5A'];\ncid_flat=camIDs+[stitch_pair[camID] for camID in camIDs]\n\n# days=['20180823124','20180829165'];\n# # days=['20180825161']; ####multilayer cloud\n# days=['20180829165']\n# days=['20180829162'] #####scattered cloud\ndays=['20181001141'] #####scattered cloud\n# days=['20180922150'] ####high clouds\n\ninpath='~/data/images/' \n# tmpfs='/dev/shm/'\ntmpfs='~/ldata/tmp/'\nstitch_path='~/ldata/stitch/'\n\n\ncameras={};\nfor camID in all_cams:\n cameras[camID] = cam.camera(camID,max_theta=70,nx=1000,ny=1000) \n\nlon0,lat0=cameras['HD5A'].lon,cameras['HD5B'].lat\nx_cams=(cameras['HD1B'].lon-lon0)*deg2km*np.cos(cameras['HD1B'].lat*np.pi/180)\ny_cams=(lat0-cameras['HD1B'].lat)*deg2km \n\n \ndef stitch(cams, dates): \n for day in dates: \n flist = sorted(glob.glob(inpath+camIDs[0]+'/'+day[:8]+'/'+camIDs[0]+'_'+day+'*jpg')) \n \n if len(flist)<=1:\n continue\n for f in flist[1:]:\n ymdhms=f[-18:-4]\n print('Processing',ymdhms)\n if os.path.isfile(stitch_path+ymdhms+'.sth') and (~REPROCESS): ######already processed, skip\n continue\n \n counter=0;\n selected=[]; imgs=[] \n for counter in range(20):\n pkls=sorted(glob.glob(tmpfs+day[:8]+'/HD*_'+ymdhms+'.hkl'));\n for pkl in pkls:\n camID=pkl[-23:-19]\n if camID not in cid_flat or camID in selected or stitch_pair[camID] in selected:\n continue;\n with open(pkl,'rb') as input:\n try:\n img=pickle.load(input)\n except EOFError:\n img=None\n if img is not None:\n imgs+=[img];\n selected += [camID] \n if len(selected)>=len(camIDs)-2:\n break;\n time.sleep(5); \n if len(imgs)<=0:\n continue\n# print(selected)\n \n h=[]; v=[]\n for i, img in enumerate(imgs):\n if np.isfinite(img.height): \n h += [img.height]\n if len(img.v)>=1: \n v += [img.v]\n if len(h)<=0 or len(v)<=0: ####clear sky\n h=[15]; \n v=[[0,0]];\n else:\n h=np.array(h)/1e3; v=np.array(v)\n h=np.nanmedian(h,axis=0); v=np.nanmedian(v,axis=0);\n \n max_tan=np.tan(imgs[0].max_theta*np.pi/180) \n for ilayer,height in enumerate(h):\n if np.isnan(h[ilayer]): continue\n stch=cam.stitch(ymdhms); \n stch.sz,stch.saz=imgs[0].sz,imgs[0].saz\n stch.height=height; stch.v=v\n \n pixel_size=2*h[ilayer]*max_tan/imgs[0].nx; \n stch.pixel_size=pixel_size;\n xlen,ylen=2*h[ilayer]*max_tan+x_cams, 2*h[ilayer]*max_tan+y_cams\n nstch_y,nstch_x=int(ylen//pixel_size),int(xlen//pixel_size)\n stch.lon=lon0-h[ilayer]*max_tan/deg2km/np.cos(cameras['HD3A'].lat*np.pi/180); \n stch.lat=lat0+h[ilayer]*max_tan/deg2km;\n# print(pixel_size,xlen,ylen)\n rgb=np.zeros((nstch_y,nstch_x,3),dtype=np.float32)\n cnt=np.zeros((nstch_y,nstch_x),dtype=np.uint8);\n cm=np.zeros((nstch_y,nstch_x),dtype=np.float32) \n for i, img in enumerate(imgs):\n start_x=(img.lon-lon0)*deg2km*np.cos(img.lat*np.pi/180)/pixel_size; start_x=int(start_x)\n start_y=(lat0-img.lat)*deg2km/pixel_size; start_y=int(start_y)\n \n tmp=np.flip(img.rgb,axis=1); #tmp[img.cm!=ilayer+1,:]=0; \n mk=tmp[...,0]>0\n# print(img.camID,ilayer,h[ilayer],start_x,start_y,mk.shape,stitched.shape)\n rgb[start_y:start_y+img.ny,start_x:start_x+img.nx][mk]+=tmp[mk]\n cnt[start_y:start_y+img.ny,start_x:start_x+img.nx]+=mk\n \n if (img.cm is not None):\n tmp=np.flip(img.cm,axis=1); #tmp[img.cm!=ilayer+1,:]=0; \n cm[start_y:start_y+img.ny,start_x:start_x+img.nx][mk]+=tmp[mk] \n \n for i in range(3):\n rgb[...,i]/=cnt\n cm/=cnt\n# fig,ax=plt.subplots(1,2); ax[0].imshow(cnt); ax[1].imshow(rgb.astype(np.uint8)); plt.show() \n stch.rgb=rgb.astype(np.uint8); stch.cm=(cm+0.5).astype(np.uint8)\n# stch.dump_stitch(stitch_path+'/'+day[:8]+'/'+ymdhms+'.sth');\n \n plt.figure(); plt.imshow(stch.rgb,extent=[0,xlen,ylen,0]);\n plt.xlabel('East distance, km'); plt.ylabel('South distance, km')\n plt.tight_layout();\n plt.show();\n# # fig.savefig(outpath+ymdhms); plt.close(); \n\n\ndef height(args):\n imager,neighbors,day=args \n \n ymd=day[:8]\n flist = sorted(glob.glob(inpath+imager.camID+'/'+ymd+'/'+imager.camID+'_'+day+'*jpg'))\n if len(flist)<=0:\n return\n \n for f in flist:\n basename=f[-23:-4]\n if os.path.isfile(tmpfs+f[-18:-10]+'/'+basename+'.hkl') and (~REPROCESS): ######already processed, skip\n continue \n \n# print('Procesing', basename)\n fpickle = glob.glob(tmpfs+f[-18:-10]+'/'+basename+'*pkl')\n img=None\n if len(fpickle)<=0:\n img=cam.preprocess(imager,f,tmpfs);\n else:\n with open(fpickle[0],'rb') as input:\n try:\n img=pickle.load(input);\n except EOFError:\n img=None \n if img is None or img.red is None:\n continue\n if img.layers<=0:\n img.dump_img(tmpfs+f[-18:-10]+'/'+f[-23:-4]+'.hkl');\n continue;\n\n if img.layers>=1:\n h = [np.nan]*img.layers\n for inghb,neighbor in enumerate(neighbors):\n bname=basename.replace(imager.camID,neighbor.camID);\n fp_nb = glob.glob(tmpfs+f[-18:-10]+'/'+bname+'*pkl') \n img1=None;\n if len(fp_nb)<=0:\n fnb=f.replace(imager.camID,neighbor.camID) \n img1=cam.preprocess(neighbor,fnb,tmpfs); ###img object contains four data fields: rgb, red, rbr, and cm \n else:\n with open(fp_nb[0],'rb') as input:\n try:\n img1=pickle.load(input);\n except EOFError:\n img1=None\n \n if img1 is None or img1.red is None:\n continue \n \n distance = 6367e3*geo.distance_sphere(img.lat,img.lon,img1.lat,img1.lon)\n for ih in range(img.layers):\n if np.isfinite(h[ih]):\n continue\n if (ih>=1) and (distance<500):\n break;\n res=cam.cloud_height(img,img1,layer=ih+1, distance=distance)\n if np.isfinite(res) and res<20*distance and res>0.5*distance:\n h[ih]=int(res);\n # print('Cloud height computed for', f[-23:]);\n # print('Cloud layer',ih+1,':',res,' computed with cameras ',img.camID,img1.camID,'(distance:',distance,'m)')\n if not SAVE_FIG:\n fig,ax=plt.subplots(2,2,figsize=(10,10),sharex=True,sharey=True);\n ax[0,0].imshow(img.rgb); ax[0,1].imshow(img1.rgb); \n ax[0,0].set_title(img.camID); ax[0,1].set_title(img1.camID)\n ax[1,0].imshow(img.cm); ax[1,1].imshow(img1.cm); \n ax[1,0].set_title(str(6367e3*geo.distance_sphere(img.lat,img.lon,img1.lat,img1.lon))) \n plt.tight_layout(); \n plt.show(); \n \n if np.isfinite(h[-1]): \n break \n# img.height+=[h];\n img.height=h;\n \n img.dump_img(tmpfs+f[-18:-10]+'/'+f[-23:-4]+'.hkl');\n\n\nif __name__ == \"__main__\": \n for day in days:\n if not os.path.isdir(stitch_path+day[:8]):\n try:\n subprocess.call(['mkdir', stitch_path+day[:8]]) \n except:\n print('Cannot create directory,',stitch_path+day[:8])\n continue \n p0=multiprocessing.Process(target=stitch, args=(camIDs, days,))\n p0.start(); \n\n p = multiprocessing.Pool(len(camIDs)) \n \n for day in days:\n if not os.path.isdir(tmpfs+day[:8]):\n try:\n subprocess.call(['mkdir', tmpfs+day[:8]]) \n except:\n print('Cannot create directory,',tmpfs+day[:8])\n continue \n# args=[[[camID for camID in camg], day] for camg in camIDs] \n args=[[cameras[camID], [cameras[cmr] for cmr in height_group[camID]], day] for camID in cid_flat] \n p.map(height,args) \n \n p0.join(); \n \n\n\n\n","sub_path":"code/preprocessing/stitch_demo.py","file_name":"stitch_demo.py","file_ext":"py","file_size_in_byte":10932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"391832771","text":"'''\nCreated on 14 de jul de 2016\n\n@author: romuere\n\natributos de textura multiescala // Anisotropia e Energia Total\n'''\nimport numpy as np\nimport pywt\nfrom skimage.color import rgb2gray\nfrom skimage.exposure import equalize_hist as histeq\nfrom scipy.misc import imresize\n\ndef wavelet_based(imagem,mascara,L):\n \n if (mascara == []):\n mascara = np.zeros((imagem.shape[0],imagem.shape[1]),dtype=np.uint8)+1;\n\n #imagem = rgb2gray(imagem);\n imagem = histeq(imagem);\n Niveis = L;\n EnergiaTotal = np.zeros(L);\n Anisotropia = np.zeros(L);\n textura = np.zeros(L*2)\n for i in range(L):\n cont = 0\n mascara = imresize(mascara,0.5)\n wp = pywt.WaveletPacket2D(data = imagem,wavelet = 'haar')\n CA = wp['a'].data\n CH = wp['h'].data\n CV = wp['v'].data\n CD = wp['d'].data\n l, m = mascara.shape\n EH = 0\n EV = 0\n ED = 0\n ch = CH**2\n cv = CV**2\n cd = CD**2 \n \n for p in range(l):\n for q in range(m):\n if(mascara[p,q]==1):\n EH += ch[p,q];\n EV += cv[p,q];\n ED += cd[p,q];\n cont += 1;\n\n EH = EH/cont;\n EV = EV/cont;\n ED = ED/cont;\n \n EnergiaTotal[i] = EH + EV + ED; \n DE = (EH - EV)**2 + (EH - ED)**2 + (EV - ED)**2;\n Anisotropia[i] = (1/EnergiaTotal[i])*(DE**0.5);\n imagem = [];\n imagem = CA;\n textura[(i*2):(i*2)+2] = [EnergiaTotal[i], Anisotropia[i]];\n \n return textura\n","sub_path":"classical/wavelet_based.py","file_name":"wavelet_based.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"196537088","text":"'''\nInput: a List of integers as well as an integer `k`\nrepresenting the size of the sliding window\nReturns: a List of integers\n'''\nfrom collections import deque\n\n\ndef sliding_window_max(nums, k):\n \"\"\" # len(nums) - k + 1 elements in the result array\n # window is smaller than the list size\n # window moves over 1 element at a time\n result = []\n for i in range(len(nums) - k + 1):\n # set max value to first element in the sliding window\n max_value = nums[i]\n # iterate over elements in the sliding window\n for j in range(i, i + k):\n # if the current element value is greater than the max\n # replace the max value with the current index value\n if nums[j] > max_value:\n max_value = nums[j]\n # aadd the max value from that window to the results list\n result.append(max_value)\n return result \"\"\"\n\n # create a double ended que of the size of our window\n # to keep track of the arr index from our window that\n # had the greatest value\n queue = deque()\n\n # create a list to store the max of each window position\n result = []\n\n # iterate through the first window of elements in the array\n for i in range(k):\n # we don't need to keep elements that are smaller than the current max\n while queue and nums[i] >= nums[queue[-1]]:\n queue.pop()\n\n # add the new element to the queue\n queue.append(i)\n\n # move the window through the rest of the array\n for i in range(k, len(nums)):\n\n # the max value of the window pass is at the front of the queue\n # we need to store this in the results list\n result.append(nums[queue[0]])\n\n # remove elements from the queue that are outside the current window\n while queue and queue[0] <= i - k:\n # remove from the front of the queue\n queue.popleft()\n\n # repeat the process of finding the max value in the window area\n # we don't need to keep elements that are smaller than the current max\n while queue and nums[i] >= nums[queue[-1]]:\n queue.pop()\n\n # add the new element to the queue\n queue.append(i)\n\n # store the max value from the last window\n result.append(nums[queue[0]])\n\n # return the result list\n return result\n\n\nif __name__ == '__main__':\n # Use the main function here to test out your implementation\n arr = [1, 3, -1, -3, 5, 3, 6, 7]\n k = 3\n\n print(\n f\"Output of sliding_window_max function is: {sliding_window_max(arr, k)}\")\n","sub_path":"sliding_window_max/sliding_window_max.py","file_name":"sliding_window_max.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"291284787","text":"from db.services import PageService, LocationService, WordService\nfrom db.session import get_session\nfrom db.models import Page, Location, Word\n\nsession = get_session()\nlocation_service = LocationService(session)\nword_service = WordService(session)\npage_service = PageService(session)\n\n\n\nword_1 = word_service.find(stem=\"the\")\nword_2 = word_service.find(stem=\"of\")\nword_3 = word_service.find(stem=\"analysing\")\nwords = [word_1, word_2, word_3]\npage = page_service.find(url=\"https://willthishappen.com/us-president-2020-female\")\n\n\ndistance = 0 \nfor word, next_word in zip(words, words[1:]):\n position_word = session.query(Location).filter_by(page=page, word=word).order_by(Location.position).first().position\n position_next_word = session.query(Location).filter_by(page=page, word=next_word).order_by(Location.position).first().position\n distance += abs(position_word - position_next_word)\n","sub_path":"m.py","file_name":"m.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"225219718","text":"\"\"\"\n==========\nColor Demo\n==========\n\nmatplotlib gives you 5 ways to specify colors,\n\n 1) as a single letter string, ala MATLAB\n\n 2) as an html style hex string or html color name\n\n 3) as an R,G,B tuple, where R,G,B, range from 0-1\n\n 4) as a string representing a floating point number\n from 0 to 1, corresponding to shades of gray.\n\n 5) as a special color \"Cn\", where n is a number 0-9 specifying the\n nth color in the currently active color cycle.\n\nSee help(colors) for more info.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nt = np.arange(0.0, 2.0, 0.01)\ns = np.sin(2 * np.pi * t)\n\nfig, ax = plt.subplots(facecolor='darkslategray')\nax.plot(t, s, 'C1')\nax.set_xlabel('time (s)', color='C1')\nax.set_ylabel('voltage (mV)', color='0.5') # grayscale color\nax.set_title('About as silly as it gets, folks', color='#afeeee')\n\nplt.show()\n","sub_path":"Packages/matplotlib-2.2.2/examples/color/color_demo.py","file_name":"color_demo.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"76105939","text":"### TP2 exercice 3 ###\n__author__='Antoine-Alexis Bourdon '\n__date__='01/02/2018'\n\n##Module:\nfrom random import *\n\n##Variables:\nPointCarte = {\"7\":0,\"8\":0,\"9\":0,\"10\":10,\"Valet\":2,\"Dame\":3,\"Roi\":4,\"As\":11}\nPointCarteAtout = {\"7\":0,\"8\":0,\"9\":14,\"10\":4,\"Valet\":20,\"Dame\":0,\"Roi\":2,\"As\":4}\n\n##Constante:\nCOULEUR = [\"Trèfle\",\"Carreau\",\"Coeur\",\"Piqure\"]\n\n###Class Carte:\nclass Carte:\n\t'''Classe pour la construction des cartes de belote.'''\n\tdef __init__(self, couleur, hauteur, atout = False):\n\t\t'''constructeur pour la classe carte\n\t\tArguments:\n\t\t\tCarte(modif).\n\t\t\tcouleur : --str.\n\t\t\thauteur : --str.\n\t\t\tatout : --boolean.\n\t\tRetour :\n\t\t\tNone.\n\t\t'''\n\t\tself.__couleur = couleur\n\t\tself.__hauteur = hauteur\n\t\tself.__atout = atout\n\n\tdef affiche(self):\n\t\t'''Méthode pour afficher une carte.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tNone.\n\t\t'''\n\t\tprint(self.str())\n\n\tdef str(self):\n\t\t'''Méthode qui retourne la hauteur et la couleur de la carte.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tCarte(hauteur / couleur) : --str\n\t\t'''\n\t\treturn str(self.__hauteur) + \" de \" + str(self.__couleur)\n\n\tdef couleur(self):\n\t\t'''Méthode qui retourne la couleur de la carte.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tCarte(couleur) --str\n\t\t'''\n\t\treturn self.__couleur\n\n\tdef hauteur(self):\n\t\t'''Méthode qui retourne la hauteur de la carte.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tCarte(hauteur) --str\n\t\t'''\n\t\treturn self.__hauteur\n\n\tdef estAtout(self):\n\t\t'''Méthode qui indique si la carte est un atout\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tCarte(atout) --str\n\t\t'''\n\t\treturn self.__atout\n\n\tdef nbrePoints(self):\n\t\t'''Méthode qui retourne le nombre de point de la carte.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tCarte(hauteur) : --int\n\t\t'''\n\t\tif self.__atout:\n\t\t\treturn PointCarteAtout[self.__hauteur]\n\t\treturn PointCarte[self.__hauteur]\n\n\tdef est_plus_grand(self, carte):\n\t\t'''Méthode qui teste si une carte est plus grand qu'une autre.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tboolean\n\t\t'''\n\t\treturn self.nbrePoints() > carte.nbrePoints()\n\n\n\tdef est_egal(self, carte):\n\t\t'''Méthode qui teste si une carteest égal à une autre.\n\t\tArgument :\n\t\t\tCarte\n\t\tRetour :\n\t\t\tboolean\n\t\t'''\n\t\treturn self.nbrePoints() == carte.nbrePoints()\n\n\ndef affiche_jeu(liste):\n\t'''affiche la liste des cartes.\n\tArgument :\n\t\tliste --list\n\tretour :\n\t\tNone\n\t'''\n\tretour = \"[\"\n\tfor lis in liste:\n\t\tretour += lis.str() + \",\"\n\tretour += \"]\"\n\tprint(retour)\n\n\ndef creer_jeu_de_belote():\n\t'''fonction qui crée un jeu de cartes pour la belote.\n\tAtout aléa.\n\tArgument :\n\t\tNone.\n\tRetour :\n\t\tliste : --list\n\t'''\n\tliste = []\n\tfor couleur in COULEUR:\n\t\tfor hauteur in PointCarte.keys():\n\t\t\tatout = randint(0,1)\n\t\t\tliste.append(Carte(couleur,hauteur, atout == 1))\n\treturn liste\n\n\ndef main():\n\t'''Fonction principale\n\tArgument :\n\t\tNone\n\tRetour :\n\t\tNone\n\t'''\n\tprint('''\n\t ############################\n\t # Programme Principal TEST #\n\t ############################\n\t''')\n\tbelote = creer_jeu_de_belote()\n\tprint('''\n\t #######################\n\t # Affiche Jeu #\n\t #######################\n\t''')\n\taffiche_jeu(belote)\n\tprint('''\n\t ######################\n\t # belote[7].str() #\n\t ######################\n\t''')\n\tprint(belote[7].str())\n\tprint('''\n ####################### \n # belote[15].str() #\n ####################### \n ''')\n\n\tprint(belote[15].str())\n\tprint('''\n ############################# \n # [15].est_egal(belote[7]) #\n ############################# \n ''')\n\n\tprint(belote[15].est_egal(belote[7]))\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"L1/semestre2/algo2/TPs/TP2/exercice3.py","file_name":"exercice3.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"482569562","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#Defino la función para dibujar la red\ndef net_drawing(G,pos,labels,title):\n nx.draw_networkx_labels(G, pos=pos, labels=labels)\n nx.draw(G, pos=pos, node_size=10, width=0.5)\n plt.title(title)\n plt.show()\n plt.clf()\n\n#Defino la función para hacer el intercambio de agentes\ndef swap(G, matrix):\n #Hallo la suma de los pesos alrededor de cada nodo\n suma = []\n for i in range(len(matrix)):\n suma.append(np.sum(matrix[i]))\n\n '''\n Obtengo los diccionarios con los Susceptibles, Expuestos, Infectados y\n Recuperados de cada nodo\n '''\n sus = nx.get_node_attributes(G,'Susceptibles')\n exp = nx.get_node_attributes(G,'Expuestos')\n inf = nx.get_node_attributes(G,'Infectados')\n rec = nx.get_node_attributes(G,'Recuperados')\n\n '''\n Defino unos diccionarios donde pondré los nuevos Susceptibles, Expuestos,\n Infectados y Recuperados de cada nodo\n '''\n asus = {}\n aexp = {}\n ainf = {}\n arec = {}\n \n #Defino la proporción de personas de cada tipo que se van y las resto\n for i in range(len(matrix)):\n total = sus[i] + exp[i] + inf[i] + rec[i]\n value = suma[i]\n asus[i] = (sus[i]/total)*value\n sus[i] -= asus[i]\n aexp[i] = (exp[i]/total)*value\n exp[i] -= aexp[i]\n ainf[i] = (inf[i]/total)*value\n inf[i] -= ainf[i]\n arec[i] = (rec[i]/total)*value\n rec[i] -= arec[i]\n\n #Hago la asignación de esas personas a los nuevos nodos\n for i in range(len(matrix)):\n #Hago el ciclo sobre los vecinos del nodo\n for j in range(len(matrix)):\n value = matrix.item((i,j))/suma[i]\n sus[j] += value*asus[i]\n exp[j] += value*aexp[i]\n inf[j] += value*ainf[i]\n rec[j] += value*arec[i]\n\n #Le asigno los nuevos valores de las personas a los nodos\n nx.set_node_attributes(G, sus, 'Susceptibles')\n nx.set_node_attributes(G, exp, 'Expuestos')\n nx.set_node_attributes(G, inf, 'Infectados')\n nx.set_node_attributes(G, rec, 'Recuperados')\n\n return G\n\n#Esta función me imprime los datos de las características de los nodos\ndef print_data(i,NS,NE,NI,NR):\n with open(\"Data_1/node_\" + str(i) + \".csv\", \"a\") as myfile:\n for j in range(len(NS)):\n myfile.write(str(NS[j]) + '\\t' + str(NE[j]) + '\\t' + str(NI[j]) + '\\t' + str(NR[j]) + '\\n')\n","sub_path":"Colombia_Dep/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"46068138","text":"'''\n由自己的手写数据生成 images 和 labels 并保存\n'''\n\n\nimport os\nfrom PIL import Image\nimport numpy as np\n\n\nclass NoDataError(Exception):\n\tpass\n\n\ndef img_box(img):\n\tindex=np.where(img)\n\tweight=img[index]\n\tindex_x_mean=np.average(index[1],weights=weight)\n\tindex_y_mean=np.average(index[0],weights=weight)\n\tindex_xy_std=np.sqrt(np.average(((index[1]-index_x_mean)**2+\n\t\t\t\t\t(index[0]-index_y_mean)**2)/2,weights=weight))\n\tbox=(index_x_mean-3*index_xy_std,index_y_mean-3*index_xy_std,\n\t\t\tindex_x_mean+3*index_xy_std,index_y_mean+3*index_xy_std)\t\n\treturn box\n\t\n\t\ndef normalize_image(image):\n\timg0=255-np.array(image)\n\timg1=np.where(img0>=100,img0,0)\n\timg2=Image.fromarray(img1)\n\tbox=img_box(img1)\n\tcrop_img=img2.crop(box)\n\tnorm_img=crop_img.resize((28,28))\n\tnorm_array=np.array(norm_img).flatten()/255\n\treturn norm_array\n\t\n\t\ndef format_handwriting(dirpath):\n\torigin_images,images,labels=[],[],[]\n\tfor num in range(10):\n\t\tdirname='write_{}'.format(num)\n\t\tfilepath=os.path.join(dirpath,dirname)\n\t\tfor filename in os.scandir(filepath):\n\t\t\tif filename.is_file():\n\t\t\t\torigin_img=Image.open(os.path.join(filename))\n\t\t\t\timage_fig=Image.open(os.path.join(filename)).convert('L')\n\t\t\t\timage_ary=normalize_image(image_fig)\n\t\t\t\torigin_images.append(np.array(origin_img))\n\t\t\t\timages.append(image_ary)\n\t\t\t\tlabels.append(num)\n\torigin_images=np.array(origin_images)\n\timages=np.array(images)\n\tlabels=np.array(labels)\n\treturn origin_images,images,labels\n\t\n\t\ndef save_handwriting(dirpath,filename='handwriting.npz'):\n\torigin_images,images,labels=format_handwriting(dirpath)\n\tfilepath=os.path.join(dirpath,'npz')\n\tfile=os.path.join(filepath,filename)\n\tnp.savez(file,origin_images=origin_images,images=images,labels=labels)\n\t\n\t\ndef load_handwriting(dirpath,filename='handwriting.npz'):\n\tfilepath=os.path.join(dirpath,'npz')\n\tfile=os.path.join(filepath,filename)\n\tif os.path.exists(file):\n\t\thandwriting=np.load(file, allow_pickle=True)\n\t\treturn handwriting\n\telse:\n\t\traise NoDataError(f'手写数据文件:{os.path.join(filepath,filename)} 不存在')\n\n\t\t\ndef main():\n\tsave_handwriting('../../data/my_handwriting')\n\n\nif __name__=='__main__':\n\tmain()\n","sub_path":"src/numpy_deomo/py_model/MY_handwriting.py","file_name":"MY_handwriting.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"566450710","text":"import sqlite3\n\nconn = sqlite3.connect('friends.sqlite')\ncur = conn.cursor()\n\ncur.execute('SELECT * FROM Osoby')\ncount = 0\nprint('Osoby:')\nfor row in cur:\n if count < 5: print(row)\n count = count + 1\nprint(count, 'wierszy.')\n\ncur.execute('SELECT * FROM Obserwuje')\ncount = 0\nprint('\\nObserwuje:')\nfor row in cur:\n if count < 5: print(row)\n count = count + 1\nprint(count, 'wierszy.')\n\ncur.execute('''SELECT * FROM Obserwuje JOIN Osoby\n ON Obserwuje.id_do = Osoby.id\n WHERE Obserwuje.id_od = 2''')\ncount = 0\nprint('\\nPołączenia dla id=2:')\nfor row in cur:\n if count < 5: print(row)\n count = count + 1\nprint(count, 'wierszy.')\n\ncur.close()\n","sub_path":"code3/twjoin.py","file_name":"twjoin.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"71110381","text":"#!/usr/bin/env python\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Acknowledgement: Part of the codes are borrowed or adapted from Bruno Korbar\n\nimport sys\nimport os\nimport logging\n\n\ndef setup_tbx(save_dir, is_master):\n from tensorboardX import SummaryWriter\n\n if not is_master:\n return None\n\n writer = SummaryWriter(save_dir)\n return writer\n\n\ndef setup_logger(name, save_dir, is_master, logname=\"run.log\"):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n # don't log results for the non-master process\n if not is_master:\n return logger\n ch = logging.StreamHandler(stream=sys.stdout)\n formatter = MyFormatter()\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n if save_dir:\n fh = logging.FileHandler(os.path.join(save_dir, logname))\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n return logger\n\n\n# Custom formatter\nclass MyFormatter(logging.Formatter):\n\n err_fmt = \"%(asctime)s %(name)s %(module)s: %(lineno)d: %(levelname)s: %(msg)s\"\n dbg_fmt = \"%(asctime)s %(module)s: %(lineno)d: %(levelname)s:: %(msg)s\"\n info_fmt = \"%(msg)s\"\n\n def __init__(self):\n super().__init__(fmt=\"%(asctime)s %(name)s %(levelname)s: %(message)s\",\n datefmt=None,\n style='%')\n\n def format(self, record):\n\n # Save the original format configured by the user\n # when the logger formatter was instantiated\n format_orig = self._style._fmt\n\n # Replace the original format with one customized by logging level\n if record.levelno == logging.DEBUG:\n self._style._fmt = MyFormatter.dbg_fmt\n\n elif record.levelno == logging.INFO:\n self._style._fmt = MyFormatter.info_fmt\n\n elif record.levelno == logging.ERROR:\n self._style._fmt = MyFormatter.err_fmt\n\n # Call the original formatter class to do the grunt work\n result = logging.Formatter.format(self, record)\n\n # Restore the original format configured by the user\n self._style._fmt = format_orig\n\n return result\n","sub_path":"listen_to_look_single_modality/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341810471","text":"import os\nimport numpy as np\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nfrom threedee_tools.datasets import CubeGenerator, RandomSingleViewGenerator, ConstantShapeGenerator\nfrom threedee_tools.reinforce import REINFORCE\nfrom threedee_tools.renderer import Renderer\n\nGAMMA = 1 # discount factor - doesn't apply here\nSEED = 123\nNUM_STEPS = 100 # episode steps\nNUM_EPISODES = 1000\nHIDDEN_SIZE = 128\nCHKP_FREQ = 100 # model saving freq\nWIDTH = 64\nHEIGHT = 64\nREWARD_BUF = 1000\n\nnpa = np.array\n\nfrom hyperdash import Experiment\n\nexp = Experiment(\"3DR-16-constant-shape\")\n\n\nclass Policy(nn.Module):\n def __init__(self, hidden_size, num_inputs, num_outputs):\n super(Policy, self).__init__()\n\n self.linear1 = nn.Linear(num_inputs, hidden_size)\n self.linear2 = nn.Linear(hidden_size, hidden_size)\n self.linear3 = nn.Linear(hidden_size, num_outputs)\n self.linear3_ = nn.Linear(hidden_size, num_outputs)\n\n def forward(self, inputs):\n x = inputs\n x = F.relu(self.linear1(x))\n x = F.relu(self.linear2(x))\n mu = torch.sigmoid(self.linear3(x))\n sigma_sq = torch.tanh(self.linear3_(x))\n\n return mu, sigma_sq\n\n\nenv = Renderer(WIDTH, HEIGHT)\n\ndata_generator = ConstantShapeGenerator(WIDTH, HEIGHT)\n\ntorch.manual_seed(SEED)\nnp.random.seed(SEED)\n\nagent = REINFORCE(HIDDEN_SIZE, WIDTH * HEIGHT * 3, 160, Policy)\n\ndir = 'ckpt_3dreinforcev3'\nif not os.path.exists(dir):\n os.mkdir(dir)\n\nreward_avg = []\n\nfor i_episode in range(NUM_EPISODES):\n target = data_generator.sample()\n env_state = np.ones(160, dtype=np.float32) * .5\n env_rot = np.zeros(3, dtype=np.float32)\n state = torch.Tensor([npa(target)]).view(-1)\n if torch.cuda.is_available():\n state = state.cuda()\n entropies = []\n log_probs = []\n rewards = []\n reward_raw_log = [] # just for logging purposes\n\n for t in range(NUM_STEPS):\n action, log_prob, entropy = agent.select_action(state)\n action = action.cpu()\n\n next_state = env.render(action, data_generator.cam)\n\n reward_raw = -np.linalg.norm(npa(target) - npa(next_state)).sum()\n reward_raw_log.append(reward_raw)\n\n if len(reward_avg) == 0:\n reward = reward_raw\n else:\n reward = reward_raw - np.mean(reward_avg)\n\n # update running mean\n reward_avg.append(reward_raw)\n if len(reward_avg) > REWARD_BUF:\n reward_avg.pop(0)\n\n rewards.append(reward)\n entropies.append(entropy)\n log_probs.append(log_prob)\n\n agent.update_parameters(rewards, log_probs, entropies, GAMMA)\n\n if i_episode % CHKP_FREQ == 0:\n torch.save(agent.model.state_dict(), os.path.join(dir, 'reinforce-' + str(i_episode) + '.pkl'))\n\n # print(\"Episode: {}, reward: {}\".format(i_episode, np.sum(rewards)))\n exp.metric(\"episode\", i_episode)\n exp.metric(\"rewards\", np.mean(reward_raw_log))\n\n del rewards\n del log_probs\n del entropies\n del state","sub_path":"scripts/16-r-single-view-constant-shape.py","file_name":"16-r-single-view-constant-shape.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"589370151","text":"import pygame\n\ndef main():\n width = 520\n height = 520\n monster_x = 0\n monster_y = 0\n \n monster_dir_x = 5\n monster_dir_y = 5\n change_dir_countdown = 120\n gob_dir_x = 500\n gob_dir_y = 500\n pygame.init()\n screen = pygame.display.set_mode((width, height))\n background_image = pygame.image.load('images/background.png').convert_alpha()\n pygame.display.set_caption('My Game')\n clock = pygame.time.Clock()\n monster = pygame.image.load('images/monster.png').convert_alpha()\n goblin = pygame.image.load('images/goblin.png').convert_alpha()\n hero = pygame.image.load('images/hero.png').convert_alpha()\n\n # Game initialization\n\n stop_game = False\n while not stop_game:\n for event in pygame.event.get():\n\n # Event handling\n\n if event.type == pygame.QUIT:\n stop_game = True\n\n\n # Game logic\n monster_x += monster_dir_x\n monster_y += monster_dir_y\n\n change_dir_countdown -= 1\n # Draw background\n screen.blit(background_image, (0, 0))\n screen.blit(monster, (monster_x, monster_y))\n screen.blit(hero, (260, 200))\n \n\n\n\n # Game display\n\n pygame.display.update()\n clock.tick(60)\n if monster_x >= (width - 75):\n monster_dir_x = -monster_dir_x\n monster_x = 500 - 75\n if monster_y >= (height - 75):\n monster_dir_y = -monster_dir_y\n monster_y = 500 - 75\n if monster_x <= 0:\n monster_dir_x = -monster_dir_x\n monster_x = 0\n if monster_y <= 0:\n monster_dir_y = -monster_dir_y\n monster_y = 0\n \n \n \n\n pygame.quit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"pygame/pygame-project/monster2.py","file_name":"monster2.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"448389519","text":"#!/usr/bin/env python3\n\nprint(f\"Mahlet Amare\")\n\nwith open(\"slicing-file.txt\", \"r\") as hFile:\n listfile = hFile.readlines()\n \n# Get the third word from the end of the list\n word1 = listfile[-3]\n aword1 = word1.replace('\\n', '')\n print(aword1)\n\n# Get the third through fifth word of the list\n word2 = listfile[2:5]\n s = \" \"\n nword2 = (s.join(word2))\n anword2 = nword2.replace('\\n', '')\n print(anword2)\n \n# Get the 10th word from the end of the file and every other word for 3 words\n o = \" \"\n word3 = listfile[-10:12:-2]\n nword3 = (o.join(word3))\n anword3 = nword3.replace('\\n', '')\n print(anword3)\n\n# Get the 11th though 13th word\n y = \" \"\n word4 = listfile[10:13]\n nword4 = (y.join(word4))\n anword4 = nword4.replace('\\n', '')\n print(anword4)\n# Get the 19th-21st words from the end of the file\n w = \" \"\n word5 = listfile[-19:-22:-1]\n nword5 = (w.join(word5))\n anword5 = nword5.replace('\\n','')\n print(anword5)\n# Create qoute and concatinate all the variables\n qoute = aword1 + \" \" + anword2 + \" \"+ anword3 + \" \" + anword4 + \" \" + anword5 \n print(qoute) \n \n \n","sub_path":"midterm-slicing.py","file_name":"midterm-slicing.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"625958022","text":"from collections import defaultdict\n\n\"\"\"\nTC: O(n)\nSC: O(n)\n\"\"\"\n\n\nclass SkipIterator:\n def __init__(self, nums):\n self.next_element = None\n self.iterator = iter(nums)\n self.hash_map = defaultdict(int)\n self.move_forward()\n\n def has_next(self):\n return self.next_element != None\n\n def next_(self):\n temp = self.next_element\n self.move_forward()\n return temp\n\n def skip(self, num):\n if num == self.next_element:\n self.move_forward()\n else:\n self.hash_map[num] += 1\n\n def move_forward(self):\n self.next_element = None\n next_of_iterator = next(self.iterator, None)\n while not self.next_element and next_of_iterator: # no iterator has next in py so get next before has and check\n if next_of_iterator not in self.hash_map:\n self.next_element = next_of_iterator\n else:\n self.hash_map[num] -= 1\n if self.hash_map[num] == 0:\n del self.hash_map[num]\n next_of_iterator = next(self.iterator, None) # update next\n\n\nit = SkipIterator(iter([5, 6, 7, 5, 6, 8, 9, 5, 5, 6]))\nprint(it.has_next())\nit.skip(5)\nprint(it.next_())\nit.skip(7)\nprint(it.next_())\nprint(it.next_())\nprint(it.next_())\nprint(it.next_())\nit.skip(1)\nit.skip(3)\nprint(it.has_next())","sub_path":"Problem-2.py","file_name":"Problem-2.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"579635823","text":"import phonenumbers\n\nfrom .base import Detector\nfrom ..implement import PhoneImplement\n\n\nclass PhoneDetector(Detector):\n \"\"\"Remove phone numbers from dirty dirty ``text`` using\n `python-phonenumbers\n `_, a port of a\n Google project to correctly format phone numbers in text.\n\n ``region`` specifies the best guess region to start with (default:\n ``\"US\"``). Specify ``None`` to only consider numbers with a leading\n ``+`` to be considered.\n \"\"\"\n filth_cls = PhoneImplement\n region = 'CN'\n\n def iter_filth(self, text):\n # create a copy of text to handle multiple phone numbers correctly\n for match in phonenumbers.PhoneNumberMatcher(text, self.region):\n print(\"mobile para:\",match.start,\" \",match.end,\" \",match.raw_string)\n yield PhoneImplement(\n beg=match.start,\n end=match.end,\n text=match.raw_string,\n )\n","sub_path":"desensitize/detectors/phone.py","file_name":"phone.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"287653860","text":"'''This script predicts temperature from three different machine learning models.\n The models are hosted on amazon s3 bucket\n Before starting, you should:\n 1)If not done, upload your dataset to your s3 bucket\n 2) Set the s3 bucket credentials (access key id and secret access key).\n *If you don't have these credentials, please follow the first part of this tutorial to get them https://realpython.com/python-boto3-aws-s3/\n 3)Change the s3_bucket parameter to your bucket name\n 4) Set your dataset name as hosted on your bucket (change the input_name parameter)\n'''\n\n#Set the s3 credentials\naws_key_id='', #Change here, set your s3 access key id\naws_secret_key='', #Change here, set your s3 secret access key\n\n#Set the bucket and input file name\ns3_bucket = '' #Change here, set your bucket name\ninput_name = '' #Change here. Set your input file name that will be predicted (file needs to be hosted on s3 bucket)\n\n#Don't change, these are the parameters asked by the assignment.\noutput_name = 'result.csv' #Output file for results after predicting\nmodel1 = 'https://log8415-tp2-ml.s3.amazonaws.com/model1.pkl' #Model 1: SVM. Don't change\nmodel2 = 'https://log8415-tp2-ml.s3.amazonaws.com/model2.pkl' #Model 2: RandomForestClassifier. Don't change\nmodel3 = 'https://log8415-tp2-ml.s3.amazonaws.com/model3.pkl' #Model 3: DecisionTreeClassifier. Don't change\n\n'''-------------------------------------------------------------------------'''\nimport pyspark\nfrom pyspark import SparkContext\nsc =SparkContext()\nprint('------Installing required libraries------')\ndef install(package_name):\n try:\n sc.install_pypi_package(package_name)\n except:\n print(package_name + \" is already installed\")\npkgs = ['wget', 'boto3', 'pandas', 'scikit-learn', 'pickle']\nfor pkg in pkgs:\n install(pkg)\n\nimport boto3\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.metrics import accuracy_score\nimport pickle\nimport sys\nimport wget\n\nprint('------Starting the script----------------')\n#Initialising the connection to the s3 client.\ntry:\n print('Initialising the s3 bucket...', end =\" \"),\n s3 = boto3.client(\n 's3',\n aws_access_key_id=''.join(aws_key_id), #your s3 access key id\n aws_secret_access_key=''.join(aws_secret_key), #your s3 secret access key\n )\n print('DONE')\nexcept Exception as e:\n print('Error! Did you set the s3 credentials correctly?')\n print(e)\n sys.exit('Please open the script and set the credentials. Exiting...')\n\n#This function takes as input a panda Series (column) and categorize that column from verycold to veryhot\ndef categorizeTemp(column):\n temp_cat = column.apply(\n lambda x: 'verycold' if x <0 else (\n 'cold' if 0<=x< 10 else (\n 'moderate' if 10<=x<20 else (\n 'hot' if 20<=x<30 else 'veryhot'))))\n return temp_cat\n\n# Function for Encoding String values into numerical values\ndef encode(data, columns):\n for column in columns:\n encs = {}\n encs[column] = LabelEncoder()\n data[column] = encs[column].fit_transform(data[column])\n return encs\n\n# unEncoding back numerical values into String values\ndef unencode(enc, data, columns):\n for column in columns:\n data[column] = enc.inverse_transform(data[column])\n\nprint(\"Reading input file...\", end =\" \"),\ntry:\n s3.download_file(s3_bucket, input_name,\"data.csv\")\n df = pd.read_csv('data.csv')\n print('DONE')\nexcept:\n sys.exit('Error! Please specify your s3 bucket name (s3_bucket) and/or your input file name (input_name). Exiting... %tb')\n\nprint('Starting Data preprocessing...')\nprint(' +Removing unecessary columns No, PM2.5, PM10, SO2, NO2, CO and O3...', end =\" \"),\ntry:\n cols = ['No','PM2.5','PM10','SO2','NO2','CO','O3']\n data = df.drop(cols,axis=1)\nexcept:\n sys.exit('Error! The dataset should have the same columns as those given during the assignment. Exiting...')\nprint('DONE')\n\nprint(' +Dropping NaN values...'.ljust(10), end =\" \")\ndata = data.dropna()\nprint('DONE')\n\nprint(' +Categorizing temperature column TEMP from verycold to veryhot...', end =\" \"),\ndata.TEMP = categorizeTemp(data.TEMP)\nprint('DONE')\n\nprint(' +Encoding String values into numerical values (wd, station and TEMP)', end =\" \"),\nencs = encode(data, ['wd', 'station', 'TEMP'])\nprint('DONE')\n\nprint(' +Applying feature scalling for data normalization...', end =\" \")\nscaler = StandardScaler()\nX_true = data.drop('TEMP', axis=1)\ny_true = data['TEMP']\nscaler.fit(X_true)\nX_true = scaler.transform(X_true)\nprint('DONE')\n\nprint('Predicting with first model SVM...')\nprint(' +Downloadind the model from s3 bucket....', end=' ')\nwget.download(model1, 'model1.pkl')\nwith open('model1.pkl', 'rb') as f:\n pkl_model1 = pickle.load(f)\n\n# Calculate the accuracy score and predict target values\ny_pred_model1 = pkl_model1.predict(X_true)\nscore1 = accuracy_score(y_true, y_pred_model1)\nprint('DONE')\nprint(' +\\33[32m' + 'Accuracy score of model 1 : {0:.2f} %'.format(100 * score1) + '\\33[0m')\n\nprint('Predicting with second model RandomForestClassifier...')\nprint(' +Downloadind the model from s3 bucket....', end=' ')\nwget.download(model2, 'model2.pkl')\nwith open('model2.pkl', 'rb') as f:\n pkl_model2 = pickle.load(f)\n\n# Calculate the accuracy score and predict target values\ny_pred_model2 = pkl_model2.predict(X_true)\nscore2 = accuracy_score(y_true, y_pred_model2)\nprint('DONE')\nprint(' +\\33[32m' + 'Accuracy score of model 2 : {0:.2f} %'.format(100 * score2) + '\\33[0m')\n\nprint('Predicting with third model DecisionTreeClassifier...')\nprint(' +Downloadind the model from s3 bucket....', end=' ')\nwget.download(model3, 'model3.pkl')\nwith open('model3.pkl', 'rb') as f:\n pkl_model3 = pickle.load(f)\n\n# Calculate the accuracy score and predict target values\ny_pred_model3 = pkl_model3.predict(X_true)\nscore3 = accuracy_score(y_true, y_pred_model3)\nprint('DONE')\nprint(' +\\33[32m' + 'Accuracy score of model 3 : {0:.2f} %'.format(100 * score3) + '\\33[0m')\nprint('Saving the predicted results to output file...', end=' ')\n\ndf_res = pd.DataFrame({'TEMP_true': data.TEMP, 'TEMP_model1': y_pred_model1, 'TEMP_model2': y_pred_model2, 'TEMP_model3': y_pred_model3})\nunencode(encs['TEMP'], df_res, ['TEMP_true', 'TEMP_model1', 'TEMP_model2', 'TEMP_model3'])\ndf_res.to_csv (r'result.csv', index = False, header=True)\nprint('DONE')\n\nprint('Uploading result to s3 bucket...', end=' ')\nwith open(output_name, \"rb\") as f:\n s3.upload_fileobj(f, s3_bucket, output_name,\n ExtraArgs={'ACL': 'public-read'}\n )\nprint('DONE')\nprint('------------------Program completed successfully! showing predicted results--------------------')\nprint('Description of the columns of the output file:')\nprint(' +TEMP_true: True temperature from the dataset')\nprint(' +TEMP_model1: Predicted temperature using model 1')\nprint(' +TEMP_model2: Predicted temperature using model 2')\nprint(' +TEMP_model3: Predicted temperature using model 3')\nprint(\"You can access the result file on s3 with this link https://{0}.s3.amazonaws.com/{1} or you can open the file {1} in your current directory\".format(s3_bucket, output_name))\nprint(df_res)\n","sub_path":"predict_methods.py","file_name":"predict_methods.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444168286","text":"#encoding:utf-8\nimport gevent\nfrom tasks import add\nimport sys\n\n\ndef do(n=10000):\n \"\"\"\n 异步执行1w个add任务\n\n \"\"\"\n\n for i in xrange(0, n):\n res = add.apply_async([i, 0])\n sys.stdout.write('\\r{}:{}%,{},{}'.format(n, 100 * i/n, i, res.id))\n sys.stdout.flush()\n\n sys.stdout.write('\\n done!')\n\n\nif __name__ == '__main__':\n from optparse import OptionParser\n parser = OptionParser()\n\n parser.add_option(\"-n\",\"--num\", action=\"store\", dest=\"num\",\n default=1, help=\"how many tasks you want to do?\", type='int')\n\n\n options,args = parser.parse_args()\n do(options.num)\n\n\n","sub_path":"producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316980650","text":"from picamera import PiCamera\nfrom time import sleep\ncamera = PiCamera()\n\ncamera.rotation = 180\n\ncamera.start_preview()\nsleep(5)\n\ncamera.capture('/home/pi/RPI Security System/Captured Images/test1.jpg')\ncamera.stop_preview()\n","sub_path":"Files/Troubleshooter/PiCamTest.py","file_name":"PiCamTest.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"422026719","text":"firstline=input().split(\" \")\nstr0=input()\nlength=int(firstline[1])\nlists=[]\nfor i in range(length):\n lists.append(input().split(\" \"))\n\ndef func(str1,str2):\n results = -1\n for i in range(len(str1)):\n if str1[-i] == str2[-i]:\n results = i\n return results + 1\n\ndef func2(str1,str2):\n result=0\n for i in range(len(str1)):\n if str(str2).endswith(str1[i:len(str1)]):\n return len(str1)-i\n return 0\nfor i in lists:\n str1=str0[0:int(i[0])]\n str2=str0[0:int(i[1])]\n print(func(str1,str2))\n ","sub_path":"Code/CodeRecords/2193/60760/265546.py","file_name":"265546.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"177194100","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@time:2018/7/15 21:55\n\n@author: BX\n\"\"\"\nimport pandas as pd\ndatafile=r'H:\\data_test\\chapter4\\demo\\data\\discretization_data.xls'\ndata=pd.read_excel(datafile)\ndata=data['肝气郁结证型系数'].copy()\nprint(type(data))\nk=4\nd1=pd.cut(data,k,labels=range(k))#等宽离散化,各个类别命名为0,1,2,3\n#print(d1)\n#print(d1==0)\n\n#等频率离散化\n#import math\nw=[1.0*i/k for i in range(k+1)]\nw=data.describe(percentiles=w)[4:4+k+1]#利用describe函数自动计算分位数\nw[0] = w[0]*(1-1e-10)#1的-10次方#确保比最小值小\n#print(w)\n#print(w[0])\nd2=pd.cut(data,w,labels=range(k))\n#print(d2)\n\n\n#聚类离散化\nimport numpy as np\nfrom sklearn.cluster import KMeans\nkmodel=KMeans(n_clusters=k,n_jobs=1)#n_jobs并行数,一般等于CPU数比较好\nkmodel.fit(np.array(data).reshape((-1, 1)))#训练模型\nc = pd.DataFrame(kmodel.cluster_centers_)\nprint(c)\nw1= pd.rolling_mean(c, 2)\nprint(w1)\nw1= [0] + list(w1[0]) + [data.max()]\nd3 = pd.cut(data, w1, labels = range(k))\n#print()\n\n\ndef cluster_plot(d,k):\n import matplotlib.pyplot as plt\n plt.rcParams['font.sans-serif']=['SimHei']\n plt.rcParams['axes.unicode_minus']=False\n\n plt.figure(figsize=(8,3))\n for j in range(0,k):\n plt.plot(data[d==j],[j for i in d[d==j]],'o')\n # print(data[d==j])\n plt.ylim(-0.5,k-0.5)\n return plt\ncluster_plot(d1,k).show()\ncluster_plot(d2,k).show()\ncluster_plot(d3,k).show()","sub_path":"study/descretization_test.py","file_name":"descretization_test.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"242753835","text":"#!/usr/bin/python\n# coding: utf-8\n\nimport os\nimport tarfile\nimport requests\nimport pandas as pd\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\n\nHOUSING_PATH = os.path.join(\"datasets\")\n\n\ndef fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):\n\n # Create dir if it doesn't exist\n if not os.path.isdir(housing_path):\n os.makedirs(housing_path)\n\n # Download the file\n r = requests.get(housing_url)\n\n # If file was downloaded properly\n if r.status_code == 200:\n\n # Forge destination path to save file\n tgz_path = os.path.join(housing_path, \"housing.tgz\")\n\n # Save file\n with open(tgz_path, \"wb\") as f:\n f.write(r.content)\n\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path=housing_path)\n housing_tgz.close()\n else:\n print(\"couldn't download file\")\n\n\ndef load_housing_data(housing_path=HOUSING_PATH):\n\n csv_path = os.path.join(housing_path, \"housing.csv\")\n\n return pd.read_csv(csv_path)\n\n\ndef load_strat_sets(data):\n\n \"\"\"Get stratified test ad training sets\"\"\"\n\n from sklearn.model_selection import StratifiedShuffleSplit\n import numpy as np\n\n # Create an income category (scalar ranging from 0 to 15)\n data[\"income_cat\"] = np.ceil(data[\"median_income\"] / 1.5)\n data[\"income_cat\"].where(data[\"income_cat\"] < 5, 5.0, inplace=True)\n\n # Create a stratified spliter object\n split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\n\n # Split the original df into test and training sets so that the distribution of\n # income cat entries are the same as in the original df\n for train_index, test_index in split.split(data, data[\"income_cat\"]):\n strat_train_set = data.loc[train_index]\n strat_test_set = data.loc[test_index]\n\n # Drop the income_cat column, useless now that the df was splitted\n for set in (strat_train_set, strat_test_set):\n set.drop([\"income_cat\"], axis=1, inplace=True)\n\n return strat_train_set, strat_test_set\n\n\nif __name__ == \"__main__\":\n fetch_housing_data()\n pass\n","sub_path":"house_price/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"447447324","text":"from django.conf.urls.defaults import patterns, url\nfrom django.contrib import admin\nfrom django.contrib.auth.admin import (\n GroupAdmin as DjangoGroupAdmin, UserAdmin as DjangoUserAdmin)\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites.admin import SiteAdmin as DjangoSiteAdmin\nfrom django.contrib.sites.models import Site\nfrom django.db import models\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.functional import curry\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ungettext\n\nfrom lemon import extradmin\nfrom lemon.extradmin.dashboard import AppsWidget, LogWidget\nfrom lemon.extradmin.forms import MenuItemForm, GroupPermissionsForm\nfrom lemon.extradmin.forms import PermissionMultipleChoiceField\nfrom lemon.extradmin.forms import contenttype_inlineformset_factory\nfrom lemon.extradmin.models import MenuSection, MenuItem\nfrom lemon.extradmin.widgets import PermissionSelectMultiple\n\n\nclass MenuItemInline(extradmin.TabularInline):\n\n form = MenuItemForm\n model = MenuItem\n\n def get_formset(self, request, obj=None, **kwargs):\n defaults = {\n \"formfield_callback\": curry(self.formfield_for_dbfield,\n request=request),\n \"extra\": self.extra,\n \"max_num\": self.max_num,\n }\n defaults.update(kwargs)\n return contenttype_inlineformset_factory(self.parent_model, self.model,\n self.admin_site, **defaults)\n\n\nclass MenuSectionAdmin(extradmin.ModelAdmin):\n\n tabs = True\n inlines = [MenuItemInline]\n\n\nclass UserAdmin(extradmin.ModelAdmin, DjangoUserAdmin):\n\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('username', 'password1', 'password2'),\n 'description': _(\n u\"First, enter a username and password. \"\n u\"Then, you'll be able to edit more user options.\")}\n ),\n )\n\n def formfield_for_manytomany(self, db_field, request, **kwargs):\n if db_field.name == 'user_permissions':\n kwargs['form_class'] = PermissionMultipleChoiceField\n kwargs['widget'] = PermissionSelectMultiple\n kwargs['help_text'] = u''\n return super(UserAdmin, self).formfield_for_manytomany(\n db_field, request, **kwargs)\n\n\nclass GroupAdmin(extradmin.ModelAdmin, DjangoGroupAdmin):\n\n def formfield_for_manytomany(self, db_field, request, **kwargs):\n if db_field.name == 'permissions':\n kwargs['form_class'] = PermissionMultipleChoiceField\n kwargs['widget'] = PermissionSelectMultiple\n kwargs['help_text'] = u''\n return super(GroupAdmin, self).formfield_for_manytomany(\n db_field, request, **kwargs)\n\n def get_urls(self):\n return patterns('',\n url(r'^permissions/$',\n self.admin_site.admin_view(self.permissions_view),\n name='auth_group_permissions'),\n ) + super(GroupAdmin, self).get_urls()\n\n def permissions_view(self, request):\n form = GroupPermissionsForm(data=request.POST or None)\n if form.is_valid():\n form.save()\n self.message_user(request, _(u'Permissions was successfully saved.'))\n return redirect(request.path)\n rows = []\n for permission in form.permissions:\n model_class = permission.content_type.model_class()\n model_name_plural = model_class._meta.verbose_name_plural\n rows.append({'name': model_name_plural, 'permission': permission})\n rows.sort(key=lambda x: x['name'])\n return TemplateResponse(request,\n template = 'admin/auth/group/permissions.html',\n context = {\n 'title': _(u'Groups permissions'),\n 'rows': rows,\n 'form': form\n },\n current_app = self.admin_site.name\n )\n\n\nclass SiteAdmin(extradmin.ModelAdmin, DjangoSiteAdmin):\n pass\n\n\nextradmin.site.register(MenuSection, MenuSectionAdmin)\nextradmin.site.register(User, UserAdmin)\nextradmin.site.register(Group, GroupAdmin)\nextradmin.site.register(Site, SiteAdmin)\nextradmin.site.dashboard.register(AppsWidget)\nextradmin.site.dashboard.register(LogWidget)\n","sub_path":"lemon/extradmin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367650102","text":"#!/usr/bin/python\n\nimport datetime\nimport os\nimport subprocess\nimport tarfile\n\ndef main():\n iostat_filename = '/tmp/iostat.out'\n tar_filename = '/tmp/' + datetime.datetime.now().strftime(\"%Y%m%d.%H%M%S\") + '.iostat.tar.gz'\n\n # Generate iostat.out\n fd = open(iostat_filename, 'w')\n try:\n output = subprocess.call('/usr/bin/iostat -xym 10 1'.split(), stdout=fd)\n except OSError:\n print('ERROR: Command not found')\n fd.close()\n\n # Create tar.gz\n try:\n with tarfile.open(tar_filename, 'w:gz') as tar:\n for name in [iostat_filename]:\n tar.add(name, arcname=os.path.basename(name))\n except tarfile.TarError:\n print('ERROR: Error during the tar operation')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cron_ipcinfod/iostat.py","file_name":"iostat.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"653815182","text":"import os\nimport pytest\n\nimport numpy as np\nimport renom as rm\nfrom renom.core import Variable, to_value, DEBUG_GRAPH_INIT, DEBUG_NODE_GRAPH\nfrom renom.cuda.cuda import set_cuda_active\n\nset_cuda_active(True)\n\n\nclass NN(rm.Model):\n def __init__(self):\n super(NN, self).__init__()\n self.params.value1 = Variable(np.array([1., 2., 3., 4.]))\n self.params.value2 = Variable(np.array([1., 2., 3., 4.]))\n\n def forward(self, v):\n return v * self.params.value1 * self.params.value2\n\n\ndef test_train():\n\n nn = NN()\n\n with nn.train():\n ret = nn(np.array([1., 2., 3., 4.]))\n\n grad = ret.grad(1)\n grad.update()\n\n assert np.allclose(nn.params.value1.as_ndarray(), [0., -2., -6., -12.])\n assert np.allclose(nn.params.value2.as_ndarray(), [0., -2., -6., -12.])\n\n\ndef test_train2():\n\n nn = NN()\n nn2 = NN()\n\n with nn2.train():\n ret = nn(np.array([1., 2., 3., 4.]))\n ret2 = nn2(ret)\n\n grad = ret2.grad(1)\n grad.update()\n\n assert np.allclose(nn.params.value1.as_ndarray(), [1., 2., 3., 4.])\n assert np.allclose(nn.params.value2.as_ndarray(), [1., 2., 3., 4.])\n\n assert np.allclose(nn2.params.value1.as_ndarray(), [0., -14., -78., -252.])\n assert np.allclose(nn2.params.value2.as_ndarray(), [0., -14., -78., -252.])\n\n\ndef test_not_train():\n nn = NN()\n\n ret = nn(np.array([1, 2, 3, 4]))\n assert not list(ret.attrs.get_attrs())\n\n grad = ret.grad(1)\n grad.update()\n\n nn.params.value1.to_cpu()\n nn.params.value2.to_cpu()\n\n assert np.allclose(np.array([1, 2, 3, 4]), nn.params.value1.as_ndarray())\n assert np.allclose(np.array([1, 2, 3, 4]), nn.params.value2.as_ndarray())\n\n\ndef test_prevent():\n nn = NN()\n\n with nn.train():\n ret = nn(np.array([1, 2, 3, 4]))\n\n assert list(ret.attrs.get_attrs())\n grad = ret.grad(1)\n with nn.prevent_update():\n grad.update()\n\n assert np.allclose(nn.params.value1.as_ndarray(), [1, 2, 3, 4])\n assert np.allclose(nn.params.value2.as_ndarray(), [1, 2, 3, 4])\n\n\ntry:\n import h5py\n has_h5py = True\nexcept ImportError:\n has_h5py = False\n\nskiph5py = pytest.mark.skipif(not has_h5py, reason=\"h5py is not installed\")\n\n\n@skiph5py\ndef test_save(tmpdir_factory):\n\n class NN2(rm.Model):\n def __init__(self):\n super(NN2, self).__init__()\n self.layer1 = rm.Dense(output_size=2)\n self.layer2 = rm.Dense(output_size=2)\n\n def forward(self, x):\n return self.layer2(rm.relu(self.layer1(x)))\n\n class NN3(rm.Model):\n def __init__(self):\n super(NN3, self).__init__()\n self.layer1 = NN2()\n self.layer2 = NN2()\n\n def forward(self, x):\n return self.layer2(rm.relu(self.layer1(x)))\n\n nn = NN3()\n with nn.train():\n result = nn(np.random.rand(2, 2))\n l = rm.softmax_cross_entropy(result, np.random.rand(2, 2))\n\n grad = l.grad()\n opt = rm.Sgd()\n grad.update(opt)\n\n nn.layer1.layer1.params.b._auto_update = False\n\n d = tmpdir_factory.mktemp('h5')\n fname = os.path.join(str(d), 'aaa')\n nn.save(fname)\n\n nn2 = NN3()\n nn2.load(fname)\n\n assert np.allclose(nn.layer1.layer1.params.w, nn2.layer1.layer1.params.w)\n assert np.allclose(nn.layer1.layer1.params.b, nn2.layer1.layer1.params.b)\n assert np.allclose(nn.layer1.layer2.params.w, nn2.layer1.layer2.params.w)\n assert np.allclose(nn.layer1.layer2.params.b, nn2.layer1.layer2.params.b)\n\n assert np.allclose(nn.layer2.layer1.params.w, nn2.layer2.layer1.params.w)\n assert np.allclose(nn.layer2.layer1.params.b, nn2.layer2.layer1.params.b)\n assert np.allclose(nn.layer2.layer2.params.w, nn2.layer2.layer2.params.w)\n assert np.allclose(nn.layer2.layer2.params.b, nn2.layer2.layer2.params.b)\n\n assert nn2.layer1.layer1.params.w._auto_update\n assert not nn2.layer1.layer1.params.b._auto_update\n\n\ndef test_update():\n nn = rm.Dense(2)\n nn2 = rm.Dense(2)\n with nn.train():\n ret = nn(np.random.rand(2, 2))\n loss = rm.softmax_cross_entropy(ret, np.random.rand(2, 2))\n\n cur = nn.params.w.copy()\n grad = loss.grad(np.array([1]))\n\n grad.update(models=[nn2])\n assert np.allclose(cur.as_ndarray(), nn.params.w)\n\n grad.update(models=[nn])\n assert np.allclose(cur.as_ndarray() - grad.get(nn.params.w), nn.params.w.as_ndarray())\n","sub_path":"test/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636883976","text":"import argparse\nimport random\nimport os\nimport time\nimport pyglet\nglobal delay\ndelay=3\n\n\ndef clear():\n for x in range(5):\n window.clear()\n\ndef update_image(dt):\n clear()\n for n in range(delay):\n time.sleep(1)\n global count\n try:\n count\n except:\n count=0\n img = pyglet.image.load(image_paths[count])\n sprite.image = img\n sprite.scale = get_scale(window, img)\n sprite.x = (window.width/2)-(sprite.width/2)\n sprite.y = (window.height/2)-(sprite.height/2)\n\n if count ==len(image_paths)-1:\n count=0\n else:\n count+=1\n\n\n \ndef get_image_paths(input_dir='.'):\n paths = []\n for root, dirs, files in os.walk(input_dir, topdown=True):\n for file in sorted(files):\n if file.endswith(('jpg', 'png', 'gif')):\n path = os.path.abspath(os.path.join(root, file))\n paths.append(path)\n return paths\n\n\ndef get_scale(window, image):\n if image.width > image.height:\n scale = float(window.width) / image.width\n #scale = float(window.height) / image.height\n else:\n scale = float(window.height) / image.height\n return scale\n\nglobal window\nwindow = pyglet.window.Window(fullscreen=True)\n\n\n@window.event\ndef on_draw():\n window.clear()\n sprite.draw()\n\n\nif __name__ == '__main__':\n global count\n try:\n count\n except:\n count=0\n parser = argparse.ArgumentParser()\n parser.add_argument('dir', help='directory of images',\n nargs='?', default=os.getcwd()+'\\\\slides')\n args = parser.parse_args()\n global image_paths\n image_paths = get_image_paths(args.dir)\n img = pyglet.image.load(image_paths[count])\n sprite = pyglet.sprite.Sprite(img)\n sprite.scale = get_scale(window, img)\n sprite.x = (window.width/2)-(sprite.width/2)\n sprite.y=(window.height/2)-(sprite.height/2)\n\n pyglet.clock.schedule_interval(update_image, 1)\n\n \n pyglet.app.run()\n","sub_path":"slideshow.py","file_name":"slideshow.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"630620023","text":"from selenium.webdriver import Chrome, ChromeOptions\n\n\ndef get_driver(path='chromedriver'):\n options = ChromeOptions()\n options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/91.0.4472.124 Safari/537.36')\n # options.add_argument('--headless')\n # options.add_argument('--disable-gpu')\n # options.add_argument('--no-sandbox')\n return Chrome(path, options=options)\n\n\ndef parse_headers(driver: Chrome):\n labels = driver.find_elements_by_xpath('//*[@class=\"data-table__header-label\"]/span')\n return [label.get_property('innerHTML').replace('
', ' ').strip() for label in labels]\n\n\ndef get_pages_count(driver: Chrome):\n pagination_block = driver.find_element_by_xpath('//ul[@class=\"pagination\"]')\n buttons = pagination_block.find_elements_by_xpath('.//button[@class=\"page-link\"]')\n try:\n return int(''.join(buttons[-2].text.split(',')))\n except (IndexError, ValueError):\n return None\n\n\ndef get_next_btn(driver: Chrome):\n return driver.find_element_by_xpath('//li[@title=\"Next\"]/button[@class=\"page-link\"]')\n\n\ndef get_total_count(driver: Chrome):\n try:\n return int(driver.find_element_by_class_name(\n 'display-summary__short-summary').text.split()[0].replace(',', ''))\n except (IndexError, ValueError):\n return 0\n\n\ndef set_url_param(url: str, key, val):\n params_block = url.split('/')[-1].split('?')\n if len(params_block) == 1:\n return f'{url}?{key}={val}'\n elif f'{key}=' in url:\n i = url.index(f'{key}=') + len(f'{key}=')\n offset = 0\n while url[i + offset] != '&' and i + offset < len(url) - 1:\n offset += 1\n return url[:i] + str(val) + url[i + offset:]\n return url\n\n\nif __name__ == '__main__':\n url = 'https://app.linkresearchtools.com/smart/report.php?gid=13114757#/source-pages?page=21'\n print(set_url_param(url, 'page', '3'))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"439705044","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 24 10:36:42 2019\n\n@author: ptruong\n\"\"\"\n\nimport sys \n\nfrom proteinSearch import *\n\nfrom triqlerParser import *\nfrom triqlerProcessor import * \nfrom utils import * \nfrom parseReformattedPSSS3equDecoy import * # Needs to tidy and place functions in right place!\n#from corrPlot import * #correlation plotting\n\nimport os\nimport argparse\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\nimport scipy as sp\nimport subprocess\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n\n#############\n# Triqler ###\n#############\n\ndef processTriqler(triqlerFile = \"proteins.1vs2.tsv\", FDR_treshold = 0.01):\n \"\"\"\n Parse and process triqler to analysis format.\n \"\"\" \n triqler = table2Df(triqlerFile, peptideSeperator = True)\n triqler = triqler.dropna()\n triqler = triqler2Numeric(triqler)\n triqler = getTriqlerDetailed(triqler)\n \n \n # FDR on protein_id_posterior_error_prob\n triqler.sort_values(by = \"protein_id_posterior_error_prob\", inplace = True)\n triqler[\"FDR\"] = triqler[\"protein_id_posterior_error_prob\"].expanding().mean()\n triqler = triqler[triqler[\"FDR\"] < FDR_treshold]\n \n return triqler\n\ndef splitTriqlerBySpecies(triqler, exponential = 2, truncated = False): #transform = np.exp2):\n \"\"\"\n Split triqler into species dataframes.\n \n example transform = np.exp2 or transform = np.exp\n truncated - can be subset of repl_cols\n \"\"\" \n # All runs\n at_t = triqler[triqler[\"specie\"] == \"ARATH\"]\n ce_t = triqler[triqler[\"specie\"] == \"CAEEL\"]\n hs_t = triqler[triqler[\"specie\"] == \"HUMAN\"]\n \n # DROP species and drop peptides <------------------------\n at_t = renameTriqler2Vital(at_t)\n ce_t = renameTriqler2Vital(ce_t)\n hs_t = renameTriqler2Vital(hs_t)\n \n # transform \n #if transform != False:\n # at_t = transform(at_t)\n # ce_t = transform(ce_t)\n # hs_t = transform(hs_t)\n if truncated != False:\n if truncated == True:\n print(\"Dropping [S01 S02] in Triqler split...\")\n at_t = at_t.drop([\"S01\", \"S10\"], axis = 1)\n ce_t = ce_t.drop([\"S01\", \"S10\"], axis = 1)\n hs_t = hs_t.drop([\"S01\", \"S10\"], axis = 1)\n else:\n print(\"Dropping [\" + \" \".join(truncated) +\"] in Triqler split...\")\n at_t = at_t.drop(truncateDrop(truncated), axis = 1)\n ce_t = ce_t.drop(truncateDrop(truncated), axis = 1)\n hs_t = hs_t.drop(truncateDrop(truncated), axis = 1) \n if exponential != False:\n print(\"Before exponential sample...\")\n print(hs_t.iloc[2582,:].values)\n print(\"Taking the \" + str(exponential) + \" exponential of the Triqler values...\")\n at_t = exponential**(at_t)\n ce_t = exponential**(ce_t)\n hs_t = exponential**(hs_t)\n print(\"After exponential sample...\")\n print(hs_t.iloc[2582,:].values)\n return at_t, ce_t, hs_t\n\n############################\n# Spectronaut unfiltered ###\n############################\n\ndef processSpectronaut(spectronautFile = \"500-PSSS3-raw-reformatted_dropna_dropdup_decoy.csv\",\n FDR_treshold = 0.01, impute = \"mean\", global_impute = True):\n \"\"\"\n Parse and process reformatted spectronaut to analysis format. The data is pre-reformatted \n because the formatting procedure takes some time.\n \"\"\"\n df = pd.read_csv(spectronautFile, sep =\"\\t\")\n \n # FDR filtereing\n df = df[df[\"qvalue\"].fillna(-1) 0.0].min(numeric_only=True,axis=1)/2.0\n #nnn = pd.concat([nn]*sampgroup.shape[1],axis=1)\n #sampgroup = sampgroup.where(sampgroup!=0.0, nnn)\n \n \n sampgroup['Protein'] = range(len(sampgroup))\n #sampgroup['Protein'] = sampgroup.index\n #unmeltsamp = sampgroup.copy()\n if melt == True:\n sampgroup=pd.melt(sampgroup, id_vars=['Method', 'Species','Protein'], value_vars=repl_cols)\n sampgroup.rename(columns={'variable':'Sample','value':'Expression'}, inplace=True)\n return sampgroup\n else:\n return sampgroup\n\ndef mergeSpecies(at, ce, hs, method_name = \"Spectronaut\"):\n \"\"\"\n Merges and normalizes alll the different species data frames into plotting format. \n \"\"\"\n repl_cols = [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\n \n normalized_protein_at = normalizePerProteinAbundance(at)\n normalized_protein_ce = normalizePerProteinAbundance(ce)\n normalized_protein_hs = normalizePerProteinAbundance(hs)\n\n sampgroup_at,sampgroup_hs,sampgroup_ce = pd.DataFrame(),pd.DataFrame(),pd.DataFrame()\n \n for s in repl_cols:\n sampgroup_at[s] = normalized_protein_at[s].sum(1)\n sampgroup_ce[s] = normalized_protein_ce[s].sum(1)\n sampgroup_hs[s] = normalized_protein_hs[s].sum(1)\n \n sampgroup_at['Species'] = ['A thaliana'] *len(normalized_protein_at)\n sampgroup_ce['Species'] = ['C elegans'] *len(normalized_protein_ce)\n sampgroup_hs['Species'] = ['H sapiens'] *len(normalized_protein_hs)\n sampgroup_at['Method'] = [method_name]*len(normalized_protein_at)\n sampgroup_ce['Method'] = [method_name]*len(normalized_protein_ce)\n sampgroup_hs['Method'] = [method_name]*len(normalized_protein_hs)\n \n sampgroup_spec = pd.concat([sampgroup_at,sampgroup_ce,sampgroup_hs])\n return sampgroup_spec\n\nrepl_cols = [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\nfind = [\"S02\", \"S03\", \"S05\"] #<---------------------------------- HERE CKEEP WORKING\n\ndef findReplIdx(replicates):\n \"\"\"\n returns replicates indices\n \"\"\"\n allReplicates = [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\n idxs = np.where(np.isin(allReplicates, replicates))\n return idxs[0]\n\ndef takeReplicatesMixtureAmount(mix, replicates):\n \"\"\"\n return mixture corresponding the selected replicates.\n - mix - mixture from getMixtures\n - allReplicates - [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\n - find - subset of allReplicates\n \"\"\"\n allReplicates = [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\n mixture = np.take(mix, findReplIdx(replicates))\n return mixture\n\ndef truncateDrop(replicates):\n \"\"\"\n Function to find which replicates to drop.\n \"\"\"\n allReplicates = [\"S01\",\"S02\",\"S03\",\"S04\",\"S05\",\"S06\",\"S07\",\"S08\",\"S09\",\"S10\"]\n dropRepl = np.take(allReplicates, np.where(~np.isin(allReplicates, replicates))).tolist()[0]\n return dropRepl\n\ndef getMixtures(truncated = False):\n \"\"\"\n Defines the true mixture levels.\n\"\"\"\n a_mix = np.array([0.5] * 10)\n a_mix[0] += 0.0001\n c_mix = np.array([0.5, 0.25, 0.125, 0.0625, 0.031, 0.0155, 0.008, 0.004, 0.002, 0.0])\n h_mix = np.array([0.0, 0.25, 0.375, 0.4375, 0.469, 0.4845, 0.492, 0.496, 0.498, 0.5])\n if truncated != False:\n if truncated == True:\n print(\"Getting mixtures for [S02 S03 S04 S05 S06 S07 S08 S09]\")\n a_mix = a_mix[1:-1]\n c_mix = c_mix[1:-1]\n h_mix = h_mix[1:-1]\n a_mix = a_mix/a_mix.sum()\n c_mix = c_mix/c_mix.sum()\n h_mix = h_mix/h_mix.sum()\n mix = {'A thaliana':a_mix, 'C elegans': c_mix, 'H sapiens': h_mix}\n else:\n print(\"Getting mixtures for [\" + \" \".join(truncated) +\"]\")\n a_mix = takeReplicatesMixtureAmount(a_mix, truncated)\n c_mix = takeReplicatesMixtureAmount(c_mix, truncated)\n h_mix = takeReplicatesMixtureAmount(h_mix, truncated)\n a_mix = a_mix/a_mix.sum()\n c_mix = c_mix/c_mix.sum()\n h_mix = h_mix/h_mix.sum()\n mix = {'A thaliana':a_mix, 'C elegans': c_mix, 'H sapiens': h_mix}\n \n else:\n print(\"Getting mixtures for [S01 S02 S03 S04 S05 S06 S07 S08 S09 S10]\")\n a_mix = a_mix/a_mix.sum()\n c_mix = c_mix/c_mix.sum()\n h_mix = h_mix/h_mix.sum()\n mix = {'A thaliana':a_mix, 'C elegans': c_mix, 'H sapiens': h_mix}\n \n return a_mix, c_mix, h_mix, mix\n\n\n#####################\n# ADJUST NON SHARED #\n#####################\ndef adjustNonShared(libraryDirectory = \"library/LKaell/\", \n humanLib = \"uniprot_sprot_2017-10-25_HUMAN_ISOFORMS.fasta\",\n arathLib = \"uniprot_sprot_2018-01-24_ARATH_ISOFORMS.fasta\",\n caeelLib = \"uniprot-elegans-filtered-organism__Caenorhabditis+elegans.fasta\",\n filename = \"500-PSSS3-equ decoy_Report.xls\",\n outputname = \"500-PSSS3-equ decoy_Report_nonShared_20190507.xls\"):\n findUniqueProteins(inputName = filename, outputName = \"proteins.csv\")\n uniprot = getPSSS3Uniprot(libraryDirectory = libraryDirectory, \n humanLib = humanLib,\n arathLib = arathLib,\n caeelLib = caeelLib)\n singleProteins = findSingleProteins(filename=\"proteins.csv\")\n shared, nonShared = findShared(filename = \"proteins.csv\") \n \n filename = filename\n outputname = outputname\n \n f = open(filename, \"r\")\n new_file = open(outputname, \"w\")\n #line = f.readline().split(\"\\t\")\n #i = 0\n for line in f:\n #i+=1\n row = line.split(\"\\t\")\n if row[3] in nonShared:\n row[3] = row[3].split(\";\")[0] \n new_line = \"\\t\".join(row)\n new_file.write(new_line)\n \n ################################################################\n # Code for fixing laste 15 lines #\n # unknown why last 15 lines wont get appended on previous code #\n ################################################################\n \n def tail(filename, lines):\n import sys\n import os\n \n bufsize = 8192\n \n lines = lines #int(sys.argv[1])\n fname = filename #sys.argv[2]\n fsize = os.stat(fname).st_size\n \n iter = 0\n #with open(sys.argv[2]) as f:\n with open(fname) as f:\n if bufsize > fsize:\n bufsize = fsize-1\n data = []\n while True:\n iter +=1\n f.seek(fsize-bufsize*iter)\n data.extend(f.readlines())\n if len(data) >= lines or f.tell() == 0:\n output = (''.join(data[-lines:]))\n return output\n break\n #return tailLines\n \n tailLines = tail(filename, 16)\n tailLines = tailLines.split(\"\\n\")#.split(\"\\t\")\n new_file = open(outputname, \"a\")\n for line in tailLines:\n if line == \"\":\n continue\n row = line.split(\"\\t\")\n if row[3] in nonShared:\n row[3] = row[3].split(\";\")[0]\n new_line = \"\\t\".join(row)\n new_file.write(new_line)","sub_path":"bin/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":17971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"70811248","text":"import logging.config\n\nlogger = logging.getLogger('example')\n\nlogging.config.dictConfig({\n 'version': 1,\n 'handlers': {\n 'default': {\n 'class': 'logging.StreamHandler',\n 'level': 'DEBUG',\n 'stream': 'ext://sys.stderr',\n }\n },\n 'root': {\n 'level': 'DEBUG',\n 'handlers': ['default'],\n },\n 'disable_existing_loggers': False,\n})\n\nlogger.info('Hello') # 出力される\n","sub_path":"26/00/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"89712111","text":"'''\nCreated on Mar 19, 2014\n\n@author: xzhu\n'''\n\n# Check the directories and files that may eat up the disk space.\n\nimport argparse\nimport os\n\n\ndef main():\n '''Main function.\n \n Find all the files or directories we are searching and optionally delete them.\n '''\n \n # arguments parsing\n parser = argparse.ArgumentParser()\n parser.add_argument(\"directory\", help=\"root directory of the search\")\n parser.add_argument(\"-f\", help=\"the searching file name\")\n parser.add_argument(\"-d\", help=\"the searching directory name\")\n parser.add_argument(\"--delete\", help=\"delete the searched directories and files\", action=\"store_true\")\n args = parser.parse_args()\n \n for root, dirs, files in os.walk(args.directory):\n if args.d:\n for eachDir in dirs:\n if eachDir == args.d:\n os.system(\"sudo du -hs \" + os.path.join(root, eachDir))\n \n # if delete option is specified, delete the files found.\n if args.delete:\n os.system(\"sudo rm -rf \" + os.path.join(root, eachDir))\n \n if args.f:\n for eachFile in files:\n if eachFile == args.f:\n os.system(\"sudo du -hs \" + os.path.join(root, eachFile))\n \n # if delete option is specified, delete the directories found.\n if args.delete:\n os.system(\"sudo rm -f \" + os.path.join(root, eachFile))\n \nif __name__ == '__main__':\n main()","sub_path":"sys_admin/check_disk_usage.py","file_name":"check_disk_usage.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"332237491","text":"\"\"\"\nCopyright 2014 Rackspace\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nimport mock\n\nfrom cloudcafe.identity.v3.common.projects.models.responses import Project\n\n\nclass Mock(object):\n @classmethod\n def _dict_to_obj(cls, data):\n return \"mocked stuff\"\n\n @classmethod\n def _xml_ele_to_obj(cls, data):\n return \"mocked stuff\"\n\n\nclass ProjectResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Project response model\n \"\"\"\n RESPONSES = 'cloudcafe.identity.v3.common.projects.models.responses'\n\n @mock.patch(RESPONSES+'.Domain', Mock)\n def test_dict_to_obj(self):\n \"\"\"\n test to verify Project.dict_to_obj() can convert a dictionary\n representation of a Project to a Project object\n \"\"\"\n # ARRANGE\n project_dict = {\n 'id': 'test_project_id',\n 'name': 'test_project_name',\n 'domain': 'test_domain'\n }\n expected_project_obj = Project(id_='test_project_id',\n name='test_project_name',\n domain='mocked stuff')\n # ACT\n project_resp_obj = Project._dict_to_obj(project_dict)\n # ARRANGE\n self.assertEqual(expected_project_obj, project_resp_obj)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"metatests/identity/v3/common/projects/models/test_project_responses.py","file_name":"test_project_responses.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608428215","text":"import nltk\nfrom nltk.stem import PorterStemmer, WordNetLemmatizer\nimport pandas as pd\n\ndef lemmatize_text(text):\n w_tokenizer = nltk.tokenize.WhitespaceTokenizer()\n lemmatizer = nltk.stem.WordNetLemmatizer()\n lem_text = []\n for w in w_tokenizer.tokenize(text):\n lem_text.append(lemmatizer.lemmatize(w))\n lem_text.append(\" \")\n return ''.join(lem_text)\n # return [lemmatizer.lemmatize(w) for w in w_tokenizer.tokenize(text)] # apply on dataframe: df.text.apply(lemmatize_text)\n\ndef stem_text(text):\n porter_stemmer = PorterStemmer()\n tokens = text.split()\n stem_text = []\n for token in tokens:\n stem_text.append(porter_stemmer.stem(token))\n stem_text.append(\" \")\n return ''.join(stem_text)\n # stemmed_tokens = [porter_stemmer.stem(token) for token in tokens]\n # return stemmed_tokens # # apply on dataframe: df.text.apply(stem_text)\n\ndef lem_stem_text(text):\n lemm_text = lemmatize_text(text)\n lemm_stem_text = stem_text(lemm_text)\n return lemm_stem_text","sub_path":"resources/word_extraction/text_cleaning.py","file_name":"text_cleaning.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"450849559","text":"#!/usr/bin/env python3\nimport sys\nimport shlex\n\ndef quote_attr(word):\n rword = ''\n right = False\n for i in word:\n if right:\n if i == '\"':\n rword += '"'\n else:\n rword += i\n else:\n rword += i\n if i == '=':\n right = True\n rword += '\"'\n if right: rword += '\"'\n return rword\n\ndef quote_xml(word):\n rword = ''\n for i in word:\n if i == '<':\n rword += '<'\n elif i == '>':\n rword += '>'\n else:\n rword += i\n return rword\n\ndef process_file(fin):\n c_offsets = []\n\n for line in fin:\n line = line.rstrip('\\r\\n')\n off_l = len(line)\n line = line.lstrip()\n off_l = off_l - len(line)\n\n words = shlex.split(line, comments=True, posix=True)\n if len(words) == 0: continue\n\n while (len(c_offsets) > 0) and (c_offsets[-1][0] >= off_l):\n ctag = c_offsets.pop()\n print('%s' % (' ' * len(c_offsets), ctag[1]))\n\n colon = -1\n for i,word in enumerate(words):\n if word[-1:] == ':':\n words[i] = word[:-1]\n colon = i\n break\n\n if colon == -1:\n print('%s<%s />' % (' ' * len(c_offsets), line))\n elif colon == len(words)-1:\n # OK, opening section...\n print('%s<%s>' % (' ' * len(c_offsets), line[:-1]))\n c_offsets.append( [ off_l, words[0] ] )\n else:\n left = '<' ; ql = ''\n right = '>' ; qr = ''\n for i,word in enumerate(words):\n if i > colon:\n right += qr + quote_xml(word)\n qr = ' '\n else:\n left += ql + quote_attr(word)\n ql = ' '\n print('%s%s%s' % ( ' ' * len(c_offsets), left, right, words[0]))\n \n while len(c_offsets) > 0:\n ctag = c_offsets.pop()\n print('%s' % (' ' * len(c_offsets), ctag[1]))\n\n\nif __name__ == \"__main__\":\n process_file(sys.stdin)\n \n","sub_path":"noxml.py","file_name":"noxml.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"485514952","text":"#!/usr/bin/python\n# encoding=utf-8\n\n__author__ = 'lengaoxin@gmail.com'\n\nimport os\nimport multiprocessing\nimport time\nimport sys\nimport locale\n\nREPORT_LOG_ENABLED = False\n\ndef get_current_path():\n if getattr(sys, 'frozen', None):\n ret = os.path.realpath(os.path.dirname(sys.executable))\n else:\n ret = os.path.realpath(os.path.dirname(__file__))\n\n return ret\n\nlog_file_lock = multiprocessing.Lock()\nLOG_FILE = 'report.log'\ndef report_log(msg, mode='a'):\n if not REPORT_LOG_ENABLED:\n return\n\n log_file_lock.acquire()\n folder = get_current_path()\n log_file_path = os.path.join(folder, LOG_FILE)\n f = None\n try:\n log_time = time.strftime('%Y-%m-%d %H:%M:%S')\n f = open(log_file_path, mode)\n f.write('%s %s\\n' % (log_time, msg))\n f.close()\n except:\n if f:\n f.close()\n log_file_lock.release()\n\nclass Logging(object):\n RED = '\\033[31m'\n GREEN = '\\033[32m'\n YELLOW = '\\033[33m'\n RESET = '\\033[0m'\n DEBUG_ENABLED = True\n\n @staticmethod\n def _print(s, color=None):\n encoding = 'utf-8'\n try:\n lang, encoding = locale.getdefaultlocale()\n if encoding is None:\n encoding = 'utf-8'\n except:\n pass\n\n if encoding.lower() != 'utf-8' and not isinstance(s, unicode):\n s = s.decode('utf-8')\n\n if isinstance(s, unicode):\n s = s.encode(encoding)\n\n if color and sys.stdout.isatty() and sys.platform != 'win32':\n print(color + s + Logging.RESET)\n else:\n print(s)\n\n @classmethod\n def log_msg(cls, msg):\n Logging._print(msg, Logging.GREEN)\n\n @classmethod\n def debug_msg(cls, msg):\n if cls.DEBUG_ENABLED:\n Logging._print(msg)\n\n @classmethod\n def warn_msg(cls, msg):\n warn_str = 'WARN : %s' % msg\n Logging._print(warn_str, Logging.YELLOW)\n\n @classmethod\n def error_msg(cls, msg, err_no=1):\n error_str = 'ERROR (%d): %s' % (err_no, msg)\n Logging._print(error_str, Logging.RED)\n report_log(error_str)\n\ndef raise_known_error(err_msg, err_no=1):\n Logging.error_msg(err_msg, err_no)\n raise KnownError(err_msg, err_no)\n\nclass KnownError(Exception):\n ERROR_WRONG_ARGS = 11 # wrong arguments\n ERROR_PATH_NOT_FOUND = 12 # path not found\n ERROR_BUILD_FAILED = 13 # build failed\n ERROR_RUNNING_CMD = 14 # error when running command\n ERROR_CMD_NOT_FOUND = 15 # command not found\n ERROR_ENV_VAR_NOT_FOUND = 16 # environment variable not found\n ERROR_TOOLS_NOT_FOUND = 17 # depend on tools not found\n ERROR_PARSE_FILE = 18 # error when parse files\n ERROR_WRONG_CONFIG = 19 # configuration is wrong\n\n ERROR_OTHERS = 101 # other errors\n\n def __init__(self, err_args, err_no=1):\n super(KnownError, self).__init__(err_args)\n self.error_no = err_no\n\n def get_error_no(self):\n return self.error_no\n","sub_path":"tools/utils/logUtils.py","file_name":"logUtils.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"472399809","text":"import datetime as dt\nfrom typing import Union\n\n\nclass Record:\n\n def __init__(\n self,\n amount: int,\n comment: str,\n date: Union[str, None] = None\n ) -> None:\n self.amount = amount\n if date is None:\n self.date = dt.date.today()\n else:\n self.date = dt.datetime.strptime(date, '%d.%m.%Y').date()\n self.comment = comment\n\n\nclass Calculator:\n\n def __init__(self, limit) -> None:\n self.records = []\n self.limit = limit\n\n def result_limit_get_today_status(self):\n result = self.limit - self.get_today_stats()\n return result\n\n def add_record(self, record: Record) -> None:\n self.records.append(record)\n\n def get_today_stats(self) -> int:\n now = dt.datetime.now().date()\n amount: int = 0\n for record in self.records:\n if record.date == now:\n amount += record.amount\n return amount\n\n def get_week_stats(self) -> int:\n day_week_ago = dt.date.today() - dt.timedelta(days=7)\n today = dt.datetime.now().date()\n amount = 0\n for record in self.records:\n if day_week_ago <= record.date <= today:\n amount += record.amount\n return amount\n\n\nclass CaloriesCalculator(Calculator):\n\n def get_calories_remained(self) -> str:\n result = self.result_limit_get_today_status()\n if result > 0:\n return (f\"Сегодня можно съесть что-нибудь ещё, \"\n f\"но с общей калорийностью не более \"\n f\"{result} кКал\")\n else:\n return \"Хватит есть!\"\n\n\nclass CashCalculator(Calculator):\n USD_RATE: float = 60.00\n EURO_RATE: float = 70.00\n RUB_RATE: float = 1.00\n money_dict = {\n \"usd\": [\"USD\", USD_RATE],\n \"eur\": [\"Euro\", EURO_RATE],\n \"rub\": [\"руб\", RUB_RATE],\n }\n\n def get_today_cash_remained(self, currency) -> str:\n today_cash = round(self.result_limit_get_today_status(), 2)\n if today_cash == 0:\n return \"Денег нет, держись\"\n today_cash = round(today_cash / self.money_dict[currency][1], 2)\n if today_cash > 0:\n return (f\"На сегодня осталось \"\n f\"{today_cash} {self.money_dict[currency][0]}\")\n else:\n return (f\"Денег нет, держись: твой долг - \"\n f\"{abs(today_cash)} {self.money_dict[currency][0]}\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"269268200","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom urllib.parse import quote\nfrom urllib.request import urlopen\nimport json\n\napp = Flask(__name__)\n\nOPEN_WEATHER_URL = \"http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&APPID={1}\"\n\nOPEN_WEATHER_KEY = 'c1caa429669a0b18e23646c5e746aa70' #key API ต้อง crete ขึ้นมาเอง\n\nOPEN_NEW_URL = \"http://newsapi.org/v2/everything?q={0}&from=2021-02-01&sortBy=publishedAt&apiKey={1}\"\n\nOPEN_NEW_KEY = \"2bd7353a4fdc47f180dfaf595f9c652a\"\n\n@app.route(\"/\")\ndef home():\n city = request.args.get('city') #สามารถส่ง parameter ทางหน้าหลักได้ ตรง url\n if not city:\n city = 'bangkok' #set กรุงเทพเป็นหลัก ถ้าไม่ได้ส่งค่ามา\n weather = get_weather(city, OPEN_WEATHER_KEY)\n\n new = get_new('covid-19',OPEN_NEW_KEY)\n\n return render_template(\"home.html\", weather=weather,new=new)\n\n\n\ndef get_new(news,OPEN_NEW_KEY):\n\n query = quote(news)\n\n url = OPEN_NEW_URL.format(news,OPEN_NEW_KEY) \n\n data = urlopen(url).read() #ยิง request ไป ตอบกลับมาเป็น json xml\n\n parsed = json.loads(data)\n\n news = None\n Arr = []\n for x in range (5):\n if parsed.get('articles'):\n\n title = parsed['articles'][x]['title']\n description = parsed['articles'][x]['description']\n url = parsed['articles'][x]['url']\n urlToImage = parsed['articles'][x]['urlToImage']\n\n news = { 'title': title, \n 'description': description,\n 'url': url,\n 'urlToImage': urlToImage\n \n }\n Arr.append(news)\n \n return Arr\n\n \n\ndef get_weather(city,API_KEY):\n\n query = quote(city)\n\n url = OPEN_WEATHER_URL.format(city, API_KEY) #สร้างมาเพื่อเก็บตัวเเปรมาไว้ใน {0}\n\n data = urlopen(url).read() #ยิง request ไป ตอบกลับมาเป็น json xml\n\n parsed = json.loads(data)\n\n weather = None\n if parsed.get('weather'): #check ว่า สามารถ get key weather ได้รึเปล่า\n\n description = parsed['weather'][0]['description']\n temperature = parsed['main']['temp']\n city = parsed['name']\n country = parsed['sys']['country']\n pressure = parsed['main']['pressure']\n humidity = parsed['main']['humidity']\n speed = parsed['wind']['speed']\n icon = parsed['weather'][0]['icon']\n\n\n weather = {'description': description, #ประกาศตัวเเปร weather เป็น dictionary เป็นรวม\n 'temperature': temperature,\n 'city': city,\n 'country': country,\n 'pressure' : pressure,\n 'humidity' : humidity,\n 'speed' : speed,\n 'icon' : icon\n }\n return weather\n\n\n \n\n\n@app.route('/news')\ndef news():\n newk = request.args.get('newk') #สามารถส่ง parameter ทางหน้าหลักได้ ตรง url\n if not newk:\n newk = \"esport\" \n new = get_newz(newk,OPEN_NEW_KEY)\n\n \n\n return render_template('news.html', new=new)\n\ndef get_newz(news,OPEN_NEW_KEY):\n\n query = quote(news)\n\n url = OPEN_NEW_URL.format(news,OPEN_NEW_KEY) \n\n data = urlopen(url).read() #ยิง request ไป ตอบกลับมาเป็น json xml\n\n parsed = json.loads(data)\n\n news = None\n Arr = []\n if parsed.get('articles'):\n\n for x in parsed['articles']:\n title = x['title']\n description = x['description']\n url = x['url']\n \n\n news = { 'title': title, \n 'description': description,\n 'url': url\n }\n Arr.append(news)\n \n return Arr\n\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n\napp.env=\"development\"\napp.run(debug=True)","sub_path":"weather-app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"6029326","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/1/25\n@function:\n455. Assign Cookies (Easy)\nhttps://leetcode.com/problems/assign-cookies/\n题目描述\n 有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小。每个孩子只能吃\n 一个饼干,且只有饼干的大小不小于孩子的饥饿度时,这个孩子才能吃饱。求解最多有多少孩子\n 可以吃饱。\n输入输出样例\n 输入两个数组,分别代表孩子的饥饿度和饼干的大小。输出最多有多少孩子可以吃饱的数\n 量。\n Input: [1,2], [1,2,3]\n Output: 2\n策略\n 首先考虑最小的孩子,使这个孩子吃饱。\n 贪心策略,给剩余孩子里最小饥饿度的孩子分配最小的能吃饱的饼干\n\"\"\"\n\n\ndef findContentChildren(children, cookies):\n # 首先进行排序,\n children.sort()\n cookies.sort()\n child, cookie = 0, 0\n while child < len(children) and cookie < len(cookies):\n if children[child] <= cookies[cookie]:\n child += 1\n cookie += 1\n return child\n\n\nchildren = [1, 2]\ncookies = [1, 2, 3]\n\nchild = findContentChildren(children, cookies)\nprint(child)\n","sub_path":"01.贪心算法/分配问题/455.Assign Cookies (Easy).py","file_name":"455.Assign Cookies (Easy).py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635387525","text":"from setuptools import setup\n\nwith open(\"README.md\", 'r') as f:\n long_description = f.read()\n\nversion_dict = {}\nwith open(\"fortdepend/_version.py\") as f:\n exec(f.read(), version_dict)\n\nname = 'fortdepend'\nversion = version_dict['__version__']\nrelease = version\n\nsetup(name=name,\n version=version,\n description='Automatically generate Fortran dependencies',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author='Peter Hill',\n author_email='peter@fusionplasma.co.uk',\n url='https://github.com/ZedThree/fort_depend.py/',\n download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',\n license='MIT',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Fortran',\n ],\n packages=['fortdepend'],\n install_requires=[\n 'colorama >= 0.3.9',\n 'pcpp >= 1.1.0'\n ],\n extras_require={\n 'tests': ['pytest >= 3.3.0'],\n 'docs': [\n 'sphinx >= 1.4',\n 'sphinx-argparse >= 0.2.3'\n ],\n },\n keywords=['build', 'dependencies', 'fortran'],\n entry_points={\n 'console_scripts': [\n 'fortdepend = fortdepend.__main__:main',\n ],\n },\n command_options={\n 'build_sphinx': {\n 'project': ('setup.py', name),\n 'version': ('setup.py', version),\n 'release': ('setup.py', release),\n 'source_dir': ('setup.py', 'docs'),\n }\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"13470232","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import transform\nfrom compute_wavelet_filter import compute_wavelet_filter\n\n\ndef upsampling(x, d):\n \"\"\"\n up-sampling along dimension d by factor p=2\n \"\"\"\n p = 2\n s = x.shape\n if d == 1:\n y = np.zeros((p * s[0], s[1]))\n y[::p, :] = x\n elif d == 2:\n y = np.zeros((s[0], p * s[1]))\n y[:, ::p] = x\n else:\n raise Exception('Not implemented')\n return y\n\n\ndef subsampling(x, d):\n # subsampling along dimension d by factor p=2\n p = 2\n if d == 1:\n y = x[::p, :]\n elif d == 2:\n y = x[:, ::p]\n else:\n raise Exception('Not implemented')\n return y\n\n\ndef rescale(f, a=0, b=1):\n \"\"\"\n Rescale linearly the dynamic of a vector to fit within a range [a,b]\n \"\"\"\n v = f.max() - f.min()\n g = (f - f.min()).copy()\n if v > 0:\n g = g * 1. / v\n return a * 1. + g * (b - a)\n\n\ndef load_image(name, n=-1, flatten=1, resc=1, grayscale=1):\n \"\"\"\n Load an image from a file, rescale its dynamic to [0,1], turn it into a grayscale image\n and resize it to size n x n.\n \"\"\"\n f = plt.imread(name)\n # turn into normalized grayscale image\n if grayscale == 1:\n if (flatten == 1) and np.ndim(f) > 2:\n f = np.sum(f, axis=2)\n if resc == 1:\n f = rescale(f)\n # change the size of the image\n if n > 0:\n if np.ndim(f) == 2:\n f = transform.resize(f, [n, n], 1)\n elif np.ndim(f) == 3:\n f = transform.resize(f, [n, n, f.shape[2]], 1)\n return f\n\n\ndef circshift1d(x, k):\n \"\"\" \n Circularly shift a 1D vector\n \"\"\"\n return np.roll(x, -k, axis=0)\n\n\ndef cconv(x, h, d):\n \"\"\"\n Circular convolution along dimension d.\n h should be small and with odd size\n \"\"\"\n if d == 2:\n # apply to transposed matrix\n return np.transpose(cconv(np.transpose(x), h, 1))\n y = np.zeros(x.shape)\n p = len(h)\n pc = int(round(float((p - 1) / 2)))\n for i in range(0, p):\n y = y + h[i] * circshift1d(x, i - pc)\n return y\n\n\ndef reverse(x):\n \"\"\"\n Reverse a vector. \n \"\"\"\n return x[::-1]\n\n\ndef perform_wavortho_transf(f, Jmin, dir, h):\n \"\"\"\n perform_wavortho_transf - compute orthogonal wavelet transform\n\n fw = perform_wavortho_transf(f,Jmin,dir,options);\n\n You can give the filter in options.h.\n\n Works in 2D only.\n\n Copyright (c) 2014 Gabriel Peyre\n \"\"\"\n\n n = f.shape[1]\n Jmax = int(np.log2(n) - 1)\n # compute g filter\n u = np.power(-np.ones(len(h) - 1), range(1, len(h)))\n # alternate +1/-1\n g = np.concatenate(([0], h[-1:0:-1] * u))\n\n if dir == 1:\n ### FORWARD ###\n fW = f.copy()\n for j in np.arange(Jmax, Jmin - 1, -1):\n A = fW[:2 ** (j + 1):, :2 ** (j + 1):]\n for d in np.arange(1, 3):\n Coarse = subsampling(cconv(A, h, d), d)\n Detail = subsampling(cconv(A, g, d), d)\n A = np.concatenate((Coarse, Detail), axis=d - 1)\n fW[:2 ** (j + 1):, :2 ** (j + 1):] = A\n return fW\n else:\n ### BACKWARD ###\n fW = f.copy()\n f1 = fW.copy()\n for j in np.arange(Jmin, Jmax + 1):\n A = f1[:2 ** (j + 1):, :2 ** (j + 1):]\n for d in np.arange(1, 3):\n if d == 1:\n Coarse = A[:2**j:, :]\n Detail = A[2**j: 2**(j + 1):, :]\n else:\n Coarse = A[:, :2 ** j:]\n Detail = A[:, 2 ** j:2 ** (j + 1):]\n Coarse = cconv(upsampling(Coarse, d), reverse(h), d)\n Detail = cconv(upsampling(Detail, d), reverse(g), d)\n A = Coarse + Detail\n f1[:2 ** (j + 1):, :2 ** (j + 1):] = A\n return f1\n\n\ndef noisy_observations(n=32, r_sparse=0.2, r_info=0.5):\n \"\"\"\n Measurement function.\n\n Parameters:\n - n is the image size (n x n);\n - r_sparse is the ratio of non-zero coefficients (wavelet domain) of the\n signal x to recover;\n - r_info is the ratio between the size of y and the size of x.\n\n Return y, A, where:\n - y is the vector of measurements;\n - A is the sensing matrix (we look for x such that y = Ax);\n \"\"\"\n\n im = rescale(load_image(\"barb.bmp\", n))\n\n h = compute_wavelet_filter(\"Daubechies\", 4)\n\n # Compute the matrix of wavelet transform\n mask = np.zeros((n, n))\n A0 = []\n for i in range(n):\n for j in range(n):\n mask[i, j] = 1\n wt = perform_wavortho_transf(mask, 0, +1, h)\n A0.append(wt.ravel())\n mask[i, j] = 0\n A0 = np.asarray(A0)\n\n # Gaussian matrix x Wavelet transform (keep ratio r_info)\n G = np.random.randn(int(np.floor(n**2 * r_info)), n**2) / n\n# import pdb; pdb.set_trace()\n A = G.dot(A0)\n\n # Threshold the image (keep ratio r_sparse) and generate the measurements y\n # Same as x_true = A0.T.dot(im.flatten())\n x_true = perform_wavortho_transf(im, 0, +1, h).ravel()\n thshol = np.sort(np.abs(x_true.ravel()))[int((1 - r_sparse) * n**2)]\n x_true[np.abs(x_true) <= thshol] = 0\n y = A.dot(x_true) # Vector of measurements\n\n return y, A\n\n\ndef back_to_image(x):\n n = int(np.sqrt(x.size))\n h = compute_wavelet_filter(\"Daubechies\", 4)\n wt = x.reshape((n, n))\n im = perform_wavortho_transf(wt, 0, -1, h)\n return im\n\n\ndef plot_image(x):\n plt.figure(figsize=(1, 1))\n im = back_to_image(x)\n plt.imshow(im, cmap='gray')\n plt.axis('off')\n\n\ndef total_variation_op(n=32):\n \"\"\"\n Measurement function.\n\n Parameters:\n - n is the image size (n x n);\n\n Return T a total variation operator.\n \"\"\"\n h = compute_wavelet_filter(\"Daubechies\", 4)\n\n # Compute the matrix of wavelet transform\n mask = np.zeros((n, n))\n A0 = []\n for i in range(n):\n for j in range(n):\n mask[i, j] = 1\n wt = perform_wavortho_transf(mask, 0, +1, h)\n A0.append(wt.ravel())\n mask[i, j] = 0\n A0 = np.asarray(A0)\n\n # Total variation operator\n dx = np.eye(n**2)\n dx -= np.roll(dx, 1, axis=1)\n dx = np.delete(dx, np.s_[n - 1::n], axis=0)\n\n dy = np.eye(n**2)\n dy -= np.roll(dy, n, axis=1)\n dy = np.delete(dy, np.s_[-n:], axis=0)\n\n T = np.r_[dx, dy].dot(A0) # TV in the image domain\n\n T = np.r_[np.eye(n**2), T] # For usual L1 norm, add identity\n\n return T\n\n\ndef noisy_observation_inf(n=2**4):\n A = np.zeros((n, n))\n while np.linalg.det(A) == 0:\n A = np.random.randn(n, n)\n y = A.dot(np.ones(n)) + np.random.randn(n)\n return y, A\n\n\ndef noisy_observation_nuclear(n=2**4):\n A = np.random.binomial(1, 0.1, size=(n, n))\n while np.sum(A) <= n / 5:\n A = np.random.binomial(1, 0.1, size=(n, n))\n X = np.ones((n, n))\n Y = A * X\n return Y, A\n","sub_path":"teaching/optimization/cours_optim/TP/tp2_17-18/Code/Code/tp2_tools.py","file_name":"tp2_tools.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550334589","text":"work=[]\nfor i in range(365): #生成一个工作列表\n work.append(1)\nday=0.01\ndayuk=1\ni=1\nwhile i<=365:\n t=dayuk\n for j in range(1,8):\n if i+j>=365 or work[i+j-2]==0:\n dayuk=t\n i=i+j\n break\n elif j in [1,2,3]:\n dayuk=dayuk\n elif j in [4,5,6,7]:\n dayuk=dayuk*(1+day)\n i=i+7\nprint(\"up={:.10f}\".format(dayuk)) \n\n","sub_path":"math.py","file_name":"math.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"369995226","text":"import datetime\nfrom sqlalchemy import (\n Column,\n Index,\n Integer,\n Text,\n func,\n)\nfrom sqlalchemy.dialects.postgresql import JSONB\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n)\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass BaseDataTable(Base):\n __abstract__ = True\n query = DBSession.query\n session = DBSession\n default_sort = [\n ('id', 'asc'),\n ]\n\n\n @classmethod\n def filter_args(cls, q, **kw):\n for k, w in kw.items():\n q = q.filter(getattr(cls, k)==w)\n return q\n\n @classmethod\n def filter_json_args(cls, q, meta={}, data={}):\n for k, w in meta.items():\n q = q.filter(cls.meta[k].astext ==w )\n for k, w in data.items():\n q = q.filter(cls.data[k].astext ==w )\n return q\n\n @classmethod\n def json_search(cls, meta={}, data={}, one=False):\n q = cls.query(cls)\n q = cls.filter_json_args(q, meta, data)\n if one:\n return q.one()\n return q.all()\n\n @classmethod\n def all(cls, **kw):\n q = cls.query(cls)\n q = cls.filter_args(q, **kw)\n return q.all()\n\n @classmethod\n def count(cls, **kw):\n q = cls.query(func.count())\n q = cls.filter_args(q, **kw)\n res = q.one()\n return res[0]\n\n @classmethod\n def one(cls, **kw):\n q = cls.query(cls)\n q = cls.filter_args(q, **kw)\n return q.one()\n\n @classmethod\n def first(cls, **kw):\n q = cls.query(cls)\n q = cls.filter_args(q, **kw)\n return q.first()\n\n @classmethod\n def delete(cls, **kw):\n q = cls.query(cls)\n q = cls.filter_args(q, **kw)\n q.delete()\n\n @classmethod\n def get_header(cls, defaults={}):\n now = datetime.datetime.isoformat(datetime.datetime.now())\n header = {\n 'created': now,\n }\n for k,v in defaults.items():\n header[k] = v\n return header\n\n @classmethod\n def save(cls, header, data, **kw):\n newcls = cls(\n meta=header,\n data=data,\n )\n for k, w in kw.items():\n setattr(newcls, k, w)\n cls.session.add(newcls)\n return newcls\n\n @classmethod\n def doc_update(cls, data={}, header={}, **kw):\n q = cls.query(cls)\n q = cls.filter_args(q, **kw)\n q.update({'data': data}, synchronize_session=False)\n cls.session.flush()\n doc = cls.one(**kw)\n return doc\n\n @classmethod\n def update(cls, data, **kw):\n upd_cls = cls.one(**kw)\n for key, value in data.items():\n setattr(upd_cls, key, value)\n try:\n cls.session.flush()\n except SQLAlchemyError as error:\n cls.session.rollback()\n raise(error)\n return upd_cls","sub_path":"astrobase/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"467171853","text":"from time import time\nimport numpy as np\nfrom pdb2sql.pdb2sqlcore import pdb2sql\nimport unittest\n\n\n\nclass TestCore(unittest.TestCase):\n\t\"\"\"Test Core generation.\"\"\"\n\n\tdef test_core(self):\n\n\t\tt0 = time()\n\t\tdb = pdb2sql(self.pdb)\n\t\tprint('SQL %f' %(time()-t0))\n\t\txyz = db.get('x,y,z',model=0)\n\t\t#db.update('x,y,z',xyz)\n\n\t\txyz = db.get('x,y,z',chainID='A',resName=['VAL','LEU'],name=['CA','C','O','N'])\n\n\n\t\txyz = db.get('x,y,z',chainID='A',resSeq=1)\n\t\txyz = np.array(xyz)\n\t\txyz -= np.mean(xyz)\n\t\t#db.update('x,y,z',xyz,chainID='A',resSeq=1)\n\n\tdef setUp(self):\n\t\tself.pdb = 'pdb/5hvd.pdb'\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_pdb2sqlcore.py","file_name":"test_pdb2sqlcore.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"190729395","text":"import pigpio\nimport time\nfrom datetime import datetime\nfrom nrf24 import *\nimport struct\nfrom os import environ as env\n\n\nif __name__ == \"__main__\":\n print(\"Python NRF24 Receiver 02\")\n \n # Connect to pigpiod\n pi = pigpio.pi(env['PIGPIO_HOST'])\n if not pi.connected:\n print(\"Not connected to Raspberry PI...goodbye.\")\n exit()\n\n # Create NRF24L01 communication object.\n # nrf = NRF24.NRF24(pi, ce=25, payload_size=15, channel=1, crc_bytes=2)\n nrf = NRF24(pi, ce=12, payload_size=RF24_PAYLOAD.DYNAMIC, channel=1, crc_bytes=2, spi_channel=SPI_CHANNEL.AUX_CE2)\n \n # Configure NRF24 transceiver to communicate at 250 KBPS ob channel 1 accepting dynamic payload sizes (1-32 bytes).\n nrf.set_data_rate(RF24_DATA_RATE.DATA_RATE_250KBPS)\n nrf.open_writing_pipe(\"1LD57\")\n nrf.open_reading_pipe(RF24_RX_ADDR.P1, \"GW001\")\n \n # Wait for device to settle and display the content of device registers.\n time.sleep(0.5)\n nrf.show_registers()\n\n protocol_formats = {0: \" 0:\n for test_file in files:\n test_file_path = os.path.join(root, test_file)\n\n\ntest_data = read_data(test_file_path, flag='test')\ntest_counts = Counter(test_data)\nres = \"none\"\nfor i in test_counts:\n try:\n res = dict_words[i]\n break\n except:\n pass\nif res == \"none\":\n print(\"rec\")\nprint(res)\n","sub_path":"simple_model.py","file_name":"simple_model.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"379416550","text":"from django.urls import path\r\nfrom .views import (\r\n ItemListView,\r\n ItemDetailView,\r\n AddToCartView,\r\n OrderDetailView,\r\n PaymentView,\r\n AddCouponView,\r\n\r\n\r\n)\r\n\r\nfrom core.api import views\r\n\r\nurlpatterns = [\r\n\r\n path('products/', ItemListView.as_view(), name='product-list'),\r\n path('products//', ItemDetailView.as_view(), name='product-detail'),\r\n path('add-to-cart/', AddToCartView.as_view(), name='add-to-cart'),\r\n path('order-summary/', OrderDetailView.as_view(), name='order-summary'),\r\n path('checkout/', PaymentView.as_view(), name='checkout'),\r\n path('add-coupon/', AddCouponView.as_view(), name='add-coupon'),\r\n path('address/', views.AddressListView.as_view(), name='address'),\r\n path('createaddress/',\r\n views.CreateAddressListView.as_view(), name='createaddress'),\r\n path('country', views.CountryListView.as_view(), name='country'),\r\n path('userid', views.UserIdView.as_view(), name='userid'),\r\n path('updateaddress//',\r\n views.UpdateAddressListView.as_view(), name='updateaddress'),\r\n path('deleteaddress//',\r\n views.DeleteAdress.as_view(), name='deleteaddress'),\r\n\r\n path('deleteitem//', views.deleteItem.as_view(), name='deleteitem'),\r\n path('removeitem/', views.removefromcart.as_view(), name='deleteitem'),\r\n\r\n path('paymenthistory/', views.PaymentListView.as_view(), name=\"paymenthistory\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n]\r\n","sub_path":"core/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"317808646","text":"#ensure that date is in yyyy-mm-dd format\n#returns the input_date; hence we can do expense_date = get_date() in our app.py\n\n#rationale for converting it to using datetime and back is that if the user puts in integers\n# but invalid date, e.g. for month its 2 but day is 30, then they will reject because feb doesn't have 30 days, etc.\nimport datetime\n\ndef get_date():\n # yyyy-mm-dd \n input_date = \"\"\n while True:\n try:\n input_date = input(\"What is the date? in yyyy-mm-dd: \")\n input_year=\"\" \n input_month=\"\"\n input_day=\"\"\n dash_count = 0\n for char in input_date:\n if char ==\"-\":\n dash_count +=1\n else:\n if dash_count ==0:\n input_year +=char\n elif dash_count ==1:\n input_month += char\n elif dash_count ==2:\n input_day += char \n input_date = datetime.datetime(int(input_year), int(input_month), int(input_day))\n input_date = input_date.strftime(\"%Y-%m-%d\")\n break\n except:\n print(\"Ensure date is valid and is in yyyy-mm-dd format\")\n return input_date\n","sub_path":"helper_functions/get_date.py","file_name":"get_date.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"126639973","text":"import math\nimport cv2\nimport numpy as np\n\ndef wordSegmentation(img, kernelSize, sigma, theta, minArea):\n\t# apply filter kernel\n\tkernel = createKernel(kernelSize, sigma, theta)\n\timgFiltered = cv2.filter2D(img, -1, kernel, borderType=cv2.BORDER_REPLICATE).astype(np.uint8)\n\tcv2.imshow(\"1\", imgFiltered)\n\tcv2.waitKey(0)\n\t(_, imgThres) = cv2.threshold(imgFiltered, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\timgThres = 255 - imgThres\n\n\t# find connected components. OpenCV: return type differs between OpenCV2 and 3\n\tif cv2.__version__.startswith('3.'):\n\t\t(_, components, _) = cv2.findContours(imgThres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\telse:\n\t\t(components, _) = cv2.findContours(imgThres, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n\t# append components to result\n\tres = []\n\tfor c in components:\n\t\t# skip small word candidates\n\t\tif cv2.contourArea(c) < minArea:\n\t\t\tcontinue\n\t\t# append bounding box and image of word to result list\n\t\tcurrBox = cv2.boundingRect(c) # returns (x, y, w, h)\n\t\t(x, y, w, h) = currBox\n\t\tcurrImg = img[y:y+h, x:x+w]\n\t\tres.append((currBox, currImg))\n\n\t# return list of words, sorted by x-coordinate\n\treturn sorted(res, key=lambda entry:entry[0][0])\n\n\n\ndef createKernel(kernelSize, sigma, theta):\n\t\"\"\"create anisotropic filter kernel according to given parameters\"\"\"\n\tassert kernelSize % 2 # must be odd size\n\thalfSize = kernelSize // 2\n\n\tkernel = np.zeros([kernelSize, kernelSize])\n\tsigmaX = sigma\n\tsigmaY = sigma * theta\n\n\tfor i in range(kernelSize):\n\t\tfor j in range(kernelSize):\n\t\t\tx = i - halfSize\n\t\t\ty = j - halfSize\n\n\t\t\texpTerm = np.exp(-x**2 / (2 * sigmaX) - y**2 / (2 * sigmaY))\n\t\t\txTerm = (x**2 - sigmaX**2) / (2 * math.pi * sigmaX**5 * sigmaY)\n\t\t\tyTerm = (y**2 - sigmaY**2) / (2 * math.pi * sigmaY**5 * sigmaX)\n\n\t\t\tkernel[i, j] = (xTerm + yTerm) * expTerm\n\n\tkernel = kernel / np.sum(kernel)\n\treturn kernel\n\n\ndef wordSegment(img):\n kernel_size = 33\n sigma = 11\n theta = 11\n minRect = 900\n blur = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n res = wordSegmentation(blur, kernel_size, sigma, theta, minRect)\n return res\n\n\nimg_file_path = r\"D:\\Desktop\\HandReco\\SimpleHTR\\data\\a01-000u-s00-01.png\"\n#img_file_path = r\"vd1.jpg\"\nimg = cv2.imread(img_file_path)\nimgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nres = wordSegmentation(imgray, 31, 7, 7, 150)\nfor (j, w) in enumerate(res):\n (wordBox, wordImg) = w\n (x, y, w, h) = wordBox\n #cv2.imwrite('../out/%s/%d.png'%(f, j), wordImg)\n cv2.rectangle(img,(x,y),(x+w,y+h),0,1)\n\ncv2.namedWindow(\"1\", cv2.WINDOW_GUI_EXPANDED)\ncv2.imshow(\"1\", img)\ncv2.waitKey(0)\n","sub_path":"src/modules/wordSegmentation.py","file_name":"wordSegmentation.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"337424390","text":"import importlib\nimport logging\nimport os\nimport pkgutil\nimport sys\nfrom pathlib import Path\nfrom typing import List\n\nfrom erin.core.exceptions import EnvironmentVariableError, PluginNotFoundError\n\nlogger = logging.getLogger(__name__)\n\n\ndef find_plugins(package) -> List[str]:\n \"\"\"\n Finds all top level subpackages in a package and presents them in\n the format required by :meth:`discord.ext.cli.Bot.load_extension`.\n\n This is useful when you need to load cogs from multiple\n areas of your bot. Simply convert your cogs directory\n into a package and run this method on it.\n\n Parameters\n -----------\n package : package\n Your package as a python package or a path to one.\n Note: All packages are modules, all modules are not packages.\n\n Returns\n --------\n list or None\n A list of strings of format `foo.bar` as required by\n :meth:`discord.ext.cli.Bot.load_extension`. If package passed is not\n valid then `None` is returned instead.\n \"\"\"\n # Check if parameter is a package\n if hasattr(package, \"__path__\"):\n plugins = pkgutil.walk_packages(package.__path__)\n package_name = os.path.basename(package.__path__[0])\n elif isinstance(package, str):\n if os.path.exists(package):\n plugins = pkgutil.walk_packages([package])\n package_name = os.path.basename(package)\n else:\n raise PluginNotFoundError(package)\n elif isinstance(package, Path):\n if package.exists():\n plugins = pkgutil.walk_packages([package])\n package_name = os.path.basename(str(package))\n else:\n raise PluginNotFoundError(package)\n else:\n raise TypeError(\n f\"expected package, str, pathlib.Path or os.PathLike \"\n f\"object, not {type(package).__name__}\"\n )\n\n # Create plugin import list\n plugins = [f\"{package_name}.{i.name}\" for i in plugins]\n return plugins\n\n\ndef get_plugin_data(plugin):\n \"\"\"\n Retrieve the plugin_data dictionary defined in a plugin.\n Parameters\n -----------\n plugin : path to a plugin in module import format\n Returns\n --------\n dict or None\n The plugin_data dict defined in a plugin or None if the dict is\n not defined.\n \"\"\"\n logger.debug(f\"Attempting Plugin Import: {plugin}\")\n plugin = importlib.import_module(plugin)\n plugin_data = None\n try:\n plugin_data = plugin.plugin_data\n except AttributeError:\n plugin_data = None\n finally:\n del sys.modules[plugin.__name__]\n return plugin_data\n\n\ndef config_loader(mappings, optional_envs):\n for category, settings in mappings.items():\n for setting, value in settings.items():\n if value.startswith(\"ERIN_\"):\n if value in os.environ:\n mappings[category][setting] = os.environ[value]\n elif value in optional_envs:\n mappings[category][setting] = None\n else:\n raise EnvironmentVariableError(\n f\"{value} is not optional.\\n\"\n \"Set this in your TOML config file or use 'export \"\n f\"{value}=YOUR_CUSTOM_VALUE'!\"\n )\n return mappings\n","sub_path":"erin/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"1598967","text":"import cv2\nimport numpy as np\nimport sys\nfrom scipy.optimize import curve_fit as fit\nfrom scipy import exp \nfrom matplotlib import pyplot as plt\n\nimport pdb\n\n\ndrawing = False # true if mouse is pressed\nix = -1 #Creamos un punto inicial x,y\niy = -1,\ndotslist = [] #Creamos una lista donde almacenaremos los puntos del contorno\n\n# mouse callback function\ndef draw_dots(event,x,y,flags,param): #Crea los puntos de contorno\n global ix,iy,drawing, dotslist#Hacemos globales la variabbles dentro de la funcion\n\n if event == cv2.EVENT_LBUTTONDOWN:#creamos la accion que se realizara si damos click\n drawing = True #Drawinf se vuelve True\n ix = x #Tomamos el punto donde se dio click\n iy = y\n dot = [x,y]\n dotslist.append(dot)#Lo agregamos al dotslist\n\n elif event == cv2.EVENT_MOUSEMOVE:#Creamos la accion si el mouse se mueve\n if drawing == True: #drawing se vuelve true\n #cv2.circle(img,(x,y),1,(0,0,255),2)\n cv2.line(img, (x,y), (x,y), (255,255,255), 2)#Dibujamos una linea de un solo pixel\n x = x\n y = y\n dot = [x,y]\n dotslist.append(dot)#Agregamos el punto a dotslist\n #print(dotslist) #Imprimimos el dotslist\n\n elif event == cv2.EVENT_LBUTTONUP:#Cremaos el evento si el boton se levanta\n drawing = False\n #cv2.circle(img,(x,y),1,(0,0,255),1)\n cv2.line(img, (x,y), (x,y), (255,255,255), 2)#Dibujamos la ultima lina en el ultimo punto\n \n return dotslist#Retornamos el dotlist\n\n\ndef Croped(dotslist, img):#hacemos un corte de la imagen en linea recta de tal forma que tenga las \n #dimenciones maximas del poligono que creamos\n rect = cv2.boundingRect(dotslist)#Encontramos los limites maximos del\n (x,y,w,h) = rect#Tomamos las dimenciones maximas del dotlist y las guardamos para dimencionar la mascara\n croped = img[y:y+h, x:x+w].copy()#cortamos una seccion rectangular de la imagen\n dotslist2 = dotslist- dotslist.min(axis=0)#reajustamos el dotslist con el minimo \n\n mask = np.zeros(croped.shape[:2], dtype = np.uint8)# creamos una mascara de ceros para poder hacer el corte irregular\n cv2.drawContours(mask, [dotslist2], -1, (255,255, 255), -1, cv2.LINE_AA)#dibujamos el contorno\n dts = cv2.bitwise_and(croped,croped, mask=mask)#hacemos ceros todos los pixeles externos al contorno\n \n\n return [dts, mask, croped]\n\ndef histogram(img, mask):\n hist = cv2.calcHist([img], [0], mask, [256], [0,256])\n return hist\n\ndef Listing(y):\n y1 = []#Creamos una lista vacia\n for i in range(len(y)):#llenamos la lista vacia con los datos de y, esto porque y es de la forma y = [[],[],[]], y necesitamos y = []\n y1.append(y[i][0]) \n \n return y1\n\n\ndef Countsum(hist, x):\n \n suma = 0\n #pdb.set_trace()\n for i in range(len(hist)):\n if hist[i] != 0:\n suma += x[i]\n \n\n return suma\n\ndef MeanAndSigma(x, y):\n \n mean = sum(x*y)/sum(y) #Calculamos el promedio pesado con los y\n sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))#calculamos la desviacion estandar\n #pdb.set_trace()\n\n return [mean, sigma]\n\ndef gaussModel(x, a, x0, sigma):\n \n f1 = -((x-x0)**2)/(2*(sigma**2))\n y = a*exp(f1)\n \n return y\n\ndef gauss(model, x, y, p0):\n popt, pcov = fit(model, x, y, p0)#popt son los parametros del fit, pcov es la curva del fit\n maxg = popt[0]\n meang = popt[1]\n sigmag = popt[2]\n\n return [maxg, meang, sigmag]\n\ndef maximum_value(hist, gauss):\n hist = np.asarray(hist)\n gauss = np.asarray(gauss)\n\n max_val = max(hist)\n max_ubication = hist.argmax()\n gmax_val = max(gauss)\n gmax_ubication = gauss.argmax()\n \n\n return [max_val, max_ubication, gmax_val, gmax_ubication] \n\ndef normalizer(gaussian1, gaussian2, gaussian3, x):\n Ngaussian1 = []\n Ngaussian2 = []\n Ngaussian3 = []\n Nx = []\n \n Vsmax = [max(gaussian1), max(gaussian2), max(gaussian3), max(x)]\n #Vmax = max(Vsmax)\n \n for i in gaussian1:\n j = i/Vsmax[0]\n Ngaussian1.append(j)\n \n for i in gaussian2:\n j = i/Vsmax[1]\n Ngaussian2.append(j)\n \n for i in gaussian3:\n j = i/Vsmax[2]\n Ngaussian3.append(j)\n \n for i in x:\n j = i/Vsmax[3]\n Nx.append(j)\n \n return [Ngaussian1, Ngaussian2, Ngaussian3, Nx] \n\n\nfiles = [str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3])]\n\nimg = cv2.imread(files[0])#Leemos intensidad de la primera imagen r\nimg1 = cv2.imread(files[0], cv2.IMREAD_GRAYSCALE)\nimg2 = cv2.imread(files[1], cv2.IMREAD_GRAYSCALE)#Leemos intensidad de la segunda imagen g\nimg3 = cv2.imread(files[2], cv2.IMREAD_GRAYSCALE)#Leemos intensidad de la segunda imagen b\n\n\n\ncv2.namedWindow(files[0])#Creamos la ventana para mostras a img1 como indicador para el contorno\ncv2.setMouseCallback(files[0],draw_dots) #llamamos al MouseCall para dibujar el contorno en img1\n\n\nwhile(1):\n cv2.imshow(files[0],img) #Mostramos a img1 en la ventana para dibujar el contono\n\n k = cv2.waitKey(1) & 0xFF\n \n if k == 32: #space\n dotslist = np.asarray(dotslist)#Convertimos el contorno en un array de numpy\n \n #Aplicamos el contorno a la image a partir de dtolist\n img1_croped_BB = Croped(dotslist, img1)[0]#Recuperamos solo la region de interes (imagen cortada con bordes negros)\n img2_croped_BB = Croped(dotslist, img2)[0]#Recuperamos solo la region de interes (imagen cortada con bordes negros)\n img3_croped_BB = Croped(dotslist, img3)[0]#Recuperamos solo la region de interes (imagen cortada con bordes negros)\n \n \n mask1 = Croped(dotslist, img1)[1] #Recuperamos la mascara creada en img1\n mask2 = Croped(dotslist, img2)[1]\n mask3 = Croped(dotslist, img3)[1]\n \n img1_croped = Croped(dotslist, img1)[2]#recuperamos la imagen cortada en rectangulo para analizar con la mascara \n img2_croped = Croped(dotslist, img2)[2]\n img3_croped = Croped(dotslist, img3)[2]\n \n hist1 = histogram(img1_croped, mask1)#Calculamos el histograma usando la mascara #len(hist) = 256\n hist1 = Listing(hist1)\n hist1.pop(0)\n \n hist2 = histogram(img2_croped, mask2)#Calculamos el histograma usando la mascara #len(hist) = 256\n hist2 = Listing(hist2)\n hist2.pop(0)\n \n hist3 = histogram(img3_croped, mask3)#Calculamos el histograma usando la mascara #len(hist) = 256\n hist3 = Listing(hist3)\n hist3.pop(0)\n \n x1 = np.linspace(1.0, len(hist1), len(hist1))\n x2 = np.linspace(1.0, len(hist2), len(hist2))\n x3 = np.linspace(1.0, len(hist3), len(hist3)) \n x4 = np.linspace(1.0, 60, len(hist2))\n #[mean1, sigma1] = MeanAndSigma(x1, hist1)\n #[maxg1, meang1, sigmag1] = gauss(gaussModel, x1, hist1, p0=[max(hist1), mean1, sigma1])#popt son los parametros del fit, pcov es la curva del fit\n #fit1 = gaussModel(x1, maxg1, meang1, sigma1)\n \n [mean2, sigma2] = MeanAndSigma(x2, hist2)\n [maxg2, meang2, sigmag2] = gauss(gaussModel, x2, hist2, p0=[max(hist2), mean2, sigma2])#popt son los parametros del fit, pcov es la curva del fit\n fit1 = gaussModel(x4, maxg2, 20, sigma2)\n fit2 = gaussModel(x4, maxg2, 17, sigma2)\n fit3 = gaussModel(x4, maxg2, 61, sigma2)\n \n #[mean3, sigma3] = MeanAndSigma(x3, hist3)\n #[maxg3, meang3, sigmag3] = gauss(gaussModel, x3, hist3, p0=[max(hist3), mean3, sigma3])#popt son los parametros del fit, pcov es la curva del fit\n #fit3 = gaussModel(x3, maxg3, meang3, sigma3)\n #pdb.set_trace()\n\n [Nfit1, Nfit2, Nfit3, Nx] = normalizer(fit1, fit2, fit3, x4)\n\n \n #pdb.set_trace()\n #Tcount1 = Countsum(hist1, x1)\n #print(\"Las cuentas totales distintas de cero para \" + files[0] + \" es \" + str(Tcount1))\n #Tcount2 = Countsum(hist2, x2)\n #print(\"Las cuentas totales distintas de cero para \" + files[1] + \" es \" + str(Tcount2))\n #Tcount3 = Countsum(hist3, x3)\n #print(\"Las cuentas totales distintas de cero para \" + files[2] + \" es \" + str(Tcount3))\n \n #name1 = files[0].replace('.tif', '')#b\n #name2 = files[1].replace('.tif', '')#b\n #name3 = files[2].replace('.tif', '')#b\n \n [hist_max_val1, hist_max_ubication1, gmax_val1, gmax_ubication1]= maximum_value(hist1, fit1)\n #fig1 = plt.figure()\n #ax1 = fig1.add_subplot(111)\n #ax1.set_xlabel('Intensity Values', fontsize= 12)\n #ax1.set_ylabel('Counts', fontsize= 12)\n #ax1.set_title('Histogram of: ' + name1)\n ##ax1.set_xticks(np.arange(0, len(x1), step=20))\n #ax1.plot(x1, hist1, '-', color='red', markersize=6, label = 'histogram', linewidth=2)#ploteamos el histograma\n #ax1.plot(x2, fit1, '-', color='teal', markersize=1, label = 'gaussian fit', linewidth=1)#ploteamos el histograma\n #ax1.axvline(x = gmax_ubication1)#DIbujamos una linea vertical\n #ax1.text(gmax_ubication1 + 25, (hist_max_val1)/2, 'max value: ' + str(gmax_ubication1))\n #ax1.legend(loc='best')\n #plt.savefig('Histogram of ' + name1) \n \n [hist_max_val2, hist_max_ubication2, gmax_val2, gmax_ubication2]= maximum_value(hist2, fit2)\n #fig2 = plt.figure()\n #ax2 = fig2.add_subplot(111)\n #ax2.set_xlabel('Intensity Values', fontsize= 12)\n #ax2.set_ylabel('Counts', fontsize= 12)\n #ax2.set_title('Histogram of: ' + name2)\n #ax2.set_xticks(np.arange(0, len(x2), step=20))\n #ax2.plot(x2, hist2, '-', color='red', markersize=6, label = 'histogram', linewidth=2)#ploteamos el histograma\n #ax2.plot(x2, fit2, '-', color='teal', markersize=1, label = 'gaussian fit', linewidth=1)#ploteamos el histograma\n #ax2.axvline(x = gmax_ubication2)#DIbujamos una linea vertical\n #ax2.text(gmax_ubication2 + 25, (hist_max_val2)/2, 'max value: ' + str(gmax_ubication2))\n #ax2.legend(loc='best')\n #plt.savefig('Histogram of ' + name2) \n\n\n [hist_max_val3, hist_max_ubication3, gmax_val3, gmax_ubication3]= maximum_value(hist3, fit3)\n #fig3 = plt.figure()\n #ax3 = fig3.add_subplot(111)\n #ax3.set_xlabel('Intensity Values', fontsize= 12)\n #ax3.set_ylabel('Counts', fontsize= 12)\n #ax3.set_title('Histogram of: ' + name3)\n #ax3.set_xticks(np.arange(0, len(x3), step=20))\n #ax3.plot(x3, hist3, '-', color='red', markersize=6, label = 'histogram', linewidth=2)#ploteamos el histograma\n #ax3.plot(x3, fit3, '-', color='teal', markersize=1, label = 'gaussian fit', linewidth=1)#ploteamos el histograma\n #ax3.axvline(x = gmax_ubication3)#DIbujamos una linea vertical\n #ax3.text(gmax_ubication3 + 25, (hist_max_val3)/2, 'max value: ' + str(gmax_ubication3))\n #ax3.legend(loc='best')\n #plt.savefig('Histogram of ' + name3)\n \n Legends = ['Calcium', 'Carbon', 'Oxigen']\n \n \n ElementMark1 = gmax_ubication1\n ElementMark2 = gmax_ubication2\n ElementMark3 = gmax_ubication3\n \n ticks = [ElementMark1, ElementMark2, ElementMark3]\n ticksLabels = ['Calcium', 'Carbon', 'Oxygen']\n \n fig4 = plt.figure()\n ax4 = fig4.add_subplot(111)\n ax4.set_xlabel('Element', fontsize= 20)\n ax4.set_ylabel('Intensity (arb. unit)', fontsize= 20)\n #ax4.set_title('Histogram of: ' + name1)\n ax4.set_xticks(np.arange(0, len(Nx), step=0.1))\n ax4.tick_params(direction='in', length=4, width=2, labelsize=15)\n ax4.set_xlim(left=0,right=1, emit=True)\n ax4.plot(Nx, Nfit1, '-', color='orange', markersize=8, label = 'Calcium', linewidth=2)#ploteamos el histograma\n ax4.plot(Nx, Nfit2, '-', color='teal', markersize=8, label = 'Carbon', linewidth=2)#ploteamos el histograma\n ax4.plot(Nx, Nfit3, '-', color='crimson', markersize=8, label = 'Oxygen', linewidth=2)\n #ax4.axvline(x = ElementMark1)#DIbujamos una linea vertical\n #ax4.axvline(x = ElementMark2)#DIbujamos una linea vertical\n #ax4.axvline(x = ElementMark3)#DIbujamos una linea vertical\n #ax4.text(gmax_ubication1 + 25, (hist_max_val1)/2, 'max value: ' + str(gmax_ubication1))#etiqueta de ubicacipn del maximo\n ax4.legend(loc='best')\n #plt.savefig('Histogram of ' + name1) \n\n plt.show()\n \n #cv2.imshow('croped1' + files[0], img1_croped_BB)#Mostramos img2 con el contorno \n #cv2.imshow('croped2' + files[1], img2_croped_BB)#Mostramos img2 con el contorno \n #cv2.imshow('croped3' + files[2], img3_croped_BB)#Mostramos img2 con el contorno \n \n\n #cv2.imwrite(\"Corte_\" + name1 +'.jpg', img1_croped_BB) \n #cv2.imwrite(\"Corte_\" + name2 +'.jpg', img2_croped_BB)\n #cv2.imwrite(\"Corte_\" + name3 +'.jpg', img3_croped_BB) \n\n\n if k == 27:#esc\n #pdb.set_trace()\n break# hace,el break para para el programa si se estripa esc\n\ncv2.destroyAllWindows()#Destruimos todas las ventanas","sub_path":"Analisis_CaCO3/prueba1/SpectrumIntegrator2.py","file_name":"SpectrumIntegrator2.py","file_ext":"py","file_size_in_byte":13110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39079598","text":"import os\n \npath=\"data\" \ndirList=os.listdir(path)\norderedDirList=sorted(dirList)\ni=0\nfor fname in orderedDirList:\n previous_name = path + \"/\" + fname\n new_name = path + \"/%03d.jpg\" % i\n \n os.rename(previous_name,new_name) \n i+=1","sub_path":"resurs/dirName.py","file_name":"dirName.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"17687931","text":"import subprocess\nimport os\nimport sys\nfrom distutils.dir_util import copy_tree\n\nif os.path.isfile('gen'):\n sys.exit('Error: \"gen\" already exists as a regular file')\nos.makedirs('gen', exist_ok=True)\n\ncompleted_process = subprocess.run([\n 'pandoc',\n '-o', 'gen/index.html',\n '-s',\n '--template=pyta_template.html',\n '--highlight-style=zenburn',\n '-V',\n 'root=./',\n 'index.md',\n '--filter',\n 'filters/includes.py'\n], stdout=subprocess.PIPE)\n\ncopy_tree('images', 'gen/images') # overwrite existing location with copy_tree.\ncopy_tree('styles', 'gen/styles')\n\nif not completed_process.returncode:\n print('Successful Build. Open gen/index.html to see the website.')\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"359798472","text":"# !usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author:happy_code\n@email: happy_code@foxmail.com\n@file: getdocid.py\n@time: 2018/11/29\n\"\"\"\nimport datetime\nimport json\nimport re\nimport time\n\nimport execjs\n\n\nclass TimeUtils(object):\n @staticmethod\n def get_between_day(b_date, e_date):\n \"\"\"\n 获取区间每一天的生成器\n :param begin_date: str 开始日期\n :param end_date: str 结束日期,默认为当前日期\n :return: str\n \"\"\"\n b_date = datetime.datetime.strptime(b_date, \"%Y-%m-%d\")\n e_date = datetime.datetime.strptime(e_date, \"%Y-%m-%d\")\n while b_date <= e_date:\n date_str = b_date.strftime(\"%Y-%m-%d\")\n b_date += datetime.timedelta(days=1)\n yield date_str\n\n\nclass GetDocId(object):\n\n def __init__(self):\n with open('docid.js', encoding='utf-8') as f:\n jsdata_2 = f.read()\n self.js_2 = execjs.compile(jsdata_2)\n\n def work(self, filepath):\n # 解析全部的id\n lis = []\n for i in self.get_docids(filepath):\n lis.append(i)\n\n topath = filepath.split('.txt')[0]\n topath += '-id.txt'\n with open(topath, 'w', encoding='utf-8') as f:\n for i in lis:\n f.write(i + '\\n')\n return len(lis)\n\n def works(self, begin_date, end_date):\n \"\"\"\n 解决一段日期的文件\n :param begin_date:\n :param end_date:\n :return:\n \"\"\"\n num = 0\n for date in TimeUtils.get_between_day(begin_date, end_date):\n year = date[:4]\n dirpath = '../../answer/' + year + '/'\n filepath = dirpath + date + '.txt'\n temp = self.work(filepath)\n print('日期 {0} 下文书数量: {1}'.format(date, temp))\n num += temp\n return num\n\n def get_docids(self, filepath):\n \"\"\"\n 解析docid\n :param filepath: 文件路径\n :return:\n \"\"\"\n lis = []\n with open(filepath, 'r', encoding='utf-8') as f:\n line = f.readline()\n while line:\n lis.append(line)\n line = f.readline()\n\n for data in lis:\n result = data.split(',')\n try:\n runeval = result[0]\n content = result[1:]\n for doc_id in self.decrypt_id(runeval, content):\n yield doc_id\n except KeyError:\n print('KeyError')\n except:\n print('解密错误')\n\n def decrypt_id(self, runeval, cids):\n \"\"\"\n docid解密,必须传入一组json\n :param runeval: 运行参数\n :param cids: 待解密id列表\n :return: docid\n \"\"\"\n js = self.js_2.call(\"GetJs\", runeval)\n js_objs = js.split(\";;\")\n js1 = js_objs[0] + ';'\n js2 = re.findall(r\"_\\[_\\]\\[_\\]\\((.*?)\\)\\(\\);\", js_objs[1])[0]\n key = self.js_2.call(\"EvalKey\", js1, js2)\n key = re.findall(r\"\\\"([0-9a-z]{32})\\\"\", key)[0]\n\n for cid in cids:\n yield self.js_2.call(\"DecryptDocID\", key, cid)\n\n\nif __name__ == '__main__':\n c = GetDocId()\n\n begin_date = '2001-01-01'\n end_date = '2001-01-01'\n\n cur_time = time.strftime('%Y-%m-%d, %H:%M:%S', time.localtime(time.time()))\n print('开始时间:' + cur_time)\n num = c.works(begin_date, end_date)\n print('解析{}个完成'.format(num))\n cur_time = time.strftime('%Y-%m-%d, %H:%M:%S', time.localtime(time.time()))\n print('结束时间:' + cur_time)\n\n","sub_path":"Wenshu/utils/decrypt_docids/getdocid.py","file_name":"getdocid.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"4621707","text":"__author__ = 'gregortaube'\nfrom math import *\nimport sys\n\nx,y,z = input().split()\n\noperator = ['+','-','*','/']\n\ndef checkEquality(operand1,operand2,result,operators,case1):\n for op in operators:\n exp = operand1 + op + operand2\n ans = eval(operand1 + op + operand2)\n if ans == int(result):\n if case1:\n exp = exp + '=' + result\n else:\n exp = result + '=' + exp\n print(exp)\n sys.exit()\n\n\ncheckEquality(x,y,z,operator,True)\ncheckEquality(y,z,x,operator,False)\n\n\n","sub_path":"intermediate/tri.py","file_name":"tri.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"37353128","text":"\"\"\"\nYou are given a m x n 2D grid initialized with these three possible values.\n\n1) -1 <-> A wall or an obstacle.\n2) 0 <-> A gate.\n3) INF <-> Infinity means an empty room. We use the value 2^31 - 1 = 2147483647 to represent INF as you may assume\nthat the distance to a gate is less than 2147483647.\n\nFill each empty room with the distance to its nearest gate.\nIf it is impossible to reach a gate, it should be filled with INF.\n\nFor example, given the 2D grid:\n\nINF -1 0 INF\nINF INF INF -1\nINF -1 INF -1\n 0 -1 INF INF\n\nAfter running your function, the 2D grid should be:\n\n 3 -1 0 1\n 2 2 1 -1\n 1 -1 2 -1\n 0 -1 3 4\n\n\"\"\"\nfrom collections import deque\n\n\ndef wall_and_gates(grid):\n if not grid or not grid[0]:\n return grid\n\n GATE, EMPTY = 0, 2 ** 31 - 1\n n, m = len(grid), len(grid[0])\n queue = deque([])\n\n for i in range(n):\n for j in range(m):\n if grid[i][j] == GATE:\n queue.append((i, j))\n\n while queue:\n x, y = queue.popleft()\n\n for next_x, next_y in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):\n if 0 <= next_x < n and 0 <= next_y < m and grid[next_x][next_y] == EMPTY:\n grid[next_x][next_y] = grid[x][y] + 1\n queue.append((next_x, next_y))\n\n return grid\n\n\nif __name__ == '__main__':\n INF = 2 ** 31 - 1\n grid = [[INF, -1, 0, INF], [INF, INF, INF, -1], [INF, -1, INF, -1], [0, -1, INF, INF]]\n\n for row in grid:\n print(row)\n\n print('\\n')\n\n for row in wall_and_gates(grid):\n print(row)\n","sub_path":"Problems/companies/Facebook/Walls and Gates.py","file_name":"Walls and Gates.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"371289887","text":"import gevent\nfrom gevent.event import Event\n\nfrom .util import exit_on_error\n\n\ndef run_status_logger(log_status, get_status, status_interval):\n \"\"\"Start a status logger loop in a greenlet\n\n Log status every `status_interval` seconds unless it evaluates to\n false, in which case the loop is not started.\n\n :param log_status: a status logging function.\n :param get_status: a function returning a status object to be logged.\n :param status_interval: number of seconds between status logging.\n :returns: A function that stops the logger loop.\n \"\"\"\n @exit_on_error\n def status_logger():\n log_status(get_status())\n while not exit.wait(timeout=status_interval):\n log_status(get_status())\n log_status(get_status())\n\n def stop():\n exit.set()\n loop.join()\n\n if status_interval:\n exit = Event()\n loop = gevent.spawn(status_logger)\n return stop\n return lambda: None\n","sub_path":"corehq/apps/couch_sql_migration/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"217798188","text":"import matplotlib.pyplot as plt\nfrom pontiPy import *\n\n\nlabels = ['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Miss', 'False Alarm']\nmen_means = [20, 35, 30, 35, 27]\nwomen_means = [25, 32, 34, 20, 25]\nwidth = 0.5 # the width of the bars: can also be len(x) sequence\n\nfig, ax = plt.subplots()\n\nax.barh(labels, men_means, width, label='Men')\nax.barh(labels, women_means, width, left=men_means, label='Women')\n\nax.set_ylabel('Entry size as a number of Observations')\nax.set_title('')\nax.legend()\n\nplt.show()","sub_path":"Testing/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"129381361","text":"\"Helper function for colored terminal outputs\"\n\n\nLINE_LENGTH = 100\nBLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38)\n\n\ndef colorify(message, color=BLUE):\n \"\"\"Change color of the standard output.\n\n Parameters\n ----------\n message : str\n The message to color.\n\n Returns\n -------\n color_message : str\n The colored message to be displayed in terminal.\n \"\"\"\n return (\"\\033[1;%dm\" % color) + message + \"\\033[0m\"\n","sub_path":"benchopt/utils/colorify.py","file_name":"colorify.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157548434","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.3.1'\n\nhere = os.path.abspath(os.path.dirname(__file__))\ntry:\n README = open(os.path.join(here, 'README.rst')).read()\nexcept IOError:\n README = ''\n\nsetup(name='tgext.coffeescript',\n version=version,\n description=\"CoffeeScript middleware for TurboGears2\",\n long_description=README,\n classifiers=[\n \"Environment :: Web Environment\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"License :: OSI Approved :: MIT License\",\n \"Framework :: TurboGears\"\n ],\n keywords='turbogears2.extension CoffeeScript WSGI jinja2.extension',\n author='Carlos Daniel Ruvalcaba Valenzuela',\n author_email='clsdaniel@gmail.com',\n url='http://bitbucket.org/clsdaniel/tgext.coffeescript',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n namespace_packages=['tgext'],\n include_package_data=True,\n package_data = {'':['*.html', '*.js', '*.css', '*.png', '*.gif']},\n zip_safe=False,\n install_requires=[\n \"TurboGears2 >= 2.0b7\",\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"pypi_install_script/tgext.coffeescript-0.3.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"489711756","text":"import os\nimport pickle\n\nimport numpy as np\n\nHIDDEN_LAYER_COUNT = 2\nHIDDEN_LAYER_UNITS = [5, 4]\n# HIDDEN_LAYER_UNITS = [5, 10, 20, 40, 60, 30, 20, 5]\n\nRANDOM_MODEL_PATH = '../deep_learning/random.model'\nFINAL_MODEL_PATH = '../deep_learning/final.model'\n\niteration_count = 100\n\nalpha = 0.1\n\nTRAIN_DATA_PATH = '../deep_learning/testSetRBF.txt'\nTEST_DATA_PATH = '../deep_learning/testSetRBF2.txt'\n\n\ndef store_model(model, file_path):\n fw = open(file_path, \"wb\")\n pickle.dump(model, fw)\n fw.close()\n\n\ndef load_model(file_path):\n fr = open(file_path, \"rb\")\n return pickle.load(fr)\n\n\ndef load_data(file_path=TRAIN_DATA_PATH):\n data_set = []\n label = []\n with open(file_path, 'r') as fr:\n for line in fr.readlines():\n line_array = line.strip().split('\\t')\n data_set.append([float(line_array[0]), float(line_array[1])])\n label.append(float(line_array[2]))\n data_set = np.mat(data_set)\n label = np.mat(label).T\n row_index, _ = np.nonzero(label < 0)\n label[row_index] = 0\n return data_set, label\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef make_network_framework(feature_count, hidden_layer_count=HIDDEN_LAYER_COUNT, unit_count_list=HIDDEN_LAYER_UNITS):\n if len(unit_count_list) != hidden_layer_count:\n return None\n weight_list = []\n bias_list = []\n input_dimension = feature_count\n for i in range(hidden_layer_count):\n unit_count = unit_count_list[i]\n weight = np.mat(np.random.rand(unit_count, input_dimension))\n b = np.random.rand(unit_count, 1)\n weight_list.append(weight)\n bias_list.append(b)\n input_dimension = unit_count\n # output layer\n weight = np.mat(np.random.rand(1, input_dimension))\n b = np.mat(np.random.rand(1, 1))\n weight_list.append(weight)\n bias_list.append(b)\n return {'weight': weight_list, 'bias': bias_list, 'layers': hidden_layer_count + 1}\n\n\n# TODO split data into batch\ndef make_single_hidden_layer_network(data, label):\n x = np.mat(data).T\n y = label.T\n feature_count, data_count = x.shape\n network = make_network_framework(feature_count=feature_count)\n weight_list = network['weight']\n bias_list = network['bias']\n store_model({'weight': weight_list, 'bias': bias_list}, RANDOM_MODEL_PATH)\n layers = network['layers']\n print(weight_list)\n z_cache = [x]\n for layer in range(HIDDEN_LAYER_COUNT):\n z = np.mat(np.zeros((HIDDEN_LAYER_UNITS[layer], data_count)))\n z_cache.append(z)\n # output z cache\n z_cache.append(np.mat(np.zeros((1, data_count))))\n\n for iter_count in range(iteration_count):\n # print('iteration count: ', iter_count)\n a = z_cache[0]\n for layer in range(layers):\n weight = weight_list[layer]\n bias = bias_list[layer]\n z = weight * a + bias\n a = sigmoid(z)\n z_cache[layer + 1] = z\n # output layer a\n dai = - (y / a) + (1 - y) / (1 - a)\n for layer in range(layers - 1, -1, -1):\n ai = sigmoid(z_cache[layer + 1])\n ai_1 = sigmoid(z_cache[layer])\n weight = weight_list[layer]\n bias = bias_list[layer]\n # calulate dw\n dw = np.mat(np.zeros(weight.shape))\n db = np.mat(np.zeros(bias.shape))\n base = np.multiply(dai, np.multiply(ai, (1 - ai)))\n for i in range(data_count):\n if i == 99:\n print('')\n dw = dw + np.dot(base[:, i], ai_1[:, i].T)\n db = db + base[:, i]\n dw = dw / data_count\n print('iteration: ', iter_count)\n print('dw: ', dw)\n db = db / data_count\n # update da\n dai = np.dot(weight.T, base)\n # update weight\n weight_list[layer] = weight - alpha * dw\n # update db\n bias_list[layer] = bias - alpha * db\n return weight_list, bias_list\n\n\ndef predict(weight_list, bias_list, data):\n if len(weight_list) != len(bias_list):\n print('Predict Error. ')\n return None\n layers = len(weight_list)\n value = np.mat(data).T\n for layer in range(layers):\n weight = weight_list[layer]\n bias = bias_list[layer]\n value = sigmoid(np.dot(weight, value) + bias)\n return value\n\n\ndef main():\n if not os.path.exists(FINAL_MODEL_PATH):\n train_set, train_label = load_data(TRAIN_DATA_PATH)\n weight_list, bias_list = make_single_hidden_layer_network(train_set, train_label)\n store_model({'weight': weight_list, 'bias': bias_list}, FINAL_MODEL_PATH)\n print(weight_list)\n\n test_set, test_label = load_data(TEST_DATA_PATH)\n test_count, _ = test_set.shape\n correct_count = 0\n network = load_model(RANDOM_MODEL_PATH)\n # network = load_model(FINAL_MODEL_PATH)\n weight_list = network['weight']\n bias_list = network['bias']\n for i in range(test_count):\n value = predict(weight_list, bias_list, test_set[i, :])\n real_value = test_label[i, 0]\n if value > 0.5:\n value = 1\n else:\n value = 0\n if value == real_value:\n correct_count += 1\n print(correct_count, test_count, float(correct_count) / test_count)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"deep_learning/single_hidden_layer.py","file_name":"single_hidden_layer.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"564976286","text":"from efficientnet_pytorch import EfficientNet\nimport numpy as np\nimport os\nimport torch\nimport torch.nn as nn\nimport time\ntry:\n from apex.parallel import DistributedDataParallel as DDP\n from apex.fp16_utils import *\n from apex import amp, optimizers\n from apex.multi_tensor_apply import multi_tensor_applier\nexcept ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to run this example.\")\nfrom DataAug import *\nfrom Functions import *\nfrom Dataset import *\n\n\n\ndef train_fold(fold):\n\n #hyperparameters\n epochs=65\n lr=2e-4\n lr_decay=0.3\n lr_decay_period=15\n weight_decay=1e-4\n save_freq=1\n batch_size=48\n checkpoints_folder='checkpoints'\n reload_tensor_epoch=-1\n reload_tensor_path=\"/mnt/sda1/Kaggle/PANDA/data/processed_data/512x512.p\"\n reload_batch_size=16\n cutout_ratio=0.6\n num_classes=[6,4,4,]\n label_weights=[1,0,0]\n label_smoothing=0.05\n n_drop_tile=4\n\n #dataset\n tensor_path=\"/mnt/sda1/Kaggle/PANDA/data/processed_data/concat_n12.p\"\n csv_path='/mnt/sda1/Kaggle/PANDA/data/train.csv'\n\n\n dataset=PANDADataset(tensor_path,csv_path,fold=fold,batch_size=batch_size)\n checkpoints_folder='checkpoints_fold{}'.format(fold)\n csv_file='log_fold{}.csv'.format(fold)\n #exit()\n\n #gpu selection\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n cpu_device = torch.device('cpu')\n\n\n #network\n import torchvision.models as models\n from Network import Network\n from LabelSmoothingLoss import LabelSmoothingLoss\n model = Network(num_classes,'efficientnet-b1',dropout_p=0.5).to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n opt_level = 'O1'\n model, optimizer = amp.initialize(model, optimizer, opt_level=opt_level)\n model = nn.DataParallel(model)\n\n\n #training loop\n pytorch_total_params = sum(p.numel() for p in model.parameters())\n print('Total number of paramters: {}'.format(pytorch_total_params))\n\n\n for epoch in range(epochs):\n if epoch==reload_tensor_epoch:\n dataset.reload_tensor(reload_tensor_path,reload_batch_size)\n mean=torch.Tensor(dataset.data_mean).to(device).reshape(1,1,3,1,1)\n std=torch.Tensor(dataset.data_std).to(device).reshape(1,1,3,1,1)\n model.train(True)\n t=time.time()\n total_loss=0\n for step in range(dataset.train_batches):\n #for step in range(10):\n x,y=dataset.get_batch(step)\n x=drop_tile(x,n_drop_tile)\n #print(x.shape)\n #exit()\n x=torch.Tensor(x)\n x=x.to(device)\n x=rotate_and_flip(x,device,p=0.5)\n #y=[torch.Tensor(y[i]).to(device,dtype=torch.int64) for i in range(len(num_classes))]\n y=torch.Tensor(y[0]).to(device,dtype=torch.int64)\n #y=int2onehot(y,device)\n x=standardize_batch(x,mean,std)\n optimizer.zero_grad()\n #x=cutout(x,device,cutout_ratio,std)\n outputs=model(x)\n #loss=multi_label_crossentropy(outputs,y,label_weights)\n loss=smoothcrossentropyloss(outputs,y,smoothing=label_smoothing)\n #loss=criterion(outputs,y)\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n #loss.backward()\n #torch.nn.utils.clip_grad_norm_(model.parameters(), 1)\n optimizer.step()\n total_loss+=loss.item()\n\n print (\"Epoch [{}/{}], Step [{}/{}] Loss: {:.4f} Time: {}\"\n .format(epoch+1, epochs, step+1, dataset.train_batches, total_loss/(step+1) ,time.time()-t),end='\\r',flush=True) #total_loss/(step+1)\n print('')\n if (epoch+1)%lr_decay_period==0:\n lr*=lr_decay\n update_lr(optimizer,lr)\n\n if (epoch+1)%save_freq==0:\n save_weights(model,optimizer,epoch,checkpoints_folder)\n\n validate(model,csv_file,device,dataset,mean,std,epoch)\n del model\n\nfor fold in range(5):\n train_fold(fold)\n","sub_path":"resnext50_multihead/train_5_fold.py","file_name":"train_5_fold.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"294151331","text":"\n# 파일을 연다.\nopenfile = open(\n \"C:/Python 20200209/Python기초20200103/st01.Python기초/py31파일처리/file/data.csv\", \"r\", encoding=(\"UTF-8\"))\n# 파일 안의 각 줄을 처리한다.\nfor line in openfile.readlines():\n line = line.strip()\n parts = line.split(\",\")\n for part in parts:\n print(\" \", part)\n\nopenfile.close()\n\n# 공백 문자를 없앤다.\n\n# 줄을 출력한다.\n\n# 줄을 쉼표로 분리한다.\n\n# 각 줄의 필드를 출력한다.\n","sub_path":"py31파일처리/py31_11_csv.py","file_name":"py31_11_csv.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"622098441","text":"def sortword(word):\n if word.find('a') != -1:\n if word.index('a')>0 and word.index('a')')\n p.add_option('-p', '--print', dest='print',\n action='store_true', default=False,\n help='print player data')\n p.add_option('-v', '--version', dest='version',\n help='upgrade player file to version')\n p.add_option('--to_json', dest='to_json',\n action='store_true', default=False,\n help='dump player file as JSON')\n p.add_option('--from_json', dest='from_json',\n action='store_true', default=False,\n help='load JSON into player file')\n p.add_option('-o', '--output_file', dest='output_file',\n help='output file')\n options, arguments = p.parse_args()\n # Get the path from arguments.\n if len(arguments) != 1:\n p.error('incorrect number of arguments')\n \n if options.from_json:\n # Input file is a JSON file\n try:\n # Open the file\n fh = open(arguments[0], 'r')\n player_json = json.load(fh)\n fh.close()\n player = starbound.sbvj01.SBVJ01(player_json=player_json)\n except Exception as e:\n p.error('could not open file ({})'.format(e))\n else:\n # Input file is a .player file\n try:\n # Open the file\n fh = open(arguments[0], 'rb')\n file_size = os.fstat(fh.fileno()).st_size\n player = starbound.sbvj01.SBVJ01(fh)\n fh.close()\n except Exception as e:\n p.error('could not open file ({})'.format(e))\n \n # Just pretty print the player data\n if options.print:\n pp.pprint(player.deserialize())\n \n if options.version:\n if int(options.version) == 25:\n starbound.versioning.upgrade_player_12_25(player)\n output_player = True\n \n \n output_player = False\n output_json = False\n \n if options.to_json:\n if options.output_file:\n player_json = {\n 'name' : player.name,\n 'version' : player.version,\n 'data' : player.data\n }\n \n output_json = True\n \n if options.from_json:\n output_player = True\n \n if output_player or output_json:\n if options.output_file:\n # Just to be safe, don't overwrite an existing file\n if os.path.isfile(options.output_file):\n print(\"ERROR: file {} already exists!\".format(options.output_file))\n else:\n if output_player:\n ofh = open(options.output_file, \"wb\")\n player.serialize(ofh)\n ofh.close()\n if output_json:\n ofh = open(options.output_file, \"w\")\n json.dump(player_json, ofh, indent=2, separators=(',', ': '))\n ofh.close()\n \n else:\n print(\"WARNING: 'version' option selected but with no output file.\")\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"player_utils.py","file_name":"player_utils.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"346731495","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA manage.py script to centralized all cli commands\nCreated on 21/10/2019\n@author: Anurag\n\"\"\"\n\n# imports\nimport argparse\n\n# local imports\nfrom db.models import AuthUserModel, db\nfrom db.threat_orm import threat_db\nfrom settings import HOST, PORT\nfrom api.views import app\n\nparser = argparse.ArgumentParser()\n\n# Add the arguments\nparser.add_argument('-m', metavar='--makemigration', type=str, dest='migrate', help='create the database tables')\nparser.add_argument('-r', metavar='--runserver', type=str, dest='run', help='run the flask server')\nparser.add_argument('-i', metavar='--ipaddress', type=str, dest='ip', help='create client license entry to auth table')\nparser.add_argument('-n', metavar='--clientname', type=str, dest='name', help='add client name entry to the auth table')\nparser.add_argument('-f', metavar='--flushdb', type=str, dest='flush', help='clean db by deleting all records')\n\n# Execute the parse_args() method\nargs = parser.parse_args()\napp.app_context().push()\n\n\ndef migrate():\n \"\"\"\n A migrate command for creating database tables\n :return:\n \"\"\"\n db.init_app(app)\n db.create_all()\n db.session.commit()\n\n\ndef add_license():\n \"\"\"\n A function to add api key to the client details table\n :return:\n \"\"\"\n client = AuthUserModel(client_ip=args.ip, client_name=args.name)\n db.session.add(client)\n db.session.commit()\n\n\ndef flush_db():\n \"\"\"\n Clear out all tables\n :return:\n \"\"\"\n threat_db.flush_ip()\n threat_db.flush_url()\n threat_db.flush_cve()\n\n\ndef runserver():\n \"\"\"\n For running flask server\n :return:\n \"\"\"\n app.run(host=HOST, port=PORT)\n\n\nif __name__ == '__main__':\n if args.migrate:\n migrate()\n elif args.run:\n runserver()\n elif args.ip and args.name:\n add_license()\n elif args.flush:\n flush_db()\n else:\n runserver()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444673881","text":"\nimport sys\nsys.path.insert(1,'/home/rhiba/aoc2019/utils')\nimport intcode\n#def operate(position,relbase,ops,inputs=[],outputs=[],threaded=False):\n# return position, relbase\nimport threading\n\ndef run_computer(ops,inputs,outputs):\n position = 0\n relbase = 0\n while position >= 0:\n position, relbase = intcode.operate(position, relbase,ops,inputs,outputs,True)\n \n outputs.append('fin')\n\ndef get_heading(current,direction):\n if direction == 0:\n if current == 'N':\n return 'W'\n elif current == 'E':\n return 'N'\n elif current == 'S':\n return 'E'\n elif current == 'W':\n return 'S'\n elif direction == 1:\n if current == 'N':\n return 'E'\n elif current == 'E':\n return 'S'\n elif current == 'S':\n return 'W'\n elif current == 'W':\n return 'N'\n\ndef get_loc(x,y,heading):\n if heading == 'N':\n return x, y-1\n elif heading == 'E':\n return x+1, y\n elif heading == 'S':\n return x, y+1\n elif heading == 'W':\n return x-1,y\n\ndef move_robot(inputs,outputs,grid,painted):\n # reads from outputs, writes to inputs\n x = int(len(grid)/2)\n y = int(len(grid)/2)\n heading = 'N'\n count = 0\n while True:\n count += 1\n while len(outputs) < 1:\n pass\n if outputs[0] == 'fin':\n break\n while len(outputs) < 2:\n pass\n colour = outputs.pop(0)\n direction = outputs.pop(0)\n\n\n grid[y][x] = colour\n painted[y][x] = True\n heading = get_heading(heading,direction)\n x, y = get_loc(x,y,heading)\n colour_over = grid[y][x]\n inputs.append(colour_over)\n if False:\n #if count %100 == 0:\n for row in grid:\n for entry in row:\n print(entry,end='')\n print()\n print()\n \n\ndef main(in_string):\n ops = list(map(int,in_string.strip().split(',')))\n grid_size = 100\n grid = [[0 for i in range(grid_size)] for j in range(grid_size)]\n painted = [[False for i in range(grid_size)] for j in range(grid_size)]\n\n inputs = [1]\n outputs = []\n thread_computer = threading.Thread(target=run_computer, args=(ops,inputs,outputs,))\n thread_robot = threading.Thread(target=move_robot, args=(inputs,outputs,grid,painted,))\n\n thread_computer.start()\n thread_robot.start()\n\n thread_computer.join()\n thread_robot.join()\n\n for row in grid:\n for entry in row:\n print(entry,end='')\n print()\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print('No input found.')\n else:\n with open(sys.argv[1],'r') as f:\n in_string = f.read().strip()\n main(in_string)\n","sub_path":"11/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"284720122","text":"from datetime import datetime\nfrom snakypy import printer, pick\nfrom snakypy.ansi import FG\nfrom snakypy.file import create as snakypy_file_create\nfrom os import remove as os_remove\nfrom zshpower.config import package\nfrom zshpower.config.base import Base\nfrom subprocess import check_output\nfrom contextlib import suppress as contextlib_suppress\nfrom zshpower.utils.check import checking_init\nfrom shutil import which as shutil_which\nfrom shutil import copyfile as shutil_copyfile\nfrom shutil import rmtree as shutil_rmtree\nfrom zshpower.utils.process import reload_zsh\nfrom zshpower.utils.catch import read_zshrc_omz\nfrom zshpower.utils.shift import change_theme_in_zshrc, rm_source_zshrc\n\n\ndef rm_init_file_package(init_file):\n with contextlib_suppress(Exception):\n os_remove(init_file)\n if shutil_which(\"pip\") is not None:\n check_output(\n f'pip uninstall {package.info[\"name\"]} -y',\n shell=True,\n universal_newlines=True,\n )\n\n\nclass UninstallCommand(Base):\n def __init__(self, home):\n Base.__init__(self, home)\n\n def main(self):\n checking_init(self.HOME)\n\n if not read_zshrc_omz(self.zsh_rc):\n title = f\"Do you want to uninstall {package.info['name']}?\"\n options = [\"Yes\", \"No\"]\n reply = pick(title, options, colorful=True, index=True)\n if reply is None or reply[0] == 1:\n printer(\"Whew! Thanks! :)\", foreground=FG.GREEN)\n exit(0)\n rm_init_file_package(self.init_file)\n rm_source_zshrc(self.zsh_rc)\n else:\n title = f\"What did you want to uninstall?\"\n options = [\n f\"{package.info['name']}\",\n f\"{package.info['name']} and Oh My ZSH\",\n \"Cancel\",\n ]\n reply = pick(title, options, colorful=True, index=True)\n\n if reply is None or reply[0] == 2:\n printer(\"Whew! Thanks! :)\", foreground=FG.GREEN)\n exit(0)\n\n with contextlib_suppress(Exception):\n os_remove(self.theme_file)\n\n rm_init_file_package(self.init_file)\n\n change_theme_in_zshrc(self.zsh_rc, \"robbyrussell\")\n\n if reply[0] == 1:\n shutil_rmtree(self.omz_root, ignore_errors=True)\n with contextlib_suppress(Exception):\n shutil_copyfile(\n self.zsh_rc, f\"{self.zsh_rc}-D{datetime.today().isoformat()}\"\n )\n with contextlib_suppress(Exception):\n os_remove(self.zsh_rc)\n\n snakypy_file_create(\"\", f\"{self.HOME}/.zshrc\", force=True)\n\n reload_zsh()\n printer(\"Uninstall process finished.\", foreground=FG.FINISH)\n","sub_path":"zshpower/commands/uninstall.py","file_name":"uninstall.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613357308","text":"import pytac.epics\nimport pytac.device\nimport pytest\nimport pytac\nfrom constants import DUMMY_VALUE_1, DUMMY_VALUE_2\n\n\ndef test_create_element():\n e = pytac.element.Element('bpm1', 6.0, 'bpm', 0.0)\n e.add_to_family('BPM')\n assert 'BPM' in e.families\n assert e.length == 6.0\n\n\ndef test_add_element_to_family():\n e = pytac.element.Element('dummy', 6.0, 'Quad', 0.0)\n e.add_to_family('fam')\n assert 'fam' in e.families\n\n\ndef test_device_methods_raise_DataSourceException_if_no_device_data_sorce(simple_element):\n basic_element = simple_element\n del basic_element._data_source_manager._data_sources[pytac.LIVE]\n d = pytac.device.BasicDevice(0)\n uc = pytac.units.NullUnitConv()\n with pytest.raises(pytac.exceptions.DataSourceException):\n basic_element.add_device('x', d, uc)\n with pytest.raises(pytac.exceptions.DataSourceException):\n basic_element.get_device('x')\n\n\ndef test_get_device_raises_KeyError_if_device_not_present(simple_element):\n with pytest.raises(pytac.exceptions.FieldException):\n simple_element.get_device('not-a-device')\n\n\ndef test_get_unitconv_returns_unitconv_object(simple_element, unit_uc,\n double_uc):\n assert simple_element.get_unitconv('x') == unit_uc\n assert simple_element.get_unitconv('y') == double_uc\n\n\ndef test_get_unitconv_raises_FieldException_if_device_not_present(simple_element):\n with pytest.raises(pytac.exceptions.FieldException):\n simple_element.get_unitconv('not-a-device')\n\n\ndef test_get_value_uses_uc_if_necessary_for_cs_call(simple_element, double_uc):\n simple_element._data_source_manager._uc['x'] = double_uc\n assert simple_element.get_value('x', handle=pytac.SP, units=pytac.PHYS,\n data_source=pytac.LIVE) == (DUMMY_VALUE_1 * 2)\n\n\ndef test_get_value_uses_uc_if_necessary_for_sim_call(simple_element, double_uc):\n simple_element._data_source_manager._uc['x'] = double_uc\n assert simple_element.get_value('x', handle=pytac.SP, data_source=pytac.SIM,\n units=pytac.ENG) == (DUMMY_VALUE_2 / 2)\n simple_element._data_source_manager._data_sources[pytac.SIM].get_value.assert_called_with('x', pytac.SP)\n\n\ndef test_set_value_eng(simple_element):\n simple_element.set_value('x', DUMMY_VALUE_2, handle=pytac.SP)\n # No conversion needed\n simple_element.get_device('x').set_value.assert_called_with(DUMMY_VALUE_2)\n\n\ndef test_set_value_phys(simple_element, double_uc):\n simple_element._data_source_manager._uc['x'] = double_uc\n simple_element.set_value('x', DUMMY_VALUE_2, handle=pytac.SP,\n units=pytac.PHYS)\n # Conversion fron physics to engineering units\n simple_element.get_device('x').set_value.assert_called_with((DUMMY_VALUE_2 / 2))\n\n\ndef test_set_exceptions(simple_element, unit_uc):\n with pytest.raises(pytac.exceptions.FieldException):\n simple_element.set_value('unknown_field', 40.0, 'setpoint')\n with pytest.raises(pytac.exceptions.HandleException):\n simple_element.set_value('y', 40.0, 'unknown_handle')\n with pytest.raises(pytac.exceptions.DataSourceException):\n simple_element.set_value('y', 40.0, 'setpoint',\n data_source='unknown_data_source')\n simple_element._data_source_manager._uc['uc_but_not_data_source_field'] = unit_uc\n with pytest.raises(pytac.exceptions.FieldException):\n simple_element.set_value('uc_but_not_data_source_field', 40.0,\n 'setpoint')\n\n\ndef test_get_exceptions(simple_element):\n with pytest.raises(pytac.exceptions.FieldException):\n simple_element.get_value('unknown_field', 'setpoint')\n with pytest.raises(pytac.exceptions.DataSourceException):\n simple_element.get_value('y', 'setpoint',\n data_source='unknown_data_source')\n\n\ndef test_identity_conversion(simple_element):\n value_physics = simple_element.get_value('x', 'setpoint', pytac.PHYS)\n value_machine = simple_element.get_value('x', 'setpoint', pytac.ENG)\n assert value_machine == DUMMY_VALUE_1\n assert value_physics == DUMMY_VALUE_1\n\n\ndef test_get_fields(simple_element):\n assert set(simple_element.get_fields()[pytac.LIVE]) == set(['y', 'x'])\n\n\ndef test_element_representation(simple_element):\n s = str(simple_element)\n assert simple_element.name in s\n assert str(simple_element.length) in s\n for f in simple_element.families:\n assert f in s\n","sub_path":"test/test_element.py","file_name":"test_element.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"299558927","text":"import random\nimport time\nimport xlsxwriter\nimport matplotlib.pyplot as plt\n\ndef GenerarRandom():\n numero = round(random.random(),4)\n return numero\n\ndef OrdenarLista(diccionario):\n return [(k, diccionario[k]) for k in sorted(diccionario)]\n\ndef ImprimirGanancias(listaGanancias):\n timestamp = int(round(time.time() * 1000))\n workbook = xlsxwriter.Workbook(\"output/ListaGanancias_PoliticaDos.xlsx\")\n worksheet_corridas = workbook.add_worksheet(\"Ganancias Totales\")\n cell_format_header = workbook.add_format({'center_across':True, 'bold':True, 'border':True})\n cell_format_header.set_border(style=2)\n cell_format = workbook.add_format({'center_across':True, 'border':True})\n cell_format_max = workbook.add_format({'center_across':True, 'border':True})\n cell_format_max.set_bg_color('#6fdc6f')\n\n worksheet_corridas.set_column('B:C', 16)\n worksheet_corridas.write(1, 1, \"COMPRA INICIAL\", cell_format_header)\n worksheet_corridas.write(1, 2, \"GANANCIA\", cell_format_header)\n\n row = 2\n for resultado in listaGanancias:\n worksheet_corridas.write(row, 1, resultado[0], cell_format)\n worksheet_corridas.write(row, 2, resultado[1], cell_format)\n row += 1\n\n workbook.close()\n ImprimirBoxPlot(listaGanancias)\n\ndef ImprimirBoxPlot(listaGanancias):\n data = []\n for resultado in listaGanancias:\n data.append(resultado[1])\n fig, ax = plt.subplots()\n titulo = \"Politica 2 - \"+str(len(listaGanancias))+\" Simulaciones\"\n ax.set_title(titulo)\n ax.boxplot([data])\n fig.savefig(\"output/BoxPlot-Politica2.png\") # save the figure to file\n plt.close(fig)\n print('Simulación de la politica 2 finalizada con éxito, los resultados se encuentran en la carpeta output.') ","sub_path":"politicaDos/Operaciones.py","file_name":"Operaciones.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"482478763","text":"# coding: utf-8\nfrom datetime import datetime\nimport logging\n\nfrom django.db import models, connection, transaction\nfrom django.utils import timezone\nfrom app.models import Subject\n\nlogger = logging.getLogger(__name__)\n\nclass AD(models.Model):\n title = models.CharField(verbose_name=u'广告标题', max_length=50)\n cover = models.CharField(verbose_name=u'广告图片', max_length=1024)\n desc = models.CharField(verbose_name=u'广告介绍', max_length=50)\n from_date = models.DateTimeField(verbose_name=u'上线时间')\n to_date = models.DateTimeField(verbose_name=u'下线时间')\n visible = models.BooleanField(verbose_name=u'广告状态')\n approved = models.BooleanField(verbose_name=u'审核状态')\n position = models.IntegerField(default=0)\n subject = models.ForeignKey(Subject, null=True)\n\n def __unicode__(self):\n return self.title\n\n def available(self):\n return self.visible\n\n def in_period(self):\n return self.from_date <= timezone.now() <= self.to_date\n\n class Meta:\n permissions = (\n ('sort_ad', 'Can sort the advertisements'),\n )\n\n\n_MAX_ADS = 1024\n\n@transaction.commit_manually\ndef sort_ad(pks):\n try:\n AD.objects.exclude(pk__in=pks).update(position=_MAX_ADS, visible=False)\n AD.objects.filter(pk__in=pks).update(visible=True)\n for i in range(0, len(pks)):\n ad = AD.objects.get(pk=pks[i])\n ad.position = i + 1\n ad.save()\n except Exception as e:\n logger.exception(e)\n transaction.roll_back()\n raise e\n else:\n transaction.commit()\n\n\ndef _set_ad_visible(pk):\n c = connection.cursor()\n try:\n c.execute(\"update ad_ad set position = position + 1 where visible = 1\" )\n finally:\n c.close()\n AD.objects.filter(pk=pk).update(position=0)\n\n\ndef _set_ad_invisible(pk):\n ad = AD.objects.get(pk=pk)\n c = connection.cursor()\n try:\n sql = \"update ad_ad set position = position - 1 \" + \\\n \"where position > %d and visible = 1\" % ad.position\n c.execute(sql)\n finally:\n c.close()\n ad.position = _MAX_ADS\n ad.visible = False\n ad.save()\n\n\n@transaction.commit_manually\ndef add_ad(ad):\n try: \n ad.save()\n if ad.visible:\n _set_ad_visible(ad.pk)\n else:\n ad.position = _MAX_ADS\n ad.save()\n except Exception as e:\n logger.exception(e)\n transaction.roll_back()\n raise e\n else:\n transaction.commit()\n\n\n@transaction.commit_manually\ndef edit_ad(ad):\n visible = ad.visible\n visible_changed = AD.objects.get(pk=ad.pk).visible != ad.visible\n try:\n ad.save()\n if visible_changed:\n if visible:\n _set_ad_visible(ad.pk)\n else:\n _set_ad_invisible(ad.pk)\n except Exception as e:\n logger.exception(e)\n transaction.roll_back()\n raise e\n else:\n transaction.commit()\n\n\n@transaction.commit_manually\ndef delete_ad(pk): \n try:\n ad = AD.objects.get(pk=pk)\n if not ad.visible:\n ad.delete()\n else:\n _set_ad_invisible(pk)\n delete_ad(pk)\n except Exception as e:\n logger.exception(e)\n transaction.roll_back()\n raise e\n else:\n transaction.commit()\n \n","sub_path":"ad/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"435607970","text":"import mayavi.mlab as mlab\nimport numpy as np\nimport torch\nimport cv2\nimport matplotlib.pyplot as plt\n\nbox_colormap = [\n [1, 1, 1],\n [0, 1, 0],\n [0, 1, 1],\n [1, 1, 0],\n]\nlabel_dict = {0:\"background\", 1:\"Car\", 2:\"Ped\", 3:\"Cycler\", 4:\"Truck\"}\ncolor_dict = {\"0\":[255, 255, 255], \"1\":[255, 255, 0], \"2\":[51, 153, 255], \"3\":[255, 0, 255], \"4\":[0, 0, 0]}\n\ndef check_numpy_to_torch(x):\n if isinstance(x, np.ndarray):\n return torch.from_numpy(x).float(), True\n return x, False\n\n\ndef rotate_points_along_z(points, angle):\n \"\"\"\n Args:\n points: (B, N, 3 + C)\n angle: (B), angle along z-axis, angle increases x ==> y\n Returns:\n\n \"\"\"\n points, is_numpy = check_numpy_to_torch(points)\n angle, _ = check_numpy_to_torch(angle)\n\n cosa = torch.cos(angle)\n sina = torch.sin(angle)\n zeros = angle.new_zeros(points.shape[0])\n ones = angle.new_ones(points.shape[0])\n rot_matrix = torch.stack((\n cosa, sina, zeros,\n -sina, cosa, zeros,\n zeros, zeros, ones\n ), dim=1).view(-1, 3, 3).float()\n points_rot = torch.matmul(points[:, :, 0:3], rot_matrix)\n points_rot = torch.cat((points_rot, points[:, :, 3:]), dim=-1)\n return points_rot.numpy() if is_numpy else points_rot\n\n\ndef boxes_to_corners_3d(boxes3d):\n \"\"\"\n 7 -------- 4\n /| /|\n 6 -------- 5 .\n | | | |\n . 3 -------- 0\n |/ |/\n 2 -------- 1\n Args:\n boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center\n\n Returns:\n \"\"\"\n boxes3d, is_numpy = check_numpy_to_torch(boxes3d)\n\n template = boxes3d.new_tensor((\n [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1],\n [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1],\n )) / 2\n\n corners3d = boxes3d[:, None, 3:6].repeat(1, 8, 1) * template[None, :, :]\n corners3d = rotate_points_along_z(corners3d.view(-1, 8, 3), boxes3d[:, 6]).view(-1, 8, 3)\n corners3d += boxes3d[:, None, 0:3]\n\n return corners3d.numpy() if is_numpy else corners3d\n\n\ndef visualize_pts(pts, fig=None, bgcolor=(0, 0, 0), fgcolor=(1.0, 1.0, 1.0),\n show_intensity=False, size=(600, 600), draw_origin=True):\n if pts is None:\n if fig is None:\n fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=fgcolor, engine=None, size=size)\n return fig\n if not isinstance(pts, np.ndarray):\n pts = pts.cpu().numpy()\n if fig is None:\n fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=fgcolor, engine=None, size=size)\n\n if show_intensity:\n G = mlab.points3d(pts[:, 0], pts[:, 1], pts[:, 2], pts[:, 3], mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n else:\n G = mlab.points3d(pts[:, 0], pts[:, 1], pts[:, 2], mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n if draw_origin:\n mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='cube', scale_factor=0.2)\n mlab.plot3d([0, 3], [0, 0], [0, 0], color=(0, 0, 1), tube_radius=0.1)\n mlab.plot3d([0, 0], [0, 3], [0, 0], color=(0, 1, 0), tube_radius=0.1)\n mlab.plot3d([0, 0], [0, 0], [0, 3], color=(1, 0, 0), tube_radius=0.1)\n\n return fig\n\n\ndef draw_sphere_pts(pts, color=(0, 1, 0), fig=None, bgcolor=(0, 0, 0), scale_factor=0.2):\n if not isinstance(pts, np.ndarray):\n pts = pts.cpu().numpy()\n\n if fig is None:\n fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(600, 600))\n\n if isinstance(color, np.ndarray) and color.shape[0] == 1:\n color = color[0]\n color = (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)\n\n if isinstance(color, np.ndarray):\n pts_color = np.zeros((pts.__len__(), 4), dtype=np.uint8)\n pts_color[:, 0:3] = color\n pts_color[:, 3] = 255\n G = mlab.points3d(pts[:, 0], pts[:, 1], pts[:, 2], np.arange(0, pts_color.__len__()), mode='sphere',\n scale_factor=scale_factor, figure=fig)\n G.glyph.color_mode = 'color_by_scalar'\n G.glyph.scale_mode = 'scale_by_vector'\n G.module_manager.scalar_lut_manager.lut.table = pts_color\n else:\n mlab.points3d(pts[:, 0], pts[:, 1], pts[:, 2], mode='sphere', color=color,\n colormap='gnuplot', scale_factor=scale_factor, figure=fig)\n\n mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='cube', scale_factor=0.2)\n mlab.plot3d([0, 3], [0, 0], [0, 0], color=(0, 0, 1), line_width=3, tube_radius=None, figure=fig)\n mlab.plot3d([0, 0], [0, 3], [0, 0], color=(0, 1, 0), line_width=3, tube_radius=None, figure=fig)\n mlab.plot3d([0, 0], [0, 0], [0, 3], color=(1, 0, 0), line_width=3, tube_radius=None, figure=fig)\n\n return fig\n\n\ndef draw_grid(x1, y1, x2, y2, fig, tube_radius=None, color=(0.5, 0.5, 0.5)):\n mlab.plot3d([x1, x1], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)\n mlab.plot3d([x2, x2], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)\n mlab.plot3d([x1, x2], [y1, y1], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)\n mlab.plot3d([x1, x2], [y2, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)\n return fig\n\n\ndef draw_multi_grid_range(fig, grid_size=20, bv_range=(-60, -60, 60, 60)):\n for x in range(bv_range[0], bv_range[2], grid_size):\n for y in range(bv_range[1], bv_range[3], grid_size):\n fig = draw_grid(x, y, x + grid_size, y + grid_size, fig)\n\n return fig\n\n\ndef draw_scenes(points=None, gt_boxes=None, ref_boxes=None, ref_scores=None, ref_labels=None):\n if points is not None:\n if not isinstance(points, np.ndarray):\n points = points.cpu().numpy()\n if ref_boxes is not None and not isinstance(ref_boxes, np.ndarray):\n ref_boxes = ref_boxes.cpu().numpy()\n if gt_boxes is not None and not isinstance(gt_boxes, np.ndarray):\n gt_boxes = gt_boxes.cpu().numpy()\n if ref_scores is not None and not isinstance(ref_scores, np.ndarray):\n ref_scores = ref_scores.cpu().numpy()\n if ref_labels is not None and not isinstance(ref_labels, np.ndarray):\n ref_labels = ref_labels.cpu().numpy()\n\n fig = visualize_pts(points)\n fig = draw_multi_grid_range(fig, bv_range=(0, -40, 80, 40))\n if gt_boxes is not None:\n corners3d = boxes_to_corners_3d(gt_boxes)\n fig = draw_corners3d(corners3d, fig=fig, color=(0, 0, 1), max_num=100)\n\n if ref_boxes is not None and len(ref_boxes) > 0:\n ref_corners3d = boxes_to_corners_3d(ref_boxes)\n if ref_labels is None:\n fig = draw_corners3d(ref_corners3d, fig=fig, color=(0, 1, 0), cls=ref_scores, max_num=100)\n else:\n for k in range(ref_labels.min(), ref_labels.max() + 1):\n cur_color = tuple(box_colormap[k % len(box_colormap)])\n mask = (ref_labels == k)\n fig = draw_corners3d(ref_corners3d[mask], fig=fig, color=cur_color, cls=ref_scores[mask], max_num=5)\n mlab.view(azimuth=-179, elevation=54.0, distance=104.0, roll=90.0)\n return fig\n\n\ndef draw_corners3d(corners3d, fig, color=(1, 1, 1), line_width=2, cls=None, tag='', max_num=500, tube_radius=None):\n \"\"\"\n :param corners3d: (N, 8, 3)\n :param fig:\n :param color:\n :param line_width:\n :param cls:\n :param tag:\n :param max_num:\n :return:\n \"\"\"\n import mayavi.mlab as mlab\n num = min(max_num, len(corners3d))\n for n in range(num):\n b = corners3d[n] # (8, 3)\n\n if cls is not None:\n if isinstance(cls, np.ndarray):\n mlab.text3d(b[6, 0], b[6, 1], b[6, 2], '%.2f' % cls[n], scale=(0.3, 0.3, 0.3), color=color, figure=fig)\n else:\n mlab.text3d(b[6, 0], b[6, 1], b[6, 2], '%s' % cls[n], scale=(0.3, 0.3, 0.3), color=color, figure=fig)\n\n for k in range(0, 4):\n i, j = k, (k + 1) % 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius,\n line_width=line_width, figure=fig)\n\n i, j = k + 4, (k + 1) % 4 + 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius,\n line_width=line_width, figure=fig)\n\n i, j = k, k + 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius,\n line_width=line_width, figure=fig)\n\n i, j = 0, 5\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius,\n line_width=line_width, figure=fig)\n i, j = 1, 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius,\n line_width=line_width, figure=fig)\n\n return fig\n\n# def draw_on_image(image, calib, points=None, gt_boxes=None, ref_boxes=None, ref_scores=None, ref_labels=None):\n# if points is not None:\n# if not isinstance(points, np.ndarray):\n# points = points.cpu().numpy()\n# if ref_boxes is not None and not isinstance(ref_boxes, np.ndarray):\n# ref_boxes = ref_boxes.cpu().numpy()\n# if gt_boxes is not None and not isinstance(gt_boxes, np.ndarray):\n# gt_boxes = gt_boxes.cpu().numpy()\n# if ref_scores is not None and not isinstance(ref_scores, np.ndarray):\n# ref_scores = ref_scores.cpu().numpy()\n# if ref_labels is not None and not isinstance(ref_labels, np.ndarray):\n# ref_labels = ref_labels.cpu().numpy()\n\n# if gt_boxes is not None:\n# corners3d = boxes_to_corners_3d(gt_boxes)\n# for i in range(len(corners3d)):\n# image = draw_one_frame_on_img(image, corners3d[i], color_dict, label_dict, 0, calib, pretty=True)\n\n# if ref_boxes is not None and len(ref_boxes) > 0:\n# ref_corners3d = boxes_to_corners_3d(ref_boxes)\n# for i in range(len(ref_corners3d)):\n# if ref_labels is None:\n# label = 0\n# else:\n# label = ref_labels[i]\n# image = draw_one_frame_on_img(image, ref_corners3d[i], color_dict, label_dict, label, calib, pretty=True)\n# return image\n\n# def draw_one_frame_on_img(img_draw, corners3d, color_dict, label_dict, label, calib, pretty = True):\n# box_list = [(0, 1), (0, 2), (0, 4), (1, 5), (1, 3), (2, 6), (2, 3), (3, 7), (4, 6), (4, 5), (5, 7), (6, 7)]\n# rect_min_w_h = [50, 20]\n# if not str(label) in color_dict.keys():\n# obj_color = (255, 255, 255)\n# else:\n# obj_color = color_dict[str(label)]\n# plane_cor, plane_obj_cen = project_3D_to_image(corners3d, calib)\n# print(plane_cor)\n# if pretty:\n# img_draw = draw_color_on_contour_roi(img_draw, plane_cor, obj_color)\n# for point_pair in box_list:\n# cv2.line(img_draw, (int(plane_cor[0][point_pair[0]]), int(plane_cor[1][point_pair[0]])),\n# (int(plane_cor[0][point_pair[1]]), int(plane_cor[1][point_pair[1]])), obj_color, 1)\n# for index in range(8):\n# cv2.circle(img_draw, (int(plane_cor[0][index]), int(plane_cor[1][index])), 2, (0, 255, 255), -1)\n# cv2.circle(img_draw, (int(plane_obj_cen[0]), int(plane_obj_cen[1])), 3, (255, 0, 255), -1)\n# if not label_dict == None:\n# left_corner_cor = []\n# image_label = img_draw.copy()\n# for index in range(8):\n# left_corner_cor.append([plane_cor[0][index], plane_cor[1][index]])\n# left_corner_cor.sort(key=lambda x: x[0])\n# left_corner_cor = left_corner_cor[0:2]\n# left_corner_cor.sort(key=lambda x: x[1])\n# left_corner_cor = left_corner_cor[0]\n# rect_left_top = (int(left_corner_cor[0]), int(left_corner_cor[1] - rect_min_w_h[1]))\n# rect_right_down = (int(left_corner_cor[0] + rect_min_w_h[0]), int(left_corner_cor[1]))\n# cv2.rectangle(image_label, rect_left_top, rect_right_down, (102, 178, 255), -1)\n# if label in label_dict:\n# text = label_dict[label]\n# else:\n# text = \"None\"\n# cv2.putText(image_label, text, (int(left_corner_cor[0]), int(left_corner_cor[1]) - 5), cv2.FONT_HERSHEY_DUPLEX,\n# 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n# img_draw = cv2.addWeighted(img_draw, 0.4, image_label, 0.6, 0)\n# return img_draw\n\n# def draw_one_bv_frame(corners3d, color_dict):\n# if plt.gcf().number > 1:\n# plt.close('all')\n# if plt.gcf().number < 1:\n# plt.figure()\n# plt.ion()\n# fig = plt.gcf()\n# ax = plt.gca()\n# fig.set_size_inches(5, 12.5)\n# # point_list = [(1, 3), (3, 7), (7, 5), (5, 1)]\n# point_list = [(3, 7), (7, 6), (6, 2), (2, 3)]\n# plt.cla()\n#\n# for cat in dets:\n# for i in range(len(dets[cat])):\n# if dets[cat][i, -1] > center_thresh:\n# dim_ = dets[cat][i, 5:8]\n# loc_ = dets[cat][i, 8:11]\n# rot_y = dets[cat][i, 11]\n# loc = np.array([loc_[0], loc_[1] - dim_[0] / 2, loc_[2]])\n# dim = np.array([dim_[2], dim_[0], dim_[1]])\n# if not str(cat) in obj_color_dict.keys():\n# obj_color = (1, 1, 1)\n# else:\n# obj_color = (obj_color_dict[str(cat)][2] / 255, obj_color_dict[str(cat)][1] / 255,\n# obj_color_dict[str(cat)][0] / 255)\n# corner_point = self.generate_obj_cam_cor(np.array(loc), np.array(dim), np.array([rot_y, 0, 0]))\n# for point_ in point_list:\n# ax.plot((corner_point[0][point_[0]], corner_point[0][point_[1]]),\n# (corner_point[2][point_[0]], corner_point[2][point_[1]]), color=obj_color)\n# ax.axis(xmin=-25, xmax=25)\n# ax.axis(ymin=0, ymax=100)\n# ax.grid()\n# plt.title(\"bird view\")\n# plt.xlabel(\"horizontal distance/m\")\n# plt.ylabel(\"vertical distance/m\")\n# fig.canvas.draw()\n# img_from_mat = cv2.cvtColor(np.asarray(fig.canvas.buffer_rgba()), cv2.COLOR_RGBA2BGR)\n# img_from_mat = cv2.resize(img_from_mat, (400, 1000))\n#\n# return img_from_mat\n\n\n# def project_3D_to_image(corner_point, calib):\n# calib_ = np.array(calib)[:, 0:3]\n# center_3d = corner_point[0]\n# for i in range(1, 4):\n# center_3d += corner_point[i]\n# center_3d = center_3d/4\n# center_3d = center_3d[np.newaxis,...]\n# corner_point = np.append(center_3d, corner_point, axis=0)\n# corner_point = corner_point.T\n# tmp = corner_point[0,...]\n# corner_point[0, ...] = corner_point[2,...]\n# corner_point[2, ...] = tmp\n\n# tmp = corner_point[0,...]\n# corner_point[0, ...] = corner_point[1,...]\n# corner_point[1, ...] = tmp\n\n# for i in range(9):\n# if corner_point[2, i] < 0:\n# corner_point[0, i] = -corner_point[0, i]\n# corner_point[1, i] = -corner_point[1, i]\n# corner_point = np.matmul(calib_, corner_point)\n# plane_cor = corner_point[0:2, :]\n# for i in range(9):\n# plane_cor[0][i] = corner_point[0][i] / corner_point[2][i]\n# plane_cor[1][i] = corner_point[1][i] / corner_point[2][i]\n# plane_cen = plane_cor[:, 0]\n# plane_cor = plane_cor[:, 1:]\n# #\n# return plane_cor, plane_cen\n\ndef draw_color_on_contour_roi(image, plane_cor, color):\n plane_list = [[2, 3, 7, 6], [0, 1, 3, 2], [4, 5, 7, 6], [0, 1, 5, 4], [0, 2, 6, 4], [1, 3, 7 ,5]]\n contour = []\n image_draw_contour = image.copy()\n for plane in plane_list:\n contour_ = []\n for index in plane:\n contour_.append([plane_cor[0][index], plane_cor[1][index]])\n contour.append(np.array(contour_).reshape((-1,1,2)).astype(np.int32))\n for contour_ in contour:\n cv2.drawContours(image_draw_contour, [contour_], -1, color, thickness = -1)\n image = cv2.addWeighted(image, 0.75, image_draw_contour, 0.25, 0)\n return image\n\n\n\ndef draw_one_frame_on_img(img_draw, boxes, labels, calib, point_color, center_color, obj_color_dict, pretty = False, label_dict = None):\n img_draw = np.ascontiguousarray(img_draw, dtype=np.uint8)\n box_list = [(0, 1),(0, 2),(0, 4), (1, 5), (1, 3), (2, 6), (2, 3), (3, 7), (4, 6), (4, 5), (5, 7), (6, 7)]\n rect_min_w_h = [50, 20]\n objs = list(zip(torch.Tensor.cpu(boxes), labels))\n for obj in objs:\n if not obj[1] in obj_color_dict.keys():\n obj_color = (255, 255, 255)\n else:\n obj_color = obj_color_dict[obj[1]]\n plane_cor, plane_obj_cen = project_3D_to_image(np.array([-obj[0][1], -obj[0][2],obj[0][0]]), np.array([obj[0][4], obj[0][5], obj[0][3]]), np.array([-obj[0][6], 0, 0]), calib)\n if pretty:\n img_draw = draw_color_on_contour_roi(img_draw, plane_cor, obj_color)\n for point_pair in box_list:\n cv2.line(img_draw, (int(plane_cor[0][point_pair[0]]), int(plane_cor[1][point_pair[0]])), (int(plane_cor[0][point_pair[1]]), int(plane_cor[1][point_pair[1]])), obj_color, 1)\n for index in range(8):\n cv2.circle(img_draw, (int(plane_cor[0][index]), int(plane_cor[1][index])), 2, point_color, -1)\n cv2.circle(img_draw, (int(plane_obj_cen[0]), int(plane_obj_cen[1])), 3, center_color, -1)\n if not label_dict == None:\n left_corner_cor = []\n image_label = img_draw.copy()\n for index in range(8):\n left_corner_cor.append([plane_cor[0][index], plane_cor[1][index]])\n left_corner_cor.sort(key = lambda x: x[0])\n left_corner_cor = left_corner_cor[0:2]\n left_corner_cor.sort(key = lambda x:x[1])\n left_corner_cor = left_corner_cor[0]\n rect_left_top = (int(left_corner_cor[0]), int(left_corner_cor[1] - rect_min_w_h[1]))\n rect_right_down = (int(left_corner_cor[0] + rect_min_w_h[0]), int(left_corner_cor[1]))\n cv2.rectangle(image_label, rect_left_top, rect_right_down, (102, 178, 255), -1)\n if obj[1] in label_dict:\n text = label_dict[obj[1]]\n else:\n text = \"None\"\n cv2.putText(image_label, text, (int(left_corner_cor[0]), int(left_corner_cor[1]) - 5), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n img_draw = cv2.addWeighted(img_draw, 0.4, image_label, 0.6, 0)\n\n return img_draw\n\n# def draw_color_on_contour_roi(self, image, plane_cor, color):\n# plane_list = [[2, 3, 7, 6], [0, 1, 3, 2], [4, 5, 7, 6], [0, 1, 5, 4], [0, 2, 6, 4], [1, 3, 7 ,5]]\n# contour = []\n# image_draw_contour = image.copy()\n# for plane in plane_list:\n# contour_ = []\n# for index in plane:\n# contour_.append([plane_cor[0][index], plane_cor[1][index]])\n# contour.append(np.array(contour_).reshape((-1,1,2)).astype(np.int32))\n# for contour_ in contour:\n# cv2.drawContours(image_draw_contour, [contour_], -1, color, thickness = -1)\n# image = cv2.addWeighted(image, 0.75, image_draw_contour, 0.25, 0)\n# return image\n \n\n# def generate_obj_cam_cor(self, position, size, ZYX):\n\n# pitch = ZYX[0]\n# roll = ZYX[1]\n# yaw = ZYX[2]\n\n# R_roll = np.array([[1 , 0 , 0 ],\n# [0 , np.cos(roll), -np.sin(roll)],\n# [0 , np.sin(roll), np.cos(roll)]])\n# R_pitch = np.array([[np.cos(pitch) , 0 , np.sin(pitch)],\n# [0 , 1 , 0 ],\n# [-np.sin(pitch), 0 , np.cos(pitch)]])\n# R_yaw = np.array([[np.cos(yaw) , -np.sin(yaw), 0 ],\n# [np.sin(yaw) , np.cos(yaw) , 0 ],\n# [0 , 0 , 1 ]])\n \n# R = np.matmul(R_pitch, R_roll)\n# R = np.matmul(R_yaw, R)\n# size = 0.5 * size\n# arithm_list = []\n# for i in ['+','-']:\n# for j in ['+', '-']:\n# for k in ['+', '-']:\n# arithm_list.append(i+j+k)\n# corner_point = np.array([0, 0, 0])\n# for arithm in arithm_list:\n# point = np.array([eval(str(0) + arithm[0] + str(size[0])),eval(str(0) + arithm[1] + str(size[1])),eval(str(0) + arithm[2] + str(size[2]))])\n# corner_point = np.vstack((corner_point, point))\n# corner_point = corner_point.T\n# corner_point = np.matmul(R, corner_point)\n# for i in range(9):\n# corner_point[:,i] = corner_point[:,i] + position\n# return corner_point\n\n\ndef generate_obj_cam_cor(position, size, ZYX):\n# \n pitch = ZYX[0]\n roll = ZYX[1]\n yaw = ZYX[2]\n# \n R_roll = np.array([[1 , 0 , 0 ],\n [0 , np.cos(roll), -np.sin(roll)],\n [0 , np.sin(roll), np.cos(roll)]])\n R_pitch = np.array([[np.cos(pitch) , 0 , np.sin(pitch)],\n [0 , 1 , 0 ],\n [-np.sin(pitch), 0 , np.cos(pitch)]])\n R_yaw = np.array([[np.cos(yaw) , -np.sin(yaw), 0 ],\n [np.sin(yaw) , np.cos(yaw) , 0 ],\n [0 , 0 , 1 ]])\n # \n R = np.matmul(R_pitch, R_roll)\n R = np.matmul(R_yaw, R)\n size = 0.5 * size\n arithm_list = []\n for i in ['+','-']:\n for j in ['+', '-']:\n for k in ['+', '-']:\n arithm_list.append(i+j+k)\n corner_point = np.array([0, 0, 0])\n for arithm in arithm_list:\n point = np.array([eval(str(0) + arithm[0] + str(size[0])),eval(str(0) + arithm[1] + str(size[1])),eval(str(0) + arithm[2] + str(size[2]))])\n corner_point = np.vstack((corner_point, point))\n corner_point = corner_point.T\n corner_point = np.matmul(R, corner_point)\n for i in range(9):\n corner_point[:,i] = corner_point[:,i] + position\n return corner_point\n\n\ndef project_3D_to_image(position, size, ZYX, calib):\n calib_ = np.array(calib)\n calib_ = calib_[:, 0:3]\n corner_point = generate_obj_cam_cor(position, size, ZYX)\n for i in range(9):\n if corner_point[2, i] < 0:\n corner_point[0, i] = -corner_point[0, i]\n corner_point[1, i] = -corner_point[1, i]\n corner_point = np.matmul(calib_, corner_point)\n plane_cor = corner_point[0:2,:]\n for i in range(9):\n plane_cor[0][i] = corner_point[0][i] / corner_point[2][i]\n plane_cor[1][i] = corner_point[1][i] / corner_point[2][i]\n plane_cen = plane_cor[:,0]\n plane_cor = plane_cor[:,1:]\n# \n return plane_cor, plane_cen\n","sub_path":"tools/visual_utils/visualize_utils.py","file_name":"visualize_utils.py","file_ext":"py","file_size_in_byte":22791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"356149567","text":"#! python3\r\n#\r\n# SNReport2L-B.py -- Read the Service Now Assessment Report\r\n# Two Line Report version with Estimated Completion Date\r\n#\r\n# import OPENPYXL Functions\r\n#\r\nimport openpyxl\r\nfrom openpyxl.styles import NamedStyle, Alignment\r\n#from openpyxl.comments import Comment\r\n#\r\n# Import OS Functions\r\n#\r\nimport os\r\n#\r\n# Import TK GUI FUNCTIONS\r\n#\r\nimport tkinter\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\nfrom tkinter import Label\r\n\r\n#\r\n# Starting TK and hiding the main window\r\n#\r\nroot = tkinter.Tk()\r\nroot.attributes('-fullscreen', True)\r\n#root.withdraw()\r\nLABEL = Label(root, text=\"Sevice Now Report Processing!\")\r\nLABEL.pack()\r\n\r\n#\r\n# Starting the first phase of processing\r\n# Get the input file name to process\r\n#\r\nSNFile = filedialog.askopenfile(parent=root,mode='rb',title='Enter the File Name to process')\r\nprint('Opening Workbook ', SNFile.name)\r\nOutput = 'Opening Workbook'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nOutput = SNFile.name\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\n#\r\n# Open the input file\r\n#\r\nwb = openpyxl.load_workbook(SNFile)\r\n#\r\n# Open the worksheet\r\n#\r\n#print('Opening Worksheet')\r\nsheet = wb.get_sheet_by_name('Page 1')\r\n#\r\n# Save the temporary file\r\n#\r\n#print('Saving SNReportTemp.xlsx.')\r\nOutput = 'Saving SNReportTemp.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb.save('SNReportTemp.xlsx')\r\n#\r\n# Close the temporary file\r\n#\r\nwb.close()\r\n#\r\n# Start Excel with the temporary file\r\n# Instructions for the expected Excel error\r\n#\r\nOutput = 'Starting Excel with SNReportTemp.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nmessagebox.showinfo(\"Starting Excel\", \"Answer YES to the Error, and then close the Error Log Box\")\r\nos.startfile('SNReportTemp.xlsx')\r\n#\r\n# Instructions for the tasks to be done in Excel\r\n# Instruction message box display\r\n#\r\nmessagebox.showinfo(\"In Excel\", 'Remove columns B, D, F, I.\\n\\nCut Column F and Insert at D.\\n\\nInsert One column at G.\\n\\nInsert One column at K.\\n\\nStarting at column M, Insert 9 Columns (M thru U).\\n\\nSave as SNReportTemp.xlsx, Overwriting the file!\\n\\n\\n\\nExit Excel!!!')\r\n#\r\n# Start the second phase of processing\r\n# Open the temporary file\r\n#\r\n#print('Opening File SNReportTemp.xlsx')\r\nOutput = 'Opening File SNReportTemp.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb = openpyxl.load_workbook('SNReportTemp.xlsx')\r\n#\r\n# Open the worksheet\r\n#\r\n#print('Opening Worksheet')\r\nOutput = 'Opening Worksheet'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nsheet = wb.get_sheet_by_name('Page 1')\r\n#\r\n# Adding the names for the title row\r\n#\r\n#print('Adding New Row 1 Names')\r\nOutput = 'Ading new Row 1 Names'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nsheet['a1'] = 'Assigned To RT'\r\nsheet['b1'] = 'Engagement RT'\r\nsheet['c1'] = 'Request RT'\r\nsheet['d1'] = 'Task RT'\r\nsheet['e1'] = 'Created RT'\r\nsheet['f1'] = 'Completion RT'\r\nsheet['g1'] = 'Type RT'\r\nsheet['h1'] = 'Description RT'\r\nsheet['i1'] = 'Status RT'\r\nsheet['j1'] = 'PVID RT'\r\nsheet['k1'] = 'Feature RT'\r\nsheet['l1'] = 'Estimate RT'\r\nsheet['m1'] = 'Name FT'\r\nsheet['n1'] = 'Integration FT'\r\nsheet['o1'] = 'Status FT'\r\nsheet['p1'] = 'VP FT'\r\nsheet['q1'] = 'IT Vertical FT'\r\nsheet['r1'] = 'IT Portfolio FT'\r\nsheet['s1'] = 'MD FT'\r\nsheet['t1'] = 'Sponsor Division FT'\r\nsheet['u1'] = 'Sponsor FT'\r\nsheet['v1'] = 'Requested By Name RT'\r\nsheet['w1'] = 'Requested By Email RT'\r\nsheet['x1'] = 'Requested For Name RT'\r\nsheet['y1'] = 'Requested For Email RT'\r\nsheet['z1'] = 'Approve Date FT'\r\nsheet['aa1'] = 'Approve Start Date FT'\r\nsheet['ab1'] = 'Approve End Date FT'\r\nsheet['ac1'] = 'Planned Start Date FT'\r\nsheet['ad1'] = 'Planned End Date FT'\r\nsheet['ae1'] = 'Project Manager FT'\r\nsheet['af1'] = 'Project Analyst FT'\r\nsheet['ag1'] = 'Project Category FT'\r\n#\r\n# Changing the beginning of the Descriotion to the short version\r\n#\r\n# Change Deliver\r\n#print('Changing to Deliver')\r\nOutput = 'Changing to Deliver'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor i in range(1,sheet.max_row+1):\r\n Deliver = sheet.cell(row=i, column=8).value\r\n if 'Deliver network assessment'in Deliver:\r\n Deliver2 = Deliver.split('-')\r\n Type = 'Deliver'\r\n Deliver2[0] = ''\r\n Deliver3 = (' ').join(Deliver2)\r\n Deliver4 = Deliver3.lstrip()\r\n sheet.cell(row=i, column=7).value = Type\r\n sheet.cell(row=i, column=8).value = Deliver4\r\n# Change Estimate\r\n#print('Changing to Estimate')\r\nOutput = 'Changing to Estimate'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor i in range(1,sheet.max_row+1):\r\n Estimate = sheet.cell(row=i, column=8).value\r\n if 'Build assessment estimate'in Estimate:\r\n Estimate2 = Estimate.split('-')\r\n Type = 'Estimate'\r\n Estimate2[0] = ''\r\n Estimate3 = (' ').join(Estimate2)\r\n Estimate4 = Estimate3.lstrip()\r\n sheet.cell(row=i, column=7).value = Type\r\n sheet.cell(row=i, column=8).value = Estimate4\r\n# Change Planning\r\n#print('Changing to Planning')\r\nOutput = 'Changing to Planning'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor i in range(1,sheet.max_row+1):\r\n Planning = sheet.cell(row=i, column=8).value\r\n if 'Resource & Demand planning for'in Planning:\r\n Planning2 = Planning.split('-')\r\n Type = 'Planning'\r\n Planning2[0] = ''\r\n Planning3 = (' ').join(Planning2)\r\n Planning4 = Planning3.lstrip()\r\n sheet.cell(row=i, column=7).value = Type\r\n sheet.cell(row=i, column=8).value = Planning4\r\n#\r\n# Save the second temporary file\r\n#\r\n#print('Saving SNReportTemp2.xlsx.')\r\nOutput = 'Saving SNReportTemp2.XLSX'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb.save('SNReportTemp2.xlsx')\r\n#\r\n# Close the file\r\n#\r\nwb.close()\r\n#\r\n# Instructions for the tasks to be done in Excel\r\n# Instruction message box display\r\n# Start Excel with the second temporary file\r\n#\r\nOutput = 'Starting Excell with SNReportTemp2.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nos.startfile('SNReportTemp2.xlsx')\r\n#\r\n# Instructions for the tasks to be done in Excel\r\n# Instruction message box display\r\n#\r\nmessagebox.showinfo(\"In Excel\", \"Sort on Assigned to RT, Engagement RT, Request RT, \\n Task RT, and Estimate RT.\\n\\nSave as SNReportTemp2.xlsx\\n\\n\\n\\nExit Excel!!!!\")\r\n#\r\n# Starting the third phase of processing\r\n# Open the second temporary file\r\n#\r\n#print('Opening SNReportTemp2.xls')\r\nOutput = 'Opening SNReportTemp2.XLSX'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb = openpyxl.load_workbook('SNReportTemp2.xlsx')\r\n#\r\n# Open the worksheet\r\n#\r\n#print('Opening Worksheet')\r\nOutput = 'Opening Worksheet'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nsheet = wb.get_sheet_by_name('Page 1')\r\n#\r\n# Move the estimated hours to the Estimate column on the Planview line\r\n#\r\n#print('Moving Estimated Hours')\r\nOutput = 'Moving Estimated Hours'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor i in range(2,sheet.max_row+1):\r\n Planview = sheet.cell(row=i, column=12).value\r\n if 'Planview work ID'in Planview:\r\n Estimate2 = sheet.cell(row=i-1, column=10).value\r\n if Estimate2 != None:\r\n sheet.cell(row=i, column=12).value = int(Estimate2)\r\n else:\r\n sheet.cell(row=i, column=12).value = \"\"\r\n for j in range(1,sheet.max_column):\r\n sheet.cell(row=i-1, column=j).value = \"\"\r\n#\r\n# Split the PVID cell, write just the PVID back to the cell.\r\n# rebuild the Feature in its own column\r\n#\r\n#print('Moving Feature Information')\r\nOutput = 'Moving Feature Information'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor i in range(2,sheet.max_row+1):\r\n PVIDFeature = sheet.cell(row=i, column=10).value\r\n if PVIDFeature == None:\r\n continue\r\n if PVIDFeature == \"\":\r\n continue\r\n PVF = PVIDFeature.split(' ')\r\n sheet.cell(row=i, column=10).value = int(PVF[0])\r\n PVF[0] = \"\"\r\n PVFTemp = ' '.join(PVF)\r\n PVFTemp2 = PVFTemp.lstrip()\r\n if PVFTemp2 != \"\":\r\n # Values for the feature cell\r\n sheet.cell(row=i, column=11).value = PVFTemp2\r\n else:\r\n # No values for the feature cell\r\n sheet.cell(row=i, column=11).value = 'No Feature'\r\n#\r\n# Save the third Temp file\r\n#\r\n#print('Saving SNReportTemp3.xlsx.')\r\nOutput = 'Saving SNReportTemp3.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb.save('SNReportTemp3.xlsx')\r\n#\r\n# Close the file\r\n#\r\nwb.close()\r\n#\r\n# Start Excel with the third temporary file\r\n#\r\nOutput = 'Starting Excel with SNReportTemp3.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nos.startfile('SNReportTemp3.xlsx')\r\n#\r\n# Instructions for the tasks to be done in Excel\r\n#\r\nmessagebox.showinfo(\"In Excel\", \"Sort by Assigned to RT, Engagement RT, \\n Request RT, Task RT to remove empty rows.\\n\\nSave SNReportTemp3.xlsx\\n\\n\\n\\nExit Excel!!!\")\r\n#\r\n# Starting the fourth pahse of processing\r\n# Getting data from Finanacial Info and Small Enhancement\r\n#\r\n# Opening the third teporary file\r\n#\r\n#print('Opening SNReportTemp3.xlsx')\r\nOutput = 'Opening SNReportTemp3.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb = openpyxl.load_workbook('SNReportTemp3.xlsx')\r\n#Open the worksheet\r\nsheet = wb.get_sheet_by_name('Page 1')\r\n#\r\n# Open Financial Info file\r\n#\r\n#print('opening Financial Info.xlsx')\r\nOutput = 'Opening Financial Info.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfwb = openpyxl.load_workbook('Finance Info.xlsx')\r\nfsheet = fwb.get_sheet_by_name('Sheet1')\r\n#\r\n# Open the Small Enhancement file\r\n#\r\n#print('Opening Small Enhancement')\r\nOutput = 'Opening Small Enhancement'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nswb = openpyxl.load_workbook('Small Enhancement.xlsx')\r\nssheet = fwb.get_sheet_by_name('Sheet1')\r\nfor i in range(2,sheet.max_row+1):\r\n PVIDFeature = sheet.cell(row=i, column=10).value\r\n if PVIDFeature == None:\r\n# sheet.cell(row=i, column=10).value = 'No PVID'\r\n sheet.cell(row=i, column=11).value = 'No Feature'\r\n continue\r\n if PVIDFeature == \"\":\r\n# sheet.cell(row=i, column=10).value = 'No PVID'\r\n sheet.cell(row=i, column=11).value = 'No Feature'\r\n#\r\n# Getting Data from Finacial by PVID and the Small Enhancement File\r\n#\r\n#print('Getting Data from Financial by PVID')\r\nOutput = 'Getting Data from Financial Info by PVID'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nmax_length = 0\r\nfor i in range(1,sheet.max_row):\r\n PVIDRT = str(sheet.cell(row=i, column=10).value)\r\n if PVIDRT == 'PVID RT': # Skip if column header\r\n continue\r\n elif PVIDRT == 'None': #Skip if no PVID\r\n continue\r\n elif str(PVIDRT) == '8601': # PVID is 8601 compare Feature and set the Name\r\n PVIDFeature = sheet.cell(row=i, column=11).value\r\n if PVIDFeature != 'None':\r\n if PVIDFeature == 'F3607':\r\n sheet.cell(row=i, column=13).value = 'NAIA'\r\n continue\r\n if PVIDFeature == 'F9831':\r\n sheet.cell(row=i, column=13).value = 'WAN-LAN'\r\n continue\r\n if PVIDFeature == 'F20206':\r\n sheet.cell(row=i, column=13).value = 'NAIA - CRE'\r\n continue\r\n if PVIDFeature == 'F20207':\r\n sheet.cell(row=i, column=13).value = 'NAIA - Network Engineering'\r\n continue\r\n if PVIDFeature == 'F20261':\r\n sheet.cell(row=i, column=13).value = 'NAIA - Internal'\r\n continue\r\n if PVIDFeature == 'F20268':\r\n sheet.cell(row=i, column=13).value = 'AA Ops Ticketing Network Assessment'\r\n continue\r\n else:\r\n sheet.cell(row=i, column=13).value = 'No 8601 Feature'\r\n continue\r\n elif str(PVIDRT) == '8576': # PVID is 8576 compare Feature and set the Name\r\n PVIDFeature = sheet.cell(row=i, column=11).value\r\n if PVIDFeature != 'None':\r\n if PVIDFeature == 'F20205':\r\n sheet.cell(row=i, column=13).value = 'NAIA - Operational Necessity'\r\n continue\r\n if PVIDFeature == 'F20259':\r\n sheet.cell(row=i, column=13).value = 'Application Definition'\r\n continue\r\n if PVIDFeature == 'F20260':\r\n sheet.cell(row=i, column=13).value = 'SOTA'\r\n continue\r\n if PVIDFeature == 'F':\r\n sheet.cell(row=i, column=13).value = 'Feature Not Defined'\r\n continue\r\n else:\r\n sheet.cell(row=i, column=13).value = 'No 8756 Feature'\r\n continue\r\n if PVIDRT !=\"PVID RT\": # Scan the Finance Info file\r\n for j in range(1,fsheet.max_row+1):\r\n PVIDFT = str(fsheet.cell(row=j, column=2).value)\r\n if PVIDFT == 'PV #': #skip if column header\r\n continue\r\n if PVIDRT in PVIDFT: #Look to see if the PVIDRT in in the PVIDFT\r\n sheet.cell(row=i, column=13).value = fsheet.cell(row=j, column=4).value #Name\r\n sheet.cell(row=i, column=14).value = fsheet.cell(row=j, column=7).value #Integration\r\n sheet.cell(row=i, column=15).value = fsheet.cell(row=j, column=9).value #Status\r\n sheet.cell(row=i, column=16).value = fsheet.cell(row=j, column=11).value #VP\r\n sheet.cell(row=i, column=17).value = fsheet.cell(row=j, column=12).value #IT Vertical\r\n sheet.cell(row=i, column=18).value = fsheet.cell(row=j, column=13).value #IT Portfolio\r\n sheet.cell(row=i, column=19).value = fsheet.cell(row=j, column=14).value #MD\r\n sheet.cell(row=i, column=20).value = fsheet.cell(row=j, column=15).value #Sponsor Division\r\n sheet.cell(row=i, column=21).value = fsheet.cell(row=j, column=16).value #Sponsor\r\n sheet.cell(row=i, column=26).value = fsheet.cell(row=j, column=17).value #Approve Date\r\n sheet.cell(row=i, column=27).value = fsheet.cell(row=j, column=18).value #Approve Start\r\n sheet.cell(row=i, column=28).value = fsheet.cell(row=j, column=19).value #Approve End\r\n sheet.cell(row=i, column=29).value = fsheet.cell(row=j, column=20).value #Planned Start\r\n sheet.cell(row=i, column=30).value = fsheet.cell(row=j, column=21).value #Planned End\r\n sheet.cell(row=i, column=31).value = fsheet.cell(row=j, column=28).value #Project Manager\r\n sheet.cell(row=i, column=32).value = fsheet.cell(row=j, column=36).value #Project Analyst\r\n sheet.cell(row=i, column=33).value = fsheet.cell(row=j, column=39).value #Project Category\r\nfor i in range(2,sheet.max_row+1):\r\n FinanceName = sheet.cell(row=i, column=13).value\r\n if FinanceName == None:\r\n sheet.cell(row=i, column=13).value = 'xxxxxxxxxx'\r\n continue\r\n if FinanceName == \"\":\r\n sheet.cell(row=i, column=13).value = 'xxxxxxxxxxz'\r\n#\r\n# Scan all the cells by column and get the maximum cell size for each column\r\n#\r\n#print('Adjusting Column Sizes and Formatting')\r\nOutput = 'Adjusting Column Sizes and Formatting'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nfor col in sheet.columns:\r\n max_length = 0\r\n column = col[0].column # Get the column name\r\n for cell in col:\r\n if column == 'E': # Format Created RT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'F': # Format Completion RT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'G': #Format Type\r\n cell.alignment = Alignment(horizontal='center')\r\n if column == 'H': # Format Description RT\r\n cell.alignment = Alignment(wrap_text='true')\r\n if column == 'J': # Format PVID RT\r\n cell.alignment = Alignment(horizontal='center', wrap_text='true')\r\n if column == 'K': # Format Feature RT\r\n cell.alignment = Alignment(horizontal='center', wrap_text='true')\r\n if column == 'L': # Format Estimate RT\r\n cell.alignment = Alignment(horizontal='center')\r\n if column == 'N': # Format Integration FT\r\n cell.alignment = Alignment(horizontal='center')\r\n if column == 'O': # Format Status FT\r\n cell.alignment = Alignment(horizontal='center')\r\n if column == 'Z': # Format Approve Date FT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'AA': # Format Approve Start Date FT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'AB': # Format Approve End Date FT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'AC': # Format Planned Start Date FT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n if column == 'AD': # Format Planned End Date FT\r\n cell.alignment = Alignment(horizontal='center')\r\n cell.number_format = 'mm/dd/yy'\r\n try: # Necessary to avoid error on empty cells\r\n if len(str(cell.value)) > max_length:\r\n max_length = len(cell.value)\r\n except:\r\n pass\r\n adjusted_width = (max_length + 2) * 1.2 # Define the column width\r\n sheet.column_dimensions[column].width = adjusted_width # Set the column width\r\n#\r\n# set columns to a specified width instead of maximum\r\n#\r\n#print('Adjusting specific column sizes')\r\nOutput = 'Adjusting specific column sizes'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nsheet.column_dimensions['B'].width = 14 # Engagement RT\r\nsheet.column_dimensions['C'].width = 14 # Request RT\r\nsheet.column_dimensions['D'].width = 15 # Task RT\r\nsheet.column_dimensions['E'].width = 14 # Created RT\r\nsheet.column_dimensions['F'].width = 14 # Completion RT\r\nsheet.column_dimensions['G'].width = 10 # Type RT\r\nsheet.column_dimensions['H'].width = 76 # Description RT\r\nsheet.column_dimensions['I'].width = 18 # Status RT\r\nsheet.column_dimensions['J'].width = 10 # PVID RT\r\nsheet.column_dimensions['K'].width = 20 # Feature RT\r\nsheet.column_dimensions['L'].width = 11 # Estimate RT\r\nsheet.column_dimensions['O'].width = 40 # Status FT\r\n#\r\n# Saving the fourth temporary file\r\n#\r\nOutput = 'Saving SNReportFTemp.xlsx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nwb.save('SNReportFTemp.xlsx')\r\n# Close the file\r\nwb.close()\r\n#\r\n# Opening fourth temporary file in Excel with instructions\r\n#\r\nOutput = 'Starting Excel with SNReportFTemp.xslx'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nos.startfile('SNReportFTemp.xlsx')\r\nmessagebox.showinfo(\"In Excel\", \"Save to Projected Time Folder with appropriate name.\\n\\nExit Excel\")\r\n#\r\n# Delete the temporary files\r\n#\r\nOutput = 'Removing temporary files'\r\nLABEL = Label(root, text=Output)\r\nLABEL.pack()\r\nroot.update()\r\nos.remove('SNReportTemp.xlsx')\r\nos.remove('SNReportTemp2.xlsx')\r\nos.remove('SNReportTemp3.xlsx')\r\nos.remove('SNReportFTemp.xlsx')\r\nmessagebox.showinfo(\"In Python\", \"Service Now Report processing Complete!\")\r\n","sub_path":"SNReport2L-B.py","file_name":"SNReport2L-B.py","file_ext":"py","file_size_in_byte":20447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"610845523","text":"from time import sleep_ms\n\nimport mqtt\nimport status_led\n\ndef rx(topic, msg):\n print((topic, msg))\n status_led.on()\n sleep_ms(100)\n status_led.off()\n\ndef looper(client):\n while True:\n client.wait_msg()\n\nmqtt.connect_loop_and_reconnect_forever(looper, b\"#\", rx)\n","sub_path":"accessory/wemos/d1mini/mqtt-noop/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"88789921","text":"#\n#\n#\n# values to be consumed by services / skills and saved to file / helper classes only / not needed / from old methods /backwards compatibility /ignore this shit\n#\n#\n#\nimport shelve\nimport time\nfrom mycroft.util.log import getLogger\n\n\nclass VisionContext():\n def __init__(self, name=\"vision.context\"):\n self.log = getLogger(\"Vision context log\")\n self.log.setLevel('WARNING')#uncomment to disable logs\n self.counter = 0\n ####### vision ######\n self.shelve = shelve.open(name, writeback=True)\n self.setdefaultcontext()\n\n try:\n self.read()\n except:\n pass\n\n def setdefaultcontext(self):\n ####### vision ######\n self.master = False\n self.person_on_screen = False\n self.was_person_on_screen_before = False\n self.movement = False\n self.multiple_persons = False\n self.smiling = False\n\n self.num_persons = 0\n\n self.distance = 0 # from camera\n\n # cv2 images\n self.mainface = None # user face pic - biggest face rect if several faces\n self.lefteye = None\n self.righteye = None\n self.smile = None\n self.vision = None\n self.update()\n\n def resetcounter(self):\n self.counter = 0\n return\n\n def read(self):\n #read fromn per manent storage\n self.master = self.shelve['master']\n self.person_on_screen = self.shelve['person_on_screen']\n self.was_person_on_screen_before = self.shelve['was_person_on_screen_before']\n self.movement = self.shelve['movement']\n self.multiple_persons = self.shelve['multiple_persons']\n self.num_persons = self.shelve['num']\n self.smiling = self.shelve['smiling']\n\n self.distance = self.shelve['distance']\n\n #cv2 images\n self.mainface = self.shelve['mainface']\n self.lefteye = self.shelve['lefteye ']\n self.righteye = self.shelve['righteye']\n self.smile = self.shelve['smile']\n self.vision = self.shelve['vision']\n\n self.counter = self.shelve['counter']\n return\n\n def update(self):\n self.shelve['num'] = self.num_persons\n self.shelve['counter'] = self.counter + 1\n self.shelve['distance'] = self.distance\n self.shelve['master'] = self.master\n self.shelve['person_on_screen'] = self.person_on_screen\n self.shelve['was_person_on_screen_before'] = self.was_person_on_screen_before\n self.shelve['movement'] = self.movement\n self.shelve['multiple_persons'] = self.multiple_persons\n self.shelve['smiling'] =self.smiling\n\n #cv2 images\n self.shelve['mainface'] =self.mainface\n self.shelve['lefteye '] =self.lefteye\n self.shelve['righteye'] =self.righteye\n self.shelve['smile'] =self.smile\n self.shelve['vision'] =self.vision\n\n # save to file current context, permanent!\n self.shelve.sync()\n\n return\n\n def close(self):\n self.shelve.close()\n\nclass FreeWillContext():\n def __init__(self, name=\"freewill.context\"):\n self.log = getLogger(\"Free Will context log\")\n self.log.setLevel('WARNING')#uncomment to disable logs\n self.shelve = shelve.open(name, writeback=True)\n self.setdefaultcontext()\n try:\n self.read()\n except:\n pass\n\n def setdefaultcontext(self):\n ####### vision ######\n ########\n self.dopamine = 0\n self.serotonine = 0\n self.tiredness = 0\n ########\n self.lasttought = \"hello world\"\n self.lastaction = \"do nothing\"\n self.mood = \"neutral\"\n self.dreaming = False\n self.master_last_seen = \"never\" # seconds ago\n self.user_last_seen = \"never\"\n self.counter = 0\n self.time_since_order = 0\n self.timeuser = 29 * 60\n self.update()\n self.time = time.time()\n\n def resetcounter(self):\n self.counter = 0\n return\n\n def read(self):\n self.dreaming = self.shelve['dream']\n\n self.lasttought = self.shelve[\"last_tought\"]\n self.lastaction = self.shelve[\"last action\"]\n self.mood = self.shelve[\"mood\"]\n\n self.master_last_seen = self.shelve['master_last_seen']\n self.user_last_seen = self.shelve['user_last_seen']\n\n self.time_since_order = self.shelve['time_since_order']\n self.time = self.shelve['time']\n self.timeuser = self.shelve['time_user']\n\n #hormones\n self.dopamine = self.shelve['dopamine'] #reward\n self.serotonine = self.shelve['serotonine'] #happiness\n self.tiredness = self.shelve['tiredness']\n\n self.counter = self.shelve['counter']\n return\n\n def update(self):\n\n self.shelve['dream'] = self.dreaming\n\n self.shelve[\"last_tought\"] = self.lasttought\n self.shelve[\"last action\"] = self.lastaction\n self.shelve[\"mood\"] = self.mood\n\n self.shelve['master_last_seen'] =self.master_last_seen\n self.shelve['user_last_seen'] =self.user_last_seen\n\n self.shelve['time_since_order'] =self.time_since_order\n self.shelve['time'] = time.time()\n self.shelve['time_user'] = self.timeuser\n\n # hormones\n self.shelve['dopamine'] = self.dopamine # reward\n self.shelve['serotonine'] = self.serotonine # happiness\n self.shelve['tiredness'] = self.tiredness\n\n # save to file current context, permanent!\n self.shelve.sync()\n return\n\n def close(self):\n self.shelve.close()\n\n\n","sub_path":"context/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"518437001","text":"import yfinance as yf\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport pandas_datareader.data as pdr\nyf.pdr_override() \nstart = dt.datetime(2015, 1, 1)\nend = dt.datetime.now()\ndf = pdr.get_data_yahoo('^GSPC', start, end)\n\n# for key, value in yf.Ticker('^GSPC').info.items():\n# print(key, \":\", value)\n\ndf['Adj Close'].plot(label = '^GSPC')\n\n# 200 day moving average\ndf['MA200'] = df['Adj Close'].rolling(200).mean().\\\n plot(label = 'MA200', color = 'red', alpha = 0.7)\n\n# 50 day moving average\ndf['MA50'] = df['Adj Close'].rolling(50).mean().\\\n plot(label = 'MA50', color = 'orange', alpha = 1.0)\n\nplt.style.use('ggplot')\nplt.title('S&P 500')\nplt.legend(loc = 'lower right')\nplt.ylabel('Price in USD', fontsize = 11)\nplt.grid(color = 'black', linestyle = '--', linewidth = 1)\nplt.show()\n","sub_path":"stock/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"595015725","text":"from ..solvers import solver_instance\nfrom ..solvers.solution import Status\nfrom ..cobra.simulation import FBA\nfrom .GPRtransform import gpr_transform\nfrom math import inf\n\n\ndef marge(model, rel_expression, transformed=False, constraints_a=None, constraints_b=None, rel_constraints=None,\n growth_frac_a=0.1, growth_frac_b=0.1, activation_frac=0.1, activation_max=1.0, step2_tol=0.1,\n gene_prefix='G_', pseudo_genes=None):\n \"\"\" Metabolic Analysis with Relative Gene Expression (MARGE)\n\n First step minimizes the objective (fluxes B - rel expr (B/A) * fluxes A)\n\n Second step adds a parsimony criteria (with a slight relaxation of the first objective)\n\n Args:\n model (CBModel): organism model\n rel_expression (dict): relative gene expression (condition B / condition A)\n transformed (bool): True if the model is already in extended GPR format (default: False)\n constraints_a (dict): additional constrants to use for condition A (optional)\n constraints_b (dict): additional constrants to use for condition B (optional)\n rel_constraints (dict): relative constraints between conditions (such as flux ratios) (default: False)\n growth_frac_a (float): minimum growth rate in condition A (default: 0.1)\n growth_frac_b (float): minimum growth rate in condition B (default: 0.1)\n activation_frac (float): flux activation threshold for expressed genes (fraction of max flux, default: 0.1)\n activation_max (float): max value for flux activation threshold (default: 1.0)\n step2_tol (float): relaxation from main objective during second step (default: 0.1)\n gene_prefix (str): prefix used in gene identifiers (default: 'G_')\n\n pseudo_genes (list): pseudo-genes in model to ignore (e.g: 'spontaneous') (optional)\n\n Returns:\n dict: fluxes in condition A\n dict: fluxes in condition B\n Solution: solver solution for step 1 (minimize flux changes)\n Solution: solver solution for step 2 (minimize absolute fluxes)\n\n \"\"\"\n\n if not transformed:\n model = gpr_transform(model, inplace=False, gene_prefix=gene_prefix, pseudo_genes=pseudo_genes)\n\n if constraints_a is None:\n constraints_a = {}\n else:\n constraints_a = model.convert_constraints(constraints_a)\n\n if constraints_b is None:\n constraints_b = {}\n else:\n constraints_b = model.convert_constraints(constraints_b)\n\n if rel_constraints is None:\n rel_constraints = {}\n\n pre_solver = solver_instance(model)\n\n if growth_frac_a > 0:\n biomass = model.biomass_reaction\n sol_a = FBA(model, solver=pre_solver, constraints=constraints_a)\n if sol_a.status != Status.OPTIMAL:\n print('Failed to solve reference model for condition A.')\n return None, None, None, None\n constraints_a[biomass] = (sol_a.fobj * growth_frac_a, inf)\n\n if growth_frac_b > 0:\n biomass = model.biomass_reaction\n sol_b = FBA(model, solver=pre_solver, constraints=constraints_b)\n if sol_b.status != Status.OPTIMAL:\n print('Failed to solve reference model for condition B.')\n return None, None, None, None\n constraints_b[biomass] = (sol_b.fobj * growth_frac_b, inf)\n\n if activation_frac > 0:\n act_constraints_a = {}\n act_constraints_b = {}\n\n for g_id in rel_expression:\n r_id = 'u_' + g_id[len(gene_prefix):]\n\n if r_id not in constraints_a:\n max_flux = FBA(model, objective=r_id, solver=pre_solver, constraints=constraints_a)\n if max_flux.status == Status.OPTIMAL:\n min_flux = min(max_flux.fobj * activation_frac, activation_max)\n act_constraints_a[r_id] = (min_flux, model.reactions[r_id].ub)\n\n if r_id not in constraints_b:\n max_flux = FBA(model, objective=r_id, solver=pre_solver, constraints=constraints_b)\n if max_flux.status == Status.OPTIMAL:\n min_flux = min(max_flux.fobj * activation_frac, activation_max)\n act_constraints_b[r_id] = (min_flux, model.reactions[r_id].ub)\n\n constraints_a.update(act_constraints_a)\n constraints_b.update(act_constraints_b)\n\n solver = solver_instance()\n\n for r_id, reaction in model.reactions.items():\n lb_a, ub_a = constraints_a.get(r_id, (reaction.lb, reaction.ub))\n solver.add_variable(r_id + '_a', lb_a, ub_a, update=False)\n\n lb_b, ub_b = constraints_b.get(r_id, (reaction.lb, reaction.ub))\n solver.add_variable(r_id + '_b', lb_b, ub_b, update=False)\n\n for g_id, val in rel_expression.items():\n solver.add_variable(g_id + '_+', 0, inf, update=False)\n solver.add_variable(g_id + '_-', 0, inf, update=False)\n\n solver.update()\n\n table = model.metabolite_reaction_lookup()\n\n for m_id in model.metabolites:\n stoich_a = {r_id + '_a': val for r_id, val in table[m_id].items()}\n solver.add_constraint(m_id + '_a', stoich_a, update=False)\n\n stoich_b = {r_id + '_b': val for r_id, val in table[m_id].items()}\n solver.add_constraint(m_id + '_b', stoich_b, update=False)\n\n for r_id, ratio in rel_constraints.items():\n if isinstance(ratio, tuple):\n lb, ub = ratio[0], ratio[1]\n else:\n lb, ub = ratio, ratio\n \n constr_lb = {}\n constr_ub = {}\n expr_a_lb = model.convert_id_to_expr(r_id, -lb)\n expr_a_ub = model.convert_id_to_expr(r_id, -ub)\n expr_b = model.convert_id_to_expr(r_id, 1)\n constr_lb.update({r_id2 + '_a': val for r_id2, val in expr_a_lb.items()})\n constr_lb.update({r_id2 + '_b': val for r_id2, val in expr_b.items()})\n constr_ub.update({r_id2 + '_a': val for r_id2, val in expr_a_ub.items()})\n constr_ub.update({r_id2 + '_b': val for r_id2, val in expr_b.items()})\n solver.add_constraint(r_id + '_rel_lb', constr_lb, '>', 0, update=False)\n solver.add_constraint(r_id + '_rel_ub', constr_ub, '<', 0, update=False)\n\n for g_id, val in rel_expression.items():\n u_id_a = 'u_' + g_id[len(gene_prefix):] + '_a'\n u_id_b = 'u_' + g_id[len(gene_prefix):] + '_b'\n solver.add_constraint(g_id + '_c+', {g_id + '_+': 1, u_id_b: -1, u_id_a: val}, '>', 0, update=False)\n solver.add_constraint(g_id + '_c-', {g_id + '_-': 1, u_id_b: 1, u_id_a: -val}, '>', 0, update=False)\n\n solver.update()\n\n objective1 = {}\n for g_id in rel_expression.keys():\n objective1[g_id + '_+'] = 1\n objective1[g_id + '_-'] = 1\n\n solution1 = solver.solve(objective1, minimize=True)\n\n if solution1.status != Status.OPTIMAL:\n print('Failed to solve first problem.')\n return None, None, solution1, None\n\n obj1_max = solution1.fobj * (1 + step2_tol)\n solver.add_constraint(\"obj1\", objective1, '<', obj1_max, update=True)\n\n objective2 = {}\n for r_id in model.u_reactions:\n objective2[r_id + '_a'] = 1\n objective2[r_id + '_b'] = 1\n\n solution2 = solver.solve(objective2, minimize=True)\n\n if solution2.status != Status.OPTIMAL:\n print('Failed to solve second problem.')\n return None, None, solution1, solution2\n\n fluxes_a = {r_id: solution2.values[r_id + '_a'] for r_id in model.reactions}\n fluxes_b = {r_id: solution2.values[r_id + '_b'] for r_id in model.reactions}\n\n fluxes_a = model.convert_fluxes(fluxes_a)\n fluxes_b = model.convert_fluxes(fluxes_b)\n\n return fluxes_a, fluxes_b, solution1, solution2\n","sub_path":"reframed/alpha/MARGE.py","file_name":"MARGE.py","file_ext":"py","file_size_in_byte":7565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"203389024","text":"import re \n \n# Function checks if the string contains any special character \ndef checkString(string): \n \n # Make own character set and pass \n regex = re.compile('[@_#$%^&*<>\\|}{~:]') \n \n # Pass the string in search \n if(regex.search(string) == None): \n #print(\"String is accepted\")\n return 1\n \n else: return 0\n \n ","sub_path":"CleaningData/CheckStringContainsSpecialCharacters.py","file_name":"CheckStringContainsSpecialCharacters.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"345898721","text":"from Mazo import Mazo\nfrom Jugador import Jugador\nimport CASESENSITIVES\nfrom string import ascii_letters\nfrom Menu import Menu\nfrom Carta import ESPECIALES, NEGRAS\n\nclass Partida(object):#Crea la partida en cuestion, se comporta como la mesa.\n def __init__(self, ordenNormal=True):\n self.mazo=Mazo().mazo\n self.menu=Menu()\n self.jugadores=self.crearJugadores()\n self.ordenNormal=ordenNormal\n self._current_player=self.jugadores[0]#Caso base, primer jugador\n self._ganador=None\n self._prima_Carta=self.mazo.pop(-1)\n self._ultimaJugada=[self._prima_Carta]\n self._acumulado=0 #Para acumular el valor de las cartas sumatorias cuando respondan con una sumatoria.\n @property\n def acumulado(self):\n return self.acumulado\n\n @property\n def ultimaJugada(self):\n return self._ultimaJugada\n \n @property\n def current_player(self):\n return self._current_player\n\n @property\n def ganador(self):\n return self._ganador\n\n @ganador.setter\n def ganador(self, ganador):\n self._ganador=ganador #Retorna true para que acabe el juego y pida el ganador.\n\n @acumulado.setter\n def acumulado(self, val):\n self._acumulado+=val\n\n def add_ultimaJugada(self, carta):\n self._ultimaJugada.append(carta)\n \n def nombre_de_Jugadores(self):\n _nombres_Jugadores=[jugador.nombre for jugador in self.jugadores]\n nombres_Jugadores= ''#str(_nombres_Jugadores[0])\n for val in range(0,len(self.jugadores)):\n nombres_Jugadores+=\" | \"+str(_nombres_Jugadores[val])\n return nombres_Jugadores+\" | \"\n\n def cambiar_Orden(self, param):\n self.ordenNormal=param\n\n def salir(self):\n exit\n\n def prima_Carta(self):#Primera carta al azar.\n carta=self.mazo.pop(-1)\n self.add_ultimaJugada(carta)\n return carta\n\n def crearJugadores(self, nombres_Jugadores=None):\n nombres_Jugadores=input(\"Escribe el nombre de los jugadores separado por comas: \")\n if nombres_Jugadores:#Existe?\n obj_jugadores=[]\n if \",\" not in nombres_Jugadores:\n print(\"¿Eres un lobo solitario? Porque solo veo un jugador: \"+str(nombres_Jugadores))\n if CASESENSITIVES.S_sensitiva(input(\"¿Deseas volver a crear los jugadores? S/N\")):\n return self.crearJugadores()\n else:\n return self.menu.como_Jugar()\n else:\n for char in nombres_Jugadores:\n if char not in ascii_letters + \",\":\n nombres_Jugadores=nombres_Jugadores.replace(char,\"\")\n nombres_Jugadores=nombres_Jugadores.split(\",\")\n for nombre in nombres_Jugadores:\n obj_jugadores.append(Jugador(nombre,self))\n if len(obj_jugadores)>10:\n input(\"Excedes el número máximo de jugadores por partida, que son 10. \")\n if CASESENSITIVES.S_sensitiva(input(\"¿Deseas volver a crear los jugadores? S/N \")):\n return self.crearJugadores()\n else:\n return self.menu.como_Jugar()\n return obj_jugadores\n else:\n self.crearJugadores()\n\n def tipo_Funcion(self, carta):\n if carta.carta_tipo in ESPECIALES + NEGRAS:\n if carta.carta_tipo == ESPECIALES[0]:#SKIP\n return \"skip\"\n \n if carta.carta_tipo==ESPECIALES[1]:#REVERSE\n return \"reverse\"\n\n if carta.carta_tipo==ESPECIALES[2]:#+2\n #Llamar a la funcion que agrega cartas con el current player y mandarle como param 2. Para hcer que puedan acumularse las sumas, que si el usuario no lanza una sumatoria, entonces que al current le agrega las cartas, pero si no lanza una sumatoria, que agrege una cantidad +2 o +4 al current.\n return 2 #Que hace +2?\n\n if carta.carta_tipo==NEGRAS[0]:#WildCard\n self.add_ultimaJugada(carta.negra_Wild())\n return \"Negra\"\n #llamar la funcion de carta.negrawild\n #Que hace WildCard?\n if carta.carta_tipo==NEGRAS[1]:#+4\n self.add_ultimaJugada(carta.negra_Wild())\n #Llamar a la funcion que agrega cartas con el current player y mandarle como param 4.\n return 4\n\n def jugador_Actual(self, Player):#Automaticamente el valor es el primer objeto jugador\n self._current_player=Player\n return self._current_player\n\n def siguiente_Jugador(self):\n i=self.current_player.encontrarse(self.jugadores)\n if self.jugadores[i]==self._current_player:\n siguiente=i+1\n if siguiente < len(self.jugadores):\n return self.jugadores[siguiente]\n else:\n return self.jugadores[0]\n \n def anterior_Jugador(self):\n i=self.current_player.encontrarse(self.jugadores)\n if self.jugadores[i]==self._current_player:\n anterior=i-1\n if anterior <= len(self.jugadores) and anterior>-1:\n return self.jugadores[anterior]\n else:\n return self.jugadores[len(self.jugadores)-1]\n\n @property\n def ultima_carta(self):\n if self.mazo:\n if self._prima_Carta:\n return self._ultimaJugada[-1]\n\n def _proximo(self):\n if self.ordenNormal:\n self._current_player=self._current_player._jugador_siguiente\n else:\n self._anterior()\n\n def _anterior(self):\n self._current_player=self._current_player._jugador_anterior\n\n\n#TESTING#\n\"\"\"Partida1=Partida()\nprint(Partida1.jugadores)\nprint(Partida1.current_player)\nprint(Partida1.current_player.encontrarse(Partida1.jugadores))\nPartida1.current_player.add_siguiente(True)\nPartida1.current_player.add_anterior(True)\nprint(Partida1.current_player.siguiente)\nprint(Partida1.current_player.anterior)\nPartida1.current_player.tomar(Partida1.mazo,7)\nPartida1.current_player.imprime_Cartas()\"\"\"\n#FALTA LOOP PARA JUGAR HASTA QUE EL GANADOR EXISTA, LOOP PARA OBTENER UNA CARTA DE LOS JUGADORES Y QUE PUEDA CONTONUAR JUGANDO OTRA CARTA SI COINCIDE, LOOP de CUANDO TERMINE DE ELEGIR SUS CARTAS, SIGUE EL OTRO JUGADOR, Y LAS FUNCIONes de cada carta, digamos que llame CARTA.TIPO_FUNCION y ejecute una función de acuerdo al tipo de carta que sea.","sub_path":"Partida.py","file_name":"Partida.py","file_ext":"py","file_size_in_byte":6491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121028313","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n# need to get apikey \n\n# Full address 가 아니므로 다음 API를 이용해서 Full address로 바꾸는 작업을 해주는 함수\ndef toFullAdd(df_paik):\n list2 = []\n num = 0\n while num < len(df_paik):\n url = \"https://apis.daum.net/local/geo/addr2coord?apikey={}&q={}&output =xml\".format(apikey2, df_paik.iloc[num, 0].split(\",\")[0])\n source_code = requests.get(url)\n source_code.encoding = \"utf-8\"\n plain_text = source_code.text\n #print(plain_text)\n bs = BeautifulSoup(plain_text, \"html.parser\")\n title = bs.find_all(\"title\")\n mod = 1\n for i in title:\n if mod % 2 == 0:\n print(i.get_text())\n list2.append(i.get_text())\n mod += 1\n num += 1\n return list2\n\n\n\n\n# 빽다방 홈페이지에서 매장 주소 크롤링\ndef paikStores(max_pages):\n list1 = []\n page = 1\n while page < max_pages:\n url = \"http://www.paikdabang.com/paiks/store.asp?page=\"+str(page)+\"&shop_region=&shop_name=&shop_seoul=\"\n source_code = requests.get(url)\n source_code.encoding = \"euc-kr\"\n # requests.get 을 이용해서 url의 데이터를 받아온다\n plain_text = source_code.text\n bs = BeautifulSoup(plain_text , \"html.parser\")\n table1 = bs.find_all(\"img\", src=\"img/st_icon_03.png\")\n\n for i in table1:\n list1.append(i.get_text().split(\": \")[1])\n page += 1\n\n df_paik = pd.DataFrame(list1, columns=[\"주소\"])\n paikList = toFullAdd(df_paik)\n paikList = pd.DataFrame(paikList, columns=[\"주소\"])\n return paikList\n\npages = 55\npaikList = paikStores(pages)\n#paikList.to_csv(\"/Users/sinsanghun/Documents/pycharm/fastcampus/paik2.csv\")\n\n\n\n\n\n","sub_path":"paik.py","file_name":"paik.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"161268801","text":"from datetime import date\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied\nfrom django.db.models import Q\nfrom django.http import HttpResponse, JsonResponse\nfrom django.http.response import Http404\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic.base import TemplateView, View\n\nfrom celery.result import AsyncResult\nfrom dateutil.relativedelta import relativedelta\n\nfrom couchexport.models import Format\nfrom dimagi.utils.dates import force_to_date\n\nfrom corehq.apps.domain.decorators import (\n login_and_domain_required,\n require_superuser_or_contractor,\n)\nfrom corehq.apps.domain.views.base import BaseDomainView\nfrom corehq.apps.hqwebapp.decorators import use_daterangepicker\nfrom corehq.apps.hqwebapp.views import no_permissions\nfrom corehq.apps.locations.models import SQLLocation\nfrom corehq.apps.locations.permissions import location_safe\nfrom corehq.util.files import safe_filename_header\nfrom custom.aaa.const import COLORS, INDICATOR_LIST, NUMERIC, PERCENT\nfrom custom.aaa.dbaccessors import (\n ChildQueryHelper,\n EligibleCoupleQueryHelper,\n PregnantWomanQueryHelper,\n)\nfrom custom.aaa.models import Child, Woman\nfrom custom.aaa.tasks import prepare_export_reports, run_aggregation\nfrom custom.aaa.utils import (\n build_location_filters,\n get_file_from_blobdb,\n get_location_model_for_ministry,\n)\n\n\n@location_safe\nclass ReachDashboardView(TemplateView):\n @property\n def domain(self):\n return self.kwargs['domain']\n\n @property\n def couch_user(self):\n return self.request.couch_user\n\n @property\n def user_ministry(self):\n return self.couch_user.user_data.get('ministry')\n\n def dispatch(self, *args, **kwargs):\n if (not self.couch_user.is_web_user()\n and (self.user_ministry is None or self.user_ministry == '')):\n return no_permissions(self.request)\n\n return super(ReachDashboardView, self).dispatch(*args, **kwargs)\n\n def get_context_data(self, **kwargs):\n kwargs['domain'] = self.domain\n\n kwargs['is_web_user'] = self.couch_user.is_web_user()\n kwargs['user_role_type'] = self.user_ministry\n\n user_location = self.couch_user.get_sql_locations(self.domain).first()\n kwargs['user_location_id'] = user_location.location_id if user_location else None\n user_locations_with_parents = SQLLocation.objects.get_queryset_ancestors(\n user_location, include_self=True\n ).distinct() if user_location else []\n parent_ids = [loc.location_id for loc in user_locations_with_parents]\n kwargs['user_location_ids'] = parent_ids\n kwargs['is_details'] = False\n\n selected_location = self.request.GET.get('selectedLocation', '')\n if selected_location:\n location = SQLLocation.objects.get(location_id=selected_location)\n selected_hierarchy = [loc.location_id for loc in location.get_ancestors(include_self=True)]\n kwargs['selected_location_ids'] = selected_hierarchy\n return super(ReachDashboardView, self).get_context_data(**kwargs)\n\n\n@method_decorator([login_and_domain_required], name='dispatch')\nclass ProgramOverviewReport(ReachDashboardView):\n template_name = 'aaa/reports/program_overview.html'\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass ProgramOverviewReportAPI(View):\n @property\n def couch_user(self):\n return self.request.couch_user\n\n @property\n def user_ministry(self):\n return self.couch_user.user_data.get('ministry')\n\n def post(self, request, *args, **kwargs):\n selected_month = int(self.request.POST.get('selectedMonth'))\n selected_year = int(self.request.POST.get('selectedYear'))\n selected_location = self.request.POST.get('selectedLocation')\n selected_date = date(selected_year, selected_month, 1)\n selected_ministry = self.request.POST.get('selectedMinistry')\n prev_month = date(selected_year, selected_month, 1) - relativedelta(months=1)\n\n location_filters = build_location_filters(selected_location, selected_ministry)\n data = get_location_model_for_ministry(selected_ministry).objects.filter(\n (Q(month=selected_date) | Q(month=prev_month)),\n domain=self.request.domain,\n **location_filters\n ).order_by('month').values()\n\n vals = {\n val['month']: val\n for val in data\n }\n data = vals.get(selected_date, {})\n prev_month_data = vals.get(prev_month, {})\n\n return JsonResponse(data={'data': [\n [\n {\n 'indicator': INDICATOR_LIST['registered_eligible_couples'],\n 'format': NUMERIC,\n 'color': COLORS['violet'],\n 'value': data.get('registered_eligible_couples', 0),\n 'past_month_value': prev_month_data.get('registered_eligible_couples', 0)\n },\n {\n 'indicator': INDICATOR_LIST['registered_pregnancies'],\n 'format': NUMERIC,\n 'color': COLORS['blue'],\n 'value': data.get('registered_pregnancies', 0),\n 'past_month_value': prev_month_data.get('registered_pregnancies', 0)\n },\n {\n 'indicator': INDICATOR_LIST['registered_children'],\n 'format': NUMERIC,\n 'color': COLORS['orange'],\n 'value': data.get('registered_children', 0),\n 'past_month_value': prev_month_data.get('registered_children', 0)\n }\n ],\n [\n {\n 'indicator': INDICATOR_LIST['couples_family_planning'],\n 'format': PERCENT,\n 'color': COLORS['aqua'],\n 'value': data.get('eligible_couples_using_fp_method', 0),\n 'total': data.get('registered_eligible_couples', 0),\n 'past_month_value': prev_month_data.get('eligible_couples_using_fp_method', 0),\n },\n {\n 'indicator': INDICATOR_LIST['high_risk_pregnancies'],\n 'format': PERCENT,\n 'color': COLORS['darkorange'],\n 'value': data.get('high_risk_pregnancies', 0),\n 'total': data.get('registered_pregnancies', 0),\n 'past_month_value': prev_month_data.get('high_risk_pregnancies', 0),\n },\n {\n 'indicator': INDICATOR_LIST['institutional_deliveries'],\n 'format': PERCENT,\n 'color': COLORS['mediumblue'],\n 'value': data.get('institutional_deliveries', 0),\n 'total': data.get('total_deliveries', 0),\n 'past_month_value': prev_month_data.get('institutional_deliveries', 0),\n }\n ]\n ]})\n\n\n@method_decorator([login_and_domain_required], name='dispatch')\nclass UnifiedBeneficiaryReport(ReachDashboardView):\n template_name = 'aaa/reports/unified_beneficiary.html'\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass UnifiedBeneficiaryReportAPI(View):\n def post(self, request, *args, **kwargs):\n selected_month = int(self.request.POST.get('selectedMonth'))\n selected_year = int(self.request.POST.get('selectedYear'))\n selected_date = date(selected_year, selected_month, 1)\n next_month_start = selected_date + relativedelta(months=1)\n selected_location = self.request.POST.get('selectedLocation')\n selected_ministry = self.request.POST.get('selectedMinistry')\n beneficiary_type = self.request.POST.get('selectedBeneficiaryType')\n draw = self.request.POST.get('draw', 0)\n length = int(self.request.POST.get('length', 0))\n start = int(self.request.POST.get('start', 0))\n sort_column = self.request.POST.get('sortColumn', 'name')\n sort_column_dir = self.request.POST.get('sortColumnDir', 'asc')\n\n location_filters = build_location_filters(selected_location, selected_ministry, with_child=False)\n sort_column_with_dir = sort_column\n if sort_column_dir == 'desc':\n sort_column_with_dir = '-' + sort_column\n data = []\n if beneficiary_type == 'child':\n data = ChildQueryHelper.list(request.domain, next_month_start, location_filters, sort_column_with_dir)\n elif beneficiary_type == 'eligible_couple':\n sort_column_with_dir = '\"%s\" %s' % (sort_column, sort_column_dir)\n data = EligibleCoupleQueryHelper.list(\n request.domain,\n selected_date,\n location_filters,\n sort_column_with_dir\n )\n elif beneficiary_type == 'pregnant_women':\n sort_column_with_dir = '\"%s\" %s' % (sort_column, sort_column_dir)\n data = PregnantWomanQueryHelper.list(\n request.domain,\n selected_date,\n location_filters,\n sort_column_with_dir\n )\n if data:\n number_of_data = len(data)\n data = data[start:start + length]\n else:\n number_of_data = 0\n data = list(data)\n return JsonResponse(data={\n 'rows': data,\n 'draw': draw,\n 'recordsTotal': number_of_data,\n 'recordsFiltered': number_of_data,\n })\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass LocationFilterAPI(View):\n def post(self, request, *args, **kwargs):\n selected_location = self.request.POST.get('parentSelectedId', None)\n location_type = self.request.POST.get('locationType', None)\n domain = self.kwargs['domain']\n locations = SQLLocation.objects.filter(\n domain=domain,\n location_type__code=location_type\n ).order_by('name')\n\n if selected_location:\n locations = locations.filter(parent__location_id=selected_location).order_by('name')\n\n return JsonResponse(data={'data': [\n dict(\n id=loc.location_id,\n name=loc.name,\n parent_id=loc.parent.location_id if loc.parent else None\n ) for loc in locations]\n })\n\n\n@method_decorator([login_and_domain_required, require_superuser_or_contractor], name='dispatch')\nclass AggregationScriptPage(BaseDomainView):\n page_title = 'Aggregation Script'\n urlname = 'aaa_aggregation_script_page'\n template_name = 'icds_reports/aggregation_script.html'\n\n @use_daterangepicker\n def dispatch(self, *args, **kwargs):\n if settings.SERVER_ENVIRONMENT != 'india':\n return HttpResponse(\"This page is only available for QA and not available for production instances.\")\n\n couch_user = self.request.couch_user\n if couch_user.is_domain_admin(self.domain):\n return super(AggregationScriptPage, self).dispatch(*args, **kwargs)\n\n raise PermissionDenied()\n\n def section_url(self):\n return\n\n def post(self, request, *args, **kwargs):\n date_param = self.request.POST.get('date')\n if not date_param:\n messages.error(request, 'Date is required')\n return redirect(self.urlname, domain=self.domain)\n date = force_to_date(date_param)\n run_aggregation(self.domain, date)\n messages.success(request, 'Aggregation task has run.')\n return redirect(self.urlname, domain=self.domain)\n\n\n@method_decorator([login_and_domain_required], name='dispatch')\nclass UnifiedBeneficiaryDetailsReport(ReachDashboardView):\n template_name = 'aaa/reports/unified_beneficiary_details.html'\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n context['is_details'] = True\n context['beneficiary_id'] = kwargs.get('beneficiary_id')\n context['selected_type'] = kwargs.get('details_type')\n context['selected_month'] = int(request.GET.get('month'))\n context['selected_year'] = int(request.GET.get('year'))\n\n person_model = Woman if context['selected_type'] != 'child' else Child\n\n village_id = person_model.objects.get(person_case_id=context['beneficiary_id']).village_id\n\n locations = SQLLocation.objects.get(\n domain=request.domain, location_id=village_id\n ).get_ancestors(include_self=True)\n\n context['beneficiary_location_names'] = [\n loc.name for loc in locations\n ]\n return self.render_to_response(context)\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass UnifiedBeneficiaryDetailsReportAPI(View):\n def post(self, request, *args, **kwargs):\n selected_month = int(self.request.POST.get('selectedMonth', 0))\n selected_year = int(self.request.POST.get('selectedYear', 0))\n month_end = date(selected_year, selected_month, 1) + relativedelta(months=1) - relativedelta(days=1)\n section = self.request.POST.get('section', '')\n sub_section = self.request.POST.get('subsection', '')\n beneficiary_id = self.request.POST.get('beneficiaryId', '')\n data = {}\n\n if sub_section == 'person_details':\n person_model = Woman if section != 'child' else Child\n\n values = [\n 'dob', 'name', 'sex', 'has_aadhar_number', 'hh_address', 'contact_phone_number',\n 'hh_religion', 'hh_caste', 'hh_bpl_apl', 'sc_id', 'village_id', 'awc_id'\n ]\n\n if section != 'child':\n values.extend([\n 'migration_status',\n 'age_marriage',\n 'husband_name',\n 'marital_status'\n ])\n else:\n values.append('mother_case_id')\n\n person = person_model.objects.values(*values).get(\n domain=request.domain,\n person_case_id=beneficiary_id\n )\n\n location_details = SQLLocation.objects.filter(\n domain=request.domain,\n location_id__in=[person['sc_id'], person['village_id'], person['awc_id']]\n )\n\n for location in location_details:\n person[location.location_type.code] = location.name\n\n data = dict(\n person=person,\n )\n\n if section == 'child':\n mother = Woman.objects.extra(\n select={\n 'id': 'person_case_id'\n }\n ).values('id', 'name').get(person_case_id=person['mother_case_id'])\n data.update(dict(mother=mother))\n else:\n # TODO update when the model will be created\n husband = dict(\n name=person['husband_name'],\n sex='N/A',\n dob='N/A',\n age_marriage='N/A',\n has_aadhar_number='N/A'\n )\n data.update(dict(husband=husband))\n elif sub_section == 'child_details':\n data = dict(\n children=list(Child.objects.filter(\n domain=request.domain,\n mother_case_id=beneficiary_id\n ).extra(\n select={\n 'id': 'person_case_id'\n }\n ).values('id', 'name', 'dob'))\n )\n\n if section == 'child':\n helper = ChildQueryHelper(request.domain, beneficiary_id, month_end)\n if sub_section == 'infant_details':\n data = helper.infant_details()\n elif sub_section == 'child_postnatal_care_details':\n data = {'visits': helper.postnatal_care_details()}\n elif sub_section == 'vaccination_details':\n period = self.request.POST.get('period', 'atBirth')\n data = {'vitamins': helper.vaccination_details(period)}\n elif sub_section == 'growth_monitoring':\n data = helper.growth_monitoring()\n elif sub_section == 'weight_for_age_chart':\n data = {'points': helper.weight_for_age_chart()}\n elif sub_section == 'height_for_age_chart':\n data = {'points': helper.height_for_age_chart()}\n elif sub_section == 'weight_for_height_chart':\n data = {'points': helper.weight_for_height_chart()}\n elif section == 'pregnant_women':\n helper = PregnantWomanQueryHelper(request.domain, beneficiary_id, month_end)\n if sub_section == 'pregnancy_details':\n data = helper.pregnancy_details()\n elif sub_section == 'pregnancy_risk':\n data = helper.pregnancy_risk()\n elif sub_section == 'consumables_disbursed':\n data = helper.consumables_disbursed()\n elif sub_section == 'immunization_counseling_details':\n data = helper.immunization_counseling_details()\n elif sub_section == 'abortion_details':\n data = helper.abortion_details()\n elif sub_section == 'maternal_death_details':\n data = helper.maternal_death_details()\n elif sub_section == 'delivery_details':\n data = helper.delivery_details()\n elif sub_section == 'postnatal_care_details':\n data = {'visits': helper.postnatal_care_details()}\n elif sub_section == 'antenatal_care_details':\n data = {'visits': helper.antenatal_care_details()}\n elif section == 'eligible_couple':\n helper = EligibleCoupleQueryHelper(request.domain, beneficiary_id, month_end)\n if sub_section == 'eligible_couple_details':\n data = helper.eligible_couple_details()\n\n if not data:\n raise Http404()\n return JsonResponse(data=data)\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass ExportData(View):\n def post(self, request, *args, **kwargs):\n selected_month = int(self.request.POST.get('selectedMonth'))\n selected_year = int(self.request.POST.get('selectedYear'))\n selected_date = date(selected_year, selected_month, 1)\n next_month_start = selected_date + relativedelta(months=1)\n selected_location = self.request.POST.get('selectedLocation')\n selected_ministry = self.request.POST.get('selectedMinistry')\n beneficiary_type = self.request.POST.get('selectedBeneficiaryType')\n\n task = prepare_export_reports.delay(\n request.domain,\n selected_date,\n next_month_start,\n selected_location,\n selected_ministry,\n beneficiary_type\n )\n return JsonResponse(data={\n 'task_id': task.task_id\n })\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass CheckExportTask(View):\n def get(self, request, *args, **kwargs):\n task_id = self.kwargs.get('task_id', None)\n res = AsyncResult(task_id) if task_id else None\n status = res and res.ready()\n\n if status:\n return JsonResponse(\n {\n 'task_ready': status,\n 'task_successful': res.successful(),\n 'task_result': res.result if res.successful() else None\n }\n )\n return JsonResponse({'task_ready': status})\n\n\n@location_safe\n@method_decorator([login_and_domain_required, csrf_exempt], name='dispatch')\nclass DownloadFile(View):\n def get(self, request, *args, **kwargs):\n file_id = self.kwargs.get('file_id', None)\n content_type = Format.from_format('xlsx')\n response = HttpResponse(\n get_file_from_blobdb(file_id).read(),\n content_type=content_type.mimetype\n )\n response['Content-Disposition'] = safe_filename_header(\n 'unified_beneficiary_list',\n content_type.extension\n )\n return response\n","sub_path":"custom/aaa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"497248658","text":"keyword_dict = {'javascript': ['javascript', 'js', 'angular', 'react', 'jquery', 'meteor', 'node'],\n 'java': ['java', 'blade', 'gwt', 'grails', 'jsf'],\n 'python': ['python', 'anaconda', 'flask', 'django'],\n 'css': ['css', 'bootstrap'],\n 'php': ['php', 'laravel', 'codeigniter'],\n 'ruby': ['ruby', 'padrino', 'scorched'],\n 'cplusplus': ['c++', 'cpp'],\n 'c': ['c'],\n 'shell': ['shell', 'bash'],\n 'csharp': ['c#', '.net', 'dotnet'],\n 'objective-c': ['objective-c'],\n 'r': ['r', 'rstudio'],\n 'perl': ['perl', ],\n 'coffeescript': ['coffeescript', ],\n 'tex': ['tex', 'latex'],\n 'swift': ['swift', ],\n 'scala': ['scala', 'spark'],\n 'emacs lisp': ['emacs lisp', ],\n 'haskell': ['haskell', ],\n 'lua': ['lua', ],\n 'clojure': ['clojure', ],\n 'matlab': ['matlab', ],\n 'arduino': ['arduino', ],\n 'makefile': ['makefile', ],\n 'groovy': ['groovy', ],\n 'puppet': ['puppet', ],\n 'rust': ['rust', ],\n 'powershell': ['powershell', ],\n 'containers': ['docker','kubernetes','mesos', 'rkt'],\n 'network': ['ipv4', 'ipv6', 'cisco'],\n 'sql': ['sql','mysql','mssql', 'mariadb'],\n 'non_relational': ['mongo', 'mongodb', 'couch', 'redis', 'memcache', 'hbase'],\n 'cloud_vendors': ['aws', 'gcp', 'azure'],\n 'london': ['london']}\n","sub_path":"preprocess/keyword_feature.py","file_name":"keyword_feature.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"524713000","text":"import turtle\nimport numpy as np\n\ndef poly(n, r):\n\tturtle.left(90+180.0/n)\n\tfor i in range(0, n, 1):\n\t\tturtle.forward(2*r*np.sin(np.pi/n))\n\t\tturtle.left(360.0/n)\n\tturtle.right(90+180.0/n)\n\t\n\t\t\n\nturtle.shape('turtle')\nfor i in range(3, 13, 1):\n\tr=i*15\n\tturtle.penup()\n\tturtle.forward(15)\n\tturtle.pendown()\n\tpoly(i, r)\n","sub_path":"ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527056903","text":"file = open('Expense Report.txt','r')\nnums = file.read().splitlines()\n\nfor x in nums:\n for y in nums:\n if (int(y) + int(x)) == 2020:\n print(x)\n print(y)\n print(\"Answer is: \", int(y) * int(x))\n \n \nfile.close()","sub_path":"AoC2020_Day 1/AoC2020_Day 1 - Task 1.py","file_name":"AoC2020_Day 1 - Task 1.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"621653928","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport sys\nimport binascii\nimport re\nimport pickle\nfrom requests_oauthlib import OAuth2Session\nimport json\nimport datetime\nimport subprocess\nimport unitememo\nimport markdown\nmydir = \"/home/tamura/work/onenote_api/kokuoh/\"\n\naccess_url=\"https://www.onenote.com/api/v1.0/me/notes/\"\ndef res_cmd_lfeed(cmd):\n return subprocess.Popen(\n cmd, stdout=subprocess.PIPE,shell=True).stdout.readlines()\ndef res_no_lfeed(cmd):\n return [str(x).rstrip(\"\\n\") for x in res_cmd_lfeed(cmd)]\n\ndef token_saver(token):\n with open(mydir+\"token.pickle\", mode = \"wb\") as f:\n pickle.dump(token,f)\n\ndef get_session(fkeys, ftoken):\n with open(fkeys, \"r\") as f:\n for line in f:\n if line.startswith(\"client_id\"):\n client_id = line[:-1].split(\"=\")[1]\n elif line.startswith(\"client_secret\"):\n client_secret = line[:-1].split(\"=\")[1]\n\n authorization_base_url = 'https://login.live.com/oauth20_authorize.srf'\n token_url = 'https://login.live.com/oauth20_token.srf'\n refresh_url = \"https://login.microsoftonline.com/common/oauth2/v2.0/token\"\n scope = [\"office.onenote_update\",\"wl.signin\",\"wl.offline_access\"]\n redirect_uri = 'https://localhost:8080/' \n\n with open(ftoken, mode = \"rb\") as f:\n token = pickle.load(f)\n\n extra = {\n \"client_id\": client_id,\n \"client_secret\": client_secret,\n }\n return OAuth2Session(client_id, token=token, auto_refresh_url=refresh_url, auto_refresh_kwargs=extra, token_updater= token_saver)\n\ndef post(onenote,sectionid,content):\n post_url = access_url + \"sections/%s/pages\" % sectionid\n headers = {u\"Content-Type\":u\"text/html\"}\n return onenote.request('POST',post_url,data = content, headers = headers)\n\ndef str2html(title,body):\n md = markdown.Markdown()\n str = \"\"\"\n\n \n %s\n \n \n %s\n \n\n\"\"\" % (title,md.convert(body))\n return str\n\ndef memopost_new(y,m,d):\n onenote = get_session(mydir + \"keys.txt\", mydir + \"token.pickle\")\n with open(mydir + \"id.dat\",\"r\") as f:\n for line in f:\n sectionid = line[:-1]\n str = unitememo.unite_memo(y,m,d)\n content = str2html(\"%d/%d kokuoh\" % (m,d),str).encode(\"utf-8\")\n req = post(onenote,sectionid,content)\n dreq = json.loads(req.content)\n with open(mydir + \"pageid_list.dat\",\"a\") as f:\n f.write(\"%d/%d/%d %s\\n\" % (y,m,d,dreq[\"id\"]))\n return req\n\ndef memopost_update(y,m,d,pageid):\n md = markdown.Markdown()\n onenote = get_session(mydir + \"keys.txt\", mydir + \"token.pickle\")\n str = unitememo.unite_memo(y,m,d)\n content = md.convert(str)\n headers = {u\"Content-Type\":u\"application/json\"}\n access_url=\"https://www.onenote.com/api/v1.0/me/notes/pages/%s\" % pageid\n data = json.dumps([{\"target\":\"body\",\"action\":\"replace\",\"content\":content}]) \n req = onenote.patch(access_url,data = data,headers = headers)\n return req\n\ndef memopost(y,m,d):\n isExist = False\n with open(mydir + \"pageid_list.dat\", \"r\") as f:\n for line in f:\n if \"%d/%d/%d\" % (y,m,d) in line.split(\" \")[0]:\n isExist = True\n pageid = line[:-1].split(\" \")[1]\n if isExist:\n return memopost_update(y,m,d,pageid)\n else:\n return memopost_new(y,m,d)\n \ndef main():\n y = int(sys.argv[1])\n m = int(sys.argv[2])\n d = int(sys.argv[3])\nif __name__ == \"__main__\":\n main()\n","sub_path":"kokuoh/memopost.py","file_name":"memopost.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139390366","text":"from decimal import *\n\nfrom django.template import Library\n\nregister = Library()\n\n\ndef int_or_float(arg):\n if isinstance(arg, int) or isinstance(arg, float) or isinstance(arg, Decimal):\n return arg\n try:\n return int(arg)\n except ValueError:\n return float(arg)\n\n\n@register.filter\ndef sub(value, arg):\n \"\"\"Subtracts the arg from the value.\"\"\"\n try:\n return int_or_float(value) - int_or_float(arg)\n except (ValueError, TypeError):\n try:\n return value - arg\n except Exception:\n return ''\nsub.is_safe = False\n\n\n@register.filter\ndef mul(value, arg):\n \"\"\"Multiplies the arg with the value.\"\"\"\n try:\n return int_or_float(value) * int_or_float(arg)\n except (ValueError, TypeError):\n try:\n return value * arg\n except Exception:\n return ''\nmul.is_safe = False\n\n\n@register.filter()\ndef div(value, arg):\n \"\"\"Divides the arg by the value.\"\"\"\n try:\n return int_or_float(value) / int_or_float(arg)\n except (ValueError, TypeError):\n try:\n return value / arg\n except Exception:\n return ''\ndiv.is_safe = False\n\n\n@register.filter(name='abs')\ndef absolute(value):\n \"\"\"Returns the absolute value.\"\"\"\n try:\n return abs(int_or_float(value))\n except (ValueError, TypeError):\n try:\n return abs(value)\n except Exception:\n return ''\nabsolute.is_safe = False\n","sub_path":"mathfilters/templatetags/mathfilters.py","file_name":"mathfilters.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"165864475","text":"from .entity_error import EntityErrors\n\n\nclass ApiError(EntityErrors):\n\n def get_errors_to_str(self):\n err_lst = []\n for er in self.get_errors(): # EntityErrors.get_errors\n # print ('er.error_desc = {}'.format(er.error_desc))\n err_lst.append({'error_desc': er.error_desc, 'error_number': er.error_number})\n\n error = {\n 'api_process_name': str(self.entity.api_process_name),\n 'errors': err_lst\n }\n return error\n","sub_path":"file_load/file_error/api_error.py","file_name":"api_error.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"3965849","text":"\n\nfrom xai.brain.wordbase.verbs._avow import _AVOW\n\n#calss header\nclass _AVOWING(_AVOW, ):\n\tdef __init__(self,): \n\t\t_AVOW.__init__(self)\n\t\tself.name = \"AVOWING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"avow\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_avowing.py","file_name":"_avowing.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"86402020","text":"# The number 197 is called a circular prime because all rotations of the digits:\n# 197, 971, and 719, are themselves prime.\n#\n# There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,\n# 73, 79, and 97.\n#\n# How many circular primes are there below one million?\nimport lib.euler as euler\n\nRESULT = 55\n\ndef p35(limit=1000000):\n primes = list(euler.readSmallerPrimes('data/primes.txt', limit))\n counter = 0\n\n for p in primes:\n if euler.checkAllRotations(p, primes):\n counter += 1\n\n return counter\n","sub_path":"project-euler/001-050/p35.py","file_name":"p35.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"176998327","text":"import pygame\nfrom pygame import *\nfrom systemState import systemState\nfrom systemState import gameObject\n\nclass gameOverState(gameObject):\n\n\n def __init__(self, joystickList, screenSize, systemState):\n self.font1 = pygame.font.SysFont(\"arial\", 50)\n self.font2 = pygame.font.SysFont(\"arial\", 30)\n self.joystickList = joystickList\n self.screenSize = screenSize\n self.systemState = systemState\n\n def update(self, elapsedTime):\n \n if len(self.joystickList) == 2:\n retryButton = self.joystickList[1].get_button(7) or self.joystickList[0].get_button(7)\n goBackButton = self.joystickList[1].get_button(3) or self.joystickList[0].get_button(3)\n else:\n retryButton = self.joystickList[0].get_button(7)\n goBackButton = self.joystickList[0].get_button(3)\n\n if retryButton:\n self.systemState.changeState(\"playState\")\n elif goBackButton:\n self.systemState.changeState(\"gameWorldState\")\n\n def render(self):\n screen = pygame.display.get_surface()\n screen.fill((0, 0, 0))\n\n textSurf = self.font1.render(\"GAME OVER\" , True,(255, 0, 0))\n screen.blit(textSurf, (self.screenSize[0] / 2 - 200, 200))\n \n textSurf2 = self.font2.render(\"press space to retry\" , True,(255, 0, 0))\n screen.blit(textSurf2, (self.screenSize[0] / 2 - 100, 400))\n\n textSurf2 = self.font2.render(\"press tab to retrun to title screen\" , True,(255, 0, 0))\n screen.blit(textSurf2, (self.screenSize[0] / 2 - 100, 500))\n","sub_path":"backup/gameOverState.py","file_name":"gameOverState.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"437771311","text":"import re\nimport spacy\nimport nltk\nfrom collections import Counter\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\ndef load(path):\n ret = []\n with open(path, \"r\") as f:\n data = f.readlines()\n for line in data:\n line = line.strip().split(\"\\t\")\n ret.append(line)\n return ret\n\ndef save(x, y, path):\n tmp = \"\\n\".join([str(label)+\",\"+\",\".join(list(map(str, sent))) for sent, label in zip(x, y)])\n with open(path, \"w\") as f:\n f.write(tmp)\n\nnlp = spacy.load('en')\nstemmer = nltk.stem.snowball.SnowballStemmer(language='english')\n\ndef tokenize(x):\n x = re.sub(r'\\s+', ' ', x)\n x = nlp.make_doc(x)\n x = [stemmer.stem(doc.lemma_.lower()) for doc in x]\n return x\n\ntrain, valid, test = load(\"./data/train.txt\"), load(\"./data/valid.txt\"), load(\"./data/test.txt\")\nttrain, tvalid, ttest = [[cat, tokenize(line)] for cat, line in train], [[cat, tokenize(line)] for cat, line in valid], [[cat, tokenize(line)] for cat, line in test]\n\ncounter = Counter([token for _, tokens in ttrain for token in tokens])\nvocab = [token for token, freq in counter.most_common() if 2 < freq < 300]\nword2id = {w:i for i, w in enumerate(vocab)}\n\nwith open(\"./data/vocab.txt\", \"w\") as f:\n f.write(\"\\n\".join(vocab))\n\ndef unigram_bow(sent):\n l = [0 for _ in range(len(vocab))]\n for w in sent:\n if w in vocab:\n l[word2id[w]] += 1\n return l\n\ncategories = ['b', 't', 'e', 'm']\n\ntfidf = TfidfTransformer(smooth_idf=False)\n\ntrain_X, train_y = [unigram_bow(s) for _, s in ttrain], [categories.index(label) for label, _ in ttrain]\nvalid_X, valid_y = [unigram_bow(s) for _, s in tvalid], [categories.index(label) for label, _ in tvalid]\ntest_X, test_y = [unigram_bow(s) for _, s in ttest], [categories.index(label) for label, _ in ttest]\n\nmodel = tfidf.fit(train_X)\ntrain_X, valid_X, test_X = model.transform(train_X).toarray(), model.transform(valid_X).toarray(), model.transform(test_X).toarray()\n\nsave(train_X, train_y, \"./data/train.feature.txt\")\nsave(valid_X, valid_y, \"./data/valid.feature.txt\")\nsave(test_X, test_y, \"./data/test.feature.txt\")\n\n","sub_path":"seiichi/chapter06/51.py","file_name":"51.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134768467","text":"def someFxn(num):\n return num * 5\n\ndef commonality(s):\n hashRight = {}\n commonality = 0\n hashC = {}\n for char in s:\n if char not in hashRight:\n hashRight[char] = 1\n else:\n hashRight[char] += 1\n for char in s:\n if char not in hashC:\n hashC[char] = 0\n hashLeft = {}\n for c in s:\n if c not in hashLeft:\n hashLeft[c] = 1\n else:\n hashLeft[c] += 1\n hashRight[c] -= 1\n if hashRight[c] < 0:\n hashRight[c] = 0\n commonality += min(hashRight[c], hashLeft[c])\n return commonality\n\nif __name__ == \"__main__\":\n print(someFxn(10))\n print(commonality('bbbbaaa'))\n print(commonality('abcdedeara'))\n print(commonality('safaabafsaafs'))","sub_path":"template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"450016168","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBetagro spider created on the top of ATSSpider\n\nscrapy crawl betagro -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.betagro.com/recruitment/index.php\"\n\nSample URL:\n http://www.betagro.com/recruitment/index.php\n\"\"\"\n\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, HtmlFormatter, NormalizedJoin, Prefix, ShrinkURL\nfrom brightcorp.lib.utils import extract_first\n\npattern = {\n 'page': compile(r'joblistPage=(\\d+)'),\n 'page_num': compile(r'(\\d+)$'),\n 'ref_id': compile(r'job_id=(\\d+)'),\n}\n\n\nclass betagro(ATSSpider):\n\n name = 'betagro'\n\n def parse(self, response):\n sel = Selector(response)\n for anchor in sel.xpath(\n '//table/td/a[contains(@id, \"Componentsarea_name_th\")]'\n ):\n href = anchor.xpath('./@href').extract()\n location_name = extract_first(anchor.xpath('./text()'))\n yield Request(\n callback=self.parse_jobs_list,\n meta={\n 'location': location_name,\n 'page': '1'\n },\n url=urljoin(response.url, href[0])\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n for tr in sel.xpath(\n '//table[@class=\"Grid\"]/tr'\n ):\n href = tr.xpath(\n './td/a[contains(@id, \"Contentjoblistjob_title\")]/@href'\n ).extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': tr.xpath(\n './td/a[contains(@id, \"Contentjoblistjob_title\")]/text()'\n ).extract(),\n 'date': tr.xpath(\n './td[1]/text()'\n ).extract(),\n 'location': response.meta.get('location')\n },\n url=urljoin(response.url, href[0])\n )\n\n # pagination\n last_page = sel.xpath(\n '//tr[@class=\"Footer\"]/td/span/a[last()]/@href'\n ).extract()\n if last_page:\n page = int(response.meta.get('page', 0)) + 1\n match = pattern['page'].search(last_page[0])\n if match and page <= int(match.group(1)):\n path = sub(pattern['page_num'], str(page), last_page[0])\n yield Request(\n callback=self.parse_jobs_list,\n meta={\n 'location': response.meta.get('location'),\n 'page': str(page),\n },\n url=urljoin(response.url, path)\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n workplace = extract_first(sel.xpath(\n '//tr/td[font/strong[contains(text(), \"%s\")]]/following-sibling::td[1]//text()' % unicode('สถานที่ปฏิบัติงาน :', 'utf-8')\n ))\n\n loader = BrightcorpItemLoader(selector=sel)\n loader.add_value(\n 'title', response.meta.get('title')\n )\n loader.add_value(\n 'location',\n [\n workplace, response.meta.get('location')\n ],\n NormalizedJoin(', ')\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=pattern['ref_id']\n )\n loader.add_value(\n 'date',\n response.meta.get('date'),\n ConvertDateString('%d/%m/%Y')\n )\n loader.add_value(\n 'url', response.url, ShrinkURL(['joblistPage'])\n )\n loader.add_xpath(\n 'description',\n [\n '//tr[td/font/strong[contains(text(), \"%s\")]]' % unicode('คุณสมบัติ :', 'utf-8'),\n '//tr[td/font/strong[contains(text(), \"%s\")]]' % unicode('หน้าที่และรายละเอียดของงาน', 'utf-8'),\n ],\n HtmlFormatter()\n )\n loader.add_xpath(\n 'jobcategory',\n '//tr/td[font/strong[contains(text(), \"Job Function\")]]/following-sibling::td[1]//text()'\n )\n loader.add_xpath(\n 'qualifications',\n '//tr/td[font/strong[contains(text(), \"Education Level\")]]/following-sibling::td[1]//text()'\n )\n loader.add_value(\n 'apply_url', response.url, ShrinkURL(['joblistPage'])\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/betagro.py","file_name":"betagro.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"356125231","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\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.\n\n\nimport json\nimport logging\nimport mox\nimport sys\n\nimport eventlet\nimport nose\nimport unittest\nfrom nose.plugins.attrib import attr\n\nimport heat.db as db_api\nfrom heat.engine import parser\nfrom heat.engine.resources import wait_condition as wc\nfrom heat.common import context\n\nlogger = logging.getLogger('test_waitcondition')\n\ntest_template_waitcondition = '''\n{\n \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n \"Description\" : \"Just a WaitCondition.\",\n \"Parameters\" : {},\n \"Resources\" : {\n \"WaitHandle\" : {\n \"Type\" : \"AWS::CloudFormation::WaitConditionHandle\"\n },\n \"WaitForTheHandle\" : {\n \"Type\" : \"AWS::CloudFormation::WaitCondition\",\n \"Properties\" : {\n \"Handle\" : {\"Ref\" : \"WaitHandle\"},\n \"Timeout\" : \"5\"\n }\n }\n }\n}\n'''\n\n\n@attr(tag=['unit', 'resource'])\n@attr(speed='slow')\nclass stacksTest(unittest.TestCase):\n def setUp(self):\n self.m = mox.Mox()\n self.m.StubOutWithMock(wc.WaitCondition,\n '_get_status_reason')\n self.m.StubOutWithMock(wc.WaitCondition,\n '_create_timeout')\n self.m.StubOutWithMock(eventlet, 'sleep')\n\n def tearDown(self):\n self.m.UnsetStubs()\n\n def create_stack(self, stack_name, temp, params):\n template = parser.Template(temp)\n parameters = parser.Parameters(stack_name, template, params)\n stack = parser.Stack(context.get_admin_context(), stack_name,\n template, parameters)\n\n stack.store()\n return stack\n\n def test_post_success_to_handle(self):\n\n t = json.loads(test_template_waitcondition)\n stack = self.create_stack('test_stack', t, {})\n\n wc.WaitCondition._create_timeout().AndReturn(eventlet.Timeout(5))\n wc.WaitCondition._get_status_reason(\n mox.IgnoreArg()).AndReturn(('WAITING', ''))\n eventlet.sleep(1).AndReturn(None)\n wc.WaitCondition._get_status_reason(\n mox.IgnoreArg()).AndReturn(('WAITING', ''))\n eventlet.sleep(1).AndReturn(None)\n wc.WaitCondition._get_status_reason(\n mox.IgnoreArg()).AndReturn(('SUCCESS', 'woot toot'))\n\n self.m.ReplayAll()\n\n stack.create()\n\n resource = stack.resources['WaitForTheHandle']\n self.assertEqual(resource.state,\n 'CREATE_COMPLETE')\n\n r = db_api.resource_get_by_name_and_stack(None, 'WaitHandle',\n stack.id)\n self.assertEqual(r.name, 'WaitHandle')\n\n self.m.VerifyAll()\n\n def test_timeout(self):\n\n t = json.loads(test_template_waitcondition)\n stack = self.create_stack('test_stack', t, {})\n\n tmo = eventlet.Timeout(6)\n wc.WaitCondition._create_timeout().AndReturn(tmo)\n wc.WaitCondition._get_status_reason(\n mox.IgnoreArg()).AndReturn(('WAITING', ''))\n eventlet.sleep(1).AndReturn(None)\n wc.WaitCondition._get_status_reason(\n mox.IgnoreArg()).AndReturn(('WAITING', ''))\n eventlet.sleep(1).AndRaise(tmo)\n\n self.m.ReplayAll()\n\n stack.create()\n\n resource = stack.resources['WaitForTheHandle']\n\n self.assertEqual(resource.state,\n 'CREATE_FAILED')\n self.assertEqual(wc.WaitCondition.UPDATE_REPLACE,\n resource.handle_update())\n\n stack.delete()\n\n self.m.VerifyAll()\n\n # allows testing of the test directly\n if __name__ == '__main__':\n sys.argv.append(__file__)\n nose.main()\n","sub_path":"heat/tests/test_waitcondition.py","file_name":"test_waitcondition.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366224373","text":"# coding:utf-8\n\n# 关键字参数\ndef add(a, b=10):\n result = a + b\n print(result)\n\n\nadd(2)\n\n\ndef add1(a, b=10, c=2):\n print(a,b,c)\n result = a + b + c\n print(result)\n\n\n# 知识点1:覆盖已存在参数\nadd1(2, 3) # 给b赋值成功,被覆盖\nadd1(2, c=3) # 知识点2: 通过关键字参数赋值给指定参数\n\n\n# 打印每位同学的名字和年龄\nstudents = {'001':('孔小宝',24),'002':('孔大宝',25),'003':('孔大宝宝',26),'004':('易烊千玺',27)}\n\n\ndef print_boy(students):\n if isinstance(students,dict):\n values = students.values()\n for name, age in values:\n print(\"{}的年龄是{}.\".format(name,age))\n\n\nprint_boy(students)","sub_path":"千峰py/func04.py","file_name":"func04.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"503815819","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 2 10:33:52 2021\r\n\r\n@author: Asus\r\n\"\"\"\r\n\r\nimport pandas as pd\r\ndf = pd.read_csv('Salaries.csv')\r\n\r\ntype(df)\r\ndf.shape\r\n\r\ndf.head()\r\n\r\ndf.tail(2)\r\n\r\ndf.sample(3)\r\n\r\ndf['rank']\r\n\r\ndf['salary']\r\n\r\ndf['rank']\r\n\r\ndf[['rank','salary']]\r\n\r\ndf['rank'].unique()\r\n\r\ndf['rank'].value_counts(normalize = True)\r\n\r\n\r\ndf['sex'].unique()\r\n\r\ndf['salary'].max()\r\ndf['salary'].min()\r\ndf['salary'].mean()\r\n\r\ndf['salary']\r\ndf.salary\r\n\r\ndf['rank']\r\ndf.rank\r\n\r\n\r\nfilter1 = df['salary'] > 100000\r\ndf[filter1]\r\n\r\n\r\ndf[df['salary'] > 100000]\r\n\r\n\r\n\r\ndf[(df['salary'] > 100000) & (df['sex'] == 'Female')]\r\n\r\n\r\ndf.isnull().any(axis = 0)\r\n\r\ndf.isnull().any(axis = 1)\r\n\r\ndf[df.isnull().any(axis = 1)]\r\n\r\n\r\ndf['phd'].mean()\r\n\r\ndf['phd'] = df['phd'].fillna(df['phd'].mean())\r\n\r\ndf2 = df.fillna(100)\r\n\r\ndf.dropna(inplace = True)\r\n\r\ndf = pd.read_csv('Salaries.csv')\r\n\r\n\r\ndf.iloc[0:10,2:4]\r\n\r\ndf.iloc[10,:]\r\n\r\ndf.iloc[[10,15],:]\r\n\r\ndf.iloc[:,2]\r\n\r\n\r\n\r\n\r\n","sub_path":"day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"481233445","text":"\"\"\"\nDraw graph in HTML for a specific metric.\n\nTODO: Add multiple lines for multiple files\n\"\"\"\nimport pathlib\n\nimport plotly.graph_objs as go\nimport plotly.offline\n\nfrom wily import logger, format_datetime\nfrom wily.operators import resolve_metric, resolve_metric_as_tuple\nfrom wily.state import State\n\n\ndef metric_parts(metric):\n \"\"\"Convert a metric name into the operator and metric names.\"\"\"\n operator, met = resolve_metric_as_tuple(metric)\n return operator.name, met.name\n\n\ndef graph(config, path, metrics, output=None, x_axis=None, changes=True, text=False):\n \"\"\"\n Graph information about the cache and runtime.\n\n :param config: The configuration.\n :type config: :class:`wily.config.WilyConfig`\n\n :param path: The path to the files.\n :type path: ``list``\n\n :param metrics: The Y and Z-axis metrics to report on.\n :type metrics: ``tuple``\n\n :param output: Save report to specified path instead of opening browser.\n :type output: ``str``\n \"\"\"\n logger.debug(\"Running report command\")\n\n data = []\n state = State(config)\n abs_path = config.path / pathlib.Path(path)\n\n if x_axis is None:\n x_axis = \"history\"\n else:\n x_operator, x_key = metric_parts(x_axis)\n\n if abs_path.is_dir():\n paths = [\n p.relative_to(config.path) for p in pathlib.Path(abs_path).glob(\"**/*.py\")\n ]\n else:\n paths = [path]\n\n operator, key = metric_parts(metrics[0])\n if len(metrics) == 1: # only y-axis\n z_axis = None\n else:\n z_axis = resolve_metric(metrics[1])\n z_operator, z_key = metric_parts(metrics[1])\n for path in paths:\n x = []\n y = []\n z = []\n labels = []\n last_y = None\n for rev in state.index[state.default_archiver].revisions:\n labels.append(f\"{rev.revision.author_name}
{rev.revision.message}\")\n try:\n val = rev.get(config, state.default_archiver, operator, str(path), key)\n if val != last_y or not changes:\n y.append(val)\n if z_axis:\n z.append(\n rev.get(\n config,\n state.default_archiver,\n z_operator,\n str(path),\n z_key,\n )\n )\n if x_axis == \"history\":\n x.append(format_datetime(rev.revision.date))\n else:\n x.append(\n rev.get(\n config,\n state.default_archiver,\n x_operator,\n str(path),\n x_key,\n )\n )\n last_y = val\n except KeyError:\n # missing data\n pass\n\n # Create traces\n trace = go.Scatter(\n x=x,\n y=y,\n mode=\"lines+markers+text\" if text else \"lines+markers\",\n name=f\"{path}\",\n ids=state.index[state.default_archiver].revision_keys,\n text=labels,\n marker=dict(\n size=0 if z_axis is None else z,\n color=list(range(len(y))),\n # colorscale='Viridis',\n ),\n xcalendar=\"gregorian\",\n hoveron=\"points+fills\",\n )\n data.append(trace)\n if output:\n filename = output\n auto_open = False\n else:\n filename = \"wily-report.html\"\n auto_open = True\n y_metric = resolve_metric(metrics[0])\n title = f\"{x_axis.capitalize()} of {y_metric.description} for {path}\"\n plotly.offline.plot(\n {\n \"data\": data,\n \"layout\": go.Layout(\n title=title,\n xaxis={\"title\": x_axis},\n yaxis={\"title\": y_metric.description},\n ),\n },\n auto_open=auto_open,\n filename=filename,\n )\n","sub_path":"src/wily/commands/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"298496772","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n\n\nclass sendemail:\n\n def send(self, title, fromWhere, toWhere, content):\n msg = MIMEText(content, 'plain', 'utf-8')\n msg['Subject'] = Header(title, 'utf-8').encode()\n msg['From'] = Header(fromWhere, 'utf-8').encode()\n msg['To'] = Header(toWhere).encode()\n try:\n smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)\n smtp.login(r'962139864@qq.com', r'')\n smtp.sendmail('962139864@qq.com', ['962139864@qq.com', ], msg.as_string())\n except smtplib.SMTPException:\n print(\"失败\")\n raise\n # smtplib.SMTPException.\n finally:\n smtp.quit()\n\n\nif __name__ == \"__main__\":\n sendemail().send(\"aaa\",\"aa\",'aa','aaaaa')\n print('---------------------')","sub_path":"com/util/sendemailutil.py","file_name":"sendemailutil.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"5003519","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nimport time\n\n#%% power consumption\nclass tia_power_consumption:\n def __init__(self):\n self.Id_1 = 0\n self.Id_2 = 0\n self.Id_3 = 0\n self.R = 10000\n self.I_ref = 0\n self.power1 = 0\n self.power2 = 0\n self.power3 = 0\n self.power4 = 0\n \n def set_R(self, R):\n self.R = R\n \n def set_I_ref(self, I_ref):\n self.I_ref\n \n def set_Ids(self, Id_1, Id_2, Id_3):\n self.Id_1 = Id_1\n self.Id_2 = Id_2\n self.Id_3 = Id_3\n self.upd_power()\n \n def set_params(self, ratio_1_to_3, fraction_2 ):\n self.Id_1 = ( ratio_1_to_3 / (1 + ratio_1_to_3) )*(150E-6*(1-fraction_2))\n self.Id_2 = 150E-6*fraction_2\n self.Id_3 = ( 1 / (1 + ratio_1_to_3) )*(150E-6*(1-fraction_2))\n self.upd_power()\n \n def upd_power(self):\n self.power1 = 2*5*(self.Id_1 + self.Id_2 + self.Id_3) + 5*self.I_ref + 50/(4*self.R)\n self.power2 = 2*5*(self.Id_1 + self.Id_2 + self.Id_3) \n self.power3 = 5*self.I_ref\n self.power4 = 50/(4*self.R)\n \n def get_power(self):\n return [self.power1, self.power2, self.power3, self.power4]\n \n def print_power(self, n):\n if n >= 0:\n print('total power consumption: %3.3f mw' %(self.power1/1000) )\n if n == 1:\n print('power consumption Ids: %3.3f mw' %(self.power2/1000) )\n print('power consumption I_ref: %3.3f mw' %(self.power3/1000) )\n print('power consumption R: %3.3f mw' %(self.power4/1000) )\n\ndef unit_test_tia_power_consumption(test_type):\n if test_type >= 0:\n tia_power_module_test = tia_power_consumption()\n tia_power_module_test.set_params(1.2, 5E-5)\n tia_power_module_test.print_power(1)\n \n\n#unit_test_tia_power_consumption(1)\n\n#%% MOSFET\n\nclass mosfet:\n \n unCox = 50E-6\n upCox = 25E-6\n lambd = 0.1\n # lookup table for l=1um nmos\n wl_1u = [2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000]\n cdtot_1u = [5.60, 9.50, 16.0, 29.0, 68.0, 134, 263, 653, 1303, 2603]\n cgtot_1u = [3.45, 8.60, 17.2, 34.5, 86.3, 173, 345, 863, 1727, 3453]\n cstot_1u = [5.62, 9.50, 16.1, 29.2, 68.5, 133, 265, 658, 1313, 2623]\n cbtot_1u = [10.6, 17.6, 29.2, 52.3, 122, 238, 469, 1164, 2322, 4640]\n cgs_1u = [1.02, 2.55, 5.10, 10.2, 25.5, 50, 102, 255, 510, 1020]\n cgd_1u = [1.00, 2.50, 5.00, 10.0, 25.0, 51, 100, 250, 500, 1000]\n cdtot_lookup_1u = interpolate.interp1d(wl_1u, cdtot_1u)\n cgtot_lookup_1u = interpolate.interp1d(wl_1u, cgtot_1u)\n cstot_lookup_1u = interpolate.interp1d(wl_1u, cstot_1u)\n cbtot_lookup_1u = interpolate.interp1d(wl_1u, cbtot_1u)\n cgs_lookup_1u = interpolate.interp1d(wl_1u, cgs_1u )\n cgd_lookup_1u = interpolate.interp1d(wl_1u, cgd_1u )\n \n # lookup table for l=2um\n w_2u = [2, 5, 10, 20, 50, 100, 200, 500]\n wl_2u = [1, 2.5, 5, 10, 25, 50, 100, 250]\n cdtot_2u = [5.60, 9.50, 16.0, 29.0, 68.0, 133, 263, 653]\n cgtot_2u = [4.91, 12.3, 24.5, 49.1, 123, 245, 490, 1227]\n cstot_2u = [5.64, 9.60, 16.2, 29.4, 68.9, 135, 267, 663]\n cbtot_2u = [12.1, 21.2, 36.3, 66.7, 158, 310, 613, 1523]\n cgs_2u = [1.04, 2.60, 5.20, 10.4, 26, 52, 103, 260]\n cgd_2u = [1.00, 2.50, 5.00, 10.0, 25.0, 50, 100, 250]\n cdtot_lookup_2u = interpolate.interp1d(wl_2u, cdtot_2u)\n cgtot_lookup_2u = interpolate.interp1d(wl_2u, cgtot_2u)\n cstot_lookup_2u = interpolate.interp1d(wl_2u, cstot_2u)\n cbtot_lookup_2u = interpolate.interp1d(wl_2u, cbtot_2u)\n cgs_lookup_2u = interpolate.interp1d(wl_2u, cgs_2u )\n cgd_lookup_2u = interpolate.interp1d(wl_2u, cgd_2u )\n \n R_LDM = 10000 # ohms\n C_LDM = 500 # fF\n C_in = 100 # fF\n \n def __init__(self, mosfet_type, debug): # 0=nmos l=1, 1=nmos l=2, 2=pmos l=1, 3=pmos l=2\n # set variables\n self.Vov = 0.2\n self.Id = 1E-5\n self.type= mosfet_type\n self.debug = debug\n self.type_dict = {0:'nmos l=1u', 1:'nmos l=2u', 2:'pmos l=1u', 3:'pmos l=2u',}\n # derived variables\n self.WL = -1 \n self.L = -1 # um\n self.W = -1 # um\n self.gm = -1 # A/V\n self.gmp = -1 # gm + gmb = 1.2*gm\n self.ro = -1\n self.cgs = -1\n self.cgd = -1\n self.cgb = -1\n self.csb = -1\n self.cdb = -1\n \n def print_basic(self):\n print(f'type: {self.type_dict[self.type]}')\n print('input variables: \\n Vov= %2.2fV, \\n Id =%3.0fuA' %(self.Vov, 1E+6*self.Id) )\n print('calc parameters: \\n WL = %2.2f, \\n W = %1.1fum, \\n L = %1.0fum, \\n gm = %1.2fmA/V' \n %(self.WL, self.W, self.L, 1000*self.gm) )\n \n def print_caps(self):\n print('cgs: %3.1f fF' %self.cgs)\n print('cgd: %3.1f fF' %self.cgd)\n print('cgb: %3.1f fF' %self.cgb)\n print('csb: %3.1f fF' %self.csb)\n print('cdb: %3.1f fF\\n' %self.cdb)\n \n def print_all(self):\n self.print_basic()\n self.print_caps()\n \n def set_WL(self, WL):\n self.WL = WL\n self.upd_caps()\n \n def upd_caps(self):\n if self.type == 0 or self.type == 2: \n self.cgs = self.cgs_lookup_1u(self.WL)\n self.cgd = self.cgd_lookup_1u(self.WL)\n self.cgb = self.cgtot_lookup_1u(self.WL) - self.cgs - self.cgd\n self.csb = self.cstot_lookup_1u(self.WL) - self.cgs\n self.cdb = self.cdtot_lookup_1u(self.WL) - self.cgd\n if self.type == 1 or self.type == 3: \n self.cgs = self.cgs_lookup_2u(self.WL)\n self.cgd = self.cgd_lookup_2u(self.WL)\n self.cgb = self.cgtot_lookup_2u(self.WL) - self.cgs - self.cgd\n self.csb = self.cstot_lookup_2u(self.WL) - self.cgs\n self.cdb = self.cdtot_lookup_2u(self.WL) - self.cgd\n \n def set_params(self, Vov, Id):\n self.Vov = Vov\n self.Id = Id\n # WL = 2*Id / unCox*Vov^2\n if self.type == 0 or self.type == 2:\n self.WL = 2*self.Id / ( self.unCox*self.Vov**2 )\n self.W = self.WL*(self.type+1)\n if self.type == 1 or self.type == 3:\n self.WL = 2*self.Id / ( self.upCox*self.Vov**2 )\n self.W = self.WL*(self.type-1)\n # check WL limits\n if self.WL <= 2 or self.WL > 2000:\n print(f'out of range: \\n Vov = {self.Vov} \\n Id = {self.Id} \\n WL={self.WL}')\n # gm = 2*Id/Vov\n self.gm = 2*self.Id/self.Vov\n self.gmp= 1.2*self.gm\n self.ro = 2/(self.lambd*self.Id)\n self.upd_caps()\n if self.debug:\n self.print_all()\n \n def get_gm(self):\n return self.gm\n \n def get_params(self):\n return [self.Vov, self.Id, self.WL, self.W, self.gm, self.ro]\n \n def get_caps(self):\n return [self.cgs, self.cgd, self.cgb, self.csb, self.cdb]\n \n def sweep_caps(self):\n WL_sweep_1u = [2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000]\n WL_sweep_2u = [1, 2.5, 5, 10, 25, 50, 100, 250]\n for self.type in range(4):\n if self.type == 0 or self.type == 2:\n sweep = np.zeros((10, 6))\n sweep[:,0] = WL_sweep_1u\n if self.type == 1 or self.type ==3:\n sweep = np.zeros((8,6))\n sweep[:,0] = WL_sweep_2u\n \n if self.debug: print(f'sweep: \\n{sweep}')\n for i in range(sweep[:,0].shape[0]): # iterate rows\n self.set_WL(sweep[i,0])\n sweep[i,0] = sweep[i,0]\n sweep[i, 1:6] = self.get_caps()\n \n \n \n fig = plt.figure(self.type+1)\n fig.clf()\n fig.suptitle(self.type_dict[self.type])\n ax = fig.subplots(1,1)\n ax.set_xlim([0,100])\n ax.set_ylim([0,100])\n ax.set_xlabel('W/L')\n ax.set_ylabel('C [fF]')\n \n names_list = ['cgs', 'cgd', 'cgb', 'csb', 'cdb']\n trend_list = []\n trend_max = 100\n for i in range(5):\n trend_list.append( np.polyfit(sweep[:,0], sweep[:,i+1], 1) )\n ax.plot(sweep[:,0], sweep[:,i+1], label='%s=%3.2f %3.2f' %(names_list[i], trend_list[i][0], trend_list[i][1]))\n ax.plot([0, trend_max], [trend_list[i][1], trend_max*trend_list[i][0]+trend_list[i][1]], 'k--', linewidth=0.5)\n ax.legend()\n ax.grid()\n \n \ndef unit_test_mosfet(test_type):\n nmos_1 = mosfet(0, 0)\n nmos_1.print_all()\n \n#unit_test_mosfet(1)\n\n#%%\nclass ee:\n @staticmethod\n def parallel(R1, R2):\n return (R1*R2)/(R1+R2)\n \n @staticmethod\n def print_R(name, val):\n if val > 1E+19:\n print('%s = inf' %name)\n if val <= 1E+19 and val > 1000:\n print('%s = %2.3f kohms' %(name, val/1000))\n if val <= 1000:\n print('%s = %3.0f ohms' %(name, val))\n \n @staticmethod\n def print_C(name, val):\n if val > 1E+6:\n print('%s = %3.0f uF' %(name, val/1E+6))\n if val <= 1E+6:\n print('%s = %3.0f fF' %(name, val))\n \n @staticmethod\n def print_V(name, val):\n print('%s = %1.3f V' %(name, val))\n \n @staticmethod\n def print_I(name, val):\n if val < 1E-3:\n print('%s = %3.1f uA' %(name, val*1E+6))\n if val >= 1E-3:\n print('%s = %3.2f mA' %(name, val*1E+3))\n \n @staticmethod\n def print_A(name, units, val):\n if val > 1E+3:\n print('%s = %3.2f k%s' %(name, val/1E+3, units))\n if val <= 1E+3:\n print('%s = %3.2f %s' %(name, val, units))\n\n#%% CG\nclass CG(mosfet):\n \n def __init__(self):\n self.M1 = mosfet(0, 0)\n self.RL = -1\n self.TI = -1\n self.Rin = -1\n self.Cin = -1\n self.Rout = -1\n self.Cout = -1\n \n def _print(self):\n print('CG stage parameters:')\n ee.print_A(' TI', 'ohms', self.TI)\n ee.print_R(' Rin ', self.Rin)\n ee.print_R(' Rout', self.Rout)\n ee.print_C(' Cin ', self.Cin)\n ee.print_C(' Cout', self.Cout)\n \n def _set(self, Vov, Id, RL):\n self.RL = RL\n self.M1.set_params(Vov, Id)\n self.Rin = 1/self.M1.gmp\n self.Rout = ee.parallel(2*self.M1.ro, self.RL)\n self.Cin = self.M1.cgs + self.M1.csb\n self.Cout = self.M1.cgd + self.M1.cdb\n self.TI = self.Rout\n \n def get_Rin(self):\n return self.Rin\n def get_Rout(self):\n return self.Rout\n def get_Cin(self):\n return self.Cin\n def get_Cout(self):\n return self.Cout\n def get_TI(self):\n return self.TI\n \n \ndef unit_test_CG():\n print('--- CG unit test --------------')\n cg = CG()\n cg._set(0.2, 1E-4, 10000)\n cg._print()\n\n\nunit_test_CG()\n\n#%% CG_lookup. abstract CG stage to lookup3(Vov, Id, RL)\nclass CG_LK(CG):\n _Vov = np.linspace(0.15, 0.3, 5)\n _Id = np.linspace(1E-5, 1E-4, 5)\n _RL = np.linspace(1E+4, 4E+4, 5)\n# print(f'_Vov: {_Vov}')\n# print(f'_Id: {_Id}')\n# print(f'_RL: {_RL}')\n print()\n\n def __init__(self):\n super().__init__()\n self.n_Vov = self._Vov.shape[0]\n self.n_Id = self._Id.shape[0]\n self.n_RL= self._RL.shape[0]\n# print(f'n_Vov: {self.n_Vov}')\n# print(f'n_Id: {self.n_Id}')\n# print(f'n_RL: {self.n_RL}')\n \n self.Rin_data = np.zeros((self.n_Vov, self.n_Id, self.n_RL))\n self.Rout_data = np.zeros((self.n_Vov, self.n_Id, self.n_RL))\n self.Cin_data = np.zeros((self.n_Vov, self.n_Id, self.n_RL))\n self.Cout_data = np.zeros((self.n_Vov, self.n_Id, self.n_RL))\n self.TI_data = np.zeros((self.n_Vov, self.n_Id, self.n_RL))\n \n for i in range(self.n_Vov):\n for j in range(self.n_Id):\n for k in range(self.n_RL):\n# print(f'i: {i}, j: {j}, k: {k}')\n super()._set(self._Vov[i], self._Id[j], self._RL[k])\n self.Rin_data [i,j,k] = super().get_Rin()\n self.Rout_data[i,j,k] = super().get_Rout()\n self.Cin_data [i,j,k] = super().get_Cin()\n self.Cout_data[i,j,k] = super().get_Cout()\n self.TI_data [i,j,k] = super().get_TI()\n self.Rin_f = RegularGridInterpolator((self._Vov, self._Id, self._RL), self.Rin_data)\n self.Rout_f = RegularGridInterpolator((self._Vov, self._Id, self._RL), self.Rout_data)\n self.Cin_f = RegularGridInterpolator((self._Vov, self._Id, self._RL), self.Cin_data)\n self.Cout_f = RegularGridInterpolator((self._Vov, self._Id, self._RL), self.Cout_data)\n self.TI_f = RegularGridInterpolator((self._Vov, self._Id, self._RL), self.TI_data)\n \n def get_Rin(self, Vov, Id, RL):\n return self.Rin_f([Vov, Id, RL])\n def get_Rout(self, Vov, Id, RL):\n return self.Rout_f([Vov, Id, RL])\n def get_Cin(self, Vov, Id, RL):\n return self.Cin_f([Vov, Id, RL])\n def get_Cout(self, Vov, Id, RL):\n return self.Cout_f([Vov, Id, RL])\n def get_TI(self, Vov, Id, RL):\n return self.TI_f([Vov, Id, RL])\n\ndef CG_LK_unit_test(Vov, Id, RL):\n print('--- CG_LK_unit_test ----------------')\n cg = CG_LK()\n ee.print_A(' TI', 'ohms', cg.get_TI(Vov, Id, RL))\n ee.print_R(' Rin ', cg.get_Rin (Vov, Id, RL))\n ee.print_R(' Rout', cg.get_Rout(Vov, Id, RL))\n ee.print_C(' Cin ', cg.get_Cin (Vov, Id, RL))\n ee.print_C(' Cout', cg.get_Cout(Vov, Id, RL))\n print('------------------------------------\\n')\n \nCG_LK_unit_test(0.2, 1E-4, 10000)\n\n\n#%% CS\nclass CS(mosfet):\n \n def __init__(self):\n self.M2 = mosfet(0, 0)\n self.A1 = -1\n self.Rin = -1\n self.Cin = -1\n self.Rout = -1\n self.Cout = -1\n\n def _print(self):\n print('CS stage parameters:')\n ee.print_A(' |A| ', 'V/V', self.A1)\n ee.print_R(' Rin ', self.Rin)\n ee.print_R(' Rout', self.Rout)\n ee.print_C(' Cin ', self.Cin)\n ee.print_C(' Cout', self.Cout)\n \n def _set(self, Vov, Id, A1): # A = -gain\n self.A1 = A1\n self.M2.set_params(Vov, Id)\n \n self.Rin = 1E+21\n self.Rout = ee.parallel(2*self.M2.ro, 1/(self.A1*self.M2.gmp))\n self.Cin = self.M2.cgs + self.M2.cgb + (1+self.A1)*self.M2.cgd\n self.Cout = (1+1/self.A1)*self.M2.cgd + self.M2.cdb\n# self._print()\n \n def get_Rin(self):\n return self.Rin\n def get_Rout(self):\n return self.Rout\n def get_Cin(self):\n return self.Cin\n def get_Cout(self):\n return self.Cout\n def get_A1(self):\n return self.A1\n\ndef unit_test_CS():\n print('--- CS_unit_test --------------------')\n cs = CS()\n cs._set(0.2, 1E-4, 3)\n cs._print()\n print()\n\nunit_test_CS()\n\n\n#%%\nclass CS_LK(CS):\n _Vov = np.linspace(0.15, 0.3, 5)\n _Id = np.linspace(1E-5, 1E-4, 5)\n _A1 = np.linspace(1, 5, 5)\n# print(f'_Vov: {_Vov}')\n# print(f'_Id: {_Id}')\n# print(f'_gain:{_gain}')\n \n def __init__(self):\n super().__init__()\n self.n_Vov = self._Vov.shape[0]\n self.n_Id = self._Id.shape[0]\n self.n_A1= self._A1.shape[0]\n print(f'n_Vov: {self.n_Vov}')\n print(f'n_Id: {self.n_Id}')\n print(f'n_A1: {self.n_A1}')\n \n self.Rin_data = np.zeros((self.n_Vov, self.n_Id, self.n_A1))\n self.Rout_data = np.zeros((self.n_Vov, self.n_Id, self.n_A1))\n self.Cin_data = np.zeros((self.n_Vov, self.n_Id, self.n_A1))\n self.Cout_data = np.zeros((self.n_Vov, self.n_Id, self.n_A1))\n self.A1_data = np.zeros((self.n_Vov, self.n_Id, self.n_A1))\n \n for i in range(self.n_Vov):\n for j in range(self.n_Id):\n for k in range(self.n_A1):\n# print(f'i: {i}, j: {j}, k: {k}')\n super()._set(self._Vov[i], self._Id[j], self._A1[k])\n self.Rin_data [i,j,k] = super().get_Rin()\n self.Rout_data[i,j,k] = super().get_Rout()\n self.Cin_data [i,j,k] = super().get_Cin()\n self.Cout_data[i,j,k] = super().get_Cout()\n self.A1_data [i,j,k] = super().get_A1()\n self.Rin_f = RegularGridInterpolator((self._Vov, self._Id, self._A1), self.Rin_data)\n self.Rout_f = RegularGridInterpolator((self._Vov, self._Id, self._A1), self.Rout_data)\n self.Cin_f = RegularGridInterpolator((self._Vov, self._Id, self._A1), self.Cin_data)\n self.Cout_f = RegularGridInterpolator((self._Vov, self._Id, self._A1), self.Cout_data)\n self.A1_f = RegularGridInterpolator((self._Vov, self._Id, self._A1), self.A1_data)\n \n def get_Rin(self, Vov, Id, A1):\n return self.Rin_f ([Vov, Id, A1])\n def get_Rout(self, Vov, Id, A1):\n return self.Rout_f([Vov, Id, A1])\n def get_Cin(self, Vov, Id, A1):\n return self.Cin_f ([Vov, Id, A1])\n def get_Cout(self, Vov, Id, A1):\n return self.Cout_f([Vov, Id, A1])\n def get_A1(self, Vov, Id, A1):\n return self.A1_f([Vov, Id, A1])\n \ndef CS_LK_unit_test():\n print('--- CS_LK_unit_test ----------------')\n cs = CS_LK()\n ee.print_A(' |A| ', 'V/V', cs.get_A1(0.2, 1E-4, 3))\n ee.print_R(' Rin ', cs.get_Rin(0.2, 1E-4, 3))\n ee.print_R(' Rout', cs.get_Rout(0.2, 1E-4, 3))\n ee.print_C(' Cin ', cs.get_Cin(0.2, 1E-4, 3))\n ee.print_C(' Cout', cs.get_Cout(0.2, 1E-4, 3))\n print('------------------------------------\\n')\n \nCS_LK_unit_test()\n \n\n#%% CD\nclass CD(mosfet):\n \n def __init__(self):\n self.M3 = mosfet(0, 0)\n self.A2 = -0.84\n self.Rin = -1\n self.Cin = -1\n self.Rout = -1\n self.Cout = -1\n \n def _print(self):\n print('CD stage parameters:')\n ee.print_A(' |A| ', 'V/V', -self.A2)\n ee.print_R(' Rin ', self.Rin)\n ee.print_R(' Rout', self.Rout)\n ee.print_C(' Cin ', self.Cin)\n ee.print_C(' Cout', self.Cout)\n \n def _set(self, Vov, Id): \n self.M3.set_params(Vov, Id)\n self.Rin = 1E+21\n self.Rout = ee.parallel(2*self.M3.ro, 1/self.M3.gmp)\n self.Cin = self.M3.cgs + self.M3.cgb + (1+self.A2)*self.M3.cgd\n self.Cout = (1+1/self.A2)*self.M3.cgd + self.M3.cdb\n# self._print()\n \n def get_A2(self):\n return self.A2\n def get_Rin(self):\n return self.Rin\n def get_Rout(self):\n return self.Rout\n def get_Cin(self):\n return self.Cin\n def get_Cout(self):\n return self.Cout\n \ndef unit_test_CD():\n print('--- CD_unit_test ---------------------')\n cd = CD()\n cd._set(0.2, 1E-4)\n cd._print()\n print('')\n\nunit_test_CD()\n\n\n#%%\nclass CD_LK(CD):\n _Vov = np.linspace(0.15, 0.3, 5)\n _Id = np.linspace(1E-5, 1E-4, 5)\n# print(f'_Vov: {_Vov}')\n# print(f'_Id: {_Id}')\n \n def __init__(self):\n super().__init__()\n self.n_Vov = self._Vov.shape[0]\n self.n_Id = self._Id.shape[0]\n self.A2_data = np.zeros((self.n_Vov, self.n_Id))\n self.Rin_data = np.zeros((self.n_Vov, self.n_Id))\n self.Rout_data = np.zeros((self.n_Vov, self.n_Id))\n self.Cin_data = np.zeros((self.n_Vov, self.n_Id))\n self.Cout_data = np.zeros((self.n_Vov, self.n_Id))\n print(f'n_Vov: {self.n_Vov}')\n print(f'n_Id: {self.n_Id}')\n for i in range(self.n_Vov):\n for j in range(self.n_Id):\n# print(f'i: {i}, j: {j}')\n super()._set(self._Vov[i], self._Id[j])\n self.A2_data [i,j] = super().get_A2()\n self.Rin_data[i,j] = super().get_Rin()\n self.Rout_data[i,j] = super().get_Rout()\n self.Cin_data[i,j] = super().get_Cin()\n self.Cout_data[i,j] = super().get_Cout()\n self.A2_f = RegularGridInterpolator((self._Vov, self._Id), self.A2_data)\n self.Rin_f = RegularGridInterpolator((self._Vov, self._Id), self.Rin_data)\n self.Rout_f = RegularGridInterpolator((self._Vov, self._Id), self.Rout_data)\n self.Cin_f = RegularGridInterpolator((self._Vov, self._Id), self.Cin_data)\n self.Cout_f = RegularGridInterpolator((self._Vov, self._Id), self.Cout_data)\n \n def get_A2(self, Vov, Id):\n return self.A2_f([Vov, Id])\n def get_Rin(self, Vov, Id):\n return self.Rin_f([Vov, Id])\n def get_Rout(self, Vov, Id):\n return self.Rout_f([Vov, Id])\n def get_Cin(self, Vov, Id):\n return self.Cin_f([Vov, Id])\n def get_Cout(self, Vov, Id):\n return self.Cout_f([Vov, Id])\n \ndef CD_LK_unit_test():\n print('--- CD_LK_unit_test ----------------')\n cd = CD_LK()\n ee.print_A(' |A| ', 'V/V', -cd.get_A2(0.2, 1E-4))\n ee.print_R(' Rin ', cd.get_Rin(0.2, 1E-4))\n ee.print_R(' Rout', cd.get_Rout(0.2, 1E-4))\n ee.print_C(' Cin ', cd.get_Cin(0.2, 1E-4))\n ee.print_C(' Cout', cd.get_Cout(0.2, 1E-4))\n print('------------------------------------\\n')\n \nCD_LK_unit_test()\n\n#%% Power Control Module\nclass PCM():\n I_ref = 1E-5\n Vsup = 5.\n p_total = 1.5E-3\n p_I_ref = I_ref*Vsup\n \n def __init__(self):\n self.V1 = -1\n self.R_LCG = -1\n self.Ru = -1\n self.Rd = -1\n self.p_Res = -1\n self.ratio_1 = -1 # ratio Id_1 to Id_3\n self.ratio_2 = -1 # ratio Id_2 to total\n self.Id_half = -1\n self.p_Id_half = -1\n self.Id_1 = -1\n self.Id_2 = -1\n self.Id_3 = -1\n \n def _print(self):\n print('--- PCM ------------------------')\n print('V1: %3.3f V' %self.V1)\n print('R_LCG: %1.3f kohms' %(1E-3*self.R_LCG))\n print('Ru: %1.3f kohms' %(1E-3*self.Ru))\n print('Rd: %1.3f kohms' %(1E-3*self.Rd))\n print('p_Res: %3.1f mW' %(1E+3*self.p_Id_half))\n print('ratio_1: %1.2f' %self.ratio_1)\n print('ratio_2: %1.2f' %self.ratio_2)\n print('Id_half: %3.1f uA' %(1E+6*self.Id_half))\n print('p_Id_half: %3.1f mW' %(1E+3*self.p_Id_half))\n print('Id_1: %3.1f uA' %(1E+6*self.Id_1))\n print('Id_2: %3.1f uA' %(1E+6*self.Id_2))\n print('Id_3: %3.1f uA' %(1E+6*self.Id_3))\n print('--------------------------------')\n \n def _set(self, R_LCG, V1, ratio_1, ratio_2):\n self.R_LCG = R_LCG\n self.V1 = V1\n self.ratio_1 = ratio_1\n self.ratio_2 = ratio_2\n \n self.p_Res = (2.5-self.V1)**2/self.Ru - (2.5+self.V1)**2/self.Rd\n self.p_Id_half = 0.5*(self.p_total - self.p_I_ref) - self.p_Res\n self.Id_half = self.p_Id_half/self.Vsup\n \n self.Id_1 = self.Id_half * (self.ratio_1*(1-self.ratio_2)) / (1+self.ratio_1)\n self.Id_2 = self.Id_half * self.ratio_2\n self.Id_3 = self.Id_half * (1-self.ratio_2) / (1+self.ratio_1)\n self._print()\n \n def get_Id_1(self):\n return self.Id_1\n def get_Id_2(self):\n return self.Id_2\n def get_Id_3(self):\n return self.Id_3\n \ndef PCM_unit_test():\n pcm = PCM()\n pcm._print()\n pcm._set(1E+4, 0.5, 1, 0.2)\n \nPCM_unit_test()\n\n#%% TIA\n\nclass TIA(CG_LK, CS_LK, CD_LK, PCM):\n \n def __init__(self):\n self.CG_LK = CG_LK()\n self.CS_LK = CS_LK()\n self.CD_LK = CD_LK()\n self.pcm = PCM()\n # inputs\n self.Vov_1 = -1\n self.Vov_2 = -1\n self.Vov_3 = -1\n self.R_LCG = -1\n self.V1 = -1\n self.ratio_1 = -1\n self.ratio_2 = -1\n # outputs\n self.A1 = -1\n self.power = -1\n self.gain = -1\n self.BW = -1\n self.FOM = -1\n \n def _print(self):\n print('\\nTIA inputs:')\n print('Vov_1: %3.3f V' %self.Vov_1)\n print('Vov_2: %3.3f V' %self.Vov_2)\n print('Vov_3: %3.3f V' %self.Vov_3)\n print('R_LCG: %3.1f kohms' %(1E-3*self.R_LCG))\n print('V1: %3.3f V' %self.V1)\n print('ratio_1: %3.3f' %self.ratio_1)\n print('ratio_2: %3.3f' %self.ratio_2)\n \n print('TIA outputs:')\n print('A1: %3.3f' %self.A1)\n print('power: %3.2f mw' %(1E+3*self.power))\n print('gain: %3.3f kohms' %(1E-3*self.gain))\n print('BW: %3.1f MHz' %(1E-6*self.BW))\n print('FOM: %3.3f V' %self.FOM)\n \n def _set(self, Vov_1, Vov_2, Vov_3, R_LCG, V1, ratio_1, ratio_2):\n self.Vov_1 = Vov_1\n self.Vov_2 = Vov_2\n self.Vov_3 = Vov_3\n self.R_LCG = R_LCG\n self.V1 = V1\n self.ratio_1 = ratio_1\n self.ratio_2 = ratio_2\n \n self.pcm._set(self.R_LCG, self.V1, self.ratio_1, self.ratio_2)\n self.CG_LK.get()\n \n \n \n \ndef TIA_unit_test():\n tia = TIA()\n tia._set(0.2, 0.2, 0.2, 1E+4, 0, 1, 0.2)\n tia._print()\n\nTIA_unit_test()\n\n\n\n#%% Sweep\n\nclass SWEEP(TIA):\n \n _Vov_1 = np.linspace(0.2, 0.3, 2)\n _Vov_2 = np.linspace(0.2, 0.3, 2)\n _Vov_3 = np.linspace(0.2, 0.3, 2)\n _I_ratio_1 = np.linspace(0.7, 1.4, 2)\n _I_ratio_2 = np.linspace(0.8, 1.25,2)\n _A1 = np.linspace(0.2, 0.3, 2)\n _RL = np.linspace(2E+4,3E+4,2)\n \n def __init__(self):\n self.CG_LK = CG_LK()\n self.CS_LK = CS_LK()\n self.CD_LK = CD_LK()\n \n # variables\n self.Vov_1 = -1\n self.Id_1 = -1\n self.RL = -1\n \n self.Vov_2 = -1\n self.Id_2 = -1\n self.A1 = -1\n \n self.Vov_3 = -1\n self.Id_3 = -1 \n \n # parameters\n self.I_ratio_1 = -1\n self.I_ratio_2 = -1\n \n \n def iterate(self):\n start_ms = int(round(time.time() * 1000))\n count = -1\n max_count = self._Vov_1.shape[0]*self._Vov_2.shape[0]*self._Vov_3.shape[0]*self._I_ratio_1.shape[0]*self._I_ratio_2.shape[0]*self._A1.shape[0]*self._RL.shape[0]\n for ind_Vov_1 in range(self._Vov_1.shape[0]):\n for ind_Vov_2 in range(self._Vov_2.shape[0]):\n for ind_Vov_3 in range(self._Vov_3.shape[0]):\n for ind_I_ratio_1 in range(self._I_ratio_1.shape[0]):\n for ind_I_ratio_2 in range(self._I_ratio_2.shape[0]):\n for ind_A1 in range(self._A1.shape[0]):\n for ind_RL in range(self._RL.shape[0]):\n count+=1\n print(f'count: {count}')\n \n \n \n \n \n\n print(f'max_count: {max_count}')\n end_ms = int(round(time.time() * 1000))\n print(f'total time: {end_ms-start_ms} ms')\n \ndef SWEEP_unit_test():\n sweep = SWEEP()\n sweep.iterate()\n\n#SWEEP_unit_test()\n\n\n\n\n\n","sub_path":"scratch_base.py","file_name":"scratch_base.py","file_ext":"py","file_size_in_byte":27543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638265540","text":"import numpy as np\nfrom numba import vectorize\nfrom timeit import default_timer as time\n\n\n@vectorize(['float32(float32, float32)'], target='cuda')\ndef Add(a, b):\n return a + b\n\n# Initialize arrays\nN = 100000000\nA = np.ones(N, dtype=np.float32)\nB = np.ones(A.shape, dtype=A.dtype)\nC = np.empty_like(A, dtype=A.dtype)\n\n# Add arrays on GPU\ns = time()\nC = Add(A, B)\ne = time()\ntcuda = e - s\nprint('cuda: %f' % tcuda)\n","sub_path":"numba/testNumba1GPU.py","file_name":"testNumba1GPU.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"367502202","text":"'''\nwe want to implement zip like functionality\nremember args will be tuple\n*args could be unpacked\nwe are using generator expresssion\nnotice () in comprehension like format.\n'''\n\nletters= 'abcde'\nnumbers = [1,2,3,4,5]\nsymbols = '!@#$%'\n\ndef multiziperator(*args):\n for one_index in zip(*args):\n for one_element in one_index:\n yield one_element\n\n\nfor one_item in multiziperator(letters,numbers,symbols):\n print(one_item)","sub_path":"Ex_10_Multiziperator.py","file_name":"Ex_10_Multiziperator.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"452919686","text":"import os\nimport shutil\nimport itertools\n\nimport subprocess32 as subprocess\nimport numpy as np\nimport pandas as pd\n\nfrom ..config import gps1_galfast_dir\n\n\n# The parameter data types are hard-coded as a global variable.\n# This could potentially be refactored for greater flexibility.\ndtypes = [('run_num', int), ('h_thin', float), ('h_thick', float),\n ('l_thin', float), ('l_thick', float), ('dlon', float),\n ('dlat', float)]\n\n\ndef get_run_list(directory=None, txtout=True):\n \"\"\"\n Compile a list of galfast runs.\n\n Parameters\n ----------\n directory : str, optional\n Full path of the directory to be searched.\n txtout : bool, optional\n Set to False to suppress writing results to text file.\n\n Returns\n -------\n df : pandas DataFrame\n The run numbers and associated parameters.\n\n \"\"\"\n # Initialize the DataFrame with -1.\n # For some reason it takes a 1 element array.\n data = np.array(np.repeat(-1, 1), dtype=dtypes)\n df = pd.DataFrame(data)\n\n if directory is None:\n directory = gps1_galfast_dir\n\n # Iterate through contents of directory.\n for direc in os.listdir(directory):\n if direc.startswith('gps1.run.'):\n paramfile = '{0}/{1}/params.txt'.format(directory, direc)\n\n if os.path.exists(paramfile):\n df = df.append(pd.read_table(paramfile, delim_whitespace=True))\n else:\n continue\n\n if txtout:\n # Sort by run number. Exclude first dummy entry.\n sort = df.sort_values(by='run_num')[1:]\n sort.to_csv('{0}/gps1_runs.log'.format(directory), sep='\\t',\n index=False)\n\n return df\n\n# Some cleanup code to implemented in the future.\n# def directory_cleanup(directory=None):\n# \"\"\"\n# Clean up the data directories.\n#\n# \"\"\"\n# df = get_run_list(txtout=False)\n# run_nums = df['run_num']\n#\n# # Find missing run numbers.\n# all_runs = np.arange(run_nums.min(), run_nums.max() + 2, dtype=int)\n# missing = ~np.in1d(all_runs, run_nums)\n\n\nclass RunManager(object):\n \"\"\"\n Manager object for galfast run.\n\n Creates directory for galfast output and runs galfast via command line.\n\n Parameters\n ----------\n h_thin : float\n Thin disk scale height in pc.\n h_thick : float\n Thick disk scale height in pc.\n l_thin : float\n Thin disk scale length in pc.\n l_thick : float\n Thick disk scale length in pc.\n dlon : float, optional\n Sight line longitude width in degrees. (Default: 2.)\n dlat : float, optional\n Sight line latitude width in degrees. (Default: 2.)\n\n \"\"\"\n def __init__(self, h_thin, h_thick, l_thin, l_thick, dlon=2., dlat=2.):\n self.h_thin = h_thin\n self.h_thick = h_thick\n self.l_thin = l_thin\n self.l_thick = l_thick\n self.dlon = dlon\n self.dlat = dlat\n\n # Get dataframe with run parameters.\n runs = get_run_list(txtout=True)\n # Run number = 1 + max of existing run numbers.\n # TODO: This is overkill. Could just get this from an ls command.\n run_num = runs['run_num'].max() + 1\n\n # Make a directory for the galfast output\n self.run_dir = \"{0}/gps1.run.{1:05d}\".format(gps1_galfast_dir, run_num)\n if os.path.exists(self.run_dir):\n shutil.rmtree(self.run_dir)\n os.mkdir(self.run_dir)\n\n # Save the parameters in the output directory\n data = np.array([(run_num, self.h_thin, self.h_thick, self.l_thin,\n self.l_thick, self.dlon, self.dlat)], dtype=dtypes)\n\n self.param_df = pd.DataFrame(data)\n self.param_df.to_csv('{0}/params.txt'.format(self.run_dir), sep='\\t',\n index=False)\n\n def sightline_grid(self, longitudes=None):\n \"\"\"\n Run galfast for a grid of sight lines.\n\n Parameters\n ----------\n longitudes : array_like, optional\n Specify a range of longitudes other than the default.\n latitudes : array_like, optional\n Specify a range of latitudes other than the default.\n\n \"\"\"\n # Environment variables get passed to galfast\n # Must use different variable names than those used by galfast\n os.environ['HZ_THIN'] = str(self.h_thin)\n os.environ['HZ_THICK'] = str(self.h_thick)\n os.environ['HR_THIN'] = str(self.l_thin)\n os.environ['HR_THICK'] = str(self.l_thick)\n\n command = [\"galfast\", \"catalog\", \"cmd.conf\"]\n\n # Create grid of longitudes and latitudes.\n if longitudes is None:\n longitudes = np.arange(10, 220 + 35, 35)\n latitudes = np.arange(10, 70 + 20, 20)\n latitudes = np.concatenate((-latitudes[::-1], latitudes))\n\n for lon, lat in itertools.product(longitudes, latitudes):\n # Footprint for galfast run\n os.environ['L0'] = str(lon - self.dlon / 2.)\n os.environ['L1'] = str(lon + self.dlon / 2.)\n os.environ['B0'] = str(lat - self.dlat / 2.)\n os.environ['B1'] = str(lat + self.dlat / 2.)\n\n # Output arguments for galfast command\n output = [\"--output\", \"{0}/l.{1:03d}.b.{2:+02d}.txt.gz\".\n format(self.run_dir, lon, lat)]\n\n subprocess.call(command + output)\n\n\ndef scale_grid():\n \"\"\"\n Run galfast over a grid of scale heights and lengths over a grid of\n sight lines.\n\n This will create a separate directory to hold the data for each run.\n\n \"\"\"\n h_thin_grid = np.arange(100, 400 + 100, 100)\n h_thick_grid = np.arange(500, 1000 + 250, 250)\n l_thin_grid = np.arange(1500, 3000 + 500, 500)\n l_thick_grid = np.arange(2000, 3500 + 500, 500)\n\n # Make grid of over scale height range.\n param_grid = np.meshgrid(h_thin_grid, h_thick_grid, l_thin_grid,\n l_thick_grid)\n h_thin_grid, h_thick_grid, l_thin_grid, l_thick_grid = param_grid\n\n # Flatten for iteration.\n h_thin_grid = h_thin_grid.flatten()\n h_thick_grid = h_thick_grid.flatten()\n l_thin_grid = l_thin_grid.flatten()\n l_thick_grid = l_thick_grid.flatten()\n\n for ii in range(h_thin_grid.size):\n manager = RunManager(h_thin_grid[ii], h_thick_grid[ii],\n l_thin_grid[ii], l_thick_grid[ii])\n\n manager.sightline_grid()\n","sub_path":"gps1/galfast/run_galfast.py","file_name":"run_galfast.py","file_ext":"py","file_size_in_byte":6363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134318159","text":"import csv\r\ncsvfile = open('Browser/measles.csv')\r\nreader = csv.DictReader(csvfile)\r\n\r\n\r\nimport mysql.connector\r\n\r\nmydb = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"joel\",\r\n passwd=\"test\",\r\n database=\"measles\"\r\n)\r\nmycursor = mydb.cursor()\r\n\r\namount = 50000000\r\ncount = 0\r\nfor row in reader:\r\n '''PeriodStart = row[\"PeriodStartDate\"].split(\"-\")\r\n PeriodStartDay = PeriodStart[2]\r\n PeriodStartMonth = PeriodStart[1]\r\n PeriodStartYear = PeriodStart[0]\r\n #print(PeriodStart)\r\n PeriodEnd = row[\"PeriodEndDate\"].split(\"-\")\r\n PeriodEndDay = PeriodEnd[2]\r\n PeriodEndMonth = PeriodEnd[1]\r\n PeriodEndYear = PeriodEnd[0]'''\r\n #print(PeriodEnd)\r\n\r\n string = \"'\" + row[\"ConditionName\"] + \"', \" + row[\"ConditionSNOMED\"] + \", '\" + row[\"PathogenName\"] + \"', '\" + row[\"PathogenTaxonID\"] + \"', \" + row[\"Fatalities\"] + \", '\" + row[\"CountryName\"] + \"', '\" + row[\"CountryISO\"] + \"', '\" + row[\"Admin1Name\"] + \"', '\" + row[\"Admin1ISO\"] + \"', '\" + row[\"Admin2Name\"] + \"', '\" + row[\"CityName\"] + \"', '\" + row[\"PeriodStartDate\"] + \"', '\" + row[\"PeriodEndDate\"] + \"', \" + row[\"PartOfCumulativeCountSeries\"] + \", '\" + row[\"AgeRange\"] + \"', '\" + row[\"Subpopulation\"] + \"', '\" + row[\"PlaceOfAcquisition\"] + \"', '\" + row[\"DiagnosisCertainty\"] + \"', '\" + row[\"SourceName\"] + \"', \" + row[\"CountValue\"] + \"\"\r\n #print(string)\r\n mycursor.execute('INSERT INTO data (ConditionName,ConditionSNOMED,PathogenName,PathogenTaxonID,Fatalities,CountryName,CountryISO,Admin1Name,Admin1ISO,Admin2Name,CityName,PeriodStartDate,PeriodEndDate,PartOfCumulativeCountSeries,AgeRange,Subpopulation,PlaceOfAcquisition,DiagnosisCertainty,SourceName,CountValue) VALUES(' + string + ');')\r\n \r\n count += 1\r\n if count >= amount:\r\n break\r\n\r\nmydb.commit()\r\nmycursor.close()\r\nmydb.close()\r\n\r\n'''\r\n\r\ndef CreateScript(filePath):\r\n fileoutput = open(filePath).readlines()\r\n\r\n statements = []\r\n temporary = \"\"\r\n for i in fileoutput:\r\n if i.replace(\" \",\"\")[0] == \"#\":\r\n continue\r\n temp = i.replace(\"\\n\",\"\")\r\n if len(temp) == 0:\r\n continue\r\n if temp.replace(\" \",\"\")[0] == \"-\":\r\n if temporary == \"\":\r\n continue\r\n statements.append(temporary)\r\n temporary = \"\"\r\n continue\r\n temporary += temp\r\n return statements\r\n\r\n\r\nDatabase = CreateScript(\"Browser/Measles.sql\")\r\n#print(Database)\r\n\r\nScripts = CreateScript(\"Browser/SQLQueries\")\r\n'''","sub_path":"TestBrowser/MeaslesReader.py","file_name":"MeaslesReader.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8131590","text":"class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n \"\"\"\n Time Complexity: O(n)\n Space Complexity: O(1)\n \"\"\"\n res, n = 0, len(arr)\n for i, a in enumerate(arr):\n total = (i + 1) * (n - i)\n odd = total // 2\n if total % 2 == 1:\n odd += 1\n res += odd * a\n return res\n","sub_path":"LeetCodeLearn/String_Array/1588.py","file_name":"1588.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145194529","text":"#Quick solution to control the settings of your webcam through the v412-ctl package available on Linux.\n#Authors: Christian Dorfer (dorfer@phys.ethz.ch), Joan Serra (serrajoan@me.com)\n\n\"\"\"\nRequirements:\n - pip install sh\n - pip install pyqt5 (needs Qt5 backend on system)\n - v4l-utils: Use your package manger of choice (e.g. apt-get install v4l-utils)\n \nUsage:\n python main.py\n \n\"\"\"\n\nimport sh\nimport re\nimport sys\nimport logging\nfrom time import sleep\nfrom PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QSlider\nfrom PyQt5.Qt import Qt, QLabel, QGridLayout, QPushButton\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\nclass CameraControl(object):\n \"\"\"\n Interface class to the v4l2-ctl package.\n All possible controls in the __init__ method were obtained by running 'v4l2-ctl --list-ctrls'.\n \"\"\"\n \n \n def __init__(self):\n self.cmd = sh.Command(\"/usr/bin/v4l2-ctl\")\n \n #key=name : type, min, max, step, default\n self.ctrls={\n 'brightness':['int',-64,64,1,0],\n 'contrast':['int',0,64,1,32],\n 'backlight_compensation':['int',0,2,1,1],\n 'exposure_absolute':['int',1,5000,1,156],\n 'exposure_auto':['menu',0,3,1,3],\n 'power_line_frequency':['menu',0,2,1,1],\n 'saturation':['int',0,128,1,64],\n 'sharpness':['int',0,6,1,0],\n 'white_balance_temperature':['int',2800,6500,1,4600],\n 'white_balance_temperature_auto':['bool', 1,1,1,1],\n }\n \n def getValue(self, name):\n try:\n ret = self.cmd(\"--get-ctrl\", name)\n logging.debug(\"Got return: {}\".format(ret))\n val = [int(d) for d in re.findall(r'-?\\d+', str(ret))]\n logging.debug(\"Got value: {}\".format(val))\n return val[0]\n except: \n print('Ups, could not read value.')\n pass\n \n def setValue(self, name, val):\n try:\n self.cmd(\"--set-ctrl\", (name+\"=\"+str(val)))\n except:\n print('Ups, could not set value for ', name, '.')\n pass\n \n \n def resetControls(self):\n self.setValue('backlight_compensation', self.ctrls['backlight_compensation'][4])\n self.setValue('brightness', self.ctrls['brightness'][4])\n self.setValue('sharpness', self.ctrls['sharpness'][4])\n self.setValue('contrast', self.ctrls['contrast'][4])\n\n\nclass Window(QWidget): \n def __init__(self, cc):\n super().__init__()\n \n self.camCtr = cc\n self.initUI()\n \n \n def initUI(self):\n self.setWindowTitle('Camera Control')\n self.setMinimumWidth(260)\n self.grid = QGridLayout()\n self.grid.setContentsMargins(4, 4, 4, 4)\n self.grid.setSpacing(2)\n \n ### add control elements ###\n self.backlight_lbl = QLabel(\"Backlight Compensation\")\n self.grid.addWidget(self.backlight_lbl, 10,1,1,1, Qt.AlignLeft)\n self.backlight_comp_sl = QSlider()\n self.backlight_comp_sl.setOrientation(Qt.Horizontal) \n self.backlight_comp_sl.setValue(self.camCtr.getValue('backlight_compensation'))\n self.backlight_comp_sl.setTickInterval(1)\n self.backlight_comp_sl.setMaximum(self.camCtr.ctrls['backlight_compensation'][2])\n self.backlight_comp_sl.setMinimum(self.camCtr.ctrls['backlight_compensation'][1])\n self.backlight_comp_sl.valueChanged.connect(self.backlight_com_sl_Change)\n self.backlight_comp_sl.setMinimumWidth(200)\n self.grid.addWidget(self.backlight_comp_sl, 10,2,1,1, Qt.AlignRight)\n \n self.brightness_lbl = QLabel(\"Brightness\")\n self.grid.addWidget(self.brightness_lbl, 12,1,1,1, Qt.AlignLeft)\n self.brightness_sl = QSlider()\n self.brightness_sl.setOrientation(Qt.Horizontal) \n self.brightness_sl.setValue(self.camCtr.getValue('brightness'))\n self.brightness_sl.setTickInterval(1)\n self.brightness_sl.setMaximum(self.camCtr.ctrls['brightness'][2])\n self.brightness_sl.setMinimum(self.camCtr.ctrls['brightness'][1])\n self.brightness_sl.valueChanged.connect(self.brighness_sl_Change)\n self.brightness_sl.setMinimumWidth(200)\n self.grid.addWidget(self.brightness_sl, 12,2,1,1, Qt.AlignRight)\n\n self.sharpness_lbl = QLabel(\"Sharpness\")\n self.grid.addWidget(self.sharpness_lbl, 13,1,1,1, Qt.AlignLeft)\n self.sharpness_sl = QSlider()\n self.sharpness_sl.setOrientation(Qt.Horizontal) \n self.sharpness_sl.setValue(self.camCtr.getValue('sharpness'))\n self.sharpness_sl.setTickInterval(1)\n self.sharpness_sl.setMaximum(self.camCtr.ctrls['sharpness'][2])\n self.sharpness_sl.setMinimum(self.camCtr.ctrls['sharpness'][1])\n self.sharpness_sl.valueChanged.connect(self.sharpness_sl_Change)\n self.sharpness_sl.setMinimumWidth(200)\n self.grid.addWidget(self.sharpness_sl, 13,2,1,1, Qt.AlignRight)\n \n self.contrast_lbl = QLabel(\"Contrast\")\n self.grid.addWidget(self.contrast_lbl, 14,1,1,1, Qt.AlignLeft)\n self.contrast_sl = QSlider()\n self.contrast_sl.setOrientation(Qt.Horizontal) \n self.contrast_sl.setValue(self.camCtr.getValue('contrast'))\n self.contrast_sl.setTickInterval(1)\n self.contrast_sl.setMaximum(self.camCtr.ctrls['contrast'][2])\n self.contrast_sl.setMinimum(self.camCtr.ctrls['contrast'][1])\n self.contrast_sl.valueChanged.connect(self.contrast_sl_Change)\n self.contrast_sl.setMinimumWidth(200)\n self.grid.addWidget(self.contrast_sl, 14,2,1,1, Qt.AlignRight)\n \n self.reset = QPushButton()\n self.reset.setText('Reset')\n self.reset.clicked.connect(self.reset_Slot)\n self.grid.addWidget(self.reset, 17,1,1,1, Qt.AlignCenter)\n \n ### end adding control elements \n \n self.mainLayout = QHBoxLayout()\n self.mainLayout.addLayout(self.grid)\n self.setLayout(self.mainLayout)\n self.show()\n \n \n def backlight_com_sl_Change(self):\n self.camCtr.setValue('backlight_compensation', self.backlight_comp_sl.value())\n\n def brighness_sl_Change(self):\n self.camCtr.setValue('brightness', self.brightness_sl.value())\n \n def sharpness_sl_Change(self):\n self.camCtr.setValue('sharpness', self.sharpness_sl.value())\n \n def contrast_sl_Change(self):\n self.camCtr.setValue('contrast', self.contrast_sl.value())\n\n \n def reset_Slot(self):\n self.camCtr.resetControls()\n self.backlight_comp_sl.setValue(self.camCtr.ctrls['backlight_compensation'][4])\n self.brightness_sl.setValue(self.camCtr.ctrls['brightness'][4])\n self.sharpness_sl.setValue(self.camCtr.ctrls['sharpness'][4])\n self.contrast_sl.setValue(self.camCtr.ctrls['contrast'][4]) \n \n \n \nif __name__ == '__main__':\n camCtr = CameraControl()\n app = QApplication(sys.argv)\n window = Window(camCtr)\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"410592907","text":"import os\nimport pandas as pd \nimport youtube_api\nimport argparse\nimport datetime\n\ndef main(args): \n\ttimestr= datetime.datetime.now().strftime(f\"%Y_%m_%d-%I_%M_%S_%p\")\n\tparent_dir = os.path.dirname(os.path.realpath(__file__))\n\t# base url\n\turl = f\"https://www.youtube.com/user/{args.channel}/channels\"\n\t# initilize youtube api object\n\tyoutube_obj=youtube_api.YouTubeDataAPI(key=args.apikey,api_version=3,verify_api_key=True)\n\t# grab channel id\n\tchannelid=youtube_obj.get_channel_id_from_user(args.channel)\n\t# use channel id to get subscriptions \n\tsubscriptions = youtube_obj.get_subscriptions(channelid)\n\t# data \n\tsub_df = pd.DataFrame(subscriptions)\n\tsub_data = pd.DataFrame()\n\tsub_data['subscription_title'] = sub_df['subscription_title']\n\tsub_data['subscription_channel_id'] = sub_df['subscription_channel_id']\n\tsub_data_transposed = sub_data.transpose()\n\n\tcontent = ''''''\n\tcontent +=f'''\t\n\t\n\t\t'''\n\tfor index, row in sub_data.iterrows():\n\t\tsub_title=row['subscription_title']\n\t\tchannel_id=row['subscription_channel_id']\n\t\tcontent+=f''' \n\t\t\t'''\n\tcontent += '''\t\t\n\t\t\n\t\n'''\n\t\n\twith open(os.path.join(parent_dir,f\"{args.channel}_subscriptions_{timestr}.xml\"), \"w\") as file:\t\n\t\tfile.write(content)\n\t\tfile.close()\n\nif __name__ == \"__main__\":\n\t# setup arg parser\n\tparser = argparse.ArgumentParser(description='Generate OPML From a Youtube Channels Subscriptions For RSS Import or Archive Purposes')\n\t# add arguments\n\tparser.add_argument('--apikey', type=str, required=True,\n\t\t\t\t\t\thelp='API key from a google project, 39 chars, setup instructions here: https://developers.google.com/youtube/v3/getting-started')\n\tparser.add_argument('--channel', default=\"Youtube\",\n\t\t\t\t\t\ttype=str,\n\t\t\t\t\t\thelp='Channel name you wish to scrape channel subscriptions from, example RickastleyCoUkOfficial')\n\t# pass arguments to main\n\tmain(parser.parse_args())\n","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"208351448","text":"#!/usr/bin/env python\n#\n# *------------------------------------------------------------------\n# * HostIpCheck.py\n# *\n# * Copyright (c) 2012-2014 by cisco Systems, Inc.\n# * All rights reserved.\n# *------------------------------------------------------------------\n\nimport socket\nimport re\nfrom onep.core.exception.OnepException import OnepInvalidMaskException\nfrom binascii import hexlify\n\nclass HostIpCheck(object):\n '''\n Use this to check for a valid ipv4, ipv6 or hostname string.\n Examples: \n HostIpCheck('1.1.1.1').is_ipv4() -- check for valid ipv4\n .is_ipv6() -- check for valid ipv6\n .is_hostname() -- check for valid hostname\n .is_valid() -- check for valid hostname or ip\n .is_ipaddress() -- check for valid ip address\n '''\n\n _address_space_list = ['ipv4','ipv6']\n _address_space = None\n\n def __init__(self, argument, address_space=None):\n if not isinstance(argument, str):\n raise TypeError('argument must be an IP or hostname string ')\n self._argument = argument\n\n if address_space is not None:\n if address_space in self._address_space_list:\n self._address_space = address_space\n else:\n raise ValueError(\"address_space is either \" + \n ' or '.join(self._address_space_list))\n else:\n ipv4, ipv6 = self._address_space_list\n if self.is_ipv4():\n self._address_space = ipv4\n elif self.is_ipv6():\n self._address_space = ipv6\n elif self.is_hostname():\n if not self._address_space:\n self._address_space = ipv4\n\n def _get_address_space(self):\n return self._address_space\n\n address_space = property(_get_address_space)\n\n def is_ipv4(self):\n '''\n Check if argument is a valid ipv4.\n '''\n try:\n addr = socket.inet_pton(socket.AF_INET, self._argument)\n except AttributeError: # no inet_pton here\n try:\n addr = socket.inet_aton(self._argument)\n except socket.error:\n return False\n return self._argument.count('.') == 3\n except socket.error: # not a valid address\n return False\n return True\n\n def is_ipv6(self):\n '''\n Check if argument is a valid ipv6.\n '''\n try:\n addr = socket.inet_pton(socket.AF_INET6, self._argument)\n except socket.error: # not a valid address\n return False\n return True\n\n def is_hostname(self):\n '''\n Check if argument is a valid hostname.\n '''\n if len(self._argument) > 255:\n return False\n if self._argument[-1:] == \".\":\n self._argument = self._argument[:-1] \n allowed = re.compile(\"(?!-)[A-Z\\d-]{1,63}(? 32:\n raise ValueError('Invalid prefix length %d' % len)\n\n for t in range(4):\n if len > 7:\n mask += '255.'\n else:\n dec = 255 - (2**(8 - len) - 1)\n mask += str(dec) + '.'\n len -= 8\n if len < 0:\n len = 0\n\n return mask[:-1]\n\n @staticmethod\n def mask2len(mask):\n '''\n Convert network submask to prefix length\n\n '''\n if not HostIpCheck.ipv4_validate_mask(mask):\n raise OnepInvalidMaskException(\"invalid mask\")\n\n total = 0\n for i in mask.split('.'):\n total += len(bin(int(i)).lstrip('0b').rstrip('0'))\n return total\n\n @staticmethod\n def ipv4_validate_mask(mask):\n '''\n Validate IPv4 subnetmask is valid\n\n '''\n tuples = mask.split(\".\")\n if len(tuples) != 4:\n return False\n\n # count how many \"1\" bit in the mask\n mask_value = 0\n for i in xrange(0,4):\n mask_value += int(tuples[i]) << (24-8*i)\n allbits = bin(mask_value)\n ones = allbits.count(\"1\")\n\n # mask with that many one bits set, the correct value should be:\n correct_value = 0\n for i in xrange(32-ones, 32):\n correct_value |= (1 << i)\n\n if bin(correct_value) == allbits:\n return True\n else:\n return False\n\n @staticmethod\n def calc_mask(address):\n mask = []\n lmask = [seg for seg in address.split('.') if int(seg) > 0]\n zeros = 4 - len(lmask)\n [mask.append('255') for i in lmask]\n [mask.append('0') for i in range(0, zeros)] \n return '.'.join(mask)\n","sub_path":"X-COPY/infra/onep/presentation/python/onep/core/util/HostIpCheck.py","file_name":"HostIpCheck.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"524321336","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-armv7l/egg/wyliozero/wlcd.py\n# Compiled at: 2019-11-24 09:28:29\n# Size of source mod 2**32: 493 bytes\nimport Adafruit_CharLCD as LCD\nlcd_rs = 12\nlcd_en = 25\nlcd_d4 = 6\nlcd_d5 = 26\nlcd_d6 = 24\nlcd_d7 = 16\nlcd_columns = 16\nlcd_rows = 2\nsingle = None\n\ndef lcd():\n global single\n if single == None:\n single = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows)\n else:\n return single","sub_path":"pycfiles/wyliozero-0.0.29-py3.7/wlcd.cpython-37.py","file_name":"wlcd.cpython-37.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"189746011","text":"import numpy as np\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\n#1. 데이터\nx_data = [[0,0],[1,0],[0,1],[1,1]]\ny_data = [0,1,1,0]\n\n#2. 모델\nmodel = Sequential()\nmodel.add(Dense(1, input_dim=2, activation='sigmoid'))\n\n#3. 훈련\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])\nmodel.fit(x_data, y_data, batch_size=1, epochs=100)\n\n#4. 평가, 예측\n\ny_pred = model.predict(x_data)\nprint(x_data, \"의 예측결과 : \\n\", y_pred)\n\nloss = model.evaluate(x_data, y_data)\nprint(\"loss : \", loss)\n\nacc_score = accuracy_score(y_data, y_pred.round())\nprint(\"acc_score : \", acc_score)\n\n# [[0, 0], [1, 0], [0, 1], [1, 1]] 의 예측결과 : \n# [[0.47840393]\n# [0.7053647 ]\n# [0.48446956]\n# [0.71038884]]\n# 1/1 [==============================] - 0s 1ms/step - loss: 0.7410 - acc: 0.5000\n# loss : [0.7409546375274658, 0.5]\n# acc_score : 0.5","sub_path":"ml/m04_xor2_keras1.py","file_name":"m04_xor2_keras1.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"361304247","text":"'''\r\n@author: caopeng\r\n@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. \r\n@contact: deamoncao100@gmail.com\r\n@software: garner\r\n@file: ping_mul.py\r\n@time: 23/6/30 15:35\r\n@desc:\r\n'''\r\n\r\nimport logging\r\nimport ipaddress\r\nimport multiprocessing\r\nfrom random import randint\r\nfrom scapy.layers.inet import IP, ICMP\r\nfrom scapy.sendrecv import sr1\r\n\r\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\r\n\r\n\r\ndef ping(host, queue=None):\r\n \"\"\"\r\n ping一个主机\r\n :param host: 主机地址\r\n :param queue: 成功时将地址放入该队列\r\n :return:\r\n \"\"\"\r\n print(\"Testing:\", host)\r\n id_ip = randint(1, 65535)\r\n id_ping = randint(1, 65535)\r\n seq_ping = randint(1, 65535)\r\n pkt = IP(dst=str(host), ttl=1, id=id_ip) / ICMP(id=id_ping, seq=seq_ping) / b\"I'm a ping packet \" # 构造ping包\r\n reply = sr1(pkt, timeout=2, verbose=False) # 接收一个回复包\r\n if reply:\r\n print(host, \"success\")\r\n if queue is not None:\r\n queue.put(host)\r\n\r\n\r\ndef scan(network, sacnFunc, maxPool=0, maxQueue=0):\r\n \"\"\"\r\n 对一个局域网进行扫描\r\n :param network: 扫描一个局域网\r\n :param sacnFunc: 用到的扫描函数\r\n :param maxPool: 最大进程数,如果不指定的话为本机CPU数量\r\n :param maxQueue: 队列最大数量\r\n :return: 返回\r\n \"\"\"\r\n queue = multiprocessing.Manager().Queue(maxQueue)\r\n net = ipaddress.ip_network(network) # 将网段解析为所有地址\r\n pool = multiprocessing.Pool(maxPool if maxPool else multiprocessing.cpu_count())\r\n for ip in net:\r\n pool.apply(sacnFunc, (ip, queue))\r\n\r\n pool.close()\r\n pool.join()\r\n successful_ip_list = []\r\n while not queue.empty():\r\n host = queue.get()\r\n successful_ip_list.append(host)\r\n\r\n return sorted(successful_ip_list)\r\n\r\n\r\nif __name__ == '__main__':\r\n import time\r\n\r\n start = time.time()\r\n print(\"Start scanning ...\")\r\n active_ip = scan(\"192.168.1.0/24\", ping)\r\n print(\"Scan complete!\")\r\n print(\"The hosts successfully scanned are:\")\r\n for i, ip in enumerate(active_ip):\r\n print(\"{}: {}\".format(i, ip))\r\n print(\"\\nA total of {} addresses were successful!\\n\".format(len(active_ip)))\r\n end = time.time()\r\n print(\"This scan takes a total of {} seconds.\".format(end - start))\r\n","sub_path":"network/scapy_dof/ping_mul.py","file_name":"ping_mul.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"331495954","text":"from unittest import TestCase\nfrom MaxHeap import MaxHeap\n\n\nclass TestMaxHeap(TestCase):\n def test_MaxHeap(self):\n l = [5, 3, 4, 2, 6, 1]\n h = MaxHeap()\n for item in l:\n h.push(item)\n last_element = 10\n while h.peak() is not None:\n if h.peak() > last_element:\n return self.fail('1 MinHeap return {} last time and {} this time'.format(last_element, h.peak()))\n last_element = h.pop()\n h = MaxHeap(l)\n last_element = 10\n while h.peak() is not None:\n if h.peak() > last_element:\n return self.fail('2 MinHeap return {} last time and {} this time'.format(last_element, h.peak()))\n last_element = h.pop()\n h = MaxHeap(l)\n h.pop()\n h.pop()\n h.push(0)\n h.push(7)\n if h.pop() != 7:\n return self.fail('MaxHeap did not re-heapify')","sub_path":"test_maxHeap.py","file_name":"test_maxHeap.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"121573756","text":"from nas_info import *\nfrom library import *\n\nSettings.OcrTextSearch = True\nSettings.OcrTextRead = True\nimport sys\n\nnas_name = sys.argv[1]\nnas_lanip1 = sys.argv[2]\nnas_ac = sys.argv[3]\nnas_pwd = sys.argv[4]\n\"\"\"\nnas_name = \"AT-TVS473\"\nnas_lanip1 = \"10.20.241.197\"\nnas_ac = \"admin\"\nnas_pwd = \"dqvtvs473\"\n\"\"\"\ntarget = nas_detail(name = nas_name, lanip1 = nas_lanip1, ac = nas_ac, pwd = nas_pwd)\n\n\ndef qfinder_myQNAP_sort():\n fun_name = sys._getframe().f_code.co_name\n print(\"*** Start to \" + fun_name + \" ***\")\n # open qfinder\n open_qfinder()\n click(\"1557906681939.png\")\n print(\"click myQNAPcloud field\")\n wait(1)\n \n s = Region(Region(563,281,139,373))\n myqnap_str = s.text()\n myqnap_list = myqnap_str.splitlines()\n print(\"Initial list: \" + str(myqnap_list))\n # rm space, exchange\"l\",\"S\"\n myqnaplist = []\n for i in myqnap_list:\n i = i.split(\"(\")\n i = i[0]\n q = i.replace(']','')\n q = q.replace('|','l')\n q = q.replace('}','')\n q = q.replace('t3','ts')\n q = q.replace('<:','c')\n q = q.replace('Iu','lu')\n q = q.replace(' ','')\n q = q.replace('2S3','253')\n q = q.replace('87l','871')\n q = q.replace('alorna','aloma')\n q = q.replace('\"\\xc2\\xb0Y570pro',\"roy670pro\")\n q = q.replace('\\xef\\xac\\x81871test','871test')\n q = q.replace('\\xef\\xac\\x82871test','871test')\n myqnaplist.append(q)\n print(\"Switch list: \" + str(myqnaplist))\n a = sorted(myqnaplist,key=str.lower)\n b = sorted(myqnaplist, reverse=True, key=str.upper)\n print(\"Sorted list: \" + str(a))\n print(\"Sorted list: \" + str(b))\n if myqnaplist == []:\n print(\"list fail\")\n flag = \"False\"\n elif myqnaplist == a or myqnaplist == b:\n print(\"pass\")\n flag = \"True\"\n else:\n print(\"FAIL\")\n flag = \"False\"\n with open(\"result.txt\", \"w\") as fp:\n fp.write(flag) \n print(\"--- End \" + fun_name + \" ---\")\n \nif __name__ == \"__main__\":\n qfinder_myQNAP_sort()","sub_path":"myqnapcloud_sort.sikuli/myqnapcloud_sort.py","file_name":"myqnapcloud_sort.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"534343658","text":"from operator import itemgetter\nfrom copy import deepcopy\nclass Solution(object):\n def reconstructQueue(self, people):\n \"\"\"\n :type people: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n largest_height = sorted(people, key=itemgetter(0), reverse = True)\n final_array = []\n \n while largest_height:\n temp_array = []\n current_max = largest_height[0][0]\n stop = False\n while largest_height and not stop:\n if largest_height[0][0] == current_max:\n temp_array.append(largest_height.pop(0))\n temp_array.sort(key=itemgetter(1))\n else:\n stop = True\n if not final_array: \n final_array = deepcopy(temp_array)\n else:\n for i in temp_array:\n if i[1] == 0:\n for index, j in enumerate(final_array):\n if j[0] > i[0]:\n break\n final_array.insert(index, i)\n else:\n count_greaterthan = 0\n for index, j in enumerate(final_array):\n if j[0] >= i[0]:\n count_greaterthan +=1\n if count_greaterthan == i[1]:\n break \n final_array.insert(index+1, i) # place after \n \n \n \n return final_array\n","sub_path":"LeetCode/QueueReconstruction.py","file_name":"QueueReconstruction.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264039946","text":"import os, time\r\nimport argparse,logging\r\nimport numpy as np\r\nimport mxnet as mx\r\nimport cv2, dlib, urllib\r\nfrom lightened_moon import lightened_moon_feature\r\nfrom shutil import copyfile\r\n\r\nlogger = logging.getLogger()\r\nlogger.setLevel(logging.INFO)\r\nimport pdb\r\n\r\n\r\ndef detectFaces(img, detector):\r\n faces = detector(img, 1)\r\n return faces\r\n \r\ndef detectFacesInCascade(img, face_cascade):\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n opencv_faces = face_cascade.detectMultiScale(gray, 1.3, 5, 0, (20,20))\r\n \r\n faces = []\r\n for (x,y,w,h) in opencv_faces:\r\n #print x, y, x+w, y+h\r\n faces.append(dlib.rectangle(int(x), int(y), int(x+w), int(y+h)))\r\n \r\n return faces\r\n\r\ndef attribute(img, detector, face_cascade, devs, symbol, arg_params, aux_params, argssize):\r\n h,w,c=img.shape\r\n scale = max(h/240.0, w/320.0)\r\n neww = int(w/scale)\r\n newh = int(h/scale)\r\n newimg = cv2.resize(img,(neww, newh))\r\n \r\n # read img and drat face rect\r\n faces = detectFaces(newimg, detector)\r\n if len(faces) == 0:\r\n faces = detectFacesInCascade(newimg, face_cascade)\r\n \r\n gray = np.zeros(img.shape[0:2])\r\n\r\n \r\n for i in range(len(faces)):\r\n faces[i] = dlib.rectangle(int(faces[i].left() *scale), int(faces[i].top()*scale), int(faces[i].right()*scale), int(faces[i].bottom()*scale))\r\n \r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n if len(faces) > 0:\r\n max_face = max(faces, key=lambda rect: rect.width() * rect.height())\r\n \r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n pad = [0.25, 0.25, 0.25, 0.25]\r\n left = int(max(0, max_face.left() - max_face.width()*float(pad[0])))\r\n top = int(max(0, max_face.top() - max_face.height()*float(pad[1])))\r\n right = int(min(gray.shape[1], max_face.right() + max_face.width()*float(pad[2])))\r\n bottom = int(min(gray.shape[0], max_face.bottom()+max_face.height()*float(pad[3])))\r\n \r\n gray = gray[top:bottom, left:right]\r\n #print gray.shape, left, right, top, right, argssize\r\n gray = cv2.resize(gray, (argssize, argssize))/255.0\r\n imgpred= np.expand_dims(np.expand_dims(gray, axis=0), axis=0)\r\n # get pred\r\n arg_params['data'] = mx.nd.array(imgpred, devs)\r\n exector = symbol.bind(devs, arg_params ,args_grad=None, grad_req=\"null\", aux_states=aux_params)\r\n exector.forward(is_train=False)\r\n exector.outputs[0].wait_to_read()\r\n output = exector.outputs[0].asnumpy()\r\n text = [\"5_o_Clock_Shadow\",\"Arched_Eyebrows\",\"Attractive\",\"Bags_Under_Eyes\",\"Bald\", \"Bangs\",\"Big_Lips\",\"Big_Nose\",\r\n \"Black_Hair\",\"Blond_Hair\",\"Blurry\",\"Brown_Hair\",\"Bushy_Eyebrows\",\"Chubby\",\"Double_Chin\",\"Eyeglasses\",\"Goatee\",\r\n \"Gray_Hair\", \"Heavy_Makeup\",\"High_Cheekbones\",\"Male\",\"Mouth_Slightly_Open\",\"Mustache\",\"Narrow_Eyes\",\"No_Beard\",\r\n \"Oval_Face\",\"Pale_Skin\",\"Pointy_Nose\",\"Receding_Hairline\",\"Rosy_Cheeks\",\"Sideburns\",\"Smiling\",\"Straight_Hair\",\r\n \"Wavy_Hair\",\"Wearing_Earrings\",\"Wearing_Hat\",\"Wearing_Lipstick\",\"Wearing_Necklace\",\"Wearing_Necktie\",\"Young\"]\r\n pred = np.ones(40)\r\n #print(\"attribution is:\")\r\n cnt = 0 \r\n for i in range(40):\r\n #print text[i].rjust(20)+\" : \\t\",\r\n if output[0][i] < 0:\r\n pred[i] = -1\r\n #print \"No\"\r\n else:\r\n pred[i] = 1\r\n #print \"Yes\"\r\n cv2.putText(img, text[i], (20, 50 + cnt * 30), font, 1, (255,255,0), 2, cv2.CV_AA) \r\n cnt = cnt + 1\r\n else:\r\n cv2.putText(img, \"No detected faces\", (20, 50), font, 1, (255,255,0), 2, cv2.CV_AA)\r\n\r\n for f in faces:\r\n if f == max_face:\r\n cv2.rectangle(img, (f.left(), f.top()), (f.right(), f.bottom()), (0,0,255), 2)\r\n else:\r\n cv2.rectangle(img, (f.left(), f.top()), (f.right(), f.bottom()), (255,0,0), 2)\r\n\r\n return img\r\n\r\ndef main(args):\r\n symbol = lightened_moon_feature(num_classes=40, use_fuse=True)\r\n devs = None\r\n if args.gpus is not None:\r\n print(\"use gpu...\")\r\n devs = mx.gpu()\r\n else:\r\n print(\"use cpu...\")\r\n devs = mx.cpu()\r\n _, arg_params, aux_params = mx.model.load_checkpoint(args.model_load_prefix, args.model_load_epoch)\r\n detector = dlib.get_frontal_face_detector()\r\n face_cascade = cv2.CascadeClassifier(args.opencv)\r\n\r\n stream = urllib.urlopen(args.url)\r\n bytes = ''\r\n temp_count = 16384\r\n\r\n while True:\r\n\r\n #Get a new frame\r\n imbytes = None\r\n temp_bytes = stream.read(temp_count)\r\n if temp_bytes:\r\n bytes+=temp_bytes\r\n else:\r\n stream = urllib.urlopen(args.url)\r\n bytes = ''\r\n temp_count = 16384\r\n\r\n a = bytes.find('\\xff\\xd8')\r\n b = bytes.find('\\xff\\xd9')\r\n if a != -1 and b != -1:\r\n\r\n jpg = bytes[a:b + 2]\r\n temp_count = b + 2 - a\r\n bytes = bytes[b + 2:]\r\n imbytes = jpg\r\n\r\n if imbytes is None:\r\n continue\r\n\r\n frame = cv2.imdecode(np.fromstring(imbytes, dtype=np.uint8), cv2.IMREAD_COLOR)\r\n result = attribute(frame, detector, face_cascade, devs, symbol, arg_params, aux_params, args.size)\r\n cv2.imshow(\"demo\", result)\r\n cv2.waitKey(10)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description=\"predict the face attribution of one input image\")\r\n parser.add_argument('--gpus', type=str, help='the gpus will be used, e.g \"0,1,2,3\"')\r\n parser.add_argument('--img', type=str, default='./test.jpg', help='the input img path')\r\n parser.add_argument('--url', type=str, default='', help='the input stream url')\r\n parser.add_argument('--size', type=int, default=128,\r\n help='the image size of lfw aligned image, only support squre size')\r\n parser.add_argument('--opencv', type=str, default='../model/opencv/cascade.xml',\r\n help='the opencv model path')\r\n parser.add_argument('--pad', type=float, nargs='+',\r\n help=\"pad (left,top,right,bottom) for face detection region\")\r\n parser.add_argument('--model-load-prefix', type=str, default='../model/lightened_moon/lightened_moon_fuse',\r\n help='the prefix of the model to load')\r\n parser.add_argument('--model-load-epoch', type=int, default=82,\r\n help='load the model on an epoch using the model-load-prefix')\r\n args = parser.parse_args()\r\n logging.info(args)\r\n main(args)\r\n\r\n","sub_path":"attribute/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"9849810","text":"'''\nAuthor: your name\nDate: 2021-02-11 08:50:15\nLastEditTime: 2021-02-11 08:52:36\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\python\\8_4.py\n'''\ndef greet_users(names):\n for name in names:\n msg = f\"Hello, {name.title()}!\"\n print(msg)\n\nusername = ['hannah', 'ty', 'margot']\ngreet_users((username))","sub_path":".history/8_4_20210211085236.py","file_name":"8_4_20210211085236.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"547235939","text":"from Classes.BattleField import BattleField\nimport json as json\nfrom Classes import Calculations\nimport math\nfrom Classes import Cluster\n\nx = input('Enter number of soldiers: ')\nWarField = BattleField(int(x))\n\nWarField.create_soldiers()\nsoldier_list = WarField.get_soldiers()\n\nN = len(soldier_list)\ni = 0\ncluster_points = []\n\nfor p in range(0, int(math.sqrt(N))):\n cluster_points.append(Cluster.generate_cluster_center())\n\nfor point in cluster_points:\n lat1 = point[0]\n lon1 = point[1]\n [x1, y1] = Calculations.get_world_coordinates(lat1, lon1)\n for soldier in soldier_list:\n [x2, y2] = Calculations.get_world_coordinates(soldier.get_latitude(), soldier.get_longitude())\n dist = Calculations.get_distance(x1, y1, x2, y2)\n\nfeatures = []\ni = 0\nfor soldier in soldier_list:\n temp = {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n soldier.get_longitude(),\n soldier.get_latitude()\n ]\n },\n \"properties\": {\n \"title\": 'Soldier' + str(i),\n \"icon\": \"monument\"\n }\n }\n features.append(temp)\n i = i + 1\n\nsoldier_data = {\n \"type\": \"FeatureCollection\",\n \"features\": features\n}\n\nwith open('./plots/soldiers.geojson', 'w') as outfile:\n json.dump(soldier_data, outfile)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"139940911","text":"\"\"\"Functions related to file management:\r\nFetching, loading and saving files to the disk.\"\"\"\r\nimport bpy\r\n\r\n\r\ndef get_working_directory():\r\n \"\"\"\r\n Takes the path to the current .blend file and\r\n returns the project's root directory (where the .blend file is saved)\r\n \"\"\"\r\n full_path = bpy.data.filepath\r\n project_name = bpy.path.basename(full_path)\r\n working_directory = full_path[:len(full_path) - (len(project_name) + 1)]\r\n return working_directory\r\n\r\n\r\ndef create_text_file(name):\r\n \"\"\"\r\n Create a new text file, change its name and return it\r\n Args:\r\n - name, the name of the text file, a string\"\"\"\r\n if not name and isinstance(name, str):\r\n raise TypeError('The name of the text file has to be a string')\r\n\r\n bpy.ops.text.new()\r\n import re\r\n re_text = re.compile(r'^Text.[0-9]{3}$')\r\n\r\n text_name = ''\r\n text_index, max_index = 0, 0\r\n for text in bpy.data.texts:\r\n if re_text.match(text.name):\r\n text_index = int(text.name[-3:])\r\n if text_index > max_index:\r\n max_index = text_index\r\n text_name = text.name\r\n if not text_name:\r\n text_name = 'Text'\r\n\r\n bpy.data.texts[text_name].name = name\r\n return bpy.data.texts[name]","sub_path":"All_In_One/addons/power-sequencer/functions/file_management.py","file_name":"file_management.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"537579021","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\dao\\t\\builtins\\globalenv.py\n# Compiled at: 2011-11-10 02:08:10\nfrom dao.env import GlobalEnvironment\nglobal_env = GlobalEnvironment({})\nfrom dao.base import is_subclass\nfrom dao.term import var\n\ndef collocet_builtins_to_module(globls, global_env, module):\n for (name, obj) in globls.items():\n if isinstance(obj, Command):\n try:\n symbol = obj.symbol\n except:\n try:\n symbol = obj.name\n except:\n symbol = name\n\n else:\n v = var(symbol)\n module[v] = obj\n try:\n is_global = obj.is_global\n except:\n is_global = False\n else:\n if is_global:\n global_env[v] = obj","sub_path":"pycfiles/daot-0.7.4-py2.6/globalenv.py","file_name":"globalenv.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"644281769","text":"#Py file for Q1\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[28]:\n\n\nimport pandas as pd\n\nworkbook = pd.read_csv(r\"D:\\DataMining\\Pracs\\Prac1\\specs\\AutoMpg_question1.csv\")\n\n\n# In[34]:\n\n\nmissing_col= workbook.isnull().sum()\nprint('The missing values in the Cars data:\\n', missing_col)\n\n\n# In[35]:\n\n\nfacts=workbook.describe()\n\nworkbook['horsepower'] = workbook['horsepower'].fillna(facts.loc[\"mean\",\"horsepower\"])\nworkbook['origin'] = workbook['origin'].fillna(facts.loc[\"min\",\"origin\"])\n\n\nworkbook\n\n\n# In[39]:\n\n\nquestion1_out= workbook.to_csv(r'D:\\DataMining\\Pracs\\Prac1\\specs\\output\\question1_out.csv',index= False)","sub_path":"DataExploration/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"517479924","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# \n# \n# Copyright 2021 mRuggi \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nfrom stellar_sdk import Server,Keypair,TransactionBuilder, Network\nimport requests\n\nkeypair= Keypair.random() #fund a random account that'll create yours\npublic= keypair.public_key\nsecret= keypair.secret\nprint(\"Public Key: \" + public)\nprint(\"Secret Seed: \" + secret)\n\nurl = 'https://friendbot.stellar.org'\nresponse = requests.get(url, params={'addr': public})\n\nserver = Server(horizon_url=\"https://horizon-testnet.stellar.org\")\ndestinationacc= \"YOURSECRET\"\n\ntransaction= (\n\tTransactionBuilder(\n\t\tsource_account = server.load_account(account_id=public), \n\t\tnetwork_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, \n\t\tbase_fee=100) \n\t\t.add_hash_memo(\"e3366fcb087bdb2381b7069a19405b748da831c18145eba25654d1092e93ef37\") #add the memo to the transaction\n\t\t.append_create_account_op(destination=destinationacc, starting_balance=\"5000\") #create the account\n\t\t.build()\n)\ntransaction.sign(secret)\n \nresponse = server.submit_transaction(transaction)\nprint(\"\\nTransaction hash: {}\".format(response[\"hash\"]))\nprint(\"Premi un tasto per continuare\")\ninput()\n","sub_path":"SET2/QUEST1.py","file_name":"QUEST1.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"79043124","text":"\"\"\"\nThis module provide GUI for the mass density calculator\n\n\"\"\"\nimport wx\nimport sys\nfrom sas.sasgui.guiframe.panel_base import PanelBase\nfrom wx.lib.scrolledpanel import ScrolledPanel\nfrom sas.sasgui.guiframe.utils import check_float\nfrom sas.sasgui.guiframe.events import StatusEvent\nfrom periodictable import formula as Formula\nfrom sas.sasgui.perspectives.calculator import calculator_widgets as widget\nfrom sas.sasgui.guiframe.documentation_window import DocumentationWindow\n\nAVOGADRO = 6.02214129e23\n_INPUTS = ['Mass Density', 'Molar Volume']\n_UNITS = ['g/cm^(3) ', 'cm^(3)/mol ']\n#Density panel size \nif sys.platform.count(\"win32\") > 0:\n PANEL_TOP = 0\n _STATICBOX_WIDTH = 410\n _BOX_WIDTH = 200\n PANEL_SIZE = 440\n FONT_VARIANT = 0\nelse:\n PANEL_TOP = 60\n _STATICBOX_WIDTH = 430\n _BOX_WIDTH = 200\n PANEL_SIZE = 460\n FONT_VARIANT = 1\n\nclass DensityPanel(ScrolledPanel, PanelBase):\n \"\"\"\n Provides the mass density calculator GUI.\n \"\"\"\n ## Internal nickname for the window, used by the AUI manager\n window_name = \"Mass Density Calculator\"\n ## Name to appear on the window title bar\n window_caption = \"Mass Density Calculator\"\n ## Flag to tell the AUI manager to put this panel in the center pane\n CENTER_PANE = True\n\n def __init__(self, parent, base=None, *args, **kwds):\n \"\"\"\n \"\"\"\n ScrolledPanel.__init__(self, parent, *args, **kwds)\n PanelBase.__init__(self)\n self.SetupScrolling()\n #Font size \n self.SetWindowVariant(variant=FONT_VARIANT)\n # Object that receive status event\n self.base = base\n self.parent = parent\n # chemeical formula, string\n self.compound = ''\n # value of the density/volume, float\n self.input = None\n # text controls\n self.compound_ctl = None\n self.input_ctl = None\n self.molar_mass_ctl = None\n self.output_ctl = None\n self.ctr_color = self.GetBackgroundColour()\n # button\n self.button_calculate = None\n # list\n self._input_list = _INPUTS\n self._input = self._input_list[1]\n self._output = self._input_list[0]\n self._unit_list = _UNITS\n #Draw the panel\n self._do_layout()\n self.SetAutoLayout(True)\n self.Layout()\n\n def _do_layout(self):\n \"\"\"\n Draw window content\n \"\"\"\n # units\n unit_density = self._unit_list[0]\n unit_volume = self._unit_list[1]\n\n # sizers\n sizer_input = wx.GridBagSizer(5, 5)\n sizer_output = wx.GridBagSizer(5, 5)\n sizer_button = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)\n sizer3 = wx.BoxSizer(wx.HORIZONTAL)\n vbox = wx.BoxSizer(wx.VERTICAL)\n\n # inputs\n inputbox = wx.StaticBox(self, -1, \"Inputs\")\n boxsizer1 = wx.StaticBoxSizer(inputbox, wx.VERTICAL)\n boxsizer1.SetMinSize((_STATICBOX_WIDTH, -1))\n compound_txt = wx.StaticText(self, -1, 'Molecular Formula ')\n self.compound_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))\n self.compound_eg1 = wx.StaticText(self, -1, ' e.g., H2O')\n self.compound_eg2 = wx.StaticText(self, -1, 'e.g., D2O')\n self.input_cb = wx.ComboBox(self, -1, style=wx.CB_READONLY)\n wx.EVT_COMBOBOX(self.input_cb, -1, self.on_select_input)\n hint_input_name_txt = 'Mass or volume.'\n self.input_cb.SetToolTipString(hint_input_name_txt)\n unit_density1 = \" \" + unit_density\n self.input_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))\n self.unit_input_density = wx.StaticText(self, -1, unit_density1)\n self.unit_input_volume = wx.StaticText(self, -1, unit_volume)\n iy = 0\n ix = 0\n sizer_input.Add(compound_txt, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n ix += 1\n sizer_input.Add(self.compound_ctl, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_input.Add(self.compound_eg1, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n\n ix += 1\n sizer_input.Add(self.compound_eg2, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n self.compound_eg1.Show(False)\n iy += 1\n ix = 0\n sizer_input.Add(self.input_cb, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n ix += 1\n sizer_input.Add(self.input_ctl, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_input.Add(self.unit_input_density, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n self.unit_input_density.Show(False)\n sizer_input.Add(self.unit_input_volume, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n boxsizer1.Add(sizer_input)\n self.sizer1.Add(boxsizer1, 0, wx.EXPAND | wx.ALL, 10)\n\n # outputs\n outputbox = wx.StaticBox(self, -1, \"Outputs\")\n boxsizer2 = wx.StaticBoxSizer(outputbox, wx.VERTICAL)\n boxsizer2.SetMinSize((_STATICBOX_WIDTH, -1))\n\n molar_mass_txt = wx.StaticText(self, -1, 'Molar Mass ')\n self.molar_mass_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))\n self.molar_mass_ctl.SetEditable(False)\n self.molar_mass_ctl.SetBackgroundColour(self.ctr_color)\n self.molar_mass_unit1 = wx.StaticText(self, -1, ' g/mol')\n self.molar_mass_unit2 = wx.StaticText(self, -1, 'g/mol')\n\n self.output_cb = wx.ComboBox(self, -1, style=wx.CB_READONLY)\n wx.EVT_COMBOBOX(self.output_cb, -1, self.on_select_output)\n hint_output_name_txt = 'Mass or volume.'\n self.output_cb.SetToolTipString(hint_output_name_txt)\n list = []\n for item in self._input_list:\n name = str(item)\n list.append(name)\n list.sort()\n for idx in range(len(list)):\n self.input_cb.Append(list[idx], idx)\n self.output_cb.Append(list[idx], idx)\n self.input_cb.SetStringSelection(\"Molar Volume\")\n self.output_cb.SetStringSelection(\"Mass Density\")\n unit_volume = \" \" + unit_volume\n self.output_ctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH, -1))\n self.output_ctl.SetEditable(False)\n self.output_ctl.SetBackgroundColour(self.ctr_color)\n self.unit_output_density = wx.StaticText(self, -1, unit_density)\n self.unit_output_volume = wx.StaticText(self, -1, unit_volume)\n iy = 0\n ix = 0\n sizer_output.Add(molar_mass_txt, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n ix += 1\n sizer_output.Add(self.molar_mass_ctl, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_output.Add(self.molar_mass_unit1, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_output.Add(self.molar_mass_unit2, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n self.molar_mass_unit1.Show(False)\n iy += 1\n ix = 0\n sizer_output.Add(self.output_cb, (iy, ix), (1, 1),\n wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)\n ix += 1\n sizer_output.Add(self.output_ctl, (iy, ix), (1, 1),\n wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_output.Add(self.unit_output_volume,\n (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n ix += 1\n sizer_output.Add(self.unit_output_density,\n (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n\n self.unit_output_volume.Show(False)\n boxsizer2.Add(sizer_output)\n self.sizer2.Add(boxsizer2, 0, wx.EXPAND | wx.ALL, 10)\n\n # buttons\n id = wx.NewId()\n self.button_calculate = wx.Button(self, id, \"Calculate\")\n self.button_calculate.SetToolTipString(\"Calculate.\")\n self.Bind(wx.EVT_BUTTON, self.calculate, id=id)\n\n id = wx.NewId()\n self.button_help = wx.Button(self, id, \"HELP\")\n self.button_help.SetToolTipString(\"Help for density calculator.\")\n self.Bind(wx.EVT_BUTTON, self.on_help, id=id)\n\n self.button_close = wx.Button(self, wx.ID_CANCEL, 'Close')\n self.button_close.Bind(wx.EVT_BUTTON, self.on_close)\n self.button_close.SetToolTipString(\"Close this window.\")\n\n sizer_button.Add((100, 20), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)\n sizer_button.Add(self.button_calculate, 0,\n wx.RIGHT | wx.ADJUST_MINSIZE, 20)\n sizer_button.Add(self.button_help, 0,\n wx.RIGHT | wx.ADJUST_MINSIZE, 20)\n sizer_button.Add(self.button_close, 0,\n wx.RIGHT | wx.ADJUST_MINSIZE, 20)\n sizer3.Add(sizer_button)\n\n # layout\n vbox.Add(self.sizer1)\n vbox.Add(self.sizer2)\n vbox.Add(sizer3)\n vbox.Fit(self)\n self.SetSizer(vbox)\n\n def on_select_input(self, event):\n \"\"\"\n On selection of input combobox,\n update units and output combobox\n \"\"\"\n if event is None:\n return\n event.Skip()\n\n combo = event.GetEventObject()\n self._input = combo.GetValue()\n for name in self._input_list:\n if self._input != name:\n self._output = name\n break\n\n self.set_values()\n\n def on_select_output(self, event):\n \"\"\"\n On selection of output combobox,\n update units and input combobox\n \"\"\"\n if event is None:\n return\n event.Skip()\n\n combo = event.GetEventObject()\n self._output = combo.GetValue()\n for name in self._input_list:\n if self._output != name:\n self._input = name\n break\n\n self.set_values()\n\n def set_values(self):\n \"\"\"\n Sets units and combobox values\n \"\"\"\n input, output = self.get_input()\n if input is None:\n return\n # input\n self.input_cb.SetValue(str(input))\n # output\n self.output_cb.SetValue(str(output))\n # unit\n if self._input_list.index(input) == 0:\n self.molar_mass_unit1.Show(True)\n self.molar_mass_unit2.Show(False)\n self.compound_eg1.Show(True)\n self.compound_eg2.Show(False)\n self.unit_input_density.Show(True)\n self.unit_output_volume.Show(True)\n self.unit_input_volume.Show(False)\n self.unit_output_density.Show(False)\n else:\n self.molar_mass_unit1.Show(False)\n self.molar_mass_unit2.Show(True)\n self.compound_eg1.Show(False)\n self.compound_eg2.Show(True)\n self.unit_input_volume.Show(True)\n self.unit_output_density.Show(True)\n self.unit_input_density.Show(False)\n self.unit_output_volume.Show(False)\n # layout \n self.clear_outputs()\n self.sizer1.Layout()\n self.sizer2.Layout()\n\n def get_input(self):\n \"\"\"\n Return the current input and output combobox values\n \"\"\"\n return self._input, self._output\n\n def check_inputs(self):\n \"\"\"\n Check validity user inputs\n \"\"\"\n flag = True\n msg = \"\"\n if check_float(self.input_ctl):\n self.input = float(self.input_ctl.GetValue())\n else:\n flag = False\n input_type = str(self.input_cb.GetValue())\n msg += \"Error for %s value :expect float\" % input_type\n\n self.compound = self.compound_ctl.GetValue().lstrip().rstrip()\n if self.compound != \"\":\n try :\n Formula(self.compound)\n self.compound_ctl.SetBackgroundColour(wx.WHITE)\n self.compound_ctl.Refresh()\n except:\n self.compound_ctl.SetBackgroundColour(\"pink\")\n self.compound_ctl.Refresh()\n flag = False\n msg += \"Enter correct formula\"\n else:\n self.compound_ctl.SetBackgroundColour(\"pink\")\n self.compound_ctl.Refresh()\n flag = False\n msg += \"Enter Formula\"\n return flag, msg\n\n\n def calculate(self, event):\n \"\"\"\n Calculate the mass Density/molar Volume of the molecules\n \"\"\"\n self.clear_outputs()\n try:\n #Check validity user inputs\n flag, msg = self.check_inputs()\n if self.base is not None and msg.lstrip().rstrip() != \"\":\n msg = \"Density/Volume Calculator: %s\" % str(msg)\n wx.PostEvent(self.base, StatusEvent(status=msg))\n if not flag:\n return\n #get ready to compute\n mol_formula = Formula(self.compound)\n molar_mass = float(mol_formula.molecular_mass) * AVOGADRO\n output = self._format_number(molar_mass / self.input)\n self.molar_mass_ctl.SetValue(str(self._format_number(molar_mass)))\n self.output_ctl.SetValue(str(output))\n except:\n if self.base is not None:\n msg = \"Density/Volume Calculator: %s\" % (sys.exc_info()[1])\n wx.PostEvent(self.base, StatusEvent(status=msg))\n if event is not None:\n event.Skip()\n\n def on_help(self, event):\n \"\"\"\n Bring up the density/volume calculator Documentation whenever\n the HELP button is clicked.\n\n Calls DocumentationWindow with the path of the location within the\n documentation tree (after /doc/ ....\". Note that when using old\n versions of Wx (before 2.9) and thus not the release version of\n installers, the help comes up at the top level of the file as\n webbrowser does not pass anything past the # to the browser when it is\n running \"file:///....\"\n\n :param evt: Triggers on clicking the help button\n \"\"\"\n\n _TreeLocation = \"user/sasgui/perspectives/calculator/\"\n _TreeLocation += \"density_calculator_help.html\"\n _doc_viewer = DocumentationWindow(self, -1, _TreeLocation, \"\",\n \"Density/Volume Calculator Help\")\n\n def on_close(self, event):\n \"\"\"\n close the window containing this panel\n \"\"\"\n self.parent.Close()\n\n def clear_outputs(self):\n \"\"\"\n Clear the outputs textctrl\n \"\"\"\n self.molar_mass_ctl.SetValue(\"\")\n self.output_ctl.SetValue(\"\")\n\n def _format_number(self, value=None):\n \"\"\"\n Return a float in a standardized, human-readable formatted string\n \"\"\"\n try:\n value = float(value)\n except:\n output = ''\n return output\n\n output = \"%-12.5f\" % value\n return output.lstrip().rstrip()\n\nclass DensityWindow(widget.CHILD_FRAME):\n \"\"\"\n \"\"\"\n def __init__(self, parent=None, title=\"Density/Volume Calculator\",\n base=None, manager=None,\n size=(PANEL_SIZE * 1.05, PANEL_SIZE / 1.55), *args, **kwds):\n \"\"\"\n \"\"\"\n kwds['title'] = title\n kwds['size'] = size\n widget.CHILD_FRAME.__init__(self, parent, *args, **kwds)\n \"\"\"\n \"\"\"\n self.manager = manager\n self.panel = DensityPanel(self, base=base)\n self.Bind(wx.EVT_CLOSE, self.on_close)\n self.SetPosition((wx.LEFT, PANEL_TOP))\n self.Show(True)\n\n def on_close(self, event):\n \"\"\"\n On close event\n \"\"\"\n if self.manager is not None:\n self.manager.cal_md_frame = None\n self.Destroy()\n\n\nclass ViewApp(wx.App):\n \"\"\"\n \"\"\"\n def OnInit(self):\n \"\"\"\n \"\"\"\n widget.CHILD_FRAME = wx.Frame\n frame = DensityWindow(None, title=\"Density/Volume Calculator\")\n frame.Show(True)\n self.SetTopWindow(frame)\n return True\n\n\nif __name__ == \"__main__\":\n app = ViewApp(0)\n app.MainLoop()\n","sub_path":"jhub37_mcstas_baseline/sasview-5.0.3/src/sas/sasgui/perspectives/calculator/density_panel.py","file_name":"density_panel.py","file_ext":"py","file_size_in_byte":16393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"217499282","text":"from sklearn.model_selection import cross_val_score\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport pandas as pd\r\nfrom sklearn import tree\r\n\r\n\r\ndef main():\r\n # read in the data from the .csv file and shuffle\r\n df = pd.read_csv(\r\n \"C:/Users/caire/Desktop/OutputData/OutputHtmlExcel/outputContentAnalysisNormalized.csv\",\r\n header=0, delimiter=\",\")\r\n df = df.sample(frac=1)\r\n\r\n # assign the labels as the Reliability column\r\n labels = df[\"Reliability\"]\r\n\r\n # conduct feature selection so the algorithms will run faster as now only the 5 most related attributes are used\r\n data = feature_selection(df)\r\n # data = df[[\"Article wc\", \"Title wc\", \"Article Pos Sentiment\", \"Article Neu Sentiment\", \"Article Neg Sentiment\",\r\n # \"Article Compound Sentiment\", \"Title Pos Sentiment\", \"Title Neu Sentiment\", \"Title Neg Sentiment\",\r\n # \"Title Compound Sentiment\", \"Article Bias wc\", \"Title Bias wc\", \"Article Stopword wc\", \"Title Stopword wc\",\r\n # \"Article Exclamation Count\", \"Article Cap Count\", \"Article Number Count\", \"Article Question Count\",\r\n # \"Article Comma Count\", \"Article Quote Count\", \"Title Exclamation Count\", \"Title Cap Count\",\r\n # \"Title Number Count\", \"Title Question Count\", \"Title Comma Count\", \"Title Quote Count\"]]\r\n\r\n # initialise the algorithms and fit to the data\r\n knn = KNeighborsClassifier(n_neighbors=11)\r\n lsvm = LinearSVC()\r\n clf = tree.DecisionTreeClassifier()\r\n clf.fit(data, labels)\r\n naive = GaussianNB()\r\n naive.fit(data, labels)\r\n logReg = LogisticRegression()\r\n logReg.fit(data, labels)\r\n\r\n # run 10 fold cross-validation\r\n cross_validation_test(knn, \"KNN\", data, labels)\r\n cross_validation_test(lsvm, \"LSVM\", data, labels)\r\n cross_validation_test(clf, \"CART\", data, labels)\r\n cross_validation_test(naive, \"Naive Bayes Model\", data, labels)\r\n cross_validation_test(logReg, \"logistic regression\", data, labels)\r\n\r\n\r\n# checks the results of the algorithms using 10-fold cross-validation and prints out the results\r\ndef cross_validation_test(algorithm, algorithm_name, data, results):\r\n scores = cross_val_score(algorithm, data, results, cv=10)\r\n print(algorithm_name + \":\\n\" + str(scores))\r\n print(\"Accuracy: {:0.4} (+/- {:0.3})\\n\".format(scores.mean(), scores.std() * 2))\r\n\r\n\r\n# method to find the attributes with highest correlation to the class\r\ndef feature_selection(dataframe):\r\n cor = dataframe.corr(method='pearson')\r\n cor_target = abs(cor[\"Reliability\"])\r\n relevant_features = cor_target[cor_target > 0.13]\r\n print(relevant_features)\r\n data = dataframe[[relevant_features.index[0], relevant_features.index[1], relevant_features.index[2],\r\n relevant_features.index[3], relevant_features.index[4]]]\r\n return data\r\n\r\n\r\nmain()\r\n","sub_path":"Classification/HTMLClassification.py","file_name":"HTMLClassification.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"543945015","text":"import DIPPID\nfrom pyqtgraph.flowchart import Flowchart, Node\nfrom pyqtgraph.flowchart.library.common import CtrlNode\nimport pyqtgraph.flowchart.library as fclib\nfrom pyqtgraph.Qt import QtGui, QtCore\nimport pyqtgraph as pg\nfrom DIPPID_pyqtnode import BufferNode, DIPPIDNode\nimport numpy as np\nfrom scipy.fft import fft\nimport sys\n\n\nclass GestureRecognitionNode(Node):\n \"\"\"\n Node for recording and recognizing gestures\n Contains the SVM logic and UI (ähnlich wie bei der DIPPID node in DIPPID_pyqtnode.py)\n outputs recognized activity if recognizer mode is one\n \"\"\"\n nodeName = \"GestureRecognizer\"\n\n def __init__(self, name):\n terminals = {\n 'dataIn': dict(io='in'),\n 'dataOut': dict(io='out'),\n }\n Node.__init__(self, name, terminals=terminals)\n # dict for gestures contains name as keys and their traing data as values\n self.gestures = {}\n self.mode = \"recognizing\"\n self._init_ui()\n Node.__init__(self, name, terminals=terminals)\n\n def _init_ui(self):\n print(\"init UI\")\n \"\"\"\n UI ähnlich wie bei DIPPID node\n Textbox für namen von gesture und add button (eventuell noch delete dazu)\n dann dropdown in der geaddete gestures ausgewählt werden können und start/stop record button, save model button\n theoretisch auch noch\n \"\"\"\n self.ui = QtGui.QWidget()\n self.layout = QtGui.QGridLayout()\n\n # UI for adding gestures\n label = QtGui.QLabel(\"Add new Gesture:\")\n self.new_gesture_name = QtGui.QLineEdit()\n self.layout.addWidget(self.new_gesture_name)\n self.layout.addWidget(label)\n self.add_gesture_button = QtGui.QPushButton(\"add gesture\")\n self.add_gesture_button.clicked.connect(lambda: self.add_gesture(self.new_gesture_name.text().strip()))\n self.layout.addWidget(self.add_gesture_button)\n\n # UI for recording gestures (accumulating training data)\n label2 = QtGui.QLabel(\"Record a Gesture\")\n self.layout.addWidget(label2)\n\n # drop down menu to choose gesture from list\n self.gesture_to_train = QtGui.QComboBox()\n self.gesture_to_train.addItems(self.gestures.keys())\n self.layout.addWidget(self.gesture_to_train)\n\n # button to start recording\n self.start_button = QtGui.QPushButton(\"start recording\")\n self.start_button.clicked.connect(self.start_recorder)\n self.layout.addWidget(self.start_button)\n\n # button to stop recording\n self.stop_button = QtGui.QPushButton(\"stop recording\")\n self.stop_button.clicked.connect(self.stop_recorder)\n self.layout.addWidget(self.stop_button)\n self.stop_button.setEnabled(False)\n\n self.ui.setLayout(self.layout)\n print(\"setup UI\")\n\n def ctrlWidget(self):\n return self.ui\n\n def train_model(self):\n print(\"train SVM\")\n\n def safe_model(self):\n # eventuell stattdessen einfach trainingsdaten speichern\n print(\"save svm\")\n\n def set_mode(self, mode):\n self.mode = mode\n\n def add_gesture(self, name):\n if name not in self.gestures and name != \"\":\n self.gestures[name] = []\n self.gesture_to_train.clear()\n self.gesture_to_train.addItems(self.gestures.keys())\n else:\n sys.stderr.write(\"The gesture name either already exists or is empty. Please choose another name\")\n print(\"Gestures:\", self.gestures)\n\n def start_recorder(self):\n self.set_mode(\"recording\")\n self.gesture_to_train.setEnabled(False)\n self.start_button.setEnabled(False)\n self.stop_button.setEnabled(True)\n print(\"started recognizer\")\n\n def stop_recorder(self):\n # eventuell noch idel mode hinzufügen\n self.set_mode(\"idle\")\n self.train_model()\n self.gesture_to_train.setEnabled(True)\n self.start_button.setEnabled(True)\n self.stop_button.setEnabled(False)\n print(\"started recognizer\")\n\n def recognize_gesture(self):\n print(\"recognized gesture\")\n return\n\n def process(self, **kwds):\n if self.mode == \"recording\":\n self.gestures[self.gesture_to_train.currentText()].append(kwds[\"dataIn\"])\n return recognize_gesture\n\n\nfclib.registerNodeType(GestureRecognitionNode, [('ML', )])\n\n\nclass FFTNode(Node):\n \"\"\"\n takes acceloremter data as input and outputs their fourier transform\n \"\"\"\n nodeName = \"FFT\"\n\n def __init__(self, name):\n terminals = {\n 'inputAccelX': dict(io='in'),\n 'inputAccelY': dict(io='in'),\n 'inputAccelZ': dict(io='in'),\n 'dataOut': dict(io='out'),\n }\n Node.__init__(self, name, terminals=terminals)\n print(\"start\")\n\n def transform(self, data):\n ffts = []\n for x in data:\n ffts.append(fft(x))\n return ffts\n\n def process(self, **kwds):\n fft_result = self.transform([kwds[\"inputAccelX\"], kwds[\"inputAccelY\"], kwds[\"inputAccelZ\"]])[0]\n return {'dataOut': fft_result}\n\n\nfclib.registerNodeType(FFTNode, [('Data', )])\n\n\nif __name__ == '__main__':\n\n # set up app\n app = QtGui.QApplication([])\n win = QtGui.QMainWindow()\n win.setWindowTitle('Analyze DIPPID Data')\n cw = QtGui.QWidget()\n win.setCentralWidget(cw)\n layout = QtGui.QGridLayout()\n cw.setLayout(layout)\n fc = Flowchart(terminals={})\n w = fc.widget()\n layout.addWidget(fc.widget(), 0, 0, 2, 1)\n\n # create flowchart nodes\n dippidNode = fc.createNode(\"DIPPID\", pos=(0, 0))\n recognizerNode = fc.createNode(\"GestureRecognizer\", pos=(200, 100))\n bufferNodeX = fc.createNode(\"Buffer\", pos=(150, -100))\n bufferNodeY = fc.createNode(\"Buffer\", pos=(150, 0))\n bufferNodeZ = fc.createNode(\"Buffer\", pos=(150, 100))\n fftNode = fc.createNode(\"FFT\", pos=(150, 100))\n\n # connect flowchart nodes\n fc.connectTerminals(dippidNode['accelX'], bufferNodeX['dataIn'])\n fc.connectTerminals(dippidNode['accelY'], bufferNodeY['dataIn'])\n fc.connectTerminals(dippidNode['accelZ'], bufferNodeZ['dataIn'])\n fc.connectTerminals(bufferNodeX['dataOut'], fftNode['inputAccelX'])\n fc.connectTerminals(bufferNodeY['dataOut'], fftNode['inputAccelY'])\n fc.connectTerminals(bufferNodeZ['dataOut'], fftNode['inputAccelZ'])\n fc.connectTerminals(fftNode['dataOut'], recognizerNode['dataIn'])\n\n # start app\n win.show()\n sys.exit(app.exec_())\n","sub_path":"activity_recognizer.py","file_name":"activity_recognizer.py","file_ext":"py","file_size_in_byte":6483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"270577752","text":"from django.db import models\nfrom audiofield.fields import AudioField\nfrom django.conf import settings\nimport os.path\nfrom django.core.urlresolvers import reverse\n# Create your models here.\n\nclass BG_image(models.Model):\n #name = models.CharField(max_length=60, blank=True, verbose_name=' название изображения')\n bg = models.ImageField(upload_to='backgrouns/%Y/%m/%d/', blank=True, verbose_name='Фоновое Изображение 1920х1080 px ')\n display = models.BooleanField(blank=True, default=True, verbose_name='Использовать как фон')\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n\n class Meta:\n ordering = ['bg']\n verbose_name = 'Фоновое Изображение'\n verbose_name_plural = 'Фоновые Изображения'\n\n def image_img(self):\n if self.bg:\n return u''.format(self.bg.url)\n else:\n return '(Нет изображения)'\n\n image_img.short_description = 'Картинка'\n image_img.allow_tags = True\n\n\nclass Photo_Alboom(models.Model):\n name = models.CharField(max_length=200, db_index=True)\n slug = models.SlugField(max_length=200, db_index=True, unique=True)\n image = models.ImageField(upload_to='albooms/%Y/%m/%d/', blank=True, verbose_name=\"Изображение Альбома\")\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n ordering = ['name']\n verbose_name = 'ФотоАльбом'\n verbose_name_plural = 'ФотоАльбомы'\n\n def image_img(self):\n if self.image:\n return u''.format(self.image.url)\n else:\n return '(Нет изображения)'\n def __str__(self):\n return self.name\n \n image_img.short_description = 'Картинка'\n image_img.allow_tags = True\n\n #def get_absolute_url(self):\n # return reverse('photo', args=[self.slug])\n\n\n# Модель продукта\nclass Photo(models.Model):\n photo_alboom = models.ForeignKey(Photo_Alboom, related_name='products', verbose_name=\"Фото Альбом\")\n name = models.CharField(max_length=200, db_index=True, verbose_name=\"Название\")\n slug = models.SlugField(max_length=200, db_index=True)\n image_sm = models.ImageField(upload_to='small_photo/%Y/%m/%d/', blank=True, verbose_name=\"предпросмотр\")\n image = models.ImageField(upload_to='lg_photo/%Y/%m/%d/', blank=True, verbose_name=\"фотография\")\n description = models.TextField(blank=True, verbose_name=\"Описание фотографии\")\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n ordering = ['name']\n index_together = [\n ['id', 'slug']\n ]\n verbose_name = 'Фотография'\n verbose_name_plural = 'Фотографии'\n\n def __str__(self):\n return self.name\n\n def image_img(self):\n if self.image:\n return u''.format(self.image.url)\n else:\n return '(Нет изображения)'\n\n image_img.short_description = 'Картинка'\n image_img.allow_tags = True\n\nclass MainText(models.Model):\n text_header = models.CharField(blank=True, max_length=300, verbose_name='Заголовок главного текста(например '\n 'название группы)')\n main_text = models.TextField(blank=True, verbose_name='Главный текс (о группе)')\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n ordering = ['text_header']\n verbose_name = 'Заголовок'\n verbose_name_plural = 'Главный Текст'\n\nclass Musician(models.Model):\n m_photo = models.ImageField(upload_to='musician', blank=True, verbose_name='Фотография участника группы')\n name = models.CharField(max_length=200, verbose_name='Имя(в любом формате')\n desc = models.TextField(verbose_name='Подробная информация/ описание/ биография и т.д.')\n links = models.CharField(max_length=500, blank=True, verbose_name='Ссылки на другие проекты/ профили')\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n #ordering = ['name']\n verbose_name = 'Участник Группы'\n verbose_name_plural = 'Участники группы'\n\n\nclass News(models.Model):\n header = models.CharField(max_length=200, blank=True, verbose_name='Заголовок (200 символов)')\n body = models.TextField(blank=True, verbose_name='Текст Новостей')\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n verbose_name = 'Новость'\n verbose_name_plural = 'Новости'\n\n\nclass Video(models.Model):\n header = models.CharField(max_length=200, blank=True, verbose_name='Заголовок (200 символов)')\n body = models.CharField(max_length=500, blank=True, verbose_name='код видео(заходим на YuoTube, выбираем \"поделиться\" и копируем все что после \"https://youtu.be/\" сюда!')\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n verbose_name = 'Видео'\n verbose_name_plural = 'Видео'\n\n\nclass Afisha(models.Model):\n header1 = models.CharField(max_length=200, blank=True, verbose_name='Заголовок 1 ( h4 200 символов)')\n header2 = models.CharField(max_length=200, blank=True, verbose_name='Заголовок 2 ( h1 200 символов)')\n header3 = models.CharField(max_length=200, blank=True, verbose_name='Заголовок 3 ( h2 200 символов)')\n header4 = models.CharField(max_length=200, blank=True, verbose_name='Заголовок 4 ( h3 200 символов)')\n header5 = models.CharField(max_length=200, blank=True, verbose_name='Заголовок 5 (h4 200 символов)')\n image = models.ImageField(upload_to='afisha/%Y/%m/%d/', blank=True, verbose_name=\"Афиша 150х200px\")\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n display = models.BooleanField(blank=True, default=True, verbose_name='Отображать на странице/ не отображать')\n\n class Meta:\n verbose_name = 'Афиша'\n verbose_name_plural = 'Афиши'\n\n\nclass AudioAlboom(models.Model):\n alboom_name = models.CharField(max_length=100,blank=True)\n image = models.ImageField(upload_to=\"audio_alboom\", blank=True)\n desc = models.TextField(verbose_name='Описание(Не обязательно)', blank=True)\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n\n def __str__(self):\n return self.alboom_name\n\n\n\nclass AudioFile(models.Model):\n #author = models.CharField(max_length=50, blank=True)\n #alboom = models.CharField(max_length=30,blank=True)\n alboom = models.ForeignKey(AudioAlboom,related_name='alboom_namel',verbose_name='Альбом')\n name = models.CharField(max_length=30, blank=True)\n audio_file = AudioField(upload_to='audio/', blank=True,\n ext_whitelist=(\".mp3\", \".wav\", \".ogg\"),\n help_text=(\"Allowed type - .mp3, .wav, .ogg\"))\n created = models.DateTimeField(auto_now_add=True, verbose_name='дата создания')\n updated = models.DateTimeField(auto_now=True, verbose_name='дата изменения')\n\n def audio_file_player(self):\n \"\"\"audio player tag for admin\"\"\"\n if self.audio_file:\n file_url = settings.MEDIA_URL + str(self.audio_file)\n player_string = '' % (file_url, os.path.basename(self.audio_file.name))\n\n return player_string\n\n\n def path_audio_file(self):\n name = self.audio_file\n path = os.getcwd()\n return os.path.join('/media/',str(name))\n\n def __str__(self):\n return self.name\n\n audio_file_player.allow_tags = True\n audio_file_player.short_description = 'Audio file player'","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"132006696","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 15 04:18:20 2018\n\n@author: sadievrenseker\n\nDers 9: Eksik Verileri Tamamlama(Impuatiton)\n\n\"\"\"\n\n#kutuphaneler\nimport pandas as pd\nfrom sklearn.preprocessing import Imputer\n\n#veri yukleme\nveriler = pd.read_csv('eksikveriler.csv')\n\n#veri on isleme\nboy = veriler[['boy']]\n\nboykilo = veriler[['boy','kilo']]\n\nx = 10\n\n\n#eksik veriler\n#sci - kit learn\n\nimputer= Imputer(missing_values='NaN', strategy = 'mean', axis=0 )\n\nYas = veriler.iloc[:,1:4].values\nprint(Yas)\nimputer = imputer.fit(Yas[:,1:4])\nYas[:,1:4] = imputer.transform(Yas[:,1:4])\nprint(Yas)\n\n \n \n \n \n \n \n \n \n \n \n \n \n\n","sub_path":"Data Preprocessing (Chapter 2)/9-eksikveriler.py","file_name":"9-eksikveriler.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"28421818","text":"import logmatic\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\n\nlogger = logging.getLogger()\n\n\ndef setup_logger(id=''):\n # create file handler which logs even debug messages\n file_handler = RotatingFileHandler(\"out/data-\" + str(id) + \".log\", mode='w', maxBytes=1024*1024,\n backupCount=1000, encoding=None, delay=0)\n file_handler.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.ERROR)\n\n \"\"\" Options - \n %(asctime) %(name) %(processName) %(filename) %(funcName) %(levelname) %(lineno) %(module) %(threadName) %(message)\n \"\"\"\n formatter = logmatic.JsonFormatter(fmt=\"%(levelname) %(message)\",\n extra={}) # process additional info in extra\n file_handler.setFormatter(formatter)\n stream_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n logger.addHandler(stream_handler)\n logger.setLevel(logging.DEBUG)\n\n\ndef test_file_size_logging():\n for _ in range(3):\n logger.debug('my debug message', extra={'test_debug': 'test_debug1'})\n logger.info('my info message', extra={'test_info': 'test_info2'})\n logger.warning('my warning message', extra={'test_warning': 'test_warning2'})\n logger.error('my error message', extra={'test_error': 'test_error2'})\n logger.critical('my critical message', extra={'test_critical': 'test_critical2'})\n\n\ndef test_error_logging():\n # How to log errors\n try:\n a = 3 / 0\n except Exception:\n logger.error('Some kind of error WITH TRACE INFO', exc_info=True)\n\n\nif __name__ == \"__main__\":\n setup_logger()\n test_file_size_logging()\n test_error_logging()\n","sub_path":"utils/log_config.py","file_name":"log_config.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"61602036","text":"from tensorflow.contrib import cudnn_rnn\nimport numpy as np\nimport tensorflow as tf\n\n\nclass BiLSTM():\n def __init__(self, inputs, hidden_units, dropout, name):\n self._inputs = inputs\n self._hidden_units = hidden_units\n self._dropout = dropout\n self._name = name\n self.result = self.lstm()\n\n def lstm(self):\n lstm_cell = cudnn_rnn.CudnnLSTM(\n num_layers=1,\n num_units=self._hidden_units,\n direction='bidirectional',\n dropout=self._dropout,\n name=self._name\n )\n outputs, (_, _) = lstm_cell(inputs=self._inputs)\n return outputs\n","sub_path":"no_bert_classification/BiLSTM_cudnn.py","file_name":"BiLSTM_cudnn.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353026756","text":"import json\n\nclass BulkIterator:\n\tdef __init__(self, fh, indexName):\n\t\tself.fh = fh\n\t\tself.indexName = indexName\n\n\tdef __iter__(self):\n\t\treturn self\n\n\tdef next(self):\n\t\tline = self.fh.readline()\n\n\t\tif not line:\n\t\t\traise StopIteration()\n\n\t\telse:\n\t\t\treturn {\n\t\t\t\t\"_op_type\": \"index\",\n\t\t\t\t\"_index\": self.indexName,\n\t\t\t\t\"_type\": \"disiem\",\n\t\t\t\t\"_source\": json.loads(line),\n\t\t\t}","sub_path":"elasticstack/des_BulkIterator.py","file_name":"des_BulkIterator.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87839952","text":"from tkinter import *\r\nfrom tkinter import ttk\r\n\r\n\r\nclass Grapgen:\r\n\tdef __init__(self, root):\r\n\t\troot.geometry(\"600x400\")\r\n\t\troot.title('Graph')\r\n\t\troot.wm_iconbitmap('favicon.ico')\r\n\r\n\t\tself.ffont = ('Times', -30, '')\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmainwindow = Tk()\r\n\tobj = Grapgen(mainwindow)\r\n\tmainwindow.rootmainloop()","sub_path":"upestithi/graphgui.py","file_name":"graphgui.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"113723376","text":"import torch\n\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torchvision.utils import save_image\n\nfrom models.networks import ColorTransformG, ColorTransformD\nfrom util.utils import load_state\nfrom data.data_loader import My2dDataset\n\n\nif __name__ == '__main__':\n\n assert torch.cuda.is_available()\n device = torch.device('cuda')\n\n torch.manual_seed(1234)\n torch.autograd.set_detect_anomaly(True)\n cudnn.benchmark = True\n\n netG = torch.nn.DataParallel(ColorTransformG(2))\n netD = torch.nn.DataParallel(ColorTransformD())\n\n optimizerG = optim.Adam(netG.parameters(), lr=0, betas=(0.5, 0.999))\n optimizerD = optim.Adam(netD.parameters(), lr=0, betas=(0.5, 0.999))\n\n epoch = 1\n count = 1\n\n netD = netD.to(device)\n netG = netG.to(device)\n\n epoch, count = load_state('./checkpoint_2d/params_100.pth', netG, netD, optimizerG, optimizerD)\n\n test_set = My2dDataset('test/keras', 'test/frame', 256)\n\n test_data_loader = DataLoader(test_set, batch_size=2, shuffle=False, pin_memory=True, num_workers=4)\n\n for iteration, [kera, mp, gt, ref_keras, ref_mps, ref_gts] in enumerate(test_data_loader):\n path = \"./outputs_2d/%d.jpg\" % iteration\n kera, mp, gt = kera.to(device), mp.to(device), gt.to(device)\n for ref_kera in ref_keras:\n ref_kera = ref_kera.to(device)\n for ref_mp in ref_mps:\n ref_mp = ref_mp.to(device)\n for ref_gt in ref_gts:\n ref_gt = ref_gt.to(device)\n\n with torch.no_grad():\n fake, y_sim, y_mid = netG(kera, mp, ref_keras, ref_mps, ref_gts)\n\n fake = fake[0]\n save_image(fake, path)\n\n\n","sub_path":"DLAVC/test_2d.py","file_name":"test_2d.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"71992754","text":"import os\r\nfrom arcpy import Exists as arcpyExist\r\nfrom MFII_Arcpy import geotools, get_path, path_links\r\n\r\n\r\n\r\nwirecenterIntersect = geotools.Tools()\r\nwirecenterIntersect.outputPathFolder = path_links.inputbasepath\r\nwirecenterIntersect.outputGDBName = \"_01_intersect_subsidy_with_Grid\"\r\nwirecenterIntersect.create_gdb()\r\nwirecenterIntersect.outputGDB = os.path.join(wirecenterIntersect.outputPathFolder, wirecenterIntersect.outputGDBName + \".gdb\")\r\nwirecenterSplitPath = get_path.pathFinder()\r\nLTE5Coverages_path = get_path.pathFinder()\r\n\r\n\r\nstates = wirecenterSplitPath.make_fips_list()\r\n\r\n\r\nfor fips in states:\r\n state_name = wirecenterSplitPath.query_state_name_by_fips(table_path=path_links.Fips_table_path, fips=fips)\r\n\r\n LTE5Coverages_path.env_0 = path_links.LTE5_diss_gdb_path+\".gdb\"\r\n LTE5Coverages = LTE5Coverages_path.get_file_path_with_wildcard_from_gdb(\"*_\"+fips)\r\n print(LTE5Coverages)\r\n\r\n if len(LTE5Coverages) ==0:\r\n print(\"the coverage list was empty, passing this fips\")\r\n\r\n else:\r\n intersectlist =[path_links.wireCenter_fc_path, LTE5Coverages[0]]\r\n outpath = os.path.join(wirecenterIntersect.outputGDB, \"wirecenter_intersect_Coverages_\"+fips)\r\n\r\n if arcpyExist(outpath):\r\n print(\"the file exits, skipping\")\r\n else:\r\n wirecenterIntersect.intersect_files(intersectlist, outpath)\r\n\r\n\r\n\r\n\r\ndroprows_geotool = geotools.Tools()\r\n\r\ndroprows_geotool.outputPathFolder = path_links.inputbasepath\r\ndroprows_geotool.outputGDBName = \"_01A_cleaned_intersect_subsidy_with_LTE5\"\r\ndroprows_geotool.create_gdb()\r\ndroprows_geotool.inputGDB = wirecenterIntersect.outputGDB\r\ndroprows_geotool.outputGDB = os.path.join(droprows_geotool.outputPathFolder, droprows_geotool.outputGDBName + \".gdb\")\r\n\r\n# export clean wire centers\r\ndroprows_geotool.CopyFeatureclassToFeatureclass_with_expression()\r\n\r\n# delete feature classes that are empty\r\n\r\ndeleteFC = geotools.Tools.deleteEmptyfeaturesFiles(droprows_geotool.outputGDB,\"gdb\")\r\n\r\n# create subsidized coverages:\r\n\r\nsubCoverage = geotools.Tools()\r\n\r\nsubCoverage.inputGDB = droprows_geotool.outputGDB\r\n\r\nsubCoverage.outputGDBName = path_links.wirecenter_subsidized_gdb_name\r\nsubCoverage.outputPathFolder = path_links.inputbasepath\r\nsubCoverage.create_gdb()\r\nsubCoverage.outputGDB = os.path.join(subCoverage.outputPathFolder, subCoverage.outputGDBName+\".gdb\")\r\n\r\nsubCoverage.export_subsidized_Coverage(lte5_table_basepath=path_links.inputbasepath)\r\n\r\ndeleteSubCoverageFC = geotools.Tools.deleteEmptyfeaturesFiles(subCoverage.outputGDB, \"gdb\")\r\n\r\n# split the coverages by state and provider\r\nsplitSubsidized_Coverages = geotools.Tools()\r\nsplitSubsidized_Coverages.inputGDB = subCoverage.outputGDB\r\nsplitSubsidized_Coverages.outputPathFolder = path_links.inputbasepath\r\nsplitSubsidized_Coverages.outputGDBName = path_links.wirecenter_splits_gdb_name\r\nsplitSubsidized_Coverages.create_gdb()\r\nsplitSubsidized_Coverages.outputGDB = os.path.join(splitSubsidized_Coverages.outputPathFolder, splitSubsidized_Coverages.outputGDBName+\".gdb\")\r\nsplitSubsidized_Coverages.splitCoverages(split_fields=[\"STATE_FIPS\", \"pid\"])\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","sub_path":"MFII_Arcpy/_02_Subsidy/_02_intersect_wirecenters_coverages_and_create_subsidized_coverage.py","file_name":"_02_intersect_wirecenters_coverages_and_create_subsidized_coverage.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"203834995","text":"import keras\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers.core import Activation\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda\nfrom keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, BatchNormalization, LocallyConnected2D, Permute\nfrom keras.layers import Concatenate, Reshape, Softmax, Conv2DTranspose, Embedding, Multiply\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras import regularizers\nfrom keras import backend as K\nimport keras.losses\n\nimport tensorflow as tf\n\nimport isolearn.keras as iso\n\nimport numpy as np\n\n\n#DragoNN Saved Model definition\n\ndef load_saved_predictor(model_path, library_context=None) :\n\t\n\tdef dummy_pred_func(y_true, y_pred) :\n\t\treturn y_pred\n\n\tsaved_model = load_model(model_path)\n\t#print(saved_model.summary())\n\n\tdef _initialize_predictor_weights(predictor_model, saved_model=saved_model) :\n\t\t#Load pre-trained model\n\t\tpredictor_model.get_layer('optimus5_conv1d_1').set_weights(saved_model.get_layer('conv1d_1').get_weights())\n\t\tpredictor_model.get_layer('optimus5_conv1d_1').trainable = False\n\t\t\n\t\tpredictor_model.get_layer('optimus5_conv1d_2').set_weights(saved_model.get_layer('conv1d_2').get_weights())\n\t\tpredictor_model.get_layer('optimus5_conv1d_2').trainable = False\n\t\t\n\t\tpredictor_model.get_layer('optimus5_conv1d_3').set_weights(saved_model.get_layer('conv1d_3').get_weights())\n\t\tpredictor_model.get_layer('optimus5_conv1d_3').trainable = False\n\n\t\tpredictor_model.get_layer('optimus5_dense_1').set_weights(saved_model.get_layer('dense_1').get_weights())\n\t\tpredictor_model.get_layer('optimus5_dense_1').trainable = False\n\n\t\tpredictor_model.get_layer('optimus5_dense_2').set_weights(saved_model.get_layer('dense_2').get_weights())\n\t\tpredictor_model.get_layer('optimus5_dense_2').trainable = False\n\n\tdef _initialize_predictor_weights_old(predictor_model, saved_model=saved_model, model_path=model_path) :\n\t\t#Load pre-trained model\n\t\t#print(saved_model.summary())\n\t\tpredictor_model.load_weights(model_path, by_name=True)\n\n\tdef _load_predictor_func(sequence_input) :\n\t\t#DragoNN parameters\n\t\tseq_length = 1000\n\t\tseq_input_shape = (seq_length, 4, 1)\n\t\tn_tasks = 1\n\n\t\t#Define model layers\n\t\tpermute_input = Lambda(lambda x: x[..., 0])\n\t\t\n\t\tconv_1 = Conv1D(120, 8, padding='same', activation='linear', name='optimus5_conv1d_1')\n\t\trelu_1 = Activation('relu')\n\t\t\n\t\tconv_2 = Conv1D(120, 8, padding='same', activation='linear', name='optimus5_conv1d_2')\n\t\trelu_2 = Activation('relu')\n\t\t\n\t\tconv_3 = Conv1D(120, 8, padding='same', activation='linear', name='optimus5_conv1d_3')\n\t\trelu_3 = Activation('relu')\n\t\t\n\t\tflatten_3 = Flatten()\n\t\tdense_4 = Dense(40, name='optimus5_dense_1')\n\t\trelu_4 = Activation('relu')\n\t\tdrop_4 = Dropout(0.2)\n\t\t\n\t\tfinal_dense = Dense(1, name='optimus5_dense_2')\n\n\t\t#Execute functional model definition\n\t\tpermuted_input = permute_input(sequence_input)\n\t\t\n\t\trelu_1_out = relu_1(conv_1(permuted_input))\n\t\trelu_2_out = relu_2(conv_2(relu_1_out))\n\t\trelu_3_out = relu_3(conv_3(relu_2_out))\n\n\t\trelu_4_out = drop_4(relu_4(dense_4(flatten_3(relu_3_out))), training=False)\n\t\t\n\t\tfinal_dense_out = final_dense(relu_4_out)\n\n\t\tpredictor_inputs = []\n\t\tpredictor_outputs = [final_dense_out]\n\n\t\treturn predictor_inputs, predictor_outputs, _initialize_predictor_weights\n\n\treturn _load_predictor_func\n","sub_path":"examples/optimus5/definitions/optimus5.py","file_name":"optimus5.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"436815411","text":"cities = {\n 'goa': {\n 'country': 'india',\n 'population': '500000',\n 'fact': 'for Beaches'\n },\n 'manali': {\n 'country': 'india',\n 'population': '400000',\n 'fact': 'for Hills'\n }\n}\n\nfor city, city_info in cities.items():\n print(\"City name is: \" + city + \"'s Info are: \")\n country = city_info['country']\n population = city_info['population']\n facts = city_info['fact']\n\n print('\\tCountry: ' + country)\n print(\"\\tpopulation: \" + population)\n print(\"\\tfacts: \" + facts)\n","sub_path":"Dictionaries_Programs/Cities.py","file_name":"Cities.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"402401580","text":"import cv2\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\ndef showImage(Im,image_label):\n # Im = cv2.imread('***.jpg') # 通过Opencv读入一张图片\n print(type(image_label))\n print(image_label.geometry())\n print(image_label.frameRect())\n size=image_label.geometry()\n x1=size.x()\n y1=size.y()\n x2=size.width()\n y2=size.height()\n w=x2-x1\n h=y2-y1\n Im = cv2.resize(Im, (0, 0), fx=h/Im.shape[0], fy=w/Im.shape[1], interpolation=cv2.INTER_CUBIC)\n image_height, image_width, image_depth = Im.shape # 获取图像的高,宽以及深度。\n QIm = cv2.cvtColor(Im, cv2.COLOR_BGR2RGB) # opencv读图片是BGR,qt显示要RGB,所以需要转换一下\n QIm = QImage(QIm.data, image_width, image_height, # 创建QImage格式的图像,并读入图像信息\n image_width * image_depth,\n QImage.Format_RGB888)\n image_label.setPixmap(QPixmap.fromImage(QIm)) # 将QImage显示在之前创建的QLabel控件中\n","sub_path":"system/showImage.py","file_name":"showImage.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48736859","text":"from django import forms\nfrom django.contrib import messages\nfrom product.models import Product\n\nclass RegisterForm(forms.Form):\n def __init__(self,request,*args,**kwargs):\n super().__init__(*args,**kwargs)\n self.request = request\n\n quantity = forms.IntegerField(\n error_messages = {\n 'required':'수량을 입력하세요.'\n },label = '수량'\n )\n product = forms.IntegerField(\n label = '상품',\n widget = forms.HiddenInput\n )\n\n def clean(self):\n cleaned_data = super().clean()\n quantity = cleaned_data.get('quantity')\n product = cleaned_data.get('product')\n \n # views.py 에서 product값을 사용해 redirect하기위함\n self.product = Product.objects.get(pk=product)\n if quantity and quantity <= 0:\n self.add_error('quantity',\"입력된 값이 정상적이지 않습니다.\")\n # self.add_error('quantity','수량이 입력되지 않았습니다.')\n\nclass CancelForm(forms.Form):\n pass\n ","sub_path":"order/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"421978226","text":"import math\nfrom datetime import datetime\n\nimport pytest\n\nfrom flexget.utils import json\nfrom flexget.utils.tools import parse_filesize, split_title_year, merge_dict_from_to\n\n\ndef compare_floats(float1, float2):\n eps = 0.0001\n return math.fabs(float1 - float2) <= eps\n\n\nclass TestJson:\n def test_json_encode_dt(self):\n date_str = '2016-03-11T17:12:17Z'\n dt = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%SZ')\n encoded_dt = json.dumps(dt, encode_datetime=True)\n assert encoded_dt == '\"%s\"' % date_str\n\n def test_json_encode_dt_dict(self):\n date_str = '2016-03-11T17:12:17Z'\n dt = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%SZ')\n date_obj = {'date': dt}\n encoded_dt = json.dumps(date_obj, encode_datetime=True)\n assert encoded_dt == '{\"date\": \"%s\"}' % date_str\n\n def test_json_decode_dt(self):\n date_str = '\"2016-03-11T17:12:17Z\"'\n dt = datetime.strptime(date_str, '\"%Y-%m-%dT%H:%M:%SZ\"')\n decoded_dt = json.loads(date_str, decode_datetime=True)\n assert dt == decoded_dt\n\n def test_json_decode_dt_obj(self):\n date_str = '\"2016-03-11T17:12:17Z\"'\n date_obj_str = '{\"date\": %s}' % date_str\n decoded_dt = json.loads(date_obj_str, decode_datetime=True)\n\n dt = datetime.strptime(date_str, '\"%Y-%m-%dT%H:%M:%SZ\"')\n assert decoded_dt == {'date': dt}\n\n\nclass TestParseFilesize:\n def test_parse_filesize_no_space(self):\n size = '200KB'\n expected = 200 * 1000 / 1024 ** 2\n assert compare_floats(parse_filesize(size), expected)\n\n def test_parse_filesize_space(self):\n size = '200.0 KB'\n expected = 200 * 1000 / 1024 ** 2\n assert compare_floats(parse_filesize(size), expected)\n\n def test_parse_filesize_non_si(self):\n size = '1234 GB'\n expected = 1234 * 1000 ** 3 / 1024 ** 2\n assert compare_floats(parse_filesize(size), expected)\n\n def test_parse_filesize_auto(self):\n size = '1234 GiB'\n expected = 1234 * 1024 ** 3 / 1024 ** 2\n assert compare_floats(parse_filesize(size), expected)\n\n def test_parse_filesize_auto_mib(self):\n size = '1234 MiB'\n assert compare_floats(parse_filesize(size), 1234)\n\n def test_parse_filesize_ib_not_valid(self):\n with pytest.raises(ValueError):\n parse_filesize('100 ib')\n\n def test_parse_filesize_single_digit(self):\n size = '1 GiB'\n assert compare_floats(parse_filesize(size), 1024)\n\n def test_parse_filesize_separators(self):\n size = '1,234 GiB'\n assert parse_filesize(size) == 1263616\n\n size = '1 234 567 MiB'\n assert parse_filesize(size) == 1234567\n\n\nclass TestSplitYearTitle:\n @pytest.mark.parametrize(\n 'title, expected_title, expected_year',\n [\n ('The Matrix', 'The Matrix', None),\n ('The Matrix 1999', 'The Matrix', 1999),\n ('The Matrix (1999)', 'The Matrix', 1999),\n ('The Matrix - 1999', 'The Matrix -', 1999),\n ('The.Matrix.1999', 'The.Matrix.', 1999),\n (\n 'The Human Centipede III (Final Sequence)',\n 'The Human Centipede III (Final Sequence)',\n None,\n ),\n (\n 'The Human Centipede III (Final Sequence) (2015)',\n 'The Human Centipede III (Final Sequence)',\n 2015,\n ),\n ('2020', '2020', None),\n ],\n )\n def test_split_year_title(self, title, expected_title, expected_year):\n assert split_title_year(title) == (expected_title, expected_year)\n\nclass TestDictMerge(object):\n def test_merge_dict_to_dict_list(self):\n d1 = {'setting': {'parameter': ['item_1']}}\n d2 = {'setting': {'parameter': ['item_2']}}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': {'parameter': ['item_2', 'item_1']}}\n\n def test_merge_dict_to_dict_override(self):\n d1 = {'setting': {'parameter': ['item_1']}}\n d2 = {'setting': {'parameter': 2}}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': {'parameter': 2}}\n\n def test_merge_dict_to_dict_add(self):\n d1 = {'setting': {'parameter_1': ['item_1']}}\n d2 = {'setting': {'parameter_2': 'item_2'}}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': {'parameter_1': ['item_1'], 'parameter_2': 'item_2'}}\n\n def test_merge_dict_to_dict_str(self):\n d1 = {'setting': {'parameter': 'item_1'}}\n d2 = {'setting': {'parameter': 'item_2'}}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': {'parameter': 'item_2'}}\n\n def test_merge_list_to_list(self):\n d1 = {'setting': ['item_1']}\n d2 = {'setting': ['item_2']}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': ['item_2', 'item_1']}\n\n def test_merge_list_to_str(self):\n d1 = {'setting': ['list']}\n d2 = {'setting': 'string'}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': 'string'}\n\n def test_merge_str_to_list(self):\n d1 = {'setting': 'string'}\n d2 = {'setting': ['list']}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': ['list']}\n\n def test_merge_str_to_str(self):\n d1 = {'setting': 'string_1'}\n d2 = {'setting': 'string_2'}\n merge_dict_from_to(d1, d2)\n assert d2 == {'setting': 'string_2'}\n","sub_path":"flexget/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160081963","text":"# Regex replacer project\n# Hugo Isaac Valdez Ruvalcaba - A01631301\n\n# Classes\n\nclass State:\n def __init__(self, name):\n self.name = name\n self.transitions = { }\n\n def addTransition(self, symbol, state):\n self.transitions[symbol] = state\n\n def applySymbol(self, symbol):\n if symbol in self.transitions:\n return self.transitions[symbol]\n else:\n return None\n\n\nclass Automata:\n def __init__(self, regex):\n self.regex = regex\n self.finalStates = []\n self.states = self.buildStates()\n self.initialState = self.states[0]\n \n def buildStates(self):\n divExp = self.splitRegex()\n states = [State(\"q0\")]\n nState = 1\n for i in divExp:\n finalStates = []\n prev = current = states[0]\n for j in range(len(i)):\n if current.applySymbol(i[j][0]) == None:\n newState = State(\"q\"+str(nState))\n current.addTransition(i[j][0], newState)\n states.append(newState)\n nState += 1\n current = current.applySymbol(i[j][0])\n prev.addTransition(i[j][0], current)\n if \"*\" not in i[j]:\n prev = current\n finalStates = []\n else:\n current.addTransition(i[j][0], current)\n finalStates.append(current)\n finalStates.append(prev)\n finalStates.append(current)\n self.addFinalStates(finalStates)\n return states\n\n def addFinalStates(self, finalStates):\n for state in finalStates:\n if state not in self.finalStates:\n self.finalStates.append(state)\n \n def splitRegex(self):\n divExp = []\n union = self.regex.split(\"+\")\n for i in union:\n symbols = []\n for j in range(len(i)):\n if j+1 < len(i) and i[j+1] == \"*\":\n symbols.append(i[j]+\"*\")\n elif i[j] != \"*\":\n symbols.append(i[j])\n divExp.append(symbols)\n return divExp\n\n def printAutomata(self):\n for i in self.states:\n print(i, i.name, i.transitions)\n print(self.initialState)\n print(self.finalStates)\n\n# Functions\n\ndef replaceRegex(inputStr, regex, replacement):\n\n FSA = Automata(regex)\n res = \"\"\n i = j = 0\n size = len(inputStr)\n\n if(size == 0 and FSA.initialState in FSA.finalStates):\n res = replacement\n else: \n while j < size:\n currentOutput = prevOutput = FSA.initialState.applySymbol(inputStr[j])\n while currentOutput != None and j < len(inputStr):\n j+=1\n prevOutput = currentOutput\n if j <= size-1:\n currentOutput = currentOutput.applySymbol(inputStr[j])\n if prevOutput in FSA.finalStates:\n res += replacement\n else:\n if i == j:\n j+=1\n res += inputStr[i:j]\n i=j\n\n return res\n\ndef validRegex(regex):\n size = len(regex)\n if size == 0:\n return False\n for i in range(size):\n if i == 0 and (regex[i] == \"*\" or regex[i] == \"+\"):\n return False\n elif i < size-1:\n if regex[i] == \"*\":\n if i == size-2 and (regex[i+1] == \"+\" or regex[i+1] == \"*\"):\n return False\n elif regex[i+1] == \"*\":\n return False\n elif regex[i] == \"+\" and (regex[i+1] == \"+\" or regex[i+1] == \"*\"):\n return False\n return True\n\ntest = False\n\nif not test:\n # Main\n while True:\n inputStr = str(input(\"Input string: \"))\n replacement = str(input(\"Input replacement: \"))\n regex = str(input(\"Input regular expression: \"))\n while not validRegex(regex):\n print(\"Invalid regex. Valid operators: + , *\")\n regex = str(input(\"Input egular expression: \"))\n\n res = replaceRegex(inputStr, regex, replacement)\n print(res+\"\\n\")\n print(\"----------------------------------------------\\n\")\nelse:\n inputStr = \"aa abbbbb aa\"\n regex = \"a *ab*\"\n replacement = \"0\"\n res = replaceRegex(inputStr, regex, replacement)\n print(res+\"\\n\")\n","sub_path":"regexReplacerCLI.py","file_name":"regexReplacerCLI.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"106962238","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom lxml import etree\nfrom oslo.config import cfg\n\nfrom keystoneclient import access\nfrom keystoneclient.auth.identity import v3\nfrom keystoneclient import exceptions\n\n\nclass Saml2UnscopedTokenAuthMethod(v3.AuthMethod):\n _method_parameters = []\n\n def get_auth_data(self, session, auth, headers, **kwargs):\n raise exceptions.MethodNotImplemented(('This method should never '\n 'be called'))\n\n\nclass Saml2UnscopedToken(v3.AuthConstructor):\n \"\"\"Implement authentication plugin for SAML2 protocol.\n\n ECP stands for ``Enhanced Client or Proxy`` and is a SAML2 extension\n for federated authentication where a transportation layer consists of\n HTTP protocol and XML SOAP messages.\n\n Read for more information::\n ``https://wiki.shibboleth.net/confluence/display/SHIB2/ECP``\n\n The SAML2 ECP specification can be found at::\n ``https://www.oasis-open.org/committees/download.php/\n 49979/saml-ecp-v2.0-wd09.pdf``\n\n Currently only HTTPBasicAuth mechanism is available for the IdP\n authenication.\n\n \"\"\"\n\n _auth_method_class = Saml2UnscopedTokenAuthMethod\n\n PROTOCOL = 'saml2'\n HTTP_MOVED_TEMPORARILY = 302\n SAML2_HEADER_INDEX = 0\n ECP_SP_EMPTY_REQUEST_HEADERS = {\n 'Accept': 'text/html; application/vnd.paos+xml',\n 'PAOS': ('ver=\"urn:liberty:paos:2003-08\";\"urn:oasis:names:tc:'\n 'SAML:2.0:profiles:SSO:ecp\"')\n }\n\n ECP_SP_SAML2_REQUEST_HEADERS = {\n 'Content-Type': 'application/vnd.paos+xml'\n }\n\n ECP_SAML2_NAMESPACES = {\n 'ecp': 'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp',\n 'S': 'http://schemas.xmlsoap.org/soap/envelope/',\n 'paos': 'urn:liberty:paos:2003-08'\n }\n\n ECP_RELAY_STATE = '//ecp:RelayState'\n\n ECP_SERVICE_PROVIDER_CONSUMER_URL = ('/S:Envelope/S:Header/paos:Request/'\n '@responseConsumerURL')\n\n ECP_IDP_CONSUMER_URL = ('/S:Envelope/S:Header/ecp:Response/'\n '@AssertionConsumerServiceURL')\n\n SOAP_FAULT = \"\"\"\n \n \n \n S:Server\n responseConsumerURL from SP and\n assertionConsumerServiceURL from IdP do not match\n \n \n \n \n \"\"\"\n\n def __init__(self, auth_url,\n identity_provider,\n identity_provider_url,\n username, password,\n **kwargs):\n \"\"\"Class constructor accepting following parameters:\n :param auth_url: URL of the Identity Service\n :type auth_url: string\n\n :param identity_provider: name of the Identity Provider the client\n will authenticate against. This parameter\n will be used to build a dynamic URL used to\n obtain unscoped OpenStack token.\n :type identity_provider: string\n\n :param identity_provider_url: An Identity Provider URL, where the SAML2\n authn request will be sent.\n :type identity_provider_url: string\n\n :param username: User's login\n :type username: string\n\n :param password: User's password\n :type password: string\n\n \"\"\"\n super(Saml2UnscopedToken, self).__init__(auth_url=auth_url, **kwargs)\n self.identity_provider = identity_provider\n self.identity_provider_url = identity_provider_url\n self.username, self.password = username, password\n\n @classmethod\n def get_options(cls):\n options = super(Saml2UnscopedToken, cls).get_options()\n options.extend([\n cfg.StrOpt('identity-provider', help=\"Identity Provider's name\"),\n cfg.StrOpt('identity-provider-url',\n help=\"Identity Provider's URL\"),\n cfg.StrOpt('user-name', dest='username', help='Username',\n deprecated_name='username'),\n cfg.StrOpt('password', help='Password')\n ])\n return options\n\n def _handle_http_302_ecp_redirect(self, session, response, method,\n **kwargs):\n if response.status_code != self.HTTP_MOVED_TEMPORARILY:\n return response\n\n location = response.headers['location']\n return session.request(location, method, **kwargs)\n\n def _first(self, _list):\n if len(_list) != 1:\n raise IndexError(\"Only single element list can be flatten\")\n return _list[0]\n\n def _prepare_idp_saml2_request(self, saml2_authn_request):\n header = saml2_authn_request[self.SAML2_HEADER_INDEX]\n saml2_authn_request.remove(header)\n\n def _check_consumer_urls(self, session, sp_response_consumer_url,\n idp_sp_response_consumer_url):\n \"\"\"Check if consumer URLs issued by SP and IdP are equal.\n\n In the initial SAML2 authn Request issued by a Service Provider\n there is a url called ``consumer url``. A trusted Identity Provider\n should issue identical url. If the URLs are not equal the federated\n authn process should be interrupted and the user should be warned.\n\n :param session: session object to send out HTTP requests.\n :type session: keystoneclient.session.Session\n :param sp_response_consumer_url: consumer URL issued by a SP\n :type sp_response_consumer_url: string\n :param idp_sp_response_consumer_url: consumer URL issued by an IdP\n :type idp_sp_response_consumer_url: string\n\n \"\"\"\n if sp_response_consumer_url != idp_sp_response_consumer_url:\n # send fault message to the SP, discard the response\n session.post(sp_response_consumer_url, data=self.SOAP_FAULT,\n headers=self.ECP_SP_SAML2_REQUEST_HEADERS,\n authenticated=False)\n\n # prepare error message and raise an exception.\n msg = (\"Consumer URLs from Service Provider %(service_provider)s \"\n \"%(sp_consumer_url)s and Identity Provider \"\n \"%(identity_provider)s %(idp_consumer_url)s are not equal\")\n msg = msg % {\n 'service_provider': self.saml2_token_url,\n 'sp_consumer_url': sp_response_consumer_url,\n 'identity_provider': self.identity_provider,\n 'idp_consumer_url': idp_sp_response_consumer_url\n }\n\n raise exceptions.ValidationError(msg)\n\n def _send_service_provider_request(self, session):\n \"\"\"Initial HTTP GET request to the SAML2 protected endpoint.\n\n It's crucial to include HTTP headers indicating that the client is\n willing to take advantage of the ECP SAML2 extension and receive data\n as the SOAP.\n Unlike standard authentication methods in the OpenStack Identity,\n the client accesses::\n ``/v3/OS-FEDERATION/identity_providers/{identity_providers}/\n protocols/{protocol}/auth``\n\n After a successful HTTP call the HTTP response should include SAML2\n authn request in the XML format.\n\n If a HTTP response contains ``X-Subject-Token`` in the headers and\n the response body is a valid JSON assume the user was already\n authenticated and Keystone returned a valid unscoped token.\n Return True indicating the user was already authenticated.\n\n :param session: a session object to send out HTTP requests.\n :type session: keystoneclient.session.Session\n\n \"\"\"\n sp_response = session.get(self.saml2_token_url,\n headers=self.ECP_SP_EMPTY_REQUEST_HEADERS,\n authenticated=False)\n\n if 'X-Subject-Token' in sp_response.headers:\n self.authenticated_response = sp_response\n return True\n\n try:\n self.saml2_authn_request = etree.XML(sp_response.content)\n except etree.XMLSyntaxError as e:\n msg = (\"SAML2: Error parsing XML returned \"\n \"from Service Provider, reason: %s\" % e)\n raise exceptions.AuthorizationFailure(msg)\n\n relay_state = self.saml2_authn_request.xpath(\n self.ECP_RELAY_STATE, namespaces=self.ECP_SAML2_NAMESPACES)\n self.relay_state = self._first(relay_state)\n\n sp_response_consumer_url = self.saml2_authn_request.xpath(\n self.ECP_SERVICE_PROVIDER_CONSUMER_URL,\n namespaces=self.ECP_SAML2_NAMESPACES)\n self.sp_response_consumer_url = self._first(\n sp_response_consumer_url)\n return False\n\n def _send_idp_saml2_authn_request(self, session):\n \"\"\"Present modified SAML2 authn assertion from the Service Provider.\"\"\"\n\n self._prepare_idp_saml2_request(self.saml2_authn_request)\n idp_saml2_authn_request = self.saml2_authn_request\n\n # Currently HTTPBasicAuth method is hardcoded into the plugin\n idp_response = session.post(\n self.identity_provider_url,\n headers={'Content-type': 'text/xml'},\n data=etree.tostring(idp_saml2_authn_request),\n requests_auth=(self.username, self.password))\n\n try:\n self.saml2_idp_authn_response = etree.XML(idp_response.content)\n except etree.XMLSyntaxError as e:\n msg = (\"SAML2: Error parsing XML returned \"\n \"from Identity Provider, reason: %s\" % e)\n raise exceptions.AuthorizationFailure(msg)\n\n idp_response_consumer_url = self.saml2_idp_authn_response.xpath(\n self.ECP_IDP_CONSUMER_URL,\n namespaces=self.ECP_SAML2_NAMESPACES)\n\n self.idp_response_consumer_url = self._first(\n idp_response_consumer_url)\n\n self._check_consumer_urls(session, self.idp_response_consumer_url,\n self.sp_response_consumer_url)\n\n def _send_service_provider_saml2_authn_response(self, session):\n \"\"\"Present SAML2 assertion to the Service Provider.\n\n The assertion is issued by a trusted Identity Provider for the\n authenticated user. This function directs the HTTP request to SP\n managed URL, for instance: ``https://:/Shibboleth.sso/\n SAML2/ECP``.\n Upon success the there's a session created and access to the protected\n resource is granted. Many implementations of the SP return HTTP 302\n status code pointing to the protected URL (``https://:/v3/\n OS-FEDERATION/identity_providers/{identity_provider}/protocols/\n {protocol_id}/auth`` in this case). Saml2 plugin should point to that\n URL again, with HTTP GET method, expecting an unscoped token.\n\n :param session: a session object to send out HTTP requests.\n\n \"\"\"\n self.saml2_idp_authn_response[0][0] = self.relay_state\n\n response = session.post(\n self.idp_response_consumer_url,\n headers=self.ECP_SP_SAML2_REQUEST_HEADERS,\n data=etree.tostring(self.saml2_idp_authn_response),\n authenticated=False, redirect=False)\n\n # Don't follow HTTP specs - after the HTTP 302 response don't repeat\n # the call directed to the Location URL. In this case, this is an\n # indication that saml2 session is now active and protected resource\n # can be accessed.\n response = self._handle_http_302_ecp_redirect(\n session, response, method='GET',\n headers=self.ECP_SP_SAML2_REQUEST_HEADERS)\n\n self.authenticated_response = response\n\n @property\n def saml2_token_url(self):\n \"\"\"Return full URL where authorization data is sent.\"\"\"\n values = {\n 'host': self.auth_url.rstrip('/'),\n 'identity_provider': self.identity_provider,\n 'protocol': self.PROTOCOL\n }\n url = (\"%(host)s/OS-FEDERATION/identity_providers/\"\n \"%(identity_provider)s/protocols/%(protocol)s/auth\")\n url = url % values\n\n return url\n\n def _get_unscoped_token(self, session, **kwargs):\n \"\"\"Get unscoped OpenStack token after federated authentication.\n\n This is a multi-step process including multiple HTTP requests.\n\n The federated authentication consists of::\n * HTTP GET request to the Identity Service (acting as a Service\n Provider). Client utilizes URL::\n ``/v3/OS-FEDERATION/identity_providers/{identity_provider}/\n protocols/saml2/auth``.\n It's crucial to include HTTP headers indicating we are expecting\n SOAP message in return.\n Service Provider should respond with such SOAP message.\n This step is handed by a method\n ``Saml2UnscopedToken_send_service_provider_request()``\n\n * HTTP POST request to the external Identity Provider service with\n ECP extension enabled. The content sent is a header removed SOAP\n message returned from the Service Provider. It's also worth noting\n that ECP extension to the SAML2 doesn't define authentication method.\n The most popular is HttpBasicAuth with just user and password.\n Other possibilities could be X509 certificates or Kerberos.\n Upon successful authentication the user should receive a SAML2\n assertion.\n This step is handed by a method\n ``Saml2UnscopedToken_send_idp_saml2_authn_request(session)``\n\n * HTTP POST request again to the Service Provider. The body of the\n request includes SAML2 assertion issued by a trusted Identity\n Provider. The request should be sent to the Service Provider\n consumer url specified in the SAML2 assertion.\n Providing the authentication was successful and both Service Provider\n and Identity Providers are trusted to each other, the Service\n Provider will issue an unscoped token with a list of groups the\n federated user is a member of.\n This step is handed by a method\n ``Saml2UnscopedToken_send_service_provider_saml2_authn_response()``\n\n Unscoped token example::\n\n {\n \"token\": {\n \"methods\": [\n \"saml2\"\n ],\n \"user\": {\n \"id\": \"username%40example.com\",\n \"name\": \"username@example.com\",\n \"OS-FEDERATION\": {\n \"identity_provider\": \"ACME\",\n \"protocol\": \"saml2\",\n \"groups\": [\n {\"id\": \"abc123\"},\n {\"id\": \"bcd234\"}\n ]\n }\n }\n }\n }\n\n\n :param session : a session object to send out HTTP requests.\n :type session: keystoneclient.session.Session\n\n :returns: (token, token_json)\n\n \"\"\"\n saml_authenticated = self._send_service_provider_request(session)\n if not saml_authenticated:\n self._send_idp_saml2_authn_request(session)\n self._send_service_provider_saml2_authn_response(session)\n return (self.authenticated_response.headers['X-Subject-Token'],\n self.authenticated_response.json()['token'])\n\n def get_auth_ref(self, session, **kwargs):\n \"\"\"Authenticate via SAML2 protocol and retrieve unscoped token.\n\n This is a multi-step process where a client does federated authn\n receives an unscoped token.\n\n Federated authentication utilizing SAML2 Enhanced Client or Proxy\n extension. See ``Saml2UnscopedToken_get_unscoped_token()``\n for more information on that step.\n Upon successful authentication and assertion mapping an\n unscoped token is returned and stored within the plugin object for\n further use.\n\n :param session : a session object to send out HTTP requests.\n :type session: keystoneclient.session.Session\n\n :return access.AccessInfoV3: an object with scoped token's id and\n unscoped token json included.\n\n \"\"\"\n token, token_json = self._get_unscoped_token(session, **kwargs)\n return access.AccessInfoV3(token,\n **token_json)\n","sub_path":"horizon-new/virtualenv/lib/python2.6/site-packages/keystoneclient/contrib/auth/v3/saml2.py","file_name":"saml2.py","file_ext":"py","file_size_in_byte":17073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"420486151","text":"#%%:\nimport sys\n# sys.path.append(\"/Users/tkuhar/X.Teams/module_1/pitcoin\")\nfrom serializer import Deserializer\nimport tx_valiadtor\nimport transaction\nimport os.path\nimport json\n\n\n#%%:\ndef add_tx(s):\n t = Deserializer.deserialize(s)\n tx_valiadtor.check_tx(t)\n with open((os.path.abspath(\".\") + \"/mempool\"), 'a+') as f:\n f.write(f\"{s}\\n\")\n f.close()\n\n\n#%%:\ndef get_last_tx():\n with open(\"mempool\", 'r') as s:\n quee = s.readlines()\n result = [i.rstrip() for i in quee[0:3]]\n s.close()\n with open(\"mempool\", 'w') as s:\n s.writelines(quee[3:])\n s.close()\n return result\n","sub_path":"module-2-tkuhar/pending_pool.py","file_name":"pending_pool.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"377464690","text":"__author__ = 'chinaoppo'\nimport Proxy\nimport re\nimport re\nimport ConvertHelper\n# coding=utf-8\nclass ProxyAnalyze:\n def ConvertProxyDto(self,ipProxyHtml):\n part= re.search(r'.*',ipProxyHtml,re.M)\n if part:\n arr=part.lastindex\n else:\n pass\n def ReadProxyHtml(self,htmlPath):\n txt= ConvertHelper.ConvertHelper()\n return txt.ReadHtml(htmlPath)\n def ConvertDataModeByString(self,html):\n format=html.replace('\\n','')\n tab=self.SpilderTable(format) # get table node\n return self.SpilderRowData(tab[0]) #get the body\n def SpilderTable(self,html):\n regex=r'(.*?)'\n return re.findall(regex,html)\n def SpilderRowData(self,row):\n r= row.strip()\n bf=r'(.*?)'\n body= re.findall(bf,r)\n if(len(body)==0):\n return\n #spilder the data row\n rowf=r'(.*?)'\n trs= re.findall(rowf,body[0]) #the is row data\n if(len(trs)==0):\n return\n items=[]\n regex=r'')[1]\n ip.Port=cols[1].split('>')[1]\n ip.Cryptonym=cols[2].split('>')[1]\n ip.IP_Http_Type=cols[3].split('>')[1]\n ip.IPAddress=cols[4].split('>')[1]\n ip.IPResponseSpleed=cols[5].split('>')[1]\n ip.Last_Valid_Time=cols[6].split('>')[1]\n ip.GenerateId()\n ip.ConvertIpInt()\n rows.append(ip)\n return rows\n def GetPageToolBar(self,html):\n pages=[]\n #从分页栏中提取当前页和总页数\n text=html.replace(\"\\n\",\"\")\n tool=\"listnav\\\">(.*?)(.*?)\"\n lis= re.findall(lir,ps)\n pageReg=\">(.*?)<\"\n cur=re.findall(active,ps)\n totals=lis[len(lis)-2]\n total=re.findall(pageReg,totals)\n pages.append(int(cur[0]))\n pages.append(int(total[1]))\n return pages","sub_path":"INeedPython/ProxyAnalyzeManage.py","file_name":"ProxyAnalyzeManage.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76313915","text":"#!/Anaconda3/python\n# storytime\n\n\"\"\"\ndescription\n\"\"\"\n\nimport numpy as np\n\nfrom enum import Enum\nfrom copy import deepcopy\nfrom collections import OrderedDict\n\nfrom .utils import equality_of\nfrom .utils import prepare_ndarray\nfrom .utils import prepare_object\nfrom .utils import append\n\n\n\n#----------------------------------------------------------------------------------------------#\n# Discrete Spatial data\n\n\n#----------------------------------------------------------------------------------------------#\n\nclass EdgeColorBase( Enum ) :\n pass\n\n\nclass __EdgeColor(EdgeColorBase):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\nclass Symmetry(Enum): # Unused\n NONE = 0\n POSITIVE = 1\n NEGATIVE = -1\n\n#####################\n\nclass Edge :\n \"\"\"\n source and destination are indices into the hosting Network's node array\n color can be used to define overlapping subnetworks\n symmetry = 0 - directed [a->b]\n symmetry = 1 - symmetric [a<>b]\n symmetry = -1 - antisymmetric [a>\"\n elif self.symmetry == 1 :\n string += \"<>\"\n elif self.symmetry == -1 :\n string += \"><\"\n else:\n raise ValueError(\"Edge.symmetry must be in (0, -1, 1)\", self.symmetry)\n string += \" \"+ str( self.destination ) + \"]\"\n\n if self.weight != 1.0:\n string += \" w=\"+str( self.weight )\n\n if self.color is not None :\n string += \" \" + str( self.color )\n\n string += \">\"\n return string\n\n\n#----------------------------------------------------------------------------------------------#\n\nclass Node :\n \"\"\"A Network node with a value that can be used to store the entity_id\"\"\"\n\n def __init__( self,\n index: int = None,\n value = None,\n edges: list = None\n ) :\n self.index = index\n self.value = value\n self.edges = prepare_ndarray( edges ) # ToDo: store edge.index instead\n\n\n ###\n def __str__( self ) :\n string = \" 0:\n string += \" x\" + str( len( self.edges ))\n string += \">\"\n return string\n\n\n def add_edge( self, edge ) :\n \"\"\"record list of edges for quick lookup by node\"\"\"\n\n new_edge = deepcopy( edge )\n new_edge.index = len( self.edges )\n self.edges = append( self.edges, new_edge )\n\n\n#----------------------------------------------------------------------------------------------#\n\nNetwork = None # used by __add__\nclass Network :\n \"\"\"Node-graph with weighted and colored edges. Optional root node and symmetric edges\"\"\"\n\n def __init__( self,\n nodes: list = None,\n edges: list = None,\n root: int = None,\n symmetry:int = 0\n ):\n\n self._nodes = prepare_ndarray( nodes )\n self._edges = prepare_ndarray( edges )\n\n assert symmetry in (-1, 0, 1) and isinstance(symmetry, int)\n self.symmetry = symmetry\n self.root = root\n\n\n ###\n def __str__( self ) :\n string = \"\"\n return string\n\n @property\n def __dprint__( self ) :\n string = str(self)\n for node in self._nodes:\n string += \"\\n\" + str(node)\n for edge in self._edges :\n string += \"\\n\" + str( edge )\n return string\n\n\n def __add__(self, other_network:Network):\n \"\"\"produce the union of two disjoint networks\"\"\"\n # ToDo: NotImplemented\n\n offset = len( self._nodes )\n return self + other_network\n\n\n ###\n def add_node(self, value ) -> int :\n \"\"\"Create new node containing value with no edges\"\"\"\n\n new_node = Node( len( self._nodes ), value )\n self._nodes = append( self._nodes, new_node )\n return new_node.index\n\n\n def count_nodes( self ) :\n return len( self._nodes )\n\n\n def nodes(self):\n for node in self._nodes:\n yield node\n\n\n def node( self, node_id: int ) :\n return self._nodes[node_id]\n\n\n ###\n def add_edge( self, edge:Edge ) -> int :\n \"\"\"Add an new_edge between two existing nodes\"\"\"\n\n new_edge = deepcopy( edge )\n new_edge.symmetry = self.symmetry\n\n # add to self\n new_edge.index=len( self._edges )\n self._edges = deepcopy( append( self._edges, new_edge ) )\n\n # add to nodes\n if self.symmetry != 0 and (new_edge.source != new_edge.destination) :\n new_edge.symmetry = 0 # edges keep track of symmetry only when used by networks\n self.node(new_edge.destination).add_edge( new_edge )\n self.node(new_edge.source).add_edge( new_edge )\n\n return new_edge.index\n\n\n def count_edges( self, *colors:[EdgeColorBase] ) :\n return len( list( self.edges( *colors ) ) )\n\n\n def edges( self, *colors:[EdgeColorBase] ):\n for edge in self._edges:\n if edge.color in colors \\\n or edge.color is None and len(colors) == 0 :\n yield edge\n\n\n ###\n def to_csr_matrix(self, colors: [EdgeColorBase] ):\n if colors is None: # all edges\n return _edges_to_csr_matrix( self._edges, len( self._nodes ) )\n else: # filter edges to matching colors. [None] matches color==None\n return _edges_to_csr_matrix( self.edges( *colors ), len( self._nodes ) )\n\n\n#----------------------------------------------------------------------------------------------#\n\nfrom scipy.sparse import csr_matrix\n\ndef addition(a,b): return a+b\ndef multiplication( a, b ) : return a*b\n\ndef _edges_to_csr_matrix( edges:[Edge],\n node_count:int,\n stacking_operator = addition,\n allow_zero = False\n ) -> (csr_matrix, bool):\n \"\"\"\n Used to produce the csr_matrix from an arbitrary list of edges\n stacking_operator determines the function for combining two edges with the same position\n if negative distances cause 0 weight on a node, remove the entire connection\n has_negative is used by GraphMatrix to pick a distance algorithm\n \"\"\"\n\n row = []\n col = []\n data = []\n has_negative = False\n\n edge_dict = OrderedDict()\n\n for edge in edges:\n position = (edge.source, edge.destination)\n edge_dict[position] = stacking_operator( edge_dict.get( position, 0 ), edge.weight )\n\n if edge.symmetry != 0: # add (anti)symmetric partner\n coposition = (edge.destination, edge.source)\n new_weight = edge.weight * edge.symmetry\n edge_dict[coposition] = stacking_operator( edge_dict.get( coposition, 0 ), new_weight )\n\n for ((source, destination), weight) in edge_dict.items():\n if weight < 0:\n has_negative = True\n elif allow_zero is False and weight == 0:\n continue\n\n row.append( source )\n col.append( destination )\n data.append( weight )\n\n # print( \"row\", row )\n # print( \"col\", col )\n # print( \"data\", data )\n\n matrix = csr_matrix( (data, (row, col)), shape=(node_count, node_count) )\n return matrix, has_negative\n\n\n#----------------------------------------------------------------------------------------------#\n\nfrom scipy.sparse.csgraph import connected_components\nfrom scipy.sparse.csgraph import dijkstra\nfrom scipy.sparse.csgraph import bellman_ford\nfrom scipy.sparse import find\n\nclass GraphMatrix :\n \"\"\"\n GraphMatrix( ) - empty 0x0 matrix\n GraphMatrix( Network ) - combine all edges\n GraphMatrix( Network, [EdgeColorBase] ) - filter to listed colors, [None] for color==None\n GraphMatrix( [Edge], int ) - list of edges, node_count\n GraphMatrix( csr_matrix, bool ) - assign as-is\n \"\"\"\n\n def __init__( self, arg1=None, arg2=None ) :\n\n self._connected_components = { 'value' : None, 'args' : None, 'kwargs' : None }\n self._distance_matrix = { 'value' : None, 'args' : None, 'kwargs' : None }\n\n self._has_negative = False\n self._matrix = None\n if arg2 is None:\n if arg1 is None: # ()\n self._matrix = csr_matrix( [] )\n\n elif isinstance( arg1, Network ) : # (network)\n (self._matrix, self._has_negative) = arg1.to_csr_matrix( None )\n\n else:\n raise TypeError( \"Invalid arguments: \" + str( arg1 ) + \", \" + str( arg2 ) )\n\n elif isinstance( arg1, Network ) : # (network, [colors])\n (self._matrix, self._has_negative) = arg1.to_csr_matrix( arg2 )\n\n elif hasattr( arg1, \"__iter__\" ) : # ([edges], node_count)\n (self._matrix, self._has_negative) = _edges_to_csr_matrix( arg1, arg2 )\n\n elif isinstance( arg1, csr_matrix ) : # (matrix, has_negative)\n self._matrix = arg1\n self._has_negative = arg2\n\n else:\n raise TypeError(\"Invalid arguments: \" +str(arg1)+\", \"+ str(arg2))\n\n\n def __str__(self):\n string = str( self._matrix )\n return string\n\n @property\n def __dprint__(self):\n string = \"\"\n for (i, j, v) in self.edges( ) :\n string += \"edge: [\" + str( i ) + \", \" + str( j ) + \"] \" + str( v ) +\"\\n\"\n return string\n\n\n def toarray(self, *args, **kwargs) -> np.ndarray:\n return self._matrix.toarray( *args, **kwargs )\n\n\n def edges( self ) -> [(int, int, int)]:\n \"\"\"sparse list of non-zero edges -> [(row, col, weight),...]\"\"\"\n\n (row, col, data) = find( self._matrix )\n for i in range(0, len(data)) :\n yield ( row[i], col[i], data[i] )\n\n\n ###\n def connected_components(self,*args,**kwargs):\n \"\"\"compute connectedness, cache results\"\"\"\n\n if self._connected_components['value'] is None \\\n or self._connected_components['args'] != args \\\n or self._connected_components['kwargs'] != kwargs :\n self._connected_components['args'] = args\n self._connected_components['kwargs'] = kwargs\n self._connected_components['value'] = connected_components( self._matrix, *args, **kwargs )\n return self._connected_components['value']\n\n\n def distance_matrix(self,*args,**kwargs):\n \"\"\"compute distance matrix using an appropriate algorithm, cache results\"\"\"\n\n if self._distance_matrix['value'] is None \\\n or self._distance_matrix['args'] != args \\\n or self._distance_matrix['kwargs'] != kwargs :\n self._distance_matrix['args'] = args\n self._distance_matrix['kwargs'] = kwargs\n if self._has_negative :\n self._distance_matrix['value'] = bellman_ford( self._matrix, *args, **kwargs )\n else:\n self._distance_matrix['value'] = dijkstra( self._matrix, *args, **kwargs )\n return self._distance_matrix['value']\n\n\n def distance(self, source:int, destination:int):\n return self.distance_matrix(source, destination)\n\n\n#----------------------------------------------------------------------------------------------#\n#----------------------------------------------------------------------------------------------#\n\nfrom collections import deque\nclass BKTree :\n \"\"\"\n http://signal-to-noise.xyz/post/bk-tree/\n \"\"\"\n def __init__( self, metric ) :\n self._root = None\n self._metric = metric\n\n def add( self, node ) :\n if self._root is None :\n self._root = (node, { })\n return\n\n current, children = self._root\n while True :\n dist = self._metric( node, current )\n target = children.get( dist )\n if target is None :\n children[dist] = (node, { })\n break\n current, children = target\n\n def search( self, node, radius ) :\n if self._root is None :\n return []\n\n candidates = deque( [self._root] )\n result = []\n while candidates :\n candidate, children = candidates.popleft( )\n dist = self._metric( node, candidate )\n if dist <= radius :\n result.append( (dist, candidate) )\n\n low, high = dist - radius, dist + radius\n candidates.extend( c for d, c in children.items( )\n if low <= d <= high )\n return result\n\n\n#----------------------------------------------------------------------------------------------#\n","sub_path":"examples/exp/graph2.py","file_name":"graph2.py","file_ext":"py","file_size_in_byte":13725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380851557","text":"import os\nenv = {\n 'LISTEN_PORT': 8001,\n 'LISTEN_HOST': \"0.0.0.0\",\n 'HOME_DIR': os.path.dirname( os.path.realpath( __file__ ) ),\n 'VIRTUALENV_DIR': os.path.dirname( os.path.realpath( __file__ ) ) + \"/env/lib/python2.7/site-packages\",\n 'SESSION_KEY': 'ds92d200-56f0-5002-9f7b-a6c9fe99006e',\n \n # Redis\n 'REDIS_HOST': 'localhost',\n 'REDIS_PORT': '6379',\n 'REDIS_DB': 3,\n \n # Mongo DB\n 'MONGODB_HOST' : 'localhost',\n 'MONGODB_DATABASE' : 'dojono',\n 'MONGODB_REPLICA_SET': None,\n \n # Celery\n 'CELERY_BROKER': 'redis://localhost:6379/3',\n 'CELERY_BACKEND': 'redis://localhost:6379/3',\n 'CELERY_TASK_RESULT_EXPIRES': 1440,\n 'CELERY_DEFAULT_QUEUE': 'amp_api_requests',\n\n # Slack\n 'SLACK_TOKEN': 'SLACK_API_BOT_TOKEN',\n 'RTM_READ_DELAY': 1,\n 'SLACK_BOT_ID': 'UBW91DW13',\n\n # Snips-nlu config\n 'SNIPS_CONFIG': 'snips_analysis.json',\n\n # Jenkins config\n 'JENKINS_USERNAME': 'glenn',\n 'JENKINS_PASSWORD': '11e385d8e8cd6cac4ededb1d52f1f3e5',\n 'JENKINS_HOST': 'http://dj-admin01:8080',\n\n # Dojono Jenkins/git related data for repo commands\n 'CREATE_VANILLA_WEBSITE': 'create-vanilla-site',\n 'DEPLOY_APACHE_CONFIG': 'deploy apache config',\n 'MAX_JOB_CHECK_COUNT': 200,\n 'DELAY_BETWEEN_JENKINS_CHECKS': 30,\n}\n\n","sub_path":"local_settings.py","file_name":"local_settings.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404963052","text":"import pytest\nfrom func_adl_xAOD.cms.aod import isNonnull\nfrom tests.cms.aod.utils import cms_aod_dataset # type: ignore\nfrom tests.utils.general import get_lines_of_code, print_lines # type: ignore\nfrom tests.utils.locators import (find_line_with, # type: ignore\n find_next_closing_bracket)\n\n\n# Tests that make sure the cms aod executor is working correctly\nclass CMS_AOD_File_Type:\n def __init__(self):\n pass\n\n\ndef test_Select_member_variable():\n r = cms_aod_dataset() \\\n .SelectMany(lambda e: e.Muons(\"muons\")) \\\n .Select(lambda m: m.pfIsolationR04().sumChargedHadronPt) \\\n .value()\n lines = get_lines_of_code(r)\n _ = find_line_with(\".sumChargedHadronPt\", lines)\n assert find_line_with(\".sumChargedHadronPt()\", lines, throw_if_not_found=False) == -1\n\n\ndef test_complex_dict():\n 'Seen to fail in the wild, so a test case to track'\n r = cms_aod_dataset() \\\n .Select(lambda e: {\"muons\": e.Muons(\"muons\"), \"primvtx\": e.Vertex(\"offlinePrimaryVertices\")}) \\\n .Select(lambda i: i.muons\n .Where(lambda m: isNonnull(m.globalTrack()))\n .Select(lambda m: m.globalTrack().dx(i.primvtx[0].position()))\n ) \\\n .value()\n lines = get_lines_of_code(r)\n print_lines(lines)\n\n find_line_with(\"globalTrack()->dx\", lines)\n find_line_with(\"at(0).position()\", lines)\n\n\ndef test_2nd_order_lookup():\n 'Seen in the wild to generate an out-of-scope error'\n r = (cms_aod_dataset()\n .Select(lambda e: {\"m\": e.Muons(\"muons\"), \"p\": e.Vertex(\"offlinePrimaryVertices\")[0].position()})\n .Select(lambda i:\n i.m\n .Where(lambda m: m.isPFMuon()\n and m.isPFIsolationValid()\n and isNonnull(m.globalTrack())\n and abs((m.globalTrack()).dxy(i.p)) < 0.5\n and abs((m.globalTrack()).dz(i.p)) < 1.\n )\n .Select(lambda m: m.p()),\n )\n .value()\n )\n\n lines = get_lines_of_code(r)\n print_lines(lines)\n\n # Make sure the vertex line isn't used after it goes out of scope\n vertex_decl_line = find_line_with('edm::Handle', lines)\n\n vertex_variable_name = lines[vertex_decl_line].split(' ')[-1].strip(';')\n\n closing_scope = find_next_closing_bracket(lines[vertex_decl_line:])\n vertex_used_too_late = find_line_with(vertex_variable_name, lines[vertex_decl_line + closing_scope:], throw_if_not_found=False)\n if vertex_used_too_late != -1:\n print('Here is where it is used and down')\n print_lines(lines[closing_scope + vertex_decl_line + vertex_used_too_late:])\n assert vertex_used_too_late == -1\n\n\ndef test_metadata_collection():\n 'This is integration testing - making sure the dict to root conversion works'\n r = (cms_aod_dataset()\n .MetaData({\n 'metadata_type': 'add_cms_aod_event_collection_info',\n 'name': 'ForkVertex',\n 'include_files': ['DataFormats/VertexReco/interface/Vertex.h'],\n 'container_type': 'reco::VertexCollection',\n 'contains_collection': True,\n 'element_type': 'reco::Vertex',\n 'element_pointer': False,\n })\n .Select(lambda e: e.ForkVertex(\"EventInfo\").Count())\n .Select(lambda e: {'run_number': e})\n .value())\n vs = r.QueryVisitor._gc._class_vars\n assert 1 == len(vs)\n assert \"int\" == str(vs[0].cpp_type())\n\n\ndef test_metadata_collection_bad_experiment():\n 'This is integration testing - making sure the dict to root conversion works'\n with pytest.raises(ValueError) as e:\n (cms_aod_dataset()\n .MetaData({\n 'metadata_type': 'add_atlas_event_collection_info',\n 'name': 'ForkInfo',\n 'include_files': ['xAODEventInfo/EventInfo.h'],\n 'container_type': 'xAOD::EventInfo',\n 'contains_collection': False,\n })\n .Select(lambda e: e.ForkInfo(\"EventInfo\").runNumber())\n .Select(lambda e: {'run_number': e})\n .value())\n\n assert \"backend; only\" in str(e.value)\n","sub_path":"tests/cms/aod/test_aod_executor.py","file_name":"test_aod_executor.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"536564939","text":"from __future__ import print_function, absolute_import\n\nimport os\nimport random\nimport yaml\n\nfrom src.utils.logger import get_logger\nfrom src.utils.utils import timeit\n\nlogger = get_logger()\n\nclass ConfigLoader(object):\n def __init__(self, test=False):\n if test or not os.path.isfile('config/info.yaml'):\n with open('config/info_template.yaml', 'r') as f:\n infos = yaml.load(f)\n\n logger.debug('Testing mode, using template data.')\n else:\n with open('config/info.yaml', 'r') as f:\n infos = yaml.load(f)\n logger.warn('Not in test mode. Use true data. Make sure this is what you want.')\n\n accout = random.choice(infos.keys())\n self._info = infos[accout]\n\n @property\n def info(self):\n return self._info\n\n @property\n def order_info(self):\n keys = [\n 'billing_name', 'email', 'tel', 'billing_address', 'billing_address_2',\n 'billing_zip',\n # 'billing_city', 'billing_state', 'billing_country'\n ]\n return [(k, self.info[k]) for k in keys]\n\n @property\n def cc_info(self):\n keys = ['nlb', 'month', 'year', 'rvv']\n return [(k, self.info[k]) for k in keys]\n\n\nif __name__ == '__main__':\n cl = ConfigLoader()\n order_info = cl.order_info\n cc_info = cl.cc_info","sub_path":"src/config_loader.py","file_name":"config_loader.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635063557","text":"import tkinter\nimport view\nimport model\n\nclass Controller:\n \"\"\"\n Controller at the center of the MVC temperature conversion application, which converts a user input float to celsius or fahrenheit\n \"\"\"\n def __init__(self):\n \"\"\"\n Initializes MVC components\n \"\"\"\n root = tkinter.Tk()\n root.wm_title(\"Temperature Converter\")\n self.model = model.Model()\n self.view = view.View(self)\n self.view.mainloop()\n root.destroy()\n\n def celsiusToFahrenheit(self):\n \"\"\"\n Interprets user input to text field as celsius and converts to equivalent fahrenheit temperature\n \"\"\"\n resultTemperature = \"\"\n try:\n celsius = float(self.view.enterTemperature.get())\n except:\n resultTemperature = \"Not a number!\"\n else:\n resultTemperature = str(self.model.celsiusToFahrenheit(celsius))\n self.view.outputLabel[\"text\"] = resultTemperature\n\n def fahrenheitToCelsius(self):\n \"\"\"\n Interprets user input to text field as fahrenheit and converts to equivalent celsius temperature\n \"\"\"\n resultTemperature = \"\"\n try:\n fahrenheit = float(self.view.enterTemperature.get())\n except:\n resultTemperature = \"Not a number!\"\n else:\n resultTemperature = str(self.model.fahrenheitToCelsius(fahrenheit))\n self.view.outputLabel[\"text\"] = resultTemperature\n\nif __name__ == \"__main__\":\n print(\"Doin some mvc temp converting\")\n c = Controller()\n","sub_path":"CS21A/wk10/hw/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"38023586","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Author: Jeremy Parks\n# Note: Requires Python 3.3.x or higher\n\nfrom collections import defaultdict\n\nimport requests\nimport cfscrape\nfrom io import open\nfrom datetime import datetime\nimport time\nimport re\nfrom pymongo import MongoClient\nfrom statistics import mean, stdev\nimport os\n\nfrom auto_gen import currencyrates\nfrom auto_gen import hccurrencyrates\nfrom auto_gen import pcurrencyrates\nfrom auto_gen import phccurrencyrates\n\nheader = '''#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Created: {} UTC from \"{}\" data\n'''\n\n\n# Calculate chaos equiv based on league\ndef chaosequiv(cost, unit, league):\n\tif league == 'Standard':\n\t\treturn cost * currencyrates.items[unit]\n\telif league == 'Hardcore':\n\t\treturn cost * hccurrencyrates.items[unit]\n\telif 'Hardcore' in league:\n\t\treturn cost * phccurrencyrates.items[unit]\n\telse:\n\t\treturn cost * pcurrencyrates.items[unit]\n\n\n# Update chaos equiv on items based on league\ndef updatechaosequiv(ldb):\n\tprint('Starting update of existing data')\n\tcount = ldb.items.count()\n\tsteps = 199\n\tthresholds = [i*count//steps for i in range(steps)]\n\tfor c, i in enumerate(ldb.items.find()):\n\t\tif c in thresholds:\n\t\t\tprint('{:.2f}% done'.format(c/count*100))\n\t\tldb.items.update({'_id': i['_id']}, {'$set': {'chaosequiv': chaosequiv(i['cost'], i['unit'], i['league'])}})\n\tprint('Finished updating existing data')\n\n\n# Add current data to the ldb\ndef adddata(nextchange, remove, add, ldb):\n\tprint(\"Adding {} items. Updating {} tabs.\".format(len(add), len(remove)))\n\n\t# Remove items that have a stash tab that matches this update\n\tif remove:\n\t\tldb.items.delete_many({'tabid': {'$in': remove}})\n\n\t# Insert our new data\n\tif add:\n\t\tldb.items.insert_many(add)\n\n\t# Update Next ID now that we are done with this one\n\tldb.key.update_one({}, {'$set': {'next': nextchange}}, True)\n\n\n# Retrieve Stash Tab API data from GGG\ndef get_stashes(ldb, requester,start=None):\n\tif not start:\n\t\tif 'key' in ldb.collection_names():\n\t\t\tstart = ldb.key.find_one()['next']\n\n\tif start:\n\t\turl = 'https://www.pathofexile.com/api/public-stash-tabs?id={}'.format(start)\n\telse:\n\t\turl = 'https://www.pathofexile.com/api/public-stash-tabs'\n\n\tprint(\"Starting {}\".format(url))\n\treq = requester.get(url)\n\tmybytes = len(req.content)/1000000 # Assume digital storage 1mB=1000kB=1000000B\n\tprint(\"{:.2f} MegaBytes received\".format(mybytes))\n\n\tdata = req.json(encoding='utf-8')\n\n\tnextchange = \"\"\n\tremove = []\n\tadd = []\n\tkeys = {}\n\tfor i in data:\n\t\tif 'stashes' == i:\n\t\t\tfor ii in data[i]:\n\t\t\t\tremove.append(ii['id'])\n\t\t\t\tif 'items' in ii and ii['items']:\n\t\t\t\t\tfor iii in ii['items']:\n\t\t\t\t\t\t# Why is SSF data in the stash tab river again?\n\t\t\t\t\t\tif \"SSF\" in iii['league']:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif iii['frameType'] in [3, 6]:\n\t\t\t\t\t\t\tnote = \"\"\n\t\t\t\t\t\t\tif 'note' in iii and ('~b/o' in iii['note'] or '~price' in iii['note']):\n\t\t\t\t\t\t\t\tnote = iii['note']\n\t\t\t\t\t\t\telif 'stash' in ii and ii['stash'] and ('~b/o' in ii['stash'] or '~price' in ii['stash']):\n\t\t\t\t\t\t\t\tnote = ii['stash']\n\t\t\t\t\t\t\t\tkeys[ii['stash']] = True\n\t\t\t\t\t\t\tif note:\n\t\t\t\t\t\t\t\tprice = re.search(r'(~b/o|~price) (-?\\d*(\\.\\d+)?) (silver|vaal|jew|chrom|alt|jewel|chance|chisel|cartographer|fuse|fusing|alch|scour|blessed|chaos|regret|regal|gcp|gemcutter|divine|exalted|exa|ex|mirror)', note.lower())\n\t\t\t\t\t\t\t\tif price and price.group(2):\n\t\t\t\t\t\t\t\t\tif float(price.group(2)) >= 0:\n\t\t\t\t\t\t\t\t\t\tunit = price.group(4)\n\t\t\t\t\t\t\t\t\t\tif unit in ['exalted', 'ex']:\n\t\t\t\t\t\t\t\t\t\t\tunit = 'exa'\n\t\t\t\t\t\t\t\t\t\telif unit in ['fusing']:\n\t\t\t\t\t\t\t\t\t\t\tunit = 'fuse'\n\t\t\t\t\t\t\t\t\t\tadd.append({'type': iii['frameType'], 'league': iii['league'], 'base': iii['typeLine'].replace(\"Superior \", \"\"), 'cost': float(price.group(2)), 'unit': unit, 'tabid': ii['id'], 'ids': iii['id'], 'chaosequiv': chaosequiv(float(price.group(2)), unit, iii['league'])})\n\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\twith open('erroritems.txt', 'a', encoding='utf-8') as f:\n\t\t\t\t\t\t\t\t\t\tf.write(u\"{} *** {}\\n\".format(note, {'type': iii['frameType'], 'league': iii['league'], 'base': iii['typeLine'], 'tabid': ii['id'], 'ids': iii['id']}))\n\t\telif 'next_change_id' == i:\n\t\t\tnextchange = data[i]\n\t\telse:\n\t\t\traise ValueError(\"Invalid JSON data returned: {}\".format(i))\n\n\tadddata(nextchange, remove, add, ldb)\n\n\t# Stop updating if we get less than 50 new tabs as we don't need the absolute most current data\n\tif len(remove) > 50:\n\t\treturn nextchange, mybytes\n\telse:\n\t\treturn start, mybytes\n\n\ndef gen_lists(ldb):\n\tleague = ldb.items.distinct('league')\n\n\tres = ldb.items.aggregate([\n\t\t{'$group': {\n\t\t\t'_id': {\n\t\t\t\t'league': '$league',\n\t\t\t\t'base': '$base',\n\t\t\t\t'type': '$type'\n\t\t\t},\n\t\t\t'value': {'$push': '$chaosequiv'}\n\t\t}},\n\t\t{'$unwind': '$value'},\n\t\t{'$sort': {'value': 1}},\n\t\t{'$group': {'_id': '$_id', 'value': {'$push': '$value'}}},\n\t\t{'$project': {\n\t\t\t'_id': 1,\n\t\t\t'value': {'$arrayElemAt': ['$value', {'$floor': {'$multiply': [0.25, {'$size': '$value'}]}}]}\n\t\t}}\n\t], allowDiskUse=True)\n\n\tdata = {league[0]: defaultdict(dict), league[1]: defaultdict(dict), league[2]: defaultdict(dict), league[3]: defaultdict(dict)}\n\n\tfor i in res:\n\t\tdata[i['_id']['league']][i['_id']['type']][i['_id']['base']] = i['value']\n\n\t# If Div card doesn't exist in league market copy from Standard league\n\t# This is mostly for fresh leagues\n\tother = league[:]\n\tother.remove('Standard')\n\tfor ind in other:\n\t\tfor card in data['Standard'][6]:\n\t\t\tif card not in data[ind][6]:\n\t\t\t\tprint(\"{}: {}\".format(ind, card))\n\t\t\t\tdata[ind][6][card] = data['Standard'][6][card]\n\t# Same thing as cards but for uniques\n\tfor unique in data['Standard'][3]:\n\t\tfor ind in other:\n\t\t\tif unique not in data[ind][3]:\n\t\t\t\tdata[ind][3][unique] = data['Standard'][3][unique]\n\n\tsubstringcards = find_substrings(ldb)\n\n\t# Cards that are so rare they may not even be on Standard\n\tverygoodcards = ['House of Mirrors']\n\n\t# Cards that will never be displayed\n\tbadcards = [\"The Carrion Crow\",\n\t\t\t\t\"The King's Blade\",\n\t\t\t\t\"The Inoculated\",\n\t\t\t\t\"Turn the Other Cheek\"]\n\n\t# Cards that won't make a drop noise\n\tlowcards = [\"Thunderous Skies\",\n\t\t\t\t\"The Rabid Rhoa\",\n\t\t\t\t\"The Surgeon\",\n\t\t\t\t\"The Twins\",\n\t\t\t\t\"The Scholar\",\n\t\t\t\t\"Destined to Crumble\"]\n\n\tpredefinedcards = badcards + lowcards + substringcards + verygoodcards\n\n\tfor l in data.keys():\n\t\tbcards = badcards[:]\n\t\tif l == 'Standard':\n\t\t\tname = \"\"\n\t\telif l == 'Hardcore':\n\t\t\tname = \"hc\"\n\t\telif 'Hardcore' in l:\n\t\t\tname = \"phc\"\n\t\telse:\n\t\t\tname = \"p\"\n\t\titems = {'very high': [], 'high': [], 'low': []}\n\n\t\tfor u in data[l][3].keys():\n\n\t\t\tif data[l][3][u] >= chaosequiv(1, 'exa', l):\n\t\t\t\titems['very high'].append(u)\n\t\t\telif data[l][3][u] >= chaosequiv(.2, 'exa', l):\n\t\t\t\titems['high'].append(u)\n\t\t\telif data[l][3][u] < 0.5:\n\t\t\t\titems['low'].append(u)\n\n\t\twith open('auto_gen\\\\{}uniques.py'.format(name), 'w', encoding='utf-8') as f:\n\t\t\tf.write(u'''{}\\ndesc = \"Unique\"\\n\\n# Base type : settings pair\\nitems = {{\\n'''.format(header.format(datetime.utcnow().strftime('%m/%d/%Y(m/d/y) %H:%M:%S'), l)))\n\t\t\tfor ii in sorted(items['very high']):\n\t\t\t\tf.write(u'\\t\"0 {0}\": {{\"base\": \"{0}\", \"type\": \"unique very high\"}},\\n'.format(ii))\n\t\t\tfor ii in sorted(items['high']):\n\t\t\t\tf.write(u'\\t\"1 {0}\": {{\"base\": \"{0}\", \"type\": \"unique high\"}},\\n'.format(ii))\n\t\t\tfor ii in sorted(items['low']):\n\t\t\t\tf.write(u'\\t\"7 {0}\": {{\"base\": \"{0}\", \"type\": \"unique low\"}},\\n'.format(ii))\n\t\t\tf.write(u'\\t\"9 Other uniques\": {\"type\": \"unique normal\"}\\n}\\n')\n\n\t\titems = {'high': verygoodcards[:], 'normal': [], 'low': lowcards[:]}\n\t\tfor card in substringcards:\n\t\t\tif card in items['low']:\n\t\t\t\titems['low'].remove(card)\n\t\tfor c in data[l][6]:\n\t\t\tif c in predefinedcards:\n\t\t\t\tpass\n\t\t\telif data[l][6][c] > chaosequiv(.2, 'exa', l):\n\t\t\t\titems['high'].append(c)\n\t\t\telif data[l][6][c] > chaosequiv(.035, 'exa', l):\n\t\t\t\titems['normal'].append(c)\n\t\t\telif data[l][6][c] < 0.5:\n\t\t\t\titems['low'].append(c)\n\t\twith open('auto_gen\\\\{}divination.py'.format(name), 'w', encoding='utf-8') as f:\n\t\t\tf.write(u'''{}\\ndesc = \"Divination Card\"\\n\\n# Base type : settings pair\\nitems = {{\\n'''.format(header.format(datetime.utcnow().strftime('%m/%d/%Y(m/d/y) %H:%M:%S'), l)))\n\t\t\tfor c, ii in enumerate(substringcards):\n\t\t\t\tif ii in bcards:\n\t\t\t\t\tlvl = 'hide'\n\t\t\t\t\tbcards.remove(ii)\n\t\t\t\telif data[l][6][ii] > chaosequiv(.2, 'exa', l):\n\t\t\t\t\tlvl = 'divination very high'\n\t\t\t\telif data[l][6][ii] > chaosequiv(.035, 'exa', l):\n\t\t\t\t\tlvl = 'divination high'\n\t\t\t\telif data[l][6][ii] < 0.5:\n\t\t\t\t\tlvl = 'divination low'\n\t\t\t\telse:\n\t\t\t\t\tlvl = 'divination normal'\n\t\t\t\tf.write(u'\\t\"{0:03d} {1}\": {{\"base\": \"{1}\", \"class\": \"Divination Card\", \"type\": \"{2}\"}},\\n'.format(c, ii, lvl))\n\t\t\tfor ii in sorted(items['high']):\n\t\t\t\tf.write(u'\\t\"1 {0}\": {{\"base\": \"{0}\", \"class\": \"Divination Card\", \"type\": \"divination very high\"}},\\n'.format(ii))\n\t\t\tfor ii in sorted(items['normal']):\n\t\t\t\tf.write(u'\\t\"2 {0}\": {{\"base\": \"{0}\", \"class\": \"Divination Card\", \"type\": \"divination high\"}},\\n'.format(ii))\n\t\t\tfor ii in sorted(items['low']):\n\t\t\t\tf.write(u'\\t\"3 {0}\": {{\"base\": \"{0}\", \"class\": \"Divination Card\", \"type\": \"divination low\"}},\\n'.format(ii))\n\t\t\tfor ii in sorted(bcards):\n\t\t\t\tf.write(u'\\t\"7 {0}\": {{\"base\": \"{0}\", \"class\": \"Divination Card\", \"type\": \"hide\"}},\\n'.format(ii))\n\t\t\tf.write(u'\\t\"9 Other uniques\": {\"class\": \"Divination Card\", \"type\": \"divination normal\"}\\n}\\n')\n\n\ndef divuniqueupdate():\n\t# Make sure error file exists for invalid tab data\n\tfrom os.path import exists\n\tif not exists('erroritems.txt'):\n\t\topen('erroritems.txt', 'w')\n\n\twith MongoClient() as client:\n\t\tldb = client.stashdata\n\t\trequester = requests.session()\n\n\t\tnc = None\n\t\toldnc = nc\n\t\tmybytes = 0\n\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tnc, nmybytes = get_stashes(ldb, requester, nc)\n\t\t\t\tmybytes += nmybytes\n\t\t\t\tprint(\"{:.2f} Megabytes recieved so far(total)\".format(mybytes))\n\t\t\t\tif oldnc == nc:\n\t\t\t\t\tbreak\n\t\t\t\toldnc = nc\n\t\t\texcept ValueError as ve:\n\t\t\t\tprint(\"ValueError: {}\".format(ve))\n\t\t\t\ttime.sleep(61)\n\t\t\texcept TypeError as te:\n\t\t\t\tprint(\"TypeError: {}\".format(te))\n\t\t\t\ttime.sleep(61)\n\n\t\tgen_lists(ldb)\n\n\n# Find all divination cards that have cards which are substrings\ndef find_substrings(ldb):\n\tcardnames = ldb.items.distinct('base', {'type': 6})\n\n\tsubstringmatches = {}\n\tfor index in range(len(cardnames) - 1):\n\t\tfor card in cardnames[index + 1:]:\n\t\t\tif cardnames[index] in card or card in cardnames[index]:\n\t\t\t\tif card in cardnames[index]:\n\t\t\t\t\tsub, full = card, cardnames[index]\n\t\t\t\telse:\n\t\t\t\t\tsub, full = cardnames[index], card\n\t\t\t\tif sub not in substringmatches:\n\t\t\t\t\tsubstringmatches[sub] = [full]\n\t\t\t\telse:\n\t\t\t\t\tsubstringmatches[sub].append(full)\n\n\tbadcards = [badcards for substring in substringmatches for badcards in substringmatches[substring]]\n\t# distinct values by converting to a set\n\t# reverse sort in case any names such as \"a\", \"ab\", \"abc\" exist due to how Python sorts\n\treturn sorted(set(badcards), reverse=True)\n\n\n# Convert a currency value to a priority tier\n\n# Convert a currency shorthand to full name. returns a string\ndef convertshorttolongstr(cur, val, l, exa):\n\tif val >= exa * .5:\n\t\ttier = 'currency extremely high'\n\telif val >= 3:\n\t\ttier = 'currency very high'\n\telif val >= 0.95:\n\t\ttier = 'currency high'\n\telif val >= 1/8:\n\t\ttier = 'currency normal'\n\telse:\n\t\ttier = 'currency low'\n\t\n\tcurrency = {'divine': 'Divine Orb', 'regret': 'Orb of Regret', 'gcp': 'Gemcutter\\'s Prism', 'chaos': 'Chaos Orb', 'regal': 'Regal Orb',\n\t\t\t 'fuse': 'Orb of Fusing', 'blessed': 'Blessed Orb', 'scour': 'Orb of Scouring', 'alch': 'Orb of Alchemy', 'vaal': 'Vaal Orb',\n\t\t\t 'chisel': 'Cartographer\\'s Chisel', 'bauble': 'Glassblower\\'s Bauble', 'chance': 'Orb of Chance', 'jew': 'Jeweller\\'s Orb',\n\t\t\t 'chrom': 'Chromatic Orb', 'alt': 'Orb of Alteration', 'aug': 'Orb of Augmentation', 'transmute': 'Orb of Transmutation',\n\t\t\t 'perandus': 'Perandus Coin', 'silver': 'Silver Coin', 'apprenticecartosextant': 'Apprentice Cartographer\\'s Sextant',\n\t\t\t 'journeycartosextant': 'Journeyman Cartographer\\'s Sextant', 'mastercartosextant': 'Master Cartographer\\'s Sextant'}\n\n\n\tif cur in currency:\n\t\treturn \"0 {0}\\\": {{\\\"base\\\": \\\"{0}\\\", \\\"class\\\": \\\"Currency\\\", \\\"type\\\": \\\"{1}\\\"}}\".format(currency[cur], tier)\n\telse:\n\t\tprint(\"invalid input: {}, {}\".format(cur, l))\n\t\treturn None\n\n\n# Helper function to remove spurious data\ndef stddevcheck(duration, mean_calc, stdev_calc):\n\tif abs(duration - mean_calc) <= stdev_calc:\n\t\treturn True\n\treturn False\n\n\n# scrape poe.trade for currency exchange rates\ndef poetrade_getcurrencyrates():\n\tcurrencies = {\"exa\": 6, \"fuse\": 2, \"regal\": 14, \"alt\": 1, \"alch\": 3, \"jew\": 8, \"gcp\": 5,\n\t\t\t\t \"divine\": 15, \"scour\": 11, \"blessed\": 12, \"vaal\": 16, \"chance\": 9, \"regret\": 13, \"chrom\": 7,\n\t\t\t\t \"chisel\": 10, \"silver\": 35, \"bauble\": 21, \"aug\": 23, \"transmute\": 22, \"perandus\": 26,\n\t\t\t\t \"apprenticecartosextant\": 45, \"journeycartosextant\": 46, \"mastercartosextant\": 47}\n\n\n\tchaos = 4\n\n\tdefaults = {\"exa\": 45.0, \"chaos\": 1.0, \"fuse\": 0.5, \"regal\": 1, \"alt\": 1/16, \"alch\": 1/3, \"jew\": 1/8, \"gcp\": 1,\n\t\t\t\t\"divine\": 15.0, \"scour\": 0.5, \"blessed\": 0.5, \"vaal\": 1, \"chance\": 1/8, \"regret\": 1.0, \"chrom\": 1/15,\n\t\t\t\t\"mirror\": 4500.0, \"chisel\": 0.25, \"silver\": 1/3, \"bauble\": 1/8, \"aug\": 1/32, \"transmute\": 1/64, \"perandus\": 1/45,\n\t\t\t\t\"apprenticecartosextant\": .5, \"journeycartosextant\": 2, \"mastercartosextant\": 5}\n\n\twith MongoClient() as client:\n\t\tldb = client.stashdata\n\t\tleague = ldb.items.distinct('league')\n\n\t\tfor l in league:\n\t\t\tif l == 'Standard':\n\t\t\t\tname = \"\"\n\t\t\telif l == 'Hardcore':\n\t\t\t\tname = \"hc\"\n\t\t\telif 'Hardcore' in l:\n\t\t\t\tname = \"phc\"\n\t\t\telse:\n\t\t\t\tname = \"p\"\n\n\t\t\t# Populate ratios with amount currency is being bought for chaos\n\t\t\tbuyratios = [[] for _ in range(max(currencies.values()) + 1)]\n\t\t\tsellratios = [[] for _ in range(max(currencies.values()) + 1)]\n\t\t\turl = \"http://currency.poe.trade/search?league={}&online=x&want={}&have={}\".format(l, chaos, '-'.join([str(currencies[d]) for d in currencies]))\n\n\t\t\t# req = requests(url).text\n\t\t\tcfreq = cfscrape.create_scraper()\n\n\t\t\treq = cfreq.get(url).text\n\t\t\tfor i in (req.split('\\n')):\n\t\t\t\tif 'data-sellcurrency=\"4\"' in i:\n\t\t\t\t\tcrate = float(re.search(r'data-sellvalue=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\trtype = int(re.search(r'data-buycurrency=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\trrate = float(re.search(r'data-buyvalue=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\tsellratios[rtype].append(crate / rrate)\n\n\t\t\t# Populate ratios with amount of currency you can buy for a chaos\n\t\t\turl = \"http://currency.poe.trade/search?league={}&online=x&want={}&have={}\".format(l, '-'.join([str(currencies[d]) for d in currencies]), chaos)\n\t\t\treq = cfreq.get(url).text\n\t\t\tfor i in (req.split('\\n')):\n\t\t\t\tif 'data-buycurrency=\"4\"' in i:\n\t\t\t\t\tcrate = float(re.search(r'data-buyvalue=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\trtype = int(re.search(r'data-sellcurrency=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\trrate = float(re.search(r'data-sellvalue=\"(-?\\d*(\\.\\d+)?)\"', i.lower()).group(1))\n\t\t\t\t\tbuyratios[rtype].append(crate / rrate)\n\n\t\t\t# Generate our average prices shortlist\n\t\t\tratios = [[] for _ in range(max(currencies.values()) + 1)]\n\t\t\tfor currency in currencies:\n\t\t\t\t# ensure there is enough price data to generate a meaningful average\n\t\t\t\tif len(sellratios[currencies[currency]]) + len(buyratios[currencies[currency]]) > 8:\n\t\t\t\t\tvals = sorted(sellratios[currencies[currency]], reverse=True)[:5] + sorted(buyratios[currencies[currency]])[:5]\n\t\t\t\t\tvalstdev = stdev(vals)\n\t\t\t\t\tratios[currencies[currency]] = mean([i for i in vals if stddevcheck(i, mean(vals), valstdev)])\n\n\t\t\t# slice the highest someone will buy an orb from you and the lowest you would have to pay for an orb\n\t\t\t\t\t# ratios[currencies[currency]] = mean(sorted(sellratios[currencies[currency]], reverse=True)[:5] + sorted(buyratios[currencies[currency]])[:5])\n\n\n\t\t\trates = u'''{}\\ndesc = \"Currency Rates\"\\n\\n# Base type : settings pair\\nitems = {{\\n'''.format(header.format(datetime.utcnow().strftime('%m/%d/%Y(m/d/y) %H:%M:%S'), l))\n\t\t\tcurval = u'''{}\\ndesc = \"Currency Autogen\"\\n\\n# Base type : settings pair\\nitems = {{\\n'''.format(header.format(datetime.utcnow().strftime('%m/%d/%Y(m/d/y) %H:%M:%S'), l))\n\t\t\tif ratios[currencies['exa']]:\n\t\t\t\texalt = ratios[currencies['exa']]\n\t\t\telse:\n\t\t\t\texalt = defaults['exa']\n\t\t\tfor cur in sorted(defaults.keys()):\n\t\t\t\tif cur in currencies and ratios[currencies[cur]]:\n\t\t\t\t\trates += u'\\t\"{}\": {},\\n'.format(cur, ratios[currencies[cur]])\n\t\t\t\t\tretstr = convertshorttolongstr(cur, ratios[currencies[cur]], l, exalt)\n\t\t\t\t\tif retstr:\n\t\t\t\t\t\tcurval += u'\\t\"{},\\n'.format(retstr)\n\t\t\t\telse:\n\t\t\t\t\tretstr = convertshorttolongstr(cur, defaults[cur], l, exalt)\n\t\t\t\t\tif retstr:\n\t\t\t\t\t\tcurval += u'\\t\"{},\\n'.format(retstr)\n\t\t\t\t\tif cur in currencies:\n\t\t\t\t\t\t# print the currencies that didn't have enough data\n\t\t\t\t\t\tprint(cur, l, ratios[currencies[cur]], len(ratios[currencies[cur]]))\n\t\t\t\t\trates += u'\\t\"{}\": {},\\n'.format(cur, defaults[cur])\n\t\t\trates += u'}\\n'\n\t\t\tcurval += u'}\\n'\n\n\t\t\twith open('auto_gen\\\\{}currencyrates.py'.format(name), 'w', encoding='utf-8') as f:\n\t\t\t\tf.write(rates)\n\t\t\twith open('auto_gen\\\\{}currency.py'.format(name), 'w', encoding='utf-8') as f:\n\t\t\t\tf.write(curval)\n\t\tupdatechaosequiv(ldb)\n\n\nif __name__ == '__main__':\n\tos.environ['NO_PROXY'] = 'www.pathofexile.com'\n\t# poetrade_getcurrencyrates()\n\tdivuniqueupdate()\n\n\n\tif False: # toggle True/False to run this section\n\t\twith MongoClient() as client:\n\t\t\tldb = client.stashdata\n\t\t\tgen_lists(ldb)\n","sub_path":"depreciated_pricetool_ggg_api.py","file_name":"depreciated_pricetool_ggg_api.py","file_ext":"py","file_size_in_byte":17239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"446670645","text":"def exc1():\r\n import os\r\n import cv2\r\n import numpy as np\r\n import pickle\r\n from PIL import Image\r\n path = os.path.abspath(os.path.curdir)\r\n labels={}\r\n x=[]\r\n x_c=[]\r\n x_g=[]\r\n y=[]\r\n id_=0\r\n for root,subdir,files in os.walk(path):\r\n for file in files:\r\n # print(file)\r\n fpath=os.path.join(root,file)\r\n pname=file.split('_')[0]\r\n if fpath.find('face_recog')!=-1:\r\n img=Image.open(fpath).convert('L')\r\n img=np.array(img,'uint8')\r\n # img=cv2.imread(fpath)\r\n # gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n # cv2.imwrite(fpath,gray)\r\n if pname in labels.keys():\r\n x.append(img)\r\n y.append(labels[pname])\r\n else:\r\n labels[pname]=id_\r\n id_+=1\r\n x.append(img)\r\n y.append(labels[pname])\r\n\r\n y=np.array(y)\r\n # print(x[0])\r\n #cv2.imshow('gray',x[0])\r\n #cv2.waitKey(0)\r\n print(len(x))\r\n with open('labeldata.pkl','wb') as f:\r\n pickle.dump(labels,f)\r\n rec=cv2.face.LBPHFaceRecognizer_create()\r\n rec.train(x,y)\r\n rec.save('ft.yml')\r\n #a = cv2.imread(os.path.join(subdir,file))\r\n\r\n\r\nexc1()","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"323157198","text":"from django.urls import path\n\nfrom .views import ItemDetailEndpoint, ItemCreate, StatusView, ItemListAPIView\nfrom .authentication import SocialLoginView\n\n\nurlpatterns = [\n path('', StatusView.as_view(), name='status'),\n path('items//', ItemDetailEndpoint.as_view(), name='item-list'),\n path('item/create/', ItemCreate.as_view(), name='item-create'),\n path('item-list/', ItemListAPIView.as_view(), name='item-list'),\n path('social-login/', SocialLoginView.as_view(), name='social-login')\n]\n","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"330435607","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport Bioinfo\nimport gzip\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n# file_r1 = \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R1_001.fastq.gz\"\nfile_r2 = \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R2_001.fastq.gz\"\n# file_r3 = \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R3_001.fastq.gz\"\n# file_r4 = \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R4_001.fastq.gz\"\n# dict_files = {\n# \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R1_001.fastq.gz\": [\"read 1\",1],\n# \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R2_001.fastq.gz\": [\"index 1\",2],\n# \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R3_001.fastq.gz\": [\"index 2\",3],\n# \"/projects/bgmp/shared/2017_sequencing/1294_S1_L008_R4_001.fastq.gz\": [\"read 2\",4]}\n\n# tfile_r1 = \"./unit_test_r1.fastq.gz\"\n# tfile_r2 = \"./unit_test_r2.fastq.gz\"\n# tfile_r3 = \"./unit_test_r3.fastq.gz\"\n# tfile_r4 = \"./unit_test_r4.fastq.gz\"\n# dict_files = {\n# \"./unit_test_r1.fastq.gz\": [\"read 1\",1],\n# \"./unit_test_r2.fastq.gz\": [\"index 1\",2],\n# \"./unit_test_r3.fastq.gz\": [\"index 2\",3],\n# \"./unit_test_r4.fastq.gz\": [\"read 2\",4]}\n\n\n# for file_name, ri in dict_files.items():\n ### Reading in file and creating an array of the quality scores at each position for all reads to calculate the average\ndict_tot = {}\nwith gzip.open(file_r2, \"rb\") as fr1:\n num_seq = 0\n count = 0\n for line in fr1:\n line = line[:-1]\n if count % 4 == 3:\n num_seq += 1\n seq_len = len(line)\n tot = 0\n for i in range(len(line)):\n if i in dict_tot.keys():\n dict_tot[i] += line[i] - 33\n else:\n dict_tot[i] = line[i] - 33\n count += 1\n\ndict_ave = {} \nfor base, tot in dict_tot.items():\n ave = tot/num_seq\n dict_ave[base] = ave\n\nprint(\"Number of records: \", num_seq) #number of lines\nprint(\"Number of bases: \",seq_len) #legth of the sequence\nprint(\"Total number of lines: \",count)\n\nx = range(len(dict_ave))\nplt.figure()\nplt.bar(x, dict_ave.values())\nplt.title(\"The average quality scores for each position for Index 1\")\nplt.xlabel(\"Position\")\nplt.ylabel(\"Mean\")\nplt.savefig(\"index1.png\")\n","sub_path":"Assignment-the-first/demultiplex_r2.py","file_name":"demultiplex_r2.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574700522","text":"from bart_api import BartApi\nimport json\nimport time\nimport itertools\nfrom datetime import datetime, timedelta\nimport folium\nfrom lxml import etree\nfrom urllib2 import urlopen\n\n##########################################################################\n## source code : https://github.com/projectdelphai/bart_api/blob/master/bart_api/__init__.py\ndef parse_response(raw_xml):\n if isinstance(raw_xml, bytes):\n parsed_xml = etree.fromstring(raw_xml, parser=etree.XMLParser(encoding='utf-8'))\n else:\n parsed_xml = etree.parse(raw_xml)\n return parsed_xml\n\ndef get_xml(url):\n raw_response = urlopen(url)\n xml = parse_response(raw_response)\n return xml\n\n##########################################################################\n\n\ndef bart_schedules_txt(bart):\n # # # Save bart schedules on csv file\n shedules_file = open(\"bart_schedules.txt\",\"w\")\n weekday = [\"03/05/2016\",\"03/07/2016\"]\n station_list = bart.get_stations()\n stations_abbr = [(station['abbr']) for station in station_list]\n # print schedules of a specific station\n for station, w in itertools.product(stations_abbr, weekday):\n schedule = get_xml(\"http://api.bart.gov/api/sched.aspx?cmd=stnsched&orig=%s&date=%s&key=%s&l=1\"%(station,w,key))\n sc_root = schedule.getroot()\n for child in sc_root:\n if child.tag == 'station':\n for c in child.getchildren():\n records = [item[1] for item in c.items()]\n if len(records)>0:\n shedules_file.write(station + \",\" + \",\".join(records) + \",\" + str(weekday.index(w)) + \"\\n\")\n #print station + \",\" + \",\".join(records) + \",\" + str(weekday.index(w)) + \"\\n\"\n shedules_file.close()\n\n\ndef bart_station_info_txt(bart,stations_abbr):\n #Save Bart stations information into file\n\n station_info = open(\"stations_info.txt\",\"w\")\n\n cols = ['city', 'name', 'north_routes', 'zipcode', 'south_platforms', 'county', 'south_routes',\n 'abbr', 'gtfs_latitude', 'address', 'gtfs_longitude', 'cross_street', 'north_platforms']\n for i,station in enumerate(stations_abbr):\n info = bart.station_info(station)\n info = [str(info[col]) for col in cols]\n station_info.write(\",\".join(info) + \"\\n\")\n station_info.close()\n\n\ndef add_zero_2(time):\n if time.split(\":\")[0] not in ['10','11','12']:\n time = \"0\" + time\n return unicode(time)\n\n\ndef bart_trip_durations():\n #scheduled = datetime.strptime(shedule_colma_pitt, \"%I:%M %p\")\n calculated = []\n trip_duration_file = open(\"trip_duration.txt\",\"w\")\n\n for x in all_sc:\n abbr = x.abbr\n dest = x.trainHeadStation\n origTime = datetime.strptime(add_zero_2(x.origTime), \"%I:%M %p\")\n destTime = datetime.strptime(add_zero_2(x.destTime), \"%I:%M %p\")\n trip_duration = (destTime - origTime).total_seconds()/60\n route = x.route\n weekday = x.weekday\n record = \",\".join([abbr,dest,route,weekday,str(trip_duration)])\n record2 = \",\".join([abbr,dest,weekday])\n if record2 not in calculated:\n calculated.append(record2)\n trip_duration_file.write(record + '\\n')\n\n\n# trip_duration_file.close()\n\nif __name__ == '__main__':\n bart = BartApi(\"key\")\n station_list = bart.get_stations()\n stations_abbr = [(station['abbr']) for station in station_list]\n","sub_path":"create_txt_files.py","file_name":"create_txt_files.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"504132030","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Common models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User\nfrom django.db import models as db\nfrom django.db.utils import DatabaseError\nfrom django.dispatch import Signal\nfrom tastypie.models import create_api_key\n\n\ndef create_api_key_ignore_dberrors(*args, **kwargs):\n try:\n return create_api_key(*args, **kwargs)\n except DatabaseError:\n # no such table yet, first syncdb\n from django.db import transaction\n transaction.rollback_unless_managed()\n\ndb.signals.post_save.connect(create_api_key_ignore_dberrors, sender=User)\n\n\n# workaround for a unit test bug in Django 1.4.x\n\nfrom django.contrib.auth.tests import models as auth_test_models\ndel auth_test_models.ProfileTestCase.test_site_profile_not_available\n\n# signal used by SyncFieldMixin for sending notifications on changed fields\nfields_synced_signal = Signal(providing_args=['changes', 'change_author'])\n\n\nclass SyncFieldMixin(object):\n \"\"\"\n Mixin responsible for syncing fields between linked objects. In order to\n specify objects and fields that you want to keep in sync, you need to\n implement 'get_synced_objs_and_fields' method which should return a list of\n tuples, where every such tuple should contain an object and a list of\n fields you want to sync, e.g.:\n\n [(obj1, [field1, field2]), (obj2, [field1, field3])]\n\n After syncing your objects, this mixin sends 'fields_synced_signal' which\n carries a list of changes that have been made.\n \"\"\"\n\n def get_synced_objs_and_fields(self):\n raise NotImplementedError()\n\n def save(self, *args, **kwargs):\n from ralph.ui.views.common import SAVE_PRIORITY\n # by default save with the same priority as in 'edit device' forms etc.\n priority = kwargs.get('priority')\n change_author = kwargs.get('user')\n if priority is None:\n priority = SAVE_PRIORITY\n changes = []\n for obj, fields in self.get_synced_objs_and_fields():\n for f in fields:\n source_old_value = self.dirty_fields.get(f)\n target_old_value = getattr(obj, f)\n new_value = getattr(self, f)\n if new_value not in (source_old_value, target_old_value):\n changes.append({\n 'field': f,\n 'source': self,\n 'target': obj,\n 'source_old_value': source_old_value,\n 'target_old_value': target_old_value,\n 'new_value': new_value,\n })\n setattr(obj, f, new_value)\n obj.save(sync_fields=False, priority=priority)\n fields_synced_signal.send_robust(\n sender=self, changes=changes, change_author=change_author\n )\n","sub_path":"src/ralph/util/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"101585548","text":"from utils import config\nconfig = config.get()\n\n\nclass DiscordUtilities:\n\n def __init__(self,bot):\n self.bot = bot\n\n def get_server(self):\n for server in list(self.bot.servers):\n allowed_server = config['server']['allowed']\n if server.id == allowed_server:\n return server\n raise StopIteration('No allowed Server found')\n\n def is_in_member_role(self, user_id):\n server = self.get_server()\n member = server.get_member(user_id)\n\n for role in member.roles:\n if str(role) == config['roles']['member']:\n return True\n return False\n\n def is_in_admin_role(self, user_id):\n server = self.get_server()\n member = server.get_member(user_id)\n\n for role in member.roles:\n if str(role) == config['roles']['admin']:\n return True\n return False","sub_path":"utils/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"247756143","text":"import random\nimport string\n\ndef generar_contrasena():\n mayusculas = list(string.ascii_uppercase)\n minusculas = list(string.ascii_lowercase)\n simbolos = ['!','@','#','$','%','&','/','(',')','=']\n numeros = ['0','1','2','3','4','5','6','7','8','9']\n\n caracteres = mayusculas + minusculas + simbolos + numeros\n\n contrasena = []\n\n for i in range(15):\n char_random = random.choice(caracteres)\n contrasena.append(char_random)\n\n contrasena = ''.join(contrasena)\n return contrasena\n\ndef run():\n contrasena = generar_contrasena()\n print('Tu nueva contraseña es: ' + contrasena)\n\nif __name__ == '__main__':\n run()","sub_path":"Basico/generador_contrasena.py","file_name":"generador_contrasena.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"15348599","text":"\"\"\"\nWe are given head, the head node of a linked list containing unique integer values.\n\nWe are also given the list G, a subset of the values in the linked list.\n\nReturn the number of connected components in G, where two values are connected if they appear\nconsecutively in the linked list.\n\"\"\"\n\nfrom LinkedList import *\nclass Solution(object):\n def numComponents(self, head, G):\n \"\"\"\n :type head: ListNode\n :type G: List[int]\n :rtype: int\n \"\"\"\n Gset = set(G)\n ans = 0\n while head:\n if head.val in Gset and (head.next == None or head.next.val not in Gset):\n ans += 1\n head = head.next\n\n return ans\n\n def numComponents2(self, head, G):\n Gset = set(G)\n ans = 0\n while head:\n if (head.val in Gset and getattr(head.next, 'val', None) not in Gset):\n ans += 1\n head = head.next\n\n return ans\n\n# A, G = createLinkedList([0,1,2,3]), [0,1,3] # 2\nA, G = createLinkedList([0,1,2,3,4,5,6,7]), [0,2,3,5,7] # 4\nprint(Solution().numComponents(A, G))\n","sub_path":"817LinkListComp.py","file_name":"817LinkListComp.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"224255045","text":"import scipy.io.wavfile as wav\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfs,data=wav.read('voice.wav')\nfs1,data1=wav.read('slow1.wav')\nfs2,data2=wav.read('fast1.wav')\nprint(fs,fs1,fs2)\nt1=np.arange(0,1.0/fs1)\nt2=np.arange(0,1.0/fs2)\nt1=np.arange(0,len(data)/fs1,1.0/fs)\nt2=np.arange(0,len(data2)/fs2,1.0/fs)\nprint(data1,data2)\na1=plt.subplot(211)\na1.plot(t1,data[0:len(t1)])\na2=plt.subplot(212,sharex=a1)\na2.plot(t2,data[0:len(t2)])\nplt.show()\n","sub_path":"wav.py","file_name":"wav.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613257856","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom __future__ import print_function\nfrom openeye import oechem\nfrom openeye import oequacpac\n\n\ndef main(argv=[__name__]):\n if len(argv) != 2:\n oechem.OEThrow.Usage(\"%s \" % argv[0])\n\n ifs = oechem.oemolistream(sys.argv[1])\n am1 = oequacpac.OEAM1()\n results = oequacpac.OEAM1Results()\n for mol in ifs.GetOEMols():\n for conf in mol.GetConfs():\n print(\"molecule: \", mol.GetTitle(), \"conformer:\", conf.GetIdx())\n if am1.CalcAM1(results, mol):\n nbonds = 0\n for bond in mol.GetBonds(oechem.OEIsRotor()):\n nbonds += 1\n print(results.GetBondOrder(bond.GetBgnIdx(), bond.GetEndIdx()))\n print(\"Rotatable bonds: \", nbonds)\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(main(sys.argv))\n","sub_path":"venv/Lib/site-packages/openeye/examples/quacpac/wibergbondorders.py","file_name":"wibergbondorders.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"102158255","text":"''' Based on v2, use mean_squared_error'''\n\nimport gym\nimport matplotlib\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport os\n\n\nenv = gym.make(\"CartPole-v0\")\n\nn_epoches = 1000\nn_outputs = env.action_space.n\nepsilon = 1.0\nepsilon_min = 0.01\nn_max_steps = 500\nbatch_size = 50\nmax_memory_capacity = 500000\ndiscount_rate = 0.99\nepsilon_decay = 0.995\nmemory = np.empty(shape=max_memory_capacity, dtype=np.object)\n\nclass Memory:\n def __init__(self, capacity=max_memory_capacity):\n self.memory = np.empty(shape=max_memory_capacity, dtype=np.object)\n self.index = 0\n self.length = 0\n self.capacity = capacity\n\n def append(self, data):\n self.memory[self.index] = data\n self.length = min(self.length+1, self.capacity)\n self.index += 1\n if self.index >= self.capacity:\n self.index = 0\n\n def sample(self, batch_size=batch_size):\n indexes = np.random.permutation(batch_size)[:batch_size]\n return self.memory[indexes]\n\n\n\n\ndef q_network(state_tensor):\n inputs = state_tensor\n dense_outputs1 = tf.layers.dense(inputs=inputs, units=30, activation=tf.nn.relu, kernel_initializer=tf.variance_scaling_initializer())\n dense_outputs2 = tf.layers.dense(inputs=dense_outputs1, units=30, activation=tf.nn.relu, kernel_initializer=tf.variance_scaling_initializer())\n outputs = tf.layers.dense(inputs=dense_outputs2, units=n_outputs, kernel_initializer=tf.variance_scaling_initializer())\n return outputs\n\n\ntf.reset_default_graph()\n\nstate_tensor = tf.placeholder(tf.float32, shape=(None, 4))\nq_tensor = q_network(state_tensor)\n\n\ndef predict(state_val):\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n init.run()\n q_val = sess.run(q_tensor, feed_dict={state_tensor : state_val.reshape(1,4)})\n return q_val\n\n\ndef act(state_val):\n if np.random.rand() <= epsilon:\n return np.random.randint(n_outputs)\n else:\n predicted_q = predict(state_val)\n return np.argmax(predicted_q, axis=-1)[0]\n\n\nlabels_tensor = tf.placeholder(dtype=tf.float32, shape=(None, 2))\nloss = tf.losses.mean_squared_error(labels_tensor, q_tensor)\noptimizer = tf.train.AdamOptimizer()\ntraining_op = optimizer.minimize(loss)\n\n\ndef train(training_data):\n global epsilon\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n init.run()\n for state, action, reward, next_state, done in training_data:\n next_state_q_val = sess.run(q_tensor, feed_dict={state_tensor: next_state.reshape(1,4)})\n label_q_val = reward\n if not done:\n label_q_val += discount_rate * np.amax(next_state_q_val)\n state_q_val = sess.run(q_tensor, feed_dict={state_tensor: state.reshape(1,4)})\n state_q_val[0][action] = label_q_val\n _, loss_val = sess.run([training_op, loss], feed_dict={state_tensor: state.reshape(1,4), labels_tensor: state_q_val})\n if epsilon > epsilon_min:\n epsilon *= epsilon_decay\n\n\nmemory = Memory()\n\ngame_rewards = []\nmax_game_reward = 0\nfor game in range(n_epoches):\n state = env.reset()\n total_reward = 0\n for step in range(n_max_steps):\n action = act(state)\n next_state, reward, done, _ = env.step(action)\n memory.append((state, action, reward, next_state, done))\n total_reward += reward\n state = next_state\n if done:\n print('Game {}, Step {}, Reward {}, Epsilon {:.2}'.format(game, step, total_reward, epsilon))\n break\n if memory.length >= batch_size:\n data = memory.sample()\n train(data)\n game_rewards.append(total_reward)\n if total_reward > max_game_reward:\n max_game_reward = total_reward\n print('Avg game reward is {:.4}. Max reward is {}'.format(sum(game_rewards) / len(game_rewards), max_game_reward))\n\n\n\n\n","sub_path":"python/machine-learning/cart-pole/my-cart-pole-tensorflow-v003.py","file_name":"my-cart-pole-tensorflow-v003.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"64376510","text":"import requests\nimport json\nfrom bs4 import BeautifulSoup\nfrom .models import City\ndef get_distance(start, stop):\n\tapi = \"google api key\" \n\turl = \"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\" + start + \"&destinations=\" + stop + \"&key=\" + api\n\tlink = requests.get(url)\n\tjson_loc = link.json()\n\t# print(\"start \"+start)\n\t# print(\"stop \"+stop)\n\tdistance = json_loc['rows'][0]['elements'][0]['distance']['text']\n\tdistance = int(''.join([d for d in distance if d.isdigit()==True]))\n\treturn distance\n\t\n\nimport random\nimport operator\nfrom numpy import vectorize\n\nclass GeneticAlgo():\n\t def __init__(self,hash_map,start,steps=2,crossover_prob=0.15,mutation_prob=0.15,population_size=5,iterations=100):\n\t \tself.crossover_prob=crossover_prob\n\t \tself.mutation_prob=mutation_prob\n\t \tself.population_size=population_size\n\t \tself.hash_map = hash_map\n\t \tself.steps = steps\n\t \tself.iterations = iterations\n\t \tself.start = start\n\t \tself.cities = [k for k in self.hash_map.keys()] \n\t \tself.cities.remove(start)\n\t \tself.genes = []\n\t \tself.epsilon = 1 - 1/self.iterations \n\t \tself.generate_genes = vectorize(self.generate_genes)\n\t \tself.evaluate_fitness = vectorize(self.evaluate_fitness)\n\t \tself.evolve = vectorize(self.evolve)\n\t \tself.prune_genes = vectorize(self.prune_genes)\n\t \tself.converge = vectorize(self.converge)\n\t \tself.generate_genes()\n\t def generate_genes(self):\n\t \tfor i in range(self.population_size):\n\t \t\tgene = [self.start]\n\t \t\toptions = [k for k in self.cities]\n\t \t\twhile len(gene) < len(self.cities)+1:\n\t \t\t\tcity = random.choice(options)\n\t \t\t\tloc = options.index(city)\n\t \t\t\tgene.append(city)\n\t \t\t\tdel options[loc]\n\t \t\tgene.append(self.start)\n\t \t\tself.genes.append(gene)\n\t \treturn self.genes\n\t def evaluate_fitness(self):\n\t \tfitness_scores = []\n\t \tfor gene in self.genes:\n\t \t\ttotal_distance = 0\n\t \t\tfor idx in range(1,len(gene)):\n\t \t\t\tcity_b = gene[idx]\n\t \t\t\tcity_a = gene[idx-1]\n\t \t\t\ttry:\n\t \t\t\t\tdist = self.hash_map[city_a][city_b]\n\t \t\t\texcept:\n\t \t\t\t\tdist = self.hash_map[city_b][city_a]\n\t \t\t\ttotal_distance += dist\n\t \t\t\t#print(\"total = \", total_distance)\n\t \t\t\tfitness = 1/total_distance\n\t \t\tfitness_scores.append(fitness)\n\t \treturn fitness_scores\n\t def evolve(self):\n\t\t index_map = {i:'' for i in range(1,len(self.cities)-1)}\n\t\t indices = [i for i in range(1,len(self.cities)-1)]\n\t\t to_visit = [c for c in self.cities]\n\t\t cross = (1 - self.epsilon) * self.crossover_prob\n\t\t mutate = self.epsilon * self.mutation_prob\n\t\t crossed_count = int(cross * len(self.cities)-1)\n\t\t mutated_count = int((mutate * len(self.cities)-1)/2)\n\t\t for idx in range(len(self.genes)-1):\n\t\t\t gene = self.genes[idx]\n\t\t\t for i in range(crossed_count):\n\t\t\t\t try:\n\t\t\t\t\t gene_index = random.choice(indices)\n\t\t\t\t\t sample = gene[gene_index]\n\t\t\t\t\t if sample in to_visit:\n\t\t\t\t\t\t index_map[gene_index] = sample\n\t\t\t\t\t\t loc = indices.index(gene_index)\n\t\t\t\t\t\t del indices[loc]\n\t\t\t\t\t\t loc = to_visit.index(sample)\n\t\t\t\t\t\t del to_visit[loc]\n\t\t\t\t\t else:\n\t\t\t\t\t \tcontinue\n\t\t\t\t except:\n\t\t\t\t \tpass\n\t\t last_gene = self.genes[-1]\n\t\t remaining_cities = [c for c in last_gene if c in to_visit]\n\t\t for k,v in index_map.items():\n\t\t \tif v != '':\n\t\t \t\tcontinue\n\t\t \telse:\n\t\t \t\tcity = remaining_cities.pop(0)\n\t\t \t\tindex_map[k] = city\n\t\t new_gene = [index_map[i] for i in range(1,len(self.cities)-1)]\n\t\t new_gene.insert(0,self.start)\n\t\t new_gene.append(self.start)\n\t\t for i in range(mutated_count):\n\t\t\t choices = [c for c in new_gene if c != self.start]\n\t\t\t city_a = random.choice(choices)\n\t\t\t city_b = random.choice(choices)\n\t\t\t index_a = new_gene.index(city_a)\n\t\t\t index_b = new_gene.index(city_b)\n\t\t\t new_gene[index_a] = city_b\n\t\t\t new_gene[index_b] = city_a\n\t\t self.genes.append(new_gene)\n\t\t\t\t\n\t def prune_genes(self): \n\t\t for i in range(self.steps):\n\t\t\t self.evolve()\n\t\t fitness_scores = self.evaluate_fitness()\n\t\t for i in range(self.steps):\n\t\t\t worst_gene_index = fitness_scores.index(min(fitness_scores))\n\t\t\t del self.genes[worst_gene_index]\n\t\t\t del fitness_scores[worst_gene_index]\n\t\t return max(fitness_scores),self.genes[fitness_scores.index(max(fitness_scores))]\n\t\n\t def converge(self):\n\t\t for i in range(self.iterations):\n\t\t\t values = self.prune_genes()\n\t\t\t current_score = values[0]\n\t\t\t current_best_gene = values[1]\n\t\t\t self.epsilon -= 1/self.iterations\n\t\t\t if i % 100 == 0:\n\t\t\t\t print(f\"{int(1/current_score)} km\")\n\t\t print(current_best_gene)\n\t\t\t\t\n\t\t return current_best_gene\n\n","sub_path":"vrp/tsp.py","file_name":"tsp.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49274029","text":"#Define different dictionarys\n\nperson = {}\n\nicons = {\n 'london': 'Big Ben',\n 'new york': 'Times Square',\n 'berlin': 'Berlin Wall',\n 'malta': 'Zxom Shai'\n }\n\npeople = {\n 'Charlie': ['Python', 'Java'],\n 'Richie': ['JavaScript', 'C'],\n 'Albert': ['PHP, Java'],\n 'Micky': ['C#', 'JavaScript']\n}\n\n# ---------------------------------->\n\n#Ways to assingn new values to dict\nperson['name'] = 'Charlie'\nperson['number'] = 7\nperson['secret'] = 'bad'\n\n#Remove from a dict\ndel person['secret']\n\nprint(person)\nprint(\"London has an icon called \" + icons['london'] )\n\n###\n### .items() = dictionary keys | .vlaues() = dictionary values\n###\n\n#Looping through Dict\nfor key, value in icons.items():\n print(\"\\n\")\n print(\"Key: \" + key)\n print(\"Value: \" + value)\n\nprint(\"\\n\\n\")\n\nplaces_been = ['france','london']\n\nfor place in icons.keys():\n print(place.title())\n if place in places_been:\n print(\"Hey , you;ve been to \" + place.title())\n print(\"Did you go and see \" + icons[place].title() + \"?\")\n\n\n#Looping over nested lists in dicts\n#\n#for (key),(value) in .items() :\n\nfor name,langs in people.items():\n print(\"\\n\")\n print(name.title() + \"'s langauges used are : \")\n for language in langs:\n print(language + \":\")\n","sub_path":"Fundamentals/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"166237661","text":"# coding=utf-8\r\n\r\nfrom catalog.models import Comment, Product\r\nfrom catalog.forms import CommentForm\r\nfrom checkout.forms import FreteForm\r\n\r\ndef catalog_context(request):\r\n tags = {}\r\n tags['comments'] = Comment.objects.all()\r\n tags['product_add'] = Product.objects.all()\r\n if request.user.is_authenticated:\r\n tags['comment_form'] = CommentForm()\r\n return tags","sub_path":"catalog/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"377690641","text":"with open(\"input\", \"r\") as f:\n lines = [int(n) for n in f.readlines()]\n\n\nlast_joltage = 0\nallowed_range = [1, 2, 3]\n\nadapters_sorted = sorted(lines)[::-1] # reversing them for popping\nprint(adapters_sorted)\n\ndiffs = {1: [], 2: [], 3: []}\ndevice_joltage = max(adapters_sorted) + 3\n\nwhile last_joltage < device_joltage - 3:\n adapter = adapters_sorted.pop()\n diff = adapter - last_joltage\n print(last_joltage, adapter, diff)\n if diff > 0 and diff <= 3:\n diffs[diff].append(adapter)\n else:\n raise IndexError\n last_joltage = adapter\n\ndiffs[3].append(device_joltage)\nprint(len(diffs[1]) * len(diffs[3]))\n\n","sub_path":"2020/10/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"411901725","text":"#! /usr/bin/python3\nfrom tkinter import Tk\nfrom threading import Thread\nfrom sys import platform\n\n\ndef run_gui_thread():\n root = Tk()\n if platform != 'win32':\n from s3zilla import S3Zilla\n S3Zilla(root)\n else:\n from s3zilla import S3ZillaWin10\n S3ZillaWin10(root)\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n try:\n thread = Thread(target=run_gui_thread)\n thread.daemon = True\n thread.start()\n thread.join()\n except KeyboardInterrupt:\n print('\\nExiting S3Zilla')\n","sub_path":"s3zilla.py","file_name":"s3zilla.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"100894670","text":"import pyspark\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nfrom pyspark.ml.regression import LinearRegression\nfrom pyspark.ml.linalg import Vectors\nfrom pyspark import SparkFiles\nfrom pyspark.sql import SparkSession\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pandas.plotting import autocorrelation_plot\nfrom pyspark.ml.regression import LinearRegression\nfrom datetime import timedelta, datetime\nimport time\n\nspark = SparkSession.builder \\\n .master(\"local[1]\") \\\n .appName(\"Vaccinations\") \\\n .getOrCreate()\n\n# LOADING DATA\nurl = \"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/us_state_vaccinations.csv\"\nspark.sparkContext.addFile(url)\ndf = spark.read.csv(\"file://\"+SparkFiles.get(\"us_state_vaccinations.csv\"), header=True, inferSchema= True).select(\"date\", \"location\", \"daily_vaccinations\")\n\n# ONLY INCLUDES ROWS WHERE date, location, and daily_vaccinations are present\nprint(\"all rows\", df.count())\ndf = df.na.drop()\nprint(\"only non null\", df.count())\n\n# CONVERT TO DATE TYPE\ndf = df.select('*', unix_timestamp(df.date.cast('date')).alias('time'))\n\n# GET LIST OF ALL STATES\nstates = df.rdd.map(lambda x : x.location).distinct().collect()\n\n# SAVE LIST OF STATES\nstatesfilepath = \"states.csv\"\nnewfile = np.savetxt(statesfilepath, states,\"%s\",header=\"states\")\n\nMODEL_TYPE = \"LinearRegression\"\n\nfor state in states: #[\"United States\"]:\n print(\"PROCESSING STATE: \", state)\n\n # LINEAR REGRESSION\n lr = LinearRegression()\n\n # ONLY USE CURRENT STATE\n data = df.select(\"time\", \"daily_vaccinations\").filter(df.location == state)\n dataArr = np.array(data.collect())\n x = [it[0] for it in dataArr]\n y = [it[1] for it in dataArr]\n\n # CALCULATE EPOCH TIME (X COORDINATE / INPUT) FOR THE NEXT 30 DAYS\n last_time = x[-1]\n test_x = [last_time+(idx*86400) for idx in range(1,31)] #get epoch time for the next 30 days\n\n # CREATE TRAINING SET\n train = data.rdd.map(lambda x:(Vectors.dense(x[0]), x[1])).toDF([\"features\", \"label\"])\n\n # TRAIN\n linear_model = lr.fit(train)\n\n # print(\"Coefficients: \" + str(linear_model.coefficients))\n # print(\"\\nIntercept: \" + str(linear_model.intercept))\n\n # CREATE TEST DATA\n all_X = np.concatenate([x,test_x])\n test_arr = [(Vectors.dense(i), 0) for i in test_x]\n testData = spark.sparkContext.parallelize(test_arr).toDF([\"features\", \"label\"])\n\n # GET PREDICTIONS\n output = linear_model.transform(testData)\n # output.show()\n preds = np.array(output.select(\"features\", \"prediction\").collect(), dtype='object')\n pred_y = [it[1] for it in preds]\n\n # ALL OUTPUTS FROM 1ST VACCINATION - 30 DAYS FROM NOW, PLOTTED\n dates = []\n epochidx = []\n for temp in all_X:\n date = time.strftime('%Y-%m-%d', time.localtime(temp))\n if (date[-2:]=='01'):\n dates.append(date)\n epochidx.append(temp)\n\n all_Y = np.concatenate([y, pred_y])\n numRows = all_Y.shape[0]\n plt.plot(all_X, all_Y) #THIS WILL BE SAVED IN THE CSV\n plt.xticks(epochidx,dates)\n plt.plot(x,y) #HISTORICAL DATA\n title = state + \" Vaccinations - Historical (Orange) & Predictions (Blue)\"\n plt.title(title)\n plt.savefig(\"plots/\"+state+\"_vaccination_rate_over_time.png\")\n plt.clf()\n\n # SAVE TO CSV\n locs = np.full(numRows, state)\n filepath = \"predictions/\" + state + \"_\" + MODEL_TYPE + \"_predictions.csv\"\n newfile = np.savetxt(filepath, np.dstack((locs, all_X,all_Y))[0],\"%s,%s,%s\",header=\"location,epoch,vaccination_rate\")\n","sub_path":"vaccination/vaccination.py","file_name":"vaccination.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"596729414","text":"import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import Join, MapCompose, Identity, TakeFirst\nimport urllib\nfrom urllib.parse import urljoin\nimport aer.items\nfrom urllib.request import urlretrieve\n\n# link_list = ['https://eml.berkeley.edu//~saez/course131/socialinsurance_ch12_new.pdf']\n# for link in link_list:\n# urlretrieve(link, 'lol.pdf')\n\ndef convert_relative_to_absolute_url(url,loader_context):\n return urljoin(\"https://www.aeaweb.org\", url)\n\nclass OxfordArticleLoader(ItemLoader):\n default_item_class = aer.items.Article\n default_input_processor = MapCompose(str.strip)\n default_output_processor = Join()\n url_in = MapCompose(convert_relative_to_absolute_url)\n\nclass OxfordSpider(scrapy.Spider):\n allowed_domains = ['www.aeaweb.org']\n\n # Locate articles.\n issue_xpath = '//a[contains(@href,\"/issues/\")]'\n article_xpath = '//article[@class = \"journal-article \"]'\n issue_extractor = LinkExtractor(restrict_xpaths=issue_xpath)\n\n # Locate articles on issue page\n item_field_xpaths = {\n 'title': 'h3/a/text()',\n 'publication_date': '//meta[@name = \"citation_publication_date\"]/@content',\n 'url': 'h3/a/@href'\n }\n\n # locate fields on article page\n item_article_xpaths = {\n 'doi' : '//meta[@name = \"citation_doi\"]/@content',\n 'author' : '//meta[@name = \"citation_author\"]/@content',\n 'title' : '//meta[@name = \"title\"]/text()',\n 'abstract' : '//section[@class = \"article-information abstract\"]/text()',\n 'JEL' : '//strong[@class = \"code\"]/text()',\n 'pdf_url' : '//meta[@name = \"citation_pdf_url\"]/@content',\n 'publication_date': '//meta[@name = \"citation_publication_date\"]/@content'\n }\n\n def parse(self, response):\n for issue in self.issue_extractor.extract_links(response):\n yield scrapy.Request(issue.url, callback=self.parse_issue)\n\n def parse_issue(self, response):\n for article in response.xpath(self.article_xpath):\n article_loader = OxfordArticleLoader(selector=article,\n response=response)\n for field, literal in self.item_field_literals.items():\n article_loader.add_value(field, literal)\n for field, xpath in self.item_field_xpaths.items():\n article_loader.add_xpath(field, xpath)\n article_item = article_loader.load_item()\n yield scrapy.Request(article_item['url'],\n callback=self.parse_article,\n meta={'article': article_item})\n\n def parse_article(self, response):\n article_loader = OxfordArticleLoader(response.meta['article'],\n response)\n for field, xpath in self.item_article_xpaths.items():\n article_loader.add_xpath(field, xpath)\n yield article_loader.load_item()\n\n\n\nclass aerSpider(OxfordSpider):\n name = 'aer'\n start_urls = ['https://www.aeaweb.org/journals/aer/issues']\n item_field_literals = {\n 'journal': 'American Economic Review',\n }\n\n\n\n\n\n","sub_path":"data_collection_econ/aer/aer/spiders/aer_spider.py","file_name":"aer_spider.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"573538119","text":"# IMPLEMENTATION OF THE GRADIENT DESCENT ALGORITHM\n\nimport numpy as np \nimport csv\n\n\n#THE GRADIENT DESCENT ALGORITHM IS IMPLEMENTED HERE\ndef GradientDescent(X, Y, output_file):\n\t'''\n\t\tn - Number of rows in the training data\n\t\td - Number of features in a training data\n\t\tX - Training data with a column of 1's added to it \n\t\tY - Labels of the training data \n\t\tthreshold - Maximum permissible deviation of beta's between two iterations \n\t\tlearning_rate - List of learning rates which is to be experimented \n\t\talpha - Learning rate \n\t\tbeta - weights \n\t\tdR - Differential of the Loss function \n\t\tf_X - Affine function which is evaluated \n\t\titer - Keeps track of the number of iterations \n\n\t'''\n\tdata = X\n\tX = normalize(X)\n\tX = np.insert(X, obj = 0, values = 1, axis = 1)\n\tthreshold = 0.001\n\tn = X.shape[0]\n\td = X.shape[1]\n\tY = Y.reshape(n,1)\n\tlearning_rate = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 0.9] \n\n\t#Various learning-rates are experimented here \n\tfor alpha in learning_rate:\n\t\titer = 0\n\t\tbeta = np.zeros([d, 1])\n\n\t\t#Update beta until convergence\n\t\twhile iter < 100:\n\t\t\tbeta_prev = beta\n\t\t\tf_X = np.dot(X , beta)\n\t\t\tdR = 1/n* np.dot(np.transpose(X), (f_X-Y))\n\t\t\tbeta = beta - alpha * dR\n\t\t\t\n\t\t\tdeviation = np.linalg.norm(beta - beta_prev, ord = 1)\t\n\n\t\t\tif deviation < threshold or iter > 100:\n\t\t\t\tbreak\n\t\t\t\n\t\t\titer = iter + 1\n\n\t\t#Printing the values to the output csv file\n\t\twith open(output_file, 'a', newline = '') as csvfile:\n\t\t\tfieldnames = ['alpha', 'iterations', 'beta_intercept', 'beta_age', 'beta_weight']\n\t\t\twriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\t\t\twriter.writerow({'alpha': alpha, 'iterations':iter, 'beta_intercept': float(beta[0]), 'beta_age': float(beta[1]), 'beta_weight': float(beta[2])})\n\n\n\treturn \"SUCCESS\"\n\n\n\n#NORMALIZES THE INPUT TRAINING DATA\ndef normalize(X):\n\tmu = np.mean(X, axis=0)\n\tstd = np.std(X, axis=0)\n\tX = (X - mu)/std\n\treturn X\n\n\n#VISUALIZING THE DATA AND BETA \ndef visualize(X, Y, beta):\n\timport matplotlib\n\timport matplotlib.pyplot as plt\n\tfrom matplotlib import cm\n\tfrom mpl_toolkits.mplot3d import Axes3D \n\n\tfig = plt.figure()\n\tax = fig.gca( projection='3d')\n\tage = X[:,0]\n\tweight = X[:,1]\n\theight = Y\n\tage_grid, weight_grid = np.meshgrid(age, weight)\n\t#ax.plot_surface(age, weight, )\n\tax.plot_surface(age_grid, weight_grid, beta[1]*age + beta[2]*weight + beta[0], rstride=1, cstride=1, linewidth=0, antialiased=False, shade=False)\n\tax.scatter(age, weight, height, c='red')\n\tax.set_xlabel('Age(Years)')\n\tax.set_ylabel('Weight(Kilograms)')\n\tax.set_zlabel('Height(Meters)')\n\n\tplt.show()\n\t","sub_path":"GradientDescent.py","file_name":"GradientDescent.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"493173290","text":"# from flask.ext.testing import TestCase\nimport sys, os\nfrom os import path\nsys.path.append(path.dirname(path.dirname( path.abspath(__file__) )))\nimport unittest\nimport server\n# from settings.utils import get_settings_from_env\n# from model import connect_to_db, db, User, Partner, Charge, Tag, tagscharges, Files\n\nclass BiuUnitTests(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tserver.app.config['TESTING'] = True\n\t\tserver.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\t\t# server.secret_key = get_settings_from_env(\"SECRET_KEY\")\n\t\t# server.app.config['SECRET_KEY'] = 'sekrit!'\n\t\tself.app = server.app.test_client()\n\n\tdef tearDown(self):\n\t\tpass\n\n\tdef test_start_here(self):\n\t\t\"\"\" Tests what happens if you go to landing page and are not logged in \"\"\"\n\t\tres=self.app.get('/')\n\t\tassert 'Break It Up' in res.data\n\t\tassert 'LOG IN' in res.data\n\t\tassert 'Register here' in res.data\n\n\tdef test_go_register(self):\n\t\t\"\"\" Tests if you click on Register link and are not logged in \"\"\"\n\t\tres=self.app.get('/register')\n\t\tassert 'Register' in res.data\n\t\tassert 'REGISTER' in res.data\n\n\tdef test_go_charge(self):\n\t\t\"\"\" Tests if you go to new charge view \"\"\"\n\t\trest=self.app.get('/charge')\n\t\tassert 'Charge Name' in res.data\n\t\tassert 'Description' in res.data\n\t\tassert 'Amount Paid' in res.data\n\n\t# def test_register(self):\n\t# \tres = self.app.post('/register_submit', data=dict(first_name=\"Joe\", \n\t# \t\t\t\t\t\t\t\t\t\t\t\t\t last_name=\"Schmoe\",\n\t# \t\t\t\t\t\t\t\t\t\t\t\t\t email=\"joe@schmoe.com\",\n\t# \t\t\t\t\t\t\t\t\t\t\t\t\t password1=\"fakefake\"\n\t# \t\t\t\t\t\t\t\t\t\t\t\t\t ))\n\t# \tassert 'Add your Partner\\'s email here.' in res.data\n\n\n\n\n\n\t\t# firstname = request.form.get('firstname')\n\t\t# lastname = request.form.get('lastname')\n\t\t# email = request.form.get('newemail')\n\t\t# password1 = request.form.get('password1')\n\n\t\t# if User.query.filter_by(email=email).first():\n\t\t# flash(\"A user already exists with this email\")\n\t\t# return render_template(\"register.html\")\n\t\t# else:\n\t\t# new_user = User(email, password1)\n\t\t# db.session.add(new_user)\n\t\t# new_user.first_name = firstname\n\t\t# new_user.last_name = lastname\n\t\t# db.session.commit()\n\t\t# if not session.get('new_user.user_id'):\n\t\t# session['user_id'] = new_user.user_id\n\t\t# flash(\"You have been registered successfully.\")\n\t\t# return redirect(\"/dashboard\")\n\nif __name__ == '__main__':\n unittest.main()\n\n# class BaseTestCase(TestCase):\n# \"\"\"A base test case for flask-tracking.\"\"\"\n\n# def create_app(self):\n# app.config.from_object('config.TestConfiguration')\n# return app\n\n# def setUp(self):\n# db.create_all()\n\n# def tearDown(self):\n# db.session.remove()\n# db.drop_all()\n\n# class UserViewsTests(BaseTestCase):\n# def test_users_can_login(self):\n# User.create(first_name='Joe', last_name=\"Schmoe\", password=set_password('testing'), email='joe@joes.com', password='12345')\n\n# response = self.client.post(url_for('users.login'),\n# data={'email': 'joe@joes.com', 'password': '12345'})\n\n# self.assert_redirects(response, url_for('tracking.index'))","sub_path":"test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"432148797","text":"from .utils import *\nfrom clay.shared.py_utils import *\n\n# Windowing System:\n\nBorderHighlightColor = (0.7, 0.0, 0.7, 1.0)\n\nclass WindowState():\n MAX_LAYOUT_STACK_SIZE = 6\n\n def __init__(self):\n self.windows = {}\n self.layout_stack = []\n\ndef editor_id_str(name, editor, extra_id_str=None):\n extra_id_str = default(extra_id_str, '')\n return '{}##{}{}'.format(name, editor.tab_name(), extra_id_str)\n\ndef render_window(editor, name, render_func, extra_id_str=None):\n \"\"\"\n Returns win_info, did_close\n \n If did_close returns True, the caller must perform the necessary cleanup.\n Otherwise, the window will be rendered again on the next update with a new win_info entry.\n \"\"\"\n id_str = editor_id_str(name, editor, extra_id_str)\n windows = editor.window_state.windows\n win_info = windows.setdefault(id_str, {'name': name, 'should_close': False})\n win_info['name'] = name\n if not win_info['should_close']:\n alt_id_str = win_info.get('alt_id_str', None)\n should_draw, is_open = begin(id_str, True)\n win_info['should_close'] = not is_open\n if should_draw and alt_id_str is None:\n render_func()\n end()\n if alt_id_str is not None:\n alt_flags = win_info.get('alt_flags', 0)\n begin(alt_id_str, flags=alt_flags)\n render_func()\n end()\n del win_info['alt_id_str']\n if win_info['should_close']:\n del windows[id_str]\n return id_str, win_info['should_close']\n\ndef get_window_data(id_str, focused_flags=0, hovered_flags=0):\n begin(id_str)\n data = {\n 'collapsed': is_window_collapsed(),\n 'focused': is_window_focused(focused_flags),\n 'hovered': is_window_hovered(hovered_flags),\n 'pos': get_window_pos(),\n 'size': get_window_size(),\n }\n end()\n return data\n\ndef set_window_data(id_str, data):\n \"\"\"\n Sets pos, size, and collapsed. Other fields are ignored.\n \"\"\"\n set_window_pos_str(id_str, data['pos'])\n set_window_size_str(id_str, data['size'])\n set_window_collapsed(id_str, data['collapsed'])\n\ndef push_window_state(win_state):\n windows, layout_stack = win_state.windows, win_state.layout_stack\n layout = {id_str: get_window_data(id_str) for id_str in windows.keys()}\n layout_stack.append(layout)\n if len(layout_stack) > WindowState.MAX_LAYOUT_STACK_SIZE:\n del layout_stack[0]\n\ndef pop_window_state(win_state):\n windows, layout_stack = win_state.windows, win_state.layout_stack\n if len(layout_stack) == 0:\n return\n layout = layout_stack.pop()\n for id_str, win_info in windows.items():\n entry = layout.get(id_str, None)\n if entry is None:\n continue\n set_window_data(id_str, entry)\n\ndef apply_window_layout(win_state, layout_desc, origin, region_size):\n push_window_state(win_state)\n \n # apply focus in reverse order of layout_desc, to\n # bring all wins to front and then leave focus on\n # the first window in the desc\n \n for win_id_str, (rel_pos, rel_size) in reversed(layout_desc):\n if win_id_str not in win_state.windows: \n continue\n pos = (origin[0] + rel_pos[0] * region_size[0],\n origin[1] + rel_pos[1] * region_size[1])\n size = (rel_size[0] * region_size[0],\n rel_size[1] * region_size[1])\n set_next_window_focus()\n set_next_window_pos(pos)\n set_next_window_size(size)\n set_next_window_collapsed(False)\n begin(win_id_str)\n end()\n\ndef outline_rect(pos, size, border_col):\n pos_b = (pos[0] + size[0], pos[1] + size[1])\n col = lib.igGetColorU32Vec4(border_col)\n draw_list = get_foreground_draw_list()\n lib.ImDrawList_AddRect(draw_list, pos, pos_b, col, 0.0, 0, 3.0)\n\ndef outline_current_window(border_col):\n pos = get_window_pos()\n size = get_window_size()\n outline_rect(pos, size, border_col)\n\ndef show_window_preview(id_str, win_info, id_to_skip=None):\n # show the window of the hovered item at the front by\n # temporarily rendering its contents to an alternate win.\n # Note that this causes flicker if the window appears in front of\n # the mouse. Ignore it, it's troublesome to fix.\n win_data = get_window_data(id_str)\n outline_rect(win_data['pos'], win_data['size'],\n BorderHighlightColor)\n if id_str != id_to_skip:\n alt_id_str = '{}##{}'.format(win_info['name'], 'tmp_win')\n win_info['alt_id_str'] = alt_id_str\n set_window_data(alt_id_str, win_data)\n\ndef run_window_compressor(win_state):\n \"\"\"\n Clicking a window compresses its size and centers it on the mouse.\n \"\"\"\n new_size = (200, 250)\n for win_id, _ in win_state.windows.items():\n begin(win_id)\n if is_window_hovered(flags=lib.ImGuiHoveredFlags_ChildWindows):\n outline_current_window(BorderHighlightColor)\n if is_mouse_clicked(Mouse.Left):\n mp = glfw_get_cursor_pos()\n new_pos = (mp[0] - 0.5*new_size[0],\n mp[1] - 0.5*new_size[1])\n set_window_size_vec2(new_size)\n set_window_pos_vec2(new_pos)\n end()\n\ndef run_window_picker(win_state, picker, should_show_picker):\n \"\"\"\n picker must be a SimpleHoverSelector\n \"\"\"\n options = [(win_info['name'], id_str) for\n id_str, win_info in win_state.windows.items()]\n did_submit, opt_index = picker.update(should_show_picker, options)\n if opt_index is not None:\n _, id_str = options[opt_index]\n win_info = win_state.windows[id_str]\n show_window_preview(id_str, win_info)\n if did_submit and opt_index is not None:\n _, id_str = options[opt_index]\n set_window_focus(id_str)\n\n# TODO - generalize this with ItemSelector and ItemSelectorWidget\n# of tree_picker.py\n\nclass LayoutSelector():\n \"\"\"\n Widget that allows laying out the windows in a particular arrangement.\n \"\"\"\n def __init__(self, editor, success_callback):\n self.widget = None\n self.editor = editor\n self.success_callback = success_callback\n \n def show(self):\n if self.widget is None:\n self.widget = LayoutSelectorWidget(self.editor)\n\n def hide(self):\n if self.widget is not None:\n self.widget.future.fail()\n\n def update(self):\n if self.widget is not None:\n fut = self.widget.future\n if fut.state == Future.Waiting:\n self.widget.update()\n elif fut.state == Future.Completed:\n self.widget = None\n self.success_callback(fut.result)\n elif fut.state == Future.Failed:\n self.widget = None\n\nclass LayoutSelectorWidget():\n SelectedColor = Color.creation_green\n PendingColor = BorderHighlightColor\n\n def __init__(self, editor):\n self.editor = editor\n self.future = Future()\n self.first_update = True\n\n initial_box = ((0, 0), (1, 1))\n self.geom_desc = [initial_box]\n self.chosen_wins = []\n\n def update(self):\n \"\"\"\n Works like this:\n Use WASD to split a box into the desired layout. Once it's what\n you want, you hover over the desired windows and press F. The i^th\n selected window will be put into the box numbered i in the layout graphic.\n \"\"\"\n if self.future.is_done():\n return\n\n flags = lib.ImGuiWindowFlags_NoDecoration | lib.ImGuiWindowFlags_AlwaysAutoResize\n _, keep_open = begin(editor_id_str('layout selector', self.editor), True, flags=flags)\n if not keep_open:\n self.future.fail()\n \n key_map = {\n 'w': (_split_vertical, True),\n 'a': (_split_horizontal, True),\n 's': (_split_vertical, False),\n 'd': (_split_horizontal, False)\n }\n if is_window_focused():\n for key, (split_func, swap_res) in key_map.items():\n if len(self.geom_desc) < 4 and is_key_pressed(kx(key)):\n box = self.geom_desc.pop()\n box_a, box_b = split_func(box)\n if swap_res:\n box_a, box_b = box_b, box_a\n self.geom_desc.extend([box_a, box_b])\n if is_key_pressed(kx('q')) or is_key_pressed(Key.Escape):\n self.future.fail()\n\n if not self.first_update and not is_window_focused():\n self.future.fail()\n\n partial_desc = [(pos, size, i < len(self.chosen_wins)) for\n i, (pos, size) in enumerate(self.geom_desc)]\n _render_layout_desc(partial_desc)\n\n # allow selecting windows by hovering their rect and pressing a key\n # or by hovering their entry in a list\n win_state = self.editor.window_state\n for win_id, win_info in win_state.windows.items():\n hovered_flags = lib.ImGuiHoveredFlags_ChildWindows\n win_data = get_window_data(win_id, hovered_flags=hovered_flags)\n \n # Note: not very useful\n text_with_bg_color(win_info['name'],\n LayoutSelectorWidget.PendingColor, size=(-1, 0))\n text_entry_hov = is_item_hovered()\n\n border_col = None\n if win_id in self.chosen_wins:\n border_col = LayoutSelectorWidget.SelectedColor\n elif text_entry_hov or win_data['hovered']:\n border_col = LayoutSelectorWidget.PendingColor\n if not self.first_update and (is_key_pressed(kx('f')) and \n len(self.chosen_wins) < len(self.geom_desc)):\n self.chosen_wins.append(win_id)\n if border_col is not None:\n outline_rect(win_data['pos'], win_data['size'], border_col)\n if len(self.chosen_wins) == len(self.geom_desc):\n full_desc = list(zip(self.chosen_wins, self.geom_desc))\n self.future.complete(full_desc)\n \n end()\n self.first_update = False\n\ndef _render_layout_desc(partial_desc):\n origin = get_cursor_pos()\n size = (100, 100)\n m = 1\n for i, (rel_pos, rel_size, is_set) in enumerate(partial_desc):\n push_id_int(i)\n item_pos = (origin[0] + rel_pos[0] * size[0] + m,\n origin[1] + rel_pos[1] * size[1] + m)\n item_size = (rel_size[0] * size[0] - 2*m,\n rel_size[1] * size[1] - 2*m)\n set_cursor_pos(item_pos)\n col = LayoutSelectorWidget.SelectedColor if is_set else LayoutSelectorWidget.PendingColor\n text_with_bg_color(str(i + 1), col, size=item_size)\n pop_id()\n set_cursor_pos(origin)\n dummy(size)\n\n# Geometry description helpers\n\ndef _split_horizontal(geom):\n pos, size = geom\n pos_left = pos\n pos_right = (pos[0] + size[0] * 0.5, pos[1])\n new_size = (size[0] * 0.5, size[1])\n return ((pos_left, new_size), (pos_right, new_size))\n\ndef _split_vertical(geom):\n pos, size = geom\n pos_top = pos\n pos_bot = (pos[0], pos[1] + size[1] * 0.5)\n new_size = (size[0], size[1] * 0.5)\n return ((pos_top, new_size), (pos_bot, new_size))\n\n\n","sub_path":"clay/core/gui/window_system.py","file_name":"window_system.py","file_ext":"py","file_size_in_byte":11155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516930633","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 ('auth2', '0004_auto_20151113_1552'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Congressman',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('uf', models.CharField(max_length=200, null=True, verbose_name='uf', blank=True)),\n ('party', models.CharField(max_length=200, null=True, verbose_name='party', blank=True)),\n ('parliamentary_name', models.CharField(max_length=200, null=True, verbose_name='parliamentary name', blank=True)),\n ('user', models.ForeignKey(verbose_name='user', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'congressman',\n 'verbose_name_plural': 'congressmen',\n },\n ),\n ]\n","sub_path":"wikilegis/auth2/migrations/0005_congressman.py","file_name":"0005_congressman.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306665735","text":"import pytest\n\nfrom pyramid_api import models\n\n\n@pytest.mark.parametrize('type', [\n models.MyModel.types.TYPE1,\n models.MyModel.types.TYPE2,\n])\ndef test_mymodel_create(testapp, db_transaction, type):\n resp = testapp.post('/mymodels/', dict(type=str(type).lower()), status=201)\n guid = resp.json['mymodel']['id']\n with db_transaction() as session:\n mymodel = session.query(models.MyModel).get(guid)\n assert mymodel.type == type\n\n\ndef test_mymodel_get(testapp, db_transaction):\n with db_transaction() as session:\n mymodel = models.MyModel.create(\n type=models.MyModel.types.TYPE1,\n )\n session.add(mymodel)\n resp = testapp.get(\n '/mymodels/{}'.format(mymodel.guid),\n )\n assert resp.json['mymodel']['id'] == mymodel.guid\n assert resp.json['mymodel']['type'] == 'type1'\n assert resp.json['mymodel']['updated_at'] == mymodel.updated_at.isoformat()\n assert resp.json['mymodel']['created_at'] == mymodel.created_at.isoformat()\n","sub_path":"tests/integration/test_mymodels.py","file_name":"test_mymodels.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"490494551","text":"import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-tr\", \"--pred_test_file\", type=str,\n default=\"./annotations/ner_before_wsd_batch2_with_attn_USE_THIS.mod.7.conll\")\nparser.add_argument(\"-te\", \"--gold_test_file\", type=str,\n default=\"../ner_data/eng_data/eng.testb.true.conll\")\nparser.add_argument(\"-c\", \"--combined_file\", type=str,\n default=\"./annotations/ner_before_wsd_batch2_with_attn_USE_THIS.mod.7.combined.conll\")\n\n\nargs = parser.parse_args()\n\npred_test_file = args.pred_test_file\ngold_test_file = args.gold_test_file\nop_file = args.combined_file\n\nop_instance_strs = []\n\nwith open(gold_test_file, 'r') as gt:\n with open(pred_test_file, 'r') as pt:\n gold_instances = gt.read().strip(' \\t\\r\\n').split('\\n\\n')\n pred_instances = pt.read().strip(' \\t\\r\\n').split('\\n\\n')\n assert len(gold_instances) == len(pred_instances), \"Number of instances doesn't match up!\"\n for iid, ginstance in enumerate(gold_instances):\n ginstance = ginstance.strip(\" \\t\\r\\n\")\n if len(ginstance) == 0:\n continue\n pinstance = pred_instances[iid]\n ginstance = ginstance.split('\\n')\n pinstance = pinstance.split('\\n')\n assert len(ginstance) == len(pinstance), \"Number of lines in an instance doesn't match!\"\n instance_lines = []\n for lid, gline in enumerate(ginstance):\n pline = pinstance[lid].split()\n gline = gline.split()\n gline.append(pline[-1])\n instance_lines.append(\" \".join(gline))\n op_instance_strs.append(\"\\n\".join(instance_lines))\n\n\nwith open(op_file, 'w+') as opf:\n opf.write(\"\\n\\n\".join(op_instance_strs))","sub_path":"combine_gold_pred.py","file_name":"combine_gold_pred.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"556569581","text":"# Nickelback songs\nsong_list = {\n ('Nickelback', 'How You Remind Me'), \n ('Nickelback', 'Something in Your Mouth'),\n ('Nickelback', 'Bottoms Up'),\n ('Will.i.am', 'That Power'),\n ('Miles Davis', 'Stella by Starlight'),\n ('Nickelback', 'Animals')\n}\n\n\n# create a new set that contains all songs that were not performed by Nickelback\n# You need the variable first (x) before the for in loop\n# The if statement comes after the for in loop\n# not in is a basic operator that searches through code and determines if the passed argument is in the code\n# It will execute if the code is not present\nnew_song_list = {x for x in song_list if 'Nickelback' not in x}\nprint(new_song_list)","sub_path":"music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"533460314","text":"import json\nimport ast\nfrom maya import cmds\nimport pymel.core as pm\n\nfrom mgear.core import attribute\nfrom mgear.core import string\n\nfrom . import channel_master_utils as cmu\nimport sys\n\nif sys.version_info[0] == 2:\n string_types = (basestring,)\nelse:\n string_types = (str,)\n\n\n__TAG__ = \"_isChannelMasterNode\"\n\n# TODO: Node should store the current active tab\n\n\ndef list_channel_master_nodes():\n \"\"\"return a list of channel master nodes in the scene\n\n Returns:\n list: List of channel master nodes\n \"\"\"\n return [n for n in cmds.ls(\"*.{}\".format(__TAG__), o=True, r=True)]\n\n\ndef create_channel_master_node(name):\n \"\"\"Create a new channel master node\n\n Args:\n name (str): name of the nodes\n\n Returns:\n str: name of the channel master node\n \"\"\"\n\n # Create data node (render sphere for outliner \"icon\")\n shp = cmds.createNode(\"renderSphere\")\n cmds.setAttr(\"{}.radius\".format(shp), 0)\n cmds.setAttr(\"{}.isHistoricallyInteresting\".format(shp), 0)\n cmds.setAttr(\"{}.v\".format(shp), 0)\n\n # Rename data node\n node = cmds.listRelatives(shp, p=True)[0]\n node = cmds.rename(node, string.normalize(name))\n\n cmds.addAttr(node, ln=__TAG__, at=\"bool\", dv=True)\n cmds.setAttr(\"{}.{}\".format(node, __TAG__), k=False, l=True)\n cmds.addAttr(node, ln=\"data\", dt=\"string\")\n\n attribute.lockAttribute(pm.PyNode(node))\n\n # init data\n cmds.setAttr(\"{}.data\".format(node),\n cmu.init_channel_master_config_data(),\n type=\"string\")\n return node\n\n\ndef get_node_data(node):\n \"\"\"Get the configuration data from a node\n\n Args:\n node (str): nme of the node\n\n Returns:\n dict: configuration data\n \"\"\"\n data = cmds.getAttr(\"{}.data\".format(node))\n return ast.literal_eval(data)\n\n\ndef set_node_data(node, data):\n \"\"\"Set the node data attribute\n\n Args:\n node (str): node name\n data (dict): configuration dict\n \"\"\"\n cmds.setAttr(\"{}.data\".format(node), data, type=\"string\")\n\n\ndef export_data(node, tab=None, filePath=None):\n \"\"\"Export the node data\n\n Args:\n node (str): node to export\n tab (str, optional): if a tab name is set, only that taba will\n be exported\n filePath (str, optional): the path to save the configuration file\n\n Returns:\n TYPE: Description\n \"\"\"\n # if isinstance(node, (str, unicode)):\n # node = pm.PyNode(node)\n config = get_node_data(node)\n data = {}\n data[\"node_name\"] = node\n if tab:\n if tab in config[\"tabs_data\"].keys():\n config[\"tabs\"] = [tab]\n tabs_data = {}\n tabs_data[tab] = config[\"tabs_data\"][tab]\n config[\"tabs_data\"] = tabs_data\n else:\n keys = config[\"tabs_data\"].keys()\n pm.displayWarning(\"Tab {}, not found int current node.\".format(tab)\n + \" Available tabs are: {}\".format(keys))\n data[\"config\"] = config\n\n data_string = json.dumps(data, indent=4, sort_keys=True)\n if not filePath:\n filePath = pm.fileDialog2(\n fileMode=0,\n fileFilter='Channel Master Configuration .cmc (*%s)' % \".cmc\")\n if not filePath:\n return\n if not isinstance(filePath, string_types):\n filePath = filePath[0]\n f = open(filePath, 'w')\n f.write(data_string)\n f.close()\n\n\ndef import_data(filePath=None, node=None, add_data=False):\n \"\"\"Import and create channel master configuration nodes\n\n Args:\n filePath (str, optional): Path to the channel master config file\n node (None, str): Node to add the data. If None, will create a new node\n add_data (bool, optional): If true, will add the data to existing node\n\n Returns:\n TYPE: Description\n \"\"\"\n if not filePath:\n filePath = pm.fileDialog2(\n fileMode=1,\n fileFilter='Channel Master Configuration .cmc (*%s)' % \".cmc\")\n\n if not filePath:\n return\n if not isinstance(filePath, string_types):\n filePath = filePath[0]\n data = json.load(open(filePath))\n config = data[\"config\"]\n\n if not node:\n if data:\n node = create_channel_master_node(data[\"node_name\"])\n else:\n pm.displayWarning(\"Data not imported!\")\n return\n\n if add_data:\n config = get_node_data(node)\n for tab in data[\"config\"][\"tabs\"]:\n tab_config = data[\"config\"][\"tabs_data\"][tab]\n # ensure that tab name is unique when add to existing node\n init_tab_name = tab\n i = 1\n while tab in config[\"tabs\"]:\n tab = init_tab_name + str(i)\n i += 1\n config[\"tabs\"].append(tab)\n config[\"tabs_data\"][tab] = tab_config\n\n set_node_data(node, config)\n\n return node\n","sub_path":"release/scripts/mgear/animbits/channel_master_node.py","file_name":"channel_master_node.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"475604842","text":"\"\"\"\nsetup script with information about the project needed when packaged and uploaded to Pypi\n\"\"\"\nimport setuptools\n\nwith open(\"VERSION\", \"r\") as fh:\n VERSION = fh.read().strip()\n\nwith open(\"README.md\", \"r\") as fh:\n LONG_DESCRIPTION = fh.read()\n\nsetuptools.setup(\n name=\"mark-python-client\",\n version=VERSION,\n author=\"Georgi Nikolov\",\n author_email=\"contact@cylab.be\",\n description=\"A client library for MARK server\",\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n url=\"https://gitlab.cylab.be/cylab/mark-python-client\",\n packages=setuptools.find_packages(exclude=(\"tests\")),\n classifiers=[\n \"Programming Language :: Python :: 2.7\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ]\n)\n","sub_path":"pypi_install_script/mark-python-client-1.0.9.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"505847051","text":"import requests\nimport json\nfrom requests.auth import HTTPBasicAuth\nimport utilities\nimport logging\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\njira_username = utilities.get_parameter(\"jira-user\")\njira_password = utilities.get_parameter(\"jira-password\")\nproject = utilities.get_parameter(\"jira-project-name\")\n\n#jira_url = 'http://52.42.78.141:8080'\njira_url = 'http://localhost:5050'\n\n\n\nclass Jira():\n\n def __init__(self):\n super(Jira, self)\n\n def get_jira_auth(self):\n return HTTPBasicAuth(jira_username, jira_password)\n\n def exists(_self, record_id):\n try:\n search_ticket_url = \"{0}/rest/api/2/search?jql=project={1}+and+text~'alert +for +{2}'\".format(\n jira_url, project, record_id)\n request = requests.get(search_ticket_url,\n auth=_self.get_jira_auth())\n total_tickets = request.json()['total']\n if total_tickets > 0:\n logger.info('Ticket for this record already exists in JIRA:')\n logger.info(record_id)\n return True\n\n return False\n\n except Exception as e:\n logger.info('Failed to determine if ticket exists in JIRA')\n return True\n\n def create(self, summary, description, issuetype):\n json_values = {\n \"fields\": {\n \"project\": {\"key\": project},\n \"summary\": summary,\n \"description\": description,\n \"issuetype\": {\"name\": issuetype}\n }\n }\n try:\n headers = {'Content-Type': 'application/json'}\n create_ticket_url = '{0}/rest/api/2/issue/'.format(jira_url)\n logger.info('Creating Jira ticket with following input:')\n\n logger.info(json_values)\n\n request = requests.post(create_ticket_url, headers=headers,\n auth=self.get_jira_auth(),\n data=json.dumps(json_values))\n\n logger.info('Jira creation response:')\n logger.info(request.json)\n\n except Exception as e:\n logger.info('Error occurred while creating ticket:')\n logger.info(e)\n","sub_path":"Jira.py","file_name":"Jira.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"248072068","text":"#!/usr/local/bin/python\n\n\"\"\"All function to handle various update for GhostBSD.\"\"\"\n\nfrom os import listdir, path\nfrom subprocess import Popen, PIPE, STDOUT, call\n# import urllib\nimport platform\n\nustation_db = '/var/db/update-station/'\npkglockfile = f'{ustation_db}lock-pkgs'\npkglist = '/var/db/pkg-update-check/pkg-update-list'\nfbsduf = '/var/db/freebsd-update-check/'\npkgupdatefile = f'{ustation_db}pkg-to-upgrade'\nfbtag = f'{fbsduf}tag'\nfblist = f'{fbsduf}tag'\nfbvcmd = 'freebsd-version'\nfblist = f'{fbsduf}tag'\narch = platform.uname()[4]\ncheckfbsdupdate = 'fbsdupdatecheck check'\nfetchfbsdupdate = 'fbsdupdatecheck fetch'\ninstallfbsdupdate = 'fbsdupdatecheck install'\ncheckpkgupgrade = 'fbsdpkgupdate check'\nfetchpkgupgrade = 'pkg upgrade -Fy'\nisntallpkgupgrade = 'pkg upgrade -y'\nlockpkg = 'pkg lock -y '\nunlockallpkg = 'pkg unlock -ay'\nunlockpkg = 'pkg unlock -y '\n\nrelease = Popen('uname -r', shell=True, stdin=PIPE, stdout=PIPE,\n stderr=STDOUT, close_fds=True\n ).stdout.readlines()[0].rstrip()\n\nif not path.isdir(ustation_db):\n Popen(f'mkdir -p {ustation_db}', shell=True, close_fds=True)\n Popen(f'chmod -R 665 {ustation_db}', shell=True, close_fds=True)\n\nfbftp = 'ftp://ftp.freebsd.org/pub/'\nfbsrcurl = f'{fbftp}FreeBSD/releases/{arch}/{arch}/{release}/src.txz'\ncleandotdesktop = 'sh /usr/local/lib/update-station/cleandesktop.sh'\n\n\ndef listofinstal():\n ls = listdir(fbsduf)\n for line in ls:\n if 'install.' in line:\n uptag = open(f'{fbsduf}{line}/INDEX-NEW', 'r')\n info = uptag.readlines()\n return info\n\n\ndef lookfbsdupdate():\n if path.exists(fbtag):\n uptag = open(fbtag, 'r')\n tag = uptag.readlines()[0].rstrip().split('|')\n return f'FreeBSD Update: {tag[2]}-p{tag[3]}'\n else:\n return None\n\n\ndef updatetext():\n udatetitle = lookfbsdupdate()\n text = 'Update Details:\\n'\n text += f'{udatetitle}\\n\\n'\n text += 'The following files will be update:\\n'\n for line in listofinstal():\n txtlist = line.split('|')\n text += f'{txtlist[0]}\\n'\n return text\n\ndef runcheckupdate():\n call(checkpkgupgrade, shell=True, stdout=PIPE, close_fds=True,\n universal_newlines=True)\n return True\n\ndef pkgupdatelist():\n uppkg = open(pkglist, 'r')\n pkgarr = []\n for line in uppkg.readlines():\n if '->' in line:\n pkgarr.append(line.rstrip()[1:])\n return pkgarr\n\n\ndef lockpkg(pkglist):\n for line in pkglist:\n call(f'{pkglist}{line.rstrip()}', shell=True)\n return True\n\n\ndef unlockpkg():\n # unlock all pkg\n call(unlockpkg, shell=True)\n return True\n\n\ndef fetchpkgupdate():\n fetch = Popen(fetchpkgupgrade, shell=True, stdout=PIPE, close_fds=True,\n universal_newlines=True)\n return fetch.stdout\n\n \ndef installpkgupdate():\n install = Popen(isntallpkgupgrade, shell=True, stdout=PIPE, close_fds=True,\n universal_newlines=True)\n return install.stdout\n\n \ndef checkforupdate():\n uptag = open(pkglist, 'r')\n return 'UPGRADED:' in uptag.read()\n","sub_path":"src/updateHandler.py","file_name":"updateHandler.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"645212976","text":"import torch\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow.keras.backend as K\r\nfrom collections import Iterable\r\nfrom typing import Any, Optional\r\n\r\nfrom graphgallery import backend, intx, floatx\r\nfrom graphgallery.utils.raise_error import assert_kind\r\n\r\n__all__ = ['is_iterable',\r\n 'is_list_like',\r\n 'is_scalar_like',\r\n 'is_interger_scalar',\r\n 'infer_type',\r\n 'is_tensor',\r\n 'is_strided_tensor',\r\n 'is_sparse_tensor',\r\n ]\r\n\r\ndef is_iterable(obj: Any) -> bool:\r\n \"\"\"check whether `x` is an iterable object but not string\"\"\"\r\n return isinstance(obj, Iterable) and not isinstance(obj, str)\r\n\r\n\r\ndef is_list_like(x: Any) -> bool:\r\n \"\"\"Check whether `x` is list like, e.g., Tuple or List.\r\n\r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a list like sequence.\r\n \"\"\"\r\n return isinstance(x, (list, tuple))\r\n\r\n\r\ndef is_scalar_like(x: Any) -> bool:\r\n \"\"\"Check whether `x` is a scalar, an array scalar, or a 0-dim array.\r\n\r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a scalar, an array scalar, or a 0-dim array.\r\n \"\"\"\r\n return np.isscalar(x) or (isinstance(x, np.ndarray) and x.ndim == 0)\r\n\r\n\r\ndef is_interger_scalar(x: Any) -> bool:\r\n \"\"\"Check whether `x` is an Integer scalar.\r\n\r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a Integer scalar (built-in or Numpy integer).\r\n \"\"\"\r\n return isinstance(x, (int, np.int8,\r\n np.int16,\r\n np.int32,\r\n np.int64,\r\n np.uint8,\r\n np.uint16,\r\n np.uint32,\r\n np.uint64,\r\n ))\r\n \r\n\r\ndef infer_type(x: Any) -> bool:\r\n \"\"\"Infer type of the input `x`.\r\n\r\n Parameters:\r\n ----------\r\n x: Any python object\r\n\r\n Returns:\r\n ----------\r\n dtype: string, the converted type of `x`:\r\n 1. `graphgallery.floatx()` if `x` is floating\r\n 2. `graphgallery.intx()` if `x` is integer\r\n 3. `'bool'` if `x` is bool.\r\n\r\n \"\"\"\r\n # For tensor or variable\r\n if is_th_tensor(x):\r\n if x.dtype.is_floating_point:\r\n return floatx()\r\n elif x.dtype == torch.bool:\r\n return 'bool'\r\n elif 'int' in str(x.dtype):\r\n return intx()\r\n else:\r\n raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n \r\n elif is_tf_tensor(x):\r\n if x.dtype.is_floating:\r\n return floatx()\r\n elif x.dtype.is_integer or x.dtype.is_unsigned:\r\n return intx()\r\n elif x.dtype.is_bool:\r\n return 'bool'\r\n else:\r\n raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n\r\n if not hasattr(x, 'dtype'):\r\n x = np.asarray(x)\r\n\r\n if x.dtype.kind in {'f', 'c'}:\r\n return floatx()\r\n elif x.dtype.kind in {'i', 'u'}:\r\n return intx()\r\n elif x.dtype.kind == 'b':\r\n return 'bool'\r\n elif x.dtype.kind == 'O':\r\n raise RuntimeError(f'Invalid inputs of `{x}`.')\r\n else:\r\n raise RuntimeError(f'Invalid input of `{type(x)}`')\r\n \r\n\r\ndef is_sparse_tensor(x: Any, kind: Optional[str] = None) -> bool:\r\n \"\"\"Check whether `x` is a sparse Tensor.\r\n \r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n \r\n kind: str, optional.\r\n \"T\" for TensorFlow\r\n \"P\" for PyTorch\r\n if not specified, using `backend().kind` instead. \r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a (tf or torch) sparse-tensor.\r\n \"\"\"\r\n if kind is None:\r\n kind = backend().kind\r\n else:\r\n assert_kind(kind)\r\n \r\n if kind == \"T\":\r\n return is_tf_sparse_tensor(x)\r\n else:\r\n return is_th_sparse_tensor(x)\r\n\r\n\r\ndef is_strided_tensor(x: Any, kind: Optional[str] = None) -> bool:\r\n \"\"\"Check whether `x` is a strided (dense) Tensor.\r\n \r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n \r\n kind: str, optional.\r\n \"T\" for TensorFlow\r\n \"P\" for PyTorch\r\n if not specified, using `backend().kind` instead. \r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a (tf or torch) strided (dense) Tensor.\r\n \"\"\"\r\n \r\n if kind is None:\r\n kind = backend().kind\r\n else:\r\n assert_kind(kind)\r\n \r\n if kind == \"T\":\r\n return is_tf_strided_tensor(x)\r\n else:\r\n return is_th_strided_tensor(x)\r\n \r\n\r\ndef is_tensor(x: Any, kind: Optional[str]=None) -> bool:\r\n \"\"\"Check whether `x` is \r\n tf.Tensor,\r\n tf.Variable,\r\n tf.RaggedTensor,\r\n tf.sparse.SparseTensor,\r\n torch.Tensor, \r\n torch.sparse.Tensor.\r\n\r\n Parameters:\r\n ----------\r\n x: A python object to check.\r\n \r\n kind: str, optional.\r\n \"T\" for TensorFlow\r\n \"P\" for PyTorch\r\n if not specified, using `backend().kind` instead. \r\n\r\n Returns:\r\n ----------\r\n `True` iff `x` is a (tf or torch) (sparse-)tensor.\r\n \"\"\"\r\n if kind is None:\r\n kind = backend().kind\r\n else:\r\n assert_kind(kind)\r\n \r\n if kind == \"T\":\r\n return is_tf_tensor(x)\r\n else:\r\n return is_th_tensor(x)\r\n\r\n\r\ndef is_tf_sparse_tensor(x: Any) -> bool:\r\n return K.is_sparse(x)\r\n\r\n\r\ndef is_th_sparse_tensor(x: Any) -> bool:\r\n return is_th_tensor(x) and not is_th_strided_tensor(x)\r\n\r\n\r\ndef is_tf_strided_tensor(x: Any) -> bool:\r\n return any((isinstance(x, tf.Tensor),\r\n isinstance(x, tf.Variable),\r\n isinstance(x, tf.RaggedTensor)))\r\n\r\n\r\ndef is_th_strided_tensor(x: Any) -> bool:\r\n return is_th_tensor(x) and x.layout == torch.strided\r\n \r\ndef is_tf_tensor(x: Any) -> bool:\r\n return is_tf_strided_tensor(x) or is_tf_sparse_tensor(x)\r\n\r\ndef is_th_tensor(x: Any) -> bool:\r\n return torch.is_tensor(x)\r\n","sub_path":"graphgallery/utils/type_check.py","file_name":"type_check.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"581371753","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\n\nclass Net(nn.Module):\n def __init__(self, model_name):\n super(Net, self).__init__()\n self.model_name = model_name\n \n if self.model_name == 'resnet50':\n backbone = models.resnet50(pretrained = True)\n self.features = nn.Sequential(*list(backbone.children())[:-2])\n num_features = backbone.fc.in_features\n\n if self.model_name == 'densenet121':\n backbone = models.densenet121(pretrained = True)\n self.features = nn.Sequential(*list(backbone.children())[:-1])\n num_features = backbone.classifier.in_features\n\n \n self.pool = LSEPool2d()\n self.fc = nn.Sequential(\n nn.Linear(num_features, 14),\n nn.Sigmoid())\n\n def forward(self, x):\n features = self.features(x)\n pool = self.pool(features)\n out_after_pooling = pool.view(pool.size(0), -1)\n out = self.fc(out_after_pooling)\n return out, features, out_after_pooling\n\nclass FusionNet(nn.Module):\n def __init__(self, model):\n super(FusionNet, self).__init__()\n self.model = model\n\n if self.model == 'resnet50':\n self.fc = nn.Linear(2048*2, 14)\n\n if self.model == 'densenet121':\n self.fc = nn.Linear(1024*2, 14)\n \n self.sigmoid = nn.Sigmoid()\n\n def forward(self, global_pool, local_pool):\n fusion = torch.cat((global_pool,local_pool), 1)\n out = self.fc(fusion)\n out = self.sigmoid(out)\n return out\n\nclass LSEPool2d(nn.Module):\n def __init__(self, r = 10):\n super(LSEPool2d, self).__init__()\n self.r = r\n self.maxpool = nn.MaxPool2d(kernel_size = 7, stride = 1)\n\n def forward(self, x):\n xmaxpool = torch.abs(x)\n xmaxpool = self.maxpool(xmaxpool)\n xpool = (1 / (x.shape[-1] * x.shape[-2])) * torch.sum(torch.exp(self.r * (x - xmaxpool)), dim = (-2, -1))\n xpool = xmaxpool + (1 / self.r) * torch.log(xpool).unsqueeze(-1).unsqueeze(-1)\n return xpool\n\ndef weighted_binary_cross_entropy(sigmoid_x, targets, pos_weight, neg_weight, weight=None, size_average=True, reduce=True):\n \"\"\"\n Args:\n sigmoid_x: predicted probability of size [N,C], N sample and C Class. Eg. Must be in range of [0,1], i.e. Output from Sigmoid.\n targets: true value, one-hot-like vector of size [N,C]\n pos_weight: Weight for postive sample\n \"\"\"\n if not (targets.size() == sigmoid_x.size()):\n raise ValueError(\"Target size ({}) must be the same as input size ({})\".format(targets.size(), sigmoid_x.size()))\n\n sigmoid_x = sigmoid_x.clamp(min=1e-7, max=1-1e-7)\n loss = - pos_weight * targets * sigmoid_x.log().clamp(min=-100) - neg_weight * (1 - targets) * (1 - sigmoid_x).log().clamp(min=-100)\n\n if weight is not None:\n loss = loss * weight\n\n if not reduce:\n return loss\n elif size_average:\n return loss.mean()\n else:\n return loss.sum()\n\nclass WeightedBCELoss(nn.Module):\n def __init__(self, pos_weight=1, neg_weight=1, weight=None, PosNegWeightIsDynamic=False, WeightIsDynamic=False, size_average=True, reduce=True):\n \"\"\"\n Args:\n pos_weight = Weight for postive samples. Size [1,C]\n weight = Weight for Each class. Size [1,C]\n PosWeightIsDynamic: If True, the pos_weight is computed on each batch. If pos_weight is None, then it remains None.\n WeightIsDynamic: If True, the weight is computed on each batch. If weight is None, then it remains None.\n \"\"\"\n super().__init__()\n\n self.register_buffer('weight', weight)\n self.register_buffer('pos_weight', torch.tensor(pos_weight))\n self.register_buffer('neg_weight', torch.tensor(neg_weight))\n self.size_average = size_average\n self.reduce = reduce\n self.PosNegWeightIsDynamic = PosNegWeightIsDynamic\n\n def forward(self, input, target):\n if self.PosNegWeightIsDynamic:\n len_target = target.numel()\n positive_counts = target.sum()\n negative_counts = len_target - positive_counts\n self.pos_weight = len_target / positive_counts.clamp(min = 1)\n self.neg_weight = len_target / negative_counts.clamp(min = 1)\n\n if self.weight is not None:\n return weighted_binary_cross_entropy(input, target,\n self.pos_weight,\n self.neg_weight,\n weight=self.weight,\n size_average=self.size_average,\n reduce=self.reduce)\n else:\n return weighted_binary_cross_entropy(input, target,\n self.pos_weight,\n self.neg_weight,\n weight=None,\n size_average=self.size_average,\n reduce=self.reduce)","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"202653434","text":"import random\nfrom decimal import Decimal, getcontext\nfrom typing import Dict, Generic, List, Set, TypeVar\n\nZERO = Decimal('0.00000')\nONE = Decimal('1.00000')\n\nT = TypeVar('T')\n\n\nclass Vote(Generic[T]):\n def __init__(self, choices: List[T]):\n self.weight: Decimal = ONE\n self.choice_stack: List[T] = list(reversed(choices))\n\n def transfer(self, transfer_weight: Decimal, remaining_candidates: Set[T]) -> None:\n self.weight *= transfer_weight\n self.choice_stack.pop()\n while self.choice_stack and self.choice_stack[-1] not in remaining_candidates:\n self.choice_stack.pop()\n\n\nclass CandidateVotes(Generic[T]):\n def __init__(self, candidate: T):\n self.candidate: T = candidate\n self.total: Decimal = ZERO\n self.transfer_total: Decimal = ZERO\n self.votes: List[Vote[T]] = []\n\n\nclass STVElection(Generic[T]):\n def __init__(self, candidates: List[T], num_winners: int, choices_list: List[List[T]]):\n self.votes: List[Vote[T]] = [Vote(choices) for choices in choices_list]\n self.winners: List[T] = []\n self.remaining_candidates: Set[T] = set(candidates)\n self.num_winners: int = num_winners\n self.previous_rounds: List[Dict[CandidateVotes[T], dict]] = []\n\n self.quota = int(len(self.votes) / (self.num_winners + 1)) + 1\n getcontext().prec = 5\n\n def hold_election(self) -> List[T]:\n while len(self.winners) < self.num_winners and len(self.remaining_candidates) > 0:\n self.count_votes()\n return self.winners\n\n def count_votes(self) -> None:\n candidate_votes: Dict[T, CandidateVotes[T]] = {candidate: CandidateVotes(candidate) for candidate in self.remaining_candidates}\n for vote in self.votes: # type: Vote[T]\n if len(vote.choice_stack) > 0 and vote.weight > ZERO:\n cv = candidate_votes[vote.choice_stack[-1]]\n cv.total += vote.weight\n # If this is a transfer vote, record it as such\n if vote.weight < ONE:\n cv.transfer_total += vote.weight\n cv.votes.append(vote)\n self.previous_rounds.append(\n {\n cv.candidate: {'total_votes': cv.total, 'total_transfer_votes': cv.transfer_total}\n for cv in candidate_votes.values()\n }\n )\n\n result = list(candidate_votes.values())\n result.sort(key=lambda x: x.total, reverse=True)\n if result[0].total >= self.quota or len(self.remaining_candidates) <= self.num_winners - len(self.winners):\n i = 0\n round_winners = []\n while i < len(result) and result[i].total == result[0].total:\n round_winners.append(result[i])\n i += 1\n winner = self.break_tie(round_winners, len(self.previous_rounds) - 1, True)\n self.winners.append(winner.candidate)\n self.remaining_candidates.remove(winner.candidate)\n if winner.total > self.quota:\n transfer_weight = Decimal((winner.total - self.quota) / winner.total).quantize(ZERO)\n else:\n transfer_weight = ZERO\n for vote in winner.votes:\n vote.transfer(transfer_weight, self.remaining_candidates)\n else:\n i = len(result) - 1\n round_losers = []\n while i >= 0 and result[i].total == result[-1].total:\n round_losers.append(result[i])\n i -= 1\n loser = self.break_tie(round_losers, len(self.previous_rounds) - 1, False)\n self.remaining_candidates.remove(loser.candidate)\n for vote in loser.votes:\n vote.transfer(ONE, self.remaining_candidates)\n\n def break_tie(self, round_winners: List[CandidateVotes[T]], voting_round: int, win: bool) -> CandidateVotes[T]:\n multiplier = 1 if win else -1\n if len(round_winners) == 1:\n return round_winners[0]\n if voting_round == 0:\n return random.choice(round_winners)\n max_vote = None\n next_round_winners = []\n for winner in round_winners:\n total = multiplier * self.previous_rounds[voting_round - 1][winner.candidate]['total_votes']\n if max_vote is None or total > max_vote:\n next_round_winners = [winner]\n max_vote = total\n elif total == max_vote:\n next_round_winners.append(winner)\n return self.break_tie(next_round_winners, voting_round - 1, win)\n","sub_path":"membership/util/vote.py","file_name":"vote.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514194901","text":"\n\"\"\"Functions\"\"\"\nimport os\nimport sys\nfrom sys import exit, stderr, argv, path, modules\nfrom os.path import isfile, isdir, realpath, dirname, exists\nfrom scipy.optimize import bisect\nimport csv\nimport yaml\nimport numpy as np\nimport pandas as pd\n# plotting\nimport seaborn.apionly as sns\nfrom scipy.optimize import bisect\nfrom matplotlib import rc\nimport matplotlib.lines as mlines\nimport pylab as plt\nimport matplotlib\nfrom matplotlib.ticker import NullFormatter\n\n# ESTIMATOR_DIR = '{}/../..'.format(dirname(realpath(__file__)))\nESTIMATOR_DIR = '/home/lucas/research/projects/history_dependence/hdestimator'\npath.insert(1, '{}/src'.format(ESTIMATOR_DIR))\nif 'hde_glm' not in modules:\n import hde_glm as glm\n import hde_utils as utl\n import hde_plotutils as plots\n\n# fig = dirname(realpath(__file__)).split(\"/\")[-1]\nfig = 'supplementaries'\nPLOTTING_DIR = '/home/lucas/research/papers/history_dependence/arXiv/figs/{}'.format(\n fig)\n\nrec_lengths = ['1min', '3min', '5min', '10min', '20min', '45min', '90min']\nrec_length_values = [60., 180., 300., 600., 1200., 2700., 5400.]\nrec_lengths_colors_bbc = [sns.color_palette(\"RdBu_r\", 15)[8], sns.color_palette(\"RdBu_r\", 15)[9], sns.color_palette(\"RdBu_r\", 15)[10], sns.color_palette(\n \"RdBu_r\", 15)[11], sns.color_palette(\"RdBu_r\", 15)[12], sns.color_palette(\"RdBu_r\", 15)[13], sns.color_palette(\"RdBu_r\", 15)[14]]\nsetups = np.array([['full_bbc','full_bbc_withCV'], ['full_shuffling','full_shuffling_withCV']])\n# Only plot first sample\n\n\"\"\"Plotting\"\"\"\nrc('text', usetex=True)\nmatplotlib.rcParams['font.size'] = '15.0'\nmatplotlib.rcParams['xtick.labelsize'] = '15'\nmatplotlib.rcParams['ytick.labelsize'] = '15'\nmatplotlib.rcParams['legend.fontsize'] = '15'\nmatplotlib.rcParams['axes.linewidth'] = 0.6\n\n\n# Colors\nrec_length_colors = {'bbc-1min': sns.color_palette(\"RdBu_r\", 16)[9],\n 'bbc-3min': sns.color_palette(\"RdBu_r\", 16)[10],\n 'bbc-5min': sns.color_palette(\"RdBu_r\", 16)[11],\n 'bbc-10min': sns.color_palette(\"RdBu_r\", 16)[12],\n 'bbc-20min': sns.color_palette(\"RdBu_r\", 16)[13],\n 'bbc-45min': sns.color_palette(\"RdBu_r\", 16)[14],\n 'bbc-90min': sns.color_palette(\"RdBu_r\", 16)[15],\n 'shuffling-1min': sns.color_palette(\"RdBu_r\", 16)[6],\n 'shuffling-3min': sns.color_palette(\"RdBu_r\", 16)[5],\n 'shuffling-5min': sns.color_palette(\"RdBu_r\", 16)[4],\n 'shuffling-10min': sns.color_palette(\"RdBu_r\", 16)[3],\n 'shuffling-20min': sns.color_palette(\"RdBu_r\", 16)[2],\n 'shuffling-45min': sns.color_palette(\"RdBu_r\", 16)[1],\n 'shuffling-90min': sns.color_palette(\"RdBu_r\", 16)[0]}\n\n\n\"\"\"Load data for all plots\"\"\"\n# median_rel_bias_lowT = {}\n# median_CI_rel_bias_lowT = {}\n# median_rel_bias_mediumT = {}\n# median_CI_rel_bias_mediumT = {}\n# median_rel_bias_highT = {}\n# median_CI_rel_bias_highT = {}\n# median_rel_bias_T_D = {}\n# median_CI_rel_bias_T_D = {}\n# mean_rel_bias_T_D = {}\n# mean_CI_rel_bias_T_D = {}\n\nmean_rel_deviation_R_tot = {}\nmean_CI_rel_deviation_R_tot = {}\n\nfor setup in setups.flatten():\n # Load settings from yaml file\n with open('{}/settings/Simulation_{}.yaml'.format(ESTIMATOR_DIR, setup), 'r') as analysis_settings_file:\n analysis_settings = yaml.load(\n analysis_settings_file, Loader=yaml.BaseLoader)\n ANALYSIS_DIR = analysis_settings['ANALYSIS_DIR']\n T = np.array(analysis_settings['embedding_past_range_set']).astype(float)\n regularization_method = setup.split(\"_\")[1]\n for rec_length in rec_lengths:\n rel_deviation_R_tot = []\n # rel_bias_bbc = []\n # rel_bias_bbc_lowT = []\n # rel_bias_bbc_mediumT = []\n # rel_bias_bbc_highT = []\n # rel_bias_bbc_T_D = []\n # rel_bias_shuffling = []\n # rel_bias_shuffling_lowT = []\n # rel_bias_shuffling_mediumT = []\n # rel_bias_shuffling_highT = []\n # rel_bias_shuffling_T_D = []\n number_samples = 30\n if rec_length == '45min':\n number_samples = 10\n if rec_length == '90min':\n number_samples = 10\n for sample_index in np.arange(1, number_samples):\n analysis_num_str = glm.load_embedding_parameters(\n rec_length, sample_index, analysis_settings)[1]\n # Embedding optimized estimates and confidence intervals\n hisdep_csv_file_name = '{}/ANALYSIS{}/histdep_data.csv'.format(\n ANALYSIS_DIR, analysis_num_str)\n hisdep_pd = pd.read_csv(hisdep_csv_file_name)\n R = np.array(hisdep_pd['max_R_{}'.format(regularization_method)])\n R_CI_lo = np.array(hisdep_pd['max_R_{}_CI_lo'.format(regularization_method)])\n T = np.array(hisdep_pd['#T'])\n R_tot, T_D_index, max_valid_index = plots.get_R_tot(T, R, R_CI_lo)\n\n # Embedding optimized estimates and confidence intervals\n # hisdep_csv_file_name = '{}/ANALYSIS{}/histdep_data.csv'.format(\n # ANALYSIS_DIR, analysis_num_str)\n # hisdep_pd = pd.read_csv(hisdep_csv_file_name)\n # R_bbc = np.array(hisdep_pd['max_R_bbc'])\n # R_shuffling = np.array(hisdep_pd['max_R_shuffling'])\n # T = np.array(hisdep_pd['#T'])\n # T_D, R_tot_bbc, R_tot_std, T_D_index_bbc, max_valid_index_bbc = plots.get_temporal_depth_and_R_tot(T, R_bbc)\n # T_D, R_tot_shuffling, R_tot_std, T_D_index_shuffling, max_valid_index_shuffling = plots.get_temporal_depth_and_R_tot(T, R_shuffling)\n\n # Temporal depth and total history dependence\n # statistics_csv_file_name = '{}/ANALYSIS{}/statistics.csv'.format(\n # ANALYSIS_DIR, analysis_num_str)\n # statistics_pd = pd.read_csv(statistics_csv_file_name)\n\n glm_csv_file_name = '{}/ANALYSIS{}/glm_benchmark_{}.csv'.format(\n ANALYSIS_DIR, analysis_num_str, regularization_method)\n glm_pd = pd.read_csv(glm_csv_file_name)\n T_glm = np.array(glm_pd['T'])\n R_glm = np.array(glm_pd['R_GLM'])\n # Make sure that you only average R_GLM over the right T\n if T_glm[0]>T[T_D_index]:\n print(setup, rec_length, sample_index)\n else:\n T_D_index_glm = np.where(T_glm == T[T_D_index])[0][0]\n max_valid_index_glm = np.where(T_glm == T[max_valid_index-1])[0][0]+1\n R_tot_glm = np.mean(R_glm[T_D_index_glm:max_valid_index_glm])\n # T_D_index = np.where(np.array(hisdep_pd['#T'])==T[0])[0][0]\n # max_valid_index = np.where(np.array(hisdep_pd['#T'])==T[-1])[0][0]+1\n # R_bbc = R_bbc[T_D_index:max_valid_index]\n\n # TODO: Recompute T based on T in glm benchmark file to load R_tot_glm_bbc\n # R_tot_bbc = statistics_pd['R_tot_bbc'][0]\n # T_D_bbc = statistics_pd['T_D_bbc'][0]\n # T_index = np.where(T == T_D_bbc)[0][0]\n # R_tot_glm_bbc = R_glm_bbc[T_index]\n\n # glm_shuffling_csv_file_name = '{}/ANALYSIS{}/glm_benchmark_shuffling.csv'.format(\n # ANALYSIS_DIR, analysis_num_str)\n # glm_shuffling_pd = pd.read_csv(glm_shuffling_csv_file_name)\n # T = np.array(glm_shuffling_pd['T'])\n # R_glm_shuffling = np.array(glm_shuffling_pd['R_GLM'])\n # T_D_index = np.where(np.array(hisdep_pd['#T'])==T[0])[0][0]\n # max_valid_index = np.where(np.array(hisdep_pd['#T'])==T[-1])[0][0]+1\n # R_shuffling = R_shuffling[T_D_index:max_valid_index]\n\n #\n # R_tot_shuffling = statistics_pd['R_tot_shuffling'][0]\n # T_D_shuffling = statistics_pd['T_D_shuffling'][0]\n # T_index = np.where(T == T_D_shuffling)[0][0]\n # R_tot_glm_shuffling = R_glm_shuffling[T_index]\n\n # rel_bias_bbc += [100 * (R_bbc - R_glm_bbc) / R_glm_bbc]\n # rel_bias_shuffling += [100 * (R_shuffling -\n # R_glm_shuffling) / R_glm_shuffling]\n # rel_bias_bbc_lowT += [100 *\n # (R_bbc[10] - R_glm_bbc[10]) / R_glm_bbc[10]]\n # rel_bias_bbc_mediumT += [100 *\n # (R_bbc[30] - R_glm_bbc[30]) / R_glm_bbc[30]]\n # rel_bias_bbc_highT += [100 *\n # (R_bbc[50] - R_glm_bbc[50]) / R_glm_bbc[50]]\n # rel_bias_bbc_T_D += [100 *\n # (R_tot_bbc - R_tot_glm_bbc) / R_tot_glm_bbc]\n # rel_bias_bbc_T_D += [100 *\n # np.mean(R_bbc - R_glm_bbc) / R_tot_bbc]\n rel_deviation_R_tot += [100* (R_tot-R_tot_glm)/R_tot_glm]\n # rel_bias_shuffling_lowT += [\n # 100 * (R_shuffling[10] - R_glm_shuffling[10]) / R_glm_shuffling[10]]\n # rel_bias_shuffling_mediumT += [\n # 100 * (R_shuffling[30] - R_glm_shuffling[30]) / R_glm_shuffling[30]]\n # rel_bias_shuffling_highT += [\n # 100 * (R_shuffling[50] - R_glm_shuffling[50]) / R_glm_shuffling[50]]\n\n\n # rel_bias_shuffling_T_D += [100 *\n # (R_tot_shuffling - R_tot_glm_shuffling) / R_tot_glm_shuffling]\n # rel_bias_shuffling_T_D += [100 *\n # np.mean(R_shuffling - R_glm_shuffling) / R_tot_shuffling]\n\n # median_rel_bias_lowT['bbc-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_bbc_lowT)\n # median_CI_rel_bias_lowT['bbc-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_bbc_lowT)\n # median_rel_bias_lowT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_shuffling_lowT)\n # median_CI_rel_bias_lowT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_shuffling_lowT)\n # median_rel_bias_mediumT['bbc-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_bbc_mediumT)\n # median_CI_rel_bias_mediumT['bbc-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_bbc_mediumT)\n # median_rel_bias_mediumT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_shuffling_mediumT)\n # median_CI_rel_bias_mediumT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_shuffling_mediumT)\n # median_rel_bias_highT['bbc-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_bbc_highT)\n # median_CI_rel_bias_highT['bbc-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_bbc_highT)\n # median_rel_bias_highT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_shuffling_highT)\n # median_CI_rel_bias_highT['shuffling-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_shuffling_highT)\n # median_rel_bias_T_D['bbc-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_bbc_T_D)\n # median_CI_rel_bias_T_D['bbc-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_bbc_T_D)\n # median_rel_bias_T_D['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.median(rel_bias_shuffling_T_D)\n # median_CI_rel_bias_T_D['shuffling-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_median(rel_bias_shuffling_T_D)\n mean_rel_deviation_R_tot['{}-{}'.format(setup, rec_length)\n ] = np.mean(rel_deviation_R_tot)\n mean_CI_rel_deviation_R_tot['{}-{}'.format(setup, rec_length)] = plots.get_CI_mean(rel_deviation_R_tot)\n # mean_rel_bias_T_D['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.mean(rel_bias_shuffling_T_D)\n # mean_CI_rel_bias_T_D['shuffling-{}-{}'.format(setup, rec_length)\n # ] = plots.get_CI_mean(rel_bias_shuffling_T_D)\n\n # mean_rel_bias['shuffling-{}-{}'.format(setup, rec_length)] = np.median(\n # rel_bias_shuffling)\n # std_rel_bias['bbc-{}-{}'.format(setup, rec_length)\n # ] = np.std(rel_bias_bbc)\n # std_rel_bias['shuffling-{}-{}'.format(setup, rec_length)\n # ] = np.std(rel_bias_shuffling)\n\n# for regularization in ['bbc', 'shuffling']:\n# for rec_length in rec_lengths:\n# print(rec_length + ' no CV: ', median_rel_bias_T_D['{}-full_noCV-{}'.format(regularization, rec_length)], median_CI_rel_bias_T_D['{}-full_noCV-{}'.format(regularization, rec_length)],\n# 'with CV: ', median_rel_bias_T_D['{}-full-{}'.format(regularization, rec_length)], median_CI_rel_bias_T_D['{}-full-{}'.format(regularization, rec_length)])\n\"\"\"Plotting\"\"\"\nfig, (axes) = plt.subplots(2, 2, figsize=(10, 6))\n# fig.set_size_inches(4, 3)\nfor j in range(2):\n for k in range(2):\n setup = setups[k][j]\n ax = axes[k][j]\n regularization_method = setup.split(\"_\")[1]\n # plot settings\n # ax.set_xlabel(r'past range $T$ [sec]')\n # ax.set_xscale('log')\n # ax.set_xlim((0.01, 3.5))\n # # ax.set_xticks(np.array([1, 10, 50]))\n # ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\n # ax.spines['bottom'].set_bounds(0.01, 3)\n # # ax.set_xlabel(r'memory depth $T_m$ (sec)')\n\n x = rec_length_values\n labels = ['1', '3', '5', '10', '20', '45', '90']\n\n ax.set_xscale('log')\n ax.set_xlim((50, 22500))\n ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())\n ax.xaxis.set_major_formatter(NullFormatter())\n ax.xaxis.set_minor_formatter(NullFormatter())\n ax.spines['bottom'].set_bounds(50, 5500)\n ax.minorticks_off()\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n # plt.xticks(x, labels, rotation='horizontal')\n # ax.set_xlabel(r'recording time $T_{rec}$ (min)')\n\n ##### y-axis ####\n # ax.set_ylabel(r'$M$')\n ax.set_ylim((-10, 10))\n # ax.set_yticks([0.0, 0.08, 0.16])\n # ax.spines['left'].set_bounds(.0, 0.16)\n\n ##### Unset Borders #####\n ax.spines['top'].set_bounds(0, 0)\n ax.spines['right'].set_bounds(0, 0)\n # only plot labels and legend for left-hand side\n if not setup.split('_')[-1] == 'withCV':\n # ax.set_xlabel(r'past range $T$ [sec]')\n ax.set_ylabel(r'relative bias for $\\hat{R}_{\\mathrm{tot}}$ [\\%]')\n if regularization_method == 'shuffling':\n ax.set_xlabel(r'recording time $T_{\\mathrm{rec}}$ [min]')\n\n if not setup.split('_')[-1] == 'withCV':\n ax.set_title(\n '{}, embedding-optimized estimate'.format(regularization_method))\n else:\n ax.set_title('{}, cross-validation'.format(regularization_method))\n ax.plot(rec_length_values, np.zeros(len(rec_lengths)), color='0')\n\n # legend only for no cross-validation\n for i, rec_length in enumerate(rec_lengths):\n # median_rel_bias_T_D_val = median_rel_bias_T_D['{}-{}-{}'.format(\n # regularization, setup, rec_length)]\n # median_CI_rel_bias_T_D_val = median_CI_rel_bias_T_D['{}-{}-{}'.format(\n # regularization, setup, rec_length)]\n # median_CI_lo = median_CI_rel_bias_T_D_val[0] - \\\n # median_rel_bias_T_D_val\n # median_CI_hi = median_CI_rel_bias_T_D_val[1] - \\\n # median_rel_bias_T_D_val\n mean_rel_deviation_R_tot_val = mean_rel_deviation_R_tot['{}-{}'.format(\n setup, rec_length)]\n mean_CI_rel_deviation_R_tot_val = mean_CI_rel_deviation_R_tot['{}-{}'.format(\n setup, rec_length)]\n mean_CI_lo = mean_CI_rel_deviation_R_tot_val[0] - mean_rel_deviation_R_tot_val\n mean_CI_hi = mean_CI_rel_deviation_R_tot_val[1] - mean_rel_deviation_R_tot_val\n # mean_rel_bias_arr = mean_rel_bias['{}-{}-{}'.format(\n # regularization, setup, rec_length)]\n # std_rel_bias_arr = std_rel_bias['{}-{}-{}'.format(\n # regularization, setup, rec_length)]\n # ax.plot(T, mean_rel_bias_arr,\n # linewidth=1.,\n # color=rec_length_colors['{}-{}'.format(\n # regularization, rec_length)],\n # label=rec_length,\n # zorder=4)\n ax.errorbar(x=[rec_length_values[i]], y=[mean_rel_deviation_R_tot_val], yerr=[[-mean_CI_lo], [mean_CI_hi]],\n color=rec_length_colors['{}-45min'.format(\n regularization_method)], marker='d', markersize=5.)\n # ax.fill_between(T, mean_rel_bias_arr - std_rel_bias_arr,\n # mean_rel_bias_arr + std_rel_bias_arr,\n # facecolor=rec_length_colors['{}-{}'.format(\n # regularization, rec_length)],\n # alpha=0.4)\n if setup == 'full':\n ax.legend(loc=(.6, .3), frameon=False)\n # sns.palplot(sns.color_palette(\"RdBu_r\", 15)) #visualize the color palette\n # ax.set_color_cycle(sns.color_palette(\"coolwarm_r\",num_lines)) setting it\n # as color cycle to do automatised color assignment\n\n##########################################\n########## Simulated Conventional ########\n##########################################\n\n# ax.text(0.012, M_max + 0.02 * M_max, r'$\\hat{R}_{tot}$')\n# ax.text(T_D_shuffling + 0.15 * Tm_eff, .101, r'$\\hat{T}_D$')\n\nfig.tight_layout(pad=1.0, w_pad=1.0, h_pad=1.0)\n\nplt.savefig('{}/Rtot_bias_vs_Trec_comparison.pdf'.format(PLOTTING_DIR),\n format=\"pdf\", bbox_inches='tight')\nplt.show()\nplt.close()\n","sub_path":"plots/supplementaries/Rtot_bias_vs_Trec_comparison_old.py","file_name":"Rtot_bias_vs_Trec_comparison_old.py","file_ext":"py","file_size_in_byte":18433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"229278966","text":"D = {}\nD2 = {}\ninFile = open(\"nationwidechildrens.org_clinical_patient_ucec.txt\")\nhead = inFile.readline()\nhead = inFile.readline()\nhead = inFile.readline()\n\nfor line in inFile:\n line = line.strip()\n fields = line.split(\"\\t\")\n if len(fields) > 1:\n sample = fields[0]\n D[sample] = [fields[6], fields[17], fields[21], fields[31]]\ninFile.close()\n\ninFile = open(\"UCEC-samples\")\nouFile = open(\"UCEC-samples-phenotype\", 'w')\nfor line in inFile:\n fields = line.split()\n fds = fields[0].split('-')\n k = '-'.join(fds[0:3])\n if k in D:\n ouFile.write(fields[0] + '\\t' + '\\t'.join(D[k])+'\\n')\n else:\n ouFile.write(fields[0] + '\\t' + '\\t'.join(['NA','NA','NA','NA'])+'\\n')\ninFile.close()\nouFile.close()\n\n","sub_path":"NGLY1/TCGA-NGLY1/UCEC-phenotype.py","file_name":"UCEC-phenotype.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"111920684","text":"\"\"\"\nExercise 1 : calculation\n\"\"\"\n\n# 1. How many seconds are there in 21 minutes and 15 seconds?\none = 21 * 60 + 15\nprint(f\"1: {one} seconds\")\n\n# 2. How many miles are there in 5 kilometers? # 0.62137119223733 miles in 1 kilometer\ntwo = 0.62 * 5\nprint(f\"2: {two} miles\")\n\n# 3. If you run a 5 kilometer race in 21 minutes and 15 seconds, what is your average pace (time per mile in minutes and seconds)?\nthree = one / two\nprint(f\"3: {three} sec/mile\")\n\n# 4. What is your average speed in miles per hour?\n# 60 * 60 sec == 1 hour\nfour = two / (one/3600)\nprint(f\"4: {four} m/h\")\n\n# 5. Suppose the cover price of a book is $19.95, but bookstores get a 25% discount. Shipping costs $2.50 for the first copy and $1 for each additional copy. What is the total wholesale cost for 75 copies?\ndef costCal(numOfBook):\n price = 19.95\n total_price_book = price * numOfBook\n discounted = total_price_book * 0.75\n shipping = 2.50 + (numOfBook - 1) * 1\n return discounted + shipping\n \nprint(f\"5: ${costCal(75)}\")\n\n\n\"\"\"\nExercise 2 : function object\n\"\"\"\ndef do_twice(arg1, arg2):\n arg1(arg2)\n arg1(arg2)\n\n# def print_spam():\n# print('spam')\n\ndef print_twice(arg1):\n print(arg1)\n print(arg1)\n\n# do_twice(print_spam)\n# do_twice(print_twice, 'spam')\n\ndef do_four(arg1, arg2, arg3):\n arg1(arg2, arg3)\n\ndo_four(do_twice, print_twice, 'spam')\n\n\n\"\"\"\nExercise 3 : Fermat’s Last Theorem\na**n + b**n == c**n\n\"\"\"\n\ndef check_fermat(a,b,c,n):\n if n > 2 and (a**n + b**n == c**n):\n print(\"Holy smokes, Fermat was wrong!\")\n else:\n print(\"No, that doesn't work.\")\n\ncheck_fermat(3,4,5,3)\n\nprint(\"Let's check Fermat's theorem : aⁿ + bⁿ = cⁿ\")\na = input(\"Enter a:\")\nb = input(\"Enter b:\")\nc = input(\"Enter c:\")\nn = input(\"Enter n (greater than 2):\")\n\ncheck_fermat(int(a), int(b), int(c), int(n))\n","sub_path":"17_challenges.py","file_name":"17_challenges.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"421388247","text":"class GeneralAccounts(object):\n RecordLength = 449\n TLA = \"GAA\"\n ID = \"\"\n def __init__(self, rec=False):\n \"\"\"Extract fields from GAA records\"\"\"\n if (not rec) or (rec[5] == \"\\x00\"):\n self.Valid = False\n else:\n self.Valid = True\n self.ID = \"\"\n self.Description = \"Not yet!\"\n\n","sub_path":"fsrStuff/umFuncs/GeneralAccounts.pyw","file_name":"GeneralAccounts.pyw","file_ext":"pyw","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"568333224","text":"from __future__ import print_function\nfrom routes import Mapper\nimport webob.dec\nimport webob.exc\nimport routes.middleware\nimport testtools\n\n\nclass MyController(object):\n def getlist(self, mykey):\n print(\"step 4: MyController's getlist(self, mykey) is invoked\")\n return \"getlist(), mykey=\" + mykey\n\n\nclass MyApplication(object):\n \"\"\"Test application to call from router.\"\"\"\n\n def __init__(self, controller):\n self._controller = controller\n\n def __call__(self, environ, start_response):\n print(\"step 3: MyApplication is invoked\")\n\n action_args = environ['wsgiorg.routing_args'][1].copy()\n try:\n del action_args['controller']\n except KeyError:\n pass\n\n try:\n del action_args['format']\n except KeyError:\n pass\n\n action = action_args.pop('action', None)\n controller_method = getattr(self._controller, action)\n result = controller_method(**action_args)\n\n start_response('200 OK', [('Content-Type', 'text/plain')])\n return [result]\n\n\nclass MyRouter(object):\n \"\"\"Test router.\"\"\"\n\n def __init__(self):\n route_name = \"dummy_route\"\n route_path = \"/dummies\"\n\n my_application = MyApplication(MyController())\n\n self.mapper = Mapper()\n self.mapper.connect(route_name, route_path,\n controller=my_application,\n action=\"getlist\",\n mykey=\"myvalue\",\n conditions={\"method\": ['GET']})\n\n self._router = routes.middleware.RoutesMiddleware(self._dispatch,\n self.mapper)\n\n @webob.dec.wsgify(RequestClass=webob.Request)\n def __call__(self, req):\n \"\"\"Route the incoming request to a controller based on self.map.\n\n If no match, return a 404.\n\n \"\"\"\n print(\"step 1: MyRouter is invoked\")\n return self._router\n\n @staticmethod\n @webob.dec.wsgify(RequestClass=webob.Request)\n def _dispatch(req):\n \"\"\"Dispatch the request to the appropriate controller.\n\n Called by self._router after matching the incoming request to a route\n and putting the information into req.environ. Either returns 404\n or the routed WSGI app's response.\n\n \"\"\"\n print(\"step 2: RoutesMiddleware is invoked, calling our _dispatch back\")\n\n match_dict = req.environ['wsgiorg.routing_args'][1]\n if not match_dict:\n return webob.exc.HTTPNotFound()\n app = match_dict['controller']\n return app\n\n\nclass RoutingTestCase(testtools.TestCase):\n def test_router(self):\n router = MyRouter()\n result = webob.Request.blank('/dummies').get_response(router)\n self.assertEqual(result.body, \"getlist(), mykey=myvalue\")\n","sub_path":"clloct/paste_pro/nova_api_demo.py","file_name":"nova_api_demo.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"167937104","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Function, set_grad_enabled, grad, gradcheck\nfrom efficient_util import add_weight_norms\nimport numpy as np\n\nfrom functools import reduce\nfrom operator import mul\n\n\nclass Invertible1x1Conv(nn.Conv1d):\n \"\"\"\n The layer outputs both the convolution, and the log determinant\n of its weight matrix. If reverse=True it does convolution with\n inverse\n \"\"\"\n def __init__(self, c, hparams):\n super().__init__(c, c, 1, bias=False) # init as nn.Conv1d(c, c, kernel_size=1, stride=1) \n memory_efficient = hparams.InvConv_memory_efficient\n \n # Sample a random orthonormal matrix to initialize weights\n W = torch.qr(torch.FloatTensor(c, c).normal_())[0]\n \n # Ensure determinant is 1.0 not -1.0\n if torch.det(W) < 0:\n W[:,0] = -1*W[:,0]\n W = W.view(c, c, 1)\n self.weight.data = W\n \n if memory_efficient:\n self.efficient_forward = Conv1x1Func.apply\n self.efficient_inverse = InvConv1x1Func.apply\n\n def forward(self, z):\n \n if hasattr(self, 'efficient_forward'):\n audio_out, log_det_W = self.efficient_forward(z, self.weight)\n z.storage().resize_(0)\n return audio_out, log_det_W\n else:\n *_, n_of_groups = z.shape\n log_det_W = n_of_groups * self.weight.squeeze().slogdet()[1] # should fix nan logdet\n audio_out = super().forward(z)\n return audio_out, log_det_W\n \n def inverse(self, audio_out):\n if hasattr(self, 'efficient_inverse'):\n z, log_det_W = self.efficient_inverse(audio_out, self.weight)\n audio_out.storage().resize_(0)\n return z, log_det_W\n else:\n weight = self.weight.squeeze()\n *_, n_of_groups = audio_out.shape\n log_det_W = -n_of_groups * weight.slogdet()[1] # should fix nan logdet\n z = F.conv1d(audio_out, weight.inverse().unsqueeze(-1))\n return z, log_det_W\n\n\nclass Conv1x1Func(Function):\n @staticmethod\n def forward(ctx, z, weight):\n with torch.no_grad():\n *_, n_of_groups = z.shape\n log_det_W = n_of_groups * weight.squeeze().slogdet()[1]\n #log_det_W = n_of_groups * weight.squeeze().float().slogdet()[1].half()\n audio_out = F.conv1d(z, weight)\n \n ctx.save_for_backward(z.data, weight, audio_out)\n return audio_out, log_det_W\n \n @staticmethod\n def backward(ctx, z_grad, log_det_W_grad):\n z, weight, audio_out = ctx.saved_tensors\n *_, n_of_groups = audio_out.shape\n \n with torch.no_grad():\n inv_weight = weight.squeeze().inverse()\n #inv_weight = weight.squeeze().float().inverse().half()\n z.storage().resize_(reduce(mul, audio_out.shape))\n z[:] = F.conv1d(audio_out, inv_weight.unsqueeze(-1))\n \n dx = F.conv1d(z_grad, weight[..., 0].t().unsqueeze(-1))\n dw = z_grad.transpose(0, 1).contiguous().view(weight.shape[0], -1) @ z.transpose(1, 2).contiguous().view(\n -1, weight.shape[1])\n dw += inv_weight.t() * log_det_W_grad * n_of_groups\n \n return dx, dw.unsqueeze(-1)\n\n\nclass InvConv1x1Func(Function):\n @staticmethod\n def forward(ctx, z, inv_weight):\n with torch.no_grad():\n sqr_inv_weight = inv_weight.squeeze()\n *_, n_of_groups = z.shape\n log_det_W = -sqr_inv_weight.slogdet()[1]\n log_det_W *= n_of_groups\n audio_out = F.conv1d(z, sqr_inv_weight.inverse().unsqueeze(-1))\n \n ctx.save_for_backward(z.data, inv_weight, audio_out)\n return audio_out, log_det_W\n \n @staticmethod\n def backward(ctx, z_grad, log_det_W_grad):\n z, inv_weight, audio_out = ctx.saved_tensors\n *_, n_of_groups = audio_out.shape\n \n with torch.no_grad():\n z.storage().resize_(reduce(mul, audio_out.shape))\n z[:] = F.conv1d(audio_out, inv_weight)\n \n inv_weight = inv_weight.squeeze()\n weight_T = inv_weight.inverse().t()\n dx = F.conv1d(z_grad, weight_T.unsqueeze(-1))\n dw = z_grad.transpose(0, 1).contiguous().view(weight_T.shape[0], -1) @ \\\n z.transpose(1, 2).contiguous().view(-1, weight_T.shape[1])\n dinvw = - weight_T @ dw @ weight_T\n dinvw -= weight_T * log_det_W_grad * n_of_groups\n \n return dx, dinvw.unsqueeze(-1)","sub_path":"WaveFlow/models1d/yoyololicon/Invertible1x1Conv.py","file_name":"Invertible1x1Conv.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"600342214","text":"from collections.abc import Mapping\nimport logging\nimport os\nfrom pathlib import Path\nimport re\nimport subprocess\nimport sys\n\nfrom setuptools import config, find_packages, setup\n\nDEPENDENCIES = {\n 'adcircpy>=1.0.39': ['gdal', 'fiona'],\n 'filelock': [],\n 'nemspy>=1.0.3': [],\n 'numpy': [],\n 'pyproj': [],\n 'requests': [],\n}\n\n\ndef installed_packages() -> [str]:\n return [\n re.split('#egg=', re.split('==| @ ', package.decode())[0])[-1].lower()\n for package in subprocess.run(\n f'{sys.executable} -m pip freeze', shell=True, capture_output=True,\n ).stdout.splitlines()\n ]\n\n\ndef missing_packages(required_packages: {str: [str]}) -> {str: [str]}:\n if isinstance(required_packages, Mapping):\n missing_dependencies = missing_packages(list(required_packages))\n output = {}\n for dependency, subdependencies in required_packages.items():\n missing_subdependencies = missing_packages(subdependencies)\n if dependency in missing_dependencies or len(missing_subdependencies) > 0:\n output[dependency] = missing_subdependencies\n return output\n else:\n return [\n required_package\n for required_package in required_packages\n if re.split('<|<=|==|>=|>', required_package)[0].lower()\n not in installed_packages()\n ]\n\n\ntry:\n if 'dunamai' not in installed_packages():\n subprocess.run(\n f'{sys.executable} -m pip install dunamai',\n shell=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n\n from dunamai import Version\n\n version = Version.from_any_vcs().serialize()\nexcept RuntimeError as error:\n logging.exception(error)\n version = '0.0.0'\n\nlogging.info(f'using version {version}')\n\nMISSING_DEPENDENCIES = missing_packages(DEPENDENCIES)\n\nif (Path(sys.prefix) / 'conda-meta').exists() and len(MISSING_DEPENDENCIES) > 0:\n conda_packages = []\n for dependency in list(MISSING_DEPENDENCIES):\n try:\n process = subprocess.run(\n f'conda search {dependency}', check=True, shell=True, capture_output=True,\n )\n if 'No match found for:' not in process.stdout.decode():\n conda_packages.append(dependency)\n except subprocess.CalledProcessError:\n continue\n\n try:\n subprocess.run(\n f'conda install -y {\" \".join(conda_packages)}',\n check=True,\n shell=True,\n stderr=subprocess.DEVNULL,\n )\n except subprocess.CalledProcessError:\n for dependency in conda_packages:\n try:\n subprocess.run(\n f'conda install -y {dependency}',\n check=True,\n shell=True,\n stderr=subprocess.DEVNULL,\n )\n except subprocess.CalledProcessError:\n continue\n\n MISSING_DEPENDENCIES = missing_packages(DEPENDENCIES)\n\nif os.name == 'nt' and len(MISSING_DEPENDENCIES) > 0:\n if 'pipwin' not in installed_packages():\n subprocess.run(\n f'{sys.executable} -m pip install pipwin',\n shell=True,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n subprocess.run(f'{sys.executable} -m pipwin refresh', shell=True)\n\n for dependency, subdependencies in MISSING_DEPENDENCIES.items():\n failed_pipwin_packages = []\n for _ in range(1 + len(subdependencies)):\n for package_name in subdependencies + [dependency]:\n if dependency in missing_packages(\n DEPENDENCIES\n ) or package_name in missing_packages(subdependencies):\n try:\n subprocess.run(\n f'{sys.executable} -m pip install {package_name.lower()}',\n check=True,\n shell=True,\n stderr=subprocess.DEVNULL,\n )\n if package_name in failed_pipwin_packages:\n failed_pipwin_packages.remove(package_name)\n except subprocess.CalledProcessError:\n try:\n subprocess.run(\n f'{sys.executable} -m pipwin install {package_name.lower()}',\n check=True,\n shell=True,\n stderr=subprocess.DEVNULL,\n )\n except subprocess.CalledProcessError:\n failed_pipwin_packages.append(package_name)\n\n # since we don't know the dependencies here, repeat this process n number of times\n # (worst case is `O(n)`, where the first package is dependant on all the others)\n if len(failed_pipwin_packages) == 0:\n break\n\n MISSING_DEPENDENCIES = missing_packages(DEPENDENCIES)\n\nmetadata = config.read_configuration('setup.cfg')['metadata']\n\nsetup(\n name=metadata['name'],\n version=version,\n author=metadata['author'],\n author_email=metadata['author_email'],\n description=metadata['description'],\n long_description=metadata['long_description'],\n long_description_content_type='text/markdown',\n url=metadata['url'],\n packages=find_packages(),\n python_requires='>=3.6',\n setup_requires=['dunamai', 'setuptools>=41.2'],\n install_requires=list(DEPENDENCIES),\n extras_require={\n 'testing': ['pytest', 'pytest-cov', 'pytest-xdist', 'wget'],\n 'development': ['flake8', 'isort', 'oitnb'],\n },\n entry_points={\n 'console_scripts': [\n 'initialize_adcirc=coupledmodeldriver.client.initialize_adcirc:main',\n 'generate_adcirc=coupledmodeldriver.client.generate_adcirc:main',\n 'check_completion=coupledmodeldriver.client.check_completion:main',\n ],\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"558333945","text":"import logging\nimport re\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Optional, Pattern, Type, Union\n\n\n@dataclass(frozen=True)\nclass ExceptionChecker:\n type: Type[Exception]\n pattern: Optional[Union[Pattern[str], str]] = None\n attributes: Optional[Dict[str, Any]] = None\n\n def check(self, exception: Exception) -> None:\n logging.debug(\"checking exception %s/%r\", type(exception), exception)\n pattern = self.pattern\n if pattern is not None and not isinstance(pattern, re.Pattern):\n pattern = re.compile(pattern)\n try:\n assert isinstance(exception, self.type)\n if pattern is not None:\n assert pattern.match(f\"{exception}\")\n if self.attributes is not None:\n for key, value in self.attributes.items():\n logging.debug(\"checking exception attribute %s=%r\", key, value)\n assert hasattr(exception, key)\n assert getattr(exception, key) == value\n except Exception:\n logging.error(\"problem checking exception\", exc_info=exception)\n raise\n","sub_path":"test/utils/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"231219072","text":"# Sum square difference\n# https://projecteuler.net/problem=6\n# Problem 6\n# The sum of the squares of the first ten natural numbers is,\n# 1^2 + 2^2 + ... + 10^2 = 385\n# The square of the sum of the first ten natural numbers is,\n# (1 + 2 + ... + 10)^2 = 55^2 = 3025\n# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \n# 3025 - 385 = 2640\n# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\ndef p006(n):\n sum_of_squares = n * (n + 1) * (2 * n + 1) // 6 # Formula: [n(n + 1)(2n + 1)] / 6\n square_of_sum = (n * (n + 1) // 2) ** 2 # Formula: [n(n + 1) // 2] ^ 2\t\n return square_of_sum - sum_of_squares\n\np006(10) # Expected Output: 2640\n","sub_path":"scripts/p006.py","file_name":"p006.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"216065797","text":"\"\"\"Takeoff task.\"\"\"\n\nimport math\nfrom pathlib import Path\nimport numpy as np\nfrom gym import spaces\nfrom geometry_msgs.msg import Vector3, Point, Quaternion, Pose, Twist, Wrench\nfrom .quadrocopter_task import QuadrocopterTask\n\nclass Takeoff(QuadrocopterTask):\n \"\"\"Simple task where the goal is to lift off the ground and reach a target height.\"\"\"\n\n def __init__(self, num_actions=1):\n super().__init__(num_actions)\n print(\"Takeoff(): observation_space = {}\".format(self.observation_space)) # [debug]\n print(\"Takeoff(): action_space = {}\".format(self.action_space)) # [debug]\n\n # Task-specific parameters\n self.max_duration = 10.0 # secs\n self.target_z = 10.0 # target height (z position) to reach for successful takeoff\n\n self.task_name = 'takeoff'\n\n def reset(self):\n # Nothing to reset; just return initial condition\n return Pose(\n position=Point(0.0, 0.0, np.random.normal(0.5, 0.1)), # drop off from a slight random height\n orientation=Quaternion(0.0, 0.0, 0.0, 0.0),\n ), Twist(\n linear=Vector3(0.0, 0.0, 0.0),\n angular=Vector3(0.0, 0.0, 0.0)\n )\n\n def calculate_reward(self, timestamp, pose, angular_velocity, linear_acceleration):\n # Compute reward / penalty and check if this episode is complete\n done = False\n reward = -min(abs(self.target_z - pose.position.z), 20.0) # reward = zero for matching target z, -ve as you go farther, upto -20\n dist = math.sqrt(pose.position.x * pose.position.x + pose.position.y * pose.position.y)\n reward -= dist * 2.0\n if pose.position.z >= self.target_z: # agent has crossed the target height\n reward += 50.0 - dist * 5.0 # bonus reward\n done = True\n elif timestamp > self.max_duration: # agent has run out of time\n reward -= 50.0 # extra penalty\n done = True\n\n return reward, done\n","sub_path":"tasks/emulator/takeoff.py","file_name":"takeoff.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"638336474","text":"\n# import requests\n\nimport pandas as pd\nfrom datetime import datetime\nfrom sqlalchemy import create_engine\nfrom sys import exc_info\n# import logging\n\nstartTime = datetime.now()\ndesired_width = 320\npd.set_option('display.width', desired_width)\npd.set_option(\"display.max_columns\", 10)\n\n\"\"\" ****************************************************************** \"\"\"\n\"\"\" *************** DATABASE MANAGEMENT FUNCTIONS ******************** \"\"\"\n\"\"\" ****************************************************************** \"\"\"\n\n\ndef get_sql_table(table_name = 'trips', category_id = None):\n \"\"\"********** run mysql command **********\"\"\"\n\n try:\n conn = create_engine('mysql+pymysql://root:idofarhi@localhost:3306/explore?charset=utf8', echo=False, encoding='UTF-8')\n if category_id !=None:\n query_result = pd.read_sql(\"SELECT * FROM {} WHERE category_id = {};\".format(table_name, category_id), conn)\n else:\n query_result = pd.read_sql(\"SELECT * FROM {};\".format(table_name), conn)\n except:\n print(\"Error: unable to get sql table. ERROR 1\", exc_info())\n return []\n\n return query_result\n\n\ndef write_to_database(table_name, df):\n\n try:\n # df = df[['full_name', 'sex', 'city', 'country', 'age', 'pic_link', 'email', 'pass']]\n conn = create_engine('mysql+pymysql://root:idofarhi@localhost:3306/explore?charset=utf8', echo=False, encoding='UTF-8')\n df.to_sql(name=table_name, con=conn, index=False, if_exists='append')\n\n except:\n print(\"Error: unable to write to database. ERROR 2\", exc_info())\n\n\n\"\"\" ****************************************************************** \"\"\"\n\"\"\" ************* END DATABASE MANAGEMENT FUNCTIONS ****************** \"\"\"\n\"\"\" ****************************************************************** \"\"\"\n\n\n\ndef main():\n \"\"\"\n Main Function\n \"\"\"\n # Creating a set of categories\n category_columns = ['category']\n categories = pd.DataFrame([['biking'],\n ['hiking'],\n ['skiing']], columns=category_columns)\n\n\n print('\\033[92m' + 'Showing categories dataframe:' + '\\033[0m')\n print(categories, '\\n')\n\n # write_to_database('categories', categories)\n\n print('\\033[92m' + 'Showing categories dataframe pulled from database:' + '\\033[0m')\n categories_db = get_sql_table('categories')\n print(categories_db, '\\n')\n\n\n # Creating a set of users\n user_columns = ['full_name', 'sex', 'city', 'country', 'age', 'pic_link', 'email', 'pass']\n user = pd.DataFrame([['Ido F', 'male', 'Tel Aviv', 'Israel', '29', '/ido_pic.jpg', 'idofarhi@gmail.com', '123456'],\n ['Carola K', 'female', 'Tel Aviv', 'Israel', '20', '/carola_pic.jpg', 'carola@gmail.com', '123456'],\n ['Or R', 'male', 'Tel Aviv', 'Israel', '31', '/or_pic.jpg', 'or@gmail.com', '123456']], columns=user_columns)\n\n\n print('\\033[92m' + 'Showing users dataframe:' + '\\033[0m')\n print(user, '\\n')\n\n # write_to_database('users', user)\n\n print('\\033[92m' + 'Showing users dataframe pulled from database:' + '\\033[0m')\n users_db = get_sql_table('users')\n print(users_db, '\\n')\n\n\n # Creating a set of trips\n trip_columns = ['start_date', 'end_date', 'trip_length', 'category_id', 'difficulty', 'prior_knowledge', 'description', 'organizer_ID']\n trips = pd.DataFrame([['19.1.9', '27.1.2020', '6', '3', 'moderate', 'no', \"\"\"I'd like to go skiing in france and looking for partners\"\"\", '0'],\n ['19.2.9', '17.2.2020', '6', '3', 'moderate', 'no', \"\"\"I'd like to go snowboarding. Looking for partners\"\"\", '2'],\n ['19.1.9', '28.1.2020', '3', '2', 'hard', 'no', \"\"\"I'd like to go climbing\"\"\", '1']], columns=trip_columns)\n\n print('\\033[92m' + 'Showing trips dataframe:' + '\\033[0m')\n print(trips, '\\n')\n\n # write_to_database('trips', trips)\n\n print('\\033[92m' + 'Showing trips dataframe pulled from database:' + '\\033[0m')\n trips_db = get_sql_table('trips', 3)\n print(trips_db)\n\n # datetime .strftime(\"%y-%m-%d-%H-%M\")\n\n print('\\n','Total run time:', datetime.now() - startTime)\n\n return\n\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"335551931","text":"#!/usr/bin/python\nimport math\nimport utils.plan as plan\nfrom colorama import Fore, Style\nimport scheduler.bsp as bsp\n\n\ndef build_stages(g): # use graphtool topological sort to build stages\n bsp.assign_stages(g)\n g.gp.stages = {}\n for v in g.vertices(): # This takes O(V) and V is the set of jobs in the DAG\n stage_id = g.vp.stage_id[v]\n if stage_id not in g.gp.stages:\n g.gp.stages[stage_id] = plan.Stage(stage_id)\n g.gp.stages[stage_id].add_job(g.vp.job[v])\n\n for stg_id in g.gp.stages: # This takes OV\n g.gp.stages[stg_id].finish_add_jobs()\n # g.total_runtime += g.stages[stg_id].get_runtime()\n g.gp.schedule = g.gp.stages\n return g;\n\n\ndef build_stages_byblevel(g):\n blevels = g.blevel()\n scheduled = [False] * g.n_vertices\n stages = {}\n stages[0] = set(blevels[max(blevels)])\n cur_stage = plan.Stage(0)\n for j in stages[0]:\n scheduled[j] = True\n g.jobs[j].slevel = 0\n cur_stage.add_job(g.jobs[j])\n cur_stage.finish_add_jobs()\n cur_stage.stage_id = 0\n g.stages[0] = cur_stage\n g.total_runtime += cur_stage.get_runtime()\n for blvl in range(max(blevels), 0, -1):\n csi = max(blevels) - blvl # current stage index\n stg_jobs = blevels[blvl]\n new_stage = set()\n cur_stage = plan.Stage(csi)\n for j in blevels[blvl - 1]:\n if not scheduled[j]: new_stage.add(j)\n for j in stg_jobs:\n for ch in g.jobs[j].children.keys():\n if scheduled[ch]: continue\n if g.jobs[j].blevel - 1 > g.jobs[ch].blevel and len(g.jobs[ch].parents) > 1: continue\n new_stage.add(ch)\n for j in new_stage:\n scheduled[j] = True\n g.jobs[j].slevel = csi + 1\n cur_stage.add_job(g.jobs[j])\n stages[csi + 1] = new_stage\n cur_stage.finish_add_jobs()\n cur_stage.stage_id = csi + 1\n g.stages[csi + 1] = cur_stage\n g.total_runtime += cur_stage.get_runtime()\n\n g.schedule = stages\n return g;\n\n\ndef input_scaling(g, j, prefetch_plan):\n scale_factor = j['ctime'] / (g.timeValue[j['job']] - g.cachedtimeValue[j['job']]); # csz : cache size\n pref_csz = {}\n i = 0\n\n for isz in g.inputSize[j['job']]: # isz: input size\n pref_sz = math.ceil(scale_factor * isz)\n if g.inputs[j['job']][i] in pref_csz:\n pref_sz = max(pref_csz[g.inputs[j['job']][i]], pref_sz)\n pref_csz[g.inputs[j['job']][i]] = pref_sz\n\n\ndef build_lru_stage_priorities_helper(g, s, plans_container): # s stands for stage\n priority = 1;\n s.dag_id = g.dag_id\n plans_container.add_stage(s)\n\n for j in s.jobs:\n p = plan.Plan()\n p.priority = priority\n p.size = 0\n for f in j.inputs:\n p.data[f] = {'size': j.inputs[f], 'score': -1}\n p.size += j.inputs[f]\n p.jobs.append({'job': j,\n 'improvement': j.runtime_remote - j.runtime_cache})\n plans_container.add_cache_plan(p, s)\n priority = priority + 1\n return\n\n\ndef build_kariz_stage_priorities_helper(g, s, plans_container): # s stands for stage\n priority = 1;\n t_imprv = -1\n s.dag_id = g.gp.id\n plans_container.add_stage(s)\n prev_plan = None\n while t_imprv:\n plan, t_imprv = s.get_next_plan(priority)\n if not t_imprv:\n break;\n if prev_plan:\n prev_plan.children = plan\n plan.parent = prev_plan\n plan.dag_id = g.gp.id\n plan.stage_id = s.stage_id\n plans_container.add_cache_plan(plan, s)\n priority = priority + 1\n prev_plan = plan\n return\n\n\ndef build_kariz_priorities(g):\n if not g.gp.stages:\n build_stages(g)\n\n plans_container = plan.PlansContainer(g)\n for s in g.gp.stages:\n stage = g.gp.stages[s]\n build_kariz_stage_priorities_helper(g, stage, plans_container)\n return plans_container;\n\n\ndef build_rcp_stage_priorities_helper(g, s, plans_container): # s stands for stage\n priority = 1;\n t_imprv = -1\n s.dag_id = g.dag_id\n plans_container.add_stage(s)\n while t_imprv:\n plan, t_imprv = s.get_rcp_next_plan(priority)\n if not t_imprv:\n break;\n plan.dag_id = g.dag_id\n plan.stage_id = s.stage_id\n plans_container.add_cache_plan(plan, s)\n plan.iscore = 1 / plan.size\n plan.pscore = 0\n plan.sscore = 0\n plan.wscore = 0\n priority = priority + 1\n return\n\n\ndef build_rcp_priorities(g):\n if not g.stages:\n build_stages(g)\n\n plans_container = plan.PlansContainer(g)\n for s in g.stages:\n stage = g.stages[s]\n build_rcp_stage_priorities_helper(g, stage, plans_container)\n return plans_container;\n\n\ndef build_cp_stage_priorities_helper(g, s, plans_container): # s stands for stage\n s.dag_id = g.dag_id\n plans_container.add_stage(s)\n plan, t_imprv = s.get_criticalpath_plan()\n if plan:\n plan.dag_id = g.dag_id\n plan.stage_id = s.stage_id\n plans_container.add_cache_plan(plan, s)\n\n\ndef build_cp_priorities(g):\n if not g.stages:\n build_stages(g)\n\n plans_container = plan.PlansContainer(g)\n for s in g.stages:\n stage = g.stages[s]\n build_cp_stage_priorities_helper(g, stage, plans_container)\n\n plans_container.assing_prefetch_plan_unlimitedbw()\n return plans_container;\n\n\ndef build_mrd_stage_priorities_helper(g, s, plans_container): # s stands for stage\n priority = 1;\n plans_container.add_stage(s)\n\n for j in s.jobs:\n p = plan.Plan()\n p.priority = priority\n p.dag_id = g.dag_id\n p.stage_id = s.stage_id\n p.size = 0\n for f in j.inputs:\n p.data[f] = {'size': j.inputs[f], 'score': -1}\n p.size += j.inputs[f]\n p.jobs.append({'job': j,\n 'improvement': j.est_runtime_remote - j.est_runtime_cache})\n plans_container.add_cache_plan(p, s)\n priority = priority + 1\n return\n\n\ndef build_mrd_priorities(g):\n if not g.stages:\n build_stages(g)\n\n plans_container = plan.PlansContainer(g)\n for s in g.stages:\n stage = g.stages[s]\n build_mrd_stage_priorities_helper(g, stage, plans_container)\n\n return plans_container;\n\n\ndef build_lru_priorities(g):\n if not g.stages:\n build_stages(g)\n\n plans_container = plan.PlansContainer(g)\n for s in g.stages:\n stage = g.stages[s]\n build_lru_stage_priorities_helper(g, stage, plans_container)\n\n return plans_container;\n\n\ndef build_infinite_priorities(v):\n return None\n","sub_path":"code/utils/pig.py","file_name":"pig.py","file_ext":"py","file_size_in_byte":6622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"165594578","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/LeslieZhu/.pyenv/versions/2.7.15/Python.framework/Versions/2.7/lib/python2.7/site-packages/orgnote/markdown.py\n# Compiled at: 2019-11-25 07:03:32\nimport re\n\nclass Markdown(object):\n \"\"\" re-implementation of markdown for OrgNote\n\n Perl version by John Gruber: \n - https://raw.githubusercontent.com/mundimark/markdown.pl/master/Markdown.pl\n \"\"\"\n\n def __init__(self, text=''):\n self.empty_element_suffix = ' >'\n self.tab_width = 4\n self.text = text\n self.urls = ()\n self.titles = ()\n self.html_blocks = ()\n\n def mk2html(self):\n self.text = re.sub('\\\\r\\\\n', '\\\\n', self.text)\n self.text = re.sub('\\\\r', '\\\\n', self.text)\n self.text += '\\n\\n'\n self.text = self._DeTab(self.text)\n return self.text\n\n def _DeTab(self, text):\n return re.sub('\\\\t', ' ' * self.tab_width, text)\n\n def _HashHTMLBlocks(self, text):\n self.less_than_tab = self.tab_width - 1\n self.block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'\n self.block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'","sub_path":"pycfiles/orgnote-0.5.7.macosx-10.14-x86_64.tar/markdown.py","file_name":"markdown.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"382389050","text":"from flask import Flask, Blueprint, jsonify\nfrom models import *\nimport random\n\nbp = Blueprint('main', __name__, url_prefix='/')\n\n# 국가별로 전체 week 확진자 수 불러오기\n\n\n@bp.route('/api/timeline/', methods=['GET'])\ndef get_confirmed_num(country_code):\n try:\n confirmed_list = db.session.query(CovidConfirmed).filter(\n CovidConfirmed.country_code == country_code).all()\n\n return jsonify([confirmed.serialize for confirmed in confirmed_list])\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n# 국가별로 넷플릭스 구독자/매출 불러오기\n\n\n@bp.route('/api/netflix/', methods=['GET'])\ndef get_subscribers_num(country_code):\n try:\n data = db.session.query(SubscribersByCountry).filter(\n SubscribersByCountry.country_code == country_code).first()\n\n return jsonify({'q1_subscribers': data.q1_subscribers, 'q2_subscribers': data.q2_subscribers})\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n# 국가별 가장 최신 주차(21년 40번째 주)의 1위 영화, tv쇼 불러오기\n\n\n@bp.route('/api/netflix//2021-040/top1', methods=['GET'])\ndef get_netflix_top1(country_code):\n try:\n rank = 1\n\n top1_list = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == '2021-040', NetflixTop10.rank == rank).all()\n\n x = random.randint(1, 3)\n for content in top1_list:\n if (content.poster == '') or ('img' in content.poster):\n content.poster = f'../img/{x}.png'\n db.session.commit()\n\n new_top1_list = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == '2021-040', NetflixTop10.rank == rank).all()\n\n return jsonify([top1.serialize2 for top1 in new_top1_list])\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n# 국가별 각 주차의 1위 영화, tv쇼 불러오기\n\n\n@bp.route('/api/netflix//top1', methods=['GET'])\ndef get_netflix_top1_by_week(country_code):\n try:\n rank = 1\n\n week_list = db.session.query(NetflixTop10.week).filter(\n NetflixTop10.country_code == country_code).all()\n\n week_list = list(set([week[0] for week in week_list]))\n week_list.sort()\n\n # print(week_list)\n\n top1_list = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.rank == rank).all()\n\n x = random.randint(1, 3)\n for content in top1_list:\n if (content.poster == '') or ('img' in content.poster):\n content.poster = f'../img/{x}.png'\n db.session.commit()\n\n new_top1_list = {}\n\n for week in week_list:\n top1_contents = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == week, NetflixTop10.rank == rank).all()\n serialized = {week: [content.serialize2 for content in top1_contents]}\n new_top1_list.update(serialized)\n\n return jsonify(new_top1_list)\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n\n# 국가별 각 주차의 top10 영화리스트, tv쇼 리스트\n@bp.route('/api/netflix///top10', methods=['GET'])\ndef get_netflix_top10(country_code, week):\n try:\n x = random.randint(1, 3)\n\n top10_movies = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code, NetflixTop10.week ==\n week, NetflixTop10.content_type == 'movies').all()\n\n for movie in top10_movies:\n if 'img' in movie.poster == '':\n movie.poster = f'../img/{x}.png'\n db.session.commit()\n\n top10_tv_shows = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == week, NetflixTop10.content_type == 'tv').all()\n\n for tv in top10_tv_shows:\n if 'img' in tv.poster:\n tv.poster = f'../img/{x}.png'\n db.session.commit()\n\n new_top10_movies = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code, NetflixTop10.week ==\n week, NetflixTop10.content_type == 'movies').all()\n\n new_top10_tv_shows = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == week, NetflixTop10.content_type == 'tv').all()\n\n return jsonify(\n {'movies': [movie.serialize2 for movie in new_top10_movies],\n 'tv_shows': [tv.serialize2 for tv in new_top10_tv_shows]\n })\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n# 국가별 각 주차의 가장 인기있는 장르와 색상\n\n\n@bp.route('/api/netflix///genre', methods=['GET'])\ndef get_top_genre(country_code, week):\n try:\n if country_code == 'world':\n genre = db.session.query(WorldGenreScore).filter(\n WorldGenreScore.week == week).order_by(WorldGenreScore.score.desc()).first()\n\n return jsonify({'genre': genre.genre, 'color': genre.color})\n\n contents = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == week).all()\n\n genres = []\n for content in contents:\n genres = genres + content.serialize['genre']\n\n genres = [v for v in genres if v]\n # print(genres)\n\n top_genre = genres[0]\n for genre in genres:\n if genres.count(top_genre) < genres.count(genre):\n top_genre = genre\n\n color = db.session.query(GenreColor).filter(\n GenreColor.genre == top_genre).first()\n\n return jsonify({'genre': top_genre, 'color': color.color})\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n\n# 국가별 각 주차의 장르 스코어\n\n\n@bp.route('/api/netflix///genres', methods=['GET'])\ndef get_genres_score(country_code, week):\n try:\n contents = db.session.query(NetflixContent).join(NetflixTop10).\\\n filter(NetflixTop10.country_code == country_code,\n NetflixTop10.week == week).all()\n\n genres = []\n for content in contents:\n genres = genres + content.serialize['genre']\n\n genres = [v for v in genres if v]\n genres_unique = list(set(genres))\n genres_unique.sort()\n\n result = []\n for genre in genres_unique:\n cnt = genres.count(genre)\n color = db.session.query(GenreColor).filter(\n GenreColor.genre == genre).first().color\n result.append({'genre': genre, 'score': cnt, 'color': color})\n\n # print(result)\n return jsonify(result)\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n # 전세계 통합 주차별 장르 스코어\n\n\n@bp.route('/api/netflix/world//genres', methods=['GET'])\ndef get_world_genres_score(week):\n try:\n genres = db.session.query(WorldGenreScore).filter(\n WorldGenreScore.week == week).all()\n\n return jsonify([genre.serialize for genre in genres])\n except IndexError as e:\n print ({'error' : e})\n return 'error'\n except TypeError as e:\n print ({'error' : e})\n return 'error'\n","sub_path":"backend/views/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"572152102","text":"import requests\nfrom malscrape.misc import *\n\ndef medialist_url(username, type, offset):\n url = f'http://myanimelist.net/{type}list/{username}/load.json?offset={offset}&status=7'\n return url\n\ndef parse_media_json(json, type):\n return [{\n #'title': info[f'{type}_title'],\n 'id': info[f'{type}_id'],\n 'score': info['score'],\n 'status': info['status'],\n } for info in json]\n\ndef fetch_list(username, type):\n validate_media(type)\n cursor, page, step = 0, 0, 300\n\n medialist = []\n timeouts = timeouts_coroutine(quiet=True)\n while True:\n try:\n url = medialist_url(username, type, cursor + page*step)\n medialist_http = requests.get(url)\n if medialist_http.status_code == 429:\n timeouts(False)\n continue\n list_page = parse_media_json(medialist_http.json(), type)\n medialist += list_page\n if not list_page or len(list_page) < 300:\n return medialist\n timeouts(True)\n page += 1\n except requests.ConnectionError as err:\n timeouts(False)\n print(f\"requests.ConnectionError: {err}\")\n continue\n except Exception as err:\n if medialist_http.reason == 'Bad Request':\n return []\n return None","sub_path":"mal_recs/malscrape/user_lists.py","file_name":"user_lists.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"274594098","text":"# -*- coding: utf-8 -*-\nfrom common import read, plot\nimport pandas as pd\nimport sys\nimport os\n\ndef plotArea(city, area, df = None):\n if df is None:\n df = read(city)\n df = df.dropna(subset = ['小区'])\n df = df.loc[df['小区'].str.contains(area)]\n if city == \"北京\":\n df = df.loc[df['成交价(元/平)']> 10000]\n print(city, area, 'data count:', len(df))\n if len(df) == 0:\n return df\n gp = df.groupby(['成交时间'])['成交价(元/平)']\n res=pd.DataFrame({\"volume\":gp.size(),\"median_price\":gp.median(), \"mean_price\":gp.mean()})\n res = res.iloc[:len(res),:]\n city = 'default'\n MA = True\n start_date = None\n force = True\n keep_all = True\n for ma_length in [1, 30, 60, 90]:\n title = '%s-%d日均线'%(area, ma_length)\n plot(res, city, title, MA, ma_length, start_date, force, keep_all)\n return df\ndef plotAreas(city, areas):\n dfs = []\n df = read(city)\n for area in areas:\n dfs.append(plotArea(city, area, df))\n df = pd.concat(dfs)\n print('data count:', len(df))\n gp = df.groupby(['成交时间'])['成交价(元/平)']\n res=pd.DataFrame({\"volume\":gp.size(),\"median_price\":gp.median(), \"mean_price\":gp.mean()})\n res = res.iloc[:len(res),:]\n city = 'default'\n MA = True\n start_date = None\n force = True\n keep_all = True\n for ma_length in [1, 30, 60, 90]:\n title = '%s-%d日均线'%('前滩', ma_length)\n plot(res, city, title, MA, ma_length, start_date, force, keep_all)\n \nif __name__ == '__main__':\n if len(sys.argv) == 3:\n city = sys.argv[1]\n area = sys.argv[2]\n plotArea(city, area)\n elif len(sys.argv) == 2 and sys.argv[1] == \"list\":\n plotAreas('上海', ['晶耀名邸', '中粮前滩', '前滩三湘印象', '福晟钱隆', '浦江海德', '东方惠礼', '东方逸品', '江悦名庭', '东方悦耀'])\n else:\n print(\"usage: python3 plotAreaFromData.py [city] [area]\")\n","sub_path":"plotAreaFromData.py","file_name":"plotAreaFromData.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"364887257","text":"from tkinter import *\nfrom pyyt import vidDownloader as download\nfrom pyyt import vidQuery as query \n\n\n\nclass NatesButtons:\n\n\tdef __init__(self, master):\n\t\tframe = Frame(master)\n\t\tframe.pack()\n\n\t\tself.printButton = Button(frame, text=\"Download\", command=download)\n\t\tself.printButton.pack(side=LEFT)\n\n\t\tself.quitButton = Button(frame, text=\"Quit\", command=frame.quit)\n\t\tself.quitButton.pack(side=LEFT)\n\n\t\n\n\n\n\n\n\nroot = Tk()\nb = NatesButtons(root)\n\n\nroot.mainloop()\n#query","sub_path":"pyyt_tkinter.py","file_name":"pyyt_tkinter.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"223535133","text":"from os import write\nimport pygame\nfrom pygame.surfarray import pixels_blue\n#from player import *\n\n\n\n\n\npygame.init()\nwindows = pygame.display.set_mode((1386,490))\nfont_titre = pygame.font.SysFont(None,50)\ntext_titre = font_titre.render(\"WORD WAR\", True, (255, 255, 255))\nfont = pygame.font.SysFont(None,30)\ntext_start = font.render(\"Press Entrer pour lancer\", True, (255, 255, 255))\ntext_quit = font.render(\"Press Echap pour quitter\", True, (255, 255, 255))\ntext_son = font.render(\"Press F1 ,stop music / F3 , play music\", True, (255,255,255))\nbutton_start = pygame.image.load('start_button.png')\nbutton_start = pygame.transform.scale(button_start, (150,50))\nbutton_start_rectangle = button_start.get_rect()\nbutton_start_rectangle.x = 630\nbutton_start_rectangle.y = 250\nbutton_quit = pygame.image.load('quit_button.png')\nbutton_quit = pygame.transform.scale(button_quit, (150,50))\nbutton_quit_rectangle = button_quit.get_rect()\nbackground_menu = pygame.image.load('menu_background.jpg')\nbackground_menu = pygame.transform.scale(background_menu, (1386,490))\nbackground_game = pygame.image.load('fond.jpg')\nbackground_game = pygame.transform.scale(background_game, (1386,490))\nframe_per_sec = pygame.time.Clock()\nmusic_combat = pygame.mixer.Sound('music_combat.wav')\nmusic_menu = pygame.mixer.music.load('music_menu.wav')\nmusic_menu = pygame.mixer.music.play(-1)\nmus = pygame.mouse.get_pos(650,300)\nwindows.blit(text_son, (10, 20))\nwindows.blit(background_game, (0,0))\nwindows.blit(background_menu, (0,0))\nwindows.blit(button_start, button_start_rectangle)\nwindows.blit(button_quit, (630,350))\nwindows.blit(text_start, (590, 310))\nwindows.blit(text_quit, (590, 430))\nwindows.blit(text_titre, (600, 20))\nmusic_combat_compte = 0\n#pygame.font.init()\n\nwhile True:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n if event.key == pygame.K_KP_ENTER:\n windows.blit(background_game, (0,0))\n windows.blit(text_son, (10, 20))\n music_menu = pygame.mixer.music.stop()\n music_combat.play(-1)\n music_combat_compte = 1\n if event.key == pygame.K_F3 and music_combat_compte != 1 :\n music_combat.play(-1)\n music_combat_compte = 1\n elif event.key == pygame.K_F1 and music_combat_compte == 1 :\n music_combat.stop()\n music_combat_compte = 0\n #elif event.type == pygame.MOUSEBUTTONDOWN:\n #if pygame.Rect.collidepoint(button_start_rectangle, event.pos):\n #if (event.pos > button_start_rectangle.x and event.pos < \n #(button_start_rectangle.x + 100)) and (event.pos > button_start_rectangle.y and \n #event.pos < (button_start_rectangle.y + 60)) :\n # windows.blit(background_game, (0,0))\n #music_menu = pygame.mixer.music.stop()\n #music_combat.play(-1)\n pygame.display.update()\n\n","sub_path":"windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"413058179","text":"# Wrapper for alpha_vantage\n# https://backtest-rookies.com/2018/04/20/replacing-quandl-wiki-data-with-alpha-vantage/\n# https://github.com/RomelTorres/alpha_vantage\n\n'''\nAuthor: www.backtest-rookies.com\n\nMIT License\n\nCopyright (c) 2018 backtest-rookies.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n# code to auto add packages\nimport subprocess\nimport sys\ndef install(package):\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package])\n\ninstall(\"alpha_vantage\")\ninstall(\"argparse\")\ninstall(\"pandas\")\ninstall(\"pprint\")\ninstall(\"matplotlib\")\n\nfrom alpha_vantage.timeseries import TimeSeries\nimport argparse\nimport pandas as pd\nfrom pprint import pprint\n\nimport matplotlib.pyplot as plt #for\n\n\"\"\" def parse_args():\n parser = argparse.ArgumentParser(description='CCXT Market Data Downloader')\n\n parser.add_argument('-s','--symbol',\n type=str,\n required=True,\n help='The Symbol of the Instrument/Currency Pair To Download')\n\n parser.add_argument('-o', '--outfile',\n type=str,\n required=True,\n help='The output directory and file name to save the data')\n\n return parser.parse_args()\n \"\"\"\n\n# Get our arguments\nargs_symbol = input(\"Enter symbol: \")\nprint(args_symbol)\n\nargs_outputCSV = input(\"Enter output csv filename prefix: \") + \"_\" + args_symbol + \".csv\"\n\n# Submit our API and create a session\nalpha_ts = TimeSeries(key='BCVTGY0TFDT3W7IV', output_format='pandas')\n\n# Get the data\ndata, meta_data = alpha_ts.get_intraday(symbol=args_symbol,interval='1min', outputsize='full')\npprint(data.head(2))\n\n# Save the data\ndata.to_csv(args_outputCSV)\n\n# Plotting price\ndata['4. close'].plot()\nplt.title('Intraday Times Series for the MSFT stock (1 min)')\nplt.show()\n\n# Plotting indicators\n\nti = TechIndicators(key='YOUR_API_KEY', output_format='pandas')\ndata, meta_data = ti.get_bbands(symbol='MSFT', interval='60min', time_period=60)\ndata.plot()\nplt.title('BBbands indicator for MSFT stock (60 min)')\nplt.show()","sub_path":"alpha_vantage_1m.py","file_name":"alpha_vantage_1m.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"439797597","text":"#import modules\nimport pretty_midi\nimport os\nimport numpy as np\nimport pickle\n\n\ndef get_instruments_list(directories):\n list_instrument=[]\n for directory in directories:\n songs=[directory+'/'+filename for filename in os.listdir(directory)]\n for song in songs:\n try:\n midi_data=pretty_midi.PrettyMIDI(song)\n \n for instrument in midi_data.instruments:\n if instrument not in list_instrument:\n list_instrument.append(instrument)\n except:\n pass\n return list_instrument\n\n\ndef get_notes(directories='../dataset',sampling_frequency=50,save_at='notes/session_note'):\n notes=[]\n if(os.path.exists(save_at)):\n with open(save_at,'rb') as f:\n notes=pickle.load(f)\n else:\n for directory in directories:\n print(directory)\n songs=[directory+'/'+filename for filename in os.listdir(directory)]\n #Building piano_roll\n for song in songs:\n try:\n midi_data=pretty_midi.PrettyMIDI(song)\n piano_roll=midi_data.get_piano_roll(fs=sampling_frequency,times=None)\n for i in range(piano_roll.shape[1]):\n indexes=np.where(piano_roll[:,i]>0)[0]\n a=[str(c) for c in indexes]\n note=','.join(a)\n notes.append(note)\n except:\n pass\n n_vocab=len(set([item for item in notes]))\n n_notes=len(notes)\n with open(save_at,'wb') as f:\n pickle.dump(notes,f)\n print(\"number of samples:\"+str(n_notes))\n print(\"vocab size:\"+str(n_vocab)) \n\n return notes\n\n\ndef prepare_sequences(notes,is_LSTM=False):\n sequence_length = 100\n\n # get all Bitch names\n pitchnames = sorted(set(item for item in notes))\n n_vocab=len(pitchnames)\n\n # create a dictionary to map Bitches to integers\n note_to_int = dict((note, number) for number, note in enumerate(pitchnames))\n\n network_input = []\n network_output = []\n\n # create input sequences and the corresponding outputs\n for i in range(0, int((len(notes) - sequence_length)/sequence_length), 1):\n sequence_in = notes[sequence_length*i:sequence_length+i*sequence_length]\n sequence_out=notes[sequence_length+i*sequence_length]\n network_input.append([note_to_int[char] for char in sequence_in])\n network_output.append(sequence_out)\n\n # reshape the input into a format compatible with LSTM layers\n network_output=np.asarray(network_output)\n network_output=np.eye(n_vocab)[network_output]\n network_input=np.array(network_input)\n network_input=np.eye(n_vocab)[network_input]\n if is_LSTM==True:\n return network_input,network_output\n else:\n network_input2=np.roll(network_input,1,axis=1)\n network_input2[:,0,:]=0\n return (network_input, network_input2)\n\n\n\n#IGNORE IGNORE IGNORE this function for now\ndef midi_datasets_to_samples(directories,sampling_frequency,save_at='sample.npy'):\n samples=[]\n start_pitch_index=16\n end_pitch_index=112\n n_vocab=end_pitch_index-start_pitch_index\n for directory in directories:\n print(directory)\n songs=[directory+'/'+filename for filename in os.listdir(directory)]\n for song in songs:\n print(song)\n try:\n midi_data=pretty_midi.PrettyMIDI(song)\n except:\n pass\n piano_roll=midi_data.get_piano_roll(fs=sampling_frequency,times=None).T\n sample=piano_roll[0:96*int(piano_roll.shape[0]/96),start_pitch_index:end_pitch_index]\n samples=samples+[sample] #append is computationally faster than concatention so uing list append instead of numpy concatenation\n \n \n samples=np.concatenate(samples,axis=0)\n samples=samples.reshape(samples.shape[0]//96,96,96)\n samples.astype(np.int8)\n np.save(save_at,samples) \n return samples\n\n\ndef sample_to_piano_roll(notes,decoded):\n pitchname=sorted(set(item for item in notes))\n int_to_note = dict((number, note) for number, note in enumerate(pitchname))\n gen_note=[int_to_note[ix] for ix in decoded]\n piano_roll=[]\n for note in gen_note:\n a=[0]*128\n for index in note.split(','):\n if(index==''):\n index=0\n a[int(index)]=40\n piano_roll.append(a)\n \n piano_roll=np.array(piano_roll).T\n return piano_roll\n\n\ndef piano_roll_to_midi(piano_roll,program=0,fs=50,save_at='sample.midi'):\n #reference:https://github.com/craffel/pretty-midi/blob/master/examples/reverse_pianoroll.py\n notes,frames = piano_roll.shape\n pm = pretty_midi.PrettyMIDI()\n instrument = pretty_midi.Instrument(program=program)\n\n # pad 1 column of zeros so we can acknowledge inital and ending events\n piano_roll = np.pad(piano_roll, [(0, 0), (1, 1)], 'constant')\n\n # use changes in velocities to find note on / note off events\n velocity_changes = np.nonzero(np.diff(piano_roll).T)\n\n # keep track on velocities and note on times\n prev_velocities = np.zeros(notes, dtype=int)\n note_on_time = np.zeros(notes)\n\n for time, note in zip(*velocity_changes):\n # use time + 1 because of padding above\n velocity = piano_roll[note, time + 1]\n time = time / fs\n if velocity > 0:\n if prev_velocities[note] == 0:\n note_on_time[note] = time\n prev_velocities[note] = velocity\n else:\n pm_note = pretty_midi.Note(\n velocity=prev_velocities[note],\n pitch=note,\n start=note_on_time[note],\n end=time)\n instrument.notes.append(pm_note)\n prev_velocities[note] = 0\n pm.instruments.append(instrument)\n pm.write('sample.midi')\n return pm\n\n","sub_path":"midi.py","file_name":"midi.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514998743","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Post, Comment\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n\n\ndef posts(request):\n\tposts = Post.objects.all()\n\treturn render(request, 'post/posts.html', {'posts': posts})\n\ndef post_detail(request, id):\n\tpost = get_object_or_404(Post, id=id)\n\tif request.method == 'POST':\n\t\tmessage = request.POST['message']\n\t\torigin = request.POST['origin']\n\t\tcomment = Comment(message=message, owner=post)\n\t\tif origin:\n\t\t\tcomment.origin_id = origin\n\t\tcomment.save()\n\t\treturn HttpResponseRedirect(reverse('post_detail', args=[post.id]))\n\treturn render(request, 'post/details.html', {\n\t\t'post': post, \n\t\t'comments': post.comment_set.filter(origin__isnull=True)\n\t})\n\n\ndef post_remove(request, id):\n\tpost = get_object_or_404(Post, id=id)\n\tpost.delete()\n\treturn HttpResponseRedirect(reverse('post_index'))\n\n\ndef post_create(request):\n\tif request.method == 'POST':\n\t\tpost = Post(title=request.POST['title'], content=request.POST['content'])\n\t\tpost.save()\n\t\treturn HttpResponseRedirect(reverse('post_detail', args=[post.id]))\n\treturn render(request, 'post/create.html')\n\n","sub_path":"blog/post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"275445041","text":"import glob\nimport subprocess\nimport tempfile\nimport time\n\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\nfrom os import path\n\nimport fire\n\nimport yaml\nfrom mergedeep import mergedeep\n\n\nclass Deployer:\n def __init__(self, env: str):\n self.env = env\n self.tmpl_env = Environment(\n loader=FileSystemLoader(Deployer._local_path('')),\n autoescape=select_autoescape()\n )\n\n config_file = open(Deployer._local_path(f'environments/{self.env}.yaml'), 'r')\n self.config = yaml.safe_load(config_file)\n\n def helm_install(self, app: str, chart: str, overlay_values: str = None, extra_args: list = None):\n cmd = ['helm', 'install', app, chart]\n if overlay_values is not None:\n if overlay_values.endswith('.jinja2'):\n # a bit ugly: reverse out to get back the relative path\n # for Jinja2 template resolution\n rel_path = path.relpath(overlay_values, path.dirname(__file__))\n yaml_tmpl = self.tmpl_env.get_template(rel_path)\n generated_yaml_txt = yaml_tmpl.render(self.config)\n with tempfile.NamedTemporaryFile() as tmp:\n tmp.write(generated_yaml_txt.encode('utf-8'))\n tmp.flush()\n if extra_args is not None:\n cmd.extend(extra_args)\n cmd.extend(['-f', tmp.name])\n Deployer._run_command(cmd)\n else:\n cmd.extend(['-f', Deployer._local_path(overlay_values)])\n if extra_args is not None:\n cmd.extend(extra_args)\n Deployer._run_command(cmd)\n\n def kube_install(self, yaml_path: str, namespace: str = None):\n if self.env == 'dev':\n kubectl = 'kubectl'\n else:\n kubectl = 'microk8s.kubectl'\n\n cmd = [kubectl, 'apply', '-f', yaml_path]\n if namespace is not None:\n cmd.extend(['-n', namespace])\n Deployer._run_command(cmd)\n\n def deploy_all(self, base_dir: str):\n scan_dir = Deployer._local_path(f'{base_dir}')\n input_paths = []\n for ext in ('*.yaml', '*.yaml.jinja2'):\n input_paths.extend(glob.glob(f'{scan_dir}/{ext}'))\n for input_path in input_paths:\n self.deploy(input_path)\n\n def deploy(self, input_path: str, extra_vars: dict = None):\n print(f'processing {input_path}')\n if input_path.endswith('.jinja2'):\n # a bit ugly: reverse out to get back the relative path\n # for Jinja2 template resolution\n rel_path = path.relpath(input_path, path.dirname(__file__))\n yaml_tmpl = self.tmpl_env.get_template(rel_path)\n\n tmpl_vars = self.config\n if extra_vars is not None:\n mergedeep.merge(tmpl_vars, extra_vars)\n generated_yaml_txt = yaml_tmpl.render(tmpl_vars)\n with tempfile.NamedTemporaryFile() as tmp:\n tmp.write(generated_yaml_txt.encode('utf-8'))\n tmp.flush()\n self.kube_install(tmp.name)\n else:\n self.kube_install(input_path)\n\n @staticmethod\n def _local_path(rel_path: str):\n return path.join(path.dirname(__file__), f'{rel_path}')\n\n @staticmethod\n def _run_command(args: list):\n subprocess.run(args)\n\n\n# noinspection PyDefaultArgument\ndef install_serenity(env: str = 'dev', components: list = ['core', 'db', 'infra', 'strategies', 'research']):\n if isinstance(components, str):\n components = [components]\n\n # noinspection PyUnresolvedReferences\n component_set = set([x.lower() for x in components])\n deployer = Deployer(env)\n\n # install Helm charts for infrastructure\n if 'infra' in component_set:\n deployer.helm_install('consul', 'hashicorp/consul', f'consul/consul-helm-values.yaml.jinja2',\n ['--set', 'global.name=consul'])\n print('waiting for Consul to come up')\n time.sleep(5)\n get_svc = subprocess.Popen(['kubectl', 'get', 'svc', 'consul-dns', '-o', 'jsonpath=\"{.spec.clusterIP}\"'],\n stdout=subprocess.PIPE)\n extra_vars = {'consul_dns_ip': get_svc.stdout.read().decode('utf8').replace('\"', '')}\n print(f'got Consul DNS IP: {extra_vars[\"consul_dns_ip\"]}')\n deployer.deploy('consul/consul-dns-configmap.yaml.jinja2', extra_vars)\n deployer.helm_install('prometheus', 'prometheus-community/prometheus',\n f'telemetry/prometheus-helm-values.yaml')\n deployer.helm_install('alertmanager', 'prometheus-community/alertmanager',\n f'telemetry/alertmanager-helm-values.yaml')\n deployer.helm_install('grafana', 'grafana/grafana', f'telemetry/grafana-helm-values.yaml')\n\n # install requested Kubernetes objects\n if 'core' in component_set:\n deployer.deploy_all('feedhandlers')\n\n if 'db' in component_set:\n deployer.deploy_all('db')\n\n if 'research' in component_set:\n deployer.deploy_all('research')\n\n\nif __name__ == '__main__':\n fire.Fire(install_serenity)\n","sub_path":"kubernetes/kubernetes_install.py","file_name":"kubernetes_install.py","file_ext":"py","file_size_in_byte":5200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"493164509","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\n# config = tf.ConfigProto()\r\n# config.gpu_options.per_process_gpu_memory_fraction = 0.8\r\n\r\ndata = np.load(\"50.npy\")\r\ndata_normal = (data - data.min())/(data.max()-data.min())\r\n# data_re = 1.521356 * (data.max()-data.min()) + data.min()\r\ndata_open_n = data_normal[:1200,1]\r\n\r\ntrain_keep_prob = 1.0\r\nmax_steps = 250\r\nbatch_size = 1\r\nnum_steps = 50\r\nnum_classes = 1\r\nlearning_rate = 1e-4\r\nnum_layers = 3\r\nlstm_size = 256\r\ngrad_clip = 5\r\n\r\ntf.reset_default_graph()\r\n\r\n## create RNN model\r\n# input and target\r\nwith tf.name_scope('inputs'):\r\n inputs = tf.placeholder(tf.float32, shape=(batch_size, num_steps, 1), name='inputs')\r\n targets = tf.placeholder(tf.float32, shape=(batch_size, num_steps), name='targets')\r\n keep_prob = tf.placeholder(tf.float32, name='keep_prob')\r\n\r\n# create LSTM cell\r\ndef get_a_cell(lstm_size, keep_prob):\r\n rnn_cell = tf.nn.rnn_cell.BasicLSTMCell(lstm_size, forget_bias=1.0, state_is_tuple=True)\r\n drop = tf.nn.rnn_cell.DropoutWrapper(rnn_cell, output_keep_prob=keep_prob)\r\n return drop\r\n\r\n# create muti rnn cell\r\nwith tf.name_scope('LSTMRNN'):\r\n cell = tf.nn.rnn_cell.MultiRNNCell([get_a_cell(lstm_size, keep_prob) for _ in range(num_layers)])\r\n initial_state = cell.zero_state(batch_size, tf.float32)\r\n RNN_outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)\r\n seq_output = tf.concat(RNN_outputs, 1)\r\n x = tf.reshape(seq_output, [-1, lstm_size]) \r\n \r\n# output\r\nwith tf.variable_scope('softmax'):\r\n softmax_w = tf.Variable(tf.truncated_normal([lstm_size, num_classes], stddev=0.01))\r\n softmax_b = tf.Variable(tf.zeros(num_classes))\r\n\r\nlogits = tf.matmul(x, softmax_w) + softmax_b\r\nproba_prediction = logits\r\n# proba_prediction = tf.nn.softmax(logits, name='predictions')\r\n\r\n# loss\r\nwith tf.name_scope('loss'):\r\n# y_one_hot = tf.one_hot(targets, num_classes)\r\n y_reshaped = tf.reshape(targets, [batch_size*num_steps,1])\r\n loss_nr = tf.square(y_reshaped - logits)\r\n# loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped)\r\n loss = tf.reduce_mean(loss_nr)\r\n\r\n\r\ndef get_batches(arr, n_seqs, n_steps): \r\n '''\r\n arr: data to be divided\r\n n_seqs: batch-size, # of input sequences\r\n n_steps: timestep, # of characters in a input sequences\r\n '''\r\n batch_size = n_seqs * n_steps\r\n n_batches = int(len(arr) / batch_size)\r\n arr = arr[:batch_size * n_batches]\r\n arr = arr.reshape((n_seqs, -1))\r\n\r\n for n in range(0, arr.shape[1], n_steps):\r\n x = arr[:, n:n+n_steps]\r\n y = np.zeros_like(x)\r\n y[:, :-1], y[:, -1] = x[:, 1:], x[:, 0]\r\n yield x, y\r\n \r\nre_ = np.zeros(max_steps)\r\nsaver = tf.train.Saver()\r\nsession = tf.Session() \r\nwith session as sess:\r\n initial_state = cell.zero_state(batch_size, tf.float32)\r\n new_state = sess.run(initial_state)\r\n saver.restore(session, '/home/xxxxxx/Final_model_lstm_hight')\r\n \r\n \r\n train_batches = get_batches(data_open_n, batch_size, num_steps)\r\n x, y = next(train_batches)\r\n save_x = x\r\n for epoch in range(0,max_steps):\r\n x = np.reshape(x, [batch_size, num_steps, 1])\r\n feed = {inputs: x, targets: y, keep_prob: train_keep_prob, initial_state: new_state}\r\n pre_train, new_state = sess.run([proba_prediction, final_state],feed_dict=feed)\r\n pre_train = np.reshape(np.array(pre_train), [batch_size, num_steps])\r\n pre_train = pre_train[0,batch_size]\r\n re_[epoch] = pre_train * (data.max()-data.min()) + data.min()\r\n x[0,:num_steps-1,0] = x[0,1:num_steps,0]\r\n x[0,num_steps-1,0] = pre_train\r\n \r\nnp.save(\"DayHigh.npy\",re_)\r\nplt.plot(re_, label='predict')\r\nplt.plot(data[num_steps:max_steps+num_steps,1], label='real')\r\nplt.legend(loc='upper right')\r\nplt.title('Yuan Da Taiwan 50 - Day High')\r\nplt.xlabel('day')\r\nplt.ylabel('price')\r\nplt.show()\r\n","sub_path":"code/Plot_Day_High.py","file_name":"Plot_Day_High.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145754658","text":"import numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport sys\nfrom torch.autograd import Variable\nimport math\nimport os\nimport urllib.request\nfrom tqdm import tqdm\n\n\ndef _reporthook(t):\n \"\"\" ``reporthook`` to use with ``urllib.request`` that prints the process of the download.\n\n Uses ``tqdm`` for progress bar.\n\n **Reference:**\n https://github.com/tqdm/tqdm\n\n Args:\n t (tqdm.tqdm) Progress bar.\n\n Example:\n >>> with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t: # doctest: +SKIP\n ... urllib.request.urlretrieve(file_url, filename=full_path, reporthook=reporthook(t))\n \"\"\"\n last_b = [0]\n\n def inner(b=1, bsize=1, tsize=None):\n \"\"\"\n Args:\n b (int, optional): Number of blocks just transferred [default: 1].\n bsize (int, optional): Size of each block (in tqdm units) [default: 1].\n tsize (int, optional): Total size (in tqdm units). If [default: None] remains unchanged.\n \"\"\"\n if tsize is not None:\n t.total = tsize\n t.update((b - last_b[0]) * bsize)\n last_b[0] = b\n\n return inner\n\n\ndef flip(x, dim):\n xsize = x.size()\n dim = x.dim() + dim if dim < 0 else dim\n x = x.contiguous()\n x = x.view(-1, *xsize[dim:])\n x = x.view(x.size(0), x.size(1), -1)[:, getattr(torch.arange(x.size(1)-1, \n -1, -1), ('cpu','cuda')[x.is_cuda])().long(), :]\n return x.view(xsize)\n\n\ndef sinc(band,t_right):\n y_right= torch.sin(2*math.pi*band*t_right)/(2*math.pi*band*t_right)\n y_left= flip(y_right,0)\n\n y=torch.cat([y_left,Variable(torch.ones(1)).cuda(),y_right])\n\n return y\n \n\nclass SincConvLayer(nn.Module):\n \"\"\"Sinc-based convolution\n Parameters\n ----------\n in_channels : `int`\n Number of input channels. Must be 1.\n out_channels : `int`\n Number of filters.\n kernel_size : `int`\n Filter length.\n sample_rate : `int`, optional\n Sample rate. Defaults to 16000.\n Usage\n -----\n See `torch.nn.Conv1d`\n Reference\n ---------\n Mirco Ravanelli, Yoshua Bengio,\n \"Speaker Recognition from raw waveform with SincNet\".\n https://arxiv.org/abs/1808.00158\n \"\"\"\n\n @staticmethod\n def to_mel(hz):\n return 2595 * np.log10(1 + hz / 700)\n\n @staticmethod\n def to_hz(mel):\n return 700 * (10 ** (mel / 2595) - 1)\n\n def __init__(self, out_channels, kernel_size, sample_rate=16000, in_channels=1,\n stride=1, padding=0, dilation=1, bias=False, groups=1, min_low_hz=50, min_band_hz=50):\n\n super(SincConvLayer,self).__init__()\n\n if in_channels != 1:\n #msg = (f'SincConv only support one input channel '\n # f'(here, in_channels = {in_channels:d}).')\n msg = \"SincConv only support one input channel (here, in_channels = {%i})\" % (in_channels)\n raise ValueError(msg)\n\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n \n # Forcing the filters to be odd (i.e, perfectly symmetrics)\n if kernel_size%2==0:\n self.kernel_size=self.kernel_size+1\n \n self.stride = stride\n self.padding = padding\n self.dilation = dilation\n\n if bias:\n raise ValueError('SincConv does not support bias.')\n if groups > 1:\n raise ValueError('SincConv does not support groups.')\n\n self.sample_rate = sample_rate\n self.min_low_hz = min_low_hz\n self.min_band_hz = min_band_hz\n\n # initialize filterbanks such that they are equally spaced in Mel scale\n low_hz = 30\n high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz)\n\n mel = np.linspace(self.to_mel(low_hz),\n self.to_mel(high_hz),\n self.out_channels + 1)\n hz = self.to_hz(mel)\n \n\n # filter lower frequency (out_channels, 1)\n self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1))\n\n # filter frequency band (out_channels, 1)\n self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1))\n\n # Hamming window\n #self.window_ = torch.hamming_window(self.kernel_size)\n n_lin=torch.linspace(0, (self.kernel_size/2)-1, steps=int((self.kernel_size/2))) # computing only half of the window\n self.window_=0.54-0.46*torch.cos(2*math.pi*n_lin/self.kernel_size);\n\n\n # (1, kernel_size/2)\n n = (self.kernel_size - 1) / 2.0\n self.n_ = 2*math.pi*torch.arange(-n, 0).view(1, -1) / self.sample_rate # Due to symmetry, I only need half of the time axes\n\n \n\n\n def forward(self, waveforms):\n \"\"\"\n Parameters\n ----------\n waveforms : `torch.Tensor` (batch_size, 1, n_samples)\n Batch of waveforms.\n Returns\n -------\n features : `torch.Tensor` (batch_size, out_channels, n_samples_out)\n Batch of sinc filters activations.\n \"\"\"\n\n self.n_ = self.n_.to(waveforms.device)\n\n self.window_ = self.window_.to(waveforms.device)\n\n low = self.min_low_hz + torch.abs(self.low_hz_)\n \n high = torch.clamp(low + self.min_band_hz + torch.abs(self.band_hz_),self.min_low_hz,self.sample_rate/2)\n band=(high-low)[:,0]\n \n f_times_t_low = torch.matmul(low, self.n_)\n f_times_t_high = torch.matmul(high, self.n_)\n\n band_pass_left=((torch.sin(f_times_t_high)-torch.sin(f_times_t_low))/(self.n_/2))*self.window_ # Equivalent of Eq.4 of the reference paper (SPEAKER RECOGNITION FROM RAW WAVEFORM WITH SINCNET). I just have expanded the sinc and simplified the terms. This way I avoid several useless computations. \n band_pass_center = 2*band.view(-1,1)\n band_pass_right= torch.flip(band_pass_left,dims=[1])\n \n \n band_pass=torch.cat([band_pass_left,band_pass_center,band_pass_right],dim=1)\n\n \n band_pass = band_pass / (2*band[:,None])\n \n\n self.filters = (band_pass).view(\n self.out_channels, 1, self.kernel_size)\n\n return F.conv1d(waveforms, self.filters, stride=self.stride,\n padding=self.padding, dilation=self.dilation,\n bias=None, groups=1) \n \nclass sinc_conv(nn.Module):\n\n def __init__(self, N_filt,Filt_dim,fs):\n super(sinc_conv,self).__init__()\n\n # Mel Initialization of the filterbanks\n low_freq_mel = 80\n high_freq_mel = (2595 * np.log10(1 + (fs / 2) / 700)) # Convert Hz to Mel\n mel_points = np.linspace(low_freq_mel, high_freq_mel, N_filt) # Equally spaced in Mel scale\n f_cos = (700 * (10**(mel_points / 2595) - 1)) # Convert Mel to Hz\n b1=np.roll(f_cos,1)\n b2=np.roll(f_cos,-1)\n b1[0]=30\n b2[-1]=(fs/2)-100\n \n self.freq_scale=fs*1.0\n self.filt_b1 = nn.Parameter(torch.from_numpy(b1/self.freq_scale))\n self.filt_band = nn.Parameter(torch.from_numpy((b2-b1)/self.freq_scale))\n\n \n self.N_filt=N_filt\n self.Filt_dim=Filt_dim\n self.fs=fs\n \n\n def forward(self, x):\n \n filters=Variable(torch.zeros((self.N_filt,self.Filt_dim))).cuda()\n N=self.Filt_dim\n t_right=Variable(torch.linspace(1, (N-1)/2, steps=int((N-1)/2))/self.fs).cuda()\n \n \n min_freq=50.0;\n min_band=50.0;\n \n filt_beg_freq=torch.abs(self.filt_b1)+min_freq/self.freq_scale\n filt_end_freq=filt_beg_freq+(torch.abs(self.filt_band)+min_band/self.freq_scale)\n \n n=torch.linspace(0, N, steps=N)\n\n # Filter window (hamming)\n window=0.54-0.46*torch.cos(2*math.pi*n/N);\n window=Variable(window.float().cuda())\n\n \n for i in range(self.N_filt):\n \n low_pass1 = 2*filt_beg_freq[i].float()*sinc(filt_beg_freq[i].float()*self.freq_scale,t_right)\n low_pass2 = 2*filt_end_freq[i].float()*sinc(filt_end_freq[i].float()*self.freq_scale,t_right)\n band_pass=(low_pass2-low_pass1)\n\n band_pass=band_pass/torch.max(band_pass)\n\n filters[i,:]=band_pass.cuda()*window\n\n out=F.conv1d(x, filters.view(self.N_filt,1,self.Filt_dim))\n \n return out\n \n\ndef act_fun(act_type):\n\n if act_type==\"relu\":\n return nn.ReLU()\n \n if act_type==\"tanh\":\n return nn.Tanh()\n \n if act_type==\"sigmoid\":\n return nn.Sigmoid()\n \n if act_type==\"leaky_relu\":\n return nn.LeakyReLU(0.2)\n \n if act_type==\"elu\":\n return nn.ELU()\n \n if act_type==\"softmax\":\n return nn.LogSoftmax(dim=1)\n \n if act_type==\"linear\":\n return nn.LeakyReLU(1) # initializzed like this, but not used in forward!\n \n \nclass LayerNorm(nn.Module):\n\n def __init__(self, features, eps=1e-6):\n super(LayerNorm,self).__init__()\n self.gamma = nn.Parameter(torch.ones(features))\n self.beta = nn.Parameter(torch.zeros(features))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.gamma * (x - mean) / (std + self.eps) + self.beta\n\n\nclass MLP(nn.Module):\n def __init__(self, options):\n super(MLP, self).__init__()\n \n self.input_dim=int(options['input_dim'])\n self.fc_lay=options['fc_lay']\n self.fc_drop=options['fc_drop']\n self.fc_use_batchnorm=options['fc_use_batchnorm']\n self.fc_use_laynorm=options['fc_use_laynorm']\n self.fc_use_laynorm_inp=options['fc_use_laynorm_inp']\n self.fc_use_batchnorm_inp=options['fc_use_batchnorm_inp']\n self.fc_act=options['fc_act']\n \n \n self.wx = nn.ModuleList([])\n self.bn = nn.ModuleList([])\n self.ln = nn.ModuleList([])\n self.act = nn.ModuleList([])\n self.drop = nn.ModuleList([])\n \n\n \n # input layer normalization\n if self.fc_use_laynorm_inp:\n self.ln0=LayerNorm(self.input_dim)\n \n # input batch normalization \n if self.fc_use_batchnorm_inp:\n self.bn0=nn.BatchNorm1d([self.input_dim],momentum=0.05)\n \n \n self.N_fc_lay=len(self.fc_lay)\n \n current_input=self.input_dim\n \n # Initialization of hidden layers\n \n for i in range(self.N_fc_lay):\n \n # dropout\n self.drop.append(nn.Dropout(p=self.fc_drop[i]))\n \n # activation\n self.act.append(act_fun(self.fc_act[i]))\n \n \n add_bias=True\n \n # layer norm initialization\n self.ln.append(LayerNorm(self.fc_lay[i]))\n self.bn.append(nn.BatchNorm1d(self.fc_lay[i],momentum=0.05))\n \n if self.fc_use_laynorm[i] or self.fc_use_batchnorm[i]:\n add_bias=False\n \n \n # Linear operations\n self.wx.append(nn.Linear(current_input, self.fc_lay[i],bias=add_bias))\n \n # weight initialization\n self.wx[i].weight = torch.nn.Parameter(torch.Tensor(self.fc_lay[i],current_input).uniform_(-np.sqrt(0.01/(current_input+self.fc_lay[i])),np.sqrt(0.01/(current_input+self.fc_lay[i]))))\n self.wx[i].bias = torch.nn.Parameter(torch.zeros(self.fc_lay[i]))\n \n current_input=self.fc_lay[i]\n \n \n def forward(self, x):\n \n # Applying Layer/Batch Norm\n if bool(self.fc_use_laynorm_inp):\n x=self.ln0((x))\n \n if bool(self.fc_use_batchnorm_inp):\n x=self.bn0((x))\n \n for i in range(self.N_fc_lay):\n\n if self.fc_act[i]!='linear':\n \n if self.fc_use_laynorm[i]:\n x = self.drop[i](self.act[i](self.ln[i](self.wx[i](x))))\n \n if self.fc_use_batchnorm[i]:\n x = self.drop[i](self.act[i](self.bn[i](self.wx[i](x))))\n \n if self.fc_use_batchnorm[i]==False and self.fc_use_laynorm[i]==False:\n x = self.drop[i](self.act[i](self.wx[i](x)))\n \n else:\n if self.fc_use_laynorm[i]:\n x = self.drop[i](self.ln[i](self.wx[i](x)))\n \n if self.fc_use_batchnorm[i]:\n x = self.drop[i](self.bn[i](self.wx[i](x)))\n \n if self.fc_use_batchnorm[i]==False and self.fc_use_laynorm[i]==False:\n x = self.drop[i](self.wx[i](x)) \n \n return x\n\n\n\nclass SincNetModel(nn.Module):\n \n def __init__(self,options):\n super(SincNetModel,self).__init__()\n \n self.cnn_N_filt=options['cnn_N_filt']\n self.cnn_len_filt=options['cnn_len_filt']\n self.cnn_max_pool_len=options['cnn_max_pool_len']\n \n \n self.cnn_act=options['cnn_act']\n self.cnn_drop=options['cnn_drop']\n \n self.cnn_use_laynorm=options['cnn_use_laynorm']\n self.cnn_use_batchnorm=options['cnn_use_batchnorm']\n self.cnn_use_laynorm_inp=options['cnn_use_laynorm_inp']\n self.cnn_use_batchnorm_inp=options['cnn_use_batchnorm_inp']\n \n self.input_dim=int(options['input_dim'])\n \n self.fs=options['fs']\n \n self.N_cnn_lay=len(options['cnn_N_filt'])\n self.conv = nn.ModuleList([])\n self.bn = nn.ModuleList([])\n self.ln = nn.ModuleList([])\n self.act = nn.ModuleList([])\n self.drop = nn.ModuleList([])\n \n \n if self.cnn_use_laynorm_inp:\n self.ln0=LayerNorm(self.input_dim)\n \n if self.cnn_use_batchnorm_inp:\n self.bn0=nn.BatchNorm1d([self.input_dim],momentum=0.05)\n \n current_input=self.input_dim \n \n for i in range(self.N_cnn_lay):\n \n N_filt=int(self.cnn_N_filt[i])\n len_filt=int(self.cnn_len_filt[i])\n \n # dropout\n self.drop.append(nn.Dropout(p=self.cnn_drop[i]))\n \n # activation\n self.act.append(act_fun(self.cnn_act[i]))\n \n # layer norm initialization \n self.ln.append(LayerNorm([N_filt,int((current_input-self.cnn_len_filt[i]+1)/self.cnn_max_pool_len[i])]))\n\n self.bn.append(nn.BatchNorm1d(N_filt,int((current_input-self.cnn_len_filt[i]+1)/self.cnn_max_pool_len[i]),momentum=0.05))\n \n\n if i==0:\n self.conv.append(SincConvLayer(self.cnn_N_filt[0],self.cnn_len_filt[0],self.fs))\n \n else:\n self.conv.append(nn.Conv1d(self.cnn_N_filt[i-1], self.cnn_N_filt[i], self.cnn_len_filt[i]))\n \n current_input=int((current_input-self.cnn_len_filt[i]+1)/self.cnn_max_pool_len[i])\n\n \n self.out_dim=current_input*N_filt\n\n\n\n def forward(self, x):\n batch=x.shape[0]\n seq_len=x.shape[1]\n \n if bool(self.cnn_use_laynorm_inp):\n x=self.ln0((x))\n \n if bool(self.cnn_use_batchnorm_inp):\n x=self.bn0((x))\n \n x=x.view(batch,1,seq_len)\n \n for i in range(self.N_cnn_lay):\n \n if self.cnn_use_laynorm[i]:\n if i==0:\n x = self.drop[i](self.act[i](self.ln[i](F.max_pool1d(torch.abs(self.conv[i](x)), self.cnn_max_pool_len[i])))) \n else:\n x = self.drop[i](self.act[i](self.ln[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])))) \n \n if self.cnn_use_batchnorm[i]:\n x = self.drop[i](self.act[i](self.bn[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i]))))\n\n if self.cnn_use_batchnorm[i]==False and self.cnn_use_laynorm[i]==False:\n x = self.drop[i](self.act[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])))\n\n x = x.view(batch,-1)\n return x\n \n\n \nclass SincNet(nn.Module):\n def __init__(self, only_cnn=False, pretrained=True, pretrained_path=None, device=torch.device(\"cpu\")):\n super(SincNet, self).__init__()\n self.only_cnn = only_cnn\n self.device = device\n \n # [cnn]\n fs = 16000\n cw_len=200\n wlen=int(fs*cw_len/1000.00)\n cnn_N_filt=80,60,60\n cnn_len_filt=251,5,5\n cnn_max_pool_len=3,3,3\n cnn_use_laynorm_inp=True\n cnn_use_batchnorm_inp=False\n cnn_use_laynorm=True,True,True\n cnn_use_batchnorm=False,False,False\n cnn_act=['relu','relu','relu']\n cnn_drop=0.0,0.0,0.0\n\n # [dnn]\n fc_lay=2048,2048,2048\n fc_drop=[0.0,0.0,0.0]\n fc_use_laynorm_inp=True\n fc_use_batchnorm_inp=False\n fc_use_batchnorm=True,True,True\n fc_use_laynorm=False,False,False\n fc_act=['leaky_relu','leaky_relu','leaky_relu']\n\n # [class]\n class_lay=[10]\n class_drop=[0.0]\n class_use_laynorm_inp=False\n class_use_batchnorm_inp=False\n class_use_batchnorm=[False]\n class_use_laynorm=[False]\n class_act=['softmax']\n\n CNN_arch = {'input_dim': wlen,\n 'fs': fs,\n 'cnn_N_filt': cnn_N_filt,\n 'cnn_len_filt': cnn_len_filt,\n 'cnn_max_pool_len':cnn_max_pool_len,\n 'cnn_use_laynorm_inp': cnn_use_laynorm_inp,\n 'cnn_use_batchnorm_inp': cnn_use_batchnorm_inp,\n 'cnn_use_laynorm':cnn_use_laynorm,\n 'cnn_use_batchnorm':cnn_use_batchnorm,\n 'cnn_act': cnn_act,\n 'cnn_drop':cnn_drop, \n }\n\n self.cnn_network = SincNetModel(CNN_arch)\n\n DNN1_arch = {'input_dim': self.cnn_network.out_dim,\n 'fc_lay': fc_lay,\n 'fc_drop': fc_drop, \n 'fc_use_batchnorm': fc_use_batchnorm,\n 'fc_use_laynorm': fc_use_laynorm,\n 'fc_use_laynorm_inp': fc_use_laynorm_inp,\n 'fc_use_batchnorm_inp':fc_use_batchnorm_inp,\n 'fc_act': fc_act,\n }\n\n DNN2_arch = {'input_dim':fc_lay[-1] ,\n 'fc_lay': class_lay,\n 'fc_drop': class_drop, \n 'fc_use_batchnorm': class_use_batchnorm,\n 'fc_use_laynorm': class_use_laynorm,\n 'fc_use_laynorm_inp': class_use_laynorm_inp,\n 'fc_use_batchnorm_inp':class_use_batchnorm_inp,\n 'fc_act': class_act,\n }\n if not self.only_cnn:\n self.ann_network1 = MLP(DNN1_arch)\n self.ann_network2 = MLP(DNN2_arch)\n \n if pretrained:\n filename = \"model_raw.pkl\"\n pretrained_weights_link = \"https://bitbucket.org/mravanelli/sincnet_models/raw/f3588bdf02b4634a975549500f6f68bd1a80a997/SincNet_TIMIT/model_raw.pkl\"\n if pretrained_path == None:\n if not os.path.exists(filename):\n print(f'Downloading the pretrained weights from sincnet({pretrained_weights_link}) ...', flush=True)\n with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t:\n urllib.request.urlretrieve(pretrained_weights_link, filename, reporthook=_reporthook(t))\n cp = torch.load(filename, map_location=self.device) \n else: \n cp = torch.load(pretrained_path, map_location=self.device)\n self.cnn_network.load_state_dict(cp['CNN_model_par'])\n if not self.only_cnn:\n self.ann_network1.load_state_dict(cp['DNN1_model_par'])\n # self.ann_network2.load_state_dict(cp['DNN2_model_par'])\n\n def forward(self, x):\n x = x.squeeze(1)\n y = self.cnn_network(x)\n if not self.only_cnn:\n y = self.ann_network1(y)\n # y = self.ann_network2(y)\n return y","sub_path":"wavencoder/models/sincnet.py","file_name":"sincnet.py","file_ext":"py","file_size_in_byte":19739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"422356509","text":"import os\n# 1000 boards of size 10\n\ndef size_qsub(app, threads, scriptpath):\n buffer = []\n buffer.append('#!/bin/bash\\n')\n buffer.append('#\\n')\n buffer.append('#$ -cwd\\n')\n buffer.append('#$ -j y\\n')\n buffer.append('#$ -S /bin/bash\\n')\n buffer.append('#$ -pe orte %d\\n\\n' % threads)\n buffer.append('/opt/openmpi/bin/mpirun -np $NSLOTS ./%s rand dict/scrabble.txt ' % app +\n '%d %d time > node-results/%d\\n' % (10, 1000, threads))\n\n file = open(scriptpath, 'w')\n file.writelines(buffer)\n file.close()\n\nos.system('rm -rf node-results; mkdir node-results')\nfor i in range(2, 17):\n path = 'node-qsub-%d.qsub' % i\n size_qsub('mpi-pos/boggle.x', i, path)\n os.system('qsub -pe orte %d %s' % (i, path))\n","sub_path":"boggle/run-mpi.py","file_name":"run-mpi.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"266127057","text":"import numpy as np\nfrom sklearn.preprocessing import normalize\n\nfrom actors.LoggingActor import LoggingActor\nfrom util.math_utils import low_rank_approximation, tf_idf\n\n\nclass Dictionary(LoggingActor):\n def __init__(self, ndocs, master):\n super().__init__(Dictionary, self)\n self.master = master\n self.number_of_documents = ndocs\n self.terms = []\n self.documents_index = np.zeros((0, ndocs))\n\n def on_receive(self, message):\n if message.get('msg') == 'token met':\n self.handle_token_met_message(message)\n if message.get('msg') == 'compute index approximation':\n self.handle_get_index_approximate_message(message)\n\n def handle_token_met_message(self, message):\n term = message.get('token')\n token_number = self.get_term_index(term)\n document_number = message.get('document number')\n term_weight = message.get('token weight')\n self.documents_index[token_number][document_number] += term_weight\n\n def handle_get_index_approximate_message(self, message):\n rank = message.get('rank')\n lowerest_dimension = min(self.documents_index.shape)\n ncomponents = min(rank, lowerest_dimension - 1)\n approximation = self.documents_index.copy()\n approximation = tf_idf(approximation)\n approximation = low_rank_approximation(matrix=approximation, rank=ncomponents)\n approximation = normalize(approximation, axis=0, norm='l1')\n\n self.master.tell(\n {\n 'msg': 'low rank approximation computed',\n 'vectors': approximation.transpose()\n })\n\n def get_term_index(self, term):\n try:\n return self.terms.index(term)\n except ValueError:\n return self.append_term(term)\n\n def append_term(self, term):\n self.terms.append(term)\n self.documents_index = np.vstack((self.documents_index, np.zeros(self.number_of_documents)))\n return len(self.documents_index) - 1\n","sub_path":"actors/Dictionary.py","file_name":"Dictionary.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"162840536","text":"from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url\nimport m3u8\nfrom pprint import pprint\nfrom pytube.compat import urlopen\nfrom pydub import AudioSegment\nimport io\nimport time\nimport os\nimport pprint\nimport sys\nfrom deepaffects.realtime.util import get_segment_chunk_from_pydub_chunk\n\nTIMEOUT_SECONDS = 10000\napikey = \"YOUR_API_KEY\"\nfile_path = \"PLAYLIST_PATH\"\nis_youtube_url = False\nlanguageCode = \"en-Us\"\nsampleRate = \"16000\"\nencoding = \"mp3\"\nspeakerIds = \"list of userids for for speaker verification seperated by ','\"\napiVersion = \"v2\"\nverbose = \"True\"\n\n\ndef chunk_generator_from_playlist(file_path=None, buffer_size=3):\n try:\n offset = 0\n last_processed = -1\n endlist = False\n # for playlists with m3u8 extensions\n m3u8_obj_outer = m3u8.load(\n file_path)\n base_uri = m3u8_obj_outer.base_uri\n base_audio = m3u8_obj_outer.data['playlists'][0]['uri']\n audio_stream_url = base_uri + base_audio\n chunk = None\n chunk_index = 1\n index = 0\n\n while endlist is not True:\n m3u8_obj = m3u8.load(audio_stream_url) \n if last_processed < m3u8_obj.media_sequence: \n for i, segment in enumerate(m3u8_obj.data['segments']):\n response = urlopen(base_uri + segment['uri'])\n buff = response.read()\n if chunk_index == 1:\n chunk = AudioSegment.from_file(io.BytesIO(buff), \"aac\") \n chunk_index = chunk_index + 1\n elif chunk_index < buffer_size:\n chunk = chunk + AudioSegment.from_file(io.BytesIO(buff), \"aac\") \n chunk_index = chunk_index + 1\n elif chunk_index == buffer_size:\n chunk = chunk + AudioSegment.from_file(io.BytesIO(buff), \"aac\") \n audio_segment, offset = get_segment_chunk_from_pydub_chunk(chunk, offset, index)\n index = index + 1\n yield audio_segment \n chunk_index = 1 \n last_processed = m3u8_obj.media_sequence\n if m3u8_obj.data['is_endlist']:\n endlist = True\n else:\n time.sleep(2)\n\n except KeyboardInterrupt:\n print('Interrupted Stopping Stream')\n os._exit(0)\n\n# DeepAffects realtime Api client\nclient = get_deepaffects_client()\n\nmetadata = [\n ('apikey', apikey),\n ('speakerids', speakerIds),\n ('encoding', encoding),\n ('samplerate', sampleRate),\n ('languagecode', languageCode),\n ('apiversion', apiVersion),\n ('verbose', verbose)\n]\n\n# Implement chunk_generator() is a generator function which yields segment_chunk objects asynchronously\n# from deepaffects.realtime.types import segment_chunk\n# yield segment_chunk(Args)\n\"\"\"segment_chunk.\n\nArgs:\n encoding : Audio Encoding,\n languageCode: language code ,\n sampleRate: sample rate of audio ,\n content: base64 encoded audio,\n segmentOffset: offset of the segment in complete audio stream\n\"\"\"\n\n\"\"\"\nSample implementation which reads audio from a file and splits it into\nsegments more than 3 sec\nAudioSegment and yields base64 encoded audio segment objects asynchronously\n\"\"\"\n\n\"\"\"Stream audio from earningcast.\n\"\"\"\nresponses = client.DiarizeEmotion(\n chunk_generator_from_playlist(file_path), TIMEOUT_SECONDS, metadata=metadata)\n\n# responses is the iterator for all the response values\nfor response in responses:\n print(\"Received message\")\n print(response)\n\n\"\"\"Response.\n response = {\n emotion: Emotion identified in the segment,\n start: start of the segment,\n end: end of the segment\n }\n\"\"\"\n","sub_path":"examples/playlist_chunk_generator.py","file_name":"playlist_chunk_generator.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56511905","text":"import unittest\n\n\nclass TestBaseIntent(unittest.TestCase):\n\n def get_mock_event(self, intent=None, session_id=\"SessionId.uuid\", attributes=None):\n mock_event = {\n \"session\": {\n \"sessionId\": session_id,\n \"application\": {\n \"applicationId\": \"amzn1.ask.skill.1234\"\n },\n \"user\": {\n \"userId\": \"user_id\"\n },\n \"new\": False\n },\n \"request\": {\n \"requestId\": \"EdwRequestId.24744310-0cfc-432e-a5fd-d5f42813b8b7\",\n \"locale\": \"en-US\",\n \"timestamp\": \"2016-12-16T16:27:31Z\",\n },\n \"version\": \"1.0\"\n }\n if intent:\n mock_event[\"request\"][\"type\"] = \"IntentRequest\"\n mock_event[\"request\"][\"intent\"] = intent\n\n if attributes:\n mock_event[\"session\"][\"attributes\"] = attributes\n\n return mock_event\n\n def launch_request(self):\n return dict(\n session={\n \"sessionId\": \"SessionId.5\",\n \"application\": {\n \"applicationId\": \"amzn1.ask.skill.7\"\n },\n \"user\": {\n \"userId\": \"amzn1.ask.account.E\"\n },\n \"new\": True\n }, request={\n \"type\": \"LaunchRequest\",\n \"requestId\": \"EdwRequestId.3\",\n \"locale\": \"en-US\",\n \"timestamp\": \"2016-12-22T22:12:42Z\"\n }, version=\"1.0\"\n )\n","sub_path":"tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"511391540","text":"import tkinter as tk\nfrom tkinter import ttk\n\nwin = tk.Tk()\nwin.title('Pads')\n\n\n### LabelFrame for showing the result\nlabel_frame_show = ttk.LabelFrame(win, text = 'Enter the text below')\nlabel_frame_show.grid(row = 0, column = 0, padx = 40)\n\nlabels = ['Name: ', 'Age: ', 'Sex', 'Country: ']\nfor i in range(len(labels)):\n\n cur_label = 'label' + str(i)\n cur_label = ttk.Label(label_frame_show, text = labels[i])\n cur_label.grid(row = i, column = 0, sticky = tk.W)\n\n\nuser_info = {\n 'Name': tk.StringVar(),\n 'Age': tk.StringVar(),\n 'Sex': tk.StringVar(),\n 'Country': tk.StringVar()\n}\ncount = 0\nfor j in user_info:\n \n cur_entrybox = ttk.Entry(label_frame_show, width = 16, textvariable = user_info[j])\n cur_entrybox.grid(row = count, column = 1)\n cur_entrybox.focus()\n count += 1\n####\n\n#### padding for all the widgets in label_frame_show\nfor child in label_frame_show.winfo_children():\n child.grid_configure(padx = 5, pady = 2)\n#####\n\n##### Submit button #####\ndef show():\n\n label_right = tk.LabelFrame(win, text = 'Result')\n label_right.grid(row = 0, column = 1)\n\n data = []\n for i in user_info:\n data.append(user_info[i].get())\n tk.Label(label_right, text = f'Name = {data[0]}\\nAge = {data[1]}\\nSex = {data[2]}\\nCountry = {data[3]}')\n\n for child in label_right.winfo_children():\n child.grid_configure(row = 0, column = 0, padx = 4, pady = 4)\n\nbutton = ttk.Button(win, text = 'Show', command = show)\nbutton.grid(row = 1, column = 0)\n#####\n\n\nwin.mainloop()","sub_path":"tkinter/paddinglabel.py","file_name":"paddinglabel.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"561683984","text":"import Character as c\n\nimport Loot_Pool as lp\n\nimport Functions as f\n\nimport random\n\nclass Shop(object):\n\n banned_items = []\n\n def __init__(self, value1, price1, value2, price2, value3, price3):\n self.value1 = value1\n self.value2 = value2\n self.value3 = value3\n self.item1 = lp.loot_pool.item_list[value1]['name']\n self.item2 = lp.loot_pool.item_list[value2]['name']\n self.item3 = lp.loot_pool.item_list[value3]['name']\n self.price1 = price1\n self.price2 = price2\n self.price3 = price3\n\n def asr(self):\n bools = True\n while bools == True:\n print(self.item1, \": \" + \"$\" + str(self.price1), \"(0) ||\", self.item2, \": $\" + str(self.price2), \"(1) ||\", self.item3, \": \" + \"$\" + str(self.price3), \"(2)\")\n f.bw()\n print(\"You have $\" + str(c.player.money))\n f.bw()\n shop_input = input(\"<--Type a character, 'exit' to exit or 'print stats' to view stats--> \")\n if shop_input == 'exit':\n bools = False\n if shop_input == 'quit':\n quit()\n elif shop_input == 'print stats':\n abools = True\n while abools == True:\n f.bw()\n stats_input = input(\"Which item number? (0, 1, or 2) (or 'exit' to exit) \")\n f.bw()\n if stats_input == '0' or stats_input == '1' or stats_input == '2':\n abools = False\n _stats_input = getattr(self, (\"value\" + str(int(stats_input) + 1)))\n lp.print_item(_stats_input)\n elif stats_input == 'exit':\n abools = False\n elif stats_input == 'help':\n f.print_help('shop print stats prompt')\n elif stats_input == 'quit':\n quit()\n else:\n print(\"<--Please enter a valid item number-->\")\n elif shop_input == '0' or shop_input == '1' or shop_input == '2':\n item_var = (\"item\" + str(int(shop_input) + 1))\n price_var = ('price' + str(int(shop_input) + 1))\n value_var = (\"value\" + str(int(shop_input) + 1))\n item = getattr(self, item_var)\n price = getattr(self, price_var)\n value = getattr(self, value_var)\n if shop_input in self.banned_items:\n f.bw()\n print(\"Sorry, this item is sold out.\")\n f.bw()\n\n elif c.player.money >= price:\n c.player.money -= price\n c.player.add_to_inventory(value)\n f.bw()\n print(\"You've bought \" + item)\n f.bw()\n exec(\"%s = %r\" % ((\"self.\" + item_var), \"Sold\"))\n exec(\"%s = %d\" % ((\"self.\" + price_var), 0))\n self.banned_items.append(shop_input)\n lp.loot_pool.item_list.pop(value)\n\n else: \n f.bw()\n print(\"You can't afford that!\")\n f.bw()\n\n elif shop_input == 'print i':\n f.bw()\n print(c.player.inventory)\n f.bw()\n\n elif shop_input == 'help':\n f.print_help('shop')\n \n else:\n f.bw()\n print(\"<--Please enter a valid character-->\")\n f.bw()\n \n def __call__(self): \n self.asr()\n\nclass Random_Shop(Shop):\n \n banned_items = []\n value1 = lp.shop_get_loot()\n value2 = lp.shop_get_loot()\n value3 = lp.shop_get_loot()\n item1 = lp.loot_pool.item_list[value1]['name']\n item2 = lp.loot_pool.item_list[value2]['name']\n item3 = lp.loot_pool.item_list[value3]['name']\n price1 = random.randint(1, 7)\n price2 = random.randint(1, 7)\n price3 = random.randint(1, 7)\n\n def __init__(self):\n pass\n\n def __call__(self):\n self.asr()\n\ndef create_shop(value1, price1, value2, price2, value3, price3):\n shop = Shop(value1, price1, value2, price2, value3, price3)\n shop()\n \ndef create_random_shop():\n shop = Random_Shop()\n shop()\n","sub_path":"Shop.py","file_name":"Shop.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"319562306","text":"from vidstream import ScreenShareClient\nimport threading\n\n#specify host you want to connect to\nsender = ScreenShareClient('10.0.0.46',14089)\n\nt = threading.Thread(target=sender.start_stream)\nt.start()\n\nwhile input(\"\") != 'STOP':\n continue\n\nsender.stop_stream() \n","sub_path":"practice/videoSender.py","file_name":"videoSender.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"207854249","text":"from pico2d import *\n\nKPU_WIDTH, KPU_HEIGHT = 1280, 824\nopen_canvas(KPU_WIDTH, KPU_HEIGHT)\nkpu_ground = load_image('KPU_GROUND.png')\ncharacter = load_image('animation_sheet.png')\nx, y = KPU_WIDTH // 2, KPU_HEIGHT // 2\nrunning = True\nframe = 0\ndir_x = 0\ndir_y = 0\nstop = 1\n\n\ndef handle_events():\n # fill here\n global running, dir_x, dir_y, stop\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n running = False\n elif event.type == SDL_KEYDOWN:\n if event.key == SDLK_RIGHT:\n dir_x += 1\n elif event.key == SDLK_LEFT:\n dir_x -= 1\n elif event.key == SDLK_UP:\n dir_y += 1\n elif event.key == SDLK_DOWN:\n dir_y -= 1\n elif event.key == SDLK_ESCAPE:\n running = False\n elif event.type == SDL_KEYUP:\n if event.key == SDLK_RIGHT:\n dir_x -= 1\n stop = 1\n elif event.key == SDLK_LEFT:\n dir_x += 1\n stop = -1\n elif event.key == SDLK_UP:\n dir_y -= 1\n elif event.key == SDLK_DOWN:\n dir_y += 1\n pass\n\n\ndef character_move():\n global dir_x, dir_y, x, y\n if x > 21 and dir_x < 0:\n x += dir_x * 10\n elif x < 1259 and dir_x > 0:\n x += dir_x * 10\n if y < 778 and dir_y > 0:\n y += dir_y * 10\n elif y > 41 and dir_y < 0:\n y += dir_y * 10\n pass\n\n\ndef character_animation():\n global dir_x, dir_y, x, y\n if dir_x < 0:\n character.clip_draw(frame * 100, 100 * 0, 100, 100, x, y)\n elif dir_x > 0:\n character.clip_draw(frame * 100, 100 * 1, 100, 100, x, y)\n elif dir_x == 0:\n if stop < 0:\n if dir_y != 0:\n character.clip_draw(frame * 100, 100 * 0, 100, 100, x, y)\n else:\n character.clip_draw(100, 100 * 2, 100, 100, x, y)\n elif stop > 0:\n if dir_y != 0:\n character.clip_draw(frame * 100, 100 * 1, 100, 100, x, y)\n else:\n character.clip_draw(100, 100 * 3, 100, 100, x, y)\n\n\nwhile running:\n clear_canvas()\n kpu_ground.draw(KPU_WIDTH // 2, KPU_HEIGHT // 2)\n character_animation()\n update_canvas()\n\n handle_events()\n frame = (frame + 1) % 8\n character_move()\n\n delay(0.01)\n\nclose_canvas()\n","sub_path":"Drill-04(키보드로 이동하기)/Drill04-2.py","file_name":"Drill04-2.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"342167391","text":"#!/usr/bin/env python3\n\nfrom __future__ import annotations\n\nimport asyncio\nimport datetime\nimport multiprocessing\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nfrom enum import Enum\nfrom functools import wraps\nfrom pathlib import Path\nfrom typing import (\n TYPE_CHECKING,\n Awaitable,\n Callable,\n Iterable,\n List,\n Mapping,\n Optional,\n TypeVar,\n Union,\n cast,\n)\n\n# import autoimport\nimport isort\nimport setuptools # type: ignore\nimport toml # type: ignore\nimport typer\nfrom charmonium.async_subprocess import run\nfrom termcolor import cprint # type: ignore\nfrom typing_extensions import ParamSpec\n\nParams = ParamSpec(\"Params\")\nReturn = TypeVar(\"Return\")\n\n\ndef coroutine_to_function(\n coroutine: Callable[Params, Awaitable[Return]]\n) -> Callable[Params, Return]:\n @wraps(coroutine)\n def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> Return:\n return asyncio.run(coroutine(*args, **kwargs)) # type: ignore\n\n return wrapper\n\n\nif TYPE_CHECKING:\n CompletedProc = subprocess.CompletedProcess[str]\nelse:\n CompletedProc = object\n\n\ndef default_checker(proc: CompletedProc) -> bool:\n return proc.returncode == 0\n\n\nasync def pretty_run(\n cmd: List[Union[Path, str]],\n checker: Callable[[CompletedProc], bool] = default_checker,\n env_override: Optional[Mapping[str, str]] = None,\n) -> CompletedProc:\n start = datetime.datetime.now()\n proc = await run(\n cmd, capture_output=True, text=True, check=False, env_override=env_override\n )\n proc = cast(CompletedProc, proc)\n stop = datetime.datetime.now()\n delta = stop - start\n success = checker(proc)\n color = \"green\" if success else \"red\"\n if sys.version_info >= (3, 8):\n cmd_str = shlex.join(map(str, cmd))\n else:\n cmd_str = \" \".join(map(str, cmd))\n cprint(\n f\"$ {cmd_str}\\nexited with status {proc.returncode} in {delta.total_seconds():.1f}s\",\n color,\n )\n if proc.stdout:\n print(proc.stdout)\n if proc.stderr:\n print(proc.stderr)\n if not success:\n raise typer.Exit(code=1)\n return proc\n\n\ndef most_recent_common_ancestor(packages: List[str]) -> str:\n common_ancestor = packages[0].split(\".\")\n for package in packages:\n new_common_ancestor = []\n for seg1, seg2 in zip(common_ancestor, package.split(\".\")):\n if seg1 != seg2:\n break\n new_common_ancestor.append(seg1)\n common_ancestor = new_common_ancestor\n return \".\".join(common_ancestor)\n\n\ndef get_package_path(package: str) -> Path:\n return Path().joinpath(*package.split(\".\"))\n\n\napp = typer.Typer()\ntests_dir = Path(\"tests\")\npyproject = toml.loads(Path(\"pyproject.toml\").read_text())\nextra_packages = [\n obj[\"include\"] for obj in pyproject[\"tool\"][\"poetry\"].get(\"packages\", [])\n]\nsrc_packages = setuptools.find_packages() + extra_packages\nmain_package = most_recent_common_ancestor(src_packages)\nassert main_package, f\"No common ancestor of {src_packages}\"\nmain_package_dir = get_package_path(main_package)\ndocsrc_dir = Path(\"docsrc\")\nbuild_dir = Path(\"build\")\nall_python_files = list(\n {\n *tests_dir.rglob(\"*.py\"),\n *main_package_dir.rglob(\"*.py\"),\n Path(\"script.py\"),\n # docsrc_dir / \"conf.py\",\n }\n)\n\n\ndef autoimport_and_isort(path: Path) -> None:\n orig_code = path.read_text()\n code = orig_code\n # code = autoimport.fix_code(orig_code)\n code = isort.code(code)\n # if hash(code) != hash(orig_code):\n # path.write_text(code)\n path.write_text(code)\n\n\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n\n\n@app.command()\n@coroutine_to_function\nasync def fmt(parallel: bool = True) -> None:\n with multiprocessing.Pool() as pool:\n mapper = cast(\n Callable[[Callable[[_T1], _T2], Iterable[_T1]], Iterable[_T2]],\n pool.imap_unordered if parallel else map,\n )\n list(mapper(autoimport_and_isort, all_python_files))\n await pretty_run([\"black\", \"--quiet\", *all_python_files])\n\n\n@app.command()\n@coroutine_to_function\nasync def test() -> None:\n await asyncio.gather(\n pretty_run(\n [\n \"mypy\",\n # \"dmypy\",\n # \"run\",\n # \"--\",\n \"--explicit-package-bases\",\n \"--namespace-packages\",\n *all_python_files,\n ],\n env_override={\"MYPY_FORCE_COLOR\": \"1\"},\n ),\n pretty_run(\n [\n \"pylint\",\n \"-j\",\n \"0\",\n \"--output-format\",\n \"colorized\",\n \"--score=y\",\n *all_python_files,\n ],\n # see https://pylint.pycqa.org/en/latest/user_guide/run.html#exit-codes\n checker=lambda proc: proc.returncode & (1 | 2) == 0,\n ),\n pytest(use_coverage=False, show_slow=True),\n pretty_run(\n [\n \"radon\",\n \"cc\",\n \"--min\",\n \"b\",\n \"--show-complexity\",\n \"--no-assert\",\n main_package_dir,\n tests_dir,\n ]\n ),\n pretty_run(\n [\n \"radon\",\n \"mi\",\n \"--min\",\n \"b\",\n \"--show\",\n \"--sort\",\n main_package_dir,\n tests_dir,\n ]\n ),\n )\n\n\n@app.command()\n@coroutine_to_function\nasync def per_env_tests() -> None:\n await asyncio.gather(\n pretty_run(\n # No daemon\n [\n \"mypy\",\n \"--explicit-package-bases\",\n \"--namespace-packages\",\n *map(str, all_python_files),\n ],\n env_override={\"MYPY_FORCE_COLOR\": \"1\"},\n ),\n pytest(use_coverage=False, show_slow=False),\n )\n\n\n@app.command()\n@coroutine_to_function\nasync def docs() -> None:\n await docs_inner()\n\n\nasync def docs_inner() -> None:\n await asyncio.gather(\n *(\n [pretty_run([\"sphinx-build\", \"-W\", \"-b\", \"html\", docsrc_dir, \"docs\"])]\n if docsrc_dir.exists()\n else []\n ),\n # pretty_run(\n # [\n # \"proselint\",\n # \"README.rst\",\n # *docsrc_dir.glob(\"*.rst\"),\n # ]\n # ),\n )\n if docsrc_dir.exists():\n print(f\"See docs in: file://{(Path() / 'docs' / 'index.html').resolve()}\")\n\n\n@app.command()\n@coroutine_to_function\nasync def all_tests(interactive: bool = True) -> None:\n await all_tests_inner(interactive)\n\n\nasync def all_tests_inner(interactive: bool) -> None:\n async def poetry_build() -> None:\n dist = Path(\"dist\")\n if dist.exists():\n shutil.rmtree(dist)\n # await pretty_run([\"rstcheck\", \"README.rst\"])\n await pretty_run([\"poetry\", \"build\", \"--quiet\"])\n await pretty_run([\"twine\", \"check\", \"--strict\", *dist.iterdir()])\n shutil.rmtree(dist)\n\n await asyncio.gather(\n poetry_build(),\n # docs_inner(),\n pytest(use_coverage=False, show_slow=False),\n )\n # Tox already has its own parallelism,\n # and it shows a nice stateus spinner.\n # so I'll not `await pretty_run`\n subprocess.run(\n [\"tox\", \"--parallel\", \"auto\"],\n env={\n **os.environ,\n \"PY_COLORS\": \"1\",\n \"TOX_PARALLEL_NO_SPINNER\": \"\" if interactive else \"1\",\n },\n check=True,\n )\n\n\nasync def pytest(use_coverage: bool, show_slow: bool) -> None:\n cache_path = Path(\".cache\")\n # TODO: Find a workaround for this.\n # The doctest in README expects that `.cache` does not exist, and then pollutes it.\n # Running the tests twice would fail the second time.\n # I am hesitant to add more code to the README doctest, because I want to keep the README as simple as possible.\n if cache_path.exists():\n shutil.rmtree(cache_path)\n\n if tests_dir.exists():\n await pretty_run(\n [\n \"pytest\",\n \"--exitfirst\",\n *([\"--durations=3\"] if show_slow else []),\n *([f\"--cov={main_package_dir!s}\"] if use_coverage else []),\n ],\n checker=lambda proc: proc.returncode in {0, 5},\n )\n if use_coverage:\n await pretty_run([\"coverage\", \"html\"])\n report_dir = Path(pyproject[\"tool\"][\"coverage\"][\"html\"][\"directory\"])\n print(\n f\"See code coverage in: file://{(report_dir / 'index.html').resolve()}\"\n )\n\n\nclass VersionPart(str, Enum):\n PATCH = \"patch\"\n MINOR = \"minor\"\n MAJOR = \"major\"\n\n\nT = TypeVar(\"T\")\n\n\ndef flatten1(seq: Iterable[Iterable[T]]) -> Iterable[T]:\n return (item2 for item1 in seq for item2 in item1)\n\n\ndef dct_to_args(dct: Mapping[str, Union[bool, int, float, str]]) -> List[str]:\n def inner() -> Iterable[List[str]]:\n for key, val in dct.items():\n key = key.replace(\"_\", \"-\")\n if isinstance(val, bool):\n modifier = \"\" if val else \"no-\"\n yield [f\"--{modifier}{key}\"]\n else:\n yield [f\"--{key}\", str(val)]\n\n return list(flatten1(inner()))\n\n\n@app.command()\ndef publish(\n version_part: VersionPart,\n verify: bool = True,\n build_docs: bool = True,\n bump: bool = True,\n) -> None:\n if verify:\n asyncio.run(all_tests_inner(True))\n elif build_docs:\n # verify => all_tests_inner => docs already.\n # This is only need for the case where (not verify and docs).\n asyncio.run(docs_inner())\n if bump:\n subprocess.run(\n [\n \"bump2version\",\n *dct_to_args(pyproject[\"tool\"][\"bump2version\"]),\n \"--current-version\",\n pyproject[\"tool\"][\"poetry\"][\"version\"],\n version_part.value,\n \"pyproject.toml\",\n \"charmonium/cache/memoize.py\",\n ],\n check=True,\n )\n subprocess.run(\n [\"poetry\", \"publish\", \"--build\"],\n check=True,\n )\n shutil.rmtree(\"dist\")\n subprocess.run([\"git\", \"push\", \"--tags\"], check=True)\n # TODO: publish docs\n\n\nif __name__ == \"__main__\":\n app()\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":10293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553064097","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom Aprendiendo.apps.home.models import Producto\nfrom Aprendiendo.apps.home.forms import ProductoForm\n# Create your views here.\n\n\ndef AgregarProductoView(request):\n msg='Ingrese sus datos'\n if request.method=='POST':\n formProducto=ProductoForm(request.POST)\n if formProducto.is_valid():\n Name=formProducto.cleaned_data['Name']\n Description=formProducto.cleaned_data['Description']\n Category=formProducto.cleaned_data['Category']\n\n productoModel=Producto()\n productoModel.Name=Name\n productoModel.Description=Description\n productoModel.Category=Category\n productoModel.save()\n msg='El producto fue guardado'\n else:\n msg='Los datos son incorrectos'\n formProducto=ProductoForm()\n ctx={'formProducto':formProducto,'msg':msg}\n return render_to_response('templates/home.html',ctx,context_instance=RequestContext(request))\n","sub_path":"Aprendiendo/Aprendiendo/apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508577467","text":"# File: Nim.py\n\n# Description: Program that allows us to find the winning move in the game nim sum\n\n# Student's Name: Joonsung Ha\n\n# Student's UT EID: jh69256\n# Partner's Name: Laurence Wang\n\n# Partner's UT EID: lnw653\n\n# Course Name: CS 313E \n\n# Unique Number: 50305\n\n# Date Created: 1/26/20\n\n# Date Last Modified:\n\n# Input: heaps is a list of integers giving the count in each heap\n# Output: function returns a single integer which is the nim-sum\ndef nim_sum (heaps):\n\n\n #this changes the elements in the list into integers\n for i in range(len(heaps)):\n into_int = int(heaps[i])\n heaps[i] = into_int\n\n #this returns binary\n for i in range(len(heaps)):\n into_binary = bin(heaps[i])\n heaps[i] = into_binary\n\n\n copy_heap = heaps\n\n\n #this lets me compare two heaps at a time and eventually find the nim_sum\n for i in range(len(heaps)-1):\n \n value = get_nim_sum(heaps[i],heaps[i+1])\n heaps[i+1] = value\n\n\n #get_nim_sum(heaps[i],heaps[i+1])\n print(\"VALUE\",value)\n\n\n #now this is to get xor for each individual heap\n individual_nim_sum_lst = []\n for i in range(len(copy_heap)):\n individual_nim_sum = get_nim_sum(value,copy_heap[i])\n individual_nim_sum_lst.append(individual_nim_sum)\n\n\n print(individual_nim_sum_lst)\n\n\n\n #now we have to compare each heap with nim_sum value and if the individual nim_sum value is less than the heap then thats the one\n \n\n\n\n\n \n return 0\n# placeholder for the actual return statement\n\n# Input: heaps is a list of integers giving the count in each heap\n# nim_sum is an integer \n# Output: function returns two integers. The first integer is number\n# of counters that has to be removed. The second integer is\n# the number of the heap from which the counters are removed.\n# If the nim_sum is 0, then return 0, 0\n\n\ndef get_nim_sum(heap1, heap2):\n\n nim_sum_value_non_binary = int(heap1,2) ^ int(heap2,2)\n nim_sum_value_binary = '{0:b}'.format(nim_sum_value_non_binary)\n\n \n return nim_sum_value_binary\n\n\n\n\n\ndef find_heap (heaps, nim_sum):\n\n\n \n return 0, 0\t\t# placeholder for the actual return statement\n\n\n\n\n\n\ndef main():\n # read input from input file nim.txt\n data = open(\"nim.txt\",\"r\")\n\n num_trials = data.readline()\n\n if num_trials == \"\":\n print(\"Lose Game\")\n\n else:\n num_trials = int(num_trials)\n\n\n for i in range(num_trials):\n #gets each line of data from the textfile\n line = data.readline()\n\n #gets rid of the \\n and the end\n line = line.strip()\n\n #makes the string into a list\n #elements in the list are all strings right now\n x = line.split(\" \")\n #print(x)\n #print(type(x))\n nim_sum(x)\n #print(\"DONE WITH ONE\")\n\n\n # call function nim_sum() with inputs as given\n\n # call function find_heap() with inputs as given\n\n # print the results\n\n\n\n# The line above main is for grading purposes only.\n# DO NOT REMOVE THE LINE ABOVE MAIN\nif __name__ == \"__main__\":\n main()\n","sub_path":"Nim.py","file_name":"Nim.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"136358201","text":"#!/usr/bin/env python\n\n# instantiates listeners for y and y_hat.\n# get latest values, creates list and with a service call, calculates the cf\n\nimport rospy\nimport os\nfrom std_msgs.msg import String\nimport std_srvs.srv\n\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport time\n#from sklearn import svm, datasets\n#from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\nclass Cfer():\n def __init__(self):\n self.cffile = os.path.expanduser(rospy.get_param('~cflistfile','~/myfule.txt'))\n self.y_hat_topic = rospy.get_param('~y_hat_topic','/subject/action')\n self.y_topic = rospy.get_param('~y_topic','/subject/action')\n self.done_topic = rospy.get_param('~done_topic','')\n self.classes = eval(rospy.get_param('~classes','[\"something\",\"something_else\"]')) ### will get evaluated. this is a possible security issue!\n rospy.loginfo('Cfer initialized')\n self.cnf_matrix = None\n assert type(self.classes) == list\n rate_value = rospy.get_param('~rate',5)\n self.rate = rospy.Rate(rate_value)\n self.yhs = rospy.Subscriber(self.y_hat_topic, String, self.callback_yhat_update)\n self.ys = rospy.Subscriber(self.y_topic, String, self.callback_y_update)\n self.ds = rospy.Subscriber(self.done_topic, String, self.callback_done)\n self.ss = rospy.Service('show_cf', std_srvs.srv.Empty,self.calccf)\n self.ylist = []\n self.yhatlist = []\n self.curry = None\n self.curry_hat = None\n self.lastdata = 0\n #### registers a service to calculate the confusion matrix of what it has so far?\n def __del__(self):\n self.yhs.unregister()\n self.ys.unregister()\n self.ds.unregister()\n self.ss.shutdown('cfer object deleted by service call')\n rospy.loginfo('Cfer finished deleting itself!')\n # rospy.spin()\n def callback_done(self, data):\n #print(data.data)\n if data.data == '1' and self.lastdata == '1':\n #self.calccf(None)\n rospy.logwarn_throttle(60, 'I''m done. Should print cf once and then either exit or clear cf(?)')\n self.lastdata = data.data\n def callback_y_update(self, data):\n rospy.logdebug(rospy.get_caller_id() + \": I heard %s from y_topic\", data.data )\n self.curry = data.data\n def callback_yhat_update(self, data):\n rospy.logdebug(rospy.get_caller_id() + \": I heard %s from y_hat_topic\", data.data )\n self.curry_hat = data.data\n def append_y_yhat(self):\n ## makes sure that they are the same length, even if they are published at different time intervals\n rospy.logdebug(rospy.get_caller_id() + \": I am pushing into lists: %s ; %s\", self.curry,self.curry_hat )\n self.ylist.append(self.curry)\n self.yhatlist.append(self.curry_hat)\n def calccf(self, req):\n #first save for posterity\n with open(self.cffile+'_y'+str(time.time())+'.txt','w') as f:\n for i in range(0,len(self.ylist)):\n f.write(\"%s\\n\" %self.ylist[i])\n with open(self.cffile+'_yhat'+str(time.time())+'.txt','w') as f:\n for i in range(0,len(self.yhatlist)):\n f.write(\"%s\\n\" %self.yhatlist[i])\n\n\n ### This maybe is slow, so I need to make sure it is non-blocking\n ### right now does nothing.\n rospy.loginfo('erm, calculate confusion matrix!')\n y_pred = np.array(self.yhatlist)\n y_test = np.array(self.ylist)\n for i in range(0,len(y_test)):\n if y_test[i] == None:\n y_test[i] = \"unknown\"\n if y_pred[i] == None:\n y_pred[i] = \"unknown\"\n print(\"ypred:\")\n print(y_pred)\n print(\"ytest:\")\n print(y_test)\n self.cnf_matrix = confusion_matrix(y_test, y_pred, labels=self.classes)\n\n return []\n\nclass Cfer_wrap():\n def __init__(self):\n rospy.init_node('cfer', anonymous=True)\n self.initsrv = rospy.Service('init_cfer', std_srvs.srv.Empty,self.initcf)\n self.delsrv = rospy.Service('del_cfer', std_srvs.srv.Empty,self.clearcf)\n self.mycfer = None\n def initcf(self,req):\n if self.mycfer:\n rospy.logwarn(dir(self.mycfer))\n rospy.logwarn(type(self.mycfer))\n rospy.logwarn('cfer already initialized. will start new instance, but results may not be accurate!')\n self.mycfer = Cfer()\n assert self.mycfer.cnf_matrix is None\n rospy.loginfo('new Cfer instantiated')\n return []\n\n def clearcf(self,req):\n #del(self.mycfer)\n self.mycfer.__del__() ### delete, delete delete!!!\n self.mycfer = None\n assert self.mycfer is None\n rospy.loginfo('Cfer deleted and set to None')\n return []\n\nif __name__ == '__main__':\n try:\n cferwrap = Cfer_wrap()\n # r= rospy.Rate(20)\n\n while not rospy.is_shutdown():\n if cferwrap.mycfer:\n assert cferwrap.mycfer is not None\n if cferwrap.mycfer.cnf_matrix is not None:\n rospy.loginfo('Cfn_matrix ready and prepared to be displayed')\n np.set_printoptions(precision=2)\n # Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cferwrap.mycfer.cnf_matrix, classes=cferwrap.mycfer.classes, title='Confusion matrix, without normalization')\n # Plot normalized confusion matrix\n #plt.figure()\n #plot_confusion_matrix(cnf_matrix, classes=self.classes, normalize=True,\n # title='Normalized confusion matrix')\n plt.show()\n cferwrap.mycfer.cnf_matrix = None\n rospy.loginfo('Cfn_matrix ready and prepared to be displayed')\n # else:\n # r.sleep()\n # #mycfer.calccf()\n cferwrap.mycfer.append_y_yhat()\n cferwrap.mycfer.rate.sleep()\n #rospy.spin()\n\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/cfer_show.py","file_name":"cfer_show.py","file_ext":"py","file_size_in_byte":7312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"477416414","text":"import schedule\r\nimport time\r\nimport datetime\r\nimport pymysql\r\n\r\n\r\nfrom Common.config_coordinator import config_fetcher\r\n\r\nmysql_config = config_fetcher.get_mysql_config\r\n\r\ndef getConnection():\r\n db = pymysql.connect(host=mysql_config['HOST'],\r\n user=mysql_config['USER'],\r\n passwd=mysql_config['PASSWORD'],\r\n db=mysql_config['DB'])\r\n cur = db.cursor()\r\n return cur\r\n\r\n# database connection\r\n\r\n\r\ndef getRequest():\r\n cur = getConnection()\r\n sql = \"SELECT * FROM scheduler.ScheduleDetails where date_format(scheduleDateTime,'%Y-%m-%d') = curdate() and scheduleStatus = 'Not Started'\"\r\n cur.execute(sql)\r\n obj_list = cur.fetchall()\r\n\r\n current_date = datetime.datetime.now()\r\n print(current_date)\r\n for row in obj_list:\r\n if current_date.strftime(\"%Y-%M-%d %H:%M\") == row[2].strftime(\"%Y-%M-%d %H:%M\"):\r\n print(row[2])\r\n\r\n # with open(\"testing.txt\", 'wb+') as fp:\r\n # fp.write(\"date is \" + str(row[2]))\r\n\r\n\r\nschedule.every().minutes.do(getRequest)\r\n\r\nwhile 1:\r\n schedule.run_pending()\r\n time.sleep(1)\r\n# getRequest()","sub_path":"eCube_Hotel_2/Services/Common/Scheduler.py","file_name":"Scheduler.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"466339067","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nMutual information and conditional mutual information between time series: script implementing\nthe TMI and CTMI methods.\n\nDate: Dec 2019\nAuthor: Karim Assaad, karimassaad3@gmail.com, karim.assaad@univ.grenoble.alpes.fr, karim.assaad@coservit.com\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport math\n\nfrom baselines.scripts_python.python_packages.ACITMI.tigramite.tigramite.independence_tests import CMIknn\nfrom baselines.scripts_python.python_packages.ACITMI.tigramite.tigramite.independence_tests import ParCorr\n\n\ndef indep_test(x, y, z=None, sig_samples=10000, p_value=True, measure=\"cmiknn\", k=10, test_indep= True):\n if measure == \"cmiknn\":\n cd = CMIknn(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, knn=k, confidence='bootstrap', conf_lev=0.9, conf_samples=10000,\n conf_blocklength=1, verbosity=0)\n elif measure == \"parcorr\":\n cd = ParCorr(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, confidence='bootstrap', conf_lev=0.9, conf_samples=10000, conf_blocklength=1,\n verbosity=0)\n else:\n cd = None\n print(\"Independence measure '\" + str(measure) + \"' do not exist.\")\n exit(0)\n dim_x = x.shape[1]\n dim_y = y.shape[1]\n\n # ws_xy = max(x.shape[1], x.shape[1])\n # ws_xy = 5\n ws_xy = 1\n if z is not None:\n # todo validate\n x_past = x[:-ws_xy]\n y_past = y[:-ws_xy]\n\n # x_past = x[:-1]\n # y_past = y[:-1]\n # x_past = window_representation(x_past[x_past.columns[0]], ws_xy)\n # y_past = window_representation(y_past[y_past.columns[0]], ws_xy)\n x = x[ws_xy:].reset_index(drop=True)\n y = y[ws_xy:].reset_index(drop=True)\n z = z[ws_xy:].reset_index(drop=True)\n\n x_past = x_past[x_past.columns[0]]\n y_past = y_past[y_past.columns[0]]\n\n z = pd.concat([z, x_past, y_past], axis=1)\n # z = pd.concat([z, y_past], axis=1)\n\n dim_z = z.shape[1]\n X = np.concatenate((x.values, y.values, z.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y + [2] * dim_z)\n else:\n # todo validate\n x_past = x[:-ws_xy]\n y_past = y[:-ws_xy]\n\n # x_past = x[:-1]\n # y_past = y[:-1]\n # x_past = window_representation(x_past[x_past.columns[0]], ws_xy)\n # y_past = window_representation(y_past[y_past.columns[0]], ws_xy)\n x = x[ws_xy:].reset_index(drop=True)\n y = y[ws_xy:].reset_index(drop=True)\n\n x_past = x_past[x_past.columns[0]]\n y_past = y_past[y_past.columns[0]]\n\n z = pd.concat([x_past, y_past], axis=1)\n # z = y_past.to_frame()\n # print(x)\n # print(x_past)\n # print(\"ssssssssssssssssssss\")\n dim_z = z.shape[1]\n X = np.concatenate((x.values, y.values, z.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y + [2] * dim_z)\n\n value = cd.get_dependence_measure(X.T, xyz)\n if p_value:\n pvalue = cd.get_shuffle_significance(X.T, xyz, value)\n else:\n pvalue = value\n return pvalue, value\n # return value\n\n\ndef indep_test_past(x, z=None, sig_samples=10000, p_value=True, measure=\"cmiknn\", k=10, test_indep= True):\n if measure == \"cmiknn\":\n cd = CMIknn(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, knn=k, confidence='bootstrap', conf_lev=0.9, conf_samples=10000,\n conf_blocklength=1, verbosity=0)\n elif measure == \"parcorr\":\n cd = ParCorr(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, confidence='bootstrap', conf_lev=0.9, conf_samples=10000, conf_blocklength=1,\n verbosity=0)\n else:\n cd = None\n print(\"Independence measure '\" + str(measure) + \"' do not exist.\")\n exit(0)\n dim_x = x.shape[1]\n\n ws_xy = 5\n x_past = x[:-ws_xy]\n x = x[ws_xy:].reset_index(drop=True)\n if z is not None:\n z = z[ws_xy:].reset_index(drop=True)\n\n dim_z = z.shape[1]\n X = np.concatenate((x.values, x_past.values, z.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y + [2] * dim_z)\n else:\n\n X = np.concatenate((x.values, y.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y)\n\n value = cd.get_dependence_measure(X.T, xyz)\n if p_value:\n pvalue = cd.get_shuffle_significance(X.T, xyz, value)\n else:\n pvalue = value\n return pvalue, value\n\n\n\ndef indep_test_simple(x, y, z=None, sig_samples=10000, p_value=True, measure=\"cmiknn\", k=10, test_indep= True):\n if measure == \"cmiknn\":\n cd = CMIknn(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, knn=k, confidence='bootstrap', conf_lev=0.9, conf_samples=10000,\n conf_blocklength=1, verbosity=0)\n elif measure == \"parcorr\":\n cd = ParCorr(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=sig_samples,\n sig_blocklength=3, confidence='bootstrap', conf_lev=0.9, conf_samples=10000, conf_blocklength=1,\n verbosity=0)\n else:\n cd = None\n print(\"Independence measure '\" + str(measure) + \"' do not exist.\")\n exit(0)\n dim_x = x.shape[1]\n dim_y = y.shape[1]\n\n if z is not None:\n dim_z = z.shape[1]\n X = np.concatenate((x.values, y.values, z.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y + [2] * dim_z)\n else:\n X = np.concatenate((x.values, y.values), axis=1)\n xyz = np.array([0] * dim_x + [1] * dim_y)\n\n value = cd.get_dependence_measure(X.T, xyz)\n if p_value:\n pvalue = cd.get_shuffle_significance(X.T, xyz, value)\n else:\n pvalue = value\n return pvalue, value\n # return value\n\n\ndef get_shuffle_significance_dependence(ci, array, xyz, value, return_null_dist=False):\n \"\"\"Returns p-value for shuffle significance test.\n\n For residual-based test statistics only the residuals are shuffled.\n\n Parameters\n ----------\n array : array-like\n data array with X, Y, Z in rows and observations in columns\n\n xyz : array of ints\n XYZ identifier array of shape (dim,).\n\n value : number\n Value of test statistic for unshuffled estimate.\n\n Returns\n -------\n pval : float\n p-value\n \"\"\"\n def get_single_residuals(array, target_var,\n standardize=True,\n return_means=False):\n \"\"\"Returns residuals of linear multiple regression.\n\n Performs a OLS regression of the variable indexed by target_var on the\n conditions Z. Here array is assumed to contain X and Y as the first two\n rows with the remaining rows (if present) containing the conditions Z.\n Optionally returns the estimated regression line.\n\n Parameters\n ----------\n array : array-like\n data array with X, Y, Z in rows and observations in columns\n\n target_var : {0, 1}\n Variable to regress out conditions from.\n\n standardize : bool, optional (default: True)\n Whether to standardize the array beforehand. Must be used for\n partial correlation.\n\n return_means : bool, optional (default: False)\n Whether to return the estimated regression line.\n\n Returns\n -------\n resid [, mean] : array-like\n The residual of the regression and optionally the estimated line.\n \"\"\"\n\n dim, T = array.shape\n dim_z = dim - 2\n\n # Standardize\n if standardize:\n array -= array.mean(axis=1).reshape(dim, 1)\n array /= array.std(axis=1).reshape(dim, 1)\n if np.isnan(array).sum() != 0:\n raise ValueError(\"nans after standardizing, \"\n \"possibly constant array!\")\n\n y = array[target_var, :]\n\n if dim_z > 0:\n z = np.fastCopyAndTranspose(array[2:, :])\n beta_hat = np.linalg.lstsq(z, y, rcond=None)[0]\n mean = np.dot(z, beta_hat)\n resid = y - mean\n else:\n resid = y\n mean = None\n\n if return_means:\n return (resid, mean)\n return resid\n\n cd = CMIknn(mask_type=None, significance='shuffle_test', fixed_thres=None, sig_samples=10000,\n sig_blocklength=3, knn=10, confidence='bootstrap', conf_lev=0.9, conf_samples=10000,\n conf_blocklength=1, verbosity=0)\n\n x_vals = get_single_residuals(array, target_var=0)\n y_vals = get_single_residuals(array, target_var=1)\n array_resid = np.array([x_vals, y_vals])\n xyz_resid = np.array([0, 1])\n\n null_dist = cd._get_shuffle_dist(array_resid, xyz_resid, cd.get_dependence_measure,\n sig_samples=10000,\n sig_blocklength=3,\n verbosity=0)\n\n # test independence or test dependence\n pval = (null_dist < np.abs(value)).mean()\n\n # Adjust p-value for two-sided measures\n # if pval < 1.:\n # pval *= 2.\n\n if return_null_dist:\n return pval, null_dist\n return pval\n\n\ndef get_sampling_rate(ts):\n # index of all non nan values in time series\n idx = np.argwhere(~np.isnan(ts).values)\n if len(idx) == len(ts):\n return True, 1\n # differentiate index, if there's no nan all values should be equal to 1\n diff = np.diff(idx, axis=0)\n udiff = np.unique(diff)\n if (len(udiff) == 1) and (udiff != 1):\n cd_bool = True\n cd_value = int(udiff)\n elif len(udiff) == 2:\n idx = np.argwhere(diff.reshape(-1) > 1)\n diff = diff[idx]\n udiff = np.unique(diff)\n if len(udiff) == 1:\n cd_bool = True\n cd_value = int(udiff)\n else:\n # ???\n cd_bool = False\n cd_value = np.nan\n else:\n # if there is no delay in the time series\n cd_bool = False\n cd_value = np.nan\n return cd_bool, cd_value\n\n\ndef align_cpair(x, y, sampling_rate_tuple=(1, 1), k=10, max_gamma=5, set_numbers=\"Z\"):\n \"\"\"\n :param x:\n :param y:\n :param sampling_rate_tuple:\n :param k:\n :param max_gamma:\n :param set_numbers: \"Z\", \"N\" or \"-N\"\n :return:\n \"\"\"\n c1 = list()\n c2 = list()\n\n _, val = tmi(x, y, sampling_rate_tuple, k=k, p_value=False)\n c1.append(val)\n c2.append(val)\n\n if (set_numbers == \"Z\") or (set_numbers == \"N\"):\n for g in range(1, max_gamma):\n _, val = tmi(x, y, sampling_rate_tuple, k=k, gamma=g, p_value=False)\n c1.append(val)\n\n if (set_numbers == \"Z\") or (set_numbers == \"-N\"):\n for g in range(1, max_gamma):\n _, val = tmi(x, y, sampling_rate_tuple, k=k, gamma=-g, p_value=False)\n c2.append(val)\n\n if np.max(c1) >= np.max(c2):\n g = np.argmax(c1)\n else:\n g = -np.argmax(c2)\n\n return g\n\ndef align_matrix(data_dict, keys, sampling_rates, k=10, max_gamma=5):\n d = len(keys)\n g_matrix = np.zeros([d, d], dtype=int)\n for i in range(d):\n for j in range(i, d):\n if i != j:\n x = data_dict[keys[i]]\n y = data_dict[keys[j]]\n g = align_cpair(x, y, (sampling_rates[keys[i]], sampling_rates[keys[j]]), k=k, max_gamma=max_gamma)\n g_matrix[i, j] = g\n g_matrix[j, i] = -g\n else:\n g = 1\n g_matrix[i, j] = g\n\n return pd.DataFrame(g_matrix, columns=keys, index=keys)\n\n\ndef get_alpha(mts, k=10):\n mi_list = []\n for i in range(mts.shape[1]):\n for t in range(100):\n ts_i = mts[mts.columns[i]].dropna().to_frame()\n ts_j = 0.05*ts_i + 0.95*np.random.randn(ts_i.shape[0], ts_i.shape[1])\n pval, val = tmi(ts_i, ts_j, k=k, p_value=False)\n mi_list.append(val)\n alpha = abs(max(mi_list))\n return alpha\n\n\ndef window_size(ts, alpha, lag_max=5, k=10, p_value=True):\n mi_list = []\n for i in range(3, lag_max + 1):\n wts = window_representation(ts, windows_size=i)\n i_data = wts[wts.columns[0]].to_frame()\n j_data = wts[wts.columns[i - 1]].to_frame()\n c_data = wts[wts.columns[1:i - 1]]\n\n # mi_pval, mi_val = tmi(i_data, j_data, k=k, p_value=False)\n mi_pval, mi_val = indep_test_simple(i_data, j_data, z=c_data, sig_samples=10000, p_value=False)\n if mi_val == np.inf:\n mi_val = 1\n mi_list.append(mi_val)\n\n mi_array = np.array(mi_list)\n\n j = mi_array.argmax()\n if p_value:\n wts = window_representation(ts, windows_size=j + 3)\n i_data = wts[wts.columns[0]].to_frame()\n j_data = wts[wts.columns[j + 2]].to_frame()\n c_data = wts[wts.columns[1:j + 2]]\n\n # mi_pval, mi_val = tmi(i_data, j_data, k=k, p_value=True)\n mi_pval, mi_val = indep_test_simple(i_data, j_data, z=c_data, sig_samples=10000, p_value=True)\n\n if mi_pval <= alpha:\n window = j + 3\n else:\n window = 1\n else:\n if mi_array[j] > alpha:\n window = j + 3\n else:\n window = 1\n\n if window == 1:\n wts = window_representation(ts, windows_size=3)\n i_data = wts[wts.columns[0]].to_frame()\n j_data = wts[wts.columns[1]].to_frame()\n c_data = wts[wts.columns[2]].to_frame()\n _, mi_val1 = indep_test_simple(i_data, j_data, sig_samples=10000, p_value=False)\n _, mi_val2 = indep_test_simple(i_data, j_data, z=c_data, sig_samples=10000, p_value=False)\n # i_data = wts[wts.columns[2]].to_frame()\n # j_data = wts[wts.columns[1]].to_frame()\n # c_data = wts[wts.columns[0]].to_frame()\n # _, mi_val1 = indep_test(i_data, j_data, z=c_data, sig_samples=10000, p_value=False)\n\n print(mi_val2, mi_val1)\n if mi_val2 < mi_val1:\n window = 2\n\n return window\n\n\ndef window_representation(ts, windows_size=4, overlap=True):\n ts = ts.dropna()\n if windows_size == 0:\n return ts.to_frame()\n else:\n ts_windows = pd.DataFrame()\n for i in range(windows_size):\n i_data = ts[i:(ts.shape[0]-windows_size+i+1)].values\n ts_windows.loc[:, str(ts.name)+\"_\"+str(i+1)] = i_data\n if not overlap:\n ts_windows = ts_windows.iloc[::windows_size, :]\n return ts_windows\n\n\ndef get_index_of_aligned_dict(dict_data, keys):\n # check if dict is align\n legnth_list = []\n for name in keys:\n legnth_list.append(dict_data[name].shape[0])\n if legnth_list.count(legnth_list[0]) != len(legnth_list):\n print(\"Error: time series in dict are not aligned\")\n exit(0)\n index_df = pd.DataFrame()\n for name in keys:\n index_df[name] = dict_data[name].index.map(str)\n index_df.insert(0, \"concatenated\", \"id_\")\n index_df[\"concatenated\"] = index_df.sum(axis=1)\n index_df = index_df.set_index('concatenated')\n return index_df.index\n\n\ndef aligned_dict_to_df(dict_data):\n concat_df = pd.DataFrame()\n for name in dict_data.keys():\n if isinstance(dict_data[name], pd.Series):\n dict_data[name] = dict_data[name].to_frame()\n concat_df[dict_data[name].columns] = dict_data[name].reset_index(drop=True)\n return concat_df\n\n\ndef find_gamma_x_y(x, y, sampling_rate_tuple=(1, 1), k=10, max_gamma=5):\n c1 = list()\n c2 = list()\n\n _, val = tmi(x, y, sampling_rate_tuple, k=k, p_value=False)\n c1.append(val)\n c2.append(val)\n\n for g in range(1, max_gamma):\n _, val = tmi(x, y, sampling_rate_tuple, k=k, gamma=g, p_value=False)\n c1.append(val)\n\n for g in range(1, max_gamma):\n _, val = tmi(x, y, sampling_rate_tuple, k=k, gamma=-g, p_value=False)\n c2.append(val)\n if np.max(c1) >= np.max(c2):\n g = np.argmax(c1)\n else:\n g = -np.argmax(c2)\n return g\n\n\ndef find_gamma_x(x, sampling_rate_tuple=(1, 1), k=10, max_gamma=5):\n c1 = list()\n c2 = list()\n\n c = 0\n c1.append(c)\n c2.append(c)\n\n for g in range(1, max_gamma):\n _, val = tmi(x, x, sampling_rate_tuple, k=k, gamma=g, p_value=False)\n c1.append(val)\n\n g = np.argmax(c1)\n return g\n\n\ndef gamma_matrix(data_dict, keys, sampling_rates, k=10, max_gamma=5):\n d = len(keys)\n g_matrix = np.zeros([d, d], dtype=int)\n for i in range(d):\n for j in range(i, d):\n if i != j:\n x = data_dict[keys[i]]\n y = data_dict[keys[j]]\n g = find_gamma_x_y(x, y, (sampling_rates[keys[i]], sampling_rates[keys[j]]), k=k, max_gamma=max_gamma)\n g_matrix[i, j] = g\n g_matrix[j, i] = -g\n else:\n x = data_dict[keys[i]]\n g = find_gamma_x(x, (sampling_rates[keys[i]], sampling_rates[keys[j]]), k=k, max_gamma=max_gamma)\n g_matrix[i, j] = g\n return pd.DataFrame(g_matrix, columns=keys, index=keys)\n\n\ndef tmi(x, y, sampling_rate_tuple=(1, 1), k=10, gamma=0, p_value=True, sig_samples=10000):\n sr1, sr2 = sampling_rate_tuple\n dsr = abs(sr1 - sr2)\n iter1 = (sr1 % sr2)*dsr\n iter2 = (sr2 % sr1)*dsr\n if gamma > 0:\n y = y[gamma:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n x = x[x.index % (iter1+1) == 0]\n y = y[y.index % (iter2+1) == 0]\n\n x = x[:-gamma]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n\n elif gamma < 0:\n x = x[-gamma:]\n y = y.reset_index(drop=True)\n x = x.reset_index(drop=True)\n y = y[y.index % (iter2+1) == 0]\n x = x[x.index % (iter1+1) == 0]\n\n y = y[:gamma]\n y = y.reset_index(drop=True)\n x = x.reset_index(drop=True)\n\n else:\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter2 + 1) == 0]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n\n m = min(x.shape[0], y.shape[0])\n x = x[:m]\n y = y[:m]\n\n if len(x.shape) == 1:\n x = x.to_frame()\n if len(y.shape) == 1:\n y = y.to_frame()\n\n\n mi_pval, mi_val = indep_test(x, y, sig_samples=sig_samples, p_value=p_value, measure=\"cmiknn\", k=k)\n return mi_pval, mi_val\n\n\ndef find_gamma_lambda_x_y(x, y, sampling_rate_tuple=(1, 1), k=10, max_gamma=5):\n c = np.zeros([2*max_gamma - 1, max_gamma -3, max_gamma - 3])\n gamma_list = list(range(-max_gamma+1, max_gamma))\n\n ws_x_list = list(range(1, max_gamma-2))\n ws_y_list = list(range(1, max_gamma-2))\n for idx_g in range(len(gamma_list)):\n for idx_ws_x in range(len(ws_x_list)):\n x_w_rep = window_representation(x, windows_size=ws_x_list[idx_ws_x])\n for idx_ws_y in range(len(ws_y_list)):\n if ws_x_list[idx_ws_x] == ws_y_list[idx_ws_y] == 1:\n y_w_rep = window_representation(y, windows_size=ws_y_list[idx_ws_y])\n g = gamma_list[idx_g]\n if g >= 0:\n _, val = tmi(x_w_rep, y_w_rep, sampling_rate_tuple, k=k, gamma=g, p_value=False)\n else:\n val = 0\n c[idx_g, idx_ws_x, idx_ws_y] = val\n else:\n if ws_x_list[idx_ws_x] != ws_y_list[idx_ws_y]:\n y_w_rep = window_representation(y, windows_size=ws_y_list[idx_ws_y])\n g = gamma_list[idx_g]\n if g >= 0:\n _, val = tmi(x_w_rep, y_w_rep, sampling_rate_tuple, k=k, gamma=g, p_value=False)\n else:\n val = 0\n c[idx_g, idx_ws_x, idx_ws_y] = val\n else:\n c[idx_g, idx_ws_x, idx_ws_y] = 0\n\n idx_g, idx_ws_x, idx_ws_y = np.where(c == np.max(c))\n idx_g= idx_g[0]\n idx_ws_x = idx_ws_x[0]\n idx_ws_y = idx_ws_y[0]\n g = gamma_list[idx_g]\n ws_x = ws_x_list[idx_ws_x]\n ws_y = ws_y_list[idx_ws_y]\n return g, ws_x, ws_y\n\n\ndef gamma_matrix_window_matrix(series, keys, sampling_rates, graph, k=10, max_gamma=5):\n d = len(keys)\n g_matrix = np.zeros([d, d], dtype=int)\n window_matrix = np.zeros([d, d], dtype=int)\n\n for i in range(d):\n for j in range(i, d):\n if i != j:\n x = series[keys[i]]\n y = series[keys[j]]\n if graph[i, j] == 2:\n g, ws_x, ws_y = find_gamma_lambda_x_y(x, y, (sampling_rates[keys[i]], sampling_rates[keys[j]]), k=k, max_gamma=max_gamma)\n g_matrix[i, j] = g\n g_matrix[j, i] = -g\n window_matrix[i, j] = ws_x\n window_matrix[j, i] = ws_y\n else:\n g, ws_y, ws_x = find_gamma_lambda_x_y(y, x, (sampling_rates[keys[j]], sampling_rates[keys[i]]), k=k,\n max_gamma=max_gamma)\n g_matrix[i, j] = -g\n g_matrix[j, i] = g\n window_matrix[i, j] = ws_x\n window_matrix[j, i] = ws_y\n else:\n # x = series[keys[i]]\n # g = find_gamma_x(x, (sampling_rates[keys[i]], sampling_rates[keys[j]]), k=k, max_gamma=max_gamma)\n g_matrix[i, j] = 1\n window_matrix[i, j] = 1\n window_matrix[j, i] = 1\n return pd.DataFrame(g_matrix, columns=keys, index=keys), pd.DataFrame(window_matrix, columns=keys, index=keys)\n\n\ndef align_xy(x, y, gamma, sampling_rate_tuple):\n sr1, sr2 = sampling_rate_tuple\n dsr = abs(sr1 - sr2)\n iter1 = (sr1 % sr2) * dsr\n iter2 = (sr2 % sr1) * dsr\n idx_x = x.index\n idx_y = y.index\n if gamma > 0:\n y = y[gamma:]\n idx_y = idx_y[gamma:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter2 + 1) == 0]\n idx_x = idx_x[x.index]\n idx_y = idx_y[y.index]\n\n x = x[:-gamma]\n idx_x = idx_x[:-gamma]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n\n elif gamma < 0:\n x = x[-gamma:]\n idx_x = idx_x[-gamma:]\n y = y.reset_index(drop=True)\n x = x.reset_index(drop=True)\n y = y[y.index % (iter2 + 1) == 0]\n x = x[x.index % (iter1 + 1) == 0]\n idx_x = idx_x[x.index]\n idx_y = idx_y[y.index]\n\n y = y[:gamma]\n idx_y = idx_y[:gamma]\n y = y.reset_index(drop=True)\n x = x.reset_index(drop=True)\n else:\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter2 + 1) == 0]\n idx_x = idx_x[x.index]\n idx_y = idx_y[y.index]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n\n m = min(x.shape[0], y.shape[0])\n x = x[:m]\n y = y[:m]\n idx_x = idx_x[:m]\n idx_y = idx_y[:m]\n\n if len(x.shape) == 1:\n x = x.to_frame()\n if len(y.shape) == 1:\n y = y.to_frame()\n return x, y, idx_x, idx_y\n\n\ndef find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k, gamma, sig_samples=10000, measure=\"cmiknn\"):\n sr1, sr2 = sampling_rate_tuple\n dsr = abs(sr1 - sr2)\n iter1 = (sr1 % sr2) * dsr\n iter2 = (sr2 % sr1) * dsr\n if gamma > 0:\n z = z[gamma:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n\n x = x[:-gamma]\n y = y[:-gamma]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n\n elif gamma < 0:\n x = x[-gamma:]\n y = y[-gamma:]\n z = z.reset_index(drop=True)\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z[z.index % (iter2 + 1) == 0]\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n\n z = z[:gamma]\n z = z.reset_index(drop=True)\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n\n else:\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n\n m = min(x.shape[0], y.shape[0], z.shape[0])\n x = x[:m]\n y = y[:m]\n z = z[:m]\n\n if len(x.shape) == 1:\n x = x.to_frame()\n if len(y.shape) == 1:\n y = y.to_frame()\n if len(z.shape) == 1:\n z = z.to_frame()\n\n cmi_pval, cmi_val = indep_test(x, y, z=z, sig_samples=sig_samples, p_value=False, measure=measure, k=k)\n return cmi_pval, cmi_val\n\n\ndef find_gamma_xy_z(name_x, name_y, x, y, z, sampling_rate_tuple, k, gamma_matrix, max_gamma=5, measure=\"cmiknn\",\n instantaneous=True):\n gamma_xy = gamma_matrix[name_y].loc[name_x]\n z = z.loc[x.index[0]:]\n\n c1 = list()\n c2 = list()\n\n if instantaneous:\n _, val = find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k=k, gamma=0, measure=measure)\n c1.append(val)\n c2.append(val)\n\n for g in range(1, abs(gamma_xy)):\n _, val = find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k=k, gamma=g, measure=measure)\n c1.append(val)\n\n for g in range(1, max_gamma):\n _, val = find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k=k, gamma=-g, measure=measure)\n c2.append(val)\n else:\n c1.append(1)\n c2.append(1)\n if abs(gamma_xy) >= 1:\n for g in range(1, 2):\n _, val = find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k=k, gamma=g, measure=measure)\n c1.append(val)\n\n for g in range(1, 2):\n _, val = find_gamma_xy_z_util(x, y, z, sampling_rate_tuple, k=k, gamma=-g, measure=measure)\n c2.append(val)\n\n if np.min(c1) <= np.min(c2):\n g = np.argmin(c1)\n else:\n g = -np.argmin(c2)\n\n return g\n\n\ndef align_xyz(name_x, name_y, v_x, v_y, idx_x, idx_y, z, sampling_rate_dict, k, gamma_matrix, instantaneous_dict, graph):\n # names_xy = [*xy.keys()]\n # name_x, name_y = names_xy[0], names_xy[1]\n sampling_rate_tuple = (sampling_rate_dict[name_x], sampling_rate_dict[name_y])\n\n # v_x, v_y, idx_x, idx_y = align_xy(xy[name_x], xy[name_y], g_xy, sampling_rate_tuple)\n\n v_x2 = v_x.copy()\n v_y2 = v_y.copy()\n idx_x2 = idx_x.copy()\n idx_y2 = idx_y.copy()\n\n names_z = [*z.keys()]\n\n v_z = dict()\n v_z2 = dict()\n nz_visted = []\n\n # k = 0\n for nz in names_z:\n graphical_optimization = False\n if graph is not None:\n g_xz = gamma_matrix[nz].loc[name_x]\n g_yz = gamma_matrix[nz].loc[name_y]\n\n graph = pd.DataFrame(graph, columns=gamma_matrix.columns, index=gamma_matrix.columns)\n is_xz_indep = graph[name_x].loc[nz] == 0\n is_yz_indep = graph[name_y].loc[nz] == 0\n\n if (not is_xz_indep) and (is_yz_indep):\n idx_xy = idx_x\n idx_xy2 = idx_x2\n g = g_xz\n # nz_processed = z[nz]\n graphical_optimization = True\n elif (not is_yz_indep) and (is_yz_indep):\n idx_xy = idx_y\n idx_xy2 = idx_y2\n g = g_yz\n # nz_processed = z[nz]\n graphical_optimization = True\n\n if not graphical_optimization:\n if idx_x[0] <= idx_y[0]:\n idx_xy = idx_x\n idx_xy2 = idx_x2\n else:\n idx_xy = idx_y\n idx_xy2 = idx_y2\n\n sampling_rate_tuple_xyz = (max(sampling_rate_tuple), sampling_rate_dict[nz])\n v_x_new = v_x.copy()\n v_y_new = v_y.copy()\n v_x_new.index = idx_xy\n v_y_new.index = idx_xy\n g = find_gamma_xy_z(name_x, name_y, v_x_new, v_y_new, z[nz], sampling_rate_tuple_xyz,\n k, gamma_matrix, max_gamma=5, measure=\"cmiknn\", instantaneous=instantaneous_dict[nz])\n print(\"gamma = \"+str(g))\n nz_processed = z[nz]\n\n xyz_dict = {name_x: v_x, nz: nz_processed}\n xyz_dict[name_x].index = idx_xy\n\n xyz_dict2 = {name_y: v_y2, nz: nz_processed}\n xyz_dict2[name_y].index = idx_xy2\n\n sampling_rate_tuple = (sampling_rate_dict[name_x], sampling_rate_dict[nz])\n\n bool_idx = pd.DataFrame([False] * len(idx_xy), columns=['bool'])\n bool_idx.index = idx_xy\n bool_idx2 = pd.DataFrame([False] * len(idx_xy2), columns=['bool'])\n bool_idx2.index = idx_xy2\n\n v_x, z_processed, idx_x, _ = align_xy(xyz_dict[name_x], xyz_dict[nz], g, sampling_rate_tuple)\n bool_idx.loc[idx_x] = True\n bool_idx = bool_idx['bool'].values\n v_y = v_y[bool_idx]\n idx_y = idx_y[bool_idx]\n\n v_y2, z_processed2, idx_y2, _ = align_xy(xyz_dict2[name_y], xyz_dict[nz], g, sampling_rate_tuple)\n bool_idx2.loc[idx_y2] = True\n bool_idx2 = bool_idx2['bool'].values\n v_x2 = v_x2[bool_idx2]\n idx_x2 = idx_x2[bool_idx2]\n\n for nz_v in nz_visted:\n v_z[nz_v] = v_z[nz_v][bool_idx]\n v_z2[nz_v] = v_z2[nz_v][bool_idx2]\n v_z[nz] = z_processed\n v_z2[nz] = z_processed2\n nz_visted.append(nz)\n\n names_z = [*v_z.keys()]\n names_z2 = [*v_z.keys()]\n\n index_zx = get_index_of_aligned_dict(v_z, names_z)\n index_zy = get_index_of_aligned_dict(v_z2, names_z2)\n\n idx = index_zx.intersection(index_zy)\n if not (len(idx) == len(index_zx) == len(index_zy)):\n print(\"Something is wrong\")\n input(\"enter\")\n ##\n v_x = v_x.reset_index(drop=True)\n v_y = v_y.reset_index(drop=True)\n for nz_v in nz_visted:\n v_z[nz_v] = v_z[nz_v].reset_index(drop=True)\n\n return v_x, v_y, v_z\n\n\ndef ctmi(x, y, z, name_x, name_y, sampling_rate_dict, gamma_matrix, instantaneous_dict, graph=None, p_value=False, k=10, sig_samples=10000):\n sampling_rate_tuple = (sampling_rate_dict[name_x], sampling_rate_dict[name_y])\n g_xy = gamma_matrix[name_y].loc[name_x]\n v_x, v_y, idx_x, idx_y = align_xy(x, y, g_xy, sampling_rate_tuple)\n\n if z:\n v_x, v_y, v_z = align_xyz(name_x, name_y, v_x, v_y, idx_x, idx_y, z, sampling_rate_dict, k, gamma_matrix, instantaneous_dict, graph)\n names_z = [*z.keys()]\n if len(names_z) > 0:\n v_z = aligned_dict_to_df(v_z)\n else:\n v_z = None\n else:\n v_z = None\n\n if len(v_x.shape) == 1:\n v_x = v_x.to_frame()\n if len(v_y.shape) == 1:\n v_y = v_y.to_frame()\n\n cmi_pval, cmi_val = indep_test(v_x, v_y, z=v_z, sig_samples=sig_samples, p_value=p_value, measure=\"cmiknn\", k=k)\n return cmi_pval, cmi_val\n\ndef ctmi_past(x, z, name_x, name_y, sampling_rate_dict, gamma_matrix, instantaneous_dict, graph=None, p_value=False, k=10, sig_samples=10000):\n if z:\n v_x, v_y, v_z = align_xyz(name_x, name_y, v_x, v_y, idx_x, idx_y, z, sampling_rate_dict, k, gamma_matrix, instantaneous_dict, graph)\n names_z = [*z.keys()]\n if len(names_z) > 0:\n v_z = aligned_dict_to_df(v_z)\n else:\n v_z = None\n else:\n v_z = None\n\n if len(v_x.shape) == 1:\n v_x = v_x.to_frame()\n if len(v_y.shape) == 1:\n v_y = v_y.to_frame()\n\n cmi_pval, cmi_val = indep_test_past(v_x, v_y, z=v_z, sig_samples=sig_samples, p_value=p_value, measure=\"cmiknn\", k=k)\n return cmi_pval, cmi_val\n\ndef find_gamma_xz_yz_util(x, y, z, sampling_rate_tuple, k, gamma_xz, gamma_yz, sig_samples=10000, measure=\"cmiknn\"):\n sr1, sr2 = sampling_rate_tuple\n dsr = abs(sr1 - sr2)\n iter1 = (sr1 % sr2) * dsr\n iter2 = (sr2 % sr1) * dsr\n if (gamma_xz != 0) and (gamma_yz != 0):\n gamma = max(gamma_xz, gamma_yz)\n new_gamma_xz = gamma - gamma_xz\n new_gamma_yz = gamma - gamma_yz\n z = z[gamma:]\n if new_gamma_xz != 0:\n x = x[new_gamma_xz:]\n else:\n y = y[new_gamma_yz:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n\n x = x[:-gamma_xz]\n y = y[:-gamma_yz]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n else:\n if gamma_xz != 0:\n z = z[gamma_xz:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n\n x = x[:-gamma_xz]\n y = y[gamma_xz:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n elif gamma_yz != 0:\n z = z[gamma_yz:]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n\n x = x[gamma_yz:]\n y = y[:-gamma_yz]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n else:\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n x = x[x.index % (iter1 + 1) == 0]\n y = y[y.index % (iter1 + 1) == 0]\n z = z[z.index % (iter2 + 1) == 0]\n x = x.reset_index(drop=True)\n y = y.reset_index(drop=True)\n z = z.reset_index(drop=True)\n\n m = min(x.shape[0], y.shape[0], z.shape[0])\n x = x[:m]\n y = y[:m]\n z = z[:m]\n\n if len(x.shape) == 1:\n x = x.to_frame()\n if len(y.shape) == 1:\n y = y.to_frame()\n if len(z.shape) == 1:\n z = z.to_frame()\n\n cmi_pval, cmi_val = indep_test(x, y, z=z, sig_samples=sig_samples, p_value=False, measure=measure, k=k)\n return cmi_pval, cmi_val\n\n\ndef find_gamma_xz_yz(x, y, z, sampling_rate_tuple, k, max_gamma=5, measure=\"cmiknn\"):\n z = z.loc[x.index[0]:]\n\n val_list = list()\n g_xz_list = list()\n g_yz_list = list()\n _, val = find_gamma_xz_yz_util(x, y, z, sampling_rate_tuple, k=k, gamma_xz=0, gamma_yz=0, measure=measure)\n\n for g_xz in range(max_gamma):\n for g_yz in range(max_gamma):\n _, val = find_gamma_xz_yz_util(x, y, z, sampling_rate_tuple, k=k, gamma_xz=g_xz, gamma_yz=g_yz, measure=measure)\n val_list.append(val)\n g_xz_list.append(g_xz)\n g_yz_list.append(g_yz)\n\n idx = np.argmax(val_list)\n g_xz = g_xz_list[idx]\n g_yz = g_yz_list[idx]\n return g_xz, g_yz\n\n\ndef i_ctmi(x, y, z, name_x, name_y, name_z, sampling_rate_dict, p_value=True, k=10, sig_samples=10000, test_indep=False):\n\n v_x = x.copy()\n v_y = y.copy()\n v_z = z.copy()\n\n sampling_rate_tuple_xy = (sampling_rate_dict[name_x], sampling_rate_dict[name_y])\n g_xz, g_yz = find_gamma_xz_yz(x, y, z, sampling_rate_tuple_xy, k, max_gamma=5, measure=\"cmiknn\")\n\n xz_dict = {name_x: v_x, name_z: v_z}\n yz_dict = {name_y: v_y, name_z: v_z}\n\n sampling_rate_tuple_x = (sampling_rate_dict[name_x], sampling_rate_dict[name_z])\n sampling_rate_tuple_y = (sampling_rate_dict[name_y], sampling_rate_dict[name_z])\n\n v_x, z_processed_x, idx_x, idx_z_x = align_xy(xz_dict[name_x], xz_dict[name_z], g_xz, sampling_rate_tuple_x)\n v_y, z_processed_y, idx_y, idx_z_y = align_xy(yz_dict[name_y], yz_dict[name_z], g_yz, sampling_rate_tuple_y)\n\n idx = idx_z_x.intersection(idx_z_y)\n\n bool_idx_x = pd.DataFrame([False] * len(v_x.index), columns=['bool'])\n bool_idx_x.index = idx_z_x\n bool_idx_x.loc[idx] = True\n bool_idx_x = bool_idx_x['bool'].values\n\n bool_idx_y = pd.DataFrame([False] * len(v_y.index), columns=['bool'])\n bool_idx_y.index = idx_z_y\n bool_idx_y.loc[idx] = True\n bool_idx_y = bool_idx_y['bool'].values\n\n v_x = v_x.loc[bool_idx_x]\n v_y = v_y.loc[bool_idx_y]\n v_x = v_x.reset_index(drop=True)\n v_y = v_y.reset_index(drop=True)\n\n bool_idx_z = pd.DataFrame([False] * len(z_processed_x.index), columns=['bool'])\n bool_idx_z.index = idx_z_x\n bool_idx_z.loc[idx] = True\n bool_idx_z = bool_idx_z['bool'].values\n v_z = z_processed_x.loc[bool_idx_z]\n v_z = v_z.reset_index(drop=True)\n\n if len(v_x.shape) == 1:\n v_x = v_x.to_frame()\n if len(v_y.shape) == 1:\n v_y = v_y.to_frame()\n if len(v_z.shape) == 1:\n v_z = v_z.to_frame()\n\n cmi_pval, cmi_val = indep_test(v_x, v_y, z=v_z, sig_samples=sig_samples, p_value=p_value, measure=\"cmiknn\", k=k,\n test_indep=test_indep)\n return cmi_pval, cmi_val\n\n\nif __name__ == \"__main__\":\n path = \"../../../../data/simulated_ts_data/v_structure/data_\"+str(0)+\".csv\"\n data = pd.read_csv(path, delimiter=',', index_col=0)\n data = data.loc[:1000]\n\n data_col0 = data[data.columns[0]]\n data_col1 = data[data.columns[1]]\n data_col2 = data[data.columns[2]]\n\n sampling_rate_dict1 = dict()\n for col in range(data.shape[1]):\n _, s_r1 = get_sampling_rate(data[data.columns[col]])\n sampling_rate_dict1[data.columns[col]] = s_r1\n\n Rando = np.random.normal(0, 1, 1000)\n data_col3 = pd.DataFrame()\n N = 1000\n data_col3[\"Location\"] = np.random.choice(Rando, size=N)\n\n res0 = tmi(data_col0, data_col1, sampling_rate_tuple=(1, 1), k=10, gamma=0, p_value=True, sig_samples=10000)\n print(res0)\n res = i_ctmi(data_col0, data_col1, data_col2, data.columns[0],\n data.columns[1], data.columns[2], sampling_rate_dict1, k=10)\n print(11)\n print(res)\n\n from data.sim_data import generate_fork, generate_v_structure, generate_mediator, generate_diamond\n get_data = {\"fork\": generate_fork, \"v_structure\": generate_v_structure, \"mediator\": generate_mediator,\n \"diamond\": generate_diamond}\n\n #######\n data_name = \"v_structure\"\n scale = False\n #######\n\n order = 1\n n_samples_list = [100, 250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000, 3250, 3500, 3750, 4000,\n 4250, 4500, 4750, 5000, 10000]\n # n_samples_list = [100, 250, 500, 750, 1000, 1250]\n\n main_method = \"i_ctmi\"\n col1 = 0\n col2 = 1\n col3 = 2\n col4 = 2\n\n output = []\n for n_samples in n_samples_list:\n result = []\n for it in range(100):\n print(\"iteration: \"+str(it))\n data = get_data[data_name](n_samples)\n if scale:\n data -= data.min()\n data /= data.max()\n\n if main_method == \"tmi\":\n data_dict1 = dict()\n s_rs1 = []\n s_rs_dict1 = dict()\n\n lags1 = []\n for col in range(data.shape[1]):\n _, s_r = get_sampling_rate(data[data.columns[col]])\n s_rs1.append(s_r)\n s_rs_dict1[data.columns[col]] = s_r\n\n a = get_alpha(data)\n\n for col in range(data.shape[1]):\n lags1.append(window_size(data[data.columns[col]], alpha=a))\n data_dict1[data.columns[col]] = window_representation(data[data.columns[col]],\n windows_size=lags1[col])\n\n print(\"------------------------\")\n am = gamma_matrix(data_dict1, data.columns, s_rs_dict1)\n print(\"alpha: \"+str(a))\n print(am)\n\n data_col1 = data_dict1[data.columns[col1]]\n data_col2 = data_dict1[data.columns[col2]]\n dsr1 = abs(s_rs1[col1] - s_rs1[col2])\n\n res = tmi(data_col1, data_col2, sampling_rate_tuple=(s_rs1[col1], s_rs1[col2]),\n gamma=am[data.columns[col2]].loc[data.columns[col1]])\n print(\"cti: \" + str(res))\n result.append(res)\n elif main_method == \"ctmi\":\n data_dict1 = dict()\n lags1 = []\n s_rs1 = []\n s_rs_dict1 = dict()\n\n for col in range(data.shape[1]):\n _, s_r1 = get_sampling_rate(data[data.columns[col]])\n s_rs1.append(s_r1)\n s_rs_dict1[data.columns[col]] = s_r1\n\n a = get_alpha(data)\n\n for col in range(data.shape[1]):\n lags1.append(window_size(data[data.columns[col]], alpha=a))\n data_dict1[data.columns[col]] = window_representation(data[data.columns[col]],\n windows_size=lags1[col])\n print(\"lags: \"+str(lags1))\n print(\"sampling rates: \"+str(s_rs1))\n print(\"sampling rates dict: \"+str(s_rs_dict1))\n\n print(\"------------------------\")\n am = gamma_matrix(data_dict1, data.columns, s_rs_dict1)\n print(\"gamam matrix: \\n\"+str(am))\n\n data_col1 = data_dict1[data.columns[col1]]\n data_col2 = data_dict1[data.columns[col2]]\n data_col3 = data_dict1[data.columns[col3]]\n data_col4 = data_dict1[data.columns[col4]]\n\n sampling_rate_dict1 = s_rs_dict1\n\n res = ctmi(data_col1, data_col2, {data.columns[col3]: data_col3}, data.columns[col2],\n data.columns[col1],\n sampling_rate_dict1, gamma_matrix=am, k=10)\n print(\"ccti: \" + str(res))\n result.append(res)\n\n elif main_method == \"i_ctmi\":\n data_dict1 = dict()\n lags1 = []\n s_rs1 = []\n s_rs_dict1 = dict()\n\n for col in range(data.shape[1]):\n _, s_r1 = get_sampling_rate(data[data.columns[col]])\n s_rs1.append(s_r1)\n s_rs_dict1[data.columns[col]] = s_r1\n\n a = get_alpha(data)\n\n for col in range(data.shape[1]):\n lags1.append(window_size(data[data.columns[col]], alpha=a))\n data_dict1[data.columns[col]] = window_representation(data[data.columns[col]],\n windows_size=lags1[col])\n print(\"lags: \" + str(lags1))\n print(\"sampling rates: \" + str(s_rs1))\n print(\"sampling rates dict: \" + str(s_rs_dict1))\n\n print(\"------------------------\")\n am = gamma_matrix(data_dict1, data.columns, s_rs_dict1)\n print(\"gamam matrix: \\n\" + str(am))\n\n data_col1 = data_dict1[data.columns[col1]]\n data_col2 = data_dict1[data.columns[col2]]\n data_col3 = data_dict1[data.columns[col3]]\n data_col4 = data_dict1[data.columns[col4]]\n\n sampling_rate_dict1 = s_rs_dict1\n\n res = i_ctmi(data_col1, data_col2, {data.columns[col3]: data_col3}, data.columns[col2],\n data.columns[col1], sampling_rate_dict1, gamma_matrix=am, k=10)\n print(\"ccti: \" + str(res))\n result.append(res)\n\n print(result)\n print(\"result:\")\n print(\"(\"+str(n_samples)+\", \"+str(np.mean(result))+\") +- (\"+str(np.std(result))+\", \"+str(np.std(result))+\")\")\n output.append(\"(\"+str(n_samples)+\", \"+str(np.mean(result))+\") +- (\"+str(np.std(result))+\", \" +\n str(np.std(result))+\")\")\n","sub_path":"baselines/scripts_python/python_packages/ACITMI/ctmi_new.py","file_name":"ctmi_new.py","file_ext":"py","file_size_in_byte":44472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"319335033","text":"#!/usr/local/bin/python3\n# -*- coding:utf-8 -*-\n\nimport requests\nimport re\nimport os\nimport sys\nimport click\nfrom bs4 import BeautifulSoup\n\n\"\"\"\nAuthor:Moyuqiezi\n\"\"\"\n\n\nclass Crawler():\n \"\"\"酷我音乐爬取API\n \"\"\"\n\n # 下载aac文件,基于https://blog.csdn.net/weixin_41796207/article/details/80756995\n def __init__(self):\n self.headers = {\n 'Accept': '*/*',\n 'Accept-Encoding': 'identity;q=1, *;q=0',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',\n 'Connection': 'keep-alive',\n 'Host': 'antiserver.kuwo.cn',\n 'Range': 'bytes=0-',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36',\n 'Referer': 'http://www.kuwo.cn/'\n }\n self.session = requests.session()\n self.download_session = requests.Session()\n\n def request_bs(self, url):\n \"\"\"请求网页 & 解析\n :return BeautifuSoup object\n \"\"\"\n \n r = requests.get(url)\n soup = BeautifulSoup(r.text, \"lxml\")\n return soup\n\n def get_base_number(self, base_url):\n \"\"\"获取歌曲ID和歌曲名\n :params base_url:音乐播放页面url\n return: 歌曲ID\n \"\"\"\n\n base_url = base_url.strip()\n base_number = re.findall(\n r\"(?:http://www.kuwo.cn/yinyue/)(\\d+)(?:\\?*)\", base_url)[0]\n\n return base_number\n\n def get_song_name(self, base_url):\n \"\"\"获取歌曲名\n \"\"\"\n\n soup = self.request_bs(base_url)\n song_name = str(soup.find('p', id=\"lrcName\"))[16:-4]\n return song_name\n\n def get_song_url(self, base_number):\n \"\"\"获取歌曲下载地址\n :params base_number: 音乐ID\n :return: 歌曲下载地址\n \"\"\"\n\n url = \"http://antiserver.kuwo.cn/anti.s?format=aac|mp3&rid=MUSIC_\" + \\\n base_number + \"&type=convert_url&response=res\"\n r = self.session.get(url, headers=self.headers, allow_redirects=False)\n return r.headers['Location']\n\n def get_aac(self, song_url):\n \"\"\"获取到aac文件数据\n :params song_url:歌曲下载地址\n \"\"\"\n\n # 修改请求头\n base_host = re.findall(r\"(?:http://)(.*)\", song_url)[0]\n base_host = base_host.split('/')[0]\n self.headers['Host'] = base_host\n self.headers['Referer'] = song_url\n\n r = self.download_session.get(\n song_url, headers=self.headers, stream=True)\n return r\n\n def save_aac(self, song_url, song_name, folder):\n \"\"\"保存歌曲到本地\n :params songurl: 歌曲下载地址\n :params song_name: 歌曲名字\n :params folder: 保存路径\n \"\"\"\n if not os.path.exists(folder):\n os.makedirs(folder)\n fpath = os.path.join(folder, song_name + '.aac')\n print(fpath)\n if sys.platform == 'win32' or sys.platform == 'cygwin':\n valid_name = re.sub(r'[<>:\"/\\\\|?*]', '', song_name)\n if valid_name != song_name:\n click.echo('{} will be saved as: {}.aac'.format(\n song_name, valid_name))\n # fpath = os.path.join(folder, str(song_num) + '_' + valid_name + '.mp3')\n fpath = os.path.join(folder, valid_name + '.aac')\n\n if not os.path.exists(fpath):\n resp = self.download_session.get(song_url)\n length = int(resp.headers.get('content-length'))\n label = 'Downloading {} {}kb'.format(song_name, int(length/1024))\n\n with click.progressbar(length=length, label=label) as progressbar:\n with open(fpath, 'wb') as song_file:\n for chunk in resp.iter_content(chunk_size=1024):\n if chunk:\n song_file.write(chunk)\n progressbar.update(1024)\n print(\"Downloading {}.aac Done.\".format(song_name))\n\n\nclass Kuwo():\n \"\"\"酷我音乐下载\n \"\"\"\n\n def __init__(self, folder):\n self.crawler = Crawler()\n self.folder = '.' if folder is None else folder\n\n def download_song(self, base_url):\n \"\"\"下载歌曲\n :params base_url: 音乐播放页面url\n # http://www.kuwo.cn/yinyue/512837/\n \"\"\"\n\n song_name = self.crawler.get_song_name(base_url)\n base_number = self.crawler.get_base_number(base_url)\n song_url = self.crawler.get_song_url(base_number)\n self.crawler.save_aac(song_url, song_name, self.folder)\n\n def download_listMusic(self, url):\n \"\"\"下载歌手的歌曲列表\n :params url: 歌手页面url\n # http://www.kuwo.cn/artist/content?name=周杰伦\n \"\"\"\n \n cma = 'http://www.kuwo.cn/artist/contentMusicsAjax?artistId='\n\n # 获取artistid\n soup = self.crawler.request_bs(url)\n artistid = re.findall(\n r'(?:
None:\n cls.url = Conf.TEST_APP_URL.value\n cls.http = HttpRequests(cls.url)\n cls.mysql = Mysql_connet('device')\n cls.mysql.insert_device()\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.mysql.delete_device()\n cls.mysql.close() \n @doc_parameter(Conf.TEST_URL.value,uri)\n def test_add_task_success(self):\n '''获取所有钥匙信息用例:{}{}'''\n params = {\n \"id\": self.mysql.authorize_id,\n \"pageNum\": 1,\n \"pageSize\": 1,\n \"type\": 3,\n \"userId\": self.mysql.user_id\n }\n params = json.dumps(params)\n response = Test_Add_Task.http.post(uri,data=params)\n self.assertEqual(200, response.status_code, '返回非200')\n self.assertEqual(str(0), str(response.json()['code']), '获取所有钥匙信息失败')\n logging_test.log_test()\n logging_test.logging.info(Conf.TEST_URL.value + uri + '-接口返回:' + response.text)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_case/app_test_case/cellar_well_key_controller/test_getTerminalInfo.py","file_name":"test_getTerminalInfo.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"544375962","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\n Author: kun.wang\n Create: 2013-09-04\n'''\nimport sys\nimport math\nimport json\nfrom PyQt4 import QtCore\nfrom PyQt4 import QtGui\n\nfrom core import *\n\nclass AssetTableModel(QtCore.QAbstractTableModel):\n def __init__(self, parent = None):\n super(AssetTableModel, self).__init__(parent)\n self.__assets = []\n self.__headers = ['name', 'asset_name', 'type']\n\n def addAsset(self, asset):\n self.__assets.append(asset)\n\n def addAssets(self, assets):\n for asset in assets:\n self.addAsset(asset)\n\n def clear(self):\n del self.__assets[:]\n\n def rowCount(self, parent):\n return len(self.__assets)\n\n def columnCount(self, parent):\n return len(self.__headers)\n\n def flags(self, index):\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable# | QtCore.Qt.ItemIsEditable\n\n def data(self, index, role):\n row = index.row()\n column = index.column()\n asset = self.__assets[row]\n\n if role == QtCore.Qt.DisplayRole:\n return asset.attribute(self.__headers[column])\n\n if role == QtCore.Qt.EditRole:\n return asset.attribute(self.__headers[column])\n\n def setData(self, index, value, role = QtCore.Qt.EditRole):\n row = index.row()\n column = index.column()\n if role == QtCore.Qt.EditRole:\n self.__assets[row].setAttribute(self.__headers[column], value)\n self.dataChanged.emit(index, index)\n return True\n return False\n\n def headerData(self, section, orientation, role):\n if role == QtCore.Qt.DisplayRole:\n if orientation == QtCore.Qt.Horizontal:\n return self.__headers[section]\n else:\n # return \" %04d \" % section\n return \" \"\n\n def assetItem(self, index):\n return self.__assets[index]\n\n\nclass AssetTreeModel(QtCore.QAbstractItemModel):\n def __init__(self, root = AbstractAsset('/'), parent = None):\n super(AssetTreeModel, self).__init__(parent)\n self._rootAsset = root\n self._headers = ['type', 'QC', 'Load', 'Update']\n\n def setRoot(self, root):\n self._rootAsset = root\n self.reset()\n\n def addAsset(self, parent, asset):\n parent_asset = self.getAsset(parent)\n position = parent_asset.childCount()\n self.beginInsertRows(parent, position, position)\n parent_asset.insertChild(position, asset)\n self.endInsertRows()\n return True\n\n def getAsset(self, index):\n if index.isValid():\n node = index.internalPointer()\n if node:\n return node\n return self._rootAsset\n\n def rowCount(self, parent):\n if not parent.isValid():\n parentNode = self._rootAsset\n else:\n parentNode = parent.internalPointer()\n\n return parentNode.childCount()\n\n def columnCount(self, parent):\n return len(self._headers) + 1\n\n def data(self, index, role):\n node = self.getAsset(index)\n row = index.row()\n column = index.column()\n\n if role == QtCore.Qt.DisplayRole:\n if column == 0:\n return node.name()\n else:\n attrib = self._headers[column - 1]\n return node.attribute(attrib)\n\n if role == QtCore.Qt.BackgroundRole:\n t = node.attribute('type')\n if t == 'group':\n return QtGui.QBrush(QtGui.QColor(210, 210, 210))\n\n def headerData(self, section, orientation, role):\n if role == QtCore.Qt.DisplayRole:\n if section == 0:\n return 'Asset Tree'\n else:\n return self._headers[section - 1]\n\n def flags(self, index):\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable\n\n def parent(self, index):\n node = index.internalPointer()\n parentNode = node.parent()\n if parentNode == self._rootAsset:\n return QtCore.QModelIndex()\n return self.createIndex(parentNode.row(), 0, parentNode)\n\n def index(self, row, column, parent):\n parentNode = self.getAsset(parent)\n\n childItem = parentNode.child(row)\n\n if childItem:\n return self.createIndex(row, column, childItem)\n else:\n return QtCore.QModelIndex()\n\n\n\nclass AssetStatus(object):\n Null = 0\n Unload = 1\n Loaded = 2\n Update = 3\n\n\nclass AssetThumb(QtGui.QWidget):\n \"\"\"\n Use this widget to display asset.\n \"\"\"\n def __init__(self, asset, parent = None):\n super(AssetThumb, self).__init__(parent)\n self.__id = 0\n self.__asset = asset\n self.__thumb = QtGui.QImage()\n\n self.__status = AssetStatus.Null\n self.__selected = False\n self.__hightlight = False\n\n self.__name_font = QtGui.QFont()\n self.__bg_color = QtGui.QColor(50, 50, 50)\n self.__hightlight_olor = QtGui.QColor(255, 255, 255, 100)\n self.__edge_size = 5\n self.__pen_selected = QtGui.QPen(QtGui.QColor(255, 255, 0))\n self.__pen_selected.setWidth(self.__edge_size) \n self.__pen_selected.setJoinStyle(QtCore.Qt.MiterJoin)\n\n self.setToolTip('%s' % self.__asset.name())\n\n def setThumb(self, thumb_file):\n if os.path.isfile(thumb_file):\n self.__thumb.load(QtCore.QString(thumb_file))\n self.repaint()\n return True\n\n def setSelected(self, selected = True):\n self.__selected = selected\n self.repaint()\n\n def setStatus(self, status):\n self.__status = status\n self.repaint()\n\n def drawStatus(self, painter, height):\n p1 = QtCore.QPoint(0, 0)\n p2 = QtCore.QPoint(0, height)\n p3 = QtCore.QPoint(height, 0)\n painter.setPen(QtCore.Qt.NoPen)\n painter.fillRect(0, 0, self.width(), height, QtGui.QColor(40, 40, 40, 40))\n\n if self.__status == AssetStatus.Unload:\n painter.setBrush(QtGui.QBrush(QtGui.QColor(255, 0, 0)))\n elif self.__status == AssetStatus.Loaded:\n painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 255, 0)))\n elif self.__status == AssetStatus.Update:\n painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 0, 255)))\n painter.drawConvexPolygon(p1, p2, p3)\n\n\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n\n name_height = max(self.height() * 0.15, 10)\n name_ty = self.height() - self.__edge_size * 2\n # draw background\n painter.fillRect(self.rect(), self.__bg_color)\n painter.drawImage(self.rect(), self.__thumb)\n # draw __hightlight_olor\n if self.__hightlight and not self.__selected:\n painter.fillRect(self.rect(), self.__hightlight_olor)\n # draw name\n painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255)))\n self.__name_font.setPixelSize(name_height)\n painter.setFont(self.__name_font)\n painter.drawText(self.__edge_size, name_ty, \"%s\" % self.__asset.name())\n \n if self.__status:\n title_height = self.__edge_size + name_height\n self.drawStatus(painter, title_height)\n \n\n # if self.version:\n # version_x = self.width() - self.__edge_size - name_height * 1.5\n # version_y = name_height\n # painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255)))\n # painter.drawText(version_x, version_y, '%s' % self.version)\n\n # draw __selected\n if self.__selected:\n painter.setPen(self.__pen_selected)\n painter.setBrush(QtCore.Qt.NoBrush)\n painter.drawRect(self.__edge_size/2, self.__edge_size/2,\\\n self.width() - self.__edge_size, self.height() - self.__edge_size)\n\n def mouseReleaseEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n self.emit(QtCore.SIGNAL(\"click\"), self.__id)\n\n def mouseDoubleClickEvent(self, event):\n self.emit(QtCore.SIGNAL('doubleClick'))\n\n def enterEvent(self, event):\n self.__hightlight = True\n self.repaint()\n\n def leaveEvent(self, event):\n self.__hightlight = False\n self.repaint()\n\n\n\nclass AssetThumbModel():\n def __init__(self, asset_items = []):\n self.__items = asset_items\n self.__viewer = None\n self.__connection = False\n\n def setViewer(self, viewer):\n self.__viewer = viewer\n for item in self.__items:\n self.__viewer.addItem(item)\n return True\n\n def setConnection(self, connect):\n self.__connection = connect\n\n def reset(self):\n if self.__connection:\n self.__viewer.reView()\n return True\n else:\n return False\n\n def addAsset(self, asset):\n item = AssetThumb(asset)\n self.__items.append(item)\n if self.__connection:\n self.__viewer.addItem(item)\n self.__viewer.reView()\n return True\n\n def addAssets(self, assets):\n for asset in assets:\n item = AssetThumb(asset)\n self.__items.append(item)\n if self.__connection:\n self.__viewer.addItem(item)\n if self.__connection:\n self.__viewer.reView()\n return True\n\n def clear(self):\n for item in self.__items:\n item.setParent(None)\n item.close()\n del self.__items[:]\n return True\n\n\n\n\n\nclass AssetThumbViewer(QtGui.QWidget):\n def __init__(self, parent = None):\n super(AssetThumbViewer, self).__init__(parent)\n self.__scrollarea = QtGui.QScrollArea()\n self.__item_area = QtGui.QWidget()\n self.__scrollarea.setWidget(self.__item_area)\n self.__acpect_raio = 0.618\n self.__item_sizeX = 180\n self.__item_sizeY = self.__item_sizeX * self.__acpect_raio\n self.__item_size_range = [32, 512]\n self.__space = 5\n self.__auto_space = False\n self.__item_area.setWindowOpacity(0.0)\n self.__item_area.resize(self.__item_sizeX, self.__item_sizeY)\n\n self.__main_layout = QtGui.QHBoxLayout()\n self.__main_layout.setContentsMargins(1, 1, 1, 1)\n self.setLayout(self.__main_layout)\n self.addFloatTools()\n self.__main_layout.addWidget(self.__scrollarea)\n\n def addFloatTools(self):\n self.__actSmaller = QtGui.QAction('', self)\n self.__actSmaller.setShortcut(QtGui.QKeySequence(\"[\"))\n self.connect(self.__actSmaller, QtCore.SIGNAL('triggered()'), self.smallerItemSize)\n self.__actBigger = QtGui.QAction('', self)\n self.__actBigger.setShortcut(QtGui.QKeySequence(\"]\"))\n self.connect(self.__actBigger, QtCore.SIGNAL('triggered()'), self.biggerItemSize)\n\n self.__size_slider = QtGui.QSlider()\n self.__size_slider.setOrientation(QtCore.Qt.Vertical)\n self.__size_slider.setMinimum(self.__item_size_range[0])\n self.__size_slider.setMaximum(self.__item_size_range[1])\n self.__size_slider.setValue(self.__item_sizeX)\n self.setItemSize(self.__item_sizeX)\n self.connect(self.__size_slider, QtCore.SIGNAL('valueChanged(int)'), self.setItemSize)\n\n self.__toolbar = QtGui.QToolBar(self)\n self.__toolbar.setOrientation(QtCore.Qt.Vertical)\n self.__toolbar.setIconSize(QtCore.QSize(5, 5))\n self.__toolbar.addAction(self.__actBigger)\n self.__toolbar.addWidget(self.__size_slider)\n self.__toolbar.addAction(self.__actSmaller)\n self.__main_layout.addWidget(self.__toolbar)\n \n def __layout(self):\n w = self.width() - 20\n items = self.__item_area.children()\n\n num_x = max(math.ceil(w / (self.__item_sizeX + self.__space)), 1) # Can do -1\n num_y = math.ceil(len(items) / num_x)\n self.__item_area.resize(w, num_y * (self.__item_sizeY + self.__space) + 50)\n\n main_w = self.__item_area.width()\n main_h = self.__item_area.height()\n num_x = max(math.ceil(main_w / (self.__item_sizeX + self.__space)), 1) # Can do -1\n \n x = 0\n y = 0\n for i in range(len(items)):\n space_x = 0\n if self.__auto_space:\n space_x = (main_w - self.__space * 2 - num_x * (self.__item_sizeX + self.__space)) / num_x\n items[i].move(self.__space * 2 + x * (self.__item_sizeX + self.__space + space_x), \\\n self.__space*2 + y * (self.__item_sizeY + self.__space))\n x += 1\n if x >= num_x:\n x = 0\n y += 1\n\n return True\n\n def addItem(self, item):\n item.setParent(self.__item_area)\n item.resize(self.__item_sizeX, self.__item_sizeY)\n item.show()\n\n def resizeEvent(self, event):\n self.__layout()\n \n def setItemSize(self, size):\n self.__item_sizeX = size\n self.__item_sizeY = size * self.__acpect_raio\n items = self.__item_area.children()\n for a in items:\n a.resize(self.__item_sizeX, self.__item_sizeY)\n self.__layout()\n return True\n\n def smallerItemSize(self):\n self.__size_slider.setValue(self.__size_slider.value() - 2)\n\n def biggerItemSize(self):\n self.__size_slider.setValue(self.__size_slider.value() + 2)\n\n def reView(self):\n self.__layout()\n\n def setModel(self, model):\n model.setConnection(True)\n model.setViewer(self)\n return True\n\n \n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n app.setStyle('cleanlooks')\n\n # asset_tree_view = QtGui.QTreeView()\n # asset_tree_model = AssetTreeModel()\n # asset_tree_view.setModel(asset_tree_model)\n # asset_tree_view.show()\n\n asset_thumb_model = AssetThumbModel()\n for i in range(10):\n asset = Project('Test %03d' % i)\n asset_thumb_model.addAsset(asset)\n\n asset_viewer = AssetThumbViewer()\n asset_viewer.resize(500, 300)\n asset_viewer.setModel(asset_thumb_model)\n asset_viewer.show()\n \n sys.exit(app.exec_())","sub_path":"cgPipeline/old/PAsset0.2/lib/passet/qt_model.py","file_name":"qt_model.py","file_ext":"py","file_size_in_byte":14072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"281350389","text":"from aiofacepy.exceptions import (\n FacebookError,\n FacepyError,\n HTTPError,\n OAuthError,\n SignedRequestError\n)\nfrom aiofacepy.graph_api import GraphAPI\nfrom aiofacepy.signed_request import SignedRequest\nfrom aiofacepy.utils import get_application_access_token, get_extended_access_token\n\n__all__ = [\n 'FacepyError',\n 'FacebookError',\n 'GraphAPI',\n 'HTTPError',\n 'OAuthError',\n 'SignedRequest',\n 'SignedRequestError',\n 'get_application_access_token',\n 'get_extended_access_token',\n]\n","sub_path":"aiofacepy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"595326367","text":"import time\n\nimport numpy as np\n\nfrom base import BaseDataLoader\n\n\nclass ComparisonDataLoader(BaseDataLoader):\n \"\"\"\n Implements all three use cases for HIPSCI NotNeuron:\n 1. Train on lib1, test on lib1\n 2. Train on lib1, test on lib2\n 3. Train on lib1, test on lib from other individual\n 4. Train on lib1, test on lib from other individual other tissue\n \"\"\"\n def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.1, num_workers=1,\n classification=True, classification_threshold=0.99, cross_validation_seed=0, embedded=False):\n self.data_dir = data_dir\n self.classification = classification\n self.class_threshold = classification_threshold\n self.cross_validation_seed = cross_validation_seed\n self.embedded = embedded\n start = time.time()\n print(f'starting loading of data')\n\n if data_dir:\n raise Exception('Data directories for this data loader are preset and can\\'t be overwritten.')\n else:\n prefix = \"embedded_\" if embedded else \"\"\n\n cons = np.load(f'data/iPSC/exon/{prefix}cons.npy')\n low = np.load(f'data/iPSC/exon/{prefix}low_bezi1.npy')\n high = np.load(f'data/iPSC/exon/{prefix}high_bezi1.npy')\n\n diff_lib_cons = np.load(f'data/iPSC/exon/{prefix}cons.npy')\n diff_lib_low = np.load(f'data/iPSC/exon/{prefix}low_bezi2.npy')\n diff_lib_high = np.load(f'data/iPSC/exon/{prefix}high_bezi2.npy')\n\n diff_indv_cons = np.load(f'data/iPSC/exon/{prefix}cons.npy')\n diff_indv_low = np.load(f'data/iPSC/exon/{prefix}low_lexy2.npy')\n diff_indv_high = np.load(f'data/iPSC/exon/{prefix}high_lexy2.npy')\n\n diff_tissue_cons = np.load(f'data/hipsci_majiq/exon/{prefix}cons.npy')\n diff_tissue_low = np.load(f'data/hipsci_majiq/exon/{prefix}low.npy')\n diff_tissue_high = np.load(f'data/hipsci_majiq/exon/{prefix}high.npy')\n\n if self.classification:\n cons, low, high = self.apply_classification_threshold(cons, low, high,\n embedded=embedded, threshold=classification_threshold)\n diff_lib_cons, diff_lib_low, diff_lib_high = \\\n self.apply_classification_threshold(diff_lib_cons, diff_lib_low, diff_lib_high,\n embedded=embedded, threshold=classification_threshold)\n diff_indv_cons, diff_indv_low, diff_indv_high = \\\n self.apply_classification_threshold(diff_indv_cons, diff_indv_low, diff_indv_high,\n embedded=embedded, threshold=classification_threshold)\n diff_tissue_cons, diff_tissue_low, diff_tissue_high = \\\n self.apply_classification_threshold(diff_tissue_cons, diff_tissue_low, diff_tissue_high,\n embedded=embedded, threshold=classification_threshold)\n\n train, test_all, test_low, test_high, val = self.get_train_test_and_val_sets(cons, low, high)\n\n already_used_samples = self._construct_hashset(train, val)\n diff_lib_cons, diff_lib_low, diff_lib_high = \\\n self._filter_already_used_samples(already_used_samples, diff_lib_cons, diff_lib_low, diff_lib_high)\n diff_indv_cons, diff_indv_low, diff_indv_high = \\\n self._filter_already_used_samples(already_used_samples, diff_indv_cons, diff_indv_low, diff_indv_high)\n diff_tissue_cons, diff_tissue_low, diff_tissue_high = \\\n self._filter_already_used_samples(already_used_samples, diff_tissue_cons, diff_tissue_low, diff_tissue_high)\n\n test_datasets_diff_lib = self._construct_all_low_and_high_datasets(diff_lib_cons, diff_lib_low, diff_lib_high)\n test_datasets_diff_indv = self._construct_all_low_and_high_datasets(diff_indv_cons, diff_indv_low, diff_indv_high)\n test_datasets_diff_tissue = self._construct_all_low_and_high_datasets(diff_tissue_cons, diff_tissue_low, diff_tissue_high)\n\n # flatten dataset elements\n extra_test_datasets = [sample for dataset in\n [test_datasets_diff_lib, test_datasets_diff_indv, test_datasets_diff_tissue]\n for sample in dataset]\n\n\n super().__init__(train, (test_all, test_low, test_high), val, batch_size, shuffle, validation_split, num_workers,\n cross_validation_seed=cross_validation_seed, extra_test_datasets=extra_test_datasets)\n end = time.time()\n print('total time to load data: {} secs'.format(end - start))\n\n # overriding get_valid_and_test_loaders for extra functionality;\n # would be cleaner since it means that base dataloader no longer needs to know about this class\n # def get_valid_and_test_loaders(self):\n # pass\n\n @staticmethod\n def _construct_all_low_and_high_datasets(cons, low, high):\n np.random.seed(0)\n np.random.shuffle(cons)\n np.random.shuffle(low)\n np.random.shuffle(high)\n\n all_d = np.concatenate((cons, low, high), axis=0)\n low_d = np.concatenate((cons, low), axis=0)\n high_d = np.concatenate((cons, high), axis=0)\n all_set, low_set, high_set = ComparisonDataLoader.construct_dataset(all_d), \\\n ComparisonDataLoader.construct_dataset(low_d), \\\n ComparisonDataLoader.construct_dataset(high_d)\n return all_set, low_set, high_set\n\n @staticmethod\n def _construct_hashset(train, val):\n train_np, val_np = train.samples.numpy(), val.samples.numpy()\n train_and_val_samples = set()\n for sample in list(train_np[:, :281]):\n train_and_val_samples.add(sample.tostring())\n return train_and_val_samples\n\n @staticmethod\n def _filter_already_used_samples(hashset, possibilities_cons, possibilities_low, possibilities_high):\n cons_filtered = ComparisonDataLoader._return_non_duplicates(hashset, possibilities_cons)\n low_filtered = ComparisonDataLoader._return_non_duplicates(hashset, possibilities_low)\n high_filtered = ComparisonDataLoader._return_non_duplicates(hashset, possibilities_high)\n return cons_filtered, low_filtered, high_filtered\n\n @staticmethod\n def _return_non_duplicates(hashset, possibilities):\n poss_filtered = []\n for sample in list(possibilities[:, :281]):\n if sample.tostring() not in hashset:\n poss_filtered.append(sample)\n # 35954 / 5827 w/ only sequence information\n # 36179 / 6413 w/ length information too\n return poss_filtered\n\n\n","sub_path":"data_loader/ComparisonDataLoader.py","file_name":"ComparisonDataLoader.py","file_ext":"py","file_size_in_byte":6707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"522730481","text":"import discord\nimport atexit\nimport asyncio\nimport random\nimport youtube_dl\nimport os\nimport sys\nimport subprocess\nimport simplejson as json\nfrom ctypes.util import find_library\nfrom collections import deque\n\nclient = discord.Client()\ninit = False\n\n@client.event\nasync def on_ready():\n print('Logged in as:')\n print(client.user.name)\n print(client.user.id)\n print('---------------------')\n discord.opus.load_opus(find_library(\"opus\"))\n playlist = deque()\n for serv in client.servers:\n for chan in serv.channels:\n print(\"this channel's id is: {}\".format(chan.id))\n\n@client.event\nasync def on_message(message):\n global player\n global current_song\n global playlist\n try:\n test = playlist.maxlen\n except:\n playlist = deque()\n if message.content.startswith('%test') and message.author != message.author.server.me:\n count = 0\n tmp = await client.send_message(message.channel, \"Calculating messages...\")\n async for log in client.send_message(message.channel, limit = 100):\n if log.author == message.author:\n count += 1\n await client.edit_message(tmp, \"You have {} messages.\".format(count))\n## test thread sleep.\n elif message.content.startswith('%help') and message.author != message.author.server.me:\n commandstr = \"--Commands--\\n%coinflip: flips a coin, lands on heads or tails\\n%join: Joins the voice channel you are currently in\\n%play : Plays an audio stream of a sound file available in the bot's music library\\n%music: lists all music currently available to play\\n%ytplay : Plays an audio stream from the youtube URL specified\\n%pause: pauses the current audio stream\\n%resume: resumes the current audio stream\\n%stop: ends the current audio stream\\n%disconnect: disconnects the bot from voice chat and clears the playlist\\n%dl: If added as a comment to an uploaded song, the bot will add the song to its library.\\n%queue: lists the current queue scheduled for the bot to play\\n%currentsong: lists the current song that is playing.\"\n await client.send_message(message.channel, commandstr)\n elif message.content.startswith('%sleep') and message.author != message.author.server.me:\n await asyncio.sleep(5)\n await client.send_message(message.channel, 'Done sleeping')\n## hello, world! :)\n elif message.content.startswith('%hw') and message.author != message.author.server.me:\n await client.send_message(message.channel, \"Hello, World!\")\n## performs a coinflip, will land on heads or tails.\n elif message.content.startswith('%coinflip') and message.author != message.author.server.me:\n if random.random() > .5:\n result = \"heads\"\n else:\n result = \"tails\"\n await client.send_message(message.channel, \"I flipped a coin and got {}\".format(result))\n elif message.content.startswith('%music') and message.author != message.author.server.me:\n## Reads the songs available in the \"songs\" folder\n musiclib = os.listdir(os.getcwd() + \"/songs\")\n songstr = \"\"\n for song in musiclib:\n songstr = songstr + song + \"\\n\"\n await client.send_message(message.channel, \"Music available to play:\\n {}\".format(songstr))\n elif message.content.startswith('%queue') and message.author != message.author.server.me:\n playstr = \"\"\n i = 0\n try:\n test = playlist.maxlen\n except:\n playlist = deque()\n if len(playlist) == 0:\n await client.send_message(message.channel, \"The playlist is empty.\")\n else:\n for item in playlist:\n i += 1\n playstr = playstr + str(i) + \". [\" + item.split(\" \")[1] + \"]\\n\"\n await client.send_message(message.channel, \"--Current playlist queue--\\n{}\".format(playstr))\n## play youtube stream from a youtube URL\n elif message.content.startswith('%play') and message.author != message.author.server.me:\n# print('opus loaded: {}'.format(discord.opus.is_loaded()))\n file = message.content.split(\" \")\n try:\n if (player.is_playing() or not player.is_done()) and os.path.isfile(\"songs/\" + file[1]):\n playlist.append(message.content)\n await client.send_message(message.channel, \"added <{}> to the playlist\".format(message.content.split(\" \")[1]))\n elif not os.path.isfile(\"songs/\" + file[1]):\n await client.send_message(message.channel, \"I couldn't find that in my library.\")\n except:\n try:\n test = playlist.maxlen\n except:\n playlist = deque()\n voice = list(client.voice_clients)[0]\n if(os.path.isfile(\"songs/\" + file[1])):\n player = voice.create_ffmpeg_player(\"songs/\" + file[1])\n await client.send_message(message.channel, \"Currently playing {}\".format(file[1]))\n current_song = discord.Game()\n current_song.name = file[1]\n await client.change_status(game=current_song, idle=False)\n player.start()\n else:\n await client.send_message(message.channel, \"I couldn't find that in my library.\")\n elif message.content.startswith('%ytplay') and message.author != message.author.server.me:\n print('opus loaded: {}'.format(discord.opus.is_loaded()))\n url = message.content.split(\" \")\n try:\n if player.is_playing() or not player.is_done():\n playlist.append(message.content)\n await client.send_message(message.channel, \"added <{}> to the playlist\".format(message.content.split(\" \")[1]))\n except:\n try:\n test = playlist.maxlen\n except:\n playlist = deque()\n voice = list(client.voice_clients)[0]\n player = await voice.create_ytdl_player(url[1])\n current_song = discord.Game()\n current_song.name = player.title\n await client.change_status(game=current_song, idle=False)\n await client.send_message(message.channel, \"Currently playing {}\".format(player.title))\n await asyncio.sleep(5)\n player.start()\n## commands to control audio streams.\n elif message.content.startswith('%pause') and message.author != message.author.server.me:\n try:\n player.pause()\n await client.send_message(message.channel, \"Pausing audio stream...\")\n except:\n await client.send_message(message.channel, \"Something went wrong...\")\n elif message.content.startswith('%resume') and message.author != message.author.server.me:\n try:\n player.resume()\n await client.send_message(message.channel, \"Resuming audio stream...\")\n except:\n await client.send_message(message.channel, \"Something went wrong...\")\n elif message.content.endswith('boops DJSweets'):\n await client.send_message(message.channel, \"-makes a scrunchy face-\")\n## Kills the playlist too\n elif message.content.startswith('%stop') and message.author != message.author.server.me:\n try:\n player.stop()\n player = None\n await client.change_status(game=None, idle=False)\n await client.send_message(message.channel, \"Stopping audio stream and clearing playlist...\")\n playlist.clear()\n except:\n await client.send_message(message.channel, \"Something went wrong...\")\n## Joins the voice channel specified\n## Usage (in discord: type) %join\n elif message.content.startswith('%join') and message.author != message.author.server.me:\n #channel_name = message.content[6:]\n #found_channel = False\n try:\n if player.is_playing():\n player.pause()\n except:\n pass\n if client.is_voice_connected(message.author.server):\n await list(client.voice_clients)[0].disconnect()\n #print(\"joining \" + channel_name)\n# serv = message.server\n# for chan in serv.channels:\n# if(chan.name == channel_name):\n# if(chan.type == discord.ChannelType.voice):\n# found_channel = True\n if message.author.voice_channel != None:\n await client.send_message(message.channel, \"Joining voice channel: {}\".format(message.author.voice_channel))\n voice = await client.join_voice_channel(message.author.voice_channel)\n try:\n player.resume()\n except:\n pass\n else:\n await client.send_message(message.channel, \"You're not in a voice channel for me to join you!\")\n# else:\n# await client.send_message(message.channel, \"This isn't a voice channel!\")\n# if found_channel == False:\n# await client.send_message(message.channel, \"I couldn't find the channel: {}\".format(channel_name))\n## leaves the voice channel and disconnects from voice chat, this also kills audiostreams\n elif message.content.startswith('%disconnect') and message.author != message.author.server.me:\n await client.send_message(message.channel, \"Leaving the voice channel and clearing playlist\")\n await list(client.voice_clients)[0].disconnect()\n await client.change_status(game=None,idle=False)\n player = None\n elif message.content.startswith('%dl') and message.author != message.author.server.me:\n try:\n jsonstr = json.dumps(message.attachments[0])\n jsondict = json.loads(jsonstr)\n filepath = os.getcwd()+\"/songs/\"\n print(\"file path: \" + filepath)\n url = jsondict['url']\n if jsondict['filename'].endswith('.mp3'):\n os.system('wget {0} -P {1}'.format(url, filepath))\n print(\"creating new file\")\n await client.send_message(message.channel, \"Added file to music library!\")\n else:\n await client.send_message(message.channel, \"This isn't an mp3!\")\n except:\n await client.send_message(message.channel, \"No file specified\")\n elif message.content.startswith('%currentsong'):\n try:\n await client.send_message(message.channel, \"The song playing is {}\".format(current_song))\n except:\n await client.send_message(message.channel, \"Nothing is playing right now.\")\n elif (len(playlist) != 0):\n try:\n if ('player' in globals() and (player.is_done()) and len(playlist) != 0) or ('player' in globals() and message.content.startswith('%skip') and message.author != message.author.server.me and len(playlist) != 0):\n next_item = playlist.popleft()\n voice = list(client.voice_clients)[0]\n try:\n if player.is_playing() or player.is_done():\n player.stop()\n player = None\n except:\n pass\n if next_item.startswith('%ytplay'):\n url = next_item.split(\" \")\n print (url)\n player = await voice.create_ytdl_player(url[1])\n current_song = discord.Game()\n current_song.name = player.title\n await client.change_status(game=current_song, idle=False)\n await asyncio.sleep(5)\n player.start()\n if next_item.startswith('%play'):\n file = next_item.split(\" \")\n if(os.path.isfile(\"songs/\" + file[1])):\n print(\"trying to play: {}\".format(file[1]))\n player = voice.create_ffmpeg_player(\"songs/\" + file[1])\n current_song = discord.Game()\n current_song.name = file[1]\n await client.change_status(game=current_song, idle=False)\n await asyncio.sleep(3)\n player.start()\n else:\n pass\n except:\n pass\n\n elif len(playlist) == 0:\n try: \n if 'player' in globals() and player.is_done() and len(playlist) == 0:\n await client.change_status(game=None, idle=False)\n player = None\n except:\n pass\n\n@client.event\nasync def on_socket_closed():\n await print(\"disconnected! attempting to reconnect\")\n reconnected = False\n while not reconnected:\n try:\n client.run('email','pass')\n reconnected = True\n except:\n print(\"reconnect failed, trying again\")\n client.run('email', 'pass')\n\ndef restart():\n subprocess.call(['./restart.sh'])\n\nclient.run('email', 'pass')\n\natexit.register(restart())\n","sub_path":"ciybot.py","file_name":"ciybot.py","file_ext":"py","file_size_in_byte":12873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"237144646","text":"import unittest\nimport warnings\nimport importlib\n\nfrom sqlight.connection import Connection\nfrom sqlight.platforms import Platform\nfrom sqlight.err import Error, ProgrammingError, DatabaseError\nfrom .config import MYSQL_CLIENT_URL, PYMYSQL_URL, POSTGRESQL_URL,\\\n sqlite_test_table, mysql_test_table, postgresql_test_table\n\n\nclass TestConnectionAutoCommit(unittest.TestCase):\n\n def setUp(self):\n warnings.simplefilter(\"ignore\")\n self.test_cons = []\n self.test_cons.append(\n Connection.create_from_dburl(\n \"sqlite:///:memory:?autocommit=True\"))\n\n try:\n importlib.import_module(\"MySQLdb.cursors\")\n except ImportError:\n pass\n else:\n self.test_cons.append(Connection.create_from_dburl(\n MYSQL_CLIENT_URL + \"?autocommit=True\"))\n\n try:\n importlib.import_module(\"pymysql.cursors\")\n except ImportError:\n pass\n else:\n self.test_cons.append(Connection.create_from_dburl(\n PYMYSQL_URL + \"?autocommit=True&connect_timeout=1\"))\n try:\n importlib.import_module(\"psycopg2\")\n except ImportError:\n pass\n else:\n self.test_cons.append(Connection.create_from_dburl(\n POSTGRESQL_URL + \"?autocommit=True\"))\n\n def tearDown(self):\n for c in self.test_cons:\n c.connect()\n c.execute(\"drop table if exists test\")\n\n def test_loop(self):\n for c in self.test_cons:\n self.t_connect(c)\n self.t_execute(c)\n self.t_execute_lastrowid(c)\n self.t_executemany(c)\n self.t_execute_rowcount(c)\n self.t_query(c)\n self.t_get(c)\n self.t_iter(c)\n self.t_rollback(c)\n self.t_commit(c)\n self.t_close(c)\n self.t_after_close(c)\n\n def t_connect(self, c):\n c.connect()\n\n def t_close(self, c):\n c.execute(\"drop table test\")\n c.close()\n\n def t_execute(self, c):\n \"\"\"创建表\"\"\"\n if c.dburl.platform is Platform.MySQL:\n c.execute(mysql_test_table)\n elif c.dburl.platform is Platform.SQLite:\n c.execute(sqlite_test_table)\n elif c.dburl.platform is Platform.PostgreSQL:\n c.execute(postgresql_test_table)\n\n def t_execute_lastrowid(self, c):\n \"\"\"插入数据\"\"\"\n name = \"test1\"\n c.execute_lastrowid(\"insert into test (name) values (%s)\", name)\n row = c.get(\"select * from test where name = %s\", name)\n self.assertEqual(row.id, 1)\n\n def t_executemany(self, c):\n \"\"\"批量插入数据\"\"\"\n values = [\n [\"test2\"],\n [\"test3\"],\n ]\n count = c.executemany(\"insert into test (name) values (%s)\", values)\n self.assertEqual(count, 2)\n last = c.get(\"select * from test where id = %s\", 3)\n self.assertEqual(last.id, 3)\n self.assertEqual(last.name, \"test3\")\n\n def t_execute_rowcount(self, c):\n \"\"\"更新数据\"\"\"\n count = c.execute_rowcount(\"update test set name = %s where id = %s\",\n \"test3_after\", 3)\n self.assertEqual(count, 1)\n last = c.get(\"select * from test where id = %s\", 3)\n self.assertEqual(last.id, 3)\n self.assertEqual(last.name, \"test3_after\")\n\n def t_query(self, c):\n \"\"\"查询数据\"\"\"\n last = c.query(\"select * from test where id = %(id)s\", id=3)\n self.assertEqual(len(last), 1)\n self.assertEqual(last[0].id, 3)\n self.assertEqual(last[0].name, \"test3_after\")\n self.assertEqual(\n c.get_last_executed(),\n \"select * from test where id = 3\")\n\n def t_get(self, c):\n \"\"\"查询数据\"\"\"\n self.assertRaises(ProgrammingError,\n c.get,\n \"select * from test where id > %(id)s\",\n id=1)\n with self.assertRaises(DatabaseError):\n c.get(\"select * from test2 where nn = 0\")\n\n def t_iter(self, c):\n \"\"\"查询数据\"\"\"\n iters = c.iter(\"select * from test where id > %(id)s\", id=0)\n all_rows = []\n id = 0\n for i in iters:\n id += 1\n all_rows.append(i)\n self.assertEqual(i.id, id)\n if id == 3:\n self.assertEqual(i.name, \"test3_after\")\n else:\n self.assertEqual(i.name, \"test%d\" % id)\n self.assertEqual(len(all_rows), 3)\n\n def t_rollback(self, c):\n name = \"test4\"\n c.begin()\n c.execute_lastrowid(\"insert into test (name) values (%s)\", name)\n c.rollback()\n row = c.get(\"select * from test where name = %s\", name)\n self.assertEqual(row, None)\n\n def t_commit(self, c):\n c.begin()\n name = \"test5\"\n c.execute_lastrowid(\"insert into test (name) values (%(name)s)\",\n name=name)\n c.commit()\n row = c.get(\"select * from test where name = %s\", name)\n self.assertIn(row.id, [4, 5])\n self.assertEqual(row.name, name)\n\n def t_after_close(self, c):\n with self.assertRaises(Error):\n c.get(\"select * from test\")\n","sub_path":"tests/test_connection_autocommit.py","file_name":"test_connection_autocommit.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"131845905","text":"#_*_ coding: utf-8_*_\n\nimport numpy\nimport matplotlib\nimport operator\nfrom math import log\n\n#给定一个集合,计算该集合的信息熵(信息的杂乱程度)\ndef calShannonEntropy(dataSet):\n numberOfEntry = len(dataSet)\n labelCount = {}\n for item in dataSet:\n currentLabel = item[-1]\n if currentLabel not in labelCount.keys():\n labelCount[currentLabel] = 0\n labelCount[currentLabel] += 1\n shannonEntropy = 0.0\n for key in labelCount:\n prob = float(labelCount[key])/numberOfEntry\n shannonEntropy -= prob * log(prob,2)\n return shannonEntropy\n\n#划分数据集合,将同一个类别的划分到returnDataSet集合中并返回\ndef spliteDataSet(dataSet,axis,value):\n returnDataSet = []\n for item in dataSet:\n if item[axis]==value:\n reduceItem = item[:axis]\n reduceItem.extend(item[axis+1:])\n returnDataSet.append(reduceItem)\n return returnDataSet\n\n#选择最好的分类属性进行分类,找到用哪个属性分类能得到的信息增益最大值\ndef chooseBestFeatureToSplit(dataSet):\n numberOfFeature = len(dataSet[0]) - 1\n baseEntropy = calShannonEntropy(dataSet)\n bestInfoGain = 0.0\n bestFeature = -1\n for i in range(numberOfFeature):\n labelList = []\n for j in range(len(dataSet)):\n labelList.append(dataSet[j][i])\n uniqueVals = set(labelList)\n newEntropy = 0.0\n for value in uniqueVals:\n subDataSet = spliteDataSet(dataSet,i,value)\n prob = float(len(subDataSet))/len(dataSet)\n newEntropy += prob*calShannonEntropy(subDataSet)\n infoGain = baseEntropy - newEntropy\n if( infoGain>bestInfoGain ):\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n\n#找一个出现次数最多的类型\ndef majorityClass(classList):\n classCount = {}\n for item in classList:\n classCount[item] = classCount.get(item,0) + 1\n sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n return sortedClassCount[0][0]\n\n#构建决策树\ndef createTree(dataSet,labels):\n classList = []\n for item in dataSet:\n classList.append(item[-1])\n #递归退出条件\n if classList.count(classList[0])==len(classList):\n return classList[0]\n if len(dataSet[0])==1:\n return majorityClass(classList)\n\n bestFeature = chooseBestFeatureToSplit(dataSet)\n bestLabel = labels[bestFeature]\n myTree = {labels[bestFeature]:{}}\n del(labels[bestFeature])\n featureValue = []\n for item in dataSet:\n featureValue.append(item[bestFeature])\n uniqueVals = set(featureValue)\n for value in uniqueVals:\n subLabels = labels[:] #每次都用一个新的subLabels,消除python中的列表引用传递的影响\n myTree[bestLabel][value] = createTree(spliteDataSet(dataSet,bestFeature,value),subLabels)\n return myTree\n\n#构造测试数据用的函数\ndef createDataSet():\n dataSet = [[1,1,'yes'],[1,1,'yes'],[1,0,'no'],[0,1,'no'],[0,1,'no']]\n labels = ['no surfacing','flippers']\n return dataSet,labels\n\ndataSet,labels = createDataSet()\nmyTree = createTree(dataSet,labels)\nprint(myTree)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"trees.py","file_name":"trees.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"103186765","text":"\"\"\" FF14\n\n一些最终幻想XIV相关的指令\n\"\"\"\nfrom nonebot import CommandSession, on_command\n\nfrom .monitor_server import server_monitor\nfrom .news import news\n\n\n@on_command(\n 'ff14', aliases=['最终幻想14', '最终幻想XIV'], only_to_me=False, shell_like=True\n)\nasync def ff14(session: CommandSession):\n \"\"\" 最终幻想XIV\n \"\"\"\n user_id = session.event.user_id\n if len(session.argv) == 0:\n session.finish('当前支持的功能有\\nserver:查询服务器在线状态')\n if len(session.argv) == 1 and session.argv[0] == 'server':\n session.finish(server_monitor.status)\n if len(session.argv) == 2 and session.argv[0] == 'server':\n if session.argv[1].lower() in ['0', 'off', 'false']:\n if server_monitor.is_enabled:\n server_monitor.disable()\n session.finish('已停止监控服务器状态')\n else:\n if not server_monitor.is_enabled:\n server_monitor.enable()\n session.finish('已开始监控服务器状态')\n if len(session.argv) == 1 and session.argv[0] == 'news':\n if news.is_enabled:\n session.finish('新闻自动推送开启中')\n else:\n session.finish('新闻自动推送关闭中')\n if len(session.argv) == 2 and session.argv[0] == 'news':\n if session.argv[1].lower() in ['0', 'off', 'false']:\n if news.is_enabled:\n news.disable()\n session.finish('已停止新闻自动推送')\n else:\n if not news.is_enabled:\n news.enable()\n session.finish('已开始新闻自动推送')\n\n session.finish('抱歉,并没有这个功能。')\n","sub_path":"src/plugins/ff14/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"75921999","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .models import Mood\nfrom .functions import getGiphy\n\n# Create your views here.\ndef index(request):\n mostViewedMoods = Mood.objects.order_by('-numViewed')[:5]\n latestMoods = Mood.objects.order_by('-lastViewed')[:5]\n context = {'mostViewedMoods': mostViewedMoods, 'latestMoods': latestMoods}\n return render(request, 'moods/index.html', context)\n \ndef detail(request):\n try:\n qs = request.GET['ref']\n if qs == 'search':\n giphy = getGiphy(str(request.GET['searchPhrase']))\n else:\n giphy = getGiphy(int(request.GET['mid']))\n return render(request, 'moods/detail.html', {'giphy':giphy})\n except:\n return HttpResponse('Sorry, you did not enter a decent mood.')\n\n \n ","sub_path":"moods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"517186997","text":"import pygame, helpers\r\nfrom CONSTANTS import *\r\nfrom random import randint, randrange\r\nfrom pygame.locals import *\r\n\r\ndef SimpleScreen(baseImage):\r\n # Make something to draw to the screen\r\n background = helpers.LoadImage(baseImage,\"Art\")\r\n\r\n # Make a cursor\r\n mouse = pygame.mouse.get_pressed()\r\n MousePos = pygame.mouse.get_pos()\r\n\r\n # The Menu Loop\r\n while True:\r\n \r\n # Check for quit and do so if needed\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n helpers.ExitGame()\r\n return\r\n # Get the state of the mouse\r\n mouse = pygame.mouse.get_pressed()\r\n MousePos = pygame.mouse.get_pos()\r\n if event.type == MOUSEBUTTONUP:\r\n return\r\n if event.type == KEYUP:\r\n return\r\n # Draw the background to the screen\r\n SCREEN.blit(background,(0,0))\r\n # Update the screen to reflect changes\r\n pygame.display.update()\r\n # Limit the frames drawn per second\r\n CLOCK.tick(30)\r\n\r\ndef ScrollingScreen(SCREEN,CLOCK,baseImage):\r\n # Make something to draw to the screen\r\n background = helpers.SurfaceSetup(SCREENSIZE,BLACK)\r\n foreground = helpers.LoadImage(baseImage,\"Art\",-1)\r\n\r\n starfield = StarField(45)\r\n mouse = pygame.mouse.get_pressed()\r\n MousePos = pygame.mouse.get_pos()\r\n\r\n # The Menu Loop\r\n while True:\r\n \r\n # Check for quit and do so if needed\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n helpers.ExitGame()\r\n return\r\n # Get the state of the mouse\r\n mouse = pygame.mouse.get_pressed()\r\n MousePos = pygame.mouse.get_pos()\r\n if event.type == MOUSEBUTTONUP:\r\n return\r\n if event.type == KEYUP:\r\n return\r\n # Draw the background to the screen\r\n SCREEN.blit(background,(0,0))\r\n stars = starfield.Update(2)\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n SCREEN.blit(foreground,(0,0))\r\n # Update the screen to reflect changes\r\n pygame.display.update()\r\n # Limit the frames drawn per second\r\n CLOCK.tick(30)\r\n\r\ndef MainMenu(SCREEN,CLOCK):\r\n # Make something to draw to the screen\r\n background = helpers.SurfaceSetup(SCREENSIZE,(0,0,0))\r\n\r\n # All the stuff to draw to the screen\r\n ship = helpers.LoadImage(\"Ship outside.png\",\"Art\",-1)\r\n shipposition = ((3*(SCREENSIZE[0]-ship.get_width()))/4,\r\n (3*(SCREENSIZE[1]-ship.get_height()))/4)\r\n starfield = StarField(45)\r\n buttons = helpers.LoadImage(\"Menu buttons.png\",\"Art\",-1)\r\n buttonsorg = (50,50)\r\n title = helpers.LoadImage(\"Title.png\",\"Art\",-1)\r\n titleloc = (330,50)\r\n MousePos = (0,0)\r\n\r\n buttonhighlight = helpers.SurfaceSetup((177,65),YELLOW)\r\n buttonhighlight.set_alpha(100)\r\n\r\n # The button locations\r\n buttonsloc = {1:Rect(buttonsorg[0]+1,buttonsorg[1]+1,177,65),\r\n 2:Rect(buttonsorg[0]+1,buttonsorg[1]+94,177,65),\r\n 3:Rect(buttonsorg[0]+1,buttonsorg[1]+205,177,65),\r\n 4:Rect(buttonsorg[0]+1,buttonsorg[1]+304,177,65),}\r\n # Ship jitter\r\n shipjitter = 0\r\n while True:\r\n keyup = False\r\n # Check for quit and do so if needed\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n helpers.ExitGame()\r\n return\r\n if event.type == MOUSEMOTION:\r\n MousePos = pygame.mouse.get_pos()\r\n if event.type == MOUSEBUTTONUP:\r\n keyup = True\r\n\r\n shipjitter += 1\r\n # Draw the background to the screen\r\n SCREEN.blit(background,(0,0))\r\n stars = starfield.Update(2)\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n SCREEN.blit(buttons,buttonsorg)\r\n SCREEN.blit(title,titleloc)\r\n SCREEN.blit(ship,shipposition)\r\n if shipjitter % 7 == 0:\r\n shipjitter = 0\r\n shipposition = (shipposition[0]+randrange(-1,2),shipposition[0]++randrange(-1,2))\r\n for i in buttonsloc:\r\n if buttonsloc[i].collidepoint(MousePos) == True:\r\n SCREEN.blit(buttonhighlight,buttonsloc[i])\r\n if(keyup == True and buttonsloc[i].collidepoint(MousePos) == True):\r\n return i\r\n # Update the screen to reflect changes\r\n pygame.display.update()\r\n # Limit the frames drawn per second\r\n CLOCK.tick(30)\r\n \r\n\r\ndef Ending(SCREEN,CLOCK,victory):\r\n # Make something to draw to the screen\r\n background = helpers.SurfaceSetup(SCREENSIZE,(0,0,0))\r\n ship = helpers.LoadImage(\"Ship outside.png\",\"Art\",-1)\r\n shipposition = ((SCREENSIZE[0]-ship.get_width())/2,\r\n (SCREENSIZE[1]-ship.get_height())/2)\r\n inspacebox = helpers.LoadImage(\"innerspace.png\",\"Art\",-1)\r\n starfield = StarField(45)\r\n transitiontime = 5*FPS\r\n shipmove = SCREENSIZE[0]/(4*transitiontime)\r\n shipscaling = 1.0\r\n if victory == True:\r\n winbox = helpers.LoadImage(\"Win text.png\",\"Art\",-1)\r\n starbase = helpers.LoadImage(\"Planet.png\",\"Art\",-1)\r\n starbasepos = (SCREENSIZE[0]+ship.get_width()/4,150)\r\n gotime = 4*transitiontime/5\r\n else:\r\n losebox = helpers.LoadImage(\"Loss text.png\",\"Art\",-1)\r\n explosion = helpers.LoadImage(\"Sparks.png\",\"Art\",-1)\r\n\r\n # The Game Loop\r\n while True:\r\n keys = []\r\n # Check for quit and do so if needed\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n helpers.ExitGame()\r\n return\r\n if event.type == KEYDOWN:\r\n keys.append(event.key)\r\n\r\n\r\n if transitiontime >= 0:\r\n transitiontime -= 1\r\n if transitiontime <0:\r\n if len(keys) !=0:\r\n return\r\n if transitiontime > -1*FPS:\r\n transitiontime -= 1\r\n \r\n # Draw the background to the screen\r\n SCREEN.blit(background,(0,0))\r\n if victory == True:\r\n # Update background relative to speed\r\n stars = starfield.Update(int(3*shipscaling))\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n if starbasepos[0] < SCREENSIZE[0]:\r\n SCREEN.blit(starbase,starbasepos)\r\n SCREEN.blit(ship,shipposition)\r\n if transitiontime > gotime:\r\n shipscaling -= 1.0*3.5/(transitiontime)\r\n if transitiontime < gotime:\r\n if starbasepos[0] > shipposition[0]:\r\n shipposition = (shipposition[0]+2,shipposition[1])\r\n starbasepos = (starbasepos[0]-2,starbasepos[1])\r\n elif shipposition[0] 0:\r\n # Update background relative to speed\r\n stars = starfield.Update(3)\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n SCREEN.blit(pygame.transform.scale(ship,(int(ship.get_width()*shipscaling),int(ship.get_height()*shipscaling))),\r\n (shipposition[0]+randrange(-5,5),shipposition[1]+randrange(-5,5)))\r\n shipscaling -= 1.0/(transitiontime*2)\r\n \r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,int(ship.get_width()*shipscaling)),\r\n shipposition[1]+randrange(-15,int(ship.get_height()*shipscaling))))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,int(ship.get_width()*shipscaling)),\r\n shipposition[1]+randrange(-15,int(ship.get_height()*shipscaling))))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,int(ship.get_width()*shipscaling)),\r\n shipposition[1]+randrange(-15,int(ship.get_height()*shipscaling))))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,int(ship.get_width()*shipscaling)),\r\n shipposition[1]+randrange(-15,int(ship.get_height()*shipscaling))))\r\n else:\r\n # Update background relative to speed\r\n stars = starfield.Update(3)\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n if transitiontime <= 0:\r\n if victory == False:\r\n SCREEN.blit(losebox,((SCREENSIZE[0]-losebox.get_width())/2,100))\r\n if transitiontime == -FPS:\r\n SCREEN.blit(inspacebox,((SCREENSIZE[0]-inspacebox.get_width())/2,175))\r\n else:\r\n SCREEN.blit(winbox,((SCREENSIZE[0]-winbox.get_width())/2,100))\r\n if transitiontime == -FPS:\r\n SCREEN.blit(inspacebox,((SCREENSIZE[0]-inspacebox.get_width())/2,175))\r\n # Update the screen to reflect changes\r\n pygame.display.update()\r\n # Limit the frames drawn per second\r\n CLOCK.tick(30)\r\n\r\n\r\ndef Transition(SCREEN,CLOCK,won,difficulty):\r\n # Make something to draw to the screen\r\n background = helpers.SurfaceSetup(SCREENSIZE,(0,0,0))\r\n ship = helpers.LoadImage(\"Ship outside.png\",\"Art\",-1)\r\n explosion = helpers.LoadImage(\"Sparks.png\",\"Art\",-1)\r\n shipposition = ((SCREENSIZE[0]-ship.get_width())/2,\r\n (SCREENSIZE[1]-ship.get_height())/2)\r\n starfield = StarField(45)\r\n transitiontime = 5*FPS\r\n gotime = 4*transitiontime/5\r\n shipmove = SCREENSIZE[0]/(4*transitiontime)\r\n # The Game Loop\r\n while True:\r\n \r\n # Check for quit and do so if needed\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n helpers.ExitGame()\r\n return\r\n\r\n\r\n # This is where the \"game logic\" WILL happen.\r\n transitiontime -= 1\r\n if transitiontime <0:\r\n return\r\n # Update background relative to speed\r\n stars = starfield.Update(5)\r\n \r\n # Draw the background to the screen\r\n SCREEN.blit(background,(0,0))\r\n for i in stars:\r\n SCREEN.blit(i.star.Surf(),i.star.Rect())\r\n if won == True:\r\n SCREEN.blit(ship,shipposition)\r\n if transitiontime < gotime:\r\n shipposition = (shipposition[0]+shipmove,shipposition[1])\r\n shipmove += 1\r\n else:\r\n SCREEN.blit(ship,(shipposition[0]+randrange(-5,5),shipposition[1]+randrange(-5,5)))\r\n \r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,ship.get_width()),\r\n shipposition[1]+randrange(-15,ship.get_height())))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,ship.get_width()),\r\n shipposition[1]+randrange(-15,ship.get_height())))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,ship.get_width()),\r\n shipposition[1]+randrange(-15,ship.get_height())))\r\n SCREEN.blit(explosion,(shipposition[0]+randrange(-15,ship.get_width()),\r\n shipposition[1]+randrange(-15,ship.get_height())))\r\n # Update the screen to reflect changes\r\n pygame.display.update()\r\n # Limit the frames drawn per second\r\n CLOCK.tick(30)\r\n\r\n\r\n#\r\n#\r\n#\r\n#\r\nclass Star():\r\n def __init__(self,size,location,speed):\r\n self.star = helpers.ScreenObject(location,helpers.SurfaceSetup(\r\n size,(255-randint(0,50),255-randint(0,50),255-randint(0,50))))\r\n self.speed = speed\r\n\r\n def ReturnX(self):\r\n return self.star.Rectangle[0]\r\n\r\n def Update(self,shipspeed=None,Location = None):\r\n if Location == None:\r\n self.star.MoveRect(self.star.Rectangle.move(shipspeed/self.speed,0))\r\n else:\r\n self.star.MoveRect(self.star.Rectangle.move(Location,0))\r\n return\r\n\r\n#\r\n#\r\n#\r\nclass StarField():\r\n def __init__(self,NumOfStars):\r\n self.starlist = []\r\n i = 0\r\n while i < NumOfStars:\r\n size = (randint(5,15),randint(3,5))\r\n if size[1]==3:\r\n speed = randint(-3,-1)\r\n elif size[1]==4:\r\n speed = randint(-5,-2)\r\n else:\r\n speed = randint(-8,-5)\r\n self.starlist.append(Star(size,\r\n pygame.rect.Rect((randint(0,SCREENSIZE[0]),randint(5,SCREENSIZE[1]-5)),size),\r\n speed))\r\n i = i+1\r\n\r\n def Update(self,shipspeed,moving = True):\r\n if moving == True:\r\n for i in self.starlist:\r\n if i.ReturnX()>0:\r\n i.Update(shipspeed)\r\n else:\r\n i.Update(Location=SCREENSIZE[0])\r\n return self.starlist\r\n\r\n\r\n\r\n","sub_path":"Effects.py","file_name":"Effects.py","file_ext":"py","file_size_in_byte":13014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"336940508","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport logging\nfrom math import exp\nimport random\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(lineno)s %(message)s',\n)\nlog = logging.getLogger(__name__)\n\nrandom.seed(2)\n\nALPHA = 1\nNU = 0.5\n\n\nclass XOR(object):\n def __init__(self):\n \"\"\" The XOR object is initialized as a list of lists containing the input values in the\n first two positions and the output values in the last 2\n \"\"\"\n self.cases = [\n [0, 0, 0, 1],\n [0, 1, 1, 0],\n [1, 0, 1, 0],\n [1, 1, 0, 1]\n ]\n\n def random_case(self):\n return self.cases[random.randrange(0, 4)]\n\n\nclass NeuralNetwork(object):\n def __init__(self, num_hidden_nodes, debug=False):\n \"\"\" This is a simplified model for a single hidden layer Neural Network with\n two input nodes and a two output nodes.\n Choose the number of hidden nodes to initialize an instance.\n :param num_hidden_nodes: number of hidden nodes\n :type num_hidden_nodes: int\n \"\"\"\n self.input_nodes = [Node(id, bias=0) for id in range(2)]\n if debug:\n self.hidden_nodes = [Node(id, bias=0.134364244112) for id in range(num_hidden_nodes)]\n self.output_nodes = [Node(id, bias=0.847433736937) for id in range(2)]\n else:\n self.hidden_nodes = [Node(id, bias=1 - 2 * random.random()) for id in range(num_hidden_nodes)]\n self.output_nodes = [Node(id, bias=1 - 2 * random.random()) for id in range(2)]\n\n\n # This dictionary stores the connection between input and hidden nodes\n self.ih_connections = [\n Connection(start_node, end_node, 1 - 2 * random.random())\n for end_node in self.hidden_nodes\n for start_node in self.input_nodes\n ]\n\n # This dictionary stores the connection between hidden and output nodes\n self.ho_connections = [\n Connection(start_node, end_node, 1 - 2 * random.random())\n for end_node in self.output_nodes\n for start_node in self.hidden_nodes\n ]\n\n if debug:\n debug_weights = [0.763774619, 0.255069026, 0.495435087, 0.449491065]\n for index, connection in enumerate(self.ih_connections):\n connection.set_weight(debug_weights[index])\n debug_weights = [0.651592973, 0.788723351, 0.093859587, 0.028347477]\n for index, connection in enumerate(self.ho_connections):\n connection.set_weight(debug_weights[index])\n\n def get_connection_weight(self, start_node, end_node):\n for connection in self.ih_connections:\n if (connection.start_node == start_node) and (connection.end_node == end_node):\n return connection.get_weight()\n for connection in self.ho_connections:\n if (connection.start_node == start_node) and (connection.end_node == end_node):\n return connection.get_weight()\n\n\n def train(self, logical_operator, loop, debug=False):\n \"\"\" Train function. Currently loops without any stop function (improvement needed)\n Setting debug to TRUE would log.info(connection weights.\n :param logical_operator: an object of the custom logical operator class representing the behavior of the\n operator\n :param loop: Number of training iterations\n :type loop: int\n :param debug: If set to True the function prints the weight of each layer at each iteration\n :type debug: boolean\n \"\"\"\n for i in range(loop):\n if debug:\n case = [1, 0, 1, 0]\n else:\n case = logical_operator.random_case()\n input_values = case[:2]\n desired_output = case[2:]\n for index, node in enumerate(self.input_nodes):\n node.set_value(input_values[index])\n self._forward_run()\n if debug:\n self.expose()\n self._back_propagation(desired_output, debug)\n if debug:\n self.expose()\n\n def _forward_run(self):\n \"\"\" The forward run calculates the output out of given input values. It is used for both training\n and running the final network.\n :returns: list\n \"\"\"\n # Input to Hidden backward run\n for hidden_node in self.hidden_nodes:\n total_net_input = hidden_node.bias\n for connection in self.ih_connections:\n if connection.end_node == hidden_node:\n total_net_input += connection.get_weight() * connection.start_node.get_value()\n hidden_node.set_value(self._transfer_function(total_net_input))\n\n # Hidden to Output forward run\n for output_node in self.output_nodes:\n total_net_input = output_node.bias\n for connection in self.ho_connections:\n if connection.end_node == output_node:\n total_net_input += connection.get_weight() * connection.start_node.get_value()\n output_node.set_value(self._transfer_function(total_net_input))\n return [node.get_value() for node in self.output_nodes]\n\n def _transfer_function(self, x):\n \"\"\"Sigmoid function. Please note ALPHA is hardcoded at the beginning of the script\n :param x: a float value to be normalized\n :type x: float\n :returns: float\n \"\"\"\n return 1.0 / (1.0 + exp(-ALPHA * x))\n\n def _back_propagation(self, desired_output, debug):\n ''' Applies back propagation algorithm to hidden-to-output connections first and then\n to input-to-hidden connections.\n :param desired_output: The desired output\n :type desired_output: list\n '''\n # Hidden to output\n for index, output_node in enumerate(self.output_nodes):\n for connection in self.ho_connections:\n if connection.end_node == output_node:\n #delta = self.get_hidden_to_output_delta(connection, desired_output[index], output_node)\n error = desired_output[output_node.id] - output_node.get_value()\n delta = self.process_out_delta(error, connection)\n connection.set_weight(connection.get_weight() + delta)\n\n # Input to hidden\n for connection in self.ih_connections:\n #delta = self.get_input_to_hidden_delta(connection, desired_output)\n #delta = self.get_input_to_hidden_delta2(connection, desired_output)\n delta = self.process_hidden_delta(desired_output, connection)\n if debug:\n log.info(\"from node: %d to node: %d delta: %f\" % (connection.start_node.id,\n connection.end_node.id, delta))\n connection.set_weight(connection.get_weight() + delta)\n\n def process_hidden_delta(self, desired_output, connection):\n ''' delta = NU * ALPHA * activation_H * (1 - activation_H) * Input_i * sum_over_O (v_h,o Eo)\n :rtype: float\n '''\n\n def calculate_sum_of_weithed_errors_for_h(desired_output, hidden_node):\n s = 0\n for connection in self.ho_connections:\n if connection.start_node == hidden_node:\n output_node = connection.end_node\n s += connection.get_weight() * (desired_output[output_node.id] - output_node.get_value())\n return s\n if connection.start_node.get_value() == 0:\n return 0\n else:\n activation_H = connection.end_node.get_value()\n delta = calculate_sum_of_weithed_errors_for_h(desired_output, connection.end_node) * NU * ALPHA * \\\n activation_H * (1 - activation_H) * connection.start_node.get_value()\n return delta\n\n def process_out_delta(self, error, connection):\n ''' delta = NU * ALPHA * error * activation_O * (1 - activation_O) * activation_H\n :rtype: float\n '''\n activation_O = connection.end_node.get_value()\n activation_H = connection.start_node.get_value()\n return NU * ALPHA * error * activation_O * (1 - activation_O) * activation_H\n\n\n '''\n def get_input_to_hidden_delta2(self, connection, desired_output):\n pd_error_wrt_weight = self.get_pd_errors_wrt_hidden_neuron_total_net_input(connection, desired_output) * \\\n connection.end_node.get_value() * (1 - connection.end_node.get_value()) * \\\n connection.start_node.get_value()\n # dEtot/dOut_Hi = out_hi * (1 - out_hi)\n # dOut_Hi/dNet_Hi = Ii\n # dNet_Hi/dwi\n return pd_error_wrt_weight\n\n def get_pd_errors_wrt_hidden_neuron_total_net_input(self, connection, desired_output):\n\n # We need to calculate the derivative of the error with respect to the output of each hidden layer neuron\n # dE/dyⱼ = Σ ∂E/∂zⱼ * ∂z/∂yⱼ = Σ ∂E/∂zⱼ * wᵢⱼ\n d_error_wrt_hidden_neuron_output = 0\n for index, output_node in enumerate(self.output_nodes):\n d_error_wrt_hidden_neuron_output += self.get_pd_errors_wrt_output_neuron_total_net_input(output_node,\n desired_output[index]) * self.get_connection_weight(connection.end_node, output_node)\n # dE_Oi/dNet_Oi\n # dNet_Oi/dNet_Hi\n return d_error_wrt_hidden_neuron_output\n\n def get_pd_errors_wrt_output_neuron_total_net_input(self, output_node, desired_output):\n activation = output_node.get_value()\n return -(desired_output - activation) * activation * (1 - activation)\n\n def get_input_to_hidden_delta(self, connection, desired_output):\n delta = connection.start_node.get_value() * \\\n connection.end_node.get_value() * (1 - connection.end_node.get_value())\n hidden_effect_on_total_error = 0\n for index, output_node in enumerate(self.output_nodes):\n for ho_connection in self.ho_connections:\n if ho_connection.end_node == output_node:\n activation = output_node.get_value()\n hidden_effect_on_total_error += -(desired_output[index] - activation) * \\\n (activation * (1 - activation)) * \\\n connection.get_weight()\n return delta * hidden_effect_on_total_error\n\n def get_hidden_to_output_delta(self, connection, desired_output, output_node):\n activation = output_node.get_value()\n delta = -(desired_output - activation) * \\\n activation * (1 - activation) * \\\n connection.start_node.get_value()\n return delta\n '''\n\n def _sum_of_weighted_output_errors(self, desired_output):\n total_summed_weighted_product = 0\n for index, output_node in enumerate(self.output_nodes):\n summed_weighted_product = 0\n error = output_node.value - desired_output[index]\n for connection in self.ho_connections:\n if connection.end_node == output_node:\n summed_weighted_product += connection.get_weight() * error * self._transfer_function_derivate(\n output_node)\n total_summed_weighted_product += summed_weighted_product\n return total_summed_weighted_product\n\n def _transfer_function_derivate(self, node):\n \"\"\" Derivative of the transfer function.\n :param node: a Node object\n :returns: float\n \"\"\"\n return ALPHA * node.get_value() * (1.0 - node.get_value())\n\n def run(self, input_values):\n \"\"\" This function calculates the output of given inputs from the trained network.\n :param input_values: a list of integers or float values\n :returns: float\n \"\"\"\n for index, node in enumerate(self.input_nodes):\n node.set_value(input_values[index])\n return self._forward_run()\n\n def expose(self):\n \"\"\" This function returns the weights of the neural network\n :returns: a tuple of lists of float values\n \"\"\"\n\n log.info('\\nInput Nodes')\n for node in self.input_nodes:\n log.info('node: %d\\t\\tbias: %f\\t\\tactivation: %f' %(node.id, node.bias, node.get_value()))\n\n log.info('\\nHidden Nodes')\n for node in self.hidden_nodes:\n log.info('node: %d\\t\\tbias: %f\\t\\tactivation: %f' %(node.id, node.bias, node.get_value()))\n\n log.info('\\nOutput Nodes')\n for node in self.output_nodes:\n log.info('node: %d\\t\\tbias: %f\\t\\tactivation: %f' %(node.id, node.bias, node.get_value()))\n\n log.info('\\nInput to Hidden Layer')\n for connection in self.ih_connections:\n log.info('from: %d\\t\\tto: %d\\t\\tweight: %f' % (connection.start_node.id,\n connection.end_node.id,\n connection.get_weight()))\n\n log.info('\\nHidden to Output Layer')\n for connection in self.ho_connections:\n log.info('from: %d\\t\\tto: %d\\t\\tweight: %f' % (connection.start_node.id,\n connection.end_node.id,\n connection.get_weight()))\n\n log.info('\\n***\\n')\n\n\nclass Node(object):\n ''' This object represent a node (aka neuron). It contains its bias and its activation value.\n '''\n def __init__(self, id, bias):\n self.id = id\n self.bias = bias\n self.value = None\n\n def set_value(self, value):\n self.value = value\n\n def get_value(self):\n return self.value\n\n\nclass Connection(object):\n ''' This object represent the synapse entering between two given nodes.\n It contains the starting and ending nodes as well as the weight of the connection.\n '''\n def __init__(self, start_node, end_node, weight):\n self.start_node = start_node\n self.end_node = end_node\n self.weight = weight\n\n def set_weight(self, w):\n self.weight = w\n\n def get_weight(self):\n return self.weight\n\n\ndef main():\n ''' A basic Neural Network by Emiliano Pasqualetti focused on the logical operator XOR.\n Notable limitations:\n 1. The neural network has a single hidden layer.\n 2. 2 nodes per each layer\n 3. No error threshold has been implemented yet. #Fixme\n The code runs on python 2\n '''\n debug = False\n if debug:\n loop = 1\n else:\n loop = 10000\n nn = NeuralNetwork(2, debug)\n logical_operator = XOR()\n nn.train(logical_operator, loop, debug)\n log.info('The neural network has the following weights and output value for the input to hidden layer: ')\n nn.expose()\n\n n1, n2 = nn.run([0, 0])\n log.info('%d XOR %d = %.2f %.2f' % (0, 0, n1, n2))\n n1, n2 = nn.run([0, 1])\n log.info('%d XOR %d = %.2f %.2f' % (0, 1, n1, n2))\n n1, n2 = nn.run([1, 0])\n log.info('%d XOR %d = %.2f %.2f' % (1, 0, n1, n2))\n n1, n2 = nn.run([1, 1])\n log.info('%d XOR %d = %.2f %.2f' % (1, 1, n1, n2))\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"490_deep_learning/w1/pasqualetti_xor_nn_multioutput.py","file_name":"pasqualetti_xor_nn_multioutput.py","file_ext":"py","file_size_in_byte":15172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"291290499","text":"# Wzór Herona\r\n# Obliczanie pola trojkata\r\n# pole = sqrt(p*(p-a)*(p-b)*(p-c))\r\n# p = (a+b+c) / 2\r\n\r\nfrom math import sqrt\r\n\r\n\r\ndef heron(a, b, c):\r\n p = (a+b+c) / 2\r\n pole = p*(p-a)*(p-b)*(p-c)\r\n\r\n if pole >= 0:\r\n pole = sqrt(pole)\r\n print(pole)\r\n else:\r\n print(\"To nie moga byc boki trojkata\")\r\n\r\n\r\nheron(5, 3, 4)\r\nheron(2, 3, 20)","sub_path":"Wzór Herona.py","file_name":"Wzór Herona.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"240723495","text":"from scipy.stats import norm\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nimport csv\nimport pandas as pd\nimport numpy as np\n\n\n# read data from a text file. One number per line\nprice_train = pd.read_csv('Price_Train.csv', header=None).as_matrix()\nprice_train_pred = pd.read_csv('Price_Train_pred.csv', header=None).as_matrix()\n\nmu_total = []\nsigma_total = []\n\nfor i in range(0,24):\n\tdatos = price_train[:,i] - price_train_pred[:,i]\n\n\t# best fit of data\n\t(mu, sigma) = norm.fit(datos)\n\tmu_total.append(mu)\n\tsigma_total.append(sigma)\n\n\t# the histogram of the data\n\tn, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)\n\n\t# add a 'best fit' line\n\ty = mlab.normpdf( bins, mu, sigma)\n\tl = plt.plot(bins, y, 'r--', linewidth=2)\n\n\t#plot\n\tplt.xlabel('Smarts')\n\tplt.ylabel('Probability')\n\tplt.title(r'$\\mathrm{Histogram\\ of\\ IQ:}\\ \\mu=%.3f,\\ \\sigma=%.3f$' %(mu, sigma))\n\tplt.grid(True)\n\n\tplt.show()\n\nx = open('data_obs_price.txt', 'w')\nfor j in range(0,24):\n\tx.write(\"Mean =\" + str(mu_total[j]) + \" Std dev = \" + str(sigma_total[j]) + \" \\n \")\nx.close()","sub_path":"hist_Price.py","file_name":"hist_Price.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441409877","text":"from matplotlib import pyplot as plt\nfrom Functions import Reta\nfrom numpy import arange\n\ndef Circle(var):\n X = []\n Y = []\n lista = [Reta((2,3),u,(1,1)) for u in range(-2,3)]\n\n circle1 = plt.Circle(Reta((2,3),var,(1,1)), 0.2, color='r')\n fig, ax = plt.subplots()\n ax.add_artist(circle1)\n\n for i in range(lista.__len__()):\n for j in range(lista[0].__len__()):\n if j == 0:\n X.append(lista[i][0])\n if j == 1:\n Y.append(lista[i][1])\n\n plt.plot(X,Y,color='orange')\n plt.show()\n\nfor i in arange(-2.0,3.0,0.1):\n Circle(i)","sub_path":"Teste/Circle.py","file_name":"Circle.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"506004649","text":"\"\"\"\nUsing for loop we can iterate the value in a variable.\nWe can iterate list , tuple , set and dictionary values.\n\n\"\"\"\n\n\n\"\"\"a=[1,2,3,4,5,6,7,8,9]\nfor b in a:\n if b==4:\n continue\n print(b)\"\"\"\n\na =[1,2,3,4]\nb=[\"a\",\"b\",\"c\"]\n\nfor x in a:\n for y in b:\n print(x,y)\n\n\n\n","sub_path":"Basic/For_Loop_Concept.py","file_name":"For_Loop_Concept.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"52552025","text":"# -*- coding: utf-8 -*-\nimport pickle\nimport re\nimport sparv.util as util\nfrom nltk import FreqDist, LidstoneProbDist\n\n\ndef make_model(nst_infile, picklefile, protocol=-1):\n \"\"\" Train a POS probability model on the NST lexicon and save it as a pickle file.\n The model is a LidstoneProbDist (NLTK) which has compounded POS tags (SUC set) as keys (e.g. \"NN+NN\")\n and smoothed probabilities as values.\"\"\"\n # Collect all compounds from nst data\n nst_full_compounds = set()\n with open(nst_infile, encoding='UTF-8') as f:\n for line in f:\n fields = line[:-1].split('\\t')\n word = fields[0]\n comp = fields[3].replace(\"!\", \"\")\n pos = fields[4]\n if \"+\" in comp and \"_\" not in word and not (comp.startswith(\"+\") or comp.startswith(\"-\")):\n nst_full_compounds.add((word, comp, pos))\n\n # Build POS probability model\n pos_fdist = FreqDist()\n for _w, _c, pos in nst_full_compounds:\n if '+' in pos:\n pos = re.sub(r\"\\+LN\", \"\", pos)\n pos_fdist[pos] += 1\n\n pd = LidstoneProbDist(pos_fdist, 0.001, pos_fdist.B())\n\n # Save probability model as pickle\n with open(picklefile, \"wb\") as f:\n pickle.dump(pd, f, protocol=protocol)\n\n\nif __name__ == '__main__':\n util.run.main(make_model)\n","sub_path":"sparv/train_nst_comp_model.py","file_name":"train_nst_comp_model.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"143705726","text":"from flask import Flask, render_template, session\nfrom flask import request\nimport json\nimport random\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/home.html\")\ndef home():\n return render_template('index.html')\n\n\n@app.route(\"/index.html\", methods=['POST'])\ndef get_mail():\n email = request.form['Email']\n username = email.split('@')[0]\n call_ansible(username)\n return \"Success\"\n\n\ndef call_ansible(username):\n import paramiko\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect('52.77.220.46', username='cloud_user', password='Pwcwelcome1!')\n stdin, stdout, stderr = client.exec_command('echo' + \" \" + username)\n for line in stdout:\n print('... ' + line.strip('\\n'))\n client.close()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, port=5000)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"513825330","text":"def add_commas(number, seperator = \",\", add_sign = False):\r\n if number == \"\":\r\n return number\r\n if add_sign:\r\n result = \"{:+}\".format(number)\r\n cap = 1\r\n else:\r\n result = str(number)\r\n cap = 0\r\n i = len(result) - 3\r\n while i > cap:\r\n result = result[:i] + seperator + result[i:]\r\n i -= 3\r\n return result\r\n\r\ndef sort_stats(clan, skill_num = 0, gain = False):\r\n unsorted_data = {}\r\n sorted_clan = []\r\n for i, player in enumerate(clan):\r\n if not gain:\r\n j = player.skills[skill_num].rank\r\n else:\r\n j = player.xp_gain\r\n if j > 0:\r\n unsorted_data[j] = unsorted_data.get(j, []) + [i]\r\n for val in sorted(unsorted_data.keys()):\r\n for index in unsorted_data[val]:\r\n sorted_clan.append(clan[index])\r\n if gain:\r\n sorted_clan.reverse()\r\n return sorted_clan\r\n ","sub_path":"parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"127421456","text":"\"\"\"\nDjango development settings for {{ project_name }} project.\n\"\"\"\n\nfrom .base import *\n\nDEBUG = True\n\nINTERNAL_IPS = ['127.0.0.1']\n\nADMINS = [\n # ('Your Name', 'your_email@example.com'),\n]\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '{{ secret_key }}'\n\n# Add django-debug-toolbar\nINSTALLED_APPS.append('debug_toolbar')\nMIDDLEWARE.append('debug_toolbar.middleware.DebugToolbarMiddleware')\nDEBUG_TOOLBAR_PATCH_SETTINGS = False\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n}\n","sub_path":"settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553592033","text":"#!/usr/bin/env python\n\n# Author: Nicole Guymer\n# Date: May, 24 2018\n# File: Angles.py\n# Description: This file calculates the declination angle, solar time, hour angle, altitude angle,\n#\t\t\t\tzenith angle and zaimuth angle for the user given location, date, and time.\n# Note: This file depends on the Calculate_n.py and LocationComponents.py files.\n\n\n\nimport math\nimport LocationComponents as LC\nimport Calculate_n as n\nimport datetime\n\n\nclass Angles():\n\t\n\tdef __init__(self, address, year, month, day, hour, minutes, seconds):\n\t\t\"\"\"Define all the variables in terms of the class.\n\t\tBring in the nth_day value from Calculate_n.py.\n\t\tBring in the location values from LocationComponents.py.\"\"\"\n\t\tself.address = address\n\t\tself.year = year\n\t\tself.month = month\n\t\tself.day = day\n\t\tself.hour = hour\n\t\tself.minutes = minutes\n\t\tself.seconds = seconds\n\t\tself.latitude = float(LC.LocationComponents(self.address).latitude_value())\n\t\tself.longitude = float(LC.LocationComponents(self.address).longitude_value())\n\t\tself.n = float(n.nth_day(self.year, self.month, self.day))\n\t\tself.time = datetime.time(self.hour , self.minutes, self.seconds)\n\n\tdef declination_angle(self):\n\t\t\"\"\"Calculate the declination angle for the given day of the year\"\"\"\n\t\tinside_sin = math.radians((360 * (284 + int(self.n)))/(float(365)))\n\t\t#return float(23.45 * math.sin (( inside_sin) )) #returns a number with units of Degrees\n\t\treturn float(23.45 * math.sin (( inside_sin) )) #returns a number with units of Degrees\n\n\tdef solar_time(self):\n\t\t\"\"\"Calculate the solar time of the given location on the given time and day of the year. \n\t\tThe local standard time (the time shown on your clock at that location) does not match the actual solar time\n\t\tdirectly due to the generalization of the time zones.\n\t\tThe solar time is the true time for a given location.\"\"\"\n\t\tB = (360*( int(n.nth_day(self.year, self.month, self.day))-81) )/float(364) #unit = degrees\n\t\tET = ( (float(9.87)*math.sin(2*math.radians(float(B)))) - (float(7.53)*math.cos(math.radians(float(B)))) - (float(1.5)*math.sin(math.radians(float(B)))))*60 #units = seconds\n\t\tl_st = abs(LC.LocationComponents(self.address).time_zone()*15) #units = degrees\n\t\tLST = datetime.datetime(self.year, self.month, self.day, self.hour, self.minutes, self.seconds)\n\t\tlong_offset = (l_st- abs(self.longitude))*4*60 #units = seconds\n\t\treturn LST + datetime.timedelta(seconds = ET) + datetime.timedelta(seconds = long_offset)\n\n\tdef hour_angle(self):\n\t\t\"\"\"This function calculates the difference between the local time and solar noon, then returns the hour angle.\"\"\"\n\n\t\t#turn the solar time into total seconds (since midnight)\n\t\tseconds_solartime = self.solar_time().hour*3600 + self.solar_time().minute*60 + self.solar_time().second\n\t\tseconds_from_solar_noon = abs(seconds_solartime - 12*3600)#noon in seconds\t\t\n\t\treturn (float(seconds_from_solar_noon)/60)/4 #units = degrees\n\n\tdef altitude_angle(self):\n\t\t\"\"\"Calculate the altitude angle for the given location\"\"\"\n\t\ta = math.sin(math.radians(self.latitude)) * math.sin(math.radians(self.declination_angle()))\n\t\tb = math.cos(math.radians(self.latitude)) * math.cos(math.radians(self.declination_angle())) * math.cos(math.radians(self.hour_angle()))\n\t\tc = a+b\n\t\td = math.asin(c)\n\t\treturn math.degrees(d) #units = degress\n\n\tdef zenith_angle(self):\n\t\t\"\"\"Calulate the zenith angle for the given location\"\"\"\n\t\treturn 90 - self.altitude_angle()\n\n\tdef azimuth_angle(self):\n\t\t\"\"\"Calculate the azimuth angle for the given time, date, and locaton\"\"\"\n\t\tdiv = math.cos(math.radians(self.declination_angle())) * (math.sin(math.radians(self.hour_angle())) / math.cos(math.radians(self.altitude_angle())))\n\t\treturn math.degrees(math.asin(div))\n\n\tdef all_angles(self):\n\t\t\"\"\"Create a text file that holds all the values from the above functions.\n\t\tThis file will have a unique name containing the time, date, and location used for the calculations.\"\"\"\n\n\t\tfilename = 'SolarCalcs_%(address)s_%(year)d_%(month)d_%(day)d_%(hour)d%(minutes)d%(seconds)d.txt' % {'address': self.address[:5], 'year': self.year, 'month' :self.month, 'day': self.day, 'hour':self.hour, 'minutes': self.minutes, 'seconds':self.seconds}\n\t\tst = str(self.solar_time())\n\t\twith open('%s' % filename , 'w') as f:\n\t\t\tf.write('Nth Day of the Year = %f' % self.n)\n\t\t\tf.write('\\nLatitude = %f degrees' % self.latitude)\n\t\t\tf.write('\\nLongitude = %f degrees' %self.longitude)\n\t\t\tf.write('\\nSolar Time = %s' % st)\n\t\t\tf.write('\\nDeclination Angle = %f degrees' % self.declination_angle())\n\t\t\tf.write('\\nHour Angle = %f degrees' % self.hour_angle())\n\t\t\tf.write('\\nAltitude Angle = %f degrees' % self.altitude_angle())\n\t\t\tf.write('\\nZenith Angle = %f degrees' % self.zenith_angle())\n\t\t\tf.write('\\nAzimuth Angle = %f degrees\\n' % self.azimuth_angle())\n\n\n\n","sub_path":"SolarCalcs/Angles.py","file_name":"Angles.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444023172","text":"'''5. write a NumPy program to compute the sum of the diagonal element of a given array(matrix).'''\r\nimport numpy as np\r\na=np.array([[1,2,3],[4,5,6],[7,8,9]])\r\nsum=0\r\nfor i in range(0,len(a)):\r\n for j in range(0,len(a[i])):\r\n if (i==j):\r\n sum=sum+a[i][j]\r\n \r\nprint(sum)\r\n","sub_path":"Assignment-3/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"262837788","text":"import argparse\nimport math\nimport os\nimport os.path as osp\n\nimport joblib\nimport numpy as np\nimport src.ast_toolbox.mcts.BoundedPriorityQueues as BPQ\n# from example_save_trials import *\nimport tensorflow as tf\nfrom CartPole.cartpole_simulator import CartpoleSimulator\n# from garage.tf.algos.trpo import TRPO\nfrom garage.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom garage.misc import logger\nfrom garage.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\nfrom src.ast_toolbox import TRPO\nfrom src.ast_toolbox import ASTEnv\nfrom src.ast_toolbox import TfEnv\nfrom src.ast_toolbox.rewards import ASTRewardS\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # just use CPU\n\n\n# Logger Params\nparser = argparse.ArgumentParser()\nparser.add_argument('--exp_name', type=str, default='cartpole_exp')\nparser.add_argument('--snapshot_mode', type=str, default=\"none\")\nparser.add_argument('--snapshot_gap', type=int, default=10)\nparser.add_argument('--log_dir', type=str, default='./Data/AST/TRPO/Test')\nparser.add_argument('--args_data', type=str, default=None)\nargs = parser.parse_args()\n\n# Create the logger\nlog_dir = args.log_dir\n\ntabular_log_file = osp.join(log_dir, 'process.csv')\ntext_log_file = osp.join(log_dir, 'text.csv')\nparams_log_file = osp.join(log_dir, 'args.txt')\n\nlogger.log_parameters_lite(params_log_file, args)\nlogger.add_text_output(text_log_file)\nlogger.add_tabular_output(tabular_log_file)\nprev_snapshot_dir = logger.get_snapshot_dir()\nprev_mode = logger.get_snapshot_mode()\nlogger.set_snapshot_dir(log_dir)\nlogger.set_snapshot_mode(args.snapshot_mode)\nlogger.set_snapshot_gap(args.snapshot_gap)\nlogger.set_log_tabular_only(False)\nlogger.push_prefix(\"[%s] \" % args.exp_name)\n\nseed = 0\ntop_k = 10\n\ntop_paths = BPQ.BoundedPriorityQueue(top_k)\n\nnp.random.seed(seed)\ntf.set_random_seed(seed)\nwith tf.Session() as sess:\n # Create env\n # data = joblib.load(\"../CartPole/ControlPolicy/itr_\"+str(args.sut_itr)+\".pkl\")\n data = joblib.load(\"../CartPole/Data/Train/itr_5.pkl\")\n sut = data['policy']\n reward_function = ASTRewardS()\n # sut_param = np.copy(sut.get_param_values(trainable=True))\n\n simulator = CartpoleSimulator(sut=sut, max_path_length=100, use_seed=False, nd=1)\n env = ASTEnv(open_loop=False,\n simulator=simulator,\n fixed_init_state=True,\n s_0=[0.0, 0.0, 0.0 * math.pi / 180, 0.0],\n reward_function=reward_function,\n )\n env = TfEnv(env)\n print(env.vectorized)\n # Create policy\n policy = GaussianMLPPolicy(\n name='ast_agent',\n env_spec=env.spec,\n hidden_sizes=(64, 32)\n )\n # policy = GaussianLSTMPolicy(name='lstm_policy',\n # env_spec=ast_spec,\n # hidden_dim=128,\n # use_peepholes=True)\n\n params = policy.get_params()\n sess.run(tf.variables_initializer(params))\n\n # Instantiate the garage objects\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n # optimizer = ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))\n\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=4000,\n step_size=0.1,\n n_itr=5,\n store_paths=True,\n # optimizer= optimizer,\n max_path_length=100,\n top_paths=top_paths,\n plot=False,\n )\n\n algo.train(sess=sess, init_var=False)\n\n # print(np.array_equal(sut_param,sut.get_param_values(trainable=True)))\n\n from src.ast_toolbox.algos.mcts import MCTS\n top_paths2 = BPQ.BoundedPriorityQueue(top_k)\n algo = MCTS(\n env=env,\n stress_test_num=1,\n max_path_length=100,\n ec=100.0,\n n_itr=50,\n k=0.5,\n alpha=0.5, # 0.85,\n clear_nodes=False,\n log_interval=1000,\n top_paths=top_paths2,\n plot_tree=True,\n plot_path=args.log_dir + '/tree'\n )\n\n algo.train()\n\n import src.ast_toolbox.mcts.AdaptiveStressTesting as AST\n import src.ast_toolbox.mcts.ASTSim as ASTSim\n\n # ast_params = AST.ASTParams(100,0,False)\n # ast = AST.AdaptiveStressTest(p=ast_params, env=env, top_paths=top_paths)\n print(\"~~~~~~~~~~~~~~~~~~check TRPO reward consistance~~~~~~~~~~~~~~~\")\n\n for (r, actions) in top_paths:\n print(np.mean(np.clip(actions, -1.0, 1.0)))\n action_seq = [AST.ASTAction(a) for a in actions]\n reward, _ = ASTSim.play_sequence(algo.ast, action_seq, sleeptime=0.0)\n print(\"predic reward: \", r)\n print(\"actual reward: \", reward)\n","sub_path":"examples/CartPoleNd/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"74958666","text":"import sys\r\nimport pygame\r\n\r\n\r\nwidth, height = 640, 480\r\n\r\norigin = 0, height\r\ndest = width, height\r\nspeed = 300\r\n\r\nox = dest[0] - origin[0]\r\noy = dest[1] - origin[1]\r\ndirect = dest[0] > origin[0]\r\na = 0.0045\r\nb = (oy - a*ox**2) / ox\r\nv = dict(x=0, y=0)\r\n\r\n\r\ndef move(clock):\r\n v['x'] += direct * speed * clock.tick(30)/1000.0\r\n v['y'] = a*v['x']**2 + b*v['x']\r\n\r\n\r\ndef main():\r\n pygame.init()\r\n screen = pygame.display.set_mode((width, height))\r\n clock = pygame.time.Clock()\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n move(clock)\r\n\r\n screen.fill((255, 255, 255))\r\n pygame.draw.circle(screen, (0, 0, 255), (int(origin[0]+v['x']), int(origin[1]+v['y'])), 20)\r\n pygame.display.update()\r\n\r\n if direct > 0 and origin[0]+v['x'] >= dest[0] or direct < 0 and origin[0]+v['x'] <= dest[0]:\r\n v['x'] = v['y'] = 0\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"games/demos/parabolas/parabola_origin+dest.py","file_name":"parabola_origin+dest.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"171331245","text":"##################################################################\n# NASNest has good results on the Kaggle leaderboard, so give\n# This uses the model with pretrained ImageNet weights\n# This is training round 1/2\n\nimport os\nfrom datetime import datetime\nfrom keras import Input, layers, Model, callbacks\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras.optimizers import Adam\n\nfrom data_generator import train_gen, valid_gen\nfrom make_plots import make_plots\n\n\ndef main():\n now = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')\n model_name = 'pretrain_NASNet_' + now + '.h5'\n batch_size = 32\n num_epochs = 30\n lr = .0001\n\n num_train_samples = len(os.listdir('./data/train/cancer')) + len(os.listdir('./data/train/healthy'))\n num_valid_samples = len(os.listdir('./data/validation/cancer')) + len(os.listdir('./data/validation/healthy'))\n\n # Build our model\n input_tensor = Input(shape=(96, 96, 3))\n NASNet = NASNetMobile(include_top=False, input_shape=(96, 96, 3))\n x = NASNet(input_tensor)\n x1 = layers.GlobalMaxPooling2D()(x)\n x2 = layers.GlobalAveragePooling2D()(x)\n x3 = layers.Flatten()(x)\n z = layers.Concatenate(axis=-1)([x1, x2, x3])\n z = layers.Dropout(.5)(z)\n output_tensor = layers.Dense(1, activation='sigmoid')(z)\n\n model = Model(input_tensor, output_tensor)\n model.summary()\n\n # Get things ready to train: tweak learning rate, etc.\n model.compile(optimizer=Adam(lr), loss='binary_crossentropy', metrics=['acc'])\n\n train_generator = train_gen(batch_size)\n validation_generator = valid_gen(batch_size)\n\n steps_per_epoch = num_train_samples / batch_size\n validation_steps = num_valid_samples / batch_size\n\n # Basic callbacks\n checkpoint = callbacks.ModelCheckpoint(filepath='./models/' + model_name,\n monitor='val_loss',\n save_best_only=True)\n early_stop = callbacks.EarlyStopping(monitor='val_acc',\n patience=4)\n csv_logger = callbacks.CSVLogger('./logs/' + model_name.split('.')[0] + '.csv')\n\n callback_list = [checkpoint, early_stop, csv_logger]\n\n # Training begins\n history = model.fit_generator(train_generator,\n steps_per_epoch=steps_per_epoch,\n epochs=num_epochs,\n verbose=1,\n callbacks=callback_list,\n validation_data=validation_generator,\n validation_steps=validation_steps)\n\n model.save('./models/' + model_name)\n\n make_plots(history, model_name)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train_NASNet.py","file_name":"train_NASNet.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"78328089","text":"# 四則演算\n\n# 第一パラメータの入力\ndef inputX(x):\n while True:\n x = input('第一パラメータを入力してください: ')\n if x.isnumeric():\n return float(x)\n else:\n print('入力が不正です。やり直してください')\n continue\n\n# 第二パラメータの入力\ndef inputY(y):\n while True:\n y = input('第二パラメータを入力してください: ')\n if y.isnumeric():\n return float(y)\n else:\n print('入力が不正です。やり直してください')\n continue\n\n# 四則演算子の入力\ndef inputFour(user):\n while True:\n user = input('四則演算子を入力してください: ')\n if user in '+-*/':\n return user\n else:\n print('入力が不正です。やり直してください')\n continue\n\n# 四則演算子の特定と計算\ndef fourCul(x, y, user):\n fourCulculate = {\n '+': 0,\n '-': 1,\n '*': 2,\n '/': 3\n }\n if fourCulculate[user] == 0:\n return x + y\n if fourCulculate[user] == 1:\n return x - y\n if fourCulculate[user] == 2:\n return x * y\n if fourCulculate[user] == 3:\n return round((x / y), 3)\n\n# 表示\ndef display(d):\n print('計算結果:{}'.format(d))\n\n# 起動\nif __name__ == '__main__':\n display(fourCul(inputX(0),inputY(0),inputFour(0)))\n","sub_path":"src/basic-c3/task20180719.py","file_name":"task20180719.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"594476633","text":"import telebot # Импортируем библеотеку для Телеграма\r\nfrom telebot import types # Импортируем типы из модуля, чтобы создать кнопки в чат-боте\r\nfrom config import token\r\n\r\n# Создаём объект бота с импользование токена. Токен получаем через чат-бот в Телеграме BotFather\r\nbot = telebot.TeleBot(token)\r\n\r\n# Название кнопок и их содержимое\r\nrcpeo = 'На сайте Республиканского ресурсного центра САПЭО https://rcpeo.bspu.by/ вы можете ознакомиться с предстоящими мероприятиями, а так же просмотреть информацию и '\\\r\n 'материалы по уже прошедшим онлайн-мероприятиям, консультациям и конференциям'\r\ntimetable = 'Вы можете ознакомиться с расписанием консультаций на текущий месяц по ссылке - https://rcpeo.bspu.by/wp-content/uploads/2021/09/sentyabr-2021-a.pdf'\r\nannouncement = 'Анонс предстоящих мероприятий, в которых вы можете принять участия как в качестве докладчика, так и в качестве слушателя https://rcpeo.bspu.by/anons-meropriyatij/'\r\ncontacts = 'Вы можете связаться с нами по телефону:8 (017) 311 23 99, ' \\\r\n 'внутренний тел.: 171,' \\\r\n 'или можете написать нам на e-mail: eo@bspu.by'\r\nschedule = 'График работы:' \\\r\n 'понедельник-ч��тверг: 8:30-12:30, 13:15-17:30,' \\\r\n 'пятница: 8:30-12:30, 13:15-16:15'\r\n\r\n# Декоратор для обработки сообщений\r\n@bot.message_handler(content_types=['text'])\r\n# Метод для обработки сообщений\r\ndef get_text_message(message):\r\n if message.text == 'Привет':\r\n bot.send_message(message.from_user.id, 'Добрый день! '\r\n 'Вы попали в чат-бот Республиканского ресурсного центра \"Сетевая академия педагогики электронного обучения.\"')\r\n\r\n# Создание кнопок\r\n keyboard = types.InlineKeyboardMarkup()\r\n key_rcpeo = types.InlineKeyboardButton(text='Сайт САПЭО', callback_data='rcpeo')\r\n keyboard.add(key_rcpeo) # Добавление кнопки на экран\r\n key_timetable = types.InlineKeyboardButton(text='Расписание консультаций', callback_data='timetable')\r\n keyboard.add(key_timetable)\r\n key_announcement = types.InlineKeyboardButton(text='Анонс мероприятий', callback_data='announcement')\r\n keyboard.add(key_announcement)\r\n key_contacts = types.InlineKeyboardButton(text='Контакты', callback_data='contacts')\r\n keyboard.add(key_contacts)\r\n key_schedule = types.InlineKeyboardButton(text='График работы', callback_data='schedule')\r\n keyboard.add(key_schedule)\r\n\r\n# Выводим все кнопки на экран и оставляем сообщение\r\n bot.send_message(message.from_user.id, text='Выберите интересующую вас информацию', reply_markup=keyboard)\r\n\r\n\r\n\r\n\r\n elif message.text == '/help':\r\n bot.send_message(message.from_user.id, 'Напишите, пожалуйста, Привет, чтобы продолжить.')\r\n else:\r\n bot.send_message(message.from_user.id, 'Извините, я Вас не понимаю, напишите, пожалуйста, /help, чтобы продолжить. Спасибо.')\r\n\r\n# Декоратор для работы кнопок\r\n@bot.callback_query_handler(func=lambda call: True)\r\ndef callback_worker(call):\r\n if call.data == 'rcpeo':\r\n bot.send_message(call.message.chat.id, rcpeo)\r\n elif call.data == 'timetable':\r\n bot.send_message(call.message.chat.id, timetable)\r\n elif call.data == 'announcement':\r\n bot.send_message(call.message.chat.id, announcement)\r\n elif call.data == 'contacts':\r\n bot.send_message(call.message.chat.id, contacts)\r\n elif call.data == 'schedule':\r\n bot.send_message(call.message.chat.id, schedule)\r\n\r\n# Запуск чат-бота\r\nbot.polling(none_stop=True, interval=0)\r\n\r\n\r\n\r\n\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339568993","text":"#!/usr/bin/env python\n\n# Copyright 2017 The Kubernetes 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\n\"\"\"Runs a bigquery query, filters the results, and uploads the filtered and complete data to GCS.\"\"\"\n\nimport argparse\nimport subprocess\nimport sys\nimport time\nimport yaml\n\nDEFAULT_BUCKET = \"gs://k8s-metrics\"\nDEFAULT_PROJECT = \"k8s-gubernator\"\n\ndef check(*cmd, **keyargs):\n \"\"\"Logs and runs the command, raising on errors.\"\"\"\n print >>sys.stderr, 'Run:', cmd\n # If \"stdin_string\" keyword arg is present run command and communicate string to stdin\n if \"stdin\" in keyargs and isinstance(keyargs[\"stdin\"], str):\n in_string = keyargs[\"stdin\"]\n keyargs[\"stdin\"] = subprocess.PIPE\n proc = subprocess.Popen(*cmd, **keyargs)\n proc.communicate(input=in_string)\n return\n subprocess.check_call(*cmd, **keyargs)\n\ndef validate_metric_name(name):\n \"\"\"Validates that a string is useable as a metric name (Can be used as GCS object name).\"\"\"\n if len(name) == 0:\n raise ValueError(\"metric-name cannot be an empty string.\")\n if any(char in name for char in \"\\r\\n[]*?#/\\\\\"):\n raise ValueError(\"metric-name cannot contain any line feeds, carriage returns, or the \"\n \"following characters: []*?#/\\\\\")\n\ndef do_query(query, out_filename, project):\n \"\"\"Executes a bigquery query, outputting the results to a file.\"\"\"\n with open(out_filename, \"w\") as out_file:\n check([\"bq\", \"query\", \"--format=prettyjson\", \"--project_id=\"+project], stdin=query,\n stdout=out_file)\n\ndef do_jq(jqfilter, data_filename, out_filename):\n \"\"\"Executes a jq command on a data file and outputs the results to a file.\"\"\"\n with open(out_filename, \"w\") as out_file:\n check([\"jq\", jqfilter, data_filename], stdout=out_file)\n\ndef run_metric(project, bucket_path, metric, query, jqfilter):\n \"\"\"Executes a query, filters the results, and uploads filtered and complete results to GCS.\"\"\"\n fulldata_filename = metric + time.strftime(\"-%Y-%m-%d.json\")\n latest_filename = metric + \"-latest.json\"\n\n do_query(query, fulldata_filename, project)\n do_jq(jqfilter, fulldata_filename, latest_filename)\n check([\"gsutil\", \"-h\", \"Cache-Control:private, max-age=0, no-transform\", \"cp\",\n fulldata_filename, latest_filename, bucket_path + metric + \"/\"])\n\ndef main(configs, project, bucket_path):\n \"\"\"Loads metric config files and runs each metric.\"\"\"\n if not project:\n raise ValueError(\"project-id cannot be an empty string.\")\n if not bucket_path:\n raise ValueError(\"bucket cannot be an empty string.\")\n if bucket_path[-1] != '/':\n bucket_path += '/'\n\n # the 'bq show' command is called as a hack to dodge the config prompts that bq presents\n # the first time it is run. A newline is passed to stdin to skip the prompt for default project\n # when the service account in use has access to multiple projects.\n check([\"bq\", \"show\"], stdin=\"\\n\")\n\n errs = []\n for config_raw in configs:\n try:\n config = yaml.load(config_raw)\n if not config:\n raise ValueError(\"{} does not contain a valid yaml document.\"\n \"\".format(config_raw.name))\n\n validate_metric_name(config[\"metric\"])\n run_metric(project, bucket_path, config[\"metric\"], config[\"query\"], config[\"jqfilter\"])\n except Exception as exception: # pylint: disable=broad-except\n errs += exception\n finally:\n config_raw.close()\n\n if len(errs) > 0:\n raise Exception(*errs)\n\n\nif __name__ == '__main__':\n PARSER = argparse.ArgumentParser(description=\n \"Run BigQuery query and output filtered JSON to file.\")\n PARSER.add_argument(\"--config\",\n required=True,\n action=\"append\",\n type=argparse.FileType('r'),\n help=\"A JSON config file describing a metric. This option may be listed \"\n \"multiple times to run multiple metrics.\")\n PARSER.add_argument(\"--project-id\",\n required=False,\n type=str,\n default=DEFAULT_PROJECT,\n help=\"The GCS project id to use for the bigquery query.\")\n PARSER.add_argument(\"--bucket\",\n required=False,\n type=str,\n default=DEFAULT_BUCKET,\n help='The GCS bucket path to upload output to. Files will be uploaded to a'\n ' subdir rooted at this path and named with the metric name. Defaults to \"'\n + DEFAULT_BUCKET + '\".')\n\n ARGS = PARSER.parse_args()\n main(ARGS.config, ARGS.project_id, ARGS.bucket)\n","sub_path":"scenarios/bigquery.py","file_name":"bigquery.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"68038326","text":"from typing import List\n\n\nclass Solution:\n # https://www.bilibili.com/video/BV1N541177Bk?from=search&seid=1830710312737531822\n # Using Reverse\n # Time complexity: O(n).\n # Space complexity: O(1).\n #时间复杂度:O(n),其中 nn 为数组的长度。每个元素被翻转两次,一共 n 个元素,因此总时间复杂度为 O(2n)=O(n)。\n #空间复杂度:O(1)。\n\n def rotate(self, nums: List[int], k: int) -> None:\n def reverse(nums, lo, hi):\n while lo < hi:\n nums[lo], nums[hi] = nums[hi], nums[lo]\n lo += 1\n hi -= 1\n\n if len(nums) == 1:\n return\n n = len(nums)\n k %= n\n reverse(nums, 0, n - 1) # reverse all nums\n reverse(nums, 0, k - 1) # reverse 0 to k - 1, left part\n reverse(nums, k, n - 1) # reverse the right part\n\n # https://leetcode.com/problems/rotate-array/solution/\n def rotate4(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n for i in range(k):\n # nums = [nums.pop()]+ nums\n nums.insert(0, nums.pop())\n\n # brute force\n # Time complexity: O(n×k).\n # Space complexity: O(1).\n def rotate1(self, nums: List[int], k: int) -> None:\n k %= len(nums)\n for i in range(k):\n previous = nums[-1]\n for j in range(len(nums)):\n nums[j], previous = previous, nums[j]\n\n # extra array\n # Time complexity: O(n).\n # Space complexity: O(n).\n def rotate2(self, nums: List[int], k: int) -> None:\n n = len(nums)\n a = [0] * n\n for i in range(n):\n a[(i + k) % n] = nums[i]\n nums[:] = a\n\n # Using Cyclic Replacements\n # Time complexity: O(n).\n # Space complexity: O(1).\n def rotate3(self, nums: List[int], k: int) -> None:\n n = len(nums)\n k %= n\n\n start = count = 0\n while count < n: # if count is n, all nums are cycled.\n current, prev = start, nums[start] # save current and pre\n while True:\n next_idx = (current + k) % n\n nums[next_idx], prev = prev, nums[next_idx] # move prev to next_idx, next_idx is next replacement position\n current = next_idx\n count += 1\n\n if start == current: # if current becomes start, it returns to the start position, break and continue start + 1\n break\n start += 1\n\n\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n nums = [1, 2, 3, 4, 5]\n print(\"before rotate:{}\".format(nums))\n solution.rotate(nums, 2)\n print(\"after rotate:{}\".format(nums))\n nums = [1, 2, 3, 4, 5]\n solution.rotate4(nums, 2)\n print(\"after rotate:{}\".format(nums))\n","sub_path":"Array/189-RotateArray.py","file_name":"189-RotateArray.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373411517","text":"from sqlalchemy.orm import Session\n\nfrom .models import Comment, CommentRead\n\n\ndef create(*, db_session: Session, current_user: str, post_id: int, comment_in: CommentRead):\n \"\"\"Create new Comment\"\"\"\n comment = Comment(**dict(comment_in))\n\n comment.post_id = post_id\n comment.owner_user_id = current_user\n comment.last_editor_user_id = current_user\n\n db_session.add(comment)\n db_session.commit()\n\n return comment\n","sub_path":"src/qanet/comment/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469009868","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 29 19:19:45 2021\n\nAuthor: Josef Perktold\nLicense: BSD-3\n\n\"\"\"\n\nimport numpy as np\nfrom . import transforms\n\n\nclass ArchimedeanCopula(object):\n\n def __init__(self, transform):\n self.transform = transform\n\n def cdf(self, u, args=()):\n '''evaluate cdf of multivariate Archimedean copula\n '''\n axis = -1\n phi = self.transform.evaluate\n phi_inv = self.transform.inverse\n cdfv = phi_inv(phi(u, *args).sum(axis), *args)\n # clip numerical noise\n out = cdfv if isinstance(cdfv, np.ndarray) else None\n cdfv = np.clip(cdfv, 0., 1., out=out) # inplace if possible\n return cdfv\n\n def pdf(self, u, args=()):\n '''evaluate cdf of multivariate Archimedean copula\n '''\n axis = -1\n u = np.asarray(u)\n if u.shape[-1] > 2:\n msg = \"pdf is currently only available for bivariate copula\"\n raise ValueError(msg)\n # phi = self.transform.evaluate\n # phi_inv = self.transform.inverse\n phi_d1 = self.transform.deriv\n phi_d2 = self.transform.deriv2\n\n cdfv = self.cdf(u, args=args)\n\n pdfv = - np.product(phi_d1(u, *args), axis)\n pdfv *= phi_d2(cdfv, *args)\n pdfv /= phi_d1(cdfv, *args)**3\n\n return pdfv\n\n def logpdf(self, u, args=()):\n '''evaluate cdf of multivariate Archimedean copula\n '''\n # TODO: replace by formulas, and exp in pdf\n axis = -1\n u = np.asarray(u)\n if u.shape[-1] > 2:\n msg = \"pdf is currently only available for bivariate copula\"\n raise ValueError(msg)\n\n phi_d1 = self.transform.deriv\n phi_d2 = self.transform.deriv2\n\n cdfv = self.cdf(u, args=args)\n\n # I need np.abs because derivatives are negative,\n # is this correct for mv?\n logpdfv = np.sum(np.log(np.abs(phi_d1(u, *args))), axis)\n logpdfv += np.log(np.abs(phi_d2(cdfv, *args) / phi_d1(cdfv, *args)**3))\n\n return logpdfv\n\n\nclass FrankCopula(ArchimedeanCopula):\n\n # explicit BV formulas copied from Joe 1997 p. 141\n # todo: check expm1 and log1p for improved numerical precision\n def __init__(self):\n super(FrankCopula, self).__init__(transforms.TransfFrank())\n\n def cdf(self, u, args=()):\n u = np.asarray(u)\n th = args[0]\n if u.shape[-1] == 2:\n # bivariate case\n u1, u2 = u[..., 0], u[..., 1]\n b = 1 - np.exp(-th)\n cdf = - np.log(1 - (1 - np.exp(- th * u1)) *\n (1 - np.exp(- th * u2)) / b) / th\n return cdf\n else:\n super(FrankCopula, self).pdf(u, args=args)\n\n def pdf(self, u, args=()):\n u = np.asarray(u)\n th = args[0]\n if u.shape[-1] == 2:\n # bivariate case\n u1, u2 = u[..., 0], u[..., 1]\n b = 1 - np.exp(-th)\n pdf = th * b * np.exp(- th * (u1 + u2))\n pdf /= (b - (1 - np.exp(- th * u1)) * (1 - np.exp(- th * u2)))**2\n return pdf\n else:\n super(FrankCopula, self).pdf(u, args=args)\n\n def logpdf(self, u, args=()):\n u = np.asarray(u)\n th = args[0]\n if u.shape[-1] == 2:\n # bivariate case\n u1, u2 = u[..., 0], u[..., 1]\n b = 1 - np.exp(-th)\n pdf = np.log(th * b) - th * (u1 + u2)\n pdf -= 2 * np.log(b - (1 - np.exp(- th * u1)) *\n (1 - np.exp(- th * u2)))\n return pdf\n else:\n super(FrankCopula, self).pdf(u, args=args)\n\n def cdfcond_2g1(self, u, args=()):\n u = np.asarray(u)\n th = args[0]\n if u.shape[-1] == 2:\n # bivariate case\n u1, u2 = u[..., 0], u[..., 1]\n cdfc = np.exp(- th * u1)\n cdfc /= np.expm1(-th) / np.expm1(- th * u2) + np.expm1(- th * u1)\n return cdfc\n else:\n raise NotImplementedError\n\n def ppfcond_2g1(self, q, u1, args=()):\n u1 = np.asarray(u1)\n th = args[0]\n if u1.shape[-1] == 1:\n # bivariate case, conditional on value of first variable\n ppfc = - np.log(1 + np.expm1(- th) /\n ((1 / q - 1) * np.exp(-th * u1) + 1)) / th\n\n return ppfc\n else:\n raise NotImplementedError\n","sub_path":"statsmodels/distributions/copula/archimedean.py","file_name":"archimedean.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593111779","text":"'''\nCreated on Aug 9, 2016\n\n@author: Ross Kitsis\n'''\n\nfrom netaddr import *\nimport math\n\nclass Subnet(object):\n '''\n This class manages subnets allowing users to create multiple\n subnets by specifying the number of networks and the base network IP and the base subnet mask\n Using the number of bits required to create that many subnets, those bits are subtracted from the\n original subnet mask to create multiple subnets with the same netmask\n \n Required netaddr, install instructions:\n pip install netaddr\n \n '''\n \n def create_subnets(self):\n '''\n Create the specified number of subnets \n '''\n \n num_bits_net = int (math.ceil (math.ceil(math.log(self.__num_net,2))))\n newSubnet = self.__subnet_length - num_bits_net\n \n newNetwork = self.__network + \"/\" + str(newSubnet)\n \n network = IPNetwork(newNetwork)\n \n subs = list(network.subnet(self.__subnet_length))\n \n subs = subs[:self.__num_net]\n \n #print len(subs)\n \n #print num_bits_net\n #print list(subs)\n \n return subs\n \n def __init__(self, network, num_net, subnet_length):\n '''\n Network - Base network address\n num_net - Number of networks to be created (Integer)\n subnet_length - number of bits in subnet mask\n '''\n self.__network = network\n self.__num_net = int(num_net)\n self.__subnet_length = int(subnet_length)\n \n ","sub_path":"Scale/create_subnet.py","file_name":"create_subnet.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"182719706","text":"#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nPI= 3.1415926535897\n\nx = 0\ny = 0\nyaw = 0\nz = 0\nno_of_rotation = 1\n\ndef posecallback(pose_msg):\n \n print('callback called')\n\ndef move():\n \n print('move function has been initiated')\n pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size =10)\n vel_msg = Twist()\n\n #sub = rospy.Subscriber('/turtle1/pose',Pose, posecallback)\n \n rate = rospy.Rate(10)\n \n square_side = 20\n turtle_speed = 0.5\n turtle_yawrate = 0.5 \n rotation_time = 4*PI/2/turtle_yawrate \n \n # fixed vel commands, no need to change further\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n\n while not rospy.is_shutdown():\n\n t0 = float(rospy.Time.now().to_sec())\n #print('time count started')\n current_distance = 0\n while current_distance < square_side:\n vel_msg.linear.x = turtle_speed\n vel_msg.angular.z = 0\n pub.publish(vel_msg)\n #print('moving in straigth line')\n t1 = float(rospy.Time.now().to_sec())\n\n current_distance = current_distance + (t1-t0)*turtle_speed\n print('moving in straight line, current distance= ',format(current_distance))\n rate.sleep()\n\n #stop turtlebot\n vel_msg.linear.x = 0\n vel_msg.angular.z = turtle_yawrate\n pub.publish(vel_msg)\n print('turtlebot has been stopped') # stop turtlebot by using rospy.spin()\n #rospy.spin()\n break\n\ndef rotate():\n print('Rotate function has been initiated')\n pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size =10)\n vel_msg = Twist()\n \n rate = rospy.Rate(10)\n yaw_rate = 0.5 #in rad/sec\n angle = 90*(2*PI/360)\n \n # fixed vel commands, no need to change further\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = yaw_rate\n\n while not rospy.is_shutdown():\n t0 = float(rospy.Time.now().to_sec())\n current_angle = 0\n while (current_angle < angle):\n pub.publish(vel_msg)\n t1 = float(rospy.Time.now().to_sec())\n current_angle = yaw_rate*(t1-t0)\n \n vel_msg.angular.z = 0\n pub.publish(vel_msg)\n #rospy.spin()\n print('rotation complete')\n break\n \nif __name__ == '__main__':\n try:\n #move in square loop\n rospy.init_node('open_loop_square', anonymous = True)\n print('open loop square node has been initiated')\n global z\n global no_of_rotation\n while z < 4*no_of_rotation:\n print('this is loop no.',format(z+1))\n move()\n rotate()\n z =z+1\n print('mission success') \n except rospy.ROSInterruptException: pass\n\n\n## trash\n\n #Checking if the movement is forward or backwards\n \n","sub_path":"catkin_ws/src/assignment2_ws/scripts/move_sqaure_openloop.py","file_name":"move_sqaure_openloop.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"654280445","text":"import numpy as np\n\n\ndef calculate_cost(solution: tuple, max_takes: int, costs: tuple) -> int:\n \"\"\"\n Calculate the real cost of a single solution.\n\n :param solution: a flat list of takes, representing a complete or partial solution.\n :param max_takes: the max allowed number of takes per session.\n :param costs: a two dimensions list of all takes with their corresponding needed actors.\n\n :return: the cost of the solution.\n \"\"\"\n # Solution total cost.\n solution_cost = 0\n # Takes per session counter.\n takes_count = 0\n session_cost = None\n session_is_full = False\n\n for take in solution:\n takes_count += 1\n # Whether a session reached its max allowed takes.\n session_is_full = takes_count == max_takes\n # Use a numpy array to ease bitwise operations.\n take_cost = np.array(costs[take])\n # Use bitwise 'or' operation to join the takes' costs per session,\n # as an actor gets paid the same amount regardless of his takes by session.\n session_cost = take_cost if session_cost is None else session_cost | take_cost\n\n if session_is_full:\n # Total cost is the cost sum of all sessions.\n solution_cost += session_cost.sum()\n # Reset session cost and counters.\n session_cost = None\n takes_count = 0\n\n # Sum last session if partial, as it would not have been previously added.\n if not session_is_full and session_cost is not None:\n solution_cost += session_cost.sum()\n\n return solution_cost\n","sub_path":"seminar/src/SolutionCost.py","file_name":"SolutionCost.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"432666977","text":"import matplotlib.pyplot as plt\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\n\n# Input pointcloud: (?, 3)\ndef show_pointcloud_fromarray(pointcloud, winname='PointCloud'):\n fig = plt.figure(dpi=500)\n ax = fig.add_subplot(111, projection='3d')\n minZ = 1000000\n maxZ = -1000000\n for i in range(pointcloud.shape[0]):\n point = pointcloud[i]\n if point[2] < minZ:\n minZ = point[2]\n elif point[2] > maxZ:\n maxZ = point[2]\n cm = plt.get_cmap(\"viridis\")\n colors = []\n for i in range(pointcloud.shape[0]):\n rate = math.fabs(pointcloud[i, 1] - minZ) / (maxZ - minZ)\n colors.append(cm(rate))\n ax.scatter(\n pointcloud[:, 2],\n pointcloud[:, 0],\n pointcloud[:, 1],\n cmap='spectral',\n c=colors,\n s=3.0,\n linewidths=0,\n alpha=1,\n marker='.'\n )\n plt.title(winname)\n # ax.axis('scaled')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_xlim(-1, 1)\n ax.set_ylim(-1, 1)\n ax.set_zlim(-1, 1)\n plt.show()","sub_path":"scripts/utils/matplot_viewer.py","file_name":"matplot_viewer.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"177285129","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^genre/(?P\\w+)/$', views.books_by_genre, name='bookGenre'),\n url(r'^techValleyTimes/$', views.get_tech_valley_books, name='techValleyTimes'),\n url(r'^topRatedBooks/$', views.get_book_by_rating, name='topRatedBooks'),\n url(r'^topSellingBooks/$', views.get_book_by_amount_sold, name='topSellingBooks'),\n url(r'^bookDetail/(?P.*)/', views.get_book_details, name='bookDetail'),\n url(r'^review/$', views.get_review_form, name='addBookReview'),\n url(r'^bookByAuthor/(?P<author_id>.*)/$', views.get_book_by_author, name='bookByAuthor'),\n url(r'search/$', views.search, name=\"search\"),\n]","sub_path":"bookstore/products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"102838894","text":"'''\n项目:文件的读取与保存\n'''\nfrom tkinter import *\nimport tkinter.filedialog \nclass FileEditor():\n def __init__(self):\n window = Tk()\n window.title(\"Simple Text Editor\")\n menubar = Menu(window)\n window.config(menu = menubar)\n operationMenu = Menu(menubar,tearoff = 0)\n menubar.add_cascade(label = \"File\",menu = operationMenu)\n operationMenu.add_command(label = \"Open\",command = self.openFile)\n operationMenu.add_command(label = \"Save\",command = self.saveFile)\n self.frame = Frame(window)\n self.frame.grid(row = 1,column = 1,sticky = W)\n Button(self.frame,text = \"Open\",command = self.openFile).\\\n grid(row = 1,column = 1,sticky = W)\n Button(self.frame,text = \"Save\",command = self.saveFile).\\\n grid(row = 1,column = 2)\n self.frame1 = Frame(window)\n self.frame1.grid(row = 2,column = 1)\n self.scrollbar = Scrollbar(self.frame1)\n self.scrollbar.pack(side = \"right\",fill = Y)\n self.text = Text(self.frame1,width = 40,height = 20,wrap = WORD,\\\n yscrollcommand = self.scrollbar.set)\n self.text.pack()\n self.scrollbar.config(command = self.text.yview)\n window.mainloop()\n def openFile(self):\n filenameforReading = tkinter.filedialog.askopenfilename()\n infile = open(filenameforReading,'r')\n self.text.insert(END,infile.read())\n infile.close()\n def saveFile(self):\n filenameforWriting = tkinter.filedialog.asksaveasfilename()\n outfile = open(filenameforWriting,'w')\n outfile.write(self.text.get(1.0,END))\n outfile.close()\nFileEditor()\n","sub_path":"python/文件对话框.py","file_name":"文件对话框.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20559903","text":"testCases = int(input(\"Enter number of test cases: \"))\nif(1 <= testCases <= 200):\n for j in range(1, testCases + 1):\n numOfElements = int(input(\"Enter number of Element: \"))\n inputNum = input(\"Enter Elements: \").split(\" \")\n if((numOfElements - 1) != len(inputNum)):\n print(\"Inputs doesn't match\")\n continue\n else:\n for i in range(0, numOfElements):\n try:\n if((i + 1) != int(inputNum[i])):\n print(\"Missing number: \", i + 1)\n break\n except IndexError:\n print(\"Missing number: \", i + 1)\nelse:\n exit\n","sub_path":"missingNumInArray.py","file_name":"missingNumInArray.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"140390636","text":"#%%\n\nimport pandas as pd\nimport json_lines\nimport numpy as np\nimport os\nimport json\nfrom ast import literal_eval\nfrom utils import spacy_word_mask_to_spans, f1\nfrom utils import spans_to_ents, nlp, add_ents\nimport ast\nimport csv\nimport itertools\nimport string\nimport sys\n\nSPECIAL_CHARACTERS = string.whitespace\n\ndef _contiguous_ranges(span_list):\n \"\"\"Extracts continguous runs [1, 2, 3, 5, 6, 7] -> [(1,3), (5,7)].\"\"\"\n output = []\n for _, span in itertools.groupby(\n enumerate(span_list), lambda p: p[1] - p[0]):\n span = list(span)\n output.append((span[0][1], span[-1][1]))\n return output\n\n\ndef fix_spans(spans, text, special_characters=SPECIAL_CHARACTERS):\n \"\"\"Applies minor edits to trim spans and remove singletons.\"\"\"\n cleaned = []\n for begin, end in _contiguous_ranges(spans):\n while text[begin] in special_characters and begin < end:\n begin += 1\n while text[end] in special_characters and begin < end:\n end -= 1\n if end - begin > 1:\n cleaned.extend(range(begin, end + 1))\n return cleaned\n\ndef to_doccano(entities, text):\n ''' \n {\n \"text\": \"EU rejects German call to boycott British lamb.\", \n \"labels\": [ [0, 2, \"ORG\"], [11, 17, \"MISC\"], ... ]\n } \n \n '''\n return { \"text\" : text, \"labels\": list(entities)}\n\ndef write_doccano_dataset(pr_df, fold = 'all'):\n \n pr_df['TRUE_pred_spans'] = pr_df.spans\n\n for method in ['ELECTRA', 'ROBERTA', 'BASELINE', 'ALBERT', 'TRUE']:\n pr_df['doc'] = pr_df.text.apply(nlp)\n pr_df['%s_entities' % method] = pr_df.apply( lambda row : \\\n spans_to_ents(row.doc, set(row['%s_pred_spans' % method]), method), axis = 1 )\n\n output_path = os.path.join('/home/burtenshaw/now/spans_toxic/data/doccano')\n\n singles = []\n\n for method in [\"ELECTRA\", \"ROBERTA\", \"BASELINE\", 'ALBERT', 'TRUE']:\n col = '%s_entities' % method\n output = pr_df[[col, 'text']].apply(lambda row : (row.text, row[col]), axis = 1).to_list()\n singles.append(output)\n\n together = []\n\n for z in zip(*singles):\n labels = [[list(e) for e in m[1]] for m in z]\n labels = [item for sublist in labels for item in sublist]\n text = z[0][0]\n together.append(to_doccano(labels, text))\n\n with open(os.path.join(output_path, 'models_%s.jsonl' % fold), 'w') as f:\n for line in together[:2500]:\n f.write('%s\\n' % json.dumps(line))\n\n# %%\n# df = pd.read_pickle('data/all/eval.bin')\n# sub_path = '/home/burtenshaw/now/spans_toxic/predictions/submit/spans-pred_ELECTRA_0.6578636624699009.txt'\n# with open(sub_path, 'r') as f :\n# spans = f.readlines()\n# df['spans'] = spans\n# df.spans = df.spans.apply(lambda x : literal_eval(x.split('\\t')[1]))\n# df['clean_spans'] = df.apply(lambda row : fix_spans(row.spans, row.text), axis = 1)\n\ndf = pd.read_csv('data/tsd_test.csv')\ndf['spans'] = df.spans.apply(literal_eval)\n\n#%%\ndf['doc'] = df.text.apply(nlp)\ndf['entities'] = df.apply( lambda row : spans_to_ents(row.doc, set(row.spans), 'TRUE'), axis = 1 )\n# %%\noutput = df.apply(lambda row : to_doccano(row.entities, row.text), axis = 1).to_list()\noutput_path = os.path.join('/home/burtenshaw/now/spans_toxic/data/doccano')\n\nwith open(os.path.join(output_path, 'true_labels.jsonl'), 'w') as f:\n for line in output:\n f.write('%s\\n' % json.dumps(line))\n# %%\ndata= []\nwith open(os.path.join(output_path, 'electra_check.json'), 'r') as f:\n for line in f.readlines():\n data.append(json.loads(line.strip('\\n'))['labels'])\n# %%\n\ndf['checked'] = data\n# %%\ndef ents_to_spans(ents, text, special_characters=SPECIAL_CHARACTERS):\n \"\"\"Applies minor edits to trim spans and remove singletons.\"\"\"\n cleaned = []\n for begin, end, _ in ents:\n end -= 1\n while text[begin] in special_characters and begin < end:\n begin += 1\n while text[end] in special_characters and begin < end:\n end -= 1\n if end - begin > 1:\n cleaned.extend(range(begin, end + 1))\n return cleaned\n\ndf['checked_cleaned'] = df.apply(lambda row : ents_to_spans(row.checked, row.text), axis = 1)\n# %%\ndf['cont_ranges'] = df.spans.apply(_contiguous_ranges)\nout = df.checked_cleaned.to_list()\n# %%\nfrom submit import to_submit\n\nto_submit(out, output_path='/home/burtenshaw/now/spans_toxic/predictions/submit/spans-pred_electra_cleaned.txt')\n# %%\n","sub_path":"to_doccano.py","file_name":"to_doccano.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"592688361","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\nfrom mapek_framework import Group, Interaction\nfrom mapek_framework.components import AnalyzeComponent, PlanComponent\n\n\nclass MyAnalyzeComponent(AnalyzeComponent):\n\n input_interactions = [\n Interaction('light_status', String)\n ]\n output_interactions = [\n Interaction('master_analyze_plan', String)\n ]\n\n def on_interaction_received(self, interaction, payload):\n light, status = payload.data.split(' ')\n self.knowledge[int(light)] = status\n self.send_interaction('master_analyze_plan', light)\n\n\nclass MyPlanComponent(PlanComponent):\n\n input_interactions = [\n Interaction('master_analyze_plan', String)\n ]\n output_interactions = [\n Interaction('switch_light', String)\n ]\n\n def on_interaction_received(self, interaction, payload):\n light = int(payload.data)\n if light % 2 == 0:\n self.send_interaction('switch_light', '%d on' % light)\n elif light != 0 and self.knowledge.get(light - 1, 'ko') == 'ko':\n self.send_interaction('switch_light', '%d on' % light)\n else:\n self.send_interaction('switch_light', '%d off' % light)\n\n\nclass MasterGroup(Group):\n elements = [MyAnalyzeComponent, MyPlanComponent]\n\n\ndef main():\n master = MasterGroup('master')\n master.spin()\n\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"mapek_framework_demo/nodes/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"393235999","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# COPYRIGHT (C) NEC CORPORATION 2016\n\nMETHOD_GET = 'GET'\nMETHOD_POST = 'POST'\nMETHOD_PUT = 'PUT'\nMETHOD_DELETE = 'DELETE'\nMETHOD_HEAD = 'HEAD'\n\nKEY_TOKEN = '_TOKEN'\nKEY_ENDPOINT = '_ENDPOINT'\nKEY_REQUESTID = '_REQUESTID'\n\nExce_Message_01 = 'error args key'\nExce_Message_02 = 'error GET REST I/F'\nExce_Message_03 = 'error POST REST I/F'\nExce_Message_04 = 'error PUT REST I/F'\nExce_Message_05 = 'error DELETE REST I/F'\nExce_Message_06 = 'error memcached of token id'\nExce_Message_07 = 'error memcached of endpoint'\nExce_Message_08 = 'error ENDPOINT was not found.'\nExce_Message_08 += ' Probably, you do not have authority.'\nExce_Message_09 = 'error OpenStack Non Response'\nExce_Message_10 = 'error memcached set'\nExce_Message_11 = 'error update quotas'\nExce_Message_12 = 'error endpoint not defined in config'\n","sub_path":"nec_portal/api/AwsClient/S3/conf/AwsClientS3Const.py","file_name":"AwsClientS3Const.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"594271819","text":"import os\ndef read():\n with open(os.getcwd()+os.sep+'Data'+os.sep+'doc.txt','r',encoding='utf-8')as f :\n list = []\n for line in f.readlines():\n list.append(tuple(line.strip().split(',')))\n\n return list\n\n\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"476818669","text":"# -- coding: utf-8 --\nimport os\nfrom flask import Flask, request, render_template, redirect, request\nfrom flask_mail import Mail, Message\nfrom flask_wtf import FlaskForm, CSRFProtect\nfrom wtforms import StringField, TextAreaField, SubmitField, Form\nfrom wtforms.validators import DataRequired, Email\nfrom form_contact import ContactForm, csrf\n\nmail = Mail()\napp = Flask(__name__)\nSECRET_KEY = os.urandom(32)\napp.config['SECRET_KEY'] = SECRET_KEY\ncsrf.init_app(app)\napp.config['MAIL_SERVER']='smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = 'polarbear9612@gmail.com'\napp.config['MAIL_PASSWORD'] = 'kimjiyeon1'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\n\nmail.init_app(app)\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n form = ContactForm()\n if form.validate_on_submit():\n print('-------------------------')\n print(request.form['name'])\n print(request.form['email'])\n print(request.form['subject'])\n print(request.form['message'])\n print('-------------------------')\n send_message(request.form)\n return redirect('/')\n return render_template('index.html', form=form)\n\n@app.route('/success')\ndef success():\n return render_template('index.html')\n\ndef send_message(message):\n print(message.get('name'))\n\n msg = Message(message.get('subject'), sender = message.get('email'),\n recipients = ['jiyunkim.study@gmail.com'],\n body= message.get('message')\n ) \n mail.send(msg)\n\n\nif __name__ =='__main__':\n app.run(debug=True)","sub_path":"venv/bfweb.py","file_name":"bfweb.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"406915036","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/rearrange-spaces-between-words/\n\nLC1592, LC68, LC2138\n\"\"\"\nclass Solution(object):\n def reorderSpaces(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n tokens = text.split()\n if len(tokens) == 1:\n return tokens[0] + ' '*(len(text) - len(tokens[0]))\n \n numSpaces = len(text) - sum(len(t) for t in tokens)\n gapLength = numSpaces / (len(tokens)-1)\n res = (' '*gapLength).join(tokens)#.replace('#', )\n return res + ' '*(len(text) - len(res))\n\n","sub_path":"Easy/LC1592.py","file_name":"LC1592.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"539549854","text":"#!/usr/bin/env python3\n\nimport random # for testing\n\nclass Date(object):\n \"\"\"Model a date\"\"\"\n\n MONTH_INFO = {\n 1: (31, 'January'),\n 2: (28, 'February'),\n 3: (31, 'March'),\n 4: (30, 'April'),\n 5: (31, 'May'),\n 6: (30, 'June'),\n 7: (31, 'July'),\n 8: (31, 'August'),\n 9: (30, 'September'),\n 10: (31, 'October'),\n 11: (30, 'November'),\n 12: (31, 'December'),\n }\n\n DAYS_IN_YEAR = 365\n\n def __init__(self, day, month, year):\n # It is assumed that the supplied argument represents a correct date (eg: no overflows, correct month and day numbers, etc).\n self.day = day\n self.month = month\n self.year = year\n # If the date needs to be normalised, the following won't work:\n # new_date = Date.from_days(date.to_days())\n # instead it is up to the lazy bastard that is the user of this program to code his or her own normalise() function\n\n def __str__(self):\n return '{:d} {:s} {:d}'.format(self.day, Date.MONTH_INFO[self.month][1], self.year)\n\n def __gt__(self, other):\n \"\"\"Return if one date is greater than another\"\"\"\n return self.to_days() > other.to_days()\n\n def to_days(self):\n days = 0\n\n days += self.day\n for i in range(1, self.month):\n days += Date.MONTH_INFO[i][0]\n\n days += self.year*Date.DAYS_IN_YEAR\n\n return days\n\n @classmethod\n def from_days(cls, days):\n year = 0\n month = 1\n day = 1\n\n while Date.DAYS_IN_YEAR < days:\n days -= Date.DAYS_IN_YEAR\n year += 1\n\n while Date.MONTH_INFO[month][0] < days:\n days -= Date.MONTH_INFO[month][0]\n month += 1\n\n day = days\n\n return cls(day, month, year)\n\n def increment_by_N(self, N):\n total_days = self.to_days() + N\n other = Date.from_days(total_days)\n self.day, self.month, self.year = other.day, other.month, other.year\n\ndef main():\n d1 = Date(1, 3, 1973)\n d2 = Date(23, 11, 2012)\n print(d1)\n print(d2)\n\n print(d1.to_days())\n print(d2.to_days())\n d3 = Date(32, 12, 2012)\n d = d3.to_days()\n print(d)\n print(Date.from_days(d))\n\n # Compare two dates\n assert(d2 > d1)\n\n # Increment by 1 day\n d2.increment_by_N(1)\n print(d2)\n\n # Increment by 365 days\n d2.increment_by_N(365)\n print(d2)\n\n # Increment by 800 days\n d2.increment_by_N(800)\n print(d2)\n\n # d2.increment_by_N(365+333+31+31+1)\n # print(d2)\n\n # hardcore tests - randomly generated dates\n\n # date needing normalisation\n # d4 = Date(50, 13, 0)\n # print(d4)\n # print(from_days(to_days(d4)))\n\nif __name__ == '__main__':\n main()","sub_path":"year1_1718/computer_programming_2/exam-questions-and-practice/date_121.py","file_name":"date_121.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"347880770","text":"import numpy as np\nfrom theano import config, shared, function\nimport theano.tensor as t\nfrom ae.encoder import AutoEncoder\nfrom nn.convolutionalLayer import ConvolutionalLayer\nfrom theano.tensor.nnet.conv import conv2d\n\nclass ConvolutionalAutoEncoder(ConvolutionalLayer, AutoEncoder) :\n '''This class describes a Contractive AutoEncoder (CAE) for a convolutional\n layer. This differs from the normal CAE \n\n If the decoded message matches the original input, the encoders is\n considered lossless. Otherwise the loss is calculated and the encoder \n is updated, so it can better encode the input when encountered again.\n Over time the object will extract regular patterns in the data which\n are frequently encountered.\n\n CAEs can be stacked and trained in a greedy layerwise manner, and the\n trained CAEs can be used to initialize a Neural Network into a better\n regularized state than random initialization. Lastly this technique can\n be used when the amount of unlabeled data far outweighs the amount of \n labeled data.\n\n layerID : unique name identifier for this layer\n inputSize : (batch size, channels, rows, columns)\n kernelSize : (number of kernels, channels, rows, columns)\n downsampleFactor : (rowFactor, columnFactor)\n learningRate : learning rate for all neurons\n contractionRate : variance (dimensionality) reduction rate\n None uses '1 / numNeurons'\n dropout : rate of retention in a given neuron during training\n NOTE: input layers should be around .8 or .9\n hidden layers should be around .5 or .6\n output layers should always be 1.\n initialHidThresh : thresholds to initialize the forward network\n None generates random thresholds for the layer\n initialVisThresh : thresholds to initialize the backward network\n None generates random thresholds for the layer\n activation : the sigmoid function to use for activation\n this must be a function with a derivative form\n randomNumGen : generator for the initial weight values\n '''\n def __init__ (self, layerID, inputSize, kernelSize, \n downsampleFactor, learningRate=0.001,\n dropout=None, contractionRate=None,\n initialWeights=None, initialHidThresh=None,\n initialVisThresh=None, activation=t.nnet.sigmoid,\n randomNumGen=None) :\n ConvolutionalLayer.__init__(self, layerID=layerID,\n inputSize=inputSize,\n kernelSize=kernelSize,\n downsampleFactor=downsampleFactor,\n learningRate=learningRate,\n dropout=dropout,\n initialWeights=initialWeights,\n initialThresholds=initialHidThresh,\n activation=activation, \n randomNumGen=randomNumGen)\n AutoEncoder.__init__(self, 1. / np.prod(kernelSize[:]) if \\\n contractionRate is None else \\\n contractionRate)\n\n # setup initial values for the hidden thresholds\n if initialVisThresh is None :\n initialVisThresh = np.zeros((self._inputSize[1],), \n dtype=config.floatX)\n self._thresholdsBack = shared(value=initialVisThresh, borrow=True)\n\n def _setActivation(self, out) :\n from theano.tensor import round\n return round(out) if self._activation is None else \\\n round(self._activation(out))\n\n def __getstate__(self) :\n '''Save network pickle'''\n from dataset.shared import fromShared\n dict = ConvolutionalLayer.__getstate__(self)\n dict['_thresholdsBack'] = fromShared(self._thresholdsBack)\n # remove the functions -- they will be rebuilt JIT\n if 'reconstruction' in dict : del dict['reconstruction']\n if '_costs' in dict : del dict['_costs']\n if '_updates' in dict : del dict['_updates']\n if 'trainLayer' in dict : del dict['trainLayer']\n return dict\n\n def __setstate__(self, dict) :\n '''Load network pickle'''\n from theano import shared\n # remove any current functions from the object so we force the\n # theano functions to be rebuilt with the new buffers\n if hasattr(self, 'reconstruction') : delattr(self, 'reconstruction')\n if hasattr(self, '_costs') : delattr(self, '_costs')\n if hasattr(self, '_updates') : delattr(self, '_updates')\n if hasattr(self, 'trainLayer') : delattr(self, 'trainLayer')\n ConvolutionalLayer.__setstate__(self, dict)\n initialThresholdsBack = self._thresholdsBack\n self._thresholdsBack = shared(value=initialThresholdsBack, borrow=True)\n\n def _unpool_2d(self, input, upsampleFactor) :\n '''This method performs the opposite of pool_2d. This uses the index\n which produced the largest input during pooling in order to produce\n the sparse upsample.\n '''\n op = t.signal.pool.Pool(ds=upsampleFactor, ignore_border=True, \n st=None, padding=(0, 0), mode='max')\n return op.grad((self._prePoolingInput[1],), (input,))[0]\n\n def _getWeightsBack(self) :\n '''Calculate the weights used for decoding.'''\n kernelSize = self.getKernelSize()\n kernelBackSize = (kernelSize[1], kernelSize[0], \n kernelSize[2], kernelSize[3])\n return t.reshape(self._weights, (kernelBackSize))\n\n def _decode(self, input) :\n weightsBack = self._getWeightsBack()\n deconvolve = conv2d(input, weightsBack, self.getFeatureSize(), \n weightsBack.shape.eval(), border_mode='full')\n out = deconvolve + self._thresholdsBack.dimshuffle('x', 0, 'x', 'x')\n return out if self._activation is None else self._activation(out)\n\n def finalize(self, networkInput, layerInput) :\n '''Setup the computation graph for this layer.\n networkInput : the input variable tuple for the network\n format (inClass, inTrain)\n layerInput : the input variable tuple for this layer\n format (inClass, inTrain)\n '''\n from nn.costUtils import calcLoss, leastSquares, calcSparsityConstraint\n ConvolutionalLayer.finalize(self, networkInput, layerInput)\n\n weightsBack = self._getWeightsBack()\n\n # setup the decoder --\n # this take the output of the feedforward process as input and\n # and runs the output back through the network in reverse. The net\n # effect is to reconstruct the input, and ultimately to see how well\n # the network is at encoding the message.\n unpooling = self._unpool_2d(self.output[1], self._downsampleFactor)\n decodedInput = self._decode(unpooling)\n\n # DEBUG: For Debugging purposes only\n self.reconstruction = function([networkInput[0]], decodedInput)\n\n sparseConstr = calcSparsityConstraint(self.output[0], \n self.getOutputSize())\n\n # compute the jacobian cost of the output --\n # This works as a sparsity constraint in case the hidden vector is\n # larger than the input vector.\n jacobianMat = conv2d(unpooling * (1 - unpooling), weightsBack,\n self.getFeatureSize(), weightsBack.shape.eval(), \n border_mode='full')\n jacobianCost = leastSquares(jacobianMat, self._inputSize[0], \n self._contractionRate)\n\n # create the negative log likelihood function --\n # this is our cost function with respect to the original input\n # NOTE: The jacobian was computed however takes much longer to process\n # and does not help convergence or regularization. It was removed\n cost = calcLoss(self.input[0], decodedInput, self._activation) / \\\n self.getInputSize()[0]\n self._costs = [cost, jacobianCost, sparseConstr]\n\n gradients = t.grad(t.sum(self._costs), self.getWeights())\n self._updates = [(weights, weights - self._learningRate * gradient)\n for weights, gradient in zip(self.getWeights(), \n gradients)]\n\n # TODO: this needs to be stackable and take the input to the first\n # layer, not just the input of this layer. This will ensure\n # the other layers are activated to get the input to this layer\n # DEBUG: For Debugging purposes only\n self.trainLayer = function([networkInput[0]], self._costs,\n updates=self._updates)\n\n def buildDecoder(self, input) :\n '''Calculate the decoding component. This should be used after the\n encoder has been created. The decoder is ran in the opposite\n direction.\n '''\n # NOTE: the output may come back as a different shape than it left\n # so we reshape here just in case.\n return self._decode(self._unpool_2d(\n t.reshape(input, self.getOutputSize()), self._downsampleFactor))\n\n def getWeights(self) :\n '''Update to account for the decode thresholds.'''\n return [self._weights, self._thresholds, self._thresholdsBack]\n def getUpdates(self) :\n '''This allows the Stacker to build the layerwise training.'''\n return (self._costs, self._updates)\n\n # DEBUG: For Debugging purposes only\n def saveReconstruction(self, image, ii) :\n from dataset.debugger import saveNormalizedImage\n saveNormalizedImage(np.resize(self.reconstruction(image), (28, 28)),\n 'chip_' + str(ii) + '_reconst.png')\n\n\nif __name__ == '__main__' :\n import argparse, logging, time\n from dataset.reader import ingestImagery, pickleDataset\n from dataset.debugger import saveTiledImage\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--log', dest='logfile', type=str, default=None,\n help='Specify log output file.')\n parser.add_argument('--level', dest='level', default='INFO', type=str, \n help='Log Level.')\n parser.add_argument('--contraction', dest='contraction', default=0.1, \n type=float, help='Rate of contraction.')\n parser.add_argument('--learn', dest='learn', type=float, default=0.01,\n help='Rate of learning on AutoEncoder.')\n parser.add_argument('--kernel', dest='kernel', type=int, default=6,\n help='Number of kernels in Convolutional Layer.')\n parser.add_argument('data', help='Directory or pkl.gz file for the ' +\n 'training and test sets')\n options = parser.parse_args()\n\n # setup the logger\n log = logging.getLogger('CAE: ' + options.data)\n log.setLevel(options.level.upper())\n formatter = logging.Formatter('%(levelname)s - %(message)s')\n stream = logging.StreamHandler()\n stream.setLevel(options.level.upper())\n stream.setFormatter(formatter)\n log.addHandler(stream)\n\n # NOTE: The pickleDataset will silently use previously created pickles if\n # one exists (for efficiency). So watch out for stale pickles!\n train, test, labels = ingestImagery(pickleDataset(\n options.data, batchSize=100, \n holdoutPercentage=0, log=log), shared=False, log=log)\n\n input = t.ftensor4()\n ae = ConvolutionalAutoEncoder('cae', input, train[0].shape[1:], \n (options.kernel,train[0].shape[2],5,5), \n (2,2))\n ae.writeWeights(0)\n for ii in range(100) :\n start = time.time()\n for jj in range(len(train[0])) :\n ae.train(train[0][jj])\n ae.writeWeights(ii+1)\n\n saveTiledImage(\n image=ae.reconstruction(train[0][0]),\n path=ae.layerID + '_cae_filters_reconstructed_' +\n str(ii+1) + '.png', imageShape=(28, 28), spacing=1,\n interleave=True)\n","sub_path":"trunk/modules/python/ae/convolutionalAE.py","file_name":"convolutionalAE.py","file_ext":"py","file_size_in_byte":12534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"146759679","text":"from twisted.web import resource\n\n\ndef build_resource_tree(res, children):\n \"\"\"\\\n Concisely specify a tree of web resources.\n\n @param res: a twisted web resource.\n @param children: a dict of {path, child}. Child is a (recursively\n structured) dict, or a twisted web resource.\n\n @return: res\n \"\"\"\n\n res.isLeaf = False\n\n for path, child in children.iteritems():\n if isinstance(child, dict):\n # Create a new generic resource then recursively populate it:\n child = build_resource_tree(resource.Resource(), child)\n\n res.putChild(path, child)\n\n return res\n","sub_path":"dockomorph/web/restree.py","file_name":"restree.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"562389509","text":"import os\nimport sys\nimport csv\nsys.path.insert(0, '../tools/')\nsys.path.insert(0, '../')\n\nfrom multiprocessing import Queue, Process\n\nfrom tools.WikiTextTools import WikiTextTools\nfrom model_config import CONFIG, LOGGER\nfrom WikiFixerNNet import WikiFixerNNet\n\nfrom fixer_evaluation import get_diff_log, get_diff_distance, get_eval_metrics, compare_diff_logs\nfrom test_script import compare_diff_logs_timeout\n\ntext_test_noise = []\n\n\ndef get_test_dataset(datafile=None,k=[],i1=None,i2=None,sample_size=None):\n global text_test_noise\n global text_test_org\n tools = WikiTextTools()\n if datafile:\n df = tools.read_parquet_df(datafile)\n else:\n df = tools.read_parquet_df(CONFIG.DATASET_FILE_NAME)\n if sample_size:\n df = df.sample(sample_size)\n text_test_noise = df[\"pageTextNoisy\"].tolist()[i1: i2]\n text_test_org= df[\"contentsOriginal\"].tolist()[i1: i2]\n else:\n if k:\n df_valid = df[df['k'] in k]\n else:\n df_valid = df[df['k'] == CONFIG.k]\n\n text_test_noise = df_valid[\"pageTextNoisy\"].tolist()[i1:i2]\n text_test_org = df_valid[\"contentsOriginal\"].tolist()[i1: i2]\n\n\nclass FixerNNet_Worker(Process):\n def __init__(self, gpuid, queue):\n Process.__init__(self, name='ModelProcessor')\n self._gpuid = gpuid\n self._queue = queue\n self.fixer = WikiFixerNNet()\n\n def run(self):\n import csv\n # set enviornment\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(self._gpuid)\n\n # load models\n self.fixer.load_model()\n\n LOGGER.info('s2snet init done %s' % self._gpuid)\n csv_file = open(CONFIG.PREDICTION_CSV_FILE_NAME, mode='a')\n fieldnames = ['i', 'Emetric','score'] # 'p']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n while True:\n rowX = self._queue.get()\n if rowX is None:\n self._queue.put(None)\n break\n LOGGER.info('Woker {} Starting index {}'.format(self._gpuid, str(rowX['i'])))\n p_ind = rowX['i']\n p_text = text_test_noise[p_ind]\n p_otext= text_test_org[p_ind] \n\n fixed_text = self.fixer.fix_text(p_text)\n\n original_logs = get_diff_log(p_text, p_otext)\n fixed_logs = get_diff_log(p_text, fixed_text)\n ot = compare_diff_logs_timeout(original_logs, fixed_logs)\n\n TP, FN, FP, DN = len(ot[0]), len(ot[1]), len(ot[2]), len(ot[3])\n score = TP-5.0*FP\n\n #writer.writerow({'i': rowX['i'], 'p': fixed_text})\n writer.writerow({'i': rowX['i'], 'Emetric': [TP, FN, FP, DN],'score':score})\n LOGGER.info('Woker {} Ending index {}'.format(self._gpuid, str(rowX['i'])))\n\n LOGGER.info('s2snet done %s' % self._gpuid)\n\n\nclass Scheduler:\n def __init__(self, gpuids):\n self._queue = Queue()\n self._gpuids = gpuids\n\n self.__init_workers()\n\n def __init_workers(self):\n self._workers = list()\n for gpuid in self._gpuids:\n self._workers.append(FixerNNet_Worker(gpuid, self._queue))\n\n def start(self):\n\n # put all of files into queue\n for i in range(len(text_test_noise)):\n self._queue.put({\"i\": i})\n\n # add a None into queue to indicate the end of task\n self._queue.put(None)\n\n # start the workers\n for worker in self._workers:\n worker.start()\n\n # wait all fo workers finish\n for worker in self._workers:\n worker.join()\n LOGGER.info(\"all of workers have been done\")\n\n\ngpus_list = ['GPU:0',\n 'GPU:1',\n 'GPU:2',\n 'GPU:3',\n 'GPU:4',\n 'GPU:5',\n 'GPU:6',\n 'GPU:7']\n\n\ndef init_pred_file():\n csv_file = open(CONFIG.PREDICTION_CSV_FILE_NAME, mode='w')\n fieldnames = ['i', 'p']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n csv_file.close()\n\n\ndef run(gpuids):\n # create the preds csv file\n init_pred_file()\n # get test set\n get_test_dataset(sample_size=10)\n # init scheduler\n scheduler = Scheduler(gpuids)\n # start processing and wait for complete\n scheduler.start()\n\n\nif __name__ == '__main__':\n run(gpus_list)\n","sub_path":"tests/multiproc_evaluation.py","file_name":"multiproc_evaluation.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"328279216","text":"# Run a program that prompts a user for a number,\n# and then multiplies that number by itself\n\n\n#This is the first step, prompting a user\n#Converting string to int\nuser_input = int(input(\"Please enter a number: \"))\n\n#This is the second step, mutiplying the input\nresult = user_input * user_input \n\n#Final step, return the result\nprint(result)\n\n\n\n","sub_path":"prompt_for_number.py","file_name":"prompt_for_number.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"265617625","text":"import gensim\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom features.feature_template import RowWiseFeatureCreatorBase\nfrom features.transform import nltk_tokenize\nfrom features.utils import common_feature_parser, get_stop_words\n\n\nclass FeatureCreator(RowWiseFeatureCreatorBase):\n def __init__(self, options):\n super().__init__(options)\n self.model = None\n\n @staticmethod\n def get_num_rows(data):\n return len(data)\n\n def calculate_row_feature(self, row_):\n row = row_[1]\n swords = get_stop_words()\n q1 = [word for word in str(row['question1']).split() if word not in swords]\n q2 = [word for word in str(row['question2']).split() if word not in swords]\n\n wq1 = []\n wq2 = []\n for word in q1:\n try:\n wq1.append(self.model[word])\n except:\n continue\n for word in q2:\n try:\n wq2.append(self.model[word])\n except:\n continue\n\n distance = np.zeros((len(wq1), len(wq2)))\n for i1, w1 in enumerate(wq1):\n for i2, w2 in enumerate(wq2):\n distance[i1, i2] = np.dot(w1, w2)\n\n maximum = 0\n for i1 in range(len(wq1)):\n minimum = 1e10\n for i2 in range(len(wq2)):\n minimum = min(minimum, distance[i1, i2])\n maximum = max(maximum, minimum)\n\n for i2 in range(len(wq2)):\n minimum = 1e10\n for i1 in range(len(wq1)):\n minimum = min(minimum, distance[i1, i2])\n maximum = max(maximum, minimum)\n return maximum\n\n def calculate_features(self, data):\n values = np.zeros(self.get_num_rows(data))\n for i, value in tqdm(enumerate(map(self.calculate_row_feature, self.get_row_wise_iterator(data)))):\n values[i] = value\n return values\n\n @staticmethod\n def get_row_wise_iterator(data):\n return data.iterrows()\n\n def prepare(self):\n self.model = gensim.models.KeyedVectors.load_word2vec_format('data/input/glove.840B.300d.bin',\n binary=True)\n self.model.init_sims(replace=True)\n\n def read_data(self, data_file):\n return nltk_tokenize(data_file)\n\n\ndef main():\n parser = common_feature_parser()\n options = parser.parse_args()\n feature_creator = FeatureCreator(options)\n feature_creator.create()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"features/118_glove_maximum_cosine.py","file_name":"118_glove_maximum_cosine.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"648651531","text":"#!/usr/bin/python3\n\"\"\"Starts a Flask web application\"\"\"\nfrom flask import Flask, render_template\nfrom models import storage\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef remove_session(response_or_exc):\n \"\"\"Removes the current SQLAlchemy Session\n \"\"\"\n storage.close()\n\n\n@app.route('/cities_by_states', strict_slashes=False)\ndef show_cities_by_states():\n \"\"\"Shows all Cities by State instances\n \"\"\"\n data = storage.all('State')\n states = []\n for k, v in data.items():\n states.append(v)\n return render_template('8-cities_by_states.html', states=states)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"web_flask/8-cities_by_states.py","file_name":"8-cities_by_states.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104882408","text":"from jsonschema import validate, draft7_format_checker\nfrom jsonschema.exceptions import SchemaError, ValidationError\n\nschema = {\n # 该关键字用于指定JSON Schema版本: draft-07\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n # 描述对应的JSON元素,title相对来说,更加简洁\n \"title\": \"book info\",\n # 描述对应的JSON元素,description更加倾向于详细描述相关信息\n \"description\": \"some information about book\",\n # 该关键字用于限定待校验JSON元素所属的数据类型,取值可为:object,array,integer,number,string,boolean,null\n \"type\": \"object\",\n # 用于指定JSON对象中的各种不同key应该满足的校验逻辑,\n # 如果待校验JSON对象中所有值都能够通过该关键字值中定义的对应key的校验逻辑,每个key对应的值,都是一个JSON Schema,则待校验JSON对象通过校验。\n \"properties\": {\n \"id\": {\n \"description\": \"The unique identifier for a book\",\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"name\": {\n \"description\": \"book name\",\n \"type\": \"string\",\n \"minLength\": 3,\n \"maxLength\": 30\n },\n \"info\": {\n \"description\": \"simple information about book\",\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 60\n },\n \"price\": {\n \"description\": \"book price\",\n \"type\": \"number\",\n # 能被0.5整除\n \"multipleOf\": 0.5,\n # 这里没有取等,5.0<price<99999.0\n \"minimum\": 5.0,\n \"maximum\": 99999.0,\n # 若使用下面这两个关键字则 5.0<=price<=99999.0\n # \"exclusiveMinimum\": 5.0,\n # \"exclusiveMaximum\": 99999.0\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": [\n {\n \"type\": \"string\",\n \"minLength\": 2,\n \"maxLength\": 8\n },\n {\n \"type\": \"number\",\n \"minimum\": 1.0\n }\n ],\n # 待校验JSON数组第一个元素是string类型,且可接受的最短长度为5个字符,第二个元素是number类型,且可接受的最小值为10\n # 剩余的其他元素是string类型,且可接受的最短长度为2。\n \"additonalItems\": {\n \"type\": \"string\",\n \"miniLength\": 2\n },\n # 至少一个\n \"miniItems\": 1,\n # 最多5个\n \"maxItems\": 5,\n # 值为true时,所有元素都具有唯一性时,才能通过校验。\n \"uniqueItems\": True\n },\n \"date\": {\n \"description\": \"书籍出版日期\",\n \"type\": \"string\",\n # 可以是以下取值:date、date-time(时间格式)、email(邮件格式)、hostname(网站地址格式)、ipv4、ipv6、uri等。\n # 使用format关键字时,在实例化validator时必须给它传format_checker参数,值如:draft7_format_checker, 网址:\n # https://python-jsonschema.readthedocs.io/en/latest/validate/#jsonschema.Draft7Validator\n \"format\": \"date\",\n },\n \"bookcoding\": {\n \"description\": \"书籍编码\",\n \"type\": \"string\",\n # 符合该关键字指定的正则表达式,才算通过校验。\n \"pattern\": \"^[A-Z]+[a-zA-Z0-9]{12}$\"\n },\n \"other\": {\n \"description\": \"其他信息\",\n \"type\": \"object\",\n \"properties\": {\n \"info1\": {\n \"type\": \"string\"\n },\n \"info2\": {\n \"type\": \"string\"\n }\n }\n }\n },\n # 指定了待校验JSON对象可以接受的最少 一级key 的个数\n \"minProperties\": 3,\n # 指定了待校验JSON对象可以接受的最多 一级key 的个数。\n \"maxProperties\": 7,\n # patternProperties对象的每一个一级key都是一个正则表达式,value都是一个JSON Schema。\n # 只有待校验JSON对象中的一级key,通过与之匹配的patternProperties中的一级正则表达式,对应的JSON Schema的校验,才算通过校验。\n # 下面的JSON Schema表示, 所有以a开头的一级key的value都必须是number,\n \"patternProperties\": {\n \"^a\": {\n \"type\": \"number\"\n },\n },\n # 如果待校验JSON对象中存在,既没有在properties中被定义,又没有在patternProperties中被定义,那么这些一级key必须通过additionalProperties的校验。\n \"additionalProperties\": {\n \"desc\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n },\n # 该关键字限制了JSON对象中必须包含哪些一级key。\n # 如果一个JSON对象中含有required关键字所指定的所有一级key,则该JSON对象能够通过校验。\n \"required\": [\"id\", \"name\", \"info\", \"price\"]\n}\n\njson_data = {\n \"id\": 1,\n \"name\": \"jarvis手册\",\n \"info\": \"贾维斯平台使用手册1\",\n \"price\": 5.5,\n \"tags\": [\"jar\"],\n \"date\": \"2019-5-25\",\n \"other\": {\n \"info1\": \"1111\",\n \"info2\": \"222\"\n }\n}\n\n\ntry:\n validate(instance=json_data, schema=schema, format_checker=draft7_format_checker)\nexcept SchemaError as e:\n print(\"验证模式schema出错:\\n出错位置:{}\\n提示信息:{}\".format(\" --> \".join([i for i in e.path]), e.message))\nexcept ValidationError as e:\n print(\"json数据不符合schema规定:\\n出错字段:{}\\n提示信息:{}\".format(\" --> \".join([i for i in e.path]), e.message))\nelse:\n print(\"验证成功!\")","sub_path":"modules/t_jsonschema/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"510326641","text":"import wpilib, ctre, math, logging\nfrom wpilib.drive import MecanumDrive\nfrom networktables import NetworkTables\nfrom wpilib import CameraServer\nimport numpy\nimport math\nfrom enum import Enum\nimport logging\nimport sys\nimport time\nimport threading\n\ncond = threading.Condition()\nnotified = False\n\ndef connectionListener(connected, info):\n\tprint(info, '; Connected=%s' % connected)\n\twith cond:\n\t\tnotified = True \n\t\tcond.notify()\n\n# To see messages from networktables, you must setup logging \nNetworkTables.initialize() \nNetworkTables.addConnectionListener(connectionListener, immediateNotify=True)\nsd = NetworkTables.getTable('SmartDashboard') \n\nsd.getValue('adjust_x', 0)\nsd.getValue('adjust_y', 0)\nsd.getValue('adjust_z', 0)\n\nlogging.basicConfig(level=logging.DEBUG)\n\nclass Job:\n\tdef __init__(self):\n\t\tself.function = ''\n\t\tself.parameters = '()'\n\t\tself.driveLock = False\n\t\t\n\nclass Queue:\n\t\n\tdef __init__(self):\n\t\tself.queue = list()\n\t\t\n\t# add puts the item at the back of the list\n\tdef add(self, item):\n\t\tself.queue.insert(0, item)\n\t\t\n\t# peek will return the value of the item at the beginning of the list, without removing it\n\tdef peek(self):\n\t\tQueueLength = len(self.queue)\n\t\tif QueueLength > 0:\n\t\t\treturn(self.queue[QueueLength - 1])\n\t\telse:\n\t\t\treturn()\n\t\t\n\t# remove will return the value of the item at the beginning of the list, and remove it\n\tdef remove(self):\n\t\tif len(self.queue) > 0:\n\t\t\treturn(self.queue.pop())\n\t\telse:\n\t\t\treturn()\n\nclass MyRobot(wpilib.TimedRobot):\n\tdef __init__(self):\n\t\tself.ticksPerInchPulley = 30 # 30 ticks per inch is just a guess, the number is probably different\n\t\tself.ticksPerInchLifter = 30\n\t\tself.ticksPerInchWheels = 30\n\t\tself.ticksPerInchCrabbing = 31\n\t\tself.pulleyDeadbandInches = 0.5 #how many inches we are okay with the pulley being off (to avoid the jiggle)\n\t\t\n\t\tself.spinBarDeadBand = 400 # ticks, or about 1/10 of a rotation, which is about 36 degrees\n\t\tself.ticksPerRevolution = 4096\n\t\t\n\t\tself.queue = Queue()\n\t\t\n\t\t# switches\n\t\tself.leftLeadScrewDown = 5\n\t\tself.leftLeadScrewUp = 4\n\t\tself.rightLeadScrewDown = 3\n\t\tself.rightLeadScrewUp = 2\n\t\tself.spinBarIn = 14\n\t\tself.spinBarOut = 15\n\t\tself.manualPulleyUp = 7\n\t\tself.manualPulleyDown = 6\n\t\tself.selector1 = 8\n\t\tself.selector2 = 11\n\t\tself.selector3 = 12\n\t\tself.selector4 = 13\n\t\t\n\t\t\n\t\t# buttons\n\t\tself.eStop = 1\n\t\tself.manualHatchDeposit = 1\n\t\tself.autoHatchDeposit = 4\n\t\tself.autoCargoDeposit = 3\n\t\tself.hatchCollectHeight = 7\n\t\tself.autoCargoShipDeposit = 8\n\t\tself.pulleyReset = 6\n\t\tself.hab1to2 = 10\n\t\tself.hab1to3 = 9\n\t\tself.hab2to3 = 2\n\t\t\n\t\tself.buttonsChannel2 = 2\n\t\tself.buttonsChannel1 = 1\n\t\tself.driveJoystickChannel = 0\n\t\t\n\t\tself.ds = wpilib.DriverStation.getInstance()\n\t\tself.driveStick = wpilib.Joystick(self.driveJoystickChannel)\n\t\tself.auxiliary1 = wpilib.Joystick(self.buttonsChannel1)\n\t\tself.auxiliary2 = wpilib.Joystick(self.buttonsChannel2)\n\t\t\n\t\tself.extraHeight = 1 # this is the distance (in inches) that the robot will raise above each hab level before going back down\n\t\t\n\t\tself.Lifter1to2 = 6 + self.extraHeight # these measurements are in inches\n\t\tself.Lifter1to3 = 18 + self.extraHeight\n\t\tself.Lifter2to3 = 12 + self.extraHeight\n\t\tself.lifterSpeed = .7\n\t\t\n\t\tself.selector0to1voltage = 0.5\n\t\tself.selector1to2voltage = 1.5\n\t\tself.selector2to3voltage = 2.5\n\t\t\n\t\tself.levelSelectorAnalogChannel = 0\n\t\tself.IRSensorAnalogChannel = 1\n\t\t\n\t\tself.IRSensor = wpilib.AnalogInput(self.IRSensorAnalogChannel)\n\t\t\n\t\tself.bottomPulleyHallEffectChannel = 0\n\t\tself.topPulleyHallEffectChannel = 1\n\t\tself.topLeftLeadScrewHallEffectChannel = 7\n\t\tself.topRightLeadScrewHallEffectChannel = 3\n\t\tself.bottomLeftLeadScrewHallEffectChannel = 9\n\t\tself.bottomRightLeadScrewHallEffectChannel = 5\n\t\t\n\t\t\n\t\t\n\t\tself.bottomPulleyHallEffect = wpilib.DigitalInput(self.bottomPulleyHallEffectChannel)\n\t\tself.topPulleyHallEffect = wpilib.DigitalInput(self.topPulleyHallEffectChannel)\n\t\tself.topLeftLeadScrewHallEffect = wpilib.DigitalInput(self.topLeftLeadScrewHallEffectChannel)\n\t\tself.topRightLeadScrewHallEffect = wpilib.DigitalInput(self.topRightLeadScrewHallEffectChannel)\n\t\tself.bottomLeftLeadScrewHallEffect = wpilib.DigitalInput(self.bottomLeftLeadScrewHallEffectChannel)\n\t\tself.bottomRightLeadScrewHallEffect = wpilib.DigitalInput(self.bottomRightLeadScrewHallEffectChannel)\n\t\t\n\t\tself.IRSensorThreshold = 2.5\n\t\t\n\t\tself.bottomPulleyHallEffectThreshold = 1\n\t\tself.topPulleyHallEffectThreshold = 1\n\t\tself.topLeftLeadScrewHallEffectThreshold = 1\n\t\tself.topRightLeadScrewHallEffectThreshold = 1\n\t\tself.bottomLeftLeadScrewHallEffectThreshold = 1\n\t\tself.bottomRightLeadScrewHallEffectThreshold = 1\n\t\t\n\t\tself.crab1 = -1 # these are the distances that the robot will crab onto the different hab levels, in inches\n\t\tself.crab2 = -2\n\t\tself.crab3 = -12\n\t\tself.crab4 = -2\n\t\tself.crab5 = -4\n\t\tself.crabSpeed = 0.5\n\t\t\n\t\tself.hatch1Height = 20 # these are measurements off of the ground, and will change depending on how far the pulley is off the ground\n\t\tself.hatch2Height = 48 # at the bottom (the measurements are in inches)\n\t\tself.hatch3Height = 76\n\t\tself.hatchDepositSpeed = 0.1\n\t\tself.hatchDepositSpeedForWheels = 1\n\t\t\n\t\tself.cargo1Height = 28\n\t\tself.cargo2Height = 56\n\t\tself.cargo3Height = 84\n\t\tself.cargoShipHeightInches = 36\n\t\t\n\t\tself.frontLeftChannel = 3\n\t\tself.frontRightChannel = 5\n\t\tself.rearLeftChannel = 4\n\t\tself.rearRightChannel = 1\n\t\tself.leftLeadScrewChannel = 6\n\t\tself.rightLeadScrewChannel = 10\n\t\tself.pulleyChannel = 2\n\t\tself.spinBarChannel = 8\n\t\t\n\t\tself.frontLeftMotor = ctre.WPI_TalonSRX(self.frontLeftChannel)\n\t\tself.frontRightMotor = ctre.WPI_TalonSRX(self.frontRightChannel)\n\t\tself.rearLeftMotor = ctre.WPI_TalonSRX(self.rearLeftChannel)\n\t\tself.rearRightMotor = ctre.WPI_TalonSRX(self.rearRightChannel)\n\t\tself.leftLeadScrewMotor = ctre.WPI_TalonSRX(self.leftLeadScrewChannel)\n\t\tself.rightLeadScrewMotor = ctre.WPI_TalonSRX(self.rightLeadScrewChannel)\n\t\tself.pulleyMotor = ctre.WPI_TalonSRX(self.pulleyChannel)\n\t\tself.spinBarMotor = ctre.WPI_TalonSRX(self.spinBarChannel)\n\t\t\n\t\tself.pulleyMotorModifier = 0.6 # slows down the Pulley motor speed just in case it goes way too fast\n\t\tself.frontLeftMotor.setInverted(True)\n\t\tself.frontRightMotor.setInverted(True)\n\t\tself.rearLeftMotor.setInverted(True)\n\t\tself.rearRightMotor.setInverted(True)\n\t\tself.drive = MecanumDrive(\n\t\t\tself.frontLeftMotor,\n\t\t\tself.rearLeftMotor,\n\t\t\tself.frontRightMotor,\n\t\t\tself.rearRightMotor,\n\t\t)\n\t\t\n\t\tself.frontLeftMotor.setSafetyEnabled(False)\n\t\tself.rearLeftMotor.setSafetyEnabled(False)\n\t\tself.frontRightMotor.setSafetyEnabled(False)\n\t\tself.rearRightMotor.setSafetyEnabled(False)\n\t\t\n\t\t#this is the IR dist for ball\n\t\tself.ball_dist = 2.5\n\t\tself.hatch_dist = 3\n\t\tself.alignB1 = 15\n\t\tself.alignH = 35\n\t\tself.alignCB = 12\n\t\tself.adjust_ready = False\n\t\tself.pulleyMotor.setQuadraturePosition(0,0)\n\t\t#Last thing in the init function\n\t\tsuper().__init__()\n\tdef hab(self, startLevel, goalLevel):\n\t\t'''This function will '''\n\t\thab = Job()\n\t\thab.function = 'self.raiseBase'\n\t\thab.parameters = '(' + str(startLevel) + ', ' + str(goalLevel) + ')'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.driveQuadratureReset'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.crabLeft'\n\t\thab.parameters = '(self.crab1, self.frontLeftMotor)'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.raiseLeft'\n\t\thab.parameters = '(' + str(startLevel) + ', ' + str(goalLevel) + ')'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.driveQuadratureReset'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.crabLeft'\n\t\thab.parameters = '(self.crab2, self.rearRightMotor)'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.lowerLeft'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.driveQuadratureReset'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.crabLeft'\n\t\thab.parameters = '(self.crab3, self.frontLeftMotor)'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.raiseRight'\n\t\thab.parameters = '(' + str(startLevel) + ', ' + str(goalLevel) + ')'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.driveQuadratureReset'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.crabLeft'\n\t\thab.parameters = '(self.crab4, self.frontLeftMotor)'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.lowerRight'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.driveQuadratureReset'\n\t\thab.parameters = '()'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\t\t\n\t\thab = Job()\n\t\thab.function = 'self.crabLeft'\n\t\thab.parameters = '(self.crab5, self.frontLeftMotor)'\n\t\thab.driveLock = True\n\t\tself.queue.add(hab)\n\tdef raiseBase(self, startLevel, goalLevel):\n\t\tLeft_off = 0\n\t\tRight_off = 0\n\t\tcurrentLeftLeadScrewPosition = self.leftLeadScrewMotor.getQuadraturePosition()\n\t\tcurrentRightLeadScrewPosition = self.rightLeadScrewMotor.getQuadraturePosition()\n\t\t\n\t\tif startLevel == 1:\n\t\t\tif goalLevel == 2:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to2\n\t\t\telif goalLevel == 3:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to3\n\t\telif startLevel == 2:\n\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter2to3\n\t\t\n\t\tif currentLeftLeadScrewPosition < goalPosition and (self.bottomLeftLeadScrewHallEffect).get() < self.bottomLeftLeadScrewHallEffectThreshold:\n\t\t\tself.leftLeadScrewMotor.set(self.lifterSpeed)\n\t\telse:\n\t\t\tself.leftLeadScrewMotor.set(0)\n\t\t\tLeft_off = 1\n\t\t\t\n\t\n\t\tif currentRightLeadScrewPosition < goalPosition and (self.bottomRightLeadScrewHallEffect).get() < self.bottomRightLeadScrewHallEffectThreshold:\n\t\t\tself.rightLeadScrewMotor.set(self.lifterSpeed)\n\t\telse:\n\t\t\tself.rightLeadScrewMotor.set(0)\n\t\t\tRight_off = 1\n\t\t\tself.queue.remove()\n\t\t\t\n\t\tif Left_off ==1 and Right_off ==1:\n\t\t\tself.queue.remove()\n\tdef lowerLeft(self):\n\t\t'''This moves the encoders down, or extends the lead screw.'''\n\t\tcurrentLeftLeadScrewPosition = self.leftLeadScrewMotor.getQuadraturePosition()\n\t\t\n\t\tgoalPosition = self.ticksPerInchLifter * self.extraHeight\n\t\t\n\t\tif currentLeftLeadScrewPosition < goalPosition and (self.bottomLeftLeadScrewHallEffect.get()) < self.bottomLeftLeadScrewHallEffectThreshold:\n\t\t\tself.leftLeadScrewMotor.set(self.lifterSpeed)\n\t\telse:\n\t\t\tself.leftLeadScrewMotor.set(0)\n\t\t\tself.queue.remove()\n\t\t\t\n\t\t\t\n\tdef lowerRight(self):\n\t\t\n\t\tcurrentRightLeadScrewPosition = self.rightLeadScrewMotor.getQuadraturePosition()\n\t\t\n\t\t\n\t\tgoalPosition = self.ticksPerInchLifter * self.extraHeight\n\t\t\n\t\tif currentPosition < goalPosition and (self.bottomRightLeadScrewHallEffect.get()) < self.bottomRightLeadScrewHallEffectThreshold:\n\t\t\tself.rightLeadScrewMotor.set(self.lifterSpeed)\n\t\telse:\n\t\t\tself.rightLeadScrewMotor.set(0)\n\t\t\tself.queue.remove()\n\t\t\t\n\t\t\t\n\tdef raiseLeft(self, startLevel, goalLevel):\n\t\t'''This raises the lead screws into the body, and is considered a negative direction.'''\n\t\tcurrentLeftLeadScrewPosition = self.leftLeadScrewMotor.getQuadraturePosition()\n\t\t\n\t\tif startLevel == 1:\n\t\t\tif goalLevel == 2:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to2 * -1\n\t\t\telif goalLevel == 3:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to3 * -1\n\t\telif startLevel == 2:\n\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter2to3 * -1\n\t\t\n\t\tif currentLeftLeadScrewPosition > goalPosition and (self.topLeftLeadScrewHallEffect.get()) < self.topLeftLeadScrewHallEffectThreshold:\n\t\t\tself.leftLeadScrewMotor.set(-1 * self.lifterSpeed)\n\t\telse:\n\t\t\tself.leftLeadScrewMotor.set(0)\n\t\t\tself.queue.remove()\n\t\t\t\n\t\t\t\n\tdef raiseRight(self, startLevel, goalLevel):\n\t\t\n\t\tcurrentRightLeadScrewPosition = self.rightLeadScrewMotor.getQuadraturePosition()\n\t\t\n\t\tif startLevel == 1:\n\t\t\tif goalLevel == 2:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to2 * -1\n\t\t\telif goalLevel == 3:\n\t\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter1to3 * -1\n\t\telif startLevel == 2:\n\t\t\tgoalPosition = self.ticksPerInchLifter * self.Lifter2to3 * -1\n\t\t\n\t\tif currentRightLeadScrewPosition > goalPosition and (self.topRightLeadScrewHallEffect.get()) < self.topRightLeadScrewHallEffectThreshold:\n\t\t\tself.rightLeadScrewMotor.set(-1 * self.lifterSpeed)\n\t\telse:\n\t\t\tself.rightLeadScrewMotor.set(0)\n\t\t\tself.queue.remove()\n\t\t\t\n\t\t\t\n\tdef driveQuadratureReset(self):\n\t\t\n\t\tself.frontLeftMotor.setQuadraturePosition(0, 0)\n\t\tself.frontRightMotor.setQuadraturePosition(0, 0)\n\t\tself.rearLeftMotor.setQuadraturePosition(0, 0)\n\t\tself.rearRightMotor.setQuadraturePosition(0, 0)\n\tdef crabLeft(self, distance, encoder):\n\t\t\n\t\tcurrentPosition = encoder.getQuadraturePosition()\n\t\t\n\t\tgoalPosition = self.ticksPerInchCrabbing * distance\n\t\t\n\t\tif currentPosition > goalPosition:\n\t\t\tself.frontLeftMotor.set(-1 * self.crabSpeed)\n\t\t\tself.frontRightMotor.set(self.crabSpeed)\n\t\t\tself.rearLeftMotor.set(self.crabSpeed)\n\t\t\tself.rearRightMotor.set(-1 * self.crabSpeed)\n\t\telse:\n\t\t\tself.frontLeftMotor.set(0)\n\t\t\tself.frontRightMotor.set(0)\n\t\t\tself.rearLeftMotor.set(0)\n\t\t\tself.rearRightMotor.set(0)\n\t\t\tself.queue.remove()\n\tdef depositPayload(self, level, payload):\n\t\t\n\t\tJOB = Job()\n\t\tJOB.function = 'self.pulleyHeight'\n\t\tJOB.parameters = '(' + str(level) + ', ' + str(payload) + ')'\n\t\tJOB.driveLock = True\n\t\tself.queue.add(JOB)\n\t\t\n\t\tJOB = Job()\n\t\tJOB.function = 'self.dispense'\n\t\tJOB.parameters = '(' + str(payload) + ')'\n\t\tJOB.driveLock = True\n\t\tself.queue.add(JOB)\n\tdef levelSelector(self):\n\t\t'''This function returns the level as an integer by checking the rotary switch controlling rocket level.'''\n\t\t\n\t\tif self.auxiliary2.getRawButton(self.selector1):\n\t\t\treturn(1)\n\t\telif self.auxiliary2.getRawButton(self.selector2):\n\t\t\treturn(2)\n\t\telif self.auxiliary2.getRawButton(self.selector3):\n\t\t\treturn(3)\n\t\telse:\n\t\t\tpass\n\t\t\t\n\tdef Pulley_encoder(self):\n\t\tcurrentPosition= self.pulleyMotor.getQuadraturePosition()\n\tdef pulleyHeight(self, level, payload): # level 0 is the floor, payload 1 is hatch, payload 2 is cargo, payload 3 is cargo ship cargo(not done yet)\n\t\t'''Moves the Pulley to certain levels, with a certain offset based on hatch or cargo. The cargo ship has a unique offset (supposedly), and the hatch has no offset.'''\n\t\tcurrentPosition = self.pulleyMotor.getQuadraturePosition()\n\t\t\n\t\tif payload == 1: # hatch\n\t\t\tif level == 1:\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.hatch1Height\n\t\t\telif level == 2:\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.hatch2Height\n\t\t\telse: # level 3 is the only other option the Pulley has, so the else is for level 3\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.hatch3Height\n\t\telif payload == 2: # cargo\n\t\t\tif level == 1:\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.cargo1Height\n\t\t\telif level == 2:\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.cargo2Height\n\t\t\telse:\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.cargo3Height\n\t\t\t\t\n\t\telif payload == 6:\n\t\t\tif level==1: #6 is the rocket ball\n\t\t\t\tprint('moving at ' + self.pulleyMotorModifier)\n\t\t\t\tgoalPosition = self.ticksPerInchPulley * self.alignB1\n\t\telif payload == 5: #5 is the rocket hatch\n\t\t\tif level == 1:\n\t\t\t\tprint('moving at ' + self.pulleyMotorModifier)\n\t\t\t\tgoalPosition= self.ticksPerInchPulley * self.alignH\n\t\telif payload == 4: #4 is the cargoship ball\n\t\t\tif level == 1:\n\t\t\t\tprint('moving at ' + self.pulleyMotorModifier)\n\t\t\t\tgoalPosition = self.ticksPerInchPulley* self.alignCB\n\t\telse:\n\t\t\tgoalPosition = self.ticksPerInchPulley * self.cargoShipHeightInches\n\t\t\t\n\t\t\t\n\n\t\t\t\n\t\t\t\n\t\tif currentPosition < (goalPosition - (self.ticksPerInchPulley * self.pulleyDeadbandInches)) and (self.topPulleyHallEffect.get()) < self.topPulleyHallEffectThreshold: # this sets a deadband for the encoders on the pulley so that the pulley doesnt go up and down forever\n\t\t\tself.pulleyMotor.set(self.pulleyMotorModifier)\n\t\t\t\n\t\telif currentPosition > (goalPosition + (self.ticksPerInchPulley * self.pulleyDeadbandInches)) and (topPulleyHallEffect.get()) < self.topPulleyHallEffectThreshold:\n\t\t\tself.pulleyMotor.set(-1 * self.pulleyMotorModifier)\n\t\t\t\n\t\telse:\n\t\t\tself.pulleyMotor.set(0)\n\t\t\tself.queue.remove()\n\tdef dispense(self, payload):\n\t\t\n\t\tcurrentPosition = self.spinBarMotor.getQuadraturePosition()\n\t\tgoalPositionCargo = self.ticksPerRevolution * 8\n\t\tgoalPositionHatch = self.ticksPerRevolution\n\t\t\n\t\t\n\t\tif payload == 2 or payload == 3: # a cargo or a cargoship\n\t\t\n\t\t\tif currentPosition < (goalPositionCargo - self.spinBarDeadBand):\n\t\t\t\tself.spinBarMotor.set(0.5)\n\t\t\t\t\n\t\t\telif currentPosition > (goalPositionCargo + self.spinBarDeadBand):\n\t\t\t\tself.spinBarMotor.set(-0.5)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tself.spinBarMotor.set(0)\n\t\t\t\tself.queue.remove()\n\t\t\t\n\t\t# This logic requires a job before this one to set the spinBar position to 0 when it is all the way back, without needing the spinBar to\n\t\t# go backwards multiple rotations to get to quadrature position 0. This is accomplished using the resetSpinBar function.\n\t\telif payload == 1: # a hatch\n\t\t\n\t\t\tif currentPosition < (goalPositionHatch - self.spinBarDeadBand):\n\t\t\t\tself.spinBarMotor.set(self.hatchDepositSpeed)\n\t\t\t\tself.frontLeftMotor.set(-1 * self.hatchDepositSpeedForWheels)\n\t\t\t\tself.frontRightMotor.set(self.hatchDepositSpeedForWheels)\n\t\t\t\tself.rearLeftMotor.set(self.hatchDepositSpeedForWheels)\n\t\t\t\tself.rearRightMotor.set(-1 * self.hatchDepositSpeedForWheels)\n\t\t\t\t\n\t\t\telif currentPosition > (goalPositionHatch + self.spinBarDeadBand):\n\t\t\t\tself.spinBarMotor.set(-1 * self.hatchDepositSpeed)\n\t\t\t\tself.frontLeftMotor.set(-1 * self.hatchDepositSpeedForWheels)\n\t\t\t\tself.frontRightMotor.set(self.hatchDepositSpeedForWheels)\n\t\t\t\tself.rearLeftMotor.set(self.hatchDepositSpeedForWheels)\n\t\t\t\tself.rearRightMotor.set(-1 * self.hatchDepositSpeedForWheels)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tself.spinBarMotor.set(0)\n\t\t\t\tself.frontLeftMotor.set(0)\n\t\t\t\tself.frontRightMotor.set(0)\n\t\t\t\tself.rearLeftMotor.set(0)\n\t\t\t\tself.rearRightMotor.set(0)\n\t\t\t\tself.queue.remove()\n\tdef resetSpinBar(self):\n\t\t\n\t\tcurrentPosition = self.spinBarMotor.getQuadraturePosition()\n\t\toffset = currentPosition % self.ticksPerRevolution\n\t\t\n\t\tif (offset) > self.spinBarDeadBand:\n\t\t\tself.spinBarMotor.set(-1 * self.spinBarResetSpeed)\n\t\telse:\n\t\t\tself.spinBarMotor.set(0)\n\t\t\tself.spinBarMotor.setQuadraturePosition(offset, 0)\n\t\t\tself.queue.remove()\n\tdef spinBar(self, velocity):\n\t\t\n\t\tself.spinBarMotor.set(velocity)\n\tdef resetPulley(self): # to bring the pulley back to its starting height\n\t\t# go down until the hall effect sensor reads the magnet, then stop and set encoder value to 0\n\t\t\n\t\tif (self.bottomPulleyHallEffect.get()) < self.bottomPulleyHallEffectThreshold:\n\t\t\tself.pulleyMotor.set(-1 * self.pulleyMotorModifier)\n\t\telse:\n\t\t\tself.pulleyMotor.set(0)\n\t\t\tself.pulleyMotor.setQuadraturePosition(0, 0)\n\t\t\tself.queue.remove()\n\tdef robotInit(self):\n\t\t\"\"\"Robot initialization function\"\"\"\n\t\t\n\t\t\n\tdef autonomousInit(self):\n\t\t\n\t\tpass\n\tdef autonomousPeriodic(self):\n\t\tpass\n\tdef teleopInit(self):\n\t\t\n\t\tprint('teleop starting')\n\t\tself.leftLeadScrewMotor.setQuadraturePosition(0,0)\n\t\tself.rightLeadScrewMotor.setQuadraturePosition(0,0)\n\tdef checkSwitches(self):\n\t\t\n\t\tif self.auxiliary1.getRawButton(self.eStop): #E-Stop button pressed, stop all motors and remove all jobs from job queue.\n\t\t\t\n\t\t\tself.frontLeftMotor.set(0)\n\t\t\tself.frontRightMotor.set(0)\n\t\t\tself.rearLeftMotor.set(0)\n\t\t\tself.rearRightMotor.set(0)\n\t\t\tself.leftLeadScrewMotor.set(0)\n\t\t\tself.rightLeadScrewMotor.set(0)\n\t\t\tself.pulleyMotor.set(0)\n\t\t\tself.spinBarMotor.set(0)\n\t\t\t\n\t\t\t#Remove all queued jobs by setting the queue to the blank class\n\t\t\t\n\t\t\tself.queue = Queue()\n\t\t\t\n\t\t\t\n\t\telse: #Check every other switch\n\t\t\t\n\t\t\t\n\t\t\t# buttons controlling spinBar (3 position momentary switch)\n\t\t\t\n\t\t\t\n\t\t\tif self.auxiliary2.getRawButton(self.leftLeadScrewDown): # left lead screw out manual\n\t\t\t\tself.leftLeadScrewMotor.set(self.lifterSpeed)\n\t\t\t\t#print(str(self.leftLeadScrewMotor.getQuadraturePosition()))\n\t\t\t\t\n\t\t\telif self.auxiliary2.getRawButton(self.leftLeadScrewUp): # left lead screw in manual\n\t\t\t\tself.leftLeadScrewMotor.set(-1 * self.lifterSpeed)\n\t\t\t\t#print(str(self.leftLeadScrewMotor.getQuadraturePosition()))\n\t\t\telse:\n\t\t\t\tself.leftLeadScrewMotor.set(0)\n\t\t\t\t#print(str(self.leftLeadScrewMotor.getQuadraturePosition()))\n\t\t\t\t\n\t\t\tif self.auxiliary2.getRawButton(self.rightLeadScrewDown): # right lead screw out manual\n\t\t\t\tself.rightLeadScrewMotor.set(self.lifterSpeed)\n\t\t\telif self.auxiliary2.getRawButton(self.rightLeadScrewUp): # right lead screw in manual\n\t\t\t\tself.rightLeadScrewMotor.set(-1 * self.lifterSpeed)\n\t\t\telse:\n\t\t\t\tself.rightLeadScrewMotor.set(0)\n\t\t\t\t\n\t\t\t\t\n\t\t\tif self.auxiliary2.getRawButton(self.spinBarIn): # cargo collecting\n\t\t\t\t#if self.IRSensor.getVoltage() < self.IRSensorThreshold: # IR distance sensor stops the spinBar from spinning in when the ball is already in\n\t\t\t\t\t#self.spinBarMotor.set(-1)\n\t\t\t\t#else:\n\t\t\t\t\t#self.spinBarMotor.set(0)\n\t\t\t\tself.spinBarMotor.set(-1)\n\t\t\telif self.auxiliary2.getRawButton(self.spinBarOut): # manual cargo depositing\n\t\t\t\tself.spinBarMotor.set(1)\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.manualHatchDeposit): # manual hatch depositing\n\t\t\t\tself.spinBarMotor.set(self.hatchDepositSpeed)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tself.spinBarMotor.set(0)\n\t\t\t\t\n\t\t\tif self.auxiliary2.getRawButton(self.manualPulleyUp) and self.auxiliary2.getRawButton(1) == False: # manual pulley up\n\t\t\t\tprint('you pulled pulley up')\n\t\t\t\tself.pulleyMotor.set(-1*self.pulleyMotorModifier)\n\t\t\t\t\n\t\t\telif self.auxiliary2.getRawButton(self.manualPulleyDown) and self.auxiliary2.getRawButton(1) == False: # manual pulley down\n\t\t\t\tprint('you pulled pulley down')\n\t\t\t\tself.pulleyMotor.set(self.pulleyMotorModifier)\n\t\t\telse:\n\t\t\t\tself.pulleyMotor.set(0)\n\t\t\t\t\n\t\t\t\t# buttons controlling Pulley (2 buttons and a rotary switch)\n\t\t\t\t\n\t\t\t\t# hatch buttons\n\t\t\t\t\n\t\t\tif self.auxiliary1.getRawButton(self.autoHatchDeposit): # hatch movement and depositing (auto)\n\t\t\t\tDeposit_pl = Job()\n\t\t\t\tDeposit_pl.function = 'self.depositPayload'\n\t\t\t\tDeposit_pl.parameters = '(self.levelSelector(), 1)'\n\t\t\t\tDeposit_pl.driveLock = True\n\t\t\t\tself.queue.add(Deposit_pl)\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.hatchCollectHeight): # hatch collecting (from player station)\n\t\t\t\thatchCollectManual = Job()\n\t\t\t\thatchCollectManual.function = 'self.pulleyHeight'\n\t\t\t\thatchCollectManual.parameters = '(1, 1)'\n\t\t\t\thatchCollectManual.driveLock = True\n\t\t\t\tself.queue.add(hatchCollectManual)\n\t\t\t\t\n\t\t\t\thatchCollectManual = Job()\n\t\t\t\thatchCollectManual.function = 'self.resetSpinBar'\n\t\t\t\thatchCollectManual.parameters = '()'\n\t\t\t\thatchCollectManual.driveLock = False\n\t\t\t\tself.queue.add(hatchCollectManual)\n\t\t\t\t\n\t\t\t\t\n\t\t\t# cargo buttons\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.autoCargoDeposit): # cargo movement and depositing\n\t\t\t\t\n\t\t\t\tself.depositPayload(self.levelSelector(), 2)\n\t\t\t\t\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.autoCargoShipDeposit): # cargo ship depositing\n\t\t\t\tx=self.levelSelector()\n\t\t\t\tself.depositPayload(self.levelSelector(), 3)\n\t\t\t\t\n\t\t\t\t\n\t\t\t# Pulley reset button\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.pulleyReset): # pulley reset\n\t\t\t\tresetPulley = Job()\n\t\t\t\tresetPulley.function = 'self.resetPulley'\n\t\t\t\tresetPulley.parameters = '()'\n\t\t\t\tresetPulley.driveLock = False\n\t\t\t\tself.queue.add(resetPulley)\n\t\t\t\t\n\t\t\t\t\n\t\t\t# buttons controlling baseLifter (3 buttons)\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.hab1to2): # hab level 1 to level 2\n\t\t\t\tself.hab(1, 2)\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.hab1to3): # hab level 1 to level 3\n\t\t\t\tself.hab(1, 3)\n\t\t\t\t\n\t\t\telif self.auxiliary1.getRawButton(self.hab2to3): # hab level 2 to level 3\n\t\t\t\tself.hab(2, 3)\n\tdef teleopPeriodic(self):\n\t\t# checks switches and sensors, which feed the queue with jobs\n\t\tself.checkSwitches()\n\t\t# we are checking if a job is in the queue, and then calling the function that the first job makes using eval\n\t\t\n\t\tself.drive.driveCartesian(self.driveStick.getX(), self.driveStick.getY() *-1, self.driveStick.getZ(), 0)\n\t\tif len(self.queue.queue) > 0:\n\t\t\t\n\t\t\tcurrentJob = self.queue.peek()\n\t\t\tprint(str(currentJob.function))\n\t\t\teval(currentJob.function + currentJob.parameters)\n\t\t\t\n\t\t\t#allows the driver to drive the robot when the currentJob allows them to, using the driveLock parameter in the job\n\t\t\tif currentJob.driveLock == False:\n\t\t\t\tself.drive.driveCartesian(self.driveStick.getX(), self.driveStick.getY()*-1, self.driveStick.getZ(), 0)\n\t\t\t\n\t\telse:\n\t\t\tself.drive.driveCartesian(self.driveStick.getX(), self.driveStick.getY() *-1, self.driveStick.getZ(), 0)\n\t\t\t\n\t\t\n\t\n\t\tif self.auxiliary2.getRawButton(1) == True:\n\t\t\tself.adjust_ready = False\n\t\t\tself.checkSwitches()\n\t\t\tprint('vision entered')\n\t\t\tcurrentPosition = self.pulleyMotor.getQuadraturePosition() \n\t\t\t'''(self.IRSensor.getVoltage() > 0.1) and''' '''(self.IRSensor.getVoltage() < self.ball_dist) and '''\n\t\t\tif ((self.adjust_ready == False) and (self.auxiliary2.getRawButton(6) == True)): #rocket ball\n\t\t\t\tprint('Quad pos is ' + str(currentPosition))\n\t\t\t\tprint('entered the rocket ball')\n\t\t\t\tself.pulleyMotor.set(self.pulleyMotorModifier)\n\t\t\t\tif currentPosition > -3000:\n\t\t\t\t\tself.pulleyMotorModifier += 0.05\n\t\t\t\t\tprint('moving at ' + self.pulleyMotorModifier)\n\t\t\t\telse:\n\t\t\t\t\tself.pulleyHeight(6,1) \n\t\t\t\t\tself.pulleyMotorModifier =0.6\n\t\t\t\t\tself.adjust_ready= 1\n\t\t\t\t\t'''\n\t\t\tif (self.IRSensor.getVoltage() > 0.1) and (self.IRSensor.getVoltage() < self.hatch_dist) and (self.adjust_ready == 0): #rocket hatch\n\t\t\t\tself.pulleyMotorModifier = 0.05\n\t\t\t\tself.pulleyMotor.set(self.pulleyMotorModifier)\n\t\t\t\tif self.pulleyMotor.getQuadraturePosition() > 10:\n\t\t\t\t\tself.pulleyMotorModifier += 0.05\n\t\t\t\telse:\n\t\t\t\t\tself.pulleyHeight(5,1)\n\t\t\t\t\tself.pulleyMotorModifier =0.5\n\t\t\t\t\tself.adjust_ready= 1\n\t\t\t\t\t'''\n\t\t\t\t\t'''(self.IRSensor.getVoltage() > 0.1) and''' '''(self.IRSensor.getVoltage() < self.ball_dist) and'''\n\t\t\tif ((self.adjust_ready == False) and (self.auxiliary2.getRawButton(7) == True)): #cargo ball\n\t\t\t\tprint('entered the cargo ball')\n\t\t\t\tprint('Quad pos is ' + str(currentPosition))\n\t\t\t\tif currentPosition > -3000:\n\t\t\t\t\tself.pulleyMotorModifier += 0.05\n\t\t\t\t\tprint('moving at ' + self.pulleyMotorModifier)\n\t\t\t\t\tself.pulleyMotor.set(self.pulleyMotorModifier)\n\t\t\t\telse:\n\t\t\t\t\tself.pulleyHeight(4,1)\n\t\t\t\t\tself.pulleyMotorModifier =0.6\n\t\t\t\t\tself.adjust_ready= 1\n\t\t\t\t\n\t\t\tif self.adjust_ready == True:\n\t\t\t\ttest = 0\n\t\t\t\ttesty = 0\n\t\t\t\ttestz = 0\n\t\t\t\ttry:\n\t\t\t\t\ttest = sd.getValue('adjust_x', 0)\n\t\t\t\t\ttesty = sd.getValue('adjust_y', 0)\n\t\t\t\t\ttestz = sd.getValue('adjust_z', 0)\n\t\t\t\t\tprint('x ' + str(test))\n\t\t\t\t\tprint('y ' + str(testy))\n\t\t\t\t\tprint('z ' + str(testz))\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(str(e.args))\n\t\t\t\t\n\t\t\t\tself.drive.driveCartesian(self.driveStick.getX(test), self.driveStick.getY(testy), self.driveStick.getZ(testz), 0)\n\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\nif __name__ == \"__main__\":\n\twpilib.run(MyRobot)\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":26894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"174072995","text":"from random import seed\nfrom random import random\nfrom math import exp\nfrom csv import reader\nfrom data_processing import load_csv\nfrom dataset import Dataset\n\ndef init_network(n_inputs, n_hidden, n_outputs):\n\tnetwork = list()\n\thidden_layer = [{'weights':[random() for i in range(n_inputs+1)]} for i in range(n_hidden)]\n\tnetwork.append(hidden_layer)\n\toutput_layer = [{'weights':[random() for i in range(n_hidden+1)]} for i in range(n_outputs)]\n\tnetwork.append(output_layer)\n\treturn network\n\n# forward propagation\ndef activate(weights, inputs):\n\tactivation = weights[-1]\n\tfor i in range(len(weights)-1):\n\t\tactivation += weights[i] * inputs[i]\n\treturn activation\n\ndef transfer(activation):\n\treturn 1.0/(1.0 + exp(-activation))\n\ndef forward_prop(network, row):\n\tinputs = row\n\tfor layer in network:\n\t\tnew_inputs = []\n\t\tfor neuron in layer:\n\t\t\tactivation = activate(neuron['weights'], inputs)\n\t\t\tneuron['output'] = transfer(activation)\n\t\t\tnew_inputs.append(neuron['output'])\n\t\tinputs = new_inputs\n\treturn inputs\n\n#back propagation\ndef trans_derivative(output):\n\treturn output * (1.0 - output)\n\ndef back_prop_err(network, expected):\n\tfor i in reversed(range(len(network))):\n\t\tlayer = network[i]\n\t\terrors = list()\n\t\tif i != len(network)-1:\n\t\t\tfor j in range(len(layer)):\n\t\t\t\terror = 0.0\n\t\t\t\tfor neuron in network[i+1]:\n\t\t\t\t\terror += (neuron['weights'][j] * neuron['delta'])\n\t\t\t\terrors.append(error)\n\t\telse:\n\t\t\tfor j in range(len(layer)):\n\t\t\t\tneuron = layer[j]\n\t\t\t\terrors.append(expected[j]-neuron['output'])\n\t\tfor j in range(len(layer)):\n\t\t\tneuron = layer[j]\n\t\t\tneuron['delta'] = errors[j] * trans_derivative(neuron['output'])\n\n# weight = weight + l_rate * err * input\ndef update_weights(network, row, l_rate):\n\tfor i in range(len(network)):\n\t\tinputs = row[:-1]\n\t\tif i != 0:\n\t\t\tinputs = [neuron['output'] for neuron in network[i-1]]\n\t\tfor neuron in network[i]:\n\t\t\tfor j in range(len(inputs)):\n\t\t\t\tneuron['weights'][j] += l_rate*neuron['delta']*inputs[j]\n\t\t\tneuron['weights'][-1] += l_rate*neuron['delta']\n\n\ndef train_network(network, train, l_rate, n_epoch, n_outputs):\n\tfor epoch in range(n_epoch):\n\t\tsum_error = 0\n\t\tfor row in train:\n\t\t\toutputs = forward_prop(network, row)\n\t\t\texpected = [0 for i in range(n_outputs)]\n\t\t\texpected[row[-1]] = 1\n\t\t\tsum_error += sum([(expected[i] - outputs[i])**2 for i in range(len(expected))])\n\t\t\tback_prop_err(network, expected)\n\t\t\tupdate_weights(network, row, l_rate)\n\t\tprint('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error))\n\n\ndef predict(network, row):\n\toutputs = forward_prop(network, row)\n\treturn outputs.index(max(outputs))\n\ndef back_prop(train, test, l_rate, n_epoch, n_hidden):\n\tn_inputs = len(train[0]) - 1\n\tn_outputs = len(set([row[-1] for row in train]))\n\tnetwork = init_network(n_inputs, n_hidden, n_outputs)\n\ttrain_network(network, train, l_rate, n_epoch, n_outputs)\n\tpredictions = list()\n\tfor row in test:\n\t\tpredictions.append(predict(network, row))\n\treturn predictions\n\n\nif __name__ == '__main__':\n\t# seed(1)\n\tfilename = 'wheat-seeds.csv'\n\tdataset = load_csv(filename)\n\tdataset = Dataset(dataset)\n\tfor i in range(len(dataset.dataset[0])-1):\n\t\tdataset.str_col_to_float(i)\n\tdataset.str_col_to_int(len(dataset.dataset[0])-1)\n\tminmax = dataset.minmax()\n\tdataset.normalize(minmax)\n\tn_folds = 5\n\tl_rate = 0.3\n\tn_epoch = 500\n\tn_hidden = 5\n\tscores = dataset.eval_algo(back_prop, n_folds, l_rate, n_epoch, n_hidden)\n\tprint('Scores: %s' % scores)\n\tprint('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))","sub_path":"bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"365799224","text":"from functools import reduce\nimport unittest\nimport numpy\nfrom pyscf import gto\nfrom pyscf import scf\nfrom pyscf import ao2mo\nfrom pyscf import fci\n\nnorb = 6\nnelec = 6\nna = fci.cistring.num_strings(norb, nelec//2)\nnumpy.random.seed(1)\nci0 = numpy.random.random((na,na))\nci0 = ci0 + ci0.T\nrdm1, rdm2 = fci.direct_spin1.make_rdm12(ci0, norb, nelec)\n\nclass KnowValues(unittest.TestCase):\n def test_rdm3(self):\n dm3ref = make_dm3_o0(ci0, norb, nelec)\n dm3 = fci.rdm.make_dm123('FCI3pdm_kern_spin0', ci0, ci0, norb, nelec)[2]\n self.assertTrue(numpy.allclose(dm3ref, dm3))\n\n dm3 = fci.rdm.reorder_rdm3(rdm1, rdm2, dm3)\n fac = 1. / (nelec-2)\n self.assertTrue(numpy.allclose(rdm2, numpy.einsum('ijklmm->ijkl',dm3)*fac))\n self.assertTrue(numpy.allclose(rdm2, numpy.einsum('ijmmkl->ijkl',dm3)*fac))\n self.assertTrue(numpy.allclose(rdm2, numpy.einsum('mmijkl->ijkl',dm3)*fac))\n\n dm3 = fci.rdm.make_dm123('FCI3pdm_kern_sf', ci0, ci0, norb, nelec)[2]\n dm2 = fci.direct_spin1.make_rdm12(ci0, norb, nelec, reorder=False)[1]\n self.assertTrue(numpy.allclose(dm2, numpy.einsum('mmijkl->ijkl',dm3)/nelec))\n\n numpy.random.seed(2)\n na = fci.cistring.num_strings(norb, 5)\n nb = fci.cistring.num_strings(norb, 3)\n ci1 = numpy.random.random((na,nb))\n dm3ref = make_dm3_o0(ci1, norb, (5,3))\n dm3 = fci.rdm.make_dm123('FCI3pdm_kern_sf', ci1, ci1, norb, (5,3))[2]\n self.assertTrue(numpy.allclose(dm3ref, dm3))\n\n def test_dm4(self):\n dm4ref = make_dm4_o0(ci0, norb, nelec)\n dm4 = fci.rdm.make_dm1234('FCI4pdm_kern_sf', ci0, ci0, norb, nelec)[3]\n self.assertTrue(numpy.allclose(dm4ref, dm4))\n\n numpy.random.seed(2)\n na = fci.cistring.num_strings(norb, 5)\n nb = fci.cistring.num_strings(norb, 3)\n ci1 = numpy.random.random((na,nb))\n dm4ref = make_dm4_o0(ci1, norb, (5,3))\n dm4 = fci.rdm.make_dm1234('FCI4pdm_kern_sf', ci1, ci1, norb, (5,3))[3]\n self.assertTrue(numpy.allclose(dm4ref, dm4))\n\n def test_tdm2(self):\n dm1 = numpy.einsum('ij,ijkl->kl', ci0, _trans1(ci0, norb, nelec))\n self.assertTrue(numpy.allclose(rdm1, dm1))\n\n dm2 = numpy.einsum('ij,ijklmn->klmn', ci0, _trans2(ci0, norb, nelec))\n dm2 = fci.rdm.reorder_rdm(rdm1, dm2)[1]\n self.assertTrue(numpy.allclose(rdm2,dm2))\n\n na = ci0.shape[0]\n numpy.random.seed(1)\n ci = numpy.random.random((na,na))\n ci1 = numpy.random.random((na,na))\n dm1, dm2 = fci.direct_spin1.trans_rdm12(ci, ci1, norb, nelec)\n numpy.random.seed(2)\n self.assertAlmostEqual(numpy.dot(dm2.flatten(),numpy.random.random(dm2.size)),\n 3790.8867819690477, 7)\n self.assertTrue(numpy.allclose(dm2, dm2.transpose(2,3,0,1)))\n\n t1 = _trans1(ci1, norb, nelec)\n t2 = _trans2(ci1, norb, nelec)\n dm1a = numpy.einsum('ij,ijpq->pq', ci, t1)\n dm2a = numpy.einsum('ij,ijpqrs->pqrs', ci, t2)\n self.assertTrue(numpy.allclose(dm1a, dm1))\n dm1a, dm2a = fci.rdm.reorder_rdm(dm1a, dm2a)\n self.assertTrue(numpy.allclose(dm2a,dm2a.transpose(2,3,0,1)))\n\n# (6o,6e) ~ 4MB\n# (8o,8e) ~ 153MB\n# (10o,10e) ~ 4.8GB\n# t2(*,ij,kl) = E_i^j E_k^l|0>\ndef _trans2(fcivec, norb, nelec):\n if isinstance(nelec, (int, numpy.integer)):\n neleca = nelecb = nelec//2\n else:\n neleca, nelecb = nelec\n link_indexa = fci.cistring.gen_linkstr_index(range(norb), neleca)\n link_indexb = fci.cistring.gen_linkstr_index(range(norb), nelecb)\n na, nlinka = link_indexa.shape[:2]\n nb, nlinkb = link_indexb.shape[:2]\n fcivec = fcivec.reshape(na,nb)\n t1 = _trans1(fcivec, norb, nelec)\n t2 = numpy.zeros((na,nb,norb,norb,norb,norb))\n for str0, tab in enumerate(link_indexa):\n for a, i, str1, sign in tab:\n t2[str1,:,a,i] += sign * t1[str0]\n for k in range(na):\n for str0, tab in enumerate(link_indexb):\n for a, i, str1, sign in tab:\n t2[k,str1,a,i] += sign * t1[k,str0]\n return t2\ndef _trans1(fcivec, norb, nelec):\n if isinstance(nelec, (int, numpy.integer)):\n neleca = nelecb = nelec//2\n else:\n neleca, nelecb = nelec\n link_indexa = fci.cistring.gen_linkstr_index(range(norb), neleca)\n link_indexb = fci.cistring.gen_linkstr_index(range(norb), nelecb)\n na, nlinka = link_indexa.shape[:2]\n nb, nlinkb = link_indexb.shape[:2]\n fcivec = fcivec.reshape(na,nb)\n t1 = numpy.zeros((na,nb,norb,norb))\n for str0, tab in enumerate(link_indexa):\n for a, i, str1, sign in tab:\n t1[str1,:,a,i] += sign * fcivec[str0]\n for k in range(na):\n for str0, tab in enumerate(link_indexb):\n for a, i, str1, sign in tab:\n t1[k,str1,a,i] += sign * fcivec[k,str0]\n return t1\n\n#\n# NOTE: this rdm3 is defined as\n# rdm3(p,q,r,s,t,u) = <p^+ q r^+ s t^+ u>\ndef make_dm3_o0(fcivec, norb, nelec):\n # <0|p^+ q r^+ s|i> <i|t^+ u|0>\n t1 = _trans1(fcivec, norb, nelec)\n t2 = _trans2(fcivec, norb, nelec)\n na, nb = t1.shape[:2]\n rdm3 = numpy.dot(t1.reshape(na*nb,-1).T, t2.reshape(na*nb,-1))\n return rdm3.reshape((norb,)*6).transpose(1,0,2,3,4,5)\n\ndef make_dm4_o0(fcivec, norb, nelec):\n # <0|p^+ q r^+ s|i> <i|t^+ u|0>\n t2 = _trans2(fcivec, norb, nelec)\n na, nb = t2.shape[:2]\n rdm4 = numpy.dot(t2.reshape(na*nb,-1).T, t2.reshape(na*nb,-1))\n return rdm4.reshape((norb,)*8).transpose(3,2,1,0,4,5,6,7)\n\n\nif __name__ == \"__main__\":\n print(\"Full Tests for fci.rdm\")\n unittest.main()\n\n\n","sub_path":"fci/test/test_rdm.py","file_name":"test_rdm.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"387168337","text":"from __future__ import unicode_literals\n\nfrom spacy.en import English\n\nimport pytest\nimport re\n\n\nEN = English()\n\n\n@pytest.fixture\ndef doc():\n return EN('This is a sentence. This is another sentence. And a third.')\n\n\ndef test_sent_spans(doc):\n sents = list(doc.sents)\n assert sents[0].start == 0\n assert sents[0].end == 5\n assert len(sents) == 3\n assert sum(len(sent) for sent in sents) == len(doc)\n","sub_path":"python/spaCy/2015/4/test_span.py","file_name":"test_span.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"111925166","text":"# -*- coding: iso-8859-1 -*-\n'''\nCreated on 19 de feb. de 2016\n\n@author: Andrés Hernández\n'''\nfrom Persona import Persona\n\nclass Mujer(Persona):\n \n def __init__(self):\n super().__init__()\n \n def __str__(self):\n cadena = str('Nombre: %s' % self.nombre)\n cadena += str(', sexo: mujer')\n for k, v in self.caracteristicas.items():\n cadena += str(', %s: %s' % (k, v))\n return cadena","sub_path":"quienesquien/Mujer.py","file_name":"Mujer.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"316296822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 3 21:00:00 2019\r\nCode for plotting data\r\nPut it in the same directory as the data\r\n@author: afsar\r\n\"\"\"\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nL = list(os.walk(\"./\"))\r\nc = 'rgbcmy'\r\ncname = []\r\nrgb = None\r\nZ = []\r\nseed = 7\r\nfor d,_,flist in L[1:]:\r\n print(d) \r\n for f in flist:\r\n if f.split('#')[1]==str(seed)+'.spv':\r\n name = d.split('/')[1]\r\n cname.append(name) \r\n D = np.loadtxt(os.path.join(d,f)) \r\n if rgb is not None:\r\n assert np.all(rgb == np.array(D[:,:3]))\r\n else:\r\n rgb = np.array(D[:,:3])\r\n x = np.array(D[:,3:]).T\r\n assert x.shape[0]==4\r\n assert x.shape[1]==len(rgb)\r\n Z.append(x)\r\n #plt.plot((D[:,5]-mZ)/sZ,c[i]+'+-')\r\nZ = np.array(Z)\r\ncname = np.array(cname)\r\ndA = {}\r\nfor n in set(cname):\r\n dA[n]=np.mean(Z[cname==n],axis=0)\r\nA = np.array(list(dA.values()))\r\nanames = np.array(list(dA.keys()))\r\nidx = np.argsort(anames)\r\nA = A [idx]\r\nanames = anames[idx]\r\nfor i in range(A.shape[1]):\r\n plt.figure()\r\n plt.plot(A[:,i,:].T,'o-')\r\n plt.legend(anames)\r\n plt.title('Avraged Reading'+str(i))\r\n plt.grid()","sub_path":"chemical-photo-analyzer-master/Data Collected/RGB Chemical Analyser data/plotdata.py","file_name":"plotdata.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"538642514","text":"# Copyright (c) 2021 PaddlePaddle 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.\nfrom functools import partial\nimport numpy as np\n\nimport paddle\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nimport paddle.tensor as tensor\nfrom paddle.nn import Layer, Embedding\n\nfrom .. import PretrainedModel, register_base_model\n\n__all__ = [\n 'BartModel', 'BartPretrainedModel', 'BartEncoder', 'BartDecoder',\n 'BartClassificationHead', 'BartForSequenceClassification',\n 'BartForQuestionAnswering', 'BartForConditionalGeneration'\n]\n\n\ndef shift_tokens_right(input_ids, decoder_start_token_id):\n \"\"\"\n Shift input ids one token to the right.\n \"\"\"\n shifted_input_ids = paddle.zeros_like(input_ids)\n shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()\n shifted_input_ids[:, 0] = decoder_start_token_id\n\n return shifted_input_ids\n\n\nclass BartPretrainedModel(PretrainedModel):\n \"\"\"\n An abstract class for pretrained Bart models. It provides Bart related\n `model_config_file`, `resource_files_names`, `pretrained_resource_files_map`,\n `pretrained_init_configuration`, `base_model_prefix` for downloading and\n loading pretrained models.\n See :class:`~paddlenlp.transformers.model_utils.PretrainedModel` for more details.\n \"\"\"\n model_config_file = \"model_config.json\"\n pretrained_init_configuration = {\n \"bart-base\": {\n \"vocab_size\": 50265,\n \"bos_token_id\": 0,\n \"pad_token_id\": 1,\n \"eos_token_id\": 2,\n \"decoder_start_token_id\": 2,\n \"d_model\": 768,\n \"num_encoder_layers\": 6,\n \"num_decoder_layers\": 6,\n \"encoder_attention_heads\": 12,\n \"decoder_attention_heads\": 12,\n \"encoder_ffn_dim\": 3072,\n \"decoder_ffn_dim\": 3072,\n \"dropout\": 0.1,\n \"activation_function\": \"gelu\",\n \"attention_dropout\": 0.1,\n \"activation_dropout\": 0.1,\n \"max_position_embeddings\": 1024,\n \"init_std\": 0.02,\n },\n \"bart-large\": {\n \"vocab_size\": 50265,\n \"bos_token_id\": 0,\n \"pad_token_id\": 1,\n \"eos_token_id\": 2,\n \"decoder_start_token_id\": 2,\n \"d_model\": 1024,\n \"num_encoder_layers\": 12,\n \"num_decoder_layers\": 12,\n \"encoder_attention_heads\": 16,\n \"decoder_attention_heads\": 16,\n \"encoder_ffn_dim\": 4096,\n \"decoder_ffn_dim\": 4096,\n \"dropout\": 0.1,\n \"activation_function\": \"gelu\",\n \"attention_dropout\": 0.1,\n \"activation_dropout\": 0.1,\n \"max_position_embeddings\": 1024,\n \"init_std\": 0.02,\n }\n }\n resource_files_names = {\"model_state\": \"model_state.pdparams\"}\n pretrained_resource_files_map = {\n \"model_state\": {\n \"bart-base\":\n \"https://paddlenlp.bj.bcebos.com/models/transformers/bart/bart-base.pdparams\",\n \"bart-large\":\n \"https://paddlenlp.bj.bcebos.com/models/transformers/bart/bart-large.pdparams\"\n }\n }\n base_model_prefix = \"bart\"\n\n def init_weights(self, layer):\n \"\"\" Initialization hook \"\"\"\n if isinstance(layer, (nn.Linear, nn.Embedding)):\n # In the dygraph mode, use the `set_value` to reset the parameter directly,\n # and reset the `state_dict` to update parameter in static mode.\n if isinstance(layer.weight, paddle.Tensor):\n layer.weight.set_value(\n paddle.tensor.normal(\n mean=0.0,\n std=self.init_std if hasattr(self, \"init_std\") else\n self.bart.config[\"init_std\"],\n shape=layer.weight.shape))\n elif isinstance(layer, (nn.TransformerEncoderLayer,\n nn.TransformerDecoderLayer)):\n if layer.activation == F.gelu:\n layer.activation = partial(F.gelu, approximate=True)\n\n\nclass BartLearnedPositionalEmbedding(Embedding):\n \"\"\"\n This module learns positional embeddings up to a fixed maximum size.\n \"\"\"\n\n def __init__(self, num_embeddings, embedding_dim, padding_idx):\n assert padding_idx is not None, \"`padding_idx` should not be None, but of type int\"\n # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2\n # and adjust num_embeddings appropriately. Other models dont have this hack\n self.offset = 2\n super().__init__(\n num_embeddings + self.offset,\n embedding_dim,\n padding_idx=padding_idx)\n\n def forward(self, input_ids_shape, past_key_values_length=0):\n \"\"\"`input_ids_shape` is expected to be [bsz x seqlen].\"\"\"\n bsz, seq_len = input_ids_shape[:2]\n positions = paddle.arange(\n past_key_values_length,\n past_key_values_length + seq_len,\n dtype=\"int64\")\n return super().forward(positions + self.offset)\n\n\nclass BartEncoder(BartPretrainedModel):\n \"\"\"\n The Transformer Encoder of BartModel. The arguments of BartEncoder can see :class:`BartModel`.\n \"\"\"\n\n def __init__(self,\n embed_tokens,\n vocab_size,\n pad_token_id=1,\n d_model=768,\n num_encoder_layers=6,\n encoder_attention_heads=12,\n encoder_ffn_dim=3072,\n dropout=0.1,\n activation_function='gelu',\n attention_dropout=0.1,\n activation_dropout=0.1,\n max_position_embeddings=1024,\n init_std=0.02):\n super().__init__()\n self.init_std = init_std\n self.pad_token_id = pad_token_id\n if embed_tokens is not None:\n self.embed_tokens = embed_tokens\n else:\n self.embed_tokens = nn.Embedding(vocab_size, d_model, pad_token_id)\n\n self.encoder_embed_positions = BartLearnedPositionalEmbedding(\n max_position_embeddings, d_model, pad_token_id)\n\n self.encoder_dropout = nn.Dropout(dropout)\n self.encoder_layernorm_embedding = nn.LayerNorm(d_model)\n encoder_layer = nn.TransformerEncoderLayer(\n d_model=d_model,\n nhead=encoder_attention_heads,\n dim_feedforward=encoder_ffn_dim,\n dropout=dropout,\n activation=activation_function,\n attn_dropout=attention_dropout,\n act_dropout=activation_dropout)\n self.encoder = nn.TransformerEncoder(encoder_layer, num_encoder_layers)\n self.apply(self.init_weights)\n\n def forward(self, input_ids=None, attention_mask=None, **kwargs):\n \"\"\"\n The BartEncoder forward method, overrides the `__call__()` special method.\n\n Args:\n input_ids (Tensor, optional):\n See :class:`BartModel`.\n attention_mask (Tensor, optional):\n See :class:`BartModel`.\n\n Returns:\n Tensor: Returns tensor `encoder_output`, which is the output at the last layer of the model.\n Its data type should be float32 and has a shape of [batch_size, sequence_length, hidden_size].\n\n \"\"\"\n if input_ids is None:\n raise ValueError(\"Input_ids cannot be None.\")\n inputs_embeds = self.embed_tokens(input_ids)\n inputs_embed_pos = self.encoder_embed_positions(input_ids.shape)\n hidden_states = inputs_embeds + inputs_embed_pos\n hidden_states = self.encoder_layernorm_embedding(hidden_states)\n encoder_input = self.encoder_dropout(hidden_states)\n\n if attention_mask is None:\n attention_mask = paddle.cast(\n input_ids == self.pad_token_id,\n dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e9\n attention_mask.stop_gradient = True\n\n encoder_output = self.encoder(encoder_input, src_mask=attention_mask)\n return encoder_output\n\n\nclass BartDecoder(BartPretrainedModel):\n \"\"\"\n The Transformer Decoder of BartModel. The arguments of BartDecoder can see :class:`BartModel`.\n \"\"\"\n\n def __init__(self,\n embed_tokens,\n vocab_size,\n pad_token_id=1,\n d_model=768,\n num_decoder_layers=6,\n decoder_attention_heads=12,\n decoder_ffn_dim=3072,\n dropout=0.1,\n activation_function='gelu',\n attention_dropout=0.1,\n activation_dropout=0.1,\n max_position_embeddings=1024,\n init_std=0.02):\n super().__init__()\n self.init_std = init_std\n if embed_tokens is not None:\n self.embed_tokens = embed_tokens\n else:\n self.embed_tokens = nn.Embedding(vocab_size, d_model, pad_token_id)\n\n self.decoder_embed_positions = BartLearnedPositionalEmbedding(\n max_position_embeddings, d_model, pad_token_id)\n self.decoder_dropout = nn.Dropout(dropout)\n self.decoder_layernorm_embedding = nn.LayerNorm(d_model)\n\n decoder_layer = nn.TransformerDecoderLayer(\n d_model=d_model,\n nhead=decoder_attention_heads,\n dim_feedforward=decoder_ffn_dim,\n dropout=dropout,\n activation=activation_function,\n attn_dropout=attention_dropout,\n act_dropout=activation_dropout)\n self.decoder = nn.TransformerDecoder(decoder_layer, num_decoder_layers)\n self.apply(self.init_weights)\n\n def forward(self,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n encoder_output=None,\n memory_mask=None,\n cache=None):\n \"\"\"\n The BartDecoder forward method, overrides the `__call__()` special method.\n\n Args:\n decoder_input_ids (Tensor, optional):\n See :class:`BartModel`.\n decoder_attention_mask (Tensor, optional):\n See :class:`BartModel`.\n encoder_output (Tensor, optional):\n See :class:`BartModel`.\n memory_mask (Tensor, optional):\n See :class:`BartModel`.\n cache (Tensor, optional):\n See :class:`BartModel`.\n\n Returns:\n Tensor: Returns tensor `decoder_output`, which is the output at the last layer of the model.\n Its data type should be float32 and has a shape of [batch_size, sequence_length, hidden_size].\n\n \"\"\"\n if decoder_attention_mask is None:\n decoder_length = paddle.shape(decoder_input_ids)[-1]\n decoder_attention_mask = paddle.tensor.triu(\n (paddle.full(\n (decoder_length, decoder_length),\n -np.inf,\n dtype=paddle.get_default_dtype())),\n 1)\n decoder_inputs_embeds = self.embed_tokens(decoder_input_ids)\n past_key_values_length = paddle.shape(cache[0][0].k)[\n 2] if cache is not None else 0\n decoder_inputs_embed_pos = self.decoder_embed_positions(\n decoder_input_ids.shape, past_key_values_length)\n hidden_states = decoder_inputs_embeds + decoder_inputs_embed_pos\n hidden_states = self.decoder_layernorm_embedding(hidden_states)\n decoder_input = self.decoder_dropout(hidden_states)\n\n decoder_output = self.decoder(\n tgt=decoder_input,\n memory=encoder_output,\n tgt_mask=decoder_attention_mask,\n memory_mask=memory_mask,\n cache=cache)\n return decoder_output\n\n\n@register_base_model\nclass BartModel(BartPretrainedModel):\n r\"\"\"\n The bare Bart Model transformer outputting raw hidden-states.\n\n This model inherits from :class:`~paddlenlp.transformers.model_utils.PretrainedModel`.\n Refer to the superclass documentation for the generic methods.\n\n This model is also a Paddle `paddle.nn.Layer <https://www.paddlepaddle.org.cn/documentation\n /docs/en/api/paddle/fluid/dygraph/layers/Layer_en.html>`__ subclass. Use it as a regular Paddle Layer\n and refer to the Paddle documentation for all matter related to general usage and behavior.\n\n Args:\n vocab_size (int):\n Vocabulary size of `inputs_ids` in `BartModel`. Also is the vocab size of token embedding matrix.\n Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling `BartModel`.\n bos_token (int, optional):\n The beginning of sequence token that was used during pretraining. Can be\n used a sequence classifier token.\n Defaults to `0`.\n pad_token_id(int, optional):\n The index of padding token in the token vocabulary.\n Defaults to `1`.\n eos_token (int, optional):\n A special token representing the end of a sequence that was used during pretraining.\n Defaults to `2`.\n d_model (int, optional):\n Dimensionality of the embedding layer, encoder layer and decoder layer. Defaults to `768`.\n num_encoder_layers (int, optional):\n Number of hidden layers in the Transformer encoder. Defaults to `6`.\n num_decoder_layers (int, optional):\n Number of hidden layers in the Transformer decoder. Defaults to `6`.\n encoder_attention_heads (int, optional):\n Number of attention heads for each attention layer in the Transformer encoder.\n Defaults to `12`.\n decoder_attention_heads (int, optional):\n Number of attention heads for each attention layer in the Transformer decoder.\n Defaults to `12`.\n encoder_ffn_dim (int, optional):\n Dimensionality of the feed-forward (ff) layer in the encoder. Input tensors\n to ff layers are firstly projected from `d_model` to `encoder_ffn_dim`,\n and then projected back to `d_model`. Typically `encoder_ffn_dim` is larger than `d_model`.\n Defaults to `3072`.\n decoder_ffn_dim (int, optional):\n Dimensionality of the feed-forward (ff) layer in the encoder. Input tensors\n to ff layers are firstly projected from `d_model` to `decoder_ffn_dim`,\n and then projected back to `d_model`. Typically `decoder_ffn_dim` is larger than `d_model`.\n Defaults to `3072`.\n dropout (float, optional):\n The dropout probability used in all fully connected layers (pre-process and post-process of MHA and FFN sub-layer)\n in the encoders and decoders. Defaults to `0.1`.\n activation_function (str, optional):\n The non-linear activation function in the feed-forward layer.\n ``\"gelu\"``, ``\"relu\"`` and any other paddle supported activation functions are supported.\n Defaults to `\"gelu\"`.\n attention_dropout (float, optional):\n The dropout probability used in MultiHeadAttention in all encoder layers and decoder layers to drop some attention target.\n Defaults to `0.1`.\n activation_dropout (float, optional):\n The dropout probability used after FFN activation in all encoder layers and decoder layers.\n Defaults to `0.1`.\n max_position_embeddings (int, optional):\n The maximum value of the dimensionality of position encoding, which dictates the maximum supported length of an input\n sequence. Defaults to `1024`.\n init_std (float, optional):\n The standard deviation of the truncated_normal_initializer for initializing all weight matrices.\n Default to `0.02`.\n\n \"\"\"\n\n def __init__(self,\n vocab_size,\n bos_token_id=0,\n pad_token_id=1,\n eos_token_id=2,\n decoder_start_token_id=2,\n d_model=768,\n num_encoder_layers=6,\n num_decoder_layers=6,\n encoder_attention_heads=12,\n decoder_attention_heads=12,\n encoder_ffn_dim=3072,\n decoder_ffn_dim=3072,\n dropout=0.1,\n activation_function='gelu',\n attention_dropout=0.1,\n activation_dropout=0.1,\n max_position_embeddings=1024,\n init_std=0.02):\n super().__init__()\n self.init_std = init_std\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.shared = nn.Embedding(vocab_size, d_model, pad_token_id)\n self.encoder = BartEncoder(\n self.shared, vocab_size, pad_token_id, d_model, num_encoder_layers,\n encoder_attention_heads, encoder_ffn_dim, dropout,\n activation_function, attention_dropout, activation_dropout,\n max_position_embeddings, init_std)\n\n self.decoder = BartDecoder(\n self.shared, vocab_size, pad_token_id, d_model, num_decoder_layers,\n decoder_attention_heads, decoder_ffn_dim, dropout,\n activation_function, attention_dropout, activation_dropout,\n max_position_embeddings, init_std)\n self.apply(self.init_weights)\n\n def get_encoder(self):\n return self.encoder\n\n def get_decoder(self):\n return self.decoder\n\n def forward(self,\n input_ids,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n encoder_output=None,\n use_cache=False,\n cache=None):\n r'''\n The BartModel forward method, overrides the `__call__()` special method.\n\n Args:\n input_ids (Tensor):\n Indices of input sequence tokens in the vocabulary. They are\n numerical representations of tokens that build the input sequence.\n Its data type should be `int64` and it has a shape of [batch_size, sequence_length].\n attention_mask (Tensor, optional):\n Mask used in multi-head attention to avoid performing attention to some unwanted positions,\n usually the paddings or the subsequent positions.\n Its data type can be int, float and bool.\n When the data type is bool, the `masked` tokens have `False` values and the others have `True` values.\n When the data type is int, the `masked` tokens have `0` values and the others have `1` values.\n When the data type is float, the `masked` tokens have `-INF` values and the others have `0` values.\n It is a tensor with shape broadcasted to `[batch_size, num_attention_heads, sequence_length, sequence_length]`.\n For example, its shape can be [batch_size, sequence_length], [batch_size, sequence_length, sequence_length],\n [batch_size, num_attention_heads, sequence_length, sequence_length].\n Defaults to `None`, which means nothing needed to be prevented attention to.\n decoder_input_ids (Tensor, optional):\n Indices of decoder input sequence tokens in the vocabulary.\n Its data type should be `int64` and it has a shape of [batch_size, sequence_length].\n Defaults to `None`, which means no `decoder_input_ids` is provided, the model will create the tensor\n by shifting the `input_ids` to the right.\n decoder_attention_mask (Tensor, optional):\n Mask used in multi-head attention to avoid performing attention to some unwanted positions in `decoder_input_ids`.\n Its data type and shape is the same as `attention_mask`. Defaults to `None`.\n encoder_output (tuple, optional):\n The output of the encoder, a tuple consists `last_hidden_state`, `hidden_states`(optional), `attentions`(optional).\n The data type of `last_hidden_state` is float32 and its shape is `[batch_size, sequence_length, hidden_size]`.\n `hidden_states` is hidden_states of all layers in the Transformer encoder. The length of `hidden_states` is `num_hidden_layers + 1`.\n For all element in the tuple, its data type should be float32 and its shape is [`batch_size, sequence_length, hidden_size`].\n `attentions` is attentions of all layers of in the Transformer encoder. The length of `attentions` is `num_hidden_layers`.\n For all element in the tuple, its data type should be float32 and its shape is [`batch_size, num_attention_heads, sequence_length, sequence_length`].\n use_cache (bool, optional):\n Whether or not to use cache. Defaults to `False`. If set to `True`, key value states will be returned and\n can be used to speed up decoding.\n cache (list, optional):\n It is a list, and each element in the list is a tuple `(incremental_cache, static_cache)`.\n See `TransformerDecoder.gen_cache <https://github.com/PaddlePaddle/Paddle/blob/release/2.1/python/paddle/nn/layer/transformer.py#L1060>`__ for more details.\n It is only used for inference and should be None for training.\n Default to `None`.\n\n Returns:\n Tensor: Returns tensor `decoder_output`, which is the output at the last layer of the model.\n Its data type should be float32 and has a shape of [batch_size, sequence_length, hidden_size].\n\n Example:\n .. code-block::\n\n import paddle\n from paddlenlp.transformers import BartModel, BartTokenizer\n\n tokenizer = BartTokenizer.from_pretrained('bart-base')\n model = BartModel.from_pretrained('bart-base')\n\n inputs = tokenizer(\"Welcome to use PaddlePaddle and PaddleNLP!\")\n inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}\n output = model(**inputs)\n '''\n # different to other models, Bart automatically creates decoder_input_ids from\n # inputBartForSequenceClassification_ids if no decoder_input_ids are provided\n if input_ids is None and encoder_output is None:\n raise ValueError(\n \"You have to specify either input_ids or encoder_output\")\n if decoder_input_ids is None:\n assert input_ids is not None, \"input_ids should be \" \\\n \"specified when generating decoder_input_ids\"\n decoder_input_ids = shift_tokens_right(input_ids,\n self.decoder_start_token_id)\n if attention_mask is None:\n assert input_ids is not None, \"input_ids should be \" \\\n \"specified when generating attention_mask\"\n attention_mask = paddle.cast(\n input_ids == self.pad_token_id,\n dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e9\n # For 2D attention_mask from tokenizer\n elif attention_mask.ndim == 2:\n attention_mask = paddle.unsqueeze(\n attention_mask, axis=[1, 2]).astype(paddle.get_default_dtype())\n attention_mask = (1.0 - attention_mask) * -1e9\n attention_mask.stop_gradient = True\n if encoder_output is None:\n encoder_output = self.encoder(input_ids, attention_mask)\n if use_cache:\n if cache is None:\n cache = self.decoder.decoder.gen_cache(encoder_output)\n else:\n cache = None\n decoder_output = self.decoder(decoder_input_ids, decoder_attention_mask,\n encoder_output, attention_mask, cache)\n\n return decoder_output\n\n\nclass BartClassificationHead(Layer):\n \"\"\"\n Head for sentence-level classification tasks.\n \"\"\"\n\n def __init__(self,\n input_dim: int,\n inner_dim: int,\n num_classes: int,\n pooler_dropout: float):\n super().__init__()\n self.dense = nn.Linear(input_dim, inner_dim)\n self.dropout = nn.Dropout(p=pooler_dropout)\n self.out_proj = nn.Linear(inner_dim, num_classes)\n\n def forward(self, hidden_states):\n \"\"\"\n Args:\n hidden_states (Tensor):\n Hidden states of the classification model.\n \"\"\"\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.dense(hidden_states)\n hidden_states = F.tanh(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.out_proj(hidden_states)\n return hidden_states\n\n\nclass BartForSequenceClassification(BartPretrainedModel):\n r\"\"\"\n Bart Model with a linear layer on top of the pooled output,\n designed for sequence classification/regression tasks like GLUE tasks.\n\n Args:\n bart (:class:`BartModel`):\n An instance of BartModel.\n num_labels (int, optional):\n The number of different labels. Defaults to `2`.\n dropout (float, optional):\n The dropout probability for output of Bart.\n If None, use the same value as `hidden_dropout_prob` of `BartModel`\n instance `bart`. Defaults to None.\n \"\"\"\n\n def __init__(self, bart, num_labels=2, dropout=None):\n super().__init__()\n self.bart = bart\n self.classifier = BartClassificationHead(\n self.bart.config['d_model'], self.bart.config['d_model'],\n num_labels, dropout if dropout else self.bart.config['dropout'])\n self.apply(self.init_weights)\n\n def forward(self,\n input_ids,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n encoder_output=None,\n use_cache=False,\n cache=None):\n r\"\"\"\n The BartForSequenceClassification forward method, overrides the __call__() special method.\n\n Args:\n input_ids (Tensor):\n See :class:`BartModel`.\n attention_mask (Tensor, optional):\n See :class:`BartModel`.\n decoder_input_ids (Tensor, `optional`):\n See :class:`BartModel`.\n decoder_attention_mask (Tensor, optional):\n See :class:`BartModel`.\n encoder_output (Tensor, optonal):\n See :class:`BartModel`.\n use_cache (bool, optional):\n See :class:`BartModel`.\n cache (Tensor, optional):\n See :class:`BartModel`.\n\n Returns:\n Tensor: Returns tensor `logits`, a tensor of the input text classification logits.\n Shape as `[batch_size, num_labels]` and dtype as float32.\n\n Example:\n .. code-block::\n\n import paddle\n from paddlenlp.transformers import BartForSequenceClassification, BartTokenizer\n\n tokenizer = BartTokenizer.from_pretrained('bart-base')\n model = BartForSequenceClassification.from_pretrained('bart-base')\n\n inputs = tokenizer(\"Welcome to use PaddlePaddle and PaddleNLP!\")\n inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}\n logits = model(**inputs)\n \"\"\"\n output = self.bart(input_ids, attention_mask, decoder_input_ids,\n decoder_attention_mask, encoder_output, use_cache,\n cache)\n if use_cache:\n output = output[0]\n eos_mask = paddle.cast(\n input_ids == self.bart.config['eos_token_id'], dtype='int64')\n if len(paddle.unique(paddle.sum(eos_mask, axis=1))) > 1:\n raise ValueError(\n 'All examples must have the same number of <eos> tokens.')\n\n output_shape = paddle.shape(output)\n # TODO(gongenlei): support bool tensor index\n output = output.masked_select(\n eos_mask.unsqueeze(-1).astype('bool').tile(\n [1, 1, output_shape[-1]]))\n sentence_representation = output.reshape(\n [output_shape[0], -1, output_shape[-1]])[:, -1, :]\n logits = self.classifier(sentence_representation)\n return logits\n\n\nclass BartForQuestionAnswering(BartPretrainedModel):\n r\"\"\"\n Bart Model with a linear layer on top of the hidden-states output to\n compute `span_start_logits` and `span_end_logits`, designed for question-answering tasks like SQuAD.\n\n Args:\n bart (:class:`BartModel`):\n An instance of BartModel.\n \"\"\"\n\n def __init__(self, bart):\n super().__init__()\n self.bart = bart\n self.classifier = nn.Linear(self.bart.config['d_model'], 2)\n self.apply(self.init_weights)\n\n def forward(self,\n input_ids,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n encoder_output=None,\n use_cache=False,\n cache=None):\n r\"\"\"\n The BartForQuestionAnswering forward method, overrides the __call__() special method.\n\n Args:\n input_ids (Tensor):\n See :class:`BartModel`.\n attention_mask (Tensor, optional):\n See :class:`BartModel`.\n decoder_input_ids (Tensor, `optional`):\n See :class:`BartModel`.\n decoder_attention_mask (Tensor, optional):\n See :class:`BartModel`.\n encoder_output (Tensor, optonal):\n See :class:`BartModel`.\n use_cache (bool, optional):\n See :class:`BartModel`.\n cache (Tensor, optional):\n See :class:`BartModel`.\n\n Returns:\n tuple: Returns tuple (`start_logits`, `end_logits`).\n\n With the fields:\n\n - `start_logits` (Tensor):\n A tensor of the input token classification logits, indicates the start position of the labelled span.\n Its data type should be float32 and its shape is [batch_size, sequence_length].\n\n - `end_logits` (Tensor):\n A tensor of the input token classification logits, indicates the end position of the labelled span.\n Its data type should be float32 and its shape is [batch_size, sequence_length].\n\n Example:\n .. code-block::\n\n import paddle\n from paddlenlp.transformers import BartForQuestionAnswering, BartTokenizer\n\n tokenizer = BartTokenizer.from_pretrained('bart-base')\n model = BartForQuestionAnswering.from_pretrained('bart-base')\n\n inputs = tokenizer(\"Welcome to use PaddlePaddle and PaddleNLP!\")\n inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}\n outputs = model(**inputs)\n start_logits = outputs[0]\n end_logits =outputs[1]\n \"\"\"\n output = self.bart(input_ids, attention_mask, decoder_input_ids,\n decoder_attention_mask, encoder_output, use_cache,\n cache)\n logits = self.classifier(output[0] if use_cache else output, )\n logits = paddle.transpose(logits, perm=[2, 0, 1])\n start_logits, end_logits = paddle.unstack(x=logits, axis=0)\n return start_logits, end_logits\n\n\nclass BartForConditionalGeneration(BartPretrainedModel):\n r\"\"\"\n Bart Model with a linear layer on top of the hidden-states output to\n compute `span_start_logits` and `span_end_logits`, designed for question-answering tasks like SQuAD .\n\n Args:\n bart (:class:`BartModel`):\n An instance of BartModel.\n \"\"\"\n\n def __init__(self, bart):\n super().__init__()\n self.bart = bart\n self.lm_head_weight = self.create_parameter(\n shape=[\n self.bart.config['vocab_size'], self.bart.config['d_model']\n ],\n dtype=self.bart.shared.weight.dtype,\n is_bias=False)\n self.register_buffer(\"final_logits_bias\",\n paddle.zeros((1, self.bart.config['vocab_size'])))\n self.apply(self.init_weights)\n\n def get_encoder(self):\n return self.bart.get_encoder()\n\n def get_decoder(self):\n return self.bart.get_decoder()\n\n def forward(self,\n input_ids,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n encoder_output=None,\n use_cache=False,\n cache=None):\n r\"\"\"\n The BartForConditionalGeneration forward method, overrides the __call__() special method.\n\n Args:\n input_ids (Tensor):\n See :class:`BartModel`.\n attention_mask (Tensor, optional):\n See :class:`BartModel`.\n decoder_input_ids (Tensor, `optional`):\n See :class:`BartModel`.\n decoder_attention_mask (Tensor, optional):\n See :class:`BartModel`.\n encoder_output (Tensor, optonal):\n See :class:`BartModel`.\n use_cache (bool, optional):\n See :class:`BartModel`.\n cache (Tensor, optional):\n See :class:`BartModel`.\n\n Returns:\n Tensor or tuple: Returns Tensor `lm_logits` if `use_cache` is `False`, otherwise, returns tuple (`lm_logits`, `cache`).\n\n With the fields:\n\n - `lm_logits` (Tensor):\n The generated sentence of the model.\n Its data type should be float32 and has a shape of [batch_size, sequence_length, vocab_size].\n\n - `cache` (Tensor):\n See :class:`BartModel`.\n\n Example:\n .. code-block::\n\n import paddle\n from paddlenlp.transformers import BartForConditionalGeneration, BartTokenizer\n\n tokenizer = BartTokenizer.from_pretrained('bart-base')\n model = BartForConditionalGeneration.from_pretrained('bart-base')\n\n inputs = tokenizer(\"Welcome to use PaddlePaddle and PaddleNLP!\")\n inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}\n outputs = model(**inputs)\n\n \"\"\"\n output = self.bart(input_ids, attention_mask, decoder_input_ids,\n decoder_attention_mask, encoder_output, use_cache,\n cache)\n lm_logits = paddle.tensor.matmul(\n output[0] if use_cache else output,\n self.lm_head_weight,\n transpose_y=True) + self.final_logits_bias\n if use_cache:\n cache = output[1]\n return lm_logits, cache\n else:\n return lm_logits\n\n def prepare_inputs_for_generation(self,\n decoder_input_ids,\n attention_mask=None,\n decoder_attention_mask=None,\n cache=None,\n use_cache=False,\n encoder_output=None,\n **kwargs):\n # cut decoder_input_ids if past is used\n if cache is not None:\n decoder_input_ids = decoder_input_ids[:, -1].unsqueeze(-1)\n if decoder_attention_mask is not None:\n decoder_attention_mask = decoder_attention_mask[:, :,\n -1, :].unsqueeze(\n 2)\n\n return {\n \"input_ids\": None,\n \"decoder_input_ids\": decoder_input_ids,\n \"encoder_output\": encoder_output,\n \"decoder_attention_mask\": decoder_attention_mask,\n \"attention_mask\": attention_mask,\n \"use_cache\": use_cache,\n \"cache\": cache\n }\n\n def __getattr__(self, name):\n try:\n return super().__getattr__(name)\n except AttributeError as e:\n try:\n return getattr(getattr(self, self.base_model_prefix), name)\n except AttributeError:\n try:\n return getattr(self, self.base_model_prefix).config[name]\n except KeyError:\n raise e\n","sub_path":"finetuning_paddle/paddlenlp/transformers/bart/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":37210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181296099","text":"from django.db import models\n\n# Create your models here.\n\nclass Device(models.Model):\n identifier = models.CharField('unique device identifier',max_length=20)\n location = models.CharField('location of device',max_length=100)\n description = models.TextField('description of device usage')\n eng_units = models.CharField('engineering units of datapoints',\n max_length=10)\n\n def __str__(self):\n return self.identifier\n\nclass Datapoint(models.Model):\n device = models.ForeignKey(Device)\n timestamp = models.DateTimeField('time of reading')\n update_time = models.DateTimeField('time server recieved update',\n auto_now = True)\n value = models.FloatField() \n","sub_path":"datalogger/readings/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"8078149","text":"# TO-DO: Complete the selection_sort() function below \n\nthing = [7, 15, 2, 58, 9]\n\n\ndef selection_sort( arr ):\n # loop through n-1 elements\n for i in range(0, len(arr) - 1):\n cur_index = i\n smallest_index = cur_index\n # TO-DO: find next smallest element\n # (hint, can do in 3 loc)\n print(\"cur_index- \", cur_index)\n print(\"smallest_index-\", smallest_index)\n if smallest_index <= cur_index:\n print(\"made it\")\n cur_index += 1\n\n elif smallest_index > cur_index:\n smallest_index = cur_index\n cur_index += 1\n\n # \n\n\n\n # TO-DO: swap\n\n\n\n\n return arr\n\nprint(selection_sort(thing))\n\n\n# TO-DO: implement the Bubble Sort function below\ndef bubble_sort( arr ):\n #Get first two elements 0, 1\n slot1 = 0\n slot2 = 1\n\n\n\n #compare 0 <= 1\n #swap if false\n #move to elements 1,2\n #repeat until there are zero swaps\n\n return arr\n\n\n# STRETCH: implement the Count Sort function below\ndef count_sort( arr, maximum=-1 ):\n\n return arr","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"545421336","text":"\"\"\"\n:author: Arne (gojira) Simon [arne_simon@gmx.de]\n\"\"\"\nimport click\nimport os\nimport sys\nimport yaml\n\nfrom builda import ninja\n\n\nVERSION = '0.1'\nENVIRONMENT_FILE = os.path.join(os.path.expanduser('~'), '.builda.yml')\n\n\n@click.group()\ndef main():\n pass\n\n\n@main.add_command\n@click.command()\n@click.option('-n', 'name', default=None, help='Name of the project')\ndef init(name):\n \"\"\"\n Initialies a folder to be builda project.\n \"\"\"\n if name is None:\n path = os.getcwd()\n name = path[path.rfind('/')+1:]\n\n project = {\n 'name': name,\n # 'author': os.getlogin(),\n 'config': {\n 'release': {\n 'dependencies': [],\n 'cflags': '-std=c++11 -O3 -march=native',\n 'includes': ['./include'],\n 'libraries': [],\n 'sources': ['./src/**/*.cpp'],\n 'type': 'exe'\n }\n }\n }\n\n with open('builda.yml', 'w') as out:\n yaml.dump(project, out, default_flow_style=False)\n\n for name in ['include', 'src', 'lib', 'bin']:\n if not os.path.exists(name):\n os.mkdir(name)\n\n if not os.path.exists('.git'):\n os.system('git init')\n\n if not os.path.exists('.gitignore'):\n with open('.gitignore', 'w') as out:\n out.write('lib/*\\nbin/*\\n*.o\\n*.ninja\\n.ninja_deps\\n.ninja_log')\n\n\ndef find_clang():\n clang = 'clang++'\n\n if sys.platform.startswith('win'):\n clang = 'C:\\\\Program Files\\\\LLVM\\\\bin\\\\clang++.exe'\n\n return clang\n\n\ndef find_ninja():\n return 'ninja'\n\n\ndef find_git():\n return 'git'\n\n\n@main.add_command\n@click.command()\n@click.option('--clang', prompt=True, default=find_clang)\n@click.option('--ninja', prompt=True, default=find_ninja)\n@click.option('--git', prompt=True, default=find_git)\ndef env(clang, ninja, git):\n \"\"\"\n Sets the environment for builda, aka where the neccessary tooly are.\n \"\"\"\n config = {\n 'clang': clang,\n 'ninja': ninja,\n 'git': git\n }\n\n with open(ENVIRONMENT_FILE, 'w') as out:\n yaml.dump(config, out)\n\n\ndef __env(config):\n with open(ENVIRONMENT_FILE) as src:\n env = yaml.load(src)\n\n with open('builda.yml') as src:\n project = yaml.load(src)\n\n return env, project\n\n\ndef __build(config):\n env, project = __env(config)\n\n ninjafile = '{}.ninja'.format(config)\n\n with open(ninjafile, 'w') as out:\n out.write(ninja.create(project, config, env))\n\n os.system('{} -f {}'.format(env['ninja'], ninjafile))\n\n return env, project\n\n\n@main.add_command\n@click.command()\n@click.argument('config', default='release')\ndef build(config):\n __build(config)\n\n\n@main.add_command\n@click.command()\n@click.argument('config', default='release')\n@click.argument('args', nargs=-1)\ndef run(config, args):\n env, project = __build(config)\n\n exename = 'bin/{}'.format(project['name'])\n libpaths, libs, includes = ninja.gather_dependencies(project['config'][config])\n\n ldpaths = ':'.join(libpaths)\n os.system('LD_LIBRARY_PATH={} {} {}'.format(ldpaths, exename, ' '.join(args)))\n\n\n@main.add_command\n@click.command()\n@click.argument('config', default='release')\ndef clean(config):\n \"\"\"\n Removes binary, ninja build file and object files of a configuration.\n \"\"\"\n env, project = __env(config)\n\n exename = 'bin/{}'.format(project['name'])\n\n if os.path.exists(exename):\n os.remove(exename)\n\n sources = ninja.gather_sources(project, config)\n objects = ninja.coresponding_objects(sources, config)\n\n for obj in objects:\n if os.path.exists(obj):\n os.remove(obj)\n\n buildfile = '{}.ninja'.format(config)\n\n if os.path.exists(buildfile):\n os.remove(buildfile)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"builda/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"591310631","text":"import json\n\ndef get_config(name):\n data = {}\n with open(f'{name}.json', 'r') as read_file:\n data = json.load(read_file)\n return data\n\n\nif __name__ == '__main__':\n print(get_config('config').get('users').get('end'))","sub_path":"read_json.py","file_name":"read_json.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"505929198","text":"from django.http import Http404\nfrom django.shortcuts import render\nfrom django.core.paginator import Paginator, InvalidPage\n\nfrom .models import Category, Good\n\n\ndef index(request, cat_id=None):\n try:\n page_num = request.GET['page']\n except KeyError:\n page_num = 1\n\n cats = Category.objects.all().order_by('name')\n\n if not cat_id:\n cat = Category.objects.first()\n else:\n cat = Category.objects.get(pk=cat_id)\n\n paginator = Paginator(Good.objects.filter(\n category=cat).order_by('name'), 5)\n\n try:\n goods = paginator.page(page_num)\n except InvalidPage:\n goods = paginator.page(1)\n\n print(goods)\n\n return render(request, 'index.html', context={'cats': cats,\n 'goods': goods,\n 'category': cat}\n )\n\n\ndef good(request, good_id):\n try:\n page_num = request.GET['page']\n except KeyError:\n page_num = 1\n\n cats = Category.objects.all().order_by('name')\n try:\n good = Good.objects.get(pk=good_id)\n except Good.DoesNotExist:\n raise Http404\n\n return render(request, 'good.html', context={'good': good, 'cats': cats, 'pn': page_num})\n","sub_path":"goods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307036214","text":"import time\nimport sys\nimport csv\nimport floyd\nimport xml.dom.minidom\nimport numpy as np\n\n\ndef init_matrix (filename):\n data = xml.dom.minidom.parse(filename)\n\t\n net = data.getElementsByTagName('net')\n resistors = data.getElementsByTagName('resistor')\n capacitors = data.getElementsByTagName('capactor')\n diods = data.getElementsByTagName('diode')\n count_nets = len(net)\n matrix = []\n for i in range (count_nets):\n matrix.append ([0] * count_nets)\n \n scheme_edges = []\n for index, edge in enumerate(resistors + capacitors + diods):\n edge = edge.attributes\n net_from = int(edge['net_from'].value)-1\n net_to = int(edge['net_to'].value) - 1\n resistance = float(edge['resistance'].value)\n scheme_edges.append ((net_from, net_to, resistance))\n if index < len(resistors) + len(capacitors):\n scheme_edges.append ((net_to, net_from, resistance))\n else:\n reverse_resistance = float(edge['reverse_resistance'].value)\n scheme_edges.append ((net_to, net_from, reverse_resistance))\n for edge in scheme_edges:\n source = edge[0]\n dest = edge[1]\n resistance = edge[2]\n if matrix[source][dest]:\n matrix[source][dest] = (matrix[source][dest] * resistance) / (matrix[source][dest] + resistance)\n else:\n matrix[source][dest] = resistance\n return matrix\n\ndef write_results (matrix, filename):\n\twith open (filename, 'w') as data:\n\t for row in matrix:\n\t for element in row:\n\t data.write (str(round(element, 7)) + ',')\n\t data.write('\\n')\n\ndef main ():\n if len(sys.argv) != 3:\n print ('Incorrect input format\\n')\n else:\n start = time.process_time()\n inp_file = sys.argv[1]\n out_file = sys.argv[2]\n matrix = init_matrix (inp_file)\n matrix = floyd.FloydAlgorithm(matrix)\n write_results(matrix, out_file)\n end = time.process_time()\n print(\"Work time: {} sec\".format((end-start)))\n\nmain()\n","sub_path":"problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"577389451","text":"\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nimport datetime\n\n\ndef main():\n\n\tdirectory = 'c:\\\\Users\\\\oanuf\\\\GitHub\\\\Fun\\\\Idealo\\\\'\n\n\tall=pd.read_csv(directory+\"Travel.csv\",sep=\";\") # reading current status\n\n\t# Filling in empty regios from previous run\n\tRegio=pd.read_csv(directory+\"regio.csv\",sep=\";\", index_col='Destination') # reading mapping for regions\n\tif len(all[all.isna().any(axis=1)])>0: # if there is not-filled region from previous run ...\n\t\t\tall.loc[all.isna().any(axis=1),'Regio'] = all.Destination.map(Regio.Regio) # ... vlookup it from updated region mapping\n\n\tmainURL = \"https://flug.idealo.de/deals/\"\n\tkeyWords = {\"herbstferien\", \"fernreisen\", \"sommerferien\", \"best-in-europe\", \"last-minute\",\n\t\t\t\t\"staedtereisen\", \"kurzurlaub\", \"warme-reiseziele\", \"weihnachtsferien\", \"weihnachten\"\n\t\t\t\t\"beste-urlaubsziele-des-jahres\", \"osterferien\"}\n\tnot_interested = pd.read_csv(directory+\"not_interesting.csv\")\n\n\tprices = []\n\tflight_dates = []\n\tdestins = []\n\tgroups =[]\n\tstatus=[]\n\n\tprint('Starting parsing Idealo')\n\n\tfor keyword in keyWords:\n\t\t\ttry:\n\t\t\t\turl = mainURL+keyword\n\t\t\t\tpage = urlopen(url)\n\t\t\t\tsoup = bs(page)\n\t\t\t\ttrips = soup.find_all('div', class_ = 'deals-card deals-card--default')\n\t\t\t\tfor trip in trips:\n\t\t\t\t\tprice = trip.find('span',class_=\"deals-card-offer-price\").text\n\t\t\t\t\tprices.append(price)\n\t\t\t\t\tflight_date = trip.find('div',class_=\"deals-card-date\").text.split(\" - \")\n\t\t\t\t\tflight_dates.append(flight_date)\n\t\t\t\t\tdestin = trip.find('div',class_=\"deals-card-destination-container\")['title']\n\t\t\t\t\tdestins.append(destin)\n\t\t\t\t\tgroups.append(keyword)\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\t\n\n\tangebots = pd.DataFrame({'Destination': destins,\n\t\t\t\t\t\t\t'Dates': flight_dates,\n\t\t\t\t\t\t\t'Price': prices,\n\t\t\t\t\t\t\t'Group': groups\n\t\t\t\t\t\t\t})\n\tangebots=angebots[angebots['Destination'].str.contains('Münc')| # keep only the flights from Munich ...\n\t\t\t\t\t\tangebots['Destination'].str.contains('Memm')] # ... and Memmingen\n\tangebots[\"Destination\"]=angebots[\"Destination\"].str.split(' - ').str[1] # after splitting keep only 2nd part: destination\n\tangebots = angebots[~angebots['Destination'].isin(not_interested.Destination.values)] # removing not interesting destinations\n\tangebots[\"Period\"]=pd.to_datetime(angebots[\"Dates\"].str[0], format='%d.%m.%Y').dt.strftime('%Y-%m') # new column: month of flight\n\tangebots['Status'] = str(datetime.date.today()) # new column: when the query was done\n\tangebots[\"Destination\"]=angebots[\"Destination\"].replace({'-': ' ', ',': ''}, regex=True) # some destinations contain bad-for-csv symbols\n\tangebots.Price = angebots.Price.str.extract('(\\d+)').astype(int) # split string with \".\" or \",\" and take the 1st part\n\tangebots['Regio'] = angebots.Destination.map(Regio.Regio) # vlookuping region\n\n\tnew=angebots[angebots.isnull().Regio]['Destination'].drop_duplicates() # new destinations\n\tif len(new)>0:\n\t\tnew.to_csv(directory+\"regio.csv\", # the file exists already\n\t\t\t\t\tmode='a', # append mode: puts new df in the end of csv\n\t\t\t\t\tsep=\";\", \n\t\t\t\t\theader=False, # as we are appending, the file has headers already\n\t\t\t\t\tindex=False) # we need to eliminate the index column\n\n\tall=all.append(angebots, ignore_index = True) # adding new information to the main file below\n\tall=all.sort_values([\"Regio\",\"Destination\"])\n\tall['min_price']=all.groupby([\"Destination\"])[\"Price\"].transform(min) # calculating the min price for every destination\n\n\tall.to_csv(directory+\"Travel.csv\", # creating new file\n\t\t\t\tsep=\";\", \n\t\t\t\tindex=False) # we need to eliminate the index column\n\n\tprint('Done!')\n\n\nif __name__== \"__main__\":\n main()\n\n\n\n'''\n# cities_db_url=\"https://simplemaps.com/static/data/world-cities/basic/simplemaps_worldcities_basicv1.5.zip\"\n# cities_db = pd.read_csv(cities_db_url)\n\ntype(all.Status[1])\nall[all.Status == str(datetime.date.today())]\nall[all['Price'] < 1.2*all['min_price']]\nall[pd.DatetimeIndex(all[\"Period\"]).year==2020]\n\nrecord_price = all[(all.Status == str(datetime.date.today())) & \n\t\t\t\t\t(all['Price'] < 1.2*all['min_price']) &\n\t\t\t\t\t(pd.DatetimeIndex(all[\"Period\"]).year==2020)]\nrecord_price = record_price.drop(['min_price','Status'],axis=1).sort_values([\"Regio\"])\n\n\n\tall.to_csv(directory+\"Travel.csv\", # the file exists already\n\t\t\t\tmode='a', # append mode: puts new df in the end of csv\n\t\t\t\tsep=\";\", \n\t\t\t\theader=False, # as we are appending, the file has headers already\n\t\t\t\tindex=False) # we need to eliminate the index column\n\n\n# angebots.sort_values(by=['Group', 'Period'], inplace=True)\n\n\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport os\n\nemail = EMAIL1\npassword = PASS1\nsend_to_email =[\"XXX\",\"XXXX\"]\nsubject = 'Record flight prices for yesterday'\n\nds=str(record_price.to_html())\nmessageHTML = 'Flights from Idealo'+ds\nmsg = MIMEMultipart('alternative')\nmsg['From'] = email\nmsg['To'] = ', '.join(send_to_email)\nmsg['Subject'] = subject\n\nmsg.attach(MIMEText(messageHTML, 'html'))\n\nserver = smtplib.SMTP(\"smtp.gmail.com\",587)\nserver.starttls()\nserver.login(email, password)\ntext = msg.as_string()\nserver.sendmail(email, send_to_email, text)\nserver.quit()\n\n\n\nall2 = all.copy()\n\nall2['prices']=list(all2.Price.unique())\n\nall.Regio = all.Destination.map(Regio.Regio) \nall[all.isna().Price]\n\n\n\nall2['prices'] = [list(set(all2['subreddit'].loc[all2['Destination'] == x['Destination']])) \n for _, x in df2.iterrows()]\ngroupby([\"Destination\"])\n'''\n\n\n","sub_path":"Idealo/idealo.py","file_name":"idealo.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"49072245","text":"# -*- coding: utf-8 -*-\n\n\n\"\"\" Reads in crux/percolator tab-delimited results (psms) and returns tmt values\"\"\"\n\nimport os.path\nimport sys\nimport re\nimport pandas as pd\nimport tqdm\nimport logging\n\nfrom pytmt import __version__\nfrom pytmt.get_spec import Mzml\nfrom pytmt import tmt_reporters\nfrom pytmt import quantify_spec\n\ndef quant(args):\n \"\"\"\n reads in Percolator tab-delimited results (PSMS) \\\\\n and filter each row by protein-uniqueness and by Percolator q value \\\\\n then it opens the corresponding mzML file of the fraction and finds the scan \\\\\n and returns the intensity of each TMT reporter within specified \\\\\n mass tolerance. Currently supports only Percolator, and MS2-level quantification.\n\n Tested on:\n standalone comet 2017.01rev4 > crux 3.1 percolator\n crux 3.1 tide > crux 3.1 percolator\n\n To-do features:\n ms3 or multi-notch (shifting scan numbers)\n read in mzID files rather than percolator\n normalization and isotope purity adjustment\n filtering based on ms1\n\n Known issues:\n uses only directory index to match mzml files because of percolator\n\n Note:\n currently the sum of intensities is returned if multiple peaks are within the tolerance of reporter\n\n Usage:\n pytmt tests/data/mzml tests/data/percolator/percolator.target.psms.txt -o out\n\n Example values for arguments:\n mzml_loc = 'tests/data/mzml'\n id_loc = 'tests/data/percolator'\n precision = 10\n q_filter = 0.1\n unique_only = True\n\n :param args: arguments from argparse\n :return: Exit OK\n \"\"\"\n\n # Main logger setup\n main_log = logging.getLogger('pytmt')\n main_log.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n os.makedirs(args.out, exist_ok=True)\n fh = logging.FileHandler(os.path.join(args.out, 'tmt.log'))\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n main_log.addHandler(fh)\n main_log.addHandler(ch)\n\n main_log.info(args)\n main_log.info(__version__)\n\n # Folders of mzML files and the Percolator results.\n mzml_loc = args.mzml\n id_loc = args.id\n\n assert args.multiplex in [0, 2, 6, 10, 11, 16], '[error] TMT multiplexity not 0, 2, 6, 10, 11 or 16'\n\n # Get the reporter masses\n reporters = tmt_reporters.get_reporters(args.multiplex)\n\n # Define the PPM of integration\n precision = args.precision\n assert 1 <= precision <= 1000, '[error] mass tolerance must be between 1 and 1000 ppm'\n\n # Define the Percolator Q value cutoff filter\n q_filter = args.qvalue\n\n # Define the Percolator protein-unique PSM filter\n unique_only = args.unique\n\n assert os.path.isdir(mzml_loc), '[error] mzml directory path not valid'\n assert os.path.isfile(id_loc), '[error] percolator file path not valid'\n\n # List all files in the percolator directory ending with target.psms.txt.\n # id_files = [f for f in os.listdir(id_loc) if f.endswith('target.psms.txt')]\n # assert len(id_files) == 1, 'Check percolator output directory has 1 *.target.psms.txt'\n\n # Read the Percolator psms file.\n try:\n id_df = pd.read_csv(filepath_or_buffer=id_loc, # os.path.join(id_loc, id_files[0]),\n sep='\\t')\n except pd.errors.ParserError:\n main_log.info(\"Pandas ParserError: trying readlines for possible standalone Percolator file\")\n\n with open(id_loc, 'r') as f:\n f_ln = f.readlines()\n\n # The percolator output has different number of columns per row because the proteins are separated by tabs\n # Read the first half of the table without the protein IDs\n id_df = pd.DataFrame([ln.split('\\t')[0:5] for ln in f_ln[1:]])\n id_df.columns = ['PSMId', 'score', 'percolator q-value', 'posterior_error_prob', 'peptide']\n id_df['percolator q-value'] = id_df['percolator q-value'].astype(float)\n id_df['posterior_error_prob'] = id_df['posterior_error_prob'].astype(float)\n\n # Create a sequence column for compatibility\n id_df['sequence'] = [pep[2:-2] for pep in id_df['peptide']]\n\n # Then read in the protein names and join them by comma instead of tab\n id_df['protein id'] = [','.join(ln.rstrip().split('\\t')[5:]) for ln in f_ln[1:]]\n\n # Split the PSMId column to create file_idx, scan, and charge.\n id_df['charge'] = [psm.split('_')[-2] for psm in id_df['PSMId']]\n id_df['charge'] = id_df['charge'].astype(int)\n id_df['scan'] = [psm.split('_')[-3] for psm in id_df['PSMId']]\n id_df['scan'] = id_df['scan'].astype(int)\n # The file name is the underscore('_') split until the last 3 parts, then rejoined by underscore\n # in case there are underscores in the filename. We then remove everything\n # We then remove all directories to get base name\n id_df['file_name'] = [os.path.basename('_'.join(psm.split('_')[:-3])) for psm in id_df['PSMId']]\n\n # Get the sorted file names, hopefully this is the same index as the Crux Percolator output\n # TODO: Read the Percolator log file to get actual index and use file names to open the mzml instead\n sorted_index = sorted(set(id_df['file_name']))\n id_df['file_idx'] = id_df['file_name'].apply(sorted_index.index)\n\n # Get all the file indices in the Percolator results file.\n file_indices = list(set(id_df['file_idx']))\n\n # Check that the number of mzMLs in the mzML folder is the same as the maximum of the ID file's file_idx column.\n # Note this will throw an error if not every fraction results in at least some ID, but we will ignore for now.\n\n mzml_files = [f for f in os.listdir(mzml_loc) if re.match('^.*.mzML', f)]\n\n # Sort the mzML files by names\n # Note this may create a problem if the OS Percolator runs on has natural sorting (xxxx_2 before xxxx_10)\n # But we will ignore for now\n mzml_files.sort()\n\n # Throw an error if there is no mzML file in the mzml directory\n assert len(mzml_files) != 0, '[error] no mzml files in the specified directory'\n assert len(mzml_files) == max(file_indices) + 1, '[error] number of mzml files not matching id list'\n\n # For each file index (fraction), open the mzML file, and create a subset Percolator ID dataframe\n for idx in file_indices:\n\n # Logging mzML\n main_log.info('Reading mzml file: {0} ({1} of {2})'.format(mzml_files[idx],\n str(idx + 1),\n str(len(file_indices)),\n )\n )\n\n # Make a subset dataframe with the current file index (fraction) being considered\n fraction_id_df = id_df[id_df['file_idx'] == idx]\n\n # Arrange the PSM rows by scan number\n fraction_id_df = fraction_id_df.sort_values(by='scan').reset_index(drop=True)\n\n # Open the mzML file\n fraction_mzml = Mzml(path=os.path.join(mzml_loc, mzml_files[idx]),\n precision=precision)\n fraction_mzml.parse_mzml_ms2()\n\n # Loop through each qualifying row in sub_df_filtered\n for i in tqdm.trange(len(fraction_id_df)):\n\n # Get current scan number\n scan = fraction_id_df.loc[i, 'scan']\n\n # If q-value filter is on, skip any row that fails the filter.\n if fraction_id_df.loc[i, 'percolator q-value'] > q_filter:\n continue\n\n # If the protein-unique PSM filter is on, skip any row that fails the filter.\n if unique_only and len(fraction_id_df.loc[i, 'protein id'].split(',')) > 1:\n continue\n\n # If this is a qualifying row, get the spectrum in the mzML file by scan number\n try:\n spectrum = fraction_mzml.msdata.get(scan)\n\n except KeyError:\n main_log.error('[error] spectrum index out of bound')\n continue\n\n #except xml.etree.ElementTree.ParseError:\n # if args.verbosity == 2:\n # print('[verbosity 2] XML eTree does not appear to be able to read this spectrum',\n # '(scan number:', str(scan) + ')', sep=' ')\n # continue\n\n #assert spectrum['ms level'] > 1, '[error] specified spectrum is a full scan'\n\n # For each reporter, check that the spectrum has that peak using pymzml\n # This returns a (m/z, intensity) tuple\n # We will append the intensity of each reporter to a list\n\n # Get the intensity of each reporter\n tmt_intensities = quantify_spec.quantify_reporters(idx=idx,\n scan=scan,\n spectrum=spectrum,\n precision=precision,\n reporters=reporters,\n digits=2)\n\n # Grow the results into an output list of lists (creating if does not exist)\n try:\n output_list.append(tmt_intensities)\n\n except NameError:\n output_list = [tmt_intensities]\n\n # Turn the output list into a data frame\n output_df_columns = ['file_idx', 'scan', ]\n\n for reporter in reporters:\n output_df_columns.append('m' + str(reporter))\n\n output_df_columns.append('spectrum_int')\n\n output_df = pd.DataFrame(output_list, columns=output_df_columns)\n\n # Final output, merging the input and output tables\n final_df = pd.merge(id_df, output_df, how='left')\n\n # Create output directory if it does not exist\n save_path = os.path.join(args.out, 'tmt_out.txt')\n\n # Save the file\n final_df.to_csv(save_path, sep='\\t')\n\n main_log.info(\"Run completed successfully.\")\n return sys.exit(os.EX_OK)\n\n\ndef main():\n \"\"\"\n Entry point\n\n :return:\n \"\"\"\n\n import argparse\n\n parser = argparse.ArgumentParser(description='pytmt returns ms2 tmt quantification values'\n 'from Percolator (Crux or Standalone) output')\n\n parser.add_argument('mzml', help='path to folder containing mzml files')\n\n parser.add_argument('id', help='path to percolator target psms output file')\n\n parser.add_argument('-u', '--unique', action='store_true', help='quantify unique peptides only')\n\n parser.add_argument('-q', '--qvalue',\n help='quantify peptides with q value below this threshold [default: 1.0]',\n type=float,\n default=1.0)\n\n parser.add_argument('-m', '--multiplex',\n help='TMT-plex (0, 2, 6, 10, 11, 16) [default:10]',\n type=int,\n default=10)\n\n parser.add_argument('-p', '--precision',\n help='ms2 spectrum mass shift tolerance in ppm [default: 10]',\n type=int,\n default=10)\n\n parser.add_argument('-o', '--out', help='name of the output directory [default: tmt_out]',\n default='tmt_out')\n\n\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s {version}'.format(version=__version__))\n\n parser.set_defaults(func=quant)\n\n\n # Print help message if no arguments are given\n\n if len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n\n # Parse all the arguments\n args = parser.parse_args()\n\n # Run the function in the argument\n args.func(args)\n","sub_path":"pytmt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613529389","text":"#!/usr/bin/env python3\n# _ _ _| _ _\n# (_ | (_| |_) (_|\n# |\n# scraper to search for item on sale in a specific page\n# this script was made to run in a cronjob, that's why i use absolute paths\n#\n# scraper para encontrar item em promoção em determinada página\n# este# script foi feito para rodar em um cronjob, por isso utilizei\n# caminho absoluto ao chamar o subprocesso de notificação\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nimport subprocess\nimport argparse\n\n\ndef read_page(url):\n user_agent = \"Mozilla/5.0 (X11; Linux x86_64; rv:82.0)\" \\\n \"Gecko/20100101 Firefox/82.0\"\n headers = {\"User-Agent\": user_agent}\n request = urllib.request.Request(url, None, headers)\n response = urllib.request.urlopen(request)\n html = response.read()\n soup = BeautifulSoup(html, \"html.parser\")\n page_string = soup.get_text()\n return page_string\n\n\ndef find_item(items, page_string):\n items_string = \"|\".join(items)\n search_query = re.compile(items_string, re.IGNORECASE)\n items_found = search_query.findall(page_string)\n items_found = list(dict.fromkeys(items_found))\n return items_found\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Search for items on sale.\")\n parser.add_argument(\"-i\", \"--items\", type=str, required=True, nargs=\"+\",\n help='item(s) to search')\n parser.add_argument(\"-u\", \"--url\", type=str, required=True, help='url')\n args = parser.parse_args()\n items = args.items\n url = args.url\n\n html = read_page(url)\n results = find_item(items, html)\n\n if not results:\n quit()\n else:\n items = \", \".join(results)\n subprocess.Popen([\"/usr/bin/notify-send\", \"-u\", \"normal\",\n \"-t\", \"60000\",\n \"{} em promoção!\".format(items)])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"promoscrapper.py","file_name":"promoscrapper.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"124621593","text":"from selenium import webdriver\nfrom PIL import Image\nimport glob\nimport os\nimport time\nfrom selenium.webdriver.support import expected_conditions as EC\nIMAGE_PATH =\"Images/\"\n\n# https://www.insecam.org/en/view/431570/\n# https://www.insecam.org/en/view/831786/\n# https://www.insecam.org/en/view/807253/\n# https://www.insecam.org/en/view/422846/\n# https://www.insecam.org/en/view/271799/\n# https://www.insecam.org/en/view/513555/\n# https://www.insecam.org/en/view/833391/\n# https://www.insecam.org/en/bytag/Traffic/?page=33\n#\n\ndef open_driver():\n chromeOptions = webdriver.ChromeOptions()\n chromeOptions.add_argument('window-size=1920x1080')\n chromeOptions.add_argument('disable-extensions')\n chromeOptions.add_argument(\"--headless\")\n return webdriver.Chrome(options=chromeOptions)\n\ndef get_and_save_image(driver):\n driver.get('https://www.insecam.org/en/view/833391/')\n element = driver.find_element_by_id('image0')\n driver.execute_script(\"arguments[0].scrollIntoView();\", element)\n location = element.location_once_scrolled_into_view\n size = element.size\n driver.save_screenshot(\"pageImage.png\")\n crop_and_save_image(location,size)\n\ndef crop_and_save_image(location, size):\n x = location['x']\n y = location['y']\n width = location['x']+size['width']\n height = location['y']+size['height']\n im = Image.open(\"pageImage.png\")\n im = im.convert('RGB')\n im = im.crop((int(x), int(y), int(width), int(height)))\n im.save(create_image_path_and_name())\ndef create_image_path_and_name():\n list_of_files = glob.glob(IMAGE_PATH+\"*\")\n if len(list_of_files) == 0:\n return IMAGE_PATH+\"00001.jpg\"\n latest_file = max(list_of_files, key=os.path.getctime)\n number = int(latest_file.split(\"/\")[1].split(\".\")[0])\n number += 1\n number = str(number).zfill(5)\n return IMAGE_PATH+number+\".jpg\"\n\ndriver = open_driver()\nwhile 1:\n get_and_save_image(driver)\n time.sleep(60)\ndriver.close()\n","sub_path":"cam_screenshot.py","file_name":"cam_screenshot.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"533849347","text":"import cv2\nimport math\nimport os\nimport numpy as np\ncap = cv2.VideoCapture(0)\nimport socket\n\n\nclass Frame:\n _frame=None\n center=0\n x=0\n y=0\n radius=0\n mask=None\n res=None\n\n def __init__(self, frame):\n self._frame = frame\n\n\ndef color_detection(frame):\n #print(\"color_detection\")\n #cv2.imshow(\"frame\", frame._frame)\n #cv2.waitKey(7)\n hsv = cv2.cvtColor(frame._frame, cv2.COLOR_RGB2HSV)\n #cv2.imshow(\"frame\", frame._frame)\n #cv2.waitKey(7) \n lower_blue = np.array([44,54,63])\n upper_blue = np.array([71,255,255])\n mask = cv2.inRange(hsv, lower_blue, upper_blue )\n #cv2.imshow(\"mask\", mask)\n #cv2.waitKey(5)\n frame.res = cv2.bitwise_and(frame._frame, frame._frame, mask=mask)\n # rengin daha net gorulmesi icin erode ve dilate filtrelerinde gecirilip daha net goruntulenmesi saglanir\n mask = cv2.erode(mask, None, iterations=2)\n mask = cv2.dilate(mask, None, iterations=2)\n # cevreler (contours) bu fonksiyon ile hesaplanir\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n frame.mask = mask\n #print(\"cnts: {}\".format(cnts))\n center = None\n if len(cnts) > 0:\n #print(\"cnts: {}\".format(cnts))\n # Maksimum alanli cevre baz alinir ve etrafina cember cizilir\n c = max(cnts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n # En buyuk cevrenin momentleri hesaplanir\n M = cv2.moments(c)\n # Objenin merkezi center degiskenine atanmistir\n center = int(M[\"m10\"] / M[\"m00\"]),int(M[\"m01\"] / M[\"m00\"])\n\n frame.x = x\n frame.y = y\n frame.radius = radius\n frame.center = center\n \n return frame\n\n\ndef send_center(sock, center):\n print(\"send_center\")\n sock.sendto(str(center), (UDP_IP, UDP_PORT))\n\n\ndef draw_circle_and_center(frame):\n print(\"draw_circle_and_center\")\n if frame.radius > 10:\n # cember ve merkez noktasinin cizdirildigi fonksiyonlar\n cv2.circle(frame._frame, (int(frame.x), int(frame.y)), int(frame.radius), (255, 0, 0), 2)\n cv2.circle(frame._frame, frame.center, 5, (0, 0, 0), -1)\n\n cv2.imshow('frame',frame._frame)\n cv2.imshow('mask',frame.mask)\n cv2.imshow('res',frame.res)\t\n\n\nif __name__ == '__main__':\n\n UDP_IP = \"127.0.0.1\"\n UDP_PORT = 5005\n sock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n\n while(True):\n _, frame = cap.read()\n print(\"frame: {}\".format(frame.shape))\n _frame = Frame(frame)\n _frame = color_detection(_frame)\n send_center(sock, _frame._frame)\n draw_circle_and_center(_frame)\n\n if cv2.waitKey(1) & 0xFF == ord ('q'):\n break\n\t\n\t\n\n\n\n\n","sub_path":"scripts/gimbal_color_detection.py","file_name":"gimbal_color_detection.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"545946576","text":"import os\n\ndef find_dup(path,newPath):\n\n res = readFile(path)\n\n writeFile(res, path, newPath)\n\n\ndef readFile(path):\n '''读取文件数据'''\n res = {}\n for file in os.listdir(path):\n if file.split('.')[-1] == 'txt':\n file_path = os.path.join(path, file)\n with open(file_path, 'rb') as f:\n for line in f.readlines():\n line = line.strip().decode()\n if line in res and file not in res[line]:\n res[line].append(file)\n else:\n res[line] = [file]\n return res\n\ndef writeFile(res,path,newPath):\n '''写入文件'''\n with open(newPath,'wb') as f:\n for k,v in res.items():\n if len(v) > 1:\n f.write(('%s\\n'%k).encode())\n for i in v:\n f.write(('--%s\\n'%i).encode())\n\n\n\n\nif __name__ == '__main__':\n find_dup('C:\\\\后端工程师-上机题目\\\\寻找重复行','C:\\\\后端工程师-上机题目')","sub_path":"find_dup.py","file_name":"find_dup.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"218979115","text":"from discord.ext.commands import Bot, Context, errors, Cog, command, group, has_permissions\nfrom discord import Embed, Member, Role, utils, Color\n\n\ndef setup(bot: Bot):\n global settings\n settings = bot.settings\n bot.add_cog(Utils(bot))\n\n\nclass Utils(Cog):\n \"\"\"utils\"\"\"\n def __init__(self, bot: Bot):\n self.bot = bot\n if 'reaction_roles' not in settings:\n settings['reaction_roles'] = {}\n\n @command(name='pfp')\n async def pfp(self, ctx: Context, user: Member = None):\n \"\"\"Get user's pfp\"\"\"\n if user is None:\n user = ctx.author\n await ctx.send(f'{str(user)}\\'s pfp')\n await ctx.send(user.avatar_url)\n\n @command(name='color')\n @has_permissions(administrator=True)\n async def color(self, ctx: Context, color: Color):\n if ctx.message.reference is None:\n raise errors.UserInputError('You must reply to a reaction role embed to use this command')\n\n msg = await ctx.fetch_message(ctx.message.reference.message_id)\n\n if msg.author.id != self.bot.user.id:\n raise errors.UserInputError('`rr add` can only be used on messages sent by ZedUtils')\n\n embed = msg.embeds[0]\n embed.color = color\n\n await msg.edit(embed=embed)\n await ctx.message.delete()\n\n @group(name='rr')\n @has_permissions(administrator=True)\n async def rr(self, ctx):\n \"\"\"Create and manage reaction roles\"\"\"\n ...\n\n @rr.command(name='create')\n async def create(self, ctx: Context, name: str):\n \"\"\"Create reaction role embed\"\"\"\n embed = Embed(\n title=name\n )\n embed.set_author(\n name='Reaction roles',\n icon_url=ctx.guild.icon_url,\n url='https://github.com/foxnerdsaysmoo/zedutils'\n )\n msg = await ctx.send(embed=embed)\n await ctx.message.delete()\n settings['reaction_roles'][str(msg.id)] = []\n await settings.save()\n\n @rr.command(name='add')\n async def add(self, ctx: Context, emoji: str, option_name: str, role: Role):\n \"\"\"Add role to reaction role embed\"\"\"\n if ctx.message.reference is None:\n raise errors.UserInputError('You must reply to a reaction role embed to use this command')\n\n msg = await ctx.fetch_message(ctx.message.reference.message_id)\n\n if msg.author.id != self.bot.user.id:\n raise errors.UserInputError('`rr add` can only be used on messages sent by ZedUtils')\n\n embed = msg.embeds[0]\n\n if embed.description:\n if str(emoji) in embed.description:\n parts = embed.description.split('\\n')\n description = ''\n for part in parts:\n if not part.startswith(str(emoji)):\n description += part\n embed.description = description\n\n embed.description += f'\\n{emoji} {option_name}'\n else:\n embed.description = f'\\n{emoji} {option_name}'\n\n await msg.edit(embed=embed)\n await msg.add_reaction(emoji)\n\n await ctx.message.delete()\n\n settings['reaction_roles'][str(msg.id)].append([emoji, role.id])\n await settings.save()\n\n @Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if payload.user_id == self.bot.user.id:\n return\n\n reaction = payload.emoji\n msg_id = str(payload.message_id)\n\n if msg_id in settings['reaction_roles'].keys():\n rr_settings = settings['reaction_roles'][msg_id]\n\n if str(reaction) in dict(rr_settings).keys():\n guild = self.bot.get_guild(payload.guild_id)\n user = utils.get(guild.members, id=payload.user_id)\n\n await Member.add_roles(user, utils.get(guild.roles, id=dict(rr_settings)[str(reaction)]))\n\n @Cog.listener()\n async def on_raw_reaction_remove(self, payload):\n if payload.user_id == self.bot.user.id:\n return\n\n reaction = payload.emoji\n msg_id = str(payload.message_id)\n\n if msg_id in settings['reaction_roles'].keys():\n rr_settings = settings['reaction_roles'][msg_id]\n\n if str(reaction) in dict(rr_settings).keys():\n guild = self.bot.get_guild(payload.guild_id)\n user = utils.get(guild.members, id=payload.user_id)\n\n await Member.remove_roles(user, utils.get(guild.roles, id=dict(rr_settings)[str(reaction)]))\n\n","sub_path":"cogs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"238962511","text":"import pandas as pd\nimport geopandas as gp\nimport folium as fo\nimport streamlit as st\nfrom streamlit_folium import folium_static\nimport altair as alt\nimport pydeck as pdk\nimport numpy as np\n\nData1 = pd.read_csv('https://raw.github.com/Maplub/odsample/9cfc6ae4dd6a23e874b60b095d9dfcac11cddbed/20190101.csv')\nData2 = pd.read_csv('https://raw.github.com/Maplub/odsample/9cfc6ae4dd6a23e874b60b095d9dfcac11cddbed/20190102.csv')\nData3 = pd.read_csv('https://raw.github.com/Maplub/odsample/9cfc6ae4dd6a23e874b60b095d9dfcac11cddbed/20190103.csv')\nData4 = pd.read_csv('https://raw.github.com/Maplub/odsample/9cfc6ae4dd6a23e874b60b095d9dfcac11cddbed/20190104.csv')\nData5 = pd.read_csv('https://raw.github.com/Maplub/odsample/9cfc6ae4dd6a23e874b60b095d9dfcac11cddbed/20190105.csv')\n\nDATE_TIME = \"timestart\"\nData1[DATE_TIME] = pd.to_datetime(Data1[DATE_TIME])\nData2[DATE_TIME] = pd.to_datetime(Data2[DATE_TIME])\nData3[DATE_TIME] = pd.to_datetime(Data3[DATE_TIME])\nData4[DATE_TIME] = pd.to_datetime(Data4[DATE_TIME])\nData5[DATE_TIME] = pd.to_datetime(Data5[DATE_TIME])\n\nData1.drop(['Unnamed: 0','latstop','lonstop','timestop','Unnamed: 7','Unnamed: 8','Unnamed: 9','Unnamed: 10','Unnamed: 11'],axis=1,inplace=True)\nData2.drop(['Unnamed: 0','latstop','lonstop','timestop','Unnamed: 7','Unnamed: 8','Unnamed: 9','Unnamed: 10','Unnamed: 11','Unnamed: 12','Unnamed: 13'],axis=1,inplace=True)\nData3.drop(['Unnamed: 0','latstop','lonstop','timestop','Unnamed: 7','Unnamed: 8','Unnamed: 9','Unnamed: 10','Unnamed: 11'],axis=1,inplace=True)\nData4.drop(['Unnamed: 0','latstop','lonstop','timestop','Unnamed: 7','Unnamed: 8','Unnamed: 9','Unnamed: 10','Unnamed: 11'],axis=1,inplace=True)\nData5.drop(['Unnamed: 0','latstop','lonstop','timestop','Unnamed: 7','Unnamed: 8','Unnamed: 9','Unnamed: 10','Unnamed: 11'],axis=1,inplace=True)\n\n# CREATING FUNCTION FOR MAPS\n\ndef map(data, lat, lon, zoom):\n st.write(pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n initial_view_state={\n \"latitude\": lat,\n \"longitude\": lon,\n \"zoom\": zoom,\n \"pitch\": 50,\n },\n layers=[\n pdk.Layer(\n \"HexagonLayer\",\n data=data,\n get_position=[\"lonstartl\", \"latstartl\"],\n radius=100,\n elevation_scale=4,\n elevation_range=[0, 1000],\n pickable=True,\n extruded=True,\n ),\n ]\n ))\n\n\t# LAYING OUT THE TOP SECTION OF THE APP\nrow1_1, row1_2 = st.columns((2,3))\n\nwith row1_1:\n st.title(\"BKK Ridesharing Data\")\n hour_selected = st.slider(\"Select hour of pickup\", 0, 23)\n\nwith row1_2:\n st.write(\n \"\"\"\n ##\n Examining how pickups vary over time in Bangkok City's.\n By sliding the slider on the left you can view different slices of time and explore different transportation trends.\n \"\"\")\nst.write('Made by Sanhanat Chalanant ')\n\n# FILTERING DATA BY HOUR SELECTED\nData1 = Data1[Data1[DATE_TIME].dt.hour == hour_selected]\nData2 = Data2[Data2[DATE_TIME].dt.hour == hour_selected]\nData3 = Data3[Data3[DATE_TIME].dt.hour == hour_selected]\nData4 = Data4[Data4[DATE_TIME].dt.hour == hour_selected]\nData5 = Data5[Data5[DATE_TIME].dt.hour == hour_selected]\n\n\n\n\n# SETTING THE ZOOM LOCATIONS \nzoom_level = 12\nbkk = [13.736717,\t100.523186]\n\nst.write('''**All BKK City from %i:00 and %i:00**''' % (hour_selected, (hour_selected + 1) % 24))\n\n\n#with row3_1:\nst.write(\"** 01/01/2019 **\" )\nmap(Data1, bkk[0], bkk[1], 11)\n\n\nst.write(\"** 02/01/2019 **\" )\nmap(Data2, bkk[0], bkk[1], 11)\n\nst.write(\"** 03/01/2019 **\" )\nmap(Data3, bkk[0], bkk[1], 11)\n\nst.write(\"** 04/01/2019 **\" )\nmap(Data4, bkk[0], bkk[1], 11)\n\nst.write(\"** 04/01/2019 **\" )\nmap(Data5, bkk[0], bkk[1], 11)\n\n \n# FILTERING DATA FOR THE HISTOGRAM\nfiltered1 = Data1[\n (Data1[DATE_TIME].dt.hour >= hour_selected) & (Data1[DATE_TIME].dt.hour < (hour_selected + 1))\n ]\n\nhist1 = np.histogram(filtered1[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]\n\nchart_data1 = pd.DataFrame({\"minute\": range(60), \"pickups\": hist1})\n\n# LAYING OUT THE HISTOGRAM SECTION\n\nst.write(\"\")\n\nst.write(\"**Breakdown of rides in 01/01/2019 per minute between %i:00 and %i:00**\" % (hour_selected, (hour_selected + 1) % 24))\n\nst.altair_chart(alt.Chart(chart_data1)\n .mark_area(\n interpolate='step-after',\n ).encode(\n x=alt.X(\"minute:Q\", scale=alt.Scale(nice=False)),\n y=alt.Y(\"pickups:Q\"),\n tooltip=['minute', 'pickups']\n ).configure_mark(\n opacity=0.5,\n color='orange'\n ), use_container_width=True)\n#day2\n\nfiltered2 = Data2[\n (Data2[DATE_TIME].dt.hour >= hour_selected) & (Data2[DATE_TIME].dt.hour < (hour_selected + 1))\n ]\n\nhist2 = np.histogram(filtered2[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]\n\nchart_data2 = pd.DataFrame({\"minute\": range(60), \"pickups\": hist2})\n\n# LAYING OUT THE HISTOGRAM SECTION\n\nst.write(\"\")\n\nst.write(\"**Breakdown of rides in 02/01/2019 per minute between %i:00 and %i:00**\" % (hour_selected, (hour_selected + 1) % 24))\n\nst.altair_chart(alt.Chart(chart_data2)\n .mark_area(\n interpolate='step-after',\n ).encode(\n x=alt.X(\"minute:Q\", scale=alt.Scale(nice=False)),\n y=alt.Y(\"pickups:Q\"),\n tooltip=['minute', 'pickups']\n ).configure_mark(\n opacity=0.5,\n color='orange'\n ), use_container_width=True)\n\n#day2\n\nfiltered3 = Data3[\n (Data3[DATE_TIME].dt.hour >= hour_selected) & (Data3[DATE_TIME].dt.hour < (hour_selected + 1))\n ]\n\nhist3 = np.histogram(filtered3[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]\n\nchart_data3 = pd.DataFrame({\"minute\": range(60), \"pickups\": hist3})\n\n# LAYING OUT THE HISTOGRAM SECTION\n\nst.write(\"\")\n\nst.write(\"**Breakdown of rides in 03/01/2019 per minute between %i:00 and %i:00**\" % (hour_selected, (hour_selected + 1) % 24))\n\nst.altair_chart(alt.Chart(chart_data3)\n .mark_area(\n interpolate='step-after',\n ).encode(\n x=alt.X(\"minute:Q\", scale=alt.Scale(nice=False)),\n y=alt.Y(\"pickups:Q\"),\n tooltip=['minute', 'pickups']\n ).configure_mark(\n opacity=0.5,\n color='orange'\n ), use_container_width=True)\n\n#day4\n\nfiltered4 = Data4[\n (Data4[DATE_TIME].dt.hour >= hour_selected) & (Data4[DATE_TIME].dt.hour < (hour_selected + 1))\n ]\n\nhist4 = np.histogram(filtered4[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]\n\nchart_data4 = pd.DataFrame({\"minute\": range(60), \"pickups\": hist4})\n\n# LAYING OUT THE HISTOGRAM SECTION\n\nst.write(\"\")\n\nst.write(\"**Breakdown of rides in 04/01/2019 per minute between %i:00 and %i:00**\" % (hour_selected, (hour_selected + 1) % 24))\n\nst.altair_chart(alt.Chart(chart_data4)\n .mark_area(\n interpolate='step-after',\n ).encode(\n x=alt.X(\"minute:Q\", scale=alt.Scale(nice=False)),\n y=alt.Y(\"pickups:Q\"),\n tooltip=['minute', 'pickups']\n ).configure_mark(\n opacity=0.5,\n color='orange'\n ), use_container_width=True)\n\n#day5\n\nfiltered5 = Data5[\n (Data5[DATE_TIME].dt.hour >= hour_selected) & (Data5[DATE_TIME].dt.hour < (hour_selected + 1))\n ]\n\nhist5 = np.histogram(filtered5[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]\n\nchart_data5 = pd.DataFrame({\"minute\": range(60), \"pickups\": hist5})\n\n# LAYING OUT THE HISTOGRAM SECTION\n\nst.write(\"\")\n\nst.write(\"**Breakdown of rides in 05/01/2019 per minute between %i:00 and %i:00**\" % (hour_selected, (hour_selected + 1) % 24))\n\nst.altair_chart(alt.Chart(chart_data5)\n .mark_area(\n interpolate='step-after',\n ).encode(\n x=alt.X(\"minute:Q\", scale=alt.Scale(nice=False)),\n y=alt.Y(\"pickups:Q\"),\n tooltip=['minute', 'pickups']\n ).configure_mark(\n opacity=0.5,\n color='orange'\n ), use_container_width=True)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"173924051","text":"#簡単な出力\nclass aiueo:\n def test_print(self):\n print(\"test\")\n def haruto_print(self):\n print(\"haruto\")\n\n#計算\nclass Calculator:\n def plus(self,value1,value2):\n print(value1+value2)\n def minus(self,value1,value2):\n print(value1-value2)\n def kakeru(self,value1,value2):\n print(value1*value2)\n def wari(self,value1,value2):\n print(value1/value2)\n\n#utf-8に変換するクラス\nclass Encode:\n def e_utf8(self,string):\n return string.encode('utf-8')\n def d_utf8(self,string):\n return string.decode('utf-8')\n\n#ユークリッドしよう\nclass Euclid:\n def set_value(self,value1,value2):\n if value1 < value2:\n tmp = value1\n value1 = value2\n value2 = tmp\n return value1,value2\n else:\n return value1,value2\n\n def start_euclid(self,value1,value2):\n r = 0\n while r != 1:\n try:\n s = value1 / value2\n r = value1 % value2\n except ZeroDivisionError:\n print(\"ZeroDivisonError\")\n break\n value1 = value2\n value2 = r\n return r\n\n\ntest = aiueo()\ntest.test_print()\ntest.haruto_print()\n\ncal = Calculator()\ncal.plus(4,2)\ncal.minus(4,2)\ncal.kakeru(4,2)\ncal.wari(4,2)\n\n#入力待ち\nstring = input(\"please type string:\")\n#インスタンスを生成\nenc = Encode()\neuc = Euclid()\nencode_string = enc.e_utf8(string)\nprint(encode_string)\nprint(enc.d_utf8(encode_string))\n\n#2つの数字を入力してユークリッドする\ninput_value1 = input(\"please push number1:\")\ninput_value2 = input(\"please push number2:\")\ninput_value1 = int(input_value1)\ninput_value2 = int(input_value2)\n\n#数字の入力と大小の並べ替え\ninput_value1,input_value2 = euc.set_value(input_value1,input_value2)\nprint(input_value1,input_value2)\n\n#ユークリッド開始\nprint(euc.start_euclid(input_value1,input_value2))\n\n","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"402795146","text":"from psychopy import visual, core\n\n#setup stimulus\nwin=visual.Window([400,400])\ngabor = visual.GratingStim(win, tex='sin', mask='gauss', sf=5,\n name='gabor', autoLog=False)\nfixation = visual.GratingStim(win, tex=None, mask='gauss', sf=0, size=0.02,\n name='fixation', autoLog=False)\n\nclock = core.Clock()\n#let's draw a stimulus for 200 frames, drifting for frames 50:100\nfor frameN in range(200):#for exactly 200 frames\n if 10 <= frameN < 150: # present fixation for a subset of frames\n fixation.draw()\n if 50 <= frameN < 100: # present stim for a different subset\n gabor.setPhase(0.1, '+') # increment by 10th of cycle\n gabor.draw()\n win.flip()\n","sub_path":"week2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"534273316","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\nfrom collections import Iterable, Counter\nimport types\n\nimport numpy as np\nimport numpy.linalg as LA\n\ndef _min(xs):\n return min(x for x in xs if x!=0)\n\ndef _max(xs):\n return max(x for x in xs if x!=0)\n\nclass Field(object):\n '''Field has 3 (principal) propteries\n name: name\n type_: type \n range_: range [None]'''\n defaultPart = 12\n\n def __init__(self, name='none', type_=str, range_=None):\n self.name = name\n self.type_ = type_\n self.range_ = range_\n self.is_hybrid = False\n if type_ == float:\n self.is_discrete = False\n if self.range_:\n self.part = Field.defaultPart\n else:\n self.step = 1\n else:\n self.is_discrete = True\n self.dim = 1\n\n @property\n def is_continuous(self):\n return not self.is_discrete\n \n\n @property\n def part(self):\n return self._part\n\n @part.setter\n def part(self, s):\n self._part = s\n self.step = (self.range_[1] - self.range_[0]) / s\n \n\n @staticmethod\n def fromValue(value, name='none'):\n '''Infer the type from a value\n \n Arguments:\n value {anything} -- any value\n \n Keyword Arguments:\n name {str} -- the name of the field (default: {'none'})\n \n Returns:\n Field\n '''\n\n if isinstance(value, str):\n return Field(name, str)\n elif isinstance(value, (int, np.int64)):\n return Field(name, int)\n elif isinstance(value, (float, np.float64)):\n return Field(name, float)\n elif isinstance(value, Iterable):\n t = Field.get_type(value)\n f = Field(name, t)\n f.dim = len(value)\n f.is_hybrid = True\n f.types = set(t)\n return f\n else:\n return Field(name, type(value))\n\n @staticmethod\n def get_type(value):\n if isinstance(value, str):\n return str\n elif isinstance(value, (int, np.int64)):\n return int\n elif isinstance(value, (float, np.float64)):\n return float\n elif isinstance(value, Iterable):\n return tuple(map(Field.get_type, value))\n\n @staticmethod\n def fromValues(values, name='none', continuous=False):\n if values:\n f = Field.fromValue(values[0], name)\n if f.is_continuous or continuous:\n if isinstance(values[0], Iterable):\n A = np.array([value for value in values if 0 not in value])\n f.range_ = A.min(axis=0), A.max(axis=0)\n # stds = np.array([np.std([v[k] for v in values]) for k in range(f.dim)])\n f.part = Field.defaultPart\n f.is_hybrid = True\n cov = np.cov(np.transpose(A))\n f.cov = LA.inv(cov) * np.diag(cov).max()\n def ap(f, x, y):\n d = np.array(x)-np.array(y)\n return np.sqrt(np.dot(np.dot(d, f.cov), d)) < max(f.step)\n f.approx = types.MethodType(ap, f)\n else:\n f.range_ = _min(values), _max(values)\n f.part = Field.defaultPart\n f.is_discrete = False\n return f\n else:\n return Field(name, float)\n\n @staticmethod\n def fromValuesx(values, name='none', tol=0.01):\n\n if isinstance(values[0], int): # regarded as a continous variable\n c = Counter(values)\n if np.mean([n for a, n in c.items()]) / len(values) < tol:\n return Field.fromValues(values, name, continuous=True)\n else:\n return Field.fromValues(values, name)\n elif isinstance(values[0], str):\n return Field.fromValues(values, name)\n elif isinstance(values[0], Iterable):\n return Field.fromValues(values, name, continuous=True)\n else:\n return Field.fromValues(values, name)\n\n def __str__(self):\n return self.name\n\n def approx(self, a, b, step=None):\n if step is None:\n step = self.step\n if self.is_discrete:\n return a == b\n elif self.is_hybrid:\n return np.all(abs(ai - bi) < s for ai, bi, s in zip(a, b, self.step))\n else:\n return abs(a - b) < self.step\n","sub_path":"field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"150827554","text":"from PyExpUtils.results.results import Result, whereParametersEqual, getBest, splitOverParameter\nfrom PyExpUtils.results.indices import listIndices\nfrom PyExpUtils.models.ExperimentDescription import ExperimentDescription\nimport unittest\nimport numpy as np\n\nexp = ExperimentDescription({\n 'metaParameters': {\n 'alpha': [1.0, 0.5, 0.25],\n 'ratio': [1.0, 2.0, 4.0, 8.0],\n 'model': {\n 'name': ['PR', 'ESARSA'],\n }\n },\n})\n\nclass TestResults(unittest.TestCase):\n def test_Results(self):\n results = [Result('fake/path', exp, i) for i in listIndices(exp)]\n\n r = results[0]\n self.assertDictEqual(r.params, { 'alpha': 1.0, 'ratio': 1.0, 'model': { 'name': 'PR' }})\n r = results[1]\n self.assertDictEqual(r.params, { 'alpha': 0.5, 'ratio': 1.0, 'model': { 'name': 'PR' }})\n self.assertEqual(r.idx, 1)\n\n # can overload load function\n class TestResult(Result):\n def _load(self):\n # (mean, std, runs)\n return (1, 2, 3)\n\n results = [TestResult('fake/path', exp, i) for i in listIndices(exp)]\n\n r = results[0]\n self.assertEqual(r.mean(), 1)\n\n\n def test_splitOverParameter(self):\n results = (Result('fake/path', exp, i) for i in listIndices(exp))\n\n split_results = splitOverParameter(results, 'alpha')\n self.assertEqual(list(split_results), [1.0, 0.5, 0.25]) # check keys\n self.assertEqual(len(split_results[1.0]), 8)\n\n for key in split_results:\n sub_results = split_results[key]\n for res in sub_results:\n self.assertEqual(res.params['alpha'], key)\n\n results = (Result('fake/path', exp, i) for i in listIndices(exp))\n\n split_results = splitOverParameter(results, 'model.name')\n self.assertEqual(list(split_results), ['PR', 'ESARSA']) # check keys\n self.assertEqual(len(split_results['PR']), 12)\n\n\n def test_getBest(self):\n # lowest\n load_counter = 0\n class TestResult(Result):\n def _load(self):\n nonlocal load_counter\n load_counter += 1\n return (np.ones(100) * load_counter, np.ones(100), 3)\n\n results = (TestResult('fake/path', exp, i) for i in listIndices(exp))\n\n best = getBest(results)\n self.assertEqual(best.mean()[0], 1)\n\n # highest\n results = (TestResult('fake/path', exp, i) for i in listIndices(exp))\n\n best = getBest(results, comparator=lambda a, b: a > b)\n self.assertEqual(best.mean()[0], load_counter)\n\n def test_whereParametersEqual(self):\n results = (Result('fake/path', exp, i) for i in listIndices(exp))\n\n results = whereParametersEqual(results, {\n 'alpha': 1.0,\n 'epsilon': 2, # if a parameter in the filter list does not exist, ignore it\n 'model': {\n 'name': 'ESARSA',\n },\n })\n results = list(results)\n\n self.assertEqual(len(results), 4)\n\n got = [r.params['ratio'] for r in results]\n expected = [1.0, 2.0, 4.0, 8.0]\n self.assertListEqual(got, expected)\n","sub_path":"tests/results/test_results.py","file_name":"test_results.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629311508","text":"\"\"\"\nA minimal example of TBNNAM for binary classification without attention.\n\"\"\"\nfrom functools import partial\nimport numpy as np\nimport keras\nimport keras.backend as K\nfrom keras import callbacks, layers, optimizers, regularizers\nfrom keras.initializers import Initializer\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import set_random_seed\n\nfrom minimal_example_common_params import (\n num_samples,\n num_tokens_at_once,\n embedding_dim,\n l2_weight,\n num_entity_classes,\n num_event_classes,\n dim_ent,\n seed_value,\n MASK_VALUE_IGNORE_POSITION,\n beta,\n learning_rate,\n num_training_epochs,\n log_dir,\n lstm_dim,\n event_embedding_dim,\n)\n\n\nnp.random.seed(seed_value)\nset_random_seed(seed_value)\n\n\nclass ScaledRandomNormal(Initializer):\n def __init__(self, seed=None, scale_factor=1.0):\n self.mean = 0.0\n self.stddev = 1.0\n self.seed = seed\n self.scale_factor = scale_factor\n\n def __call__(self, shape, dtype=None):\n return self.scale_factor * K.random_normal(\n shape, self.mean, self.stddev, dtype=dtype, seed=self.seed\n )\n\n def get_config(self):\n return {\n \"mean\": self.mean,\n \"stddev\": self.stddev,\n \"seed\": self.seed,\n \"scale_factor\": self.scale_factor,\n }\n\n\ndef biased_mean_squared_error(\n y_true: np.ndarray, y_pred: np.ndarray, *, beta: float = 0.0\n):\n return K.mean(K.square(y_pred - y_true) * K.square(1 + (y_true * beta)), axis=-1)\n\n\nK.clear_session()\nword_embedding_input = layers.Input(\n shape=(num_tokens_at_once, embedding_dim), name=\"w_emb\"\n)\nentity_type_input = layers.Input(shape=(num_tokens_at_once,), name=\"entity_type_input\")\nevent_type_input = layers.Input(shape=(1,), name=\"event_type_input\")\nentity_type_embedding = layers.Embedding(\n num_entity_classes,\n dim_ent,\n name=\"ent_emb\",\n embeddings_initializer=ScaledRandomNormal(seed=seed_value, scale_factor=0.01),\n embeddings_regularizer=regularizers.l2(l2_weight),\n)(entity_type_input)\nevent_type_embedding = layers.Embedding(\n num_event_classes,\n event_embedding_dim,\n name=\"evt_emb\",\n embeddings_initializer=ScaledRandomNormal(seed=seed_value, scale_factor=0.01),\n embeddings_regularizer=regularizers.l2(l2_weight),\n)(event_type_input)\nconcat = layers.concatenate([word_embedding_input, entity_type_embedding])\nmask = layers.Masking(mask_value=MASK_VALUE_IGNORE_POSITION)(concat)\nencoder = layers.LSTM(\n lstm_dim,\n kernel_regularizer=regularizers.l2(l2_weight),\n bias_regularizer=regularizers.l2(l2_weight),\n)(mask)\nmult = layers.Flatten()(\n layers.multiply(\n [\n layers.Reshape((-1, 1))(encoder),\n layers.Reshape((1, -1))(layers.Flatten()(event_type_embedding)),\n ]\n )\n)\nsigmoid = layers.Dense(\n 1,\n activation=\"sigmoid\",\n kernel_regularizer=regularizers.l2(l2_weight),\n bias_regularizer=regularizers.l2(l2_weight),\n name=\"output\",\n)(mult)\nmodel = keras.Model(\n inputs=[word_embedding_input, entity_type_input, event_type_input], outputs=sigmoid\n)\n# TODO\nmodel.layers[6].trainable = False\nloss_function = partial(biased_mean_squared_error, beta=beta)\nloss_function.__name__ = biased_mean_squared_error.__name__\nmodel.compile(optimizer=optimizers.Adam(lr=learning_rate), loss=loss_function)\nmodel.summary()\ncustom_objects = {\"biased_mean_squared_error\": loss_function}\n\n\nembeddings = np.random.standard_normal(\n size=(num_samples, num_tokens_at_once, embedding_dim)\n)\nentity_types = np.random.random_integers(\n low=0, high=num_entity_classes - 1, size=(num_samples, num_tokens_at_once)\n)\n# one sentence at a time\nevent_types = np.random.random_integers(\n low=0, high=num_event_classes - 1, size=(num_samples, 1)\n)\nlabels = np.random.random_integers(low=0, high=1, size=(num_samples, 1))\nres = train_test_split(\n embeddings,\n entity_types,\n event_types,\n labels,\n test_size=0.10,\n shuffle=False,\n stratify=None,\n)\nembeddings_train, embeddings_test = res[0], res[1]\nentity_types_train, entity_types_test = res[2], res[3]\nevent_types_train, event_types_test = res[4], res[5]\nlabels_train, labels_test = res[6], res[7]\ntraining_batch_size = min(100, len(labels_test) // 2)\nvalidation_data = (\n {\n \"w_emb\": embeddings_test,\n \"entity_type_input\": entity_types_test,\n \"event_type_input\": event_types_test,\n },\n {\"output\": labels_test},\n)\nmodel.fit(\n [embeddings_train, entity_types_train, event_types_train],\n labels_train,\n epochs=num_training_epochs,\n batch_size=training_batch_size,\n validation_data=validation_data,\n callbacks=[\n callbacks.TensorBoard(\n log_dir=str(log_dir / \"m3\"),\n histogram_freq=1,\n write_graph=True,\n write_grads=True,\n update_freq=\"batch\",\n )\n ],\n)\n\n\ndef _compute_elemwise_op_output_shape(shape1, shape2):\n \"\"\"Computes the shape of the resultant of an elementwise operation.\n\n # Arguments\n shape1: tuple or None. Shape of the first tensor\n shape2: tuple or None. Shape of the second tensor\n\n # Returns\n expected output shape when an element-wise operation is\n carried out on 2 tensors with shapes shape1 and shape2.\n tuple or None.\n\n # Raises\n ValueError: if shape1 and shape2 are not compatible for\n element-wise operations.\n \"\"\"\n if None in [shape1, shape2]:\n return None\n elif len(shape1) < len(shape2):\n return _compute_elemwise_op_output_shape(shape2, shape1)\n elif not shape2:\n return shape1\n output_shape = list(shape1[: -len(shape2)])\n for i, j in zip(shape1[-len(shape2) :], shape2):\n if i is None or j is None:\n output_shape.append(None)\n elif i == 1:\n output_shape.append(j)\n elif j == 1:\n output_shape.append(i)\n else:\n if i != j:\n raise ValueError(\n \"Operands could not be broadcast \"\n \"together with shapes \" + str(shape1) + \" \" + str(shape2)\n )\n output_shape.append(i)\n return tuple(output_shape)\n","sub_path":"tbnnam_minimal_example_3.py","file_name":"tbnnam_minimal_example_3.py","file_ext":"py","file_size_in_byte":6203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"283381131","text":"from sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)\n\n\nfrom sklearn import preprocessing\n# Standarize the features\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n\nfrom sklearn import linear_model \nclf = linear_model.SGDClassifier(loss='log', random_state=42)\nclf.fit(X_train, y_train_setosa)\nprint (clf.coef_,clf.intercept_)\n\n\nfrom sklearn import metrics\ny_train_pred = clf2.predict(X_train)\nmetrics.accuracy_score(y_train, y_train_pred)\nmetrics.classification_report(y_test, y_pred, target_names=iris.target_names)\n\n\nmetrics.auc(x, y, reorder=False)\nimport numpy as np\nfrom sklearn import metrics\ny = np.array([1, 1, 2, 2])\npred = np.array([0.1, 0.4, 0.35, 0.8])\nfpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)\nmetrics.auc(fpr, tpr)\n\n\n\n\nfrom sklearn import cluster\nclf_sepal = cluster.KMeans(init='k-means++', n_clusters=3, random_state=33)\nclf_sepal.fit(X_train4[:,0:2])\n\n\n\n\ncv = sklearn.cross_validation.KFold(X_train.shape[0], folds, shuffle=True, random_state=33)\nscores = sklearn.cross_validation.cross_val_score(clf, X_train, y_train, cv=cv)\nprint ('Average score using {}-fold crossvalidation:{:.2f}'.format(folds,np.mean(scores)))\n","sub_path":"example/scikit.py","file_name":"scikit.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"495818850","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 16 16:03:59 2019\r\n\r\n@author: sscherrer/chalbeisen\r\n\r\nThis program defines the neural network for the audio-visual speech separation \r\nmodel for two independent speakers.\r\n\"\"\"\r\n\r\nfrom __future__ import absolute_import, division, print_function\r\n\r\nimport tensorflow as tf\r\nimport os\r\nimport random\r\n\r\n\r\ntf.logging.set_verbosity(tf.logging.INFO)\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: defines the loss as mse between labels and predictions\r\nparam: \r\n calc_mask1: prediction of the avspeech model for speaker 1\r\n calc_mask2: prediction of the avspeech model for speaker 2\r\n aud_mix: superimposed audio signal (both speaker)\r\n lbl_aud1: label of speaker 1\r\n lbl_aud2: label of speaker 2\r\n\r\nreturn: loss (scalar)\r\n------------------------------------------------------------------------------\r\n'''\r\ndef loss_mean_squared_error(calc_mask1, calc_mask2, aud_mix, lbl_aud1, lbl_aud2):\r\n calc_mask1 = tf.complex(calc_mask1[:,:,:,0], calc_mask1[:,:,:,1])\r\n calc_mask2 = tf.complex(calc_mask2[:,:,:,0], calc_mask2[:,:,:,1])\r\n aud_mix = tf.complex(aud_mix[:,:,:,0], aud_mix[:,:,:,1])\r\n lbl_aud1 = tf.complex(lbl_aud1[:,:,:,0], lbl_aud1[:,:,:,1])\r\n lbl_aud2 = tf.complex(lbl_aud2[:,:,:,0], lbl_aud2[:,:,:,1])\r\n \r\n pred1 = tf.math.multiply(aud_mix,calc_mask1)\r\n pred2 = tf.math.multiply(aud_mix,calc_mask2)\r\n\r\n l1 = tf.square(tf.real(pred1-lbl_aud1)) + tf.square(tf.imag(pred1-lbl_aud1))\r\n l2 = tf.square(tf.real(pred2-lbl_aud2)) + tf.square(tf.imag(pred2-lbl_aud2))\r\n return tf.reduce_mean(tf.add(l1, l2))\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: model function for the neural network\r\nparam: \r\n features: input data as dictionary\r\n labels: labels as dictionary\r\n mode: mode (EVAL or TRAIN)\r\n\r\nreturn: EstimatorSpec for TRAIN or EVAL\r\n------------------------------------------------------------------------------\r\n'''\r\ndef cnn_model_fn(features, labels, mode):\r\n \r\n # define names for the nodes in tensorboard, used for prediction\r\n vid1 = tf.identity(features[\"vid1\"], name=\"vid1\")\r\n vid2 = tf.identity(features[\"vid2\"], name=\"vid2\")\r\n aud_mix = tf.identity(features[\"aud\"], name=\"aud_mix\")\r\n aud1 = labels[\"aud1\"]\r\n aud2 = labels[\"aud2\"]\r\n \r\n #audio stream\r\n def dnn_audio(layer_name, x):\r\n \r\n with tf.variable_scope(layer_name): \r\n input_layer_raw = tf.reshape(x, [-1, x.shape[1], x.shape[2], x.shape[3]])\r\n input_layer = tf.transpose(input_layer_raw,[0,2,1,3])\r\n \r\n # 1. convolutional layer \r\n with tf.variable_scope('layer1_a'):\r\n conv1_a = tf.layers.conv2d(\r\n inputs=input_layer,\r\n filters=96,\r\n kernel_size=[1, 7],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv1_a\")\r\n \r\n # 1. batch normalization\r\n norm1_a = tf.layers.batch_normalization(\r\n inputs=conv1_a,\r\n name=\"norm1_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 2. convolutional layer \r\n with tf.variable_scope('layer2_a'):\r\n conv2_a = tf.layers.conv2d(\r\n inputs=norm1_a,\r\n filters=96,\r\n kernel_size=[7, 1],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv2_a\")\r\n \r\n # 2. batch normalization\r\n norm2_a = tf.layers.batch_normalization(\r\n inputs=conv2_a,\r\n name=\"norm2_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 3. convolutional layer \r\n with tf.variable_scope('layer3_a'):\r\n conv3_a = tf.layers.conv2d(\r\n inputs=norm2_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv3_a\")\r\n \r\n # 3. batch normalization\r\n norm3_a = tf.layers.batch_normalization(\r\n inputs=conv3_a,\r\n name=\"norm3_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 4. convolutional layer \r\n with tf.variable_scope('layer4_a'):\r\n conv4_a = tf.layers.conv2d(\r\n inputs=norm3_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(2,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv4_a\")\r\n \r\n # 4. batch normalization\r\n norm4_a = tf.layers.batch_normalization(\r\n inputs=conv4_a,\r\n name=\"norm4_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 5. convolutional layer \r\n with tf.variable_scope('layer5_a'):\r\n conv5_a = tf.layers.conv2d(\r\n inputs=norm4_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(4,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv5_a\")\r\n \r\n # 5. batch normalization\r\n norm5_a = tf.layers.batch_normalization(\r\n inputs=conv5_a,\r\n name=\"norm5_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 6. convolutional layer \r\n with tf.variable_scope('layer6_a'):\r\n conv6_a = tf.layers.conv2d(\r\n inputs=norm5_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(8,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv6_a\")\r\n \r\n # 6. batch normalization\r\n norm6_a = tf.layers.batch_normalization(\r\n inputs = conv6_a,\r\n name=\"norm6_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 7. convolutional layer \r\n with tf.variable_scope('layer7_a'):\r\n conv7_a = tf.layers.conv2d(\r\n inputs=norm6_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(16,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv7_a\")\r\n \r\n # 7. batch normalization\r\n norm7_a = tf.layers.batch_normalization(\r\n inputs=conv7_a,\r\n name=\"norm7_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 8. convolutional layer \r\n with tf.variable_scope('layer8_a'):\r\n conv8_a = tf.layers.conv2d(\r\n inputs=norm7_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(32,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv8_a\")\r\n \r\n # 8. batch normalization\r\n norm8_a = tf.layers.batch_normalization(\r\n inputs=conv8_a,\r\n name=\"norm8_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 9. convolutional layer \r\n with tf.variable_scope('layer9_a'):\r\n conv9_a = tf.layers.conv2d(\r\n inputs=norm8_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv9_a\")\r\n \r\n # 9. batch normalization\r\n norm9_a = tf.layers.batch_normalization(\r\n inputs=conv9_a,\r\n name=\"norm9_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 10. convolutional layer \r\n with tf.variable_scope('layer10_a'):\r\n conv10_a = tf.layers.conv2d(\r\n inputs=norm9_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(2,2),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv10_a\")\r\n \r\n # 10. batch normalization\r\n norm10_a = tf.layers.batch_normalization(\r\n inputs=conv10_a,\r\n name=\"norm10_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 11. convolutional layer \r\n with tf.variable_scope('layer11_a'):\r\n conv11_a = tf.layers.conv2d(\r\n inputs=norm10_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(4,4),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv11_a\")\r\n \r\n # 11. batch normalization\r\n norm11_a = tf.layers.batch_normalization(\r\n inputs=conv11_a,\r\n name=\"norm11_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 12. convolutional layer \r\n with tf.variable_scope('layer12_a'):\r\n conv12_a = tf.layers.conv2d(\r\n inputs=norm11_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(8,8),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv12_a\")\r\n \r\n # 12. batch normalization\r\n norm12_a = tf.layers.batch_normalization(\r\n inputs=conv12_a,\r\n name=\"norm12_a\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 13. convolutional layer \r\n with tf.variable_scope('layer13_a'):\r\n conv13_a = tf.layers.conv2d(\r\n inputs=norm12_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(16,16),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv13_a\")\r\n \r\n # 13. batch normalization\r\n norm13_a = tf.layers.batch_normalization(\r\n inputs=conv13_a,\r\n name=\"norm13_a\",\r\n\t\t\t\t\t\ttraining= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 14. convolutional layer \r\n with tf.variable_scope('layer14_a'):\r\n conv14_a = tf.layers.conv2d(\r\n inputs=norm13_a,\r\n filters=96,\r\n kernel_size=[5, 5],\r\n dilation_rate=(32,32),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv14_a\")\r\n \r\n # 14. batch normalization\r\n norm14_a = tf.layers.batch_normalization(\r\n inputs=conv14_a,\r\n name=\"norm14_a\",\r\n\t\t\t\t\t\ttraining= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 15. convolutional layer \r\n with tf.variable_scope('layer15_a'):\r\n conv15_a = tf.layers.conv2d(\r\n inputs=norm14_a,\r\n filters=8,\r\n kernel_size=[1, 1],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv15_a\")\r\n \r\n # 15. batch normalization\r\n norm15_a = tf.layers.batch_normalization(\r\n inputs=conv15_a,\r\n name=\"norm15_a\",\r\n\t\t\t\t\t\ttraining= mode==tf.estimator.ModeKeys.TRAIN)\r\n\t\t\t\t\t\t\r\n with tf.variable_scope('output_audio'):\r\n output_a = tf.reshape(norm15_a,[-1,norm15_a.shape[1],norm15_a.shape[2]*norm15_a.shape[3]], name=\"output_a\")\r\n \r\n return output_a\r\n \r\n \r\n # visual stream\r\n def dnn_video(layer_name, x, audio_time, sharedWeights): \r\n with tf.name_scope(layer_name):\r\n \r\n input_reshape = tf.reshape(x,[-1,x.shape[1], x.shape[2],1])\r\n input_video = tf.transpose(input_reshape,[0,1,3,2])\r\n with tf.variable_scope('dnn_speaker', reuse=sharedWeights):\r\n \r\n # 1. convolutional layer \r\n with tf.variable_scope('layer1_v'):\r\n conv1_v = tf.layers.conv2d(\r\n inputs=input_video,\r\n filters=256,\r\n kernel_size=[7,1],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv1_v\")\r\n \r\n # 1. batch normalization\r\n conv1_v_norm = tf.layers.batch_normalization(\r\n conv1_v,\r\n name=\"norm1_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 2. convolutional layer \r\n with tf.variable_scope('layer2_v'):\r\n conv2_v = tf.layers.conv2d(\r\n inputs=conv1_v_norm,\r\n filters=256,\r\n kernel_size=[5,1],\r\n dilation_rate=(1,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv2_v\")\r\n \r\n # 2. batch normalization\r\n conv2_v_norm = tf.layers.batch_normalization(\r\n conv2_v,\r\n name=\"norm2_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 3. convolutional layer \r\n with tf.variable_scope('layer3_v'):\r\n conv3_v = tf.layers.conv2d(\r\n inputs=conv2_v_norm,\r\n filters=256,\r\n kernel_size=[5,1],\r\n dilation_rate=(2,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv3_v\")\r\n \r\n # 3. batch normalization\r\n conv3_v_norm = tf.layers.batch_normalization(\r\n conv3_v,\r\n name=\"norm3_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 4. convolutional layer \r\n with tf.variable_scope('layer4_v'):\r\n conv4_v = tf.layers.conv2d(\r\n inputs=conv3_v_norm,\r\n filters=256,\r\n kernel_size=[5,1],\r\n dilation_rate=(4,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv4_v\")\r\n \r\n # 4. batch normalization\r\n conv4_v_norm = tf.layers.batch_normalization(\r\n conv4_v,\r\n name=\"norm4_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 5. convolutional layer \r\n with tf.variable_scope('layer5_v'):\r\n conv5_v = tf.layers.conv2d(\r\n inputs=conv4_v_norm,\r\n filters=256,\r\n kernel_size=[5,1],\r\n dilation_rate=(8,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv5_v\")\r\n \r\n # 5. batch normalization\r\n conv5_v_norm = tf.layers.batch_normalization(\r\n conv5_v,\r\n name=\"norm5_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 6. convolutional layer \r\n with tf.variable_scope('layer6_v'):\r\n conv6_v = tf.layers.conv2d(\r\n inputs=conv5_v_norm,\r\n filters=256,\r\n kernel_size=[5,1],\r\n dilation_rate=(16,1),\r\n padding=\"same\",\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"conv6_v\")\r\n \r\n # 6. batch normalization\r\n conv6_v_norm = tf.layers.batch_normalization(\r\n conv6_v,\r\n name=\"norm6_v\",\r\n training= mode==tf.estimator.ModeKeys.TRAIN)\r\n \r\n # resize time axis (nearest neighbor interpolation) \r\n with tf.variable_scope('output_video'):\r\n conv6_reshape = tf.transpose(conv6_v_norm, [0,1,3,2])\r\n \r\n conv6_resize = tf.image.resize_nearest_neighbor(\r\n conv6_reshape,\r\n align_corners=True,\r\n size=[audio_time,conv6_reshape.shape[2]],\r\n name=\"ResizeVideo\")\r\n \r\n output_v = tf.reshape(conv6_resize, [-1,conv6_resize.shape[1],conv6_resize.shape[2]])\r\n \r\n return output_v\r\n \r\n # audio stream\r\n audio = dnn_audio(\"dnn_audio\",aud_mix)\r\n \r\n #visual stream of two speakers (shared weights)\r\n with tf.variable_scope(\"dnn_visual\"):\r\n s1 = dnn_video(\"speaker1\", vid1, audio.shape[1], False)\r\n s2 = dnn_video(\"speaker2\", vid2, audio.shape[1], True)\r\n # concatenate the two visual streams\r\n visual = tf.concat([s1, s2], axis=2, name=\"fusion_visual\")\r\n \r\n # audio-visual fusionfusion\r\n with tf.variable_scope(\"fusion\"):\r\n fusion = tf.concat([audio, visual], axis=2, name=\"audio_visual\")\r\n \r\n # bidirectional LSTM\r\n with tf.variable_scope(\"BLSTM\"):\r\n cell_fw = tf.nn.rnn_cell.LSTMCell(200)\r\n cell_bw = tf.nn.rnn_cell.LSTMCell(200)\r\n \r\n outputs, states = tf.nn.bidirectional_dynamic_rnn(\r\n cell_fw=cell_fw,\r\n cell_bw=cell_bw,\r\n inputs=fusion,\r\n dtype=tf.float32,\r\n scope=\"blstm\")\r\n \r\n output = tf.concat(outputs,2)\r\n \r\n # fully connected layer\r\n with tf.variable_scope('fc_layers'):\r\n fc1 = tf.layers.dense(\r\n inputs=output,\r\n units=600,\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"fully_connected1\")\r\n \r\n fc2 = tf.layers.dense(\r\n inputs=fc1,\r\n units=600,\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"fully_connected2\")\r\n \r\n fc3 = tf.layers.dense(\r\n inputs=fc2,\r\n units=600,\r\n activation=tf.nn.relu,\r\n kernel_initializer=tf.initializers.he_uniform(),\r\n name=\"fully_connected3\")\r\n \r\n # fully connected layer for complex masks\r\n with tf.variable_scope('output'):\r\n complex_mask = tf.layers.dense(\r\n inputs=fc3,\r\n units=257*2*2,\r\n activation=tf.nn.sigmoid,\r\n name=\"complex_mask\")\r\n \r\n complex_mask_out = tf.reshape(complex_mask, [-1,fc3.shape[1],257,2,2])\r\n complex_mask_out_t = tf.transpose(complex_mask_out,[0,2,1,3,4], name=\"output_masks\")\r\n \r\n # define a name for output tensor (contains the complex masks, stacked)\r\n prediction_masks = tf.identity(complex_mask_out_t, name=\"prediction_masks\")\r\n \r\n # check the shapes\r\n print(\"complex mask: \", complex_mask_out_t.shape) \r\n print(\"predictions: \", prediction_masks.shape) \r\n \r\n \r\n # calculate Loss (for both TRAIN and EVAL modes)\r\n with tf.name_scope('loss'):\r\n loss = loss_mean_squared_error(complex_mask_out_t[:,:,:,:,0], complex_mask_out_t[:,:,:,:,1], aud_mix, aud1, aud2)\r\n \r\n # add summary for tensorboard\r\n mse_loss_metric = tf.metrics.mean(loss)\r\n tf.summary.scalar('normal/mse_metric', mse_loss_metric[1])\r\n tf.summary.scalar('normal/loss', loss)\r\n tf.summary.histogram('normal/loss', loss)\r\n \r\n # define a name for the loss (needed for the logging hook)\r\n mse_loss = tf.identity(loss, name=\"mse_loss\")\r\n \r\n # visualize biases and weights as histograms\r\n for var in tf.trainable_variables():\r\n tf.summary.histogram(var.name.replace(':','_'), var)\r\n \r\n # configure the Training Op (for TRAIN mode)\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n optimizer = tf.train.AdamOptimizer(learning_rate=0.00003)\r\n \r\n # update the UPDATE_OPS (needed for batch norm)\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(update_ops):\r\n train_op = optimizer.minimize(\r\n loss=loss,\r\n global_step=tf.train.get_global_step())\r\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\r\n \r\n # define a metric for EVAL mode\r\n eval_metric_ops = {\r\n \"mse_loss\": mse_loss_metric\r\n\t}\r\n\r\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)#, evaluation_hooks=evaluation_hooks\r\n\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: parser for TFRecords\r\nparam: \r\n record: single TFRecord\r\n \r\nreturn: \r\n audio: input: audio mixed spectrogram [257,298,2]\r\n video: input: face embeddings [2,75,512] (stacked)\r\n label: label: clean spectrogram per speaker [2,257,298,2] (stacked)\r\n------------------------------------------------------------------------------\r\n'''\r\ndef parser(record):\r\n keys_to_features = {\r\n 'audio_s1': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'audio_s2': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'audio_s3': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'video_s1': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'video_s2': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'video_s3': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'label_s1': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'label_s2': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'label_s3': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'label_s4': tf.FixedLenFeature(shape=[1], dtype=tf.int64),\r\n 'audio': tf.FixedLenFeature(shape=[257,298,2], dtype=tf.float32),\r\n 'video': tf.FixedLenFeature(shape=[2,75,512], dtype=tf.float32),\r\n 'label': tf.FixedLenFeature(shape=[2,257,298,2], dtype=tf.float32)\r\n \r\n }\r\n \r\n features = tf.parse_single_example(record, keys_to_features)\r\n\r\n audio = tf.cast(features['audio'], tf.float32)\r\n video = tf.cast(features['video'], tf.float32)\r\n label = tf.cast(features['label'], tf.float32)\r\n \r\n #print(train_audio.shape)\r\n return audio, video, label\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: input function for TRAIN mode\r\nparam: \r\n train_dir_tfrecord: dirs of train data as a list\r\n doshuffle: True if you want to shuffle the data (default=True)\r\n batch_size: batch_size for training (default=4)\r\n num_epoches: number of epochs to train (default=1)\r\n \r\nreturn:\r\n x: input data (features) as dictionary for TRAIN\r\n y: labels as dictionary for TRAIN\r\n------------------------------------------------------------------------------\r\n'''\r\ndef train_input_fn(train_dir_tfrecord, doshuffle=True, batch_size=4, num_epochs=1):\r\n filenames = []\r\n for t in train_dir_tfrecord:\r\n for dirs,_,files in os.walk(t):\r\n for f in files:\r\n filenames.append(os.path.abspath(os.path.join(dirs, f)))\r\n \r\n print(\"Trainingsdaten: \", len(filenames))\r\n random.shuffle(filenames)\r\n \r\n # define a dataset for train data\r\n train_dataset = tf.data.TFRecordDataset(filenames,num_parallel_reads=4) \r\n \r\n if doshuffle:\r\n train_dataset = train_dataset.shuffle(buffer_size=500)\r\n \r\n train_dataset = train_dataset.map(map_func=parser, num_parallel_calls=4)\r\n train_dataset = train_dataset.batch(batch_size)\r\n train_dataset = train_dataset.repeat(num_epochs)\r\n train_dataset = train_dataset.prefetch(4)\r\n train_iterator = train_dataset.make_one_shot_iterator()\r\n \r\n train_audio, train_video, train_labels = train_iterator.get_next()\r\n \r\n x={\"vid1\": train_video[:,0,:,:],\r\n \"vid2\": train_video[:,1,:,:],\r\n \"aud\": train_audio}\r\n y={\"aud1\": train_labels[:,0,:,:,:],\r\n \"aud2\": train_labels[:,1,:,:,:]}\r\n \r\n return x, y\r\n\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: input function for EVAL mode\r\nparam: \r\n eval_dir_tfrecord: dirs of eval data as a list\r\n doshuffle: True if you want to shuffle the data (default=False)\r\n batch_size: batch_size for training (default=4)\r\n num_epoches: number of epochs to train (default=1)\r\n \r\nreturn:\r\n x: input data (features) as dictionary for EVAL\r\n y: labels as dictionary for EVAL \r\n------------------------------------------------------------------------------\r\n'''\r\ndef eval_input_fn(eval_dir_tfrecord, doshuffle=False, batch_size=4, num_epochs=1): \r\n \r\n filenames = []\r\n for e in eval_dir_tfrecord:\r\n for dirs,_,files in os.walk(e):\r\n for f in files:\r\n filenames.append(os.path.abspath(os.path.join(dirs, f)))\r\n print(\"Evaluierungsdaten: \", len(filenames))\r\n \r\n # define a dataset for eval data\r\n eval_dataset = tf.data.TFRecordDataset(filenames,num_parallel_reads=4)\r\n \r\n if doshuffle:\r\n eval_dataset = eval_dataset.shuffle(buffer_size=500)\r\n eval_dataset = eval_dataset.map(map_func=parser, num_parallel_calls=4)\r\n eval_dataset = eval_dataset.batch(batch_size)\r\n eval_dataset = eval_dataset.repeat(num_epochs)\r\n eval_dataset = eval_dataset.prefetch(4)\r\n eval_iterator = eval_dataset.make_one_shot_iterator()\r\n \r\n eval_audio, eval_video, eval_labels = eval_iterator.get_next()\r\n \r\n x={\"vid1\": eval_video[:,0,:,:],\r\n \"vid2\": eval_video[:,1,:,:],\r\n \"aud\": eval_audio}\r\n y={\"aud1\": eval_labels[:,0,:,:,:],\r\n \"aud2\": eval_labels[:,1,:,:,:]}\r\n \r\n return x, y\r\n\r\n\r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: basic function, defines:\r\n - train and eval data dir as lists\r\n - run configuration (gpu options, save_checkpoints_steps)\r\n - custom estimator (classifier)\r\n - logging hook during training\r\n - train und eval specification with lambda operator\r\nparam: \r\n model_dir: dir where the model should be saved\r\n\r\nreturn: - \r\n------------------------------------------------------------------------------\r\n'''\r\ndef traineval(model_dir):\r\n # define the train data dirs as a list (absolute path)\r\n train_dir_tfrecord = [\"D:/BA_LipRead/03_DeepNet/data_tfrecord_train/\", \r\n \"D:/BA_LipRead/03_DeepNet/data_tfrecord_train_1/\", \r\n \"D:/BA_LipRead/03_DeepNet/data_tfrecord_train_2/\", \r\n \"C:/temp/BA_LipRead/03_DeepNet/data_tfrecord_train_2_1/\", \r\n \"G:/BA_LipRead/data_tfrecord_train_2_2/\", \r\n \"G:/BA_LipRead/data_tfrecord_train_3/\", \r\n \"D:/BA_LipRead/03_DeepNet/data_tfrecord_train_4/\", \r\n \"G:/BA_LipRead/data_tfrecord_train_5/\"] \r\n\r\n # define the train data dirs as a list (absolute path) \r\n eval_dir_tfrecord = [\"D:/BA_LipRead/03_DeepNet/data_tfrecord_eval/\", \r\n \"D:/BA_LipRead/03_DeepNet/data_tfrecord_eval_1/\", \r\n \"C:/temp/BA_LipRead/03_DeepNet/data_tfrecord_eval_2/\", \r\n \"C:/temp/BA_LipRead/03_DeepNet/data_tfrecord_eval_3/\", \r\n \"G:/BA_LipRead/data_tfrecord_eval_4/\"] \r\n \r\n # option use dynamic gpu memory\r\n gpu_options = tf.GPUOptions(allow_growth=True)\r\n sess_config = tf.ConfigProto(gpu_options=gpu_options) \r\n\r\n # define run config, save checkpoints after 200 train steps\r\n run_config = tf.estimator.RunConfig(session_config = sess_config,save_checkpoints_steps=200)\r\n # create the custom estimator\r\n avspeech_classifier = tf.estimator.Estimator(\r\n model_fn=cnn_model_fn, \r\n model_dir=model_dir, \r\n config=run_config) \r\n \r\n # set up a logging hook, logging tensor \"mse_loss\" every 10 steps of training\r\n tensors_to_log = {\"error\": \"mse_loss\"}\r\n \r\n logging_hook = tf.train.LoggingTensorHook(\r\n tensors=tensors_to_log, every_n_iter=10) \r\n \r\n # define the train specification with lambda operator\r\n train_spec = tf.estimator.TrainSpec(\r\n input_fn=lambda: train_input_fn(train_dir_tfrecord, \r\n doshuffle=True, \r\n batch_size=2,\r\n num_epochs=200),\r\n hooks=[logging_hook])\r\n\r\n # define the eval specification with lambda operator\r\n # throttle sec: after how many seconds the model should be evaluated\r\n eval_spec = tf.estimator.EvalSpec(\r\n input_fn=lambda: eval_input_fn(eval_dir_tfrecord,\r\n doshuffle=False,\r\n batch_size=2,\r\n num_epochs=1),\r\n throttle_secs=100)\r\n \r\n # start training\r\n tf.estimator.train_and_evaluate(avspeech_classifier, train_spec, eval_spec)\r\n \r\n \r\n'''\r\n------------------------------------------------------------------------------\r\ndesc: main function\r\nparam: \r\n -\r\n------------------------------------------------------------------------------\r\n'''\r\ndef main(unused_argv):\r\n # define model dir\r\n model_dir=\"./logs/model_AVSpeech/\"\r\n \r\n traineval(model_dir)\r\n \r\nif __name__ == \"__main__\":\r\n tf.app.run()\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"models/model_AVSpeech_twoSpeakers.py","file_name":"model_AVSpeech_twoSpeakers.py","file_ext":"py","file_size_in_byte":34006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"521222482","text":"# 27. Uma fruteira está vendendo frutas com a seguinte tabela de preços:\n# Até 5 Kg Acima de 5 Kg\n# Morango R$ 2,50 por Kg R$ 2,20 por Kg\n# Maçã R$ 1,80 por Kg R$ 1,50 por Kg\n# Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra ultrapassar \n# R$ 25,00, receberá ainda um desconto de 10% sobre este total. Escreva um algoritmo \n# para ler a quantidade (em Kg) de morangos e a quantidade (em Kg) de maças adquiridas \n# e escreva o valor a ser pago pelo cliente.\n# Desenvolvido por Thiago Moreira de Souza Arrais\n# Fonte: https://github.com/ThiagoMSArrais/python-exercise/blob/master/Q27.py\n\ndef calcular_precos():\n \n #variável\n count = 0\n calculo_produto = 0\n \n #dados do produto.\n dados_produto = [(\"morango\", 2.50, 2.20), (\"maçã\", 1.80, 1.50)]\n \n while True:\n\n #variavel\n finalizar = False\n \n #perguntar qual tipo de produto desejado.\n produto = input(\"Por favor, informe o produto desejado(Morango ou Maçã):\")\n \n for x in range(2):\n #verificar se tem o produto desejado\n if produto.lower() == dados_produto[x][0]:\n #armazenar a posição do produto na variável count.\n count = x\n #Inserir o valor booleano True para a variável finalizar, para que possa interromper o loop while.\n finalizar = True\n #interromper o loop for caso tenha encontrado o determinado produto.\n break\n \n else:\n if x == 1:\n #Informa que o valor esta invalido.\n finalizar = False\n print (\"Valor inválido.\", produto)\n \n if finalizar:\n break\n\n while True:\n \n try:\n \n #obter o peso do produto.\n peso = float(input(\"Por favor, informe o peso desejado:\"))\n \n #verificar se o peso está acima de zero.\n if peso > 0:\n break\n \n else:\n continue\n\n except ValueError:\n print (\"valor Invalido do peso.\")\n continue\n\n #calculos do produto\n if peso <= 5 and peso > 0:\n #calculando o valor do produto com o peso.\n calculo_produto = dados_produto[count][1] * peso\n \n elif peso > 5:\n #calculando o valor do produto com o peso.\n calculo_produto = dados_produto[count][2] * peso\n #verificando se o peso é maior que 8kg ou o valor passa de R$25,00.\n if peso > 8 or calculo_produto > 25:\n calculo_produto = (dados_produto[count][2] * peso) - ((dados_produto[count][2] * peso) * 10 / 100)\n \n print (\"Valor a pagar:R$%.2f\" % calculo_produto)\n\ncalcular_precos()","sub_path":"exercicio27.py","file_name":"exercicio27.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"209128211","text":"# 치즈\n\n# 풀이 방법\n\n'''\ndfs 진행하면서 1을 만나면 +1 해주고 0이면 -1 해준다.\n그리고 3이상인 수와 -1을 0으로 초기화 해준다. 하고 나머지는 1로 다시 초기화 해준다.\n이것을 반복한다.\n'''\n\nimport sys\nfrom collections import *\nsys.setrecursionlimit(20000)\ninput = sys.stdin.readline\nN, M = map(int, input().split())\n\nMap = [list(map(int, list(input().split()))) for i in range(N)]\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\n\n\ndef in_Map(i, j):\n if i < 0 or j < 0 or i == N or j == M:\n return False\n return True\n\n# 치즈 녹이고 숫자 원상복구\n\n\ndef melt():\n for i in range(N):\n for j in range(M):\n if Map[i][j] == 1 or Map[i][j] == 2:\n Map[i][j] = 1\n else:\n Map[i][j] = 0\n\n# 녹을 치즈 고르기\n\n\ndef check_melt(x, y):\n Map[x][y] = -1\n for i in range(4):\n new_x = x+dx[i]\n new_y = y+dy[i]\n\n if in_Map(new_x, new_y):\n if Map[new_x][new_y] == 0:\n check_melt(new_x, new_y)\n elif Map[new_x][new_y] > 0:\n Map[new_x][new_y] += 1\n\n\ndef end_ch(map):\n ch = True\n for row in map:\n if 1 in row:\n ch = False\n break\n return ch\n\n\ntime = 0\nwhile not end_ch(Map):\n check_melt(0, 0)\n melt()\n time += 1\n\nprint(time)\n\n\n# 내가 푼 방법 =>시간초과\n\n'''\n조건 포인트 : 가장자리는 치즈가 놓이지 않는다.\n녹는 시간만 구하는 거면 너무 간단한 문제다.\n그래서 추가된 조건이 치즈 내부에 있는 공기는 무시한다는 것.\n1.시작점에서 bfs를 돌려 내부공기를 제외한 외부공기를 구한다.\n2.외부공기를 제외한 모든 영역을 치즈라고 가정하고 치즈를 녹인다.\n3.다시 시작점에서 bfs를 돌려서 영역을 나눈다.\n4.반복\n========>시간초과\n\n\n\n# 0,0에서 시작해서 0과 1을 임의로 나눈다.\n# 만약 시작전과 후가 같다면 더이상 makeMap을 할 필요가 없다.\ndef makeMap(map):\n newMap = [[1 for i in range(M)] for j in range(N)]\n visited = [[0 for i in range(M)] for j in range(N)]\n queue = deque([[0, 0]])\n while queue:\n x, y = queue.popleft()\n visited[x][y] = 1\n newMap[x][y] = 0\n for i in range(4):\n new_x = x+dx[i]\n new_y = y+dy[i]\n\n if not in_Map(new_x, new_y):\n continue\n if visited[new_x][new_y] == 1:\n continue\n if map[new_x][new_y] == 1:\n continue\n\n queue.append([new_x, new_y])\n\n if newMap == map:\n global makeMap_ch\n makeMap_ch = False\n return newMap\n else:\n return newMap\n\n# dfs를 돌려서 치즈를 녹여준다.\n\n\ndef dfs(i, j):\n visited = [[0 for i in range(M)] for j in range(N)]\n queue = deque([[i, j]])\n while queue:\n x, y = queue.popleft()\n visited[x][y] = 1\n count = 0\n for i in range(4):\n new_x = x+dx[i]\n new_y = y+dy[i]\n\n if not in_Map(new_x, new_y):\n continue\n if visited[new_x][new_y] == 1:\n continue\n if Map[new_x][new_y] == 0:\n count += 1\n continue\n queue.append([new_x, new_y])\n if count > 1:\n Map[x][y] = 0\n\n\ntotal = sum([sum(i) for i in Map])\ntime = 0\nmakeMap_ch = True\nwhile total != 0:\n if makeMap_ch:\n newMap = makeMap(Map)\n newMap = Map\n\n dfs_ch = False\n for i in range(1, N-1):\n for j in range(1, M-1):\n if newMap[i][j] == 1:\n dfs(i, j)\n time += 1\n dfs_ch = True\n break\n if dfs_ch:\n break\n\n total = sum([sum(i) for i in Map])\n\nprint(time)\n'''\n","sub_path":"백준/Python/알고파/구현/2638.py","file_name":"2638.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"509340802","text":"\nfrom sklearn.linear_model import SGDClassifier\nimport pickle\n\ndef sgd_classifier(train, test, trainLabels):\n #declaring classifier\n classifier = SGDClassifier(loss='perceptron',random_state=5)\n \n filename = 'sgd_model.sav'\n # clf = classifier.fit(train, trainLabels)\n # pickle.dump(clf, open(filename, 'wb'))\n classifier = pickle.load(open(filename, 'rb'))\n # prediction = clf.predict(test)\n prediction = classifier.predict(test)\n return prediction\n","sub_path":"notebook/sgd_classifier.py","file_name":"sgd_classifier.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"604206155","text":"# -*- encoding: utf-8 -*-\n\nfrom __future__ import print_function\nimport os\nfrom .writer import ImageWriter\nfrom ..parser import annotation, generic, surface, volume\nfrom ..model.constants import projections\n\n\nclass ImageProcessor(object):\n snapshot_name = \"snapshot\"\n snapshot_extension = \".png\"\n\n def __init__(self):\n self.parser_volume = volume.VolumeParser()\n self.parser_surface = surface.SurfaceParser()\n self.generic_parser = generic.GenericParser()\n self.annotation_parser = annotation.AnnotationParser()\n self.writer = ImageWriter()\n\n try:\n snapshot_count = int(os.environ['SNAPSHOT_NUMBER'])\n except ValueError:\n snapshot_count = 0\n\n self.snapshot_count = snapshot_count\n\n\n def _new_name(self, current_projection):\n file_name = self.snapshot_name + str(self.snapshot_count) + current_projection\n return file_name\n\n\n def is_surface_gifti(self, surface_path):\n gifti_extension = \".gii\"\n filename, extension = os.path.splitext(surface_path)\n\n if(extension == gifti_extension):\n return True\n else:\n return False\n\n\n def choose_parser_for_surface(self, surface_path):\n\n if (self.is_surface_gifti(surface_path)):\n return self.parser_surface.parse_gifti(surface_path)\n else:\n return self.parser_surface.parse_fs(surface_path)\n\n\n def show_single_volume(self, volume_path):\n\n volume = self.parser_volume.parse(volume_path)\n ras = [0.68, -53.32, -19.71] #self.generic_parser.get_ras_coordinates()\n\n for i in projections:\n volume_matrix = volume.align(i, ras)\n self.writer.write_matrix(volume_matrix, self._new_name(i))\n\n def overlap_2_volumes(self, background_path, overlay_path):\n\n volume_background = self.parser_volume.parse(background_path)\n volume_overlay = self.parser_volume.parse(overlay_path)\n ras = [0.68, -53.32, -19.71] #self.generic_parser.get_ras_coordinates()\n\n for i in projections:\n background_matrix = volume_background.align(i, ras)\n overlay_matrix = volume_overlay.align(i, ras)\n self.writer.write_2_matrices(background_matrix, overlay_matrix, self._new_name(i))\n\n\n def overlap_3_volumes(self, background_path, overlay_1_path, overlay_2_path):\n\n volume_background = self.parser_volume.parse(background_path)\n volume_overlay_1 = self.parser_volume.parse(overlay_1_path)\n volume_overlay_2 = self.parser_volume.parse(overlay_2_path)\n\n ras = [0.68, -53.32, -19.71] #self.generic_parser.get_ras_coordinates()\n\n for i in projections:\n background_matrix = volume_background.align(i, ras)\n overlay_1_matrix = volume_overlay_1.align(i, ras)\n overlay_2_matrix = volume_overlay_2.align(i, ras)\n self.writer.write_3_matrices(background_matrix, overlay_1_matrix, overlay_2_matrix, self._new_name(i))\n\n\n def overlap_surface_annotation(self, surface_path, annotation):\n annot = self.annotation_parser.parse(annotation)\n surface = self.choose_parser_for_surface(surface_path)\n self.writer.write_surface_with_annotation(surface, annot, self._new_name('surface_annotation'))\n\n\n def overlap_volume_surface(self, volume_background, surfaces_path):\n # TODO surface contour is a little lower than it should be\n # TODO the image and the contour are reversed (compared to freeview)\n volume = self.parser_volume.parse(volume_background)\n surfaces = [0 for _ in range(len(surfaces_path))]\n for i, surf in enumerate(surfaces_path):\n surfaces[i] = self.choose_parser_for_surface(surf)\n ras = [0.68, -53.32, -19.71] #self.generic_parser.get_ras_coordinates()\n for i in projections:\n X,Y,background_matrix = volume.align(i, ras)\n clear_flag = True\n for surface in surfaces:\n x_array, y_array = surface.get_x_y_array(i, ras)\n self.writer.write_matrix_and_surface(X,Y,background_matrix, x_array, y_array, clear_flag)\n clear_flag = False\n self.writer.save_figure(self._new_name(i))\n\n\n def overlap_volume_surfaces(self, volume_background, resampled_name):\n surfaces_path = os.path.expandvars(os.environ['SURF'])\n if resampled_name != '':\n resampled_name = '.' + resampled_name\n volume = self.parser_volume.parse(volume_background)\n ras = [0.68, -53.32, -19.71] #self.generic_parser.get_ras_coordinates()\n print(ras)\n for i in projections:\n clear_flag = True\n background_matrix = volume.align(i, ras)\n for k in ('rh', 'lh'):\n for j in ('pial', 'white'):\n current_surface = self.parser_surface.parse_gifti(surfaces_path + '/' + k + '.' + j + resampled_name + '.gii')\n surf_x_array, surf_y_array = current_surface.get_x_y_array(i, ras)\n self.writer.write_matrix_and_surfaces(background_matrix, surf_x_array, surf_y_array, clear_flag, j)\n clear_flag = False\n self.writer.save_figure(self._new_name(i))\n\n","sub_path":"bnm/recon/qc/image/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":5238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"307032503","text":"import copy, math\n\n\nclass Matrix:\n\n def __init__(self, file=None, array=None):\n\n self.row = 0\n self.column = 0\n self.matrix = []\n\n if file:\n self.matrix = self.load(file)\n self.row = len(self.matrix)\n self.column = len(self.matrix[0])\n\n elif array:\n self.matrix = array\n self.row = len(self.matrix)\n\n if type(array[0]) is int:\n self.column = 1\n else:\n self.column = len(self.matrix[0])\n\n else:\n raise ValueError('Illegal number of arguments') \n\n\n def __add__(self, other):\n if ((self.row, self.column) != (other.row, other.column)):\n raise ValueError('Matrices have different dimensions')\n\n mat = [[self.matrix[i][j] + other.matrix[i][j] for j in range (self.column)] for i in range(self.row)]\n\n return Matrix(array = mat)\n\n\n def __mul__(self, other):\n if (type(other) is Matrix):\n result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*other.matrix)] for X_row in self.matrix]\n \n return Matrix(array=result)\n\n else:\n self.matrix = [[other*num for num in row] for row in self.matrix]\n\n return self\n\n\n def __sub__(self, other):\n other = other * (-1)\n return self + other\n\n\n def __eq__(self, other):\n return self.matrix == other.matrix\n\n\n def transpone(self):\n mx_transposed = [[self.matrix[i][j] for i in range(self.row)] for j in range(self.column)]\n \n self.matrix = mx_transposed\n (self.row, self. column) = (self.column, self.row)\n\n return self\n\n\n def load(self, file):\n matrix = []\n with open(file, 'r') as fp:\n for line in fp:\n matrix.append([float(x) for x in line.split(' ')])\n\n return matrix\n\n\n def clone(self):\n other = copy.deepcopy(self.matrix)\n return Matrix(array=other)\n\n\n def print(self):\n for x in self.matrix:\n print(x)\n print()\n\n\n def save(self, file):\n with open(file, 'w') as dat:\n for row in self.matrix:\n for num in row:\n dat.write(str(num) + ' ')\n dat.write('\\n')\n\n\n def luDecomposition(self):\n eps = 10**(-15)\n\n if (self.row != self.column):\n raise TypeError(\"The matrix must be square for decomposition\")\n\n A = copy.deepcopy(self.matrix)\n\n for k in range(self.row-1):\n for i in range (k+1, self.row):\n\n if (abs(A[k][k]) <= eps):\n raise ValueError('LU decomposition - Cannot divide with zero')\n\n A[i][k] /= A[k][k]\n for j in range(k+1, self.row):\n A[i][j] -= A[i][k]*A[k][j]\n\n return Matrix(array=A)\n\n\n def lupDecomposition(self):\n A = copy.deepcopy(self.matrix)\n P = [i for i in range(self.row)]\n \n eps = 10**(-9)\n\n for i in range(self.row-1):\n pivot = i\n for j in range(i+1, self.row):\n if (abs(A[P[j]][i]) > abs(A[P[pivot]][i])):\n pivot = j\n P[i], P[pivot] = P[pivot], P[i]\n\n for j in range(i+1,self.row):\n if (abs(A[P[i]][i]) <= eps):\n raise ValueError('LUP decomposition - Cannot divide with zero')\n A[P[j]][i] /= A[P[i]][i]\n for k in range(i+1,self.row):\n A[P[j]][k] -= A[P[j]][i]*A[P[i]][k]\n\n A = Matrix.swapRows(A, P)\n return Matrix(array=A),P\n\n\n def getUpper(self):\n upper_matrix = copy.deepcopy(self.matrix)\n\n for i in range(self.row):\n for j in range(self.row):\n if j<i:\n upper_matrix[i][j] = 0\n \n return Matrix(array=upper_matrix)\n\n\n def getLower(self):\n lower_matrix = copy.deepcopy(self.matrix)\n\n for i in range(self.row):\n for j in range(self.row):\n if i==j:\n lower_matrix[i][j] = 1\n if j>i:\n lower_matrix[i][j] = 0\n\n return Matrix(array=lower_matrix)\n\n\n def forwardSubstitution(self, b_vector):\n y = self.row * [0]\n for i in range(self.row):\n y[i] = b_vector[i]\n for j in range(self.row):\n if (i==j):\n continue\n y[i] -= self.matrix[i][j]*y[j]\n\n return y\n\n\n def backwardSubstitution(self,y_vector):\n eps = 10**(-9)\n\n for i in reversed(range(0,self.row)):\n if abs(self.matrix[i][i]) < eps:\n raise ZeroDivisionError \n y_vector[i] /= self.matrix[i][i]\n for j in range(i):\n y_vector[j] -= self.matrix[j][i]*y_vector[i]\n\n return y_vector\n\n\n def solveLUP(self, b_vector):\n print(\"\\nSolution with LUP:\")\n LU,P = self.lupDecomposition()\n b_vector = Matrix.swapRows(b_vector, P) \n U = LU.getUpper()\n print(\"\\nMatrix U:\")\n U.print()\n L = LU.getLower()\n print(\"Matrix L:\")\n L.print()\n\n y = L.forwardSubstitution(b_vector)\n print(\"Vector y:\", y)\n x = U.backwardSubstitution(y)\n print(\"Vector x:\", x)\n\n\n def solveLU(self, b_vector):\n print(\"\\nSolution with LU:\")\n LU = self.luDecomposition()\n U = LU.getUpper()\n print(\"\\nMatrix U:\")\n U.print()\n L = LU.getLower()\n print(\"Matrix L:\")\n L.print()\n\n y = L.forwardSubstitution(b_vector)\n print(\"Vector y: \", y)\n x = U.backwardSubstitution(y)\n print(\"Vector x:\", x)\n print('Equation cannot be solved.')\n\n\n def inverse(self):\n inv = []\n\n A = self.clone()\n LU, P = A.lupDecomposition()\n U = LU.getUpper()\n L = LU.getLower()\n\n E = Matrix.identity(self.row)\n E.matrix = Matrix.swapRows(E.matrix,P)\n E.transpone()\n\n for e in E.matrix:\n y = L.forwardSubstitution(e)\n x = U.backwardSubstitution(y)\n inv.append(x)\n \n return Matrix(array=inv).transpone()\n\n\n @staticmethod\n def swapRows(A, P):\n new_matrix = []\n for i in P:\n new_matrix.append(A[i])\n return new_matrix\n\n\n @staticmethod\n def identity(size):\n return Matrix(array=[[1 if i==j else 0 for j in range(size)] for i in range(size)])","sub_path":"Computer Aided Analysis and Design/LAB1 - Solving equations using LUP decomposition/Matrix.py","file_name":"Matrix.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"271186121","text":"#!/usr/bin/env python\n# code:UTF-8 \n# @Author : SUN FEIFEI\nimport time\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\n\nfrom app.honor.student.homework.object_page.homework_page import Homework\nfrom app.honor.student.homework.object_page.result_page import ResultPage\nfrom app.honor.student.homework.test_data.sentence_transform_data import sentence_transform_operate\nfrom conf.decorator import teststep, teststeps\nfrom conf.base_page import BasePage\nfrom utils.get_attribute import GetAttribute\n\n\nclass SentenceTrans(BasePage):\n \"\"\"句型转换\"\"\"\n # 以下为 共有元素\n def __init__(self):\n self.result = ResultPage()\n\n @teststeps\n def wait_check_page(self):\n \"\"\"以“句型转换”的ID为依据\"\"\"\n locator = (By.XPATH, \"//android.widget.TextView[contains(@text,'句型转换')]\")\n try:\n WebDriverWait(self.driver, 20, 0.5).until(lambda x: x.find_element(*locator))\n return True\n except:\n return False\n\n @teststeps\n def wait_check_play_page(self):\n \"\"\"以“rate”的ID为依据\"\"\"\n locator = (By.XPATH, \"//android.widget.TextView[contains(@resource-id,\"\n \"'{}rate')]\".format(self.id_type()))\n try:\n WebDriverWait(self.driver, 20, 0.5).until(lambda x: x.find_element(*locator))\n return True\n except:\n return False\n\n @teststep\n def rate(self):\n \"\"\"获取作业数量\"\"\"\n rate = self.driver \\\n .find_element_by_id(self.id_type() + \"rate\").text\n return rate\n\n @teststep\n def time(self):\n \"\"\"获取作业时间\"\"\"\n rate = self.driver \\\n .find_element_by_id(self.id_type() + \"time\").text\n return rate\n\n @teststep\n def clear_button(self):\n \"\"\"页面内清除按钮\"\"\"\n self.driver \\\n .find_element_by_id(self.id_type() + \"bt_clear\").click()\n\n @teststeps\n def clear_button_judge(self):\n \"\"\"页面内清除按钮\"\"\"\n try:\n self.driver \\\n .find_element_by_id(self.id_type() + \"bt_clear\")\n return True\n except:\n return False\n\n @teststep\n def question_content(self):\n \"\"\"展示的题目 - 句子\"\"\"\n ele = self.driver \\\n .find_element_by_id(self.id_type() + \"tv_question\").text\n return ele\n\n @teststeps\n def mine_answer(self):\n \"\"\"展示的 我的答案\"\"\"\n ele = self.driver \\\n .find_elements_by_xpath(\"//android.widget.RelativeLayout[contains(@index,1)]/descendant::android.widget.TextView\")\n words = []\n for i in range(len(ele)):\n words.append(ele[i].text)\n print('我的答案:', words)\n return ele, words\n\n @teststep\n def word(self):\n \"\"\"展示的 待还原的单词\"\"\"\n ele = self.driver \\\n .find_elements_by_xpath(\"//android.widget.RelativeLayout[contains(@index,2)]/descendant::android.widget.TextView\")\n\n return ele\n\n # 每小题回答完,下一步按钮后展示答案的页面\n @teststeps\n def correct_title(self):\n \"\"\"展示的答案 的ID为依据\"\"\"\n locator = (By.ID, self.id_type() + \"tv_answer\")\n try:\n WebDriverWait(self.driver, 20, 0.5).until(lambda x: x.find_element(*locator))\n return True\n except:\n return False\n\n @teststeps\n def mine_result(self):\n \"\"\"展示的答题结果\"\"\"\n ele = self.driver \\\n .find_elements_by_id(self.id_type() + \"tv_text\")\n word = []\n for i in range(len(ele)):\n word.append(ele[i].text)\n print('我的答题结果:', word)\n return word\n\n @teststep\n def correct_answer(self):\n \"\"\"点击 下一题 按钮之后展示的答案\"\"\"\n ele = self.driver \\\n .find_element_by_id(self.id_type() + \"tv_answer\").text\n word = ele[2:].split(' ')\n return ele, word\n\n # 查看答案页面\n @teststeps\n def wait_check_detail_page(self):\n \"\"\"以“answer”的ID为依据\"\"\"\n locator = (By.XPATH, \"//android.widget.TextView[contains(@resource-id,\"\n \"'{}tv_answer')]\".format(self.id_type()))\n try:\n WebDriverWait(self.driver, 20, 0.5).until(lambda x: x.find_element(*locator))\n return True\n except:\n return False\n\n @teststeps\n def result_question(self):\n \"\"\"展示的题目\"\"\"\n ele = self.driver \\\n .find_elements_by_id(self.id_type() + \"tv_question\")\n word = []\n for i in range(len(ele)):\n word.append(ele[i].text)\n return word\n\n @teststeps\n def result_answer(self):\n \"\"\"展示的 正确答案\"\"\"\n ele = self.driver \\\n .find_elements_by_id(self.id_type() + \"tv_answer\")\n word = []\n for i in range(len(ele)):\n word.append(ele[i].text)\n return word\n\n @teststeps\n def result_mine(self):\n \"\"\"我的答案\"\"\"\n ele = self.driver \\\n .find_elements_by_id(self.id_type() + \"tv_mine\")\n words = []\n for i in range(len(ele)):\n words.append(ele[i].text)\n word = words[0].split(' ')\n return words, word\n\n @teststeps\n def result_mine_state(self, index):\n \"\"\"我的答案对错标识 selected属性\"\"\"\n word = self.driver \\\n .find_elements_by_id(self.id_type() + \"iv_mine\")[index]\n value = GetAttribute().get_selected(word)\n return value\n\n @teststeps\n def sentence_transform(self):\n \"\"\"《句型转换》 游戏过程\"\"\"\n if self.wait_check_page(): # 页面检查点\n if self.wait_check_play_page():\n count = [] # 做题结果\n answer = []\n timestr = [] # 获取每小题的时间\n rate = self.rate()\n for i in range(int(rate)):\n Homework().rate_judge(rate, i) # 测试当前rate值显示是否正确\n\n if not self.clear_button_judge(): # 判断清除按钮存在\n print('❌❌❌ Error - 清除按钮不存在!!')\n\n question = self.question_content() # 展示的题目内容\n value = sentence_transform_operate(question).split(' ')\n self.restore_word(value) # 填入单词 具体过程\n var = self.mine_answer() # 到目前为止我填入的答案\n\n if i == 0:\n print('第%s题 - 点击框中单词,移出框中' % (i + 1))\n self.remove_word(var) # 点击框中单词,是否可以移出框中\n elif i == 1:\n print('第%s题 - 点击清除按钮' % (i+1))\n self.clear_button() # 点击清除按钮\n self.restore_word(value) # 填入单词 具体过程\n print('-------------')\n timestr.append(self.time()) # 统计每小题的计时控件time信息\n Homework().next_button_operate('true') # 下一题 按钮 状态判断 加点击\n\n if self.correct_title(): # 页面检查点\n result = self.mine_result() # 做题结果\n correct = self.correct_answer()[1] # 正确答案-- 分解成单词\n for k in range(len(result)): # 做错 count+1\n if correct[k] != result[k]:\n count.append(k)\n break\n answer.append(result) # 做题结果\n\n Homework().next_button_operate('true') # 下一题 按钮 状态判断 加点击\n print('--------------------------------')\n Homework().now_time(timestr) # 判断游戏界面 计时功能控件 是否在计时\n print('========================================')\n return rate, answer\n\n @teststeps\n def restore_word(self, value):\n \"\"\"填入单词 具体过程\"\"\"\n time.sleep(2)\n for j in range(len(value)):\n words = self.word() # 待还原的单词\n for k in range(len(words)):\n if words[k].text == value[j]:\n Homework().next_button_operate('false') # 下一题 按钮 状态判断 加点击\n words[k].click()\n break\n\n @teststeps\n def remove_word(self, var):\n \"\"\"点击框中单词,是否可以移出框中\"\"\"\n word = []\n for i in range(len(var[0])):\n var[0][i].click() # 移出框中\n word.append(var[1][i])\n\n self.restore_word(word) # 将移出框中的单词重新填入\n\n @teststeps\n def check_detail_page(self, i, answer):\n \"\"\"查看答案页面\"\"\"\n if self.result.wait_check_result_page():\n print('查看答案页面:')\n self.result.check_result_button()\n if self.result.wait_check_detail_page():\n if self.wait_check_detail_page():\n if int(i) <= 16:\n self.result_operate(answer)\n else:\n item = self.result_question()\n if int(i) % len(item) == 0:\n page = int(int(i) / len(item))\n else:\n page = int(int(i) / len(item)) + 1\n print('页数:', page)\n for j in range(page):\n last_one = self.result_operate(answer) # 滑动前页面内最后一个小题- 做题结果\n self.screen_swipe_up(0.5, 0.75, 0.35, 1000)\n item_2 = self.result_question() # 滑动后页面内的题目 的数量\n if item_2[len(item_2) - 1].text == last_one:\n print('到底啦', last_one)\n self.result.back_up_button()\n break\n elif item_2[len(item_2) - 1].text == answer[len(answer) - 1]:\n # 滑动后到底,因为普通情况下最多只有两页,滑动一次即可到底\n print('滑动后到底', last_one)\n k = []\n for i in range(len(item_2) - 1, -1, -1): # 倒序\n if item_2[i].text == last_one:\n k.append(i + 1)\n break\n self.result_operate(answer, k[0])\n break\n else:\n continue\n self.screen_swipe_down(0.5, 0.75, 0.35, 1000)\n time.sleep(2)\n self.result.back_up_button() # 返回结果页\n\n @teststeps\n def result_operate(self, var, index=0):\n \"\"\"查看答案页面 -- 展示的解释内容验证\"\"\"\n explain = self.result_question() # 题目\n word = self.result_mine() # 我的答案\n answer = self.result_answer() # 正确答案\n for i in range(index, len(explain)):\n count = []\n value = sentence_transform_operate(explain[i]).split(' ')\n if answer[i] == var[i]: # 测试结果页 我的答案展示是否正确\n if answer[i] == value: # 测试 正确答案\n for j in range(len(word[1])): # 我的答案 与 正确答案 比较\n if word[1][j] != value[j]: # 答案不正确 count+1\n count.append(j)\n break\n\n if count == 0:\n if self.result_mine_state() != 'true':\n print('❌❌❌ Error - 我的答案:%s 与 正确答案:%s 对错标识:%s' % (word[0], value, 'false'))\n else:\n if self.result_mine_state() != 'false':\n print('❌❌❌ Error - 我的答案:%s 与 正确答案:%s 对错标识:%s' % (word[0], value, 'true'))\n else:\n print('❌❌❌ Error - 正确答案:', answer[i], value)\n print('--------------------------------')\n return word[1][len(word[1]) - 1]\n\n @teststeps\n def study_again(self):\n \"\"\"《句型转换》 再练一遍 操作过程\"\"\"\n print('========================================')\n if self.result.wait_check_result_page(): # 结果页检查点\n self.result.again_button() # 结果页 再练一遍 按钮\n print('再练一遍:')\n result = self.sentence_transform() # 游戏过程\n return '再练一遍按钮', result[0], result[1]\n","sub_path":"app/honor/student/homework/object_page/sentence_transform_page.py","file_name":"sentence_transform_page.py","file_ext":"py","file_size_in_byte":13118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"619681300","text":"\n\n#calss header\nclass _FLAG():\n\tdef __init__(self,): \n\t\tself.name = \"FLAG\"\n\t\tself.definitions = [u'a piece of cloth, usually rectangular and attached to a pole at one edge, that has a pattern that shows it represents a country or a group, or has a particular meaning: ', u'a flagstone ', u'a flower that is a type of large iris']\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/_flag.py","file_name":"_flag.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"469797663","text":"import scrapy\r\nfrom ProductsScraper.items import Product\r\nfrom scrapy.selector import Selector\r\nfrom scrapy.http.request import Request\r\nfrom ProductsScraper.settings import *\r\nimport re\r\nimport requests\r\n\r\nclass ForallmankindSpider(scrapy.Spider):\r\n name = \"7forallmankind\"\r\n start_urls = [\"http://www.7forallmankind.com/sale-women/l/254601\"]\r\n\r\n def __init__(self):\r\n self.ajax_url = 'http://www.7forallmankind.com/l/products/254601?PageSize=200&Page=1'\r\n\r\n def parse(self, response):\r\n products = requests.get(self.ajax_url, headers={'X-Requested-With': 'XMLHttpRequest'}).json()['Products']\r\n for prod in products:\r\n item = Product()\r\n\r\n item['Name'] = prod['ModelName']\r\n item['original_url'] = prod['ProductUrl']\r\n item['reg_price'] = prod['MaxRegularPrice']\r\n item['sale_price'] = prod['MinSalePrice']\r\n item['website_id'] = 12\r\n item['category_id'] = 2\r\n item['original_image_url'] = [prod['ProductImageUrl']]\r\n item['image_urls'] = item['original_image_url']\r\n\r\n yield item\r\n # break\r\n","sub_path":"e-commerce/ProductsScraper/ProductsScraper/spiders/7forallmankind.py","file_name":"7forallmankind.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"168128568","text":"\"\"\"\nChemistry: A program designed to link energy values to a constant number of data points.\nA energy txt file and a data txt file are used.\nBy: Kyle Zhang\n\"\"\"\n\nfilePath = \"Woochulpy/EnergyLink1/\" #leave blank if not necessary\n#file names\nenergyFileName = filePath + \"ener.txt\"\nnumbersFileName = filePath + \"nmr.txt\"\n\n#userSetNumbers: user may change these numbers\ndataPerEnergy = 48 #how many data values per energy value\nindexToStartSorting = 0 #set to zero if the whole list isn't sorted, and set to index n if certain the first n numbers are sorted. Generally, leave this at zero\nconstantToMultiplyOutput = 24122.15 #the program will multiply this number to the output file upon request, modify if needed\n\n#creation of a class to link energy values with data\nclass EnergyData:\n def __init__(self, energy):\n #instantiating class with an energy and corresponding array of integer dataPerEnergy length/size\n self.energy = energy\n self.data = [0] * dataPerEnergy\n\nlistEnergyData = [] #declaration of our list of Energy Values\nlinesEnergy = open(energyFileName).read().splitlines() #read the file every line-by-line into this list\nfor line in linesEnergy:\n listEnergyData.append( EnergyData(line) ) #append each line into the energy field of the corresponding energy into a list of energy classes\n\n#CheckPoints\nprint(\"Program: Appended Energy Values!!\")\n\nlinesNumbers = open(numbersFileName).read().splitlines() #read the file every line-by-line into this list\n#Appending the data values to their corresponding energy values in order\nfor i in range(len(listEnergyData)):\n for j in range(dataPerEnergy):\n #this index expression represents the index of the overall nmr.txt line in terms of i and j, which are indices for the \"2d array\"\n index = i * dataPerEnergy + j\n listEnergyData[i].data[j] = linesNumbers[index]\n\n#CheckPoints\nprint(\"Program: Appended Data Values!!\")\n\n\"\"\" Sorting Algorithm:\nThe general idea here is that I need to circulate through the entire list and pick out the most minimum/negative number. Once I pick out that number,\nI need to move it to the front of the list, and start circulating again for everything excluding that sorted value, since it is already at the start.\nI keep dragging the most minimum number out in front of the previous minimum number until I reach the last number, which evidently is the greatest,\nso it is sorted from most negative to max. \"\"\"\n#we sort every index but the last one, since once sorted, the last index is bound to be the greatest\nfor i in range(indexToStartSorting, len(listEnergyData)-1):\n #declaring my minimum to the first index\n min = float(listEnergyData[i].energy)\n minIndex = i\n #searching everything after the first index and comparing to see if it is less than it, if it is, it becomes new minimum to be compared against\n for i1 in range(i+1, len(listEnergyData)): #named i1 because it circulates through every index 1 above i\n if (float(listEnergyData[i1].energy) < min):\n min = float(listEnergyData[i1].energy)\n minIndex = i1\n #remove Energy value at where it was and insert at front of list where it is last sorted\n temp = listEnergyData[minIndex]\n listEnergyData.remove(listEnergyData[minIndex])\n listEnergyData.insert(i, temp)\n\n#CheckPoints\nprint(\"Program: Sorted the List of Energy Values!!\")\n\n#function for writing out to the files\ndef outputNLinesToFile(n, list):\n #The File is doesn't have to exist, as it will create or overwrite a file. User feel free to change the file name or path for output\n fileName = filePath + \"lowest_\" + n + \"data.txt\" \n\n #The w+ means it will overwrite if exists, and create if doesn't\n outputFile = open(fileName, \"w+\")\n #Output everything starting from least energy value's data values up until desired energy level\n for energyIndex in range(int(n)):\n for dataIndex in range(dataPerEnergy):\n outputFile.write(list[energyIndex].data[dataIndex] + \"\\n\")\n\ndef multiplyOutputByNumber(constantToMultiplyBy, outputFileName):\n const = float(constantToMultiplyBy)\n fileName = filePath + outputFileName\n linesData = open(fileName).read().splitlines() #read the file every line-by-line into this linesData\n outputFile = open(fileName, \"w+\")\n\n listData = []\n for line in linesData:\n num = float(line)\n listData.append(num*const) #we will take the read numbers, and append them multiplied to a new list\n \n for i in range(len(listData)):\n outputFile.write(str(listData[i]) + \"\\n\") #overwrite the values that have been multiplied back into the file\n \n print(\"Program: Data File multiplied by Requested Value!!\")\n\n#User Input/Interaction\nresponse = \"y\"\n#loop to always keep getting information until user doesn't want any\nwhile (response != \"n\"):\n inp = input(\"How many energy values (sorted lowest to highest) would you like to see data for (typing zero creates an empty txt file, just don't)? \")\n outputFile = \"lowest_\" + inp + \"data.txt\"\n outputNLinesToFile(inp, listEnergyData)\n print(\"Program: File Created:\", outputFile)\n userMultiplyMenu = \"Would you like to multiply the whole data file by \" + str(constantToMultiplyOutput) + \"? (y/n (OR type d if you want to multiply by a different number)): \"\n response = input(userMultiplyMenu)\n if (response.lower() == \"y\"):\n multiplyOutputByNumber(constantToMultiplyOutput, outputFile)\n elif (response.lower() == \"d\"):\n inp = input(\"What number would you multiply the whole data file by? \")\n multiplyOutputByNumber(inp, outputFile)\n\n resp = input(\"Would you like to create another one of these files? (y/n): \")\n response = resp.lower()\n ","sub_path":"EnergyLink1/energiesLink.py","file_name":"energiesLink.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"546906597","text":"import pygame\nimport bird, pipe\n\n\nscreen = pygame.display.set_mode((600, 600))\nscreen.fill((0,0,0))\n\nbird = bird.Bird(screen)\npipes = []\npipes.append(pipe.Pipe(screen))\n\n\nrunning = True\nclock = pygame.time.Clock()\nthousands_ticks = 1000\nwhile running:\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n bird.up()\n\n\n screen.fill((0,0,0))\n\n for p in pipes:\n p.show()\n p.update()\n \n p.hit(bird)\n\n \n \n\n\n bird.show()\n bird.update()\n\n ticks = pygame.time.get_ticks()\n if ticks > thousands_ticks:\n pipes.append(pipe.Pipe(screen))\n thousands_ticks += 1000\n pygame.display.update()\n\n for p in pipes:\n if p.offscreen():\n pipes.remove(p)\n\n clock.tick(60)\n\n ","sub_path":"flappybird/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"441806363","text":"def palindrom(niz):\r\n return niz == niz[::-1]\r\n\r\ni = 100\r\nj = 100\r\nnajvecji = 0\r\nwhile (i <= 999):\r\n while (j <= 999):\r\n produkt = i * j\r\n if (produkt > najvecji and palindrom(str(produkt))):\r\n najvecji = produkt\r\n j += 1\r\n j = 100\r\n i += 1\r\nprint(najvecji)\r\n\r\n","sub_path":"euler4.py","file_name":"euler4.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"103487587","text":"import sys\nfrom . import config\nimport math\nimport random\nimport functools\nimport time\n\ndef allclose(v1, v2):\n \"\"\"Compare if v1 and v2 are close\n\n v1, v2 - any numerical type or list/tuple of numerical types\n\n Return bool if vectors are close, up to some epsilon specified in config.py\n \"\"\"\n\n v1 = make_iterable(v1)\n v2 = make_iterable(v2)\n\n elementwise_compare = list(map(\n (lambda x, y: abs(x - y) < config.EPSILON), v1, v2))\n return functools.reduce((lambda x, y: x and y), elementwise_compare)\n\ndef make_iterable(obj):\n \"\"\"Check if obj is iterable, if not return an iterable with obj inside it.\n Otherwise just return obj.\n\n obj - any type\n\n Return an iterable\n \"\"\"\n try:\n iter(obj)\n except:\n return [obj]\n else:\n return obj\n\n\ndef dot(v1, v2):\n \"\"\"Dot product(inner product) of v1 and v2\n\n v1, v2 - python list\n\n Return v1 dot v2\n \"\"\"\n elementwise_multiply = list(map((lambda x, y: x * y), v1, v2))\n return functools.reduce((lambda x, y: x + y), elementwise_multiply)\n\n\ndef norm(vec):\n \"\"\" Return the Euclidean norm of a 3d vector.\n\n vec - a 3d vector expressed as a list of 3 floats.\n \"\"\"\n return math.sqrt(functools.reduce((lambda x, y: x + y * y), vec, 0.0))\n\n\ndef normalize(vec):\n \"\"\"Normalize a vector\n\n vec - python list\n\n Return normalized vector\n \"\"\"\n if norm(vec) < 1e-6:\n return [0 for i in xrange(len(vec))]\n return list(map(lambda x: x / norm(vec), vec))\n\n\ndef cross_product(v1, v2):\n \"\"\" Return the cross product of v1, v2.\n\n v1, v2 - 3d vector expressed as a list of 3 floats.\n \"\"\"\n x3 = v1[1] * v2[2] - v2[1] * v1[2]\n y3 = -(v1[0] * v2[2] - v2[0] * v1[2])\n z3 = v1[0] * v2[1] - v2[0] * v1[1]\n return [x3, y3, z3]\n\ndef create_vector(p1, p2):\n \"\"\"Contruct a vector going from p1 to p2.\n\n p1, p2 - python list wth coordinates [x,y,z].\n\n Return a list [x,y,z] for the coordinates of vector\n \"\"\"\n return list(map((lambda x,y: x-y), p2, p1))\n\ndef create_file(titre, color):\n file = open(titre, \"w\")\n if color:\n file.write(\"COFF\\n\")\n else:\n file.write(\"OFF\\n\")\n return file\n\ndef close_file(file):\n file.close()\n\ndef multiple_write(file, param):\n for p in param:\n file.write(str(p))\n file.write(\" \")\n\ndef count_bord(tab_halfedge):\n nb_bord = 0\n\n if tab_halfedge != []:\n print(\" Pour la composante il y a au moins un bord\")\n while tab_halfedge != []:\n first = tab_halfedge[0]\n del tab_halfedge[0]\n next = first.next_in_bord()\n while next != first:\n tab_halfedge.remove(next)\n next = next.next_in_bord()\n nb_bord += 1\n return nb_bord\n\ndef random_color():\n tmp = []\n tmp.append(random.uniform(0, 1) * 255)\n tmp.append(random.uniform(0, 1) * 255)\n tmp.append(random.uniform(0, 1) * 255)\n return tmp\n\ndef calcul_perimetre(face):\n perimetre = 0\n for v in face.adjacent_halfedges():\n perimetre += v.calcul_distance()\n face.perimetre = perimetre\n return perimetre\n\ndef return_z(face):\n return face.halfedge.vertex.z\n\ndef init_classe(nb_classe, nb_functions, tab_min, tab_max):\n tab_classe = [0] * nb_classe\n tmps = [0] * nb_functions\n ecart_tab = [0] * nb_functions\n for j in range(len(ecart_tab)):\n ecart_tab[j] = (tab_max[j]-tab_min[j])/nb_classe\n for i in range(nb_classe) :\n tab_classe[i] = tmps[:]\n for j in range(nb_functions):\n tab_classe[i][j] = tab_min[j] + i * ecart_tab[j]\n return tab_classe\n\ndef calcul_aire(face):\n aire = 0\n first = face.adjacent_vertices()[0]\n list1 = face.adjacent_vertices()\n list2 = list1[:]\n del list1[len(list1)-1]\n del list1[0]\n del list2[0]\n del list2[0]\n for i,j in zip(list1, list2):\n t = abs(first.determinant(i,j))\n aire += (t/2)\n face.aire = aire\n return aire\n\ndef calcul_time(fonction, params):\n debut = time.time()\n if params == []:\n fonction()\n else:\n fonction(params[0])\n fin = time.time()\n print(\"\\n La fonction\\n\", fonction, \"\\n met\", fin - debut, \"secondes pour s'executer\")\n return fin - debut\n","sub_path":"halfedge_mesh/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"292115753","text":"'''\nFunction:\n 走迷宫小游戏\nAuthor:\n Charles\n微信公众号:\n Charles的皮卡丘\n'''\nimport cfg\nimport sys\nimport pygame\nfrom modules import *\n\n\n'''主函数'''\ndef main(cfg):\n # 初始化\n pygame.init()\n pygame.mixer.init()\n pygame.font.init()\n pygame.mixer.music.load(cfg.BGMPATH)\n pygame.mixer.music.play(-1, 0.0)\n screen = pygame.display.set_mode(cfg.SCREENSIZE)\n pygame.display.set_caption('Maze —— Charles的皮卡丘')\n font = pygame.font.SysFont('Consolas', 15)\n # 开始界面\n print(\"Debug:\\nNow we are into modules/misc.py Interface class\")\n print(\"the modules in modules are called with from modules import *\")\n print(\"The buttons are made with class Button, always in misc.py\")\n print(\"\"\"If you press start, there's this code\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if button_1.collidepoint(pygame.mouse.get_pos()):\n return True\n \n That will return True\n \"\"\")\n Interface(screen, cfg, 'game_start') # it's in modules/misc.py\n print(\"======================\")\n print(\"Here is the maze, after return from the mode='game start' if statememt in Interface\")\n print(\"Now the mode is set to 'game_switch'\")\n # 记录关卡数\n num_levels = 0\n # 记录最少用了多少步通关\n best_scores = 'None'\n # 关卡循环切换\n while True:\n num_levels += 1\n clock = pygame.time.Clock()\n screen = pygame.display.set_mode(cfg.SCREENSIZE)\n # --随机生成关卡地图\n maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)\n # --生成hero\n hero_now = Hero(cfg.HEROPICPATH, [0, 0], cfg.BLOCKSIZE, cfg.BORDERSIZE)\n # --统计步数\n num_steps = 0\n # --关卡内主循环\n while True:\n dt = clock.tick(cfg.FPS)\n screen.fill((255, 255, 255))\n is_move = False\n # ----↑↓←→控制hero\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit(-1)\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n is_move = hero_now.move('up', maze_now)\n elif event.key == pygame.K_DOWN:\n is_move = hero_now.move('down', maze_now)\n elif event.key == pygame.K_LEFT:\n is_move = hero_now.move('left', maze_now)\n elif event.key == pygame.K_RIGHT:\n is_move = hero_now.move('right', maze_now)\n num_steps += int(is_move)\n hero_now.draw(screen)\n maze_now.draw(screen)\n # ----显示一些信息\n showText(screen, font, 'LEVELDONE: %d' % num_levels, (255, 0, 0), (10, 10))\n showText(screen, font, 'BESTSCORE: %s' % best_scores, (255, 0, 0), (210, 10))\n showText(screen, font, 'USEDSTEPS: %s' % num_steps, (255, 0, 0), (410, 10))\n showText(screen, font, 'S: your starting point D: your destination', (255, 0, 0), (10, 600))\n # ----判断游戏是否胜利\n if (hero_now.coordinate[0] == cfg.MAZESIZE[1] - 1) and (hero_now.coordinate[1] == cfg.MAZESIZE[0] - 1):\n print(\"you won\")\n break # This will break the while loop and make you go in game switch mode\n pygame.display.update()\n # --更新最优成绩\n if best_scores == 'None':\n best_scores = num_steps\n else:\n if best_scores > num_steps:\n best_scores = num_steps\n # --关卡切换\n # when you win you go here\n print(\"you won, so you go in game_switch\")\n Interface(screen, cfg, mode='game_switch')\n\n\n'''run'''\nif __name__ == '__main__':\n main(cfg)","sub_path":"Game20.py","file_name":"Game20.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"68776283","text":"import pygame\n\nclass Spaceship():\n def __init__(self, settings, screen):\n \"\"\"Initializes the spaceship and its starting position\"\"\"\n\n # assigns the main window screen to the ship to use\n self.screen = screen\n\n #Applies the window settings to the ship\n self.settings = settings\n\n #Loads the spaceship image and gets its rectangle-dimensions\n self.image = pygame.image.load('images/spaceship.bmp')\n self.rect = self.image.get_rect()\n self.screen_rect = self.screen.get_rect()\n\n #Assigns the starting position of each new spaceship at the bottom center of the screen\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n #Since we are using decimal values for speed, the ship's center should be a decimal value\n self.center = float(self.rect.centerx)\n\n\n #Moving checks\n self.move_left = False\n self.move_right = False\n\n def update(self):\n if self.move_left and self.rect.left > 0:\n self.center -= self.settings.ship_speed\n if self.move_right and self.rect.right < self.screen_rect.right:\n self.center += self.settings.ship_speed\n\n self.rect.centerx = self.center\n\n def blitme(self):\n \"\"\"Draws the spaceship at whatever position it may be\"\"\"\n self.screen.blit(self.image, self.rect)\n","sub_path":"Alien Invaderz/spaceship.py","file_name":"spaceship.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"252282966","text":"# -*- coding: utf-'8' \"-*-\"\nfrom openerp import api, models\nfrom openerp.exceptions import ValidationError\nfrom openerp.tools import SUPERUSER_ID\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass PartnerMerge(models.Model):\n _name = \"res.partner\"\n _inherit = [\"res.partner\"]\n\n @api.noguess\n def _merge_partner(self, cr, uid, partner_to_remove, partner_to_keep, context={}):\n # Create an instance from the wizard to be able to use it's methods\n logger.info(\"merge_partner: Create a base.partner.merge.automatic.wizard instance\")\n wizard = self.pool.get('base.partner.merge.automatic.wizard')\n\n # MERGE PARTNER\n # -------------\n # Update foreign keys directly in the db\n logger.info(\"merge_partner: Update foreign keys directly in the db\")\n wizard._update_foreign_keys(cr, SUPERUSER_ID, partner_to_remove, partner_to_keep, context=context)\n\n # Update reference fields\n logger.info(\"merge_partner: Update reference fields\")\n wizard._update_reference_fields(cr, SUPERUSER_ID, partner_to_remove, partner_to_keep, context=context)\n\n # Update target partner field values\n # ATTENTION: DISABLED because the field values will be already corrected in FRST!\n #logger.info(\"merge_partner: Update field values\")\n #wizard._update_values(cr, SUPERUSER_ID, partner_to_remove, partner_to_keep, context=context)\n\n @api.model\n def merge_partner(self, partner_to_remove_id=False, partner_to_keep_id=False):\n cr = self.env.cr\n uid = self.env.uid\n context = self.env.context or {}\n # HINT: There is also an OCA module base_partner_merge which seems to be exactly the same than the code in\n # the crm addon. maybe odoo just copied the code or the oca extracted it because the addon crm was the\n # wrong place for it?\n\n # Load partner and log info\n # HINT: This will throw an exception if any of the partners do not exits\n partner = self.env['res.partner']\n\n partner_to_remove = partner.browse([partner_to_remove_id])\n assert partner_to_remove, \"merge_partner: partner_to_remove (ID %s) was not found!\" % partner_to_remove_id\n\n partner_to_keep = partner.browse([partner_to_keep_id])\n assert partner_to_keep, \"merge_partner: partner_to_keep (ID %s) was not found!\" % partner_to_keep_id\n\n logger.info(\"merge_partner: Merge Partner %s (ID %s) into partner %s (ID %s)\" %\n (partner_to_remove.name, partner_to_remove_id, partner_to_keep.name, partner_to_keep_id))\n\n # Check if the partner_to_remove is a child of the partner_to_keep\n if partner_to_remove.parent_id and partner_to_remove.parent_id.id == partner_to_keep.id:\n raise ValidationError(\"You cannot merge a contact with his parent!\")\n\n # Check if the partner_to_remove has account journal items\n if self.env['ir.model'].sudo().search([('model', '=', 'account.move.line')]):\n if self.env['account.move.line'].sudo().search([('partner_id', '=', partner_to_remove.id)]):\n raise ValidationError(\"You cannot merge a contact with account journal entries!\")\n\n # Delete the BPK Requests\n # -------------------------\n if partner_to_remove.bpk_request_ids:\n logger.info(\"merge_partner: Unlink the BPK Requests with the ids: %s\"\n % partner_to_remove.bpk_request_ids.ids)\n partner_to_remove.bpk_request_ids.unlink()\n\n # MERGE\n # -----\n # HINT: Done in a separate method to avoid new to old api mapping with decorator @api.noguess because\n # the automatic mapping failed for the wizard methods called in _merge_partner()\n logger.debug(\"merge_partner: Call _merge_partner()\")\n self._merge_partner(cr, uid, partner_to_remove, partner_to_keep, context=context)\n # Post a message to the partner_to_keep chatter flow\n partner_to_keep.message_post(body=\"Partner %s (ID %s) was merged into this partner!\"\n % (partner_to_remove.name, partner_to_remove_id))\n\n # UNLINK\n # ------\n # Remove the merged partner\n logger.info(\"merge_partner: Unlink (delete) the partner_to_remove (ID %s) after the merge\"\n % partner_to_remove_id)\n partner_to_remove.unlink()\n\n # EMPTY WRITE\n # -----------\n logger.info(\"merge_partner: Do an empty write({}) for the remaining partner %s to update all state information\"\n \"\" % partner_to_keep_id)\n partner_to_keep.write({})\n\n logger.info(\"merge_partner: DONE: Merged Partner with id %s into partner with id %s!\"\n % (partner_to_remove_id, partner_to_keep_id))\n return True\n","sub_path":"addons-own/fso_sosync_base/models/partner_merge.py","file_name":"partner_merge.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"145529631","text":"import pymongo\nimport mysql.connector\n\n\ndef getSQL():\n client = pymongo.MongoClient(\n \"mongodb+srv://nepomnyashchii:natasha1977#5@cluster0-6p7nv.mongodb.net/test?retryWrites=true&w=majority\")\n db = client[\"test\"]\n mycol = db[\"sasha3\"]\n myquery = {\"name\": {\"$regex\": \"a\"}}\n mydocs = mycol.find(myquery)\n sql = ''\n val = ()\n for x in mydocs:\n # sql += \"INSERT INTO clients (name, phone, email) VALUES ('\" + \\\n # x[\"name\"]+\"', '\" + x[\"phone\"] + \"', '\" + x[\"email\"] + \"');\\n\"\n sql += \"INSERT INTO secret (name,phone, email) VALUES (%s, %s, %s)\"\n val += (x[\"phone\"], x[\"name\"], x[\"email\"])\n return sql, val\n\n\ndef executeSQL(sql):\n mydb = mysql.connector.connect(\n host=\"db4free.net\",\n user=\"coolspammail\",\n passwd=\"coolspammail-pass\",\n database=\"coolspammail\"\n )\n mycursor = mydb.cursor()\n\n for i in mycursor.execute(sql, params=None, multi=True):\n print(mycursor.rowcount)\n # it = mycursor.execute(sql, params=None, multi=True)\n # for i in it:\n # print(i)\n mydb.commit()\n\n\n\n\n\nmsn = getSQL()\nprint(msn)\nexecuteSQL(msn)\n","sub_path":"assighnment/alex_copy.py","file_name":"alex_copy.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"591572197","text":"import os\nimport unittest\n\nfrom website import settings\n\n\nrequires_search = unittest.skipIf(\n not settings.SEARCH_ENGINE,\n 'search disabled'\n)\nrequires_piwik = unittest.skipIf(\n settings.PIWIK_HOST is None,\n 'no PIWIK_HOST specified in settings'\n)\nrequires_gnupg = unittest.skipIf(\n not settings.USE_GNUPG,\n 'gnupg disabled'\n)\nrequires_csl_styles = unittest.skipIf(\n not os.path.exists(os.path.join(settings.CITATION_STYLES_PATH, '.git')),\n 'CSL styles not detected'\n)","sub_path":"tests/test_features.py","file_name":"test_features.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"295797211","text":"from ..Abstract.LoaderBase import Base\nfrom ...DataStruct.BasicData import BasicData\n\nimport re\nimport numpy as np\n\ndef MaskBoundariesFrom(mask_change):\n\tindices = []\n\tlow = mask_change[0]\n\n\tfor i in range(1,len(mask_change)):\n\t\tif (mask_change[i-1]+1 != mask_change[i]):\n\t\t\tindices.append({'low':low, 'high':mask_change[i-1]})\n\t\t\tlow = mask_change[i]\n\t\t\n\t\tif (i == len(mask_change)-1):\n\t\t\tindices.append( {'low':low, 'high':mask_change[i]} )\n\t\t\t\n\treturn indices\t\t\n\n\n\nclass Loader(Base):\n\n\tdef __init__(self, frequecy = 500):\n\t\tself.frequecy = frequecy\n\t\tsuper().__init__()\n\t\t\n\n\tdef DataFrom(self,path):\n\t\tdata = np.loadtxt(path + \".dat\", delimiter=',')\n\t\tret = []\n\n\t\t#countinuos indices from data where mask changes\n\t\tmask_change = np.where(data[0:,2]==0)[0]\n\t\tindices_pairs = MaskBoundariesFrom(mask_change)\n\n\t\t#getting rid of bad data (with annotated artifacts)\n\t\ti = 0\n\t\tfor index in indices_pairs:\n\t\t\ttmp_data = data[index['low']:index['high'],0:]\n\t\t\tqrs_indices = np.nonzero(tmp_data[0:,1])[0]\n\n\t\t\ttmp = BasicData()\n\t\t\ttmp.signal = tmp_data[0:,0]\n\t\t\ttmp.freq = self.frequecy\n\t\t\ttmp.QRSann = qrs_indices\n\t\t\ttmp.dbcode = \"TeleHealth\"\n\t\t\ttmp.patient_nr = re.findall(\"([a-zA-Z0-9_]+)$\",path)\n\t\t\ttmp.signal_index = i\t\t\t\n\n\t\t\tret.append( tmp )\n\t\t\ti += 1\n\n\t\treturn ret\n\n\tdef DataFields(self):\n\t\treturn [\"signal\", \"freq\", \"QRSann\", \"dbcode\", \"patient_nr\", \"signal_index\"]\n\t\n","sub_path":"Framework/Sketch/Loaders/QRS/TeleHealth.py","file_name":"TeleHealth.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440659270","text":"\"\"\"This file contains several modules to store or display messages which contain urls\"\"\"\nimport re\nimport discord\nfrom discord.ext import commands\n\n\n\nclass Links(commands.Cog):\n \"\"\" This File contains commands for Saving the links in a file,\n Display all the messages which contains links.\"\"\"\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_message(self, message):\n \"\"\"TO store messgaes contanning url to links.txt\"\"\"\n url=[]\n message_links = []\n temp=[]\n print(message.content)\n regex = r\"(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\" \\\n r\"\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\\\".,<>?«»“”‘’]))\"\n url = re.findall(regex, message.content)\n for url_count in url:\n temp.append(url_count[0])\n if temp:\n message_links.append(message.content)\n with open('data/links/links.txt', \"a\") as text_file:\n text_file.write(\"Message containing url :- \" + message.content + \"\\n\")\n text_file.close()\n else:\n pass\n\n\n @commands.command(name='send_links', help='Command will output all the messages which contain url')\n async def send_links(self, ctx):\n \"\"\"To display all messages which contain url.\"\"\"\n await ctx.send(\"The below list of messages contains URLs\")\n await ctx.send(file=discord.File('data/links/links.txt')) \n\n\ndef setup(bot):\n \"\"\"add the file to the bot's cog system\"\"\"\n bot.add_cog(Links(bot))\n","sub_path":"cogs/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629056303","text":"class Console(object):\n def __init__(self, stop, voice):\n self._stop = stop\n self._speech_activated = voice\n self.__layout_show = ('\\n\\t=> \\033[1;32m{}\\033[0;0m')\n self.__layout_show_error = ('\\n\\n\\t==> \\033[1;33m{}\\033[0;0m\\n\\n')\n self.__layout_get = ('\\n\\t=> \\033[1;34m{}\\033[0;0m\\n> ')\n\n def show(self, msg, type_msg=''):\n if type_msg == 'error':\n print(self.__layout_show_error.format(msg))\n else:\n print(self.__layout_show.format(msg))\n\n def get(self, msg='', type_input='str'):\n user_input = input(self.__layout_get.format(msg))\n\n self.check_stop_request(user_input)\n\n if type_input in ['int', 'float']:\n user_input = self.convert(user_input, msg, type_input)\n\n return user_input\n\n def check_stop_request(self, value):\n if value.lower() in ['exit', 'leave', 'get out']:\n self._stop()\n\n def convert(self, value, msg='', type_input='int'):\n try:\n if type_input == 'int':\n value = int(value)\n else:\n value = float(value)\n except ValueError:\n self.show('Invalid value!', type_msg='error')\n\n value = self.get(msg, type_input=type_input)\n\n return value\n","sub_path":"app/console/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134403415","text":"# Joint estimation of everything\n# but we can ablate on the tasks\n# We should compare this model to other models as well\n\nimport os\nimport json\nimport torch\nimport getpass\nimport datetime\nimport argparse\nfrom dotmap import DotMap\nimport pytorch_lightning as pl\nfrom torch.utils.data import DataLoader\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\nfrom agents.state_rnn import RNNAgent\nfrom dataset import TrajTutorState, tutor_collate_fn\n\nDATA_DIR = '/data/anie/offline_rl/data/'\nOUT_DIR = '/data/anie/offline_rl_dynamics/'\n\ndef tags_from_args(args):\n args = vars(args)\n tags = []\n ks = sorted(list(args.keys()))\n for k in ks:\n if k == 'tags':\n continue\n v = args[k]\n if type(v) == bool:\n if v: tags.append(k)\n else:\n tags.append(v)\n\n tags.extend(args['tags'])\n\n return tags\n\ndef get_date():\n date = datetime.date.today().strftime('%b%d').lower()\n return date\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"config\", type=str, help='path to config file')\n parser.add_argument(\"--tags\", nargs='+', type=str, help='optional descriptive tags for this run', default=[])\n parser.add_argument(\"--gpu-device\", type=int, default=0)\n args = parser.parse_args()\n return args\n\ndef setup(args):\n with open(args.config) as fp:\n config = json.load(fp)\n\n config = DotMap(config)\n\n train_ds = TrajTutorState(\n os.path.join(\n DATA_DIR,\n #config.dataset.folder,\n config.dataset.train_split,\n ),\n os.path.join(DATA_DIR, 'state_ids.json'),\n os.path.join(DATA_DIR, \"nlg_score.csv\"),\n include_correctness=config.dataset.include_correctness\n )\n val_ds = TrajTutorState(\n os.path.join(\n DATA_DIR,\n #config.dataset.folder,\n config.dataset.valid_split,\n ),\n os.path.join(DATA_DIR, 'state_ids.json'),\n os.path.join(DATA_DIR, \"nlg_score.csv\"),\n include_correctness=config.dataset.include_correctness\n )\n\n config.dataset.feat_dim = train_ds.dset_args()['feat_dim']\n config.dataset.num_states = 481\n config.dataset.num_actions = 3\n return config, train_ds, val_ds\n\ndef create_dataloader(dataset, dl_config, shuffle=True):\n loader = DataLoader(\n dataset,\n batch_size=dl_config.batch_size,\n shuffle=shuffle,\n pin_memory=True,\n drop_last=False,\n collate_fn=tutor_collate_fn,\n num_workers=dl_config.num_workers,\n )\n return loader\n\n\ndef main(args):\n config, train_ds, val_ds = setup(args)\n train_dl = create_dataloader(train_ds, config.dataloader)\n val_dl = create_dataloader(val_ds, config.dataloader, shuffle=False)\n\n tags = tags_from_args(args)\n tags = [str(t) for t in tags]\n name = ':'.join(tags)\n config.pprint()\n\n AgentClass = globals()[config.agent]\n agent = AgentClass(config)\n\n save_dir = os.path.join(OUT_DIR, get_date())\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n\n wandb_logger = WandbLogger(\n project='tutorial',\n entity='windweller',\n save_dir=save_dir,\n tags=tags,\n name=name,\n )\n\n trainer = pl.Trainer(\n logger=wandb_logger,\n weights_summary='full',\n max_epochs=config.epochs,\n gpus=[int(args.gpu_device)],\n # truncated_bptt_steps=32\n )\n\n trainer.fit(\n agent,\n train_dataloader=train_dl,\n val_dataloaders=val_dl,\n )\n\nif __name__ == '__main__':\n torch.manual_seed(42)\n args = parse_args()\n main(args)\n","sub_path":"dynamic_modeling/state_rnn_main.py","file_name":"state_rnn_main.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"253235216","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 5 17:40:47 2021\n\n@author: 11200\n\"\"\"\n\n#逻辑斯蒂回归 二分类\n\nimport torch \nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass LogisticModel(torch.nn.Module):\n def __init__(self):\n super(LogisticModel,self).__init__()\n self.linear=torch.nn.Linear(1,1) #仍需要线性模型\n \n def forward(self,x):\n #在torch里,sigmoid就是Logistic函数\n y_pred=F.sigmoid( self.linear(x) )\n return y_pred\n \nmodel=LogisticModel()\n \n#BCE损失函数\n#是否选择求均值,影响学习率的选择\ncriterion=torch.nn.BCELoss(size_average=False)\n\noptimizer=torch.optim.SGD(model.parameters(),lr=0.01)\n\nEpoch=10000\nx_data=torch.tensor([[1.0],[2.0],[3.0]])\ny_data=torch.tensor([[0.0],[0.0],[1.0]])\nloss_list=[]\n\nfor epoch in range(Epoch):\n y_pred=model(x_data)\n loss=criterion(y_pred,y_data)\n loss_list.append(loss.item())\n print(epoch,round(loss.item(),2))\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n'''\nplt.figure(figsize=(16,9),dpi=80)\nplt.plot(range(Epoch),loss_list)\nplt.show()\n'''\n\nx=np.linspace(0, 10,200)\nx_t=torch.tensor(x,dtype=torch.float).view((200,1))\ny_t=model(x_t)\ny=y_t.data.numpy()\nplt.plot(x,y)\nplt.plot([0,10],[0.5,0.5],c='r')\nplt.grid()\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test/07LogisticRegression_01.py","file_name":"07LogisticRegression_01.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"116671072","text":"from sellmo import modules\nfrom sellmo.apps.pricing.helpers import price_field_names\nfrom sellmo.contrib.category.admin import (\n ProductCategoryListFilter,\n ProductCategoriesMixin)\nfrom sellmo.contrib.variation.admin import (\n VariantAttributeMixin,\n ProductVariationMixin)\nfrom sellmo.contrib.attribute.admin import ProductAttributeMixin\n\nfrom sellmo.contrib.tax.admin import ProductTaxClassesMixin\nfrom sellmo.contrib.discount.admin import ProductDiscountsMixin\n\nfrom django.contrib import admin\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sorl.thumbnail import get_thumbnail\n\nfrom extras.admin.polymorphism import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass ProductQtyPriceInline(admin.TabularInline):\n model = modules.pricing.ProductQtyPrice\n\n\nclass ProductChildAdmin(\n ProductTaxClassesMixin,\n ProductDiscountsMixin,\n ProductCategoriesMixin,\n ProductAttributeMixin,\n ProductVariationMixin,\n PolymorphicChildModelAdmin):\n\n inlines = [ProductQtyPriceInline]\n fieldsets = (\n (_(\"Product\"), {\n 'fields': ('name', 'sku', 'main_image', 'short_description', 'attribute_set')\n }),\n (_(\"Product pricing\"), {\n 'fields': ('tax_classes', 'discounts')\n }),\n (_(\"Product availability\"), {\n 'fields': ('allow_backorders', 'supplier', 'min_backorder_time', 'max_backorder_time', 'stock',)\n }),\n (_(\"Store arrangement\"), {\n 'fields': ('slug', 'categories', 'primary_category', 'active', 'featured',)\n }),\n )\n\n filter_horizontal = ['categories']\n\n prepopulated_fields = {\n 'slug' : ('name',),\n }\n\n raw_id_fields = ['primary_category']\n autocomplete_lookup_fields = {\n 'fk': ['primary_category'],\n }\n\n\nclass VariantInline(VariantAttributeMixin, admin.StackedInline):\n\n fieldsets = (\n (_(\"Product information\"), {\n 'fields': ('name', 'sku', 'main_image', 'short_description',)\n }),\n (_(\"Store arrangement\"), {\n 'fields': ('slug',)\n }),\n (_(\"Product pricing\"), {\n 'fields': (tuple(price_field_names('price_adjustment', multi_currency=True, components=None)),)\n }),\n )\n\n\nclass ProductParentAdmin(PolymorphicParentModelAdmin):\n\n base_model = modules.product.Product\n\n polymorphic_list = False\n list_display = ['slug']\n list_display_links = ['slug']\n search_fields = ['slug']\n\n child_models = []\n\n\n list_display = ['thumbnail', 'name', 'active', 'featured', 'slug', 'sku', 'stock']\n list_display_links = ['name', 'slug']\n list_editable = ['active', 'featured']\n\n list_filter = [ProductCategoryListFilter, 'active', 'featured']\n search_fields = ['name', 'slug', 'sku']\n\n def get_queryset(self, queryset):\n return modules.product.Product.objects.variants(exclude=True)\n\n def thumbnail(self, instance):\n if instance.main_image:\n try:\n thumbnail = get_thumbnail(instance.main_image, '30x30', crop='center', quality=100)\n return '<img src=\"%s\"/>' % (thumbnail.url)\n except IOError as ex:\n logger.warning(ex)\n return ''\n\n thumbnail.allow_tags = True\n thumbnail.short_description = _(\"thumbnail\")\n\n\nadmin.site.register(modules.product.Product, ProductParentAdmin)\n\n\n# Simple product\n\nclass SimpleVariantInline(VariantInline):\n model = modules.variation.SimpleProductVariant\n fk_name = 'product'\n\n\nclass SimpleProductAdmin(ProductChildAdmin):\n base_model = modules.product.Product\n inlines = ProductChildAdmin.inlines + [SimpleVariantInline]\n\n\nProductParentAdmin.child_models += [\n (modules.product.SimpleProduct, SimpleProductAdmin)]\n","sub_path":"skeleton/product/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"603953128","text":"import re, sys, os, PyPDF2\ndef timeScanner(filename):\n print('You have chosen to search for times.')\n print('What type of file are you trying to scan?')\n print('\\n1. TXT File\\n2. PDF')\n ans = input()\n if int(ans) == 1:\n text1 = open(filename + '.txt')\n textContent = text1.read()\n timeChecker = re.compile(r'((\\d)?\\d:\\d{2})')\n mo1 = timeChecker.findall(textContent)\n print('Times found: ' + str(mo1))\n \n elif int(ans) == 2:\n print('Please enter the name of the PDF file you want scanned:')\n fileName = input()\n text1 = open(fileName + '.pdf', 'rb') #Opens the PDF file\n textContent = PyPDF2.PdfFileReader(text1) #Uses the PDF Reader function\n timeChecker = re.compile(r'((\\d)?\\d:\\d{2})')\n pages = 0\n while pages < textContent.numPages: #Uses a loop that starts with page 0, and keeps going until every page is gotten.\n textPage = textContent.getPage(pages)\n mo1 = timeChecker.findall(textPage.extractText())\n pages = pages + 1\n print('Times found: ' + str(mo1))\n \n else:\n print('That\\'s not a valid number.\\nSHUTTING DOWN')\n sys.exit\n","sub_path":"devel/tCheck.py","file_name":"tCheck.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141837758","text":"import collections\nimport importlib\nfrom utils.exception import RpcException, CriticalException, RpcErrorException\nimport random\n\n\nclass RpcManager:\n\n def __init__(self, settings, tokens):\n self.settings = settings\n self.tokens = tokens\n self.__id_feeds = collections.defaultdict(list)\n self.__generators = {}\n\n def __create_generator(self, setting):\n while True:\n feed_type = setting['type']\n iden = setting['id']\n\n idx = feed_type.rfind('.')\n pack, cls = feed_type[:idx], feed_type[idx + 1:]\n feed_ = getattr(importlib.import_module(pack), cls)(setting, self.tokens)\n\n yield feed_\n\n def __create_feeds(self):\n for setting in self.settings:\n if 'id' not in setting:\n raise CriticalException('bad config, not id field found')\n id_ = setting['id']\n self.__generators[id_] = self.__create_generator(setting)\n\n def get_new_feed_by_id(self, id_):\n if id_ not in self.__generators:\n raise CriticalException('id %s not in the manager' % id_)\n feed_ = next(self.__generators[id_])\n feed_.start()\n self.__id_feeds[id_].append(feed_)\n return feed_\n\n def get_available_feed(self, id_):\n if id_ not in self.__generators:\n raise CriticalException('id %s not in the manager', id_)\n if id_ not in self.__id_feeds:\n feed_ = self.get_new_feed_by_id(id_)\n l = len(self.__id_feeds[id_])\n idx = random.randint(0, l - 1)\n return self.__id_feeds[id_][idx]\n\n def start(self):\n self.__create_feeds()\n\n def stop(self):\n self.__generators.clear()\n for id_ in self.__id_feeds:\n def do_stop(x):\n x.stop()\n filter(do_stop, self.__id_feeds[id_])\n self.__id_feeds.clear()\n","sub_path":"rpcs/rpcmanager.py","file_name":"rpcmanager.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"308790693","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 12 11:58:01 2020\n\n@author: Cati\n\"\"\"\nfrom state import State\nfrom copy import deepcopy\nfrom sys import maxsize\n\n\nclass Problem:\n \n def __init__(self, initialState:State):\n self.initialState = initialState\n \n \n def getInitialState(self):\n return self.initialState\n\n\n def getRoot(self):\n return deepcopy(self.initialState)\n \n \n def getEmptyCells(self, emptyM):\n empty = []\n for i in range(len(emptyM)):\n for j in range(len(emptyM)):\n if emptyM[i][j] == 0:\n empty.append((i,j))\n \n return empty\n \n \n def getNumberEl(self, matrix,elem=1):\n nr1 = 0\n for line in matrix:\n for el in line:\n if el == elem:\n nr1 +=1\n return nr1\n \n \n def expand(self, currentState: State):\n \n values = currentState.getInitialState()\n positions = self.getEmptyCells(values)\n noOnes = self.getNumberEl(values)\n\n if noOnes >= len(values):\n return []\n\n result = []\n for t in positions:\n auxiState = deepcopy(currentState)\n auxiState.putOne(t[0]-1,t[1]-1,1)\n result.append(auxiState)\n print(auxiState)\n\n return result\n \n \n \n \n def checkRow(self):\n \n n = self.initialState.getSize()\n for i in range(n):\n count = 0\n for j in range(n):\n if self.initialState.getInitialState()[i][j] == 1:\n count = count + 1 \n if count > 1:\n return False\n return True\n \n \n def checkColumn(self):\n \n n = self.initialState.getSize()\n for i in range(n):\n count = 0\n for j in range(n):\n if self.initialState.getInitialState()[j][i] == 1:\n count = count + 1 \n if count > 1:\n return False\n return True\n \n def checkCond(self):\n if self.isFinal():\n return self.checkRow() and self.checkColumn() #and self.checkAbs()\n \n \n def checkAbs(self):\n n = self.finalState.getSize()\n for i1 in range(0,n):\n for i2 in range(i1,n):\n for j1 in range(0,n):\n for j2 in range(j1, n):\n if abs(i1-i2)-abs(j1-j2) !=0 and not self.finalState.getInitialState()[i1][j1] == 1 and not self.finalState.getInitialState()[i2][j2] == 1:\n return False\n return True\n \n \n def checkRowFinal(self):\n \n n = self.initialState.getSize()\n for i in range(n):\n count = 0\n for j in range(n):\n if self.initialState.getInitialState()[i][j] == 1:\n count = count + 1 \n if count == 1:\n return True\n return False\n \n \n def checkColumnFinal(self):\n \n n = self.initialState.getSize()\n for i in range(n):\n count = 0\n for j in range(n):\n if self.initialState.getInitialState()[j][i] == 1:\n count = count + 1 \n if count == 1:\n return True\n return False\n \n \n def checkCondFinal(self):\n return self.checkColumnFinal() and self.checkRowFinal() and self.checkAbs()\n \n \n def isFinal(self):\n for i in self.initialState.getInitialState():\n for j in self.initialState.getInitialState():\n if j==-1:\n return False \n return True\n \n \n #number of zeros in a matrix\n def heuristicFunction(self,state):\n if not self.checkCond():\n return maxsize\n return self.getNumberEl(state.getInitialState(),0)\n \n \n\n \n ","sub_path":"Lab2/Lab2/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7069558","text":"import numpy as np\r\nimport tensorflow as tf\r\n\r\n\r\nclass RNN:\r\n def __init__(self, input_size, state_size, hidden_sum, output_size, time_steps, batch_size, learning_rate):\r\n self.input_size = input_size\r\n self.state_size = state_size\r\n self.hidden_sum = hidden_sum\r\n self.output_size = output_size\r\n self.batch_size = batch_size\r\n self.time_steps = time_steps\r\n self.learning_rate = learning_rate\r\n self.children = tf.placeholder(np.float32, shape=(self.input_size, self.time_steps))\r\n self.target = tf.placeholder(np.float32, shape=(self.batch_size, self.time_steps))\r\n\r\n self.network()\r\n self.cost()\r\n self.optimizer()\r\n self.Persistent()\r\n self.Persistent_optimizer()\r\n\r\n init = tf.global_variables_initializer()\r\n self.sess = tf.Session()\r\n self.sess.run(init)\r\n\r\n # 定义网络结构\r\n def network(self):\r\n # self.cell = tf.nn.rnn_cell.BasicRNNCell(num_units=self.state_size) # 定义RNN的cell\r\n # self.inputs = tf.placeholder(np.float32, shape=(self.batch_size, self.input_size)) # 输入层\r\n # self.h0 = cell.zero_state(32, np.float32) # 通过zero_state得到一个全0的初始状态,形状为(batch_size, state_size)\r\n # self.output, self.h1 = cell.call(inputs, h0) # 一次调用call函数\r\n # 每调用一次这个函数就返回一个BasicRNNCell\r\n def get_a_cell(state_size):\r\n return tf.nn.rnn_cell.BasicRNNCell(num_units=state_size)\r\n # hidden_sum层RNN,如果hidden_sum=3,它的state_size是(128, 128, 128),表示共有3个隐层状态,每个隐层状态的大小为128\r\n cell = tf.nn.rnn_cell.MultiRNNCell([get_a_cell(self.state_size) for _ in range(self.hidden_sum)])\r\n # 输入层,shape = (batch_size, time_steps, input_size)\r\n self.inputs = tf.placeholder(np.float32, shape=(self.batch_size, self.time_steps, self.input_size))\r\n initial_state = cell.zero_state(self.batch_size, np.float32)\r\n self.outputs, self.state = tf.nn.dynamic_rnn(cell, self.inputs, initial_state=initial_state,\r\n dtype=tf.float32)\r\n\r\n self.weights = tf.Variable(tf.truncated_normal([self.state_size, self.output_size], stddev=0.1)) # 正态分布,均值为0,标准差为0.1\r\n self.biases = tf.Variable(tf.constant(0.1, shape=[self.output_size])) # 给定值的常量\r\n\r\n self.result = tf.nn.relu(tf.reshape(tf.matmul(tf.reshape(self.outputs, [self.time_steps, self.state_size]),\r\n self.weights) + self.biases, [self.output_size, self.time_steps]))\r\n\r\n\r\n # 定义递归神经网络的变换。在BasicRNNCell中,state_size永远等于output_size,需要额外对输出定义新的变换。递归神经网络\r\n def Persistent(self):\r\n\r\n def add_layer(input, timestep, output_size, state_size):\r\n\r\n if state_size == None:\r\n input_reshape = tf.reshape(input, [-1, timestep])\r\n Weight = tf.Variable(tf.truncated_normal([timestep, timestep], stddev=0.1))\r\n biases = tf.Variable(tf.constant(0.1, shape=[output_size]))\r\n output = tf.nn.tanh(tf.matmul(input_reshape, Weight) + biases)\r\n else:\r\n input_reshape = tf.reshape(input, [timestep, state_size])\r\n Weight = tf.Variable(tf.truncated_normal([state_size, timestep], stddev=0.1))\r\n biases = tf.Variable(tf.constant(0.1, shape=[output_size]))\r\n output = tf.nn.tanh(tf.matmul(input_reshape, Weight) + biases)\r\n\r\n return output\r\n\r\n def parents_layer(input1, input2, timestep, output_size):\r\n biases1 = tf.Variable(tf.constant(0.1, shape=[output_size]))\r\n input = input1 + input2 + biases1\r\n Weight = tf.Variable(tf.truncated_normal([timestep, output_size], stddev=0.1))\r\n biases2 = tf.Variable(tf.constant(0.1, shape=[output_size]))\r\n output = tf.nn.relu(tf.matmul(input, Weight) + biases2)\r\n return output\r\n\r\n # output_reshape = tf.reshape(self.outputs, [-1, self.state_size])\r\n # parents = tf.concat((output_reshape, self.children), 1)\r\n Uh = add_layer(self.outputs, self.time_steps, self.output_size, self.state_size)\r\n Wx = add_layer(self.children, self.time_steps, self.output_size, None)\r\n self.Persistent_result = tf.reshape(parents_layer(Uh, Wx, self.time_steps, self.output_size), [self.output_size, self.time_steps])\r\n # self.result = tf.reshape(result0, [self.batch_size, self.time_steps])\r\n\r\n def cost(self):\r\n # self.cost = 0.5*tf.reduce_sum(tf.pow(tf.subtract(label, self.result), 2.0))\r\n self.cost = tf.losses.mean_squared_error(self.target, self.result)\r\n\r\n def optimizer(self):\r\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.cost)\r\n\r\n def Persistent_optimizer(self):\r\n # self.cost = 0.5*tf.reduce_sum(tf.pow(tf.subtract(label, self.result), 2.0))\r\n self.Persistent_cost = tf.losses.mean_squared_error(self.target, self.Persistent_result)\r\n self.Persistent_optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize( self.Persistent_cost)\r\n\r\n # 定义执行一步训练的函数\r\n def opt(self, X, Y):\r\n cost, opt = self.sess.run((self.cost, self.optimizer), feed_dict={self.inputs: X, self.target: Y})\r\n return cost\r\n\r\n def Persistent_opt(self, X, Y, C):\r\n cost, opt = self.sess.run((self.Persistent_cost, self.Persistent_optimizer), feed_dict={self.inputs: X, self.target: Y, self.children: C})\r\n return cost\r\n\r\n # 返回输出层的结果\r\n def result(self, X):\r\n return self.sess.run(self.result, feed_dict={self.inputs: X})","sub_path":"rnn/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"41109322","text":"class Game:\n def smallGame(self):\n time = 3\n answer = '大哥哥'\n while time > 1:\n name = str(input('请输入您的姓名:'))\n age = int(input('请输入您的年龄:'))\n question = str(input('(你叫我叫什么?)请输入你的答案:'))\n if age > 18:\n time -= 1\n if question == answer:\n print('您老答对了,奖励你一个么么哒!~~~~~~')\n exit()\n else:\n print('您老是成年人了。。。。,可以玩这个游戏,你还剩%d次机会!' % time)\n else:\n print('您小还是一个骚年啊,我看你还是回家歇着吧')\n exit()\n\ngame = Game()\ngame.smallGame()\n","sub_path":"answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"608324263","text":"#!/usr/bin/env/python\n\n\"\"\"\n course_ingest.py: Given course and section data from the Office of the\n University Registrar (from the Enterprise Data Warehouse), add courses\n as necessary, and course sections of courses. Links courses to instructors\n vis teacher roles, create a course web site object for each course. Link\n Sections (instances of courses) to course, instructor (via teacher role)\n and to academic term.\n\n Exceptions are thrown, caught and logged for missing academic term and\n missing instructor.\n\n See CHANGELOG.md for history\n\n To Do:\n -- Create a test file with various test conditions and notes\n -- Move to an update design\n -- Use rdflib\n -- Support Simple VIVO processing\n -- Use argparse to handle command line arguments\n\n Long Term:\n -- Retire the two phase process where course ingest writes records for\n person ingest, person ingest runs and then course ingest is run again.\n Use add_person to add instructors if needed\n -- Update to VIVO-ISF\n\"\"\"\n\n__author__ = \"Michael Conlon\"\n__copyright__ = \"Copyright 2014, University of Florida\"\n__license__ = \"BSD 3-Clause license\"\n__version__ = \"0.7\"\n\nfrom vivopeople import make_ufid_dictionary\nfrom vivocourses import prepare_teaching_data\nfrom vivocourses import make_term_dictionary\nfrom vivocourses import make_course_dictionary\nfrom vivocourses import make_section_dictionary\nfrom vivocourses import make_course_rdf\nfrom vivocourses import make_section_rdf\nfrom vivofoundation import rdf_header\nfrom vivofoundation import rdf_footer\nimport vivofoundation as vt\nfrom datetime import datetime\nimport codecs\nimport argparse\n\naction_report = {} # determine the action to be taken for each UFID\n\n# Driver program starts here\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"filename\", help=\"name of file containing course data to be added to VIVO\",\n default=\"course\", nargs='?')\nargs = parser.parse_args()\n\ndebug = False\nsample = 1.0 # Fraction of records to be processed. Set to 1.0 to process all\n\nfile_name = args.filename\nadd_file = codecs.open(file_name+\"_add.rdf\", mode='w', encoding='ascii',\n errors='xmlcharrefreplace')\npos_file = codecs.open(file_name+\"_pos.txt\", mode='w', encoding='ascii',\n errors='xmlcharrefreplace')\nlog_file = codecs.open(file_name+\"_log.txt\", mode='w', encoding='ascii',\n errors='xmlcharrefreplace')\nexc_file = codecs.open(file_name+\"_exc.txt\", mode='w', encoding='ascii',\n errors='xmlcharrefreplace')\nadd_ufid = {}\n\nprint >>add_file, rdf_header()\nprint >>log_file, datetime.now(), \"Course ingest. Version\", __version__,\\\n \"VIVO Tools\", vt.__version__\nprint >>log_file, datetime.now(), \"Make UF Taught Dictionary\"\nteaching_data = prepare_teaching_data(filename='course_data.csv', debug=debug)\nprint >>log_file, datetime.now(), \"Taught dictionary has \",\\\n len(teaching_data), \" entries\"\nprint >>log_file, datetime.now(), \"Make VIVO Term Dictionary\"\nterm_dictionary = make_term_dictionary(debug=debug)\nprint >>log_file, datetime.now(), \"VIVO Term dictionary has \",\\\n len(term_dictionary), \" entries\"\nprint >>log_file, datetime.now(), \"Make VIVO Course Dictionary\"\ncourse_dictionary = make_course_dictionary(debug=debug)\nprint >>log_file, datetime.now(), \"VIVO Course dictionary has \",\\\n len(course_dictionary), \" entries\"\nprint >>log_file, datetime.now(), \"Make VIVO Section Dictionary\"\nsection_dictionary = make_section_dictionary(debug=debug)\nprint >>log_file, datetime.now(), \"VIVO Section dictionary has \",\\\n len(section_dictionary), \" entries\"\nprint >>log_file, datetime.now(), \"Make VIVO UFID Dictionary\"\nufid_dictionary = make_ufid_dictionary(debug=debug)\nprint >>log_file, datetime.now(), \"VIVO UFID dictionary has \",\\\n len(ufid_dictionary), \" entries\"\n\n# Loop through the course data. Process each row\n\nprint >>log_file, datetime.now(), \"Begin Processing\"\nfor teaching_record in teaching_data.values():\n\n ardf = \"\"\n\n # Look for the instructor. If not found, write to exception log\n\n try:\n person_uri = ufid_dictionary[teaching_record['ufid']]\n teaching_record['person_uri'] = person_uri\n except KeyError:\n print >>exc_file, \"No such instructor on row\", teaching_record, \"UFID = \", \\\n teaching_record['ufid']\n add_ufid[teaching_record['ufid']] = True\n\n continue\n\n # Look for the term. If not found, write to exception log\n\n try:\n term_uri = term_dictionary[teaching_record['term_name']]\n teaching_record['term_uri'] = term_uri\n except KeyError:\n print >>exc_file, \"No such term on row\", teaching_record, \"Term = \",\\\n teaching_record['term_name']\n continue\n\n # Look for the course. If not found, add it\n\n try:\n course_uri = course_dictionary[teaching_record['course_number']]\n teaching_record['course_new'] = False\n except KeyError:\n [add, course_uri] = make_course_rdf(teaching_record)\n ardf = ardf + add\n print >>log_file, \"Add course\", teaching_record['course_name'],\\\n \"at\", course_uri\n course_dictionary[teaching_record['course_number']] = course_uri\n teaching_record['course_new'] = True\n teaching_record['course_uri'] = course_uri\n\n # Look for the section. If not found, add it\n\n try:\n section_uri = section_dictionary[teaching_record['section_name']]\n except KeyError:\n [add, section_uri] = make_section_rdf(teaching_record)\n print >>log_file, \"Add section\", teaching_record['section_name'],\\\n \"at\", section_uri\n ardf = ardf + add\n section_dictionary[teaching_record['section_name']] = section_uri\n\n teaching_record['section_uri'] = section_uri\n\n if ardf != \"\":\n add_file.write(ardf)\n\n# Done processing the courses. Wrap-up\n\nfor ufid in sorted(add_ufid.keys()):\n\n # Write records into a position file. Records have the UFID to be\n # added to VIVO, along with a zero in the HR_POSITION field (last\n # field) indicating to person_ingest that no position should be created\n # for the UFID being added.\n\n print >>pos_file, \"NULL\" + \"|\" + ufid + \"|\" + \\\n \"NULL\" + \"|\" + \"NULL\" + \"|\" + \"NULL\" + \"|\" + \"NULL\" + \"|\" + \\\n \"NULL\" + \"|\" + \"0\"\n\nprint >>add_file, rdf_footer()\nprint >>log_file, datetime.now(), \"End Processing\"\n\nadd_file.close()\nlog_file.close()\nexc_file.close()\npos_file.close()\n","sub_path":"course_ingest.py","file_name":"course_ingest.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"70828114","text":"#!/usr/bin/env python3\n\nimport json\nimport subprocess\n\n\ndef shell_cmd(cmd):\n\n\tcommand = subprocess.Popen(cmd, shell=True, executable='/bin/bash')\n\tcommand.wait()\n\treturn command.returncode\n\n\nuserlist = json.load(open('/tmp/sysadmin.json', 'r'))\n\nfor user in userlist['sysadmin']:\n\tname = user['name']\n\tuid = user['uid']\n\tshell = user['shell']\n\tcomment = user['comment']\n\tssh_keys = user['ssh_keys']\n\taction = user['action']\n\n\tif action == 'create' and len(ssh_keys) > 0:\n\t\tuseradd = shell_cmd('useradd -m ' + name + ' -u ' + str(uid) + ' -G sysadmin -s ' + shell + ' -c \"' + comment + '\"')\n\t\tif useradd == 0:\n\t\t\tmkdir = shell_cmd('mkdir -p /home/' + name + '/.ssh/')\n\t\t\tif mkdir == 0:\n\t\t\t\twith open('/home/' + name + '/.ssh/authorized_keys', 'w') as authorized_keys:\n\t\t\t\t\tauthorized_keys.write(user['ssh_keys'])\n\t\t\t\t\tauthorized_keys.close()\n\t\t\t\t\tchmod = shell_cmd('chmod 600 /home/' + name + '/.ssh/authorized_keys')\n\t\t\t\t\tif chmod == 0:\t\t\t\t\n\t\t\t\t\t\tchown = shell_cmd('chown ' + name + ':' + name + ' -R /home/' + name + '/.ssh/')\n\n\tif action == 'remove':\n\t\tuserdel = shell_cmd('userdel -rf ' + name + ' > /dev/null 2>&1')","sub_path":"scripts/updateusers.py","file_name":"updateusers.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"464489523","text":"from transactions_assessment.loaders import DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom datetime import datetime\nfrom enum import Enum\nimport pandas as pd\n\n\nclass Constants(Enum):\n CAT_VARS = ['accountNumber', 'customerId', 'merchantName', 'merchantCategoryCode',\n 'currentExpDate', 'accountOpenDate', 'dateOfLastAddressChange', 'cardCVV', 'enteredCVV',\n 'cardLast4Digits']\n DROP_VARS = ['echoBuffer', 'merchantCity', 'merchantState', 'merchantZip', 'posOnPremises', 'recurringAuthInd',\n 'transactionDateTime']\n DUMMY_VARS = ['merchantCountryCode', 'posEntryMode', 'posConditionCode', 'transactionType', 'acqCountry']\n\n\nclass TransactionLoader(DataLoader):\n\n def preprocess_data(self) -> pd.DataFrame:\n \"\"\"\n load in data from text file and convert to\n a pandas dataframe. Turn the variable transactionDateTime\n into a datetime type.\n RETURNS\n ---------\n df: pd.DataFrame\n preprocessed data frame\n \"\"\"\n loaded_data: list = self.read_lines()\n df = pd.DataFrame(loaded_data)\n df['transactionDateTime'] = df.transactionDateTime.apply(\n lambda k: datetime.strptime(k.replace('T', ' '), '%Y-%m-%d %H:%M:%S'))\n df['multi_swipe'] = detect_multi_swipe(300, df)\n return df\n\n\nclass ModelDataLoader(DataLoader):\n def preprocess_data(self) -> tuple:\n \"\"\"\n Preprocess data for fitting with\n a model\n\n RETURNS\n --------\n x_train: pd.DataFrame\n training set of predictors\n y_train: pd.Series\n training set of responses\n x_test: pd.DataFrame\n testing set of predictors\n y_test: pd.Series\n test set of responses\n \"\"\"\n loaded_data: list = self.read_lines()\n df = pd.DataFrame(loaded_data)\n df['transactionDateTime'] = df.transactionDateTime.apply(\n lambda k: datetime.strptime(k.replace('T', ' '), '%Y-%m-%d %H:%M:%S'))\n df = df.sort_values('transactionDateTime').reset_index()\n df['multi_swipe'] = detect_multi_swipe(300, df)\n df['fraud_target'] = df.merchantName.apply(lambda k: 1 if k.lower() == 'fresh flowers' else 0)\n labels = df.isFraud.astype(int)\n df.drop('isFraud', axis=1, inplace=True)\n df = self.encode_cats(df)\n df.drop(Constants.DROP_VARS.value, axis=1, inplace=True)\n x_train, y_train, x_test, y_test = train_test_split(df, labels, test_size=0.2, random_state=40)\n\n return x_train, y_train, x_test, y_test\n\n def encode_cats(self, df: pd.DataFrame):\n \"\"\"\n encode categorical variables\n \"\"\"\n label_encoder = LabelEncoder()\n cat_cols = Constants.CAT_VARS.value\n for col in cat_cols:\n df[col] = label_encoder.fit_transform(df[col])\n processed_df = pd.get_dummies(df, columns=Constants.DUMMY_VARS.value, drop_first=True)\n return processed_df\n\n\ndef detect_multi_swipe(time_window: int, df: pd.DataFrame) -> list:\n \"\"\"\n Decide if any give transaction is\n part of a series of multi-swipes by\n comparing the times of transaction\n DateTime, and the amount of purchase.\n\n PARAMS\n --------\n df: pd.DataFrame\n unprocessed pandas dataframe with\n column transactionDate\n\n time_window: int\n time in seconds to use as the cut-off\n to decide if a transaction is multi-swipe\n\n RETURNS\n --------\n multi_swipe_col: list\n a list of 0s and 1s representing\n whether a transaction is multi-swipe (1)\n or not (0)\n \"\"\"\n multi_swipe_col = [0]\n for idx, dt in enumerate(df.transactionDateTime):\n if idx == 0:\n continue\n diff = abs(df.transactionDateTime[idx] - df.transactionDateTime[idx - 1]).total_seconds()\n if diff < time_window and (df.transactionAmount[idx] == df.transactionAmount[idx - 1]) and (\n df.accountNumber[idx - 1] == df.accountNumber[idx]) and (\n df.transactionType[idx].lower() == 'purchase'):\n multi_swipe = 1\n else:\n multi_swipe = 0\n multi_swipe_col.append(multi_swipe)\n return multi_swipe_col\n","sub_path":"transactions_assessment/loaders/data_loaders.py","file_name":"data_loaders.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"309736218","text":"import os\nimport markdown\n\nfrom flask import g, Blueprint, render_template, redirect, request, url_for, current_app\nfrom ulapd_ui.utils.session import dps_session\nfrom ulapd_ui.exceptions import ApplicationError\nfrom ulapd_ui.utils.decorators import requires_signed_in_user, refresh_user_session\nfrom ulapd_ui.dependencies.ulapd_api import UlapdAPI\nfrom ulapd_ui.dependencies.metric import send_metric\nfrom ulapd_ui.utils.datasets_utilities import accept_licence, check_agreement, \\\n historic_date_formatter, build_dataset_details, build_rfi_dataset_for_download\n\ndirectory = os.path.dirname(__file__)\n\ndatasets = Blueprint(\n 'datasets',\n __name__,\n url_prefix=\"/datasets\")\n\n\n@datasets.route(\"\", methods=['GET'])\ndef redirect_to_home_page():\n return redirect('/')\n\n\n@datasets.route(\"/<dataset_id>\", methods=['GET'])\n@refresh_user_session\ndef get_details(dataset_id):\n try:\n ulapd_api = UlapdAPI()\n session = dps_session.get_state()\n\n if dataset_id == 'nps_sample':\n return redirect(url_for('.get_details', dataset_id='nps'))\n\n # Go get the individual dataset details\n dataset_details = ulapd_api.get_dataset_by_name(dataset_id)\n\n # Fail nicely if the dataset doesnt exist\n if dataset_id not in dataset_details['name']:\n raise ApplicationError('Unable to display dataset details: dataset does not exist', http_code=404)\n\n # Now get the example json and to our dataset list\n extras = build_dataset_details(dataset_id)\n\n # Add details to dataset\n dataset_details.update(extras)\n\n # get dataset for dataset_id to check private boolean, if false is non restricted, if true is restricted\n is_restricted = dataset_details['private']\n\n licence_signed = check_agreement(dataset_id)\n\n if dataset_id == 'nps':\n licence_signed = {\n 'nps': check_agreement(dataset_id),\n 'nps_sample': check_agreement('nps_sample')\n }\n\n # Handle freemium licencing:\n # If a user has signed exploratory/commercial licences they should still be able to sign direct licence\n if dataset_details['type'] == 'freemium':\n if g.user:\n licence_signed = True\n dataset = session['user']['datasets'].get(dataset_id)\n\n if not dataset:\n licence_signed = False\n\n if dataset:\n if 'Direct Use' not in dataset['licences']:\n licence_signed = False\n\n if len(dataset['licences']) == 1:\n if 'Direct' in dataset['licences'][0] and not dataset['valid_licence']:\n licence_signed = False\n\n current_app.logger.info('Displaying details for user requested dataset: {}'.format(dataset_id))\n\n breadcrumb_links = [{\"label\": \"Home\", \"href\": \"/\"},\n {\"label\": dataset_details['title'], \"href\": None}]\n\n return render_template(\"app/datasets/{}/details.html\".format(dataset_id),\n dataset_details=dataset_details,\n licence_signed=licence_signed,\n is_restricted=is_restricted,\n readable_date=dataset_details['last_updated'], breadcrumb_links=breadcrumb_links)\n except ApplicationError as e:\n raise ApplicationError('Something went wrong when retrieving dataset details: {}'.format(e))\n\n\n@datasets.route(\"/<dataset_id>/licence/view\", methods=['GET'])\n@datasets.route(\"/<dataset_id>/licence/<licence_type>/view\", methods=['GET'])\n@refresh_user_session\ndef view_licence(dataset_id, licence_type=None):\n try:\n if licence_type:\n current_app.logger.info('Displaying view {} licence page for dataset: {}'.format(licence_type, dataset_id))\n return render_template(\"app/datasets/licence.html\", licence_type=licence_type, dataset_id=dataset_id)\n else:\n licence_file = open(os.path.join(directory, '../documents/datasets/{}/licence.md').format(dataset_id), \"r\")\n md_licence = licence_file.read()\n md_renderer = markdown.Markdown()\n md_html = md_renderer.convert(md_licence)\n\n current_app.logger.info('Displaying view licence page for dataset: {}'.format(dataset_id))\n return render_template(\"app/datasets/licence.html\", dataset_id=dataset_id, md=md_html)\n except Exception as e:\n raise ApplicationError('Something went wrong when retrieving licence view page: {}'.format(e))\n\n\n@datasets.route(\"/<dataset_id>/tech-spec\", methods=['GET'])\n@datasets.route(\"/<dataset_id>/tech-spec/<tech_spec_no>\", methods=['GET'])\ndef get_tech_spec(dataset_id, tech_spec_no=None):\n if tech_spec_no:\n return render_template('app/datasets/{}/tech_spec_{}.html'.format(dataset_id, tech_spec_no),\n dataset_id=dataset_id)\n else:\n return render_template('app/datasets/{}/tech_spec.html'.format(dataset_id), dataset_id=dataset_id)\n\n\n@datasets.route(\"/<dataset_id>/licence/agree\", methods=['GET'])\n@requires_signed_in_user\n@refresh_user_session\ndef get_agree_licence(dataset_id):\n try:\n ulapd_api = UlapdAPI()\n dataset_details = ulapd_api.get_dataset_by_name(dataset_id)\n accepted = check_agreement(dataset_id)\n\n if dataset_details['type'] == 'freemium':\n accepted = True\n session = dps_session.get_state()\n dataset = session['user']['datasets'].get(dataset_id)\n\n if not dataset:\n accepted = False\n\n if dataset:\n if 'Direct Use' not in dataset['licences']:\n accepted = False\n\n if len(dataset['licences']) == 1:\n if 'Direct' in dataset['licences'][0] and not dataset['valid_licence']:\n accepted = False\n\n if not accepted:\n return render_template(\n \"app/datasets/licence.html\",\n agree=True,\n dataset_id=dataset_id,\n licence_type='direct'\n )\n\n if accepted:\n current_app.logger.info('Redirecting to download page for dataset: {}'.format(dataset_id))\n return redirect(url_for('.get_details', dataset_id=dataset_id))\n\n licence_file = open(os.path.join(directory, '../documents/datasets/{}/licence.md').format(dataset_id), \"r\")\n md_licence = licence_file.read()\n md_renderer = markdown.Markdown()\n md_html = md_renderer.convert(md_licence)\n current_app.logger.info('Displaying agree licence page for dataset: {}'.format(dataset_id))\n\n return render_template(\"app/datasets/licence.html\", agree=True, dataset_id=dataset_id, md=md_html)\n except Exception as e:\n raise ApplicationError('Something went wrong when retrieving licence agree page: {}'.format(e))\n\n\n@datasets.route(\"/<dataset_id>/licence/agree\", methods=['POST'])\n@requires_signed_in_user\ndef post_agree_licence(dataset_id):\n try:\n ulapd_api = UlapdAPI()\n dataset_details = ulapd_api.get_dataset_by_name(dataset_id)\n\n if request.form.get('agree-licence') is None:\n is_freemium = dataset_details['type'] == 'freemium'\n\n md_html = ''\n\n # Until we convert licence MD files to HTML\n if not is_freemium:\n licence_file = open(os.path.join(directory, f'../documents/datasets/{dataset_id}/licence.md'), \"r\")\n md_licence = licence_file.read()\n md_renderer = markdown.Markdown()\n md_html = md_renderer.convert(md_licence)\n\n current_app.logger.info('Displaying licence page with errors for dataset: {}'.format(dataset_id))\n error_msg = 'You need to agree to the terms and conditions to download data'\n return render_template(\"app/datasets/licence.html\",\n agree=True,\n dataset_id=dataset_id,\n licence_type='direct',\n md=md_html,\n error_title=\"There are errors on this page\",\n fields={'agree-licence': {'data': '', 'error': [error_msg]}})\n else:\n # Prevent users signing licences for nps/dad etc via the service\n if dataset_details['type'] not in ['confidential', 'restricted']:\n accept_licence(dataset_id)\n current_app.logger.info('Redirecting to download page for dataset: {}'.format(dataset_id))\n session = dps_session.get_state()\n\n if dataset_id == 'nps_sample':\n return redirect(url_for('.get_details', dataset_id='nps'))\n\n return redirect(url_for('general.get_list'))\n except Exception as e:\n raise ApplicationError('Something went wrong when retrieving licence agree page: {}'.format(e))\n\n\n@datasets.route(\"/<dataset_id>/download\", methods=['GET'])\n@refresh_user_session\ndef get_download_page(dataset_id):\n ulapd_api = UlapdAPI()\n\n if dataset_id == 'rfi':\n dataset, history = build_rfi_dataset_for_download(ulapd_api.get_dataset_by_name(dataset_id),\n ulapd_api.get_dataset_history(dataset_id))\n else:\n dataset = ulapd_api.get_dataset_by_name(dataset_id)\n history = ulapd_api.get_dataset_history(dataset_id)\n\n breadcrumb_links = [{\"label\": \"Home\", \"href\": \"/\"},\n {\"label\": dataset['title'], \"href\": \"/datasets/\"+dataset['name']},\n {\"label\": \"Download dataset\", \"href\": None}]\n\n return render_template('app/datasets/{}/download.html'.format(dataset_id), dataset=dataset, history=history,\n breadcrumb_links=breadcrumb_links)\n\n\n@datasets.route(\"/<dataset_id>/download/<file_name>\", methods=['GET'], defaults={'last_updated': None})\n@datasets.route(\"/<dataset_id>/download/history/<last_updated>/<file_name>\", methods=['GET'])\n@refresh_user_session\ndef download(dataset_id, file_name, last_updated):\n try:\n ulapd_api = UlapdAPI()\n\n dataset = ulapd_api.get_dataset_by_name(dataset_id)\n\n # First check to see if its a public resource\n if last_updated is None:\n for resource in dataset['public_resources']:\n current_app.logger.info(\"Public: \" + str(resource['file_name']))\n if resource['file_name'] == file_name:\n current_app.logger.info(\"Public file download, skipping checks\")\n url = ulapd_api.get_download_link(dataset_id, resource['file_name'])\n return redirect(url['link'])\n\n if dataset['type'] != 'open':\n # Need the session to get infor about the dataset and user\n session = dps_session.get_state()\n user_id = session['user']['user_details']['user_details_id']\n user_data = session['user']['user_details']\n\n # 1. Check if user is authenticated\n if not dps_session.is_logged_in():\n return '/sign-in'\n\n # 2. Check if user has signed the correct licence\n if check_agreement(dataset_id) is not True:\n current_app.logger.info(\"User has no access to dataset\")\n return url_for('datasets.get_agree_licence', dataset_id=dataset_id)\n\n # 3. Generate link\n if last_updated:\n last_updated = historic_date_formatter(last_updated, dataset['update_frequency'])\n url = ulapd_api.get_history_download_link(dataset_id, file_name, last_updated)\n activity = 'history download'\n else:\n url = ulapd_api.get_download_link(dataset_id, file_name)\n activity = 'download'\n\n # 4. Track the download and return (create activity)\n ulapd_api.create_activity(session['user']['user_details']['user_details_id'],\n \"download\", request.remote_addr, False, file_name, dataset_id)\n\n send_metric(dataset_id, activity + \" ui\", user_id, user_data, file_name)\n else:\n # 1. Generate link\n if last_updated:\n last_updated = historic_date_formatter(last_updated, dataset['update_frequency'])\n url = ulapd_api.get_history_download_link(dataset_id, file_name, last_updated)\n else:\n url = ulapd_api.get_download_link(dataset_id, file_name)\n\n return redirect(url['link'])\n except Exception as e:\n raise ApplicationError('Tracking download has failed - error: {}'.format(e))\n","sub_path":"ulapd_ui/views/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":12819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"349910419","text":"__author__ = 'Antim_000'\n\nimport Logic\nimport Machine\n\n\nclass JobList():\n # These are the hard coded allowable values for the given parameters\n MATERIAL = (\"Aluminum\", \"Brass\", \"Blue Wax\", \"Acrylic\", \"Copper\", \"Polycarbonate\")\n\n PART_TYPE = (\n \"Photon Compensator\", \"Proton Aperture\", \"Proton Range Compensator\", \"ECT Bolus\", \"Electron Aperture\", \"Tray\")\n\n SHIP_PRIORITY = (\"24 Hour\", \"48 Hour\", \"72 Hour\")\n\n CONFIGURATION = (\"Varian\", \"Siemens\", \"Elekta\")\n\n AXIS_TYPE = ('3-Axis', '5-Axis')\n\n def __init__(self):\n self.job_list = []\n\n def add_job(self, job_number=None,\n material=None,\n part_type=None,\n set_id=None,\n size=None,\n thickness=None,\n ship_priority=None,\n run_time=None,\n configuration=None,\n site_ID=None,\n order_time=None,\n axis_type=None):\n \"\"\"\n This function adds a job with all the required parameters into the Joblist attribute\n :return: None if good, else Error\n \"\"\"\n if job_number not in self.job_list:\n self.job_list.append({'job_number': job_number, 'material': material, 'part_type': part_type,\n 'set_id': set_id, 'size': float(size), 'thickness': float(thickness),\n 'ship_priority': ship_priority, 'run_time': int(run_time),\n 'configuration': configuration, 'site_ID': site_ID, 'machine': None,\n 'machine_batch': None, 'order_time': int(order_time),\n 'axis_type': axis_type, 'committed': False})\n self.schedule_parts()\n return None\n else:\n raise RuntimeError('Job Number Already Exists')\n\n def get_next_job_number(self):\n return len(self.job_list) + 1\n\n def get_next_batch_number(self, machine):\n next_batch_num = 0\n for job in self.job_list:\n if job['machine'] == machine:\n if job['machine_batch'] >= next_batch_num:\n next_batch_num = job['machine_batch'] + 1\n return next_batch_num\n return 1\n\n\n def schedule_parts(self):\n logic = Logic.Logic(self)\n logic.schedule_parts()\n\n def get_parts_on_machine(self, machine):\n result = []\n for job in self.job_list:\n if job['machine'] == machine:\n result.append(job)\n return result\n\n def get_uncommited_parts_of_type(self, value):\n result = []\n for job in self.job_list:\n if job['part_type'] == value and job['committed'] == False:\n result.append(job)\n print(result)\n return result\n\n def set_machine(self, job_number, machine_to_set, batch_num):\n for job in self.job_list:\n if job['job_number'] == job_number:\n job['machine'], job['machine_batch'] = machine_to_set, batch_num\n self.update_machine(self, machine_to_set)\n\n def update_machine(self, job_list, machine_name):\n for machine in Machine.Machine.machine_instances:\n if machine.get_machine_name() == machine_name:\n machine.update_time(job_list)\n\n def reset_machine_batches(self, list_of_parts):\n for part in list_of_parts:\n part['machine_batch'] = 0\n\n def get_next_batch_jobs(self):\n result = []\n for machine in Machine.Machine.machines:\n part = self.get_next_batch_to_run(machine)\n if part: # ensure part is not empty\n result[machine] = part\n return result\n\n def get_next_batch_to_run(self, machine):\n parts_on_machine = []\n for job in self.job_list:\n if job['machine'] == machine:\n parts_on_machine.append(job)\n sorted(parts_on_machine, key=lambda part: part['machine_batch'])\n if parts_on_machine: # ensure not returning empty lists.\n return parts_on_machine[0]\n else:\n return None\n\n def commit_job(self, job_to_commit):\n for job in self.job_list:\n if job['job_number'] == job_to_commit:\n job['committed'] = True\n\n for machine in Machine.Machine.machine_instances:\n if machine.get_machine_name() == job['machine']:\n if job['part_type'] == 'Proton Range Compensator':\n machine.set_previous_fixture(size=job['thickness'])\n","sub_path":"JobList.py","file_name":"JobList.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"444375728","text":"from theano import shared\nimport theano.tensor as T\nimport numpy as np\n\ndef parse_example(fname):\n\twith open(fname) as f:\n\t content = f.readlines()\n\tcontent = [x.strip() for x in content]\n\tdata = []\n\tfor line in content:\n\t\t# print line\n\t\ttemp = line.split('\\t')\n\t\t#-interp\n\t\tparse = []\n\t\tfor node in temp:\n\t\t\tif \"-interp\" in node:\n\t\t\t\t# print \"here\"\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tparse.append(node)\t\t\n\t\ts = []\n\t\tfor node in parse:\n\t\t\ts.append(node[node.find(\"(\")+1:node.find(\")\")].split(\",\"))\n\t\tfor i in xrange(len(s)):\n\t\t\ts[i][0] = s[i][0][2:]\t\n\t\tdata.append(s)\n\treturn data\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"157313658","text":"# -*- coding:utf-8 -*-\n\nclass Solution:\n \"\"\"\n Problem:\n Given a non-empty array of integers, every element appears twice except for one.\n Find that single one.\n 给一个非空整数数组,所有的元素都出现了两次,除了一个。找出这个。\n\n Example 1:\n Input: [2,2,1]\n Output: 1\n Example 2:\n Input: [4,1,2,1,2]\n Output: 4\n -----------------------------------------\n Notes:\n Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n 你的算法必须要有线性的时间复杂度。你可以不需要额外的空间实现吗?\n\n -----------------------------------------\n Think:\n 1、主要的思想就是消除其他一一配对的组合元素,剩下的就是那个单独的元素。\n 2、实际这个题目在现实中并不常用,因为假如有数值出现3次,或者更多次,那么位\n 运算就可能会出错,反而是hashtable的思想可以一直使用。但是这给我们一个思\n 考,利用更底层的运算来达到加快速度的目的,可以考虑位运算。\n\n -----------------------------------------\n Idea:\n 1、利用hashtable存储元素出现的次数,这样子在最后的时候,判断只出现一次的元\n 素就是只出现一次的。\n 2、利用位运算的异或特性:\n 两个相同的数异或:为0,因为完全相同\n 一个数和0异或:为原来的数,因为1 ^ 0 = 1,0 ^ 0 = 0\n 所以两两异或,最后剩下的数就是单独的数。\n 3、数学方法:\n 2*(a+b+c) - (a+b+a+b+c) = c\n\n\n -----------------------------------------\n Code[1]:\n def singleNumber(self, nums):\n hashtable = {}\n for num in nums:\n if num not in hashtable.keys():\n hashtable[num] = 0\n hashtable[num] += 1\n\n for key,value in hashtable.items():\n if value <= 1:\n return key\n\n -----------------------\n Runtime:96ms\n Memory:O(n)\n Beats:8.41%\n Big(O):O(n)\n Space:\n 优点:容易理解也容易实现\n 缺点:消耗空间,而且需要两个遍历循环才能处理。\n -----------------------------------------\n Code[2]:\n def singleNumber(self, nums):\n res = 0\n for num in nums:\n res ^= num\n return res\n\n -----------------------\n Runtime:40ms\n Memory:O(1)\n Beats:100.0%\n Big(O):O(n)\n Space:\n 优点:不需要开辟额外的空间,位运算很快。\n 缺点:不容易想到,但是只要想到了,以后就不会忘记了。\n \"\"\"\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return 2 * sum(set(nums)) - sum(nums)\n\n\nif __name__ == '__main__':\n sol = Solution()\n print(sol.singleNumber([1,2,1,2,3]))\n","sub_path":"code/train/LeetCode/hashtable/136.Single Number[Easy].py","file_name":"136.Single Number[Easy].py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"487636565","text":"import tensorflow as tf\nimport drd_input as i\nimport matplotlib.pyplot as plt\nimport numpy as np\ndata_dir = \"/home/olle/PycharmProjects/Diabetic_Retinopathy_Detection/data/balanced\"\n\nfor example in tf.python_io.tf_record_iterator(data_dir+\"/data_batch_3.bin\"):\n result = tf.train.Example.FromString(example)\n print(result.features.feature['label'].int64_list.value)\n print(result.features.feature['image_name'].bytes_list.value)\n\nfilename_queue = tf.train.string_input_producer([data_dir+\"/data_batch_3.bin\"])\nread_input = i.read_svhn(filename_queue)\nsess = tf.InteractiveSession()\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(coord=coord)\nimg, lab, id = sess.run([read_input.uint8image, read_input.label, read_input.name])\nimg = np.asarray(img).reshape(1, img.shape[0],img.shape[1], 3)\nlab = np.asarray(lab)\nprint(img.shape,lab, id)#, label.shape, name)\n\n# Loop over each example in batch\nfor i in range(img.shape[0]):\n plt.imshow(img[i])\n plt.show()\n #print('Class label ' + lab)","sub_path":"test_data_pipe.py","file_name":"test_data_pipe.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"627733105","text":"#!/usr/bin/env python3\n\nfrom graph.core import *\n\nfrom graph.load_xml import load_graph_types_and_instances\nfrom graph.save_xml_stream import save_graph\n\nimport sys\nimport os\nimport math\nimport random\n\nimport os\nappBase=os.path.dirname(os.path.realpath(__file__))\n\nsrc=appBase+\"/relaxation_heat_graph_type.xml\"\n(graphTypes,graphInstances)=load_graph_types_and_instances(src,src)\n\ncolours=[\n[0,1,3,2],\n[0,2,3,1],\n[3,2,0,1],\n[3,1,0,2]\n]\n\ndef cell_colour(x,y):\n return colours[x%4][y%4]\n\nurand=random.random\n\nmax_steps=10\n\nn=16\nif len(sys.argv)>1:\n n=int(sys.argv[1])\nm=n\nif len(sys.argv)>2:\n m=int(sys.argv[2])\n\n#assert n>=2\n\ngraphType=graphTypes[\"relaxation_heat\"]\ncellType=graphType.device_types[\"cell\"]\nmergerType=graphType.device_types[\"merger\"]\nrootType=graphType.device_types[\"root\"]\nfanoutType=graphType.device_types[\"fanout\"]\n\ninstName=\"rheat_{}_{}\".format(n,n)\n\nproperties={}\n\nres=GraphInstance(instName, graphType, properties)\n\nnodes={}\n\nfor x in range(0,n):\n sys.stderr.write(\" Devices : Row {} of {}\\n\".format(x, n))\n for y in range(0,m):\n meta={\"loc\":[x,y],\"hull\":[ [x-0.5,y-0.5], [x+0.5,y-0.5], [x+0.5,y+0.5], [x-0.5,y+0.5] ]}\n boundary=0\n initial=0\n if x==0 or y==0:\n boundary=1\n initial=-127\n if x==n-1 or y==m-1:\n boundary=1\n initial=127\n colour=cell_colour(x,y)\n \n props={ \"initial_boundary\":boundary, \"initial_heat\":initial, \"colour\":colour, \"neighbours\":0, \"x\":x, \"y\":y } # We will update neighbours later\n di=DeviceInstance(res,\"c_{}_{}\".format(x,y), cellType, props, metadata=meta)\n nodes[(x,y)]=di\n res.add_device_instance(di)\n \ndef add_channel(dx,dy,sx,sy):\n dst=nodes[ (dx,dy) ]\n src=nodes[ ( sx, sy ) ]\n ei=EdgeInstance(res,dst,\"share_in\", src,\"share_out\")\n res.add_edge_instance(ei)\n src.properties[\"neighbours\"]+=1\n\nfor x in range(0,n):\n sys.stderr.write(\" Edges : Row {} of {}\\n\".format( x, n))\n for y in range(0,m):\n if x!=0: add_channel(x-1,y,x,y)\n if y!=0: add_channel(x,y-1,x,y)\n if x!=n-1: add_channel(x+1,y,x,y)\n if y!=m-1: add_channel(x,y+1,x,y)\n\nfor d in nodes.values():\n if n==1:\n d.properties[\"multiplier\"]=0\n else:\n d.properties[\"multiplier\"]=int( 2**16 / (d.properties[\"neighbours\"]) )\n\n\n############################################################\n## Termination tree\n\nto_merge=list(nodes.values())\n\ndepth=0\nwhile len(to_merge)>1:\n to_merge_next=[]\n offset=0\n while len(to_merge)>0:\n children=to_merge[:2] # Grab the first two (or one)\n to_merge=to_merge[2:]\n merger=DeviceInstance(res,\"m_{}_{}\".format(depth,offset), mergerType, {\"degree\":len(children)})\n res.add_device_instance(merger)\n\n for i in range(len(children)):\n children[i].properties[\"termination_index\"]=i # Give children a unique contiguous index\n ei=EdgeInstance(res,merger,\"termination_in\",children[i],\"termination_out\")\n res.add_edge_instance(ei)\n\n to_merge_next.append(merger)\n offset+=len(children)\n\n to_merge=to_merge_next\n depth+=1\n\nroot=DeviceInstance(res,\"root\", rootType, {\"totalCells\":len(nodes), \"width\":n, \"height\":m, \"max_steps\":max_steps})\nres.add_device_instance(root)\nres.add_edge_instance(EdgeInstance(res, root,\"termination_in\",to_merge[0],\"termination_out\"))\n\n# TODO : use a fanout tree\nif False:\n for d in nodes.values():\n res.add_edge_instance(EdgeInstance(res, d,\"modification_in\",root,\"modification_out\"))\nelse:\n def recurse_fanout(todo,src,srcPin,xBegin,xEnd,yBegin,yEnd, idx):\n # Do it directly for small values\n if len(todo)<=4:\n for d in todo.values():\n res.add_edge_instance(EdgeInstance(res, d,\"modification_in\",src,srcPin))\n return\n\n xR=xEnd-xBegin\n yR=yEnd-yBegin\n\n if xR >= yR:\n split_axis=0\n split_value=(xBegin+xEnd)//2\n decision=lambda x,y: 0 if x<split_value else 1\n else:\n split_axis=1\n split_value=(yBegin+yEnd)//2\n decision=lambda x,y: 0 if y<split_value else 1\n\n left={ (x,y):d for ((x,y),d) in todo.items() if decision(x,y)==0 }\n right={ (x,y):d for ((x,y),d) in todo.items() if decision(x,y)==1 }\n\n dev=DeviceInstance(res, \"f_{}\".format(idx), fanoutType, {\"split_axis\":split_axis,\"split_val\":split_value})\n res.add_device_instance(dev)\n res.add_edge_instance(EdgeInstance(res, dev,\"modification_in\", src,srcPin))\n\n if xR >= yR:\n recurse_fanout(left, dev, \"modification_out_left\", xBegin, split_value, yBegin, yEnd, idx*2)\n recurse_fanout(right, dev,\"modification_out_right\", split_value, xEnd, yBegin, yEnd, idx*2+1)\n else:\n recurse_fanout(left, dev, \"modification_out_left\",xBegin, xEnd, yBegin, split_value, idx*2)\n recurse_fanout(right, dev, \"modification_out_right\",xBegin, xEnd, split_value, yEnd, idx*2+1)\n\n recurse_fanout(nodes,root,\"modification_out\", 0, n, 0, m, 1)\n\n \n\nsave_graph(res,sys.stdout) \n","sub_path":"graph_schema-4.2.0/apps/relaxation_heat/create_relaxation_heat_instance.py","file_name":"create_relaxation_heat_instance.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"396314382","text":"from numpy import array, asarray, dot, random, transpose\nfrom scipy import special\n\nclass Network(object):\n\n def __init__(self, iNodes, hNodes, oNodes, lRate):\n self.__inputNodes = iNodes\n self.__hiddenNodes = hNodes\n self.__outputNodes = oNodes\n self.__learningRate = lRate\n\n self.__weightsInputHidden = random.normal(0.0,\n pow(self.__inputNodes, -0.5),\n (self.__hiddenNodes, self.__inputNodes))\n self.__weightsHiddenOutput = random.normal(0.0,\n pow(self.__hiddenNodes, -0.5),\n (self.__outputNodes, self.__hiddenNodes))\n\n self.__activationFunction = lambda x: special.expit(x)\n\n def train(self, inputsList, targetsList):\n inputs = array(asarray(inputsList), ndmin=2).T\n targets = array(asarray(targetsList), ndmin=2).T\n\n hiddenInputs = dot(self.__weightsInputHidden, inputs)\n hiddenOutputs = self.__activationFunction(hiddenInputs)\n\n finalInputs = dot(self.__weightsHiddenOutput, hiddenOutputs)\n finalOutputs = self.__activationFunction(finalInputs)\n\n outputsErrors = targets - finalOutputs\n hiddenErrors = dot(self.__weightsHiddenOutput.T, outputsErrors)\n \n self.__weightsHiddenOutput += self.__learningRate * dot(\n (outputsErrors * finalOutputs * (1.0 - finalOutputs)),\n transpose(hiddenOutputs))\n\n def query(self, inputsList):\n inputs = array(asarray(inputsList), ndmin=2).T\n hiddenInputs = dot(self.__weightsInputHidden, inputs)\n\n hiddenOutputs = self.__activationFunction(hiddenInputs)\n finalInputs = dot(self.__weightsHiddenOutput, hiddenOutputs)\n\n return self.__activationFunction(finalInputs)\n","sub_path":"farm/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"1571691","text":"import rpy2\nfrom rpy2.robjects import r\nfrom rpy2.robjects.vectors import StrVector, FloatVector\nfrom rnama import aws_lambda\nfrom rnama.get_data import get_userfile, get_geopart, get_clusters, pluck\nfrom rnama.upload_data import upload_userfiles, update_search\nfrom rnama.parallel import parallel_action\nimport json\nimport os\nimport ast\n\nenv = os.environ.get(\"PYTHON_ENV\")\n\n\ndef search_parallel(args):\n \"\"\"Top level search function. Calls invoke_search for each geo_part.\"\"\"\n\n # split geoparts into 22 sublists (number of lambdas to call)\n r('suppressWarnings(suppressMessages(library(rnama)))')\n geoparts = list(r('data(geoparts); geoparts'))\n\n geopartsl = [{'geoparts': geoparts[i::22], 'i': i} for i in xrange(22)]\n\n if env != \"production\":\n geopartsl = [{'geoparts': ['test_part0.csv',\n 'test_part11.csv', 'test_part13.csv'], 'i': 1}]\n\n result_files = parallel_action(geopartsl, args, invoke_search)\n\n # parse lists of results\n r('sims <- c()')\n for result_file in result_files:\n with open(result_file) as json_file:\n search_result = json.load(json_file)\n # pull out similarities and contrasts from json\n r.assign('sim', FloatVector(search_result['similarities']))\n r.assign('con', StrVector(search_result['contrasts']))\n\n # join up\n r('names(sim) <- con')\n r('sims <- c(sims, sim)')\n\n # get top test groups for CMAP02 and L1000 (for cluster queries)\n r('top_cmap <- get_tests(get_dsims(\"CMAP02\", sims, \"top\"), \"CMAP02\")')\n r('top_l1000 <- get_tests(get_dsims(\"L1000\", sims, \"top\"), \"L1000\")')\n top_cmap = list(r('top_cmap'))\n top_l1000 = list(r('top_l1000'))\n\n # get CMAP02/L1000 titles with the same drug as top predicted groups\n r('cmap_titles <- get_top_titles(\"CMAP02\", top_cmap)')\n r('l1000_titles <- get_top_titles(\"L1000\", top_l1000)')\n\n print(\"cmap_titles:\")\n r('print(cmap_titles[1:5])')\n\n # destructure args\n anal_name, source_hash, user_id, source, auth = pluck(\n args, 'selectedAnal', 'sourceHash', 'userId', 'selectedSearchSource', 'auth')\n\n # get other cluster nodes for cmap and l1000\n r.assign('include_cmap', StrVector(get_clusters('CMAP02', top_cmap, auth)))\n r.assign('include_l1000', StrVector(\n get_clusters('L1000', top_l1000, auth)))\n\n # limit to results in first 25 studies/CMAP02 drugs/L1000 drugs, and other drug cluster nodes\n r('sims <- limit_nstudy(sims, include_cmap, cmap_titles, include_l1000, l1000_titles)')\n r('searches <- get_searches(sims, top_cmap, cmap_titles, top_l1000, l1000_titles)')\n\n # save to disc, update dynamodb, and upload search result to s3\n r.assign('anal_name', anal_name)\n r.assign('source', source)\n r.assign('source_hash', source_hash)\n top_study = r('save_searches(searches, anal_name, source)')\n top_study = list(top_study)[0] # r vector to python string\n\n studies = list(r('names(searches)'))\n sources = ['{}-{}'.format(source, study) for study in studies]\n\n upload_userfiles(sources, anal_name, user_id, 'search.json')\n update_search(source, studies, top_study, top_cmap,\n top_l1000, source_hash, anal_name, user_id)\n\n # return final result to search_handler\n return {'top_study': top_study, 'cmap': top_cmap, 'l1000': top_l1000, 'studies': studies}\n\n\ndef invoke_search(args, conn):\n \"\"\"Invokes a lambda that calls search_geopart.\"\"\"\n FunctionName = 'search_geopart'\n\n if env == \"production\":\n FunctionName = 'rnama-rpy2-production-search_geopart'\n\n search_result = aws_lambda.client.invoke(\n InvocationType='RequestResponse',\n FunctionName=FunctionName,\n Payload=json.dumps(args)\n )\n\n if env == \"production\":\n search_result = ast.literal_eval(search_result['Payload'].read())\n else:\n search_result = json.loads(search_result)\n\n # save results to disc\n file_path = '/tmp/geoparts{}.txt'.format(args['i'])\n with open(file_path, 'w') as outfile:\n json.dump(search_result, outfile)\n\n # send results back to search_parallel as list\n conn.send([file_path])\n conn.close()\n\n\ndef search_geopart(geoparts, source, source_studies, anal_name, user_id):\n \"\"\"\n Performs the actualy search for a given geopart.\n\n :param list geoparts: List of geopart files to search.\n :param str source: Query source (e.g. 'all').\n :param str anal_name: Analysis name to run search against.\n :param str user_id: Analysis user to run search against.\n \"\"\"\n\n r('suppressWarnings(suppressMessages(library(rnama)))')\n\n # download top 200 dprimes from analysis\n dprimes_path = get_userfile(\n source, anal_name, user_id, 'dprimes.rds')\n\n # determine columns from geopart to download\n r.assign('dprimes_path', dprimes_path)\n r('dprimes <- readRDS(dprimes_path)')\n cols = {'cols': list(r('names(dprimes)')),\n 'colnums': [int(x) for x in r('get_colnums(dprimes)')]}\n\n # download geopart files in parallel\n geoparts = [{'geopart': geopart} for geopart in geoparts]\n geopart_paths = parallel_action(geoparts, cols, get_geopart)\n\n r.assign('geopart_paths', StrVector(geopart_paths))\n r.assign('source_studies', StrVector(source_studies))\n\n r('sims <- run_search(dprimes, geopart_paths, source_studies)')\n\n # extract contrasts and similarity values\n cons = list(r('names(sims)'))\n sims = list(r('sims'))\n\n # returns to search_worker\n return {'contrasts': cons, 'similarities': sims}\n","sub_path":"rpy2/python/rnama/rnama/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"221938958","text":"\"\"\" Biosignal autoencoder practice\r\n \r\n KOSOMBE 2019 Summer School of Biomedical Engineering\r\n Deep learning based signal processing: autoencoders & recurrent neural networks\r\n\r\n Author: Joonnyong Lee (Seoul National University Hospital, Biomedical Research Institute)\r\n Date: 2019-8-24\r\n\"\"\"\r\n\r\n# ----------------------------------------------------- setup -------------------------------------------------------- #\r\n# import all the necessary libaries\r\nfrom random import shuffle\r\nimport glob\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow.contrib import rnn\r\nimport os\r\nimport matplotlib.pyplot as plt\r\n\r\n# Set paths for tensorboard and checkpoints\r\nFILEWRITER_PATH = './RAE_tensorboard'\r\nif not os.path.isdir(FILEWRITER_PATH):\r\n os.makedirs(FILEWRITER_PATH)\r\nCHECKPOINT_PATH = './RAE_tensorboard/checkpoints'\r\nif not os.path.isdir(CHECKPOINT_PATH):\r\n os.makedirs(CHECKPOINT_PATH)\r\n\r\n# Set path for folder containing the dataset\r\ndata_path = glob.glob('C:/Users/Joon/PycharmProjects/PPG_denoising/PPG_1000samples.txt')\r\n\r\n# Autoencoder parameters\r\nsignal_length = 250\r\nnum_hidden_nodes = 40\r\n\r\n# Training Parameters\r\nbatch_size = 10000\r\nval_batch_size = 10000\r\n\r\n# ------------------------------------------------- loading data ----------------------------------------------------- #\r\n# define function to load the data\r\ndef load_data(data_path, signal_length):\r\n\r\n # load the dataset\r\n data = np.loadtxt(data_path)\r\n\r\n # shuffle the order of the samples in the dataset\r\n shuffle(data)\r\n\r\n # create a list to reorganize the data into segments of None x signal_length shape\r\n # the original data is in None x 1000 shape\r\n new_data = []\r\n for datanum in range(len(data)):\r\n for index in range(0, 750, 50):\r\n a = data[datanum, index:index + signal_length].copy()\r\n a = a - np.min(a) # normalize the samples\r\n a = a / np.max(a)\r\n if np.sum(np.isfinite(a)) == signal_length: # make sure all the data in the sample are finite\r\n new_data.append(a)\r\n data = np.asarray(new_data)\r\n answer_data = data.copy()\r\n\r\n # #실습8: dataset에 노이즈를 추가해서 denoising autoencoder를 학습시키세요============================================\r\n # noisy_data = []\r\n # answer_data = []\r\n # for datanum in range(len(data)):\r\n # dummy = data[datanum, :].copy()\r\n # # 노이즈1: 고주파\r\n # noise1 =\r\n # dummy = dummy + noise1\r\n # dummy = dummy - min(dummy)\r\n # dummy = dummy / max(dummy)\r\n #\r\n # # 노이즈2: 저주파\r\n # noise2 =\r\n # for i in range(len(dummy)):\r\n # dummy[i] =\r\n # dummy = dummy - min(dummy)\r\n # dummy = dummy / max(dummy)\r\n #\r\n # # 노이즈3: saturation\r\n # location1 =\r\n # location2 =\r\n # if location2 > signal_length:\r\n # location2 = signal_length\r\n # dummy[location1:location2] =\r\n #\r\n # noisy_data.append(dummy)\r\n # answer_data.append(data[datanum, :])\r\n #\r\n # data = np.asarray(noisy_data)\r\n # answer_data = np.asarray(answer_data)\r\n\r\n # create empty lists for training and validation data\r\n train_input_data_list = []\r\n train_output_data_list = []\r\n val_input_data_list = []\r\n val_output_data_list = []\r\n\r\n # go through the entire dataset and allocate 80% to training and 20% to validation\r\n for datanum in range(len(data)):\r\n if datanum < 0.8*len(data):\r\n train_input_data_list.append(data[datanum])\r\n train_output_data_list.append(answer_data[datanum])\r\n else:\r\n val_input_data_list.append(data[datanum])\r\n val_output_data_list.append(answer_data[datanum])\r\n\r\n return train_output_data_list, train_input_data_list, val_output_data_list, val_input_data_list\r\n\r\n\r\n# load the data into training and validation sets\r\n[train_output, train_input, val_output, val_input] = load_data(data_path[0], signal_length)\r\n\r\nprint('data loading completed! %i training data and %i validation data' % (len(train_input), len(val_input)))\r\n\r\n# ------------------------------------ defining graph input and network structure ------------------------------------ #\r\n\r\n# 실습9: autoencoder를 recurrent autoencoder로 변경해보세요 ===========================================================\r\n\r\nprint(np.shape(train_input))\r\ntrain_input = np.reshape(train_input, [len(train_input), signal_length, 1])\r\nprint(np.shape(train_input))\r\nval_input = np.reshape(val_input, [len(val_input), signal_length, 1])\r\nprob = tf.placeholder_with_default(1.0, shape=())\r\nX = tf.placeholder(\"float\", [None, signal_length, 1])\r\nY = tf.placeholder(\"float\", [None, signal_length])\r\n\r\ndef RAE(x, probability, num_hidden_nodes):\r\n # Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)\r\n # before unstacking shape = batch_size, timesteps, num_input\r\n x = tf.unstack(tf.transpose(x, perm=[1, 0, 2]))\r\n # x = tf.unstack(x, signal_length, 1)\r\n # after unstacking shape = timesteps, batch_size, num_input\r\n\r\n lstm_fw_cell = rnn.LSTMCell(num_hidden_nodes, forget_bias=1.0)\r\n lstm_fw_cell = rnn.DropoutWrapper(cell=lstm_fw_cell, output_keep_prob=probability)\r\n\r\n outputs, _ = rnn.static_rnn(lstm_fw_cell, x, dtype=tf.float32)\r\n print(outputs[-1].get_shape())\r\n\r\n # Linear activation, using rnn inner loop last output\r\n logit = tf.layers.dense(outputs[-1], signal_length, activation=None,\r\n use_bias=True, name='output_layer',\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\r\n bias_initializer=tf.ones_initializer())\r\n print(logit.get_shape())\r\n\r\n return logit\r\n\r\n# define 'prediction' as the output of the autoencoder\r\nprediction = RAE(X, prob, num_hidden_nodes)\r\n\r\n# define 'loss' as L2 loss function\r\nloss = tf.losses.mean_squared_error(Y, prediction)\r\n\r\n# define optimizer\r\noptimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)\r\n\r\n# Initialize the variables (i.e. assign their default value)\r\ninit = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\r\n# calculate total batch size based on size of train and validation sets\r\ntotal_batch = len(train_input) // batch_size\r\ntotal_val_batch = len(val_input) // val_batch_size\r\n# ---------------------------------------------------- session ------------------------------------------------------- #\r\nwith tf.Session() as sess:\r\n # run the initializer\r\n sess.run(init)\r\n # Writer\r\n writer = tf.summary.FileWriter(FILEWRITER_PATH)\r\n # Saver\r\n saver = tf.train.Saver(max_to_keep=200)\r\n # restore checkpoint ==============================================================================================\r\n latest_ckpt = tf.train.latest_checkpoint(CHECKPOINT_PATH)\r\n print(\"loading the lastest checkpoint: \" + latest_ckpt)\r\n saver.restore(sess, latest_ckpt)\r\n\r\n # pick a goal for the loss value\r\n val_loss_epochs = []\r\n val_loss = 0\r\n # set a for-loop to go through the validation set\r\n for j in range(total_val_batch):\r\n\r\n batch_index1 = j * val_batch_size\r\n\r\n val_batch = val_input[batch_index1:batch_index1 + val_batch_size]\r\n val_label = val_output[batch_index1:batch_index1 + val_batch_size]\r\n\r\n loss2, output_val = sess.run([loss, prediction], feed_dict={X: val_batch, Y: val_label})\r\n val_loss += loss2 / total_val_batch\r\n\r\n val_loss_epochs.append(val_loss)\r\n\r\n output_val = sess.run(prediction, feed_dict={X: val_batch, Y: val_label})\r\n random_index = np.random.randint(0, len(val_batch))\r\n figure = plt.figure(figsize=(14, 6))\r\n plt.subplot(1, 2, 1)\r\n plt.plot(output_val[random_index], color='g')\r\n plt.plot(val_label[random_index], color='b')\r\n plt.plot(val_batch[random_index], color='k')\r\n plt.xlabel('samples')\r\n plt.ylabel('PPG')\r\n\r\n val_loss_plot = np.asarray(val_loss_epochs)\r\n plt.subplot(1, 2, 2)\r\n plt.plot(val_loss_plot, color='b')\r\n plt.savefig('PPG_RAE_result_example_'+str(signal_length)+'samples_'+str(num_hidden_nodes)+'.png')\r\n\r\n sess.close()","sub_path":"RAE_apply.py","file_name":"RAE_apply.py","file_ext":"py","file_size_in_byte":8216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"247842121","text":"# Author-Autodesk Inc.\n# Description-This is sample of opening files from web page.\n\nimport adsk.core\nimport adsk.fusion\nimport adsk.cam\nimport traceback\nfrom .scripts import gost8328_75\n\ncommandDefinition = None\ntoolbarControl = None\nsampleHTMLFileName = 'Sample.html'\n\n# global set of event handlers to keep them referenced for the duration of the command\nhandlers = []\n\n# def formatMsg(args):\n# webArgs = adsk.core.WebRequestEventArgs.cast(args)\n# msg = 'isCanceled: ' + str(webArgs.isCanceled) + '\\n'\n# msg += 'file: ' + str(webArgs.file) + '\\n'\n# msg += 'properties: ' + str(webArgs.properties) + '\\n'\n# msg += 'id: ' + str(webArgs.id) + '\\n'\n# msg += 'privateInfo: ' + str(webArgs.privateInfo) + '\\n'\n\n# if webArgs.occurrenceOrDocument:\n# doc = adsk.core.Document.cast(webArgs.occurrenceOrDocument)\n# if doc:\n# msg += 'document: ' + str(doc.name) + '\\n'\n# else:\n# occ = adsk.fusion.Occurrence.cast(webArgs.occurrenceOrDocument)\n# msg += 'occurrence: ' + str(occ.fullPathName) + '\\n'\n\n# return msg\n\n\ndef formatMsg(args):\n webArgs = adsk.core.WebRequestEventArgs.cast(args)\n Description = str(webArgs.privateInfo)\n # Description.split(\"Description\\\".\\\"\")[1]\n return Description\n\n\nclass OpenFromWebExecutedEventHandler(adsk.core.CommandEventHandler):\n def __init__(self):\n super().__init__()\n\n def notify(self, args):\n ui = None\n try:\n app = adsk.core.Application.get()\n ui = app.userInterface\n\n import webbrowser\n import os\n # sampleHTMLFilePath = 'file:///' + os.path.join(os.path.dirname(os.path.realpath(__file__)), sampleHTMLFileName)\n webbrowser.open(\"http://localhost:4200/\")\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\nclass OpenFromWebCreatedEventHandler(adsk.core.CommandCreatedEventHandler):\n def __init__(self):\n super().__init__()\n\n def notify(self, args):\n ui = None\n try:\n app = adsk.core.Application.get()\n ui = app.userInterface\n\n # Connect to the command executed event.\n cmd = args.command\n onExecute = OpenFromWebExecutedEventHandler()\n cmd.execute.add(onExecute)\n handlers.append(onExecute)\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\n# class InsertingFromURLEventHandler(adsk.core.WebRequestEventHandler):\n# def __init__(self):\n# super().__init__()\n\n# def notify(self, args):\n# ui = None\n# try:\n# app = adsk.core.Application.get()\n# ui = app.userInterface\n\n# # temp.bearing20001(app.activeProduct)\n\n# # args.isCanceled = True\n# msg = \"The InsertingFromURL event is fired.\\n\\n\"\n# msg += formatMsg(args)\n# # ui.messageBox(msg)\n\n# except:\n# if ui:\n# ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\nclass InsertedFromURLEventHandler(adsk.core.WebRequestEventHandler):\n def __init__(self):\n super().__init__()\n\n def notify(self, args):\n ui = None\n try:\n app = adsk.core.Application.get()\n ui = app.userInterface\n design = app.activeProduct\n rootComp = design.rootComponent\n occurence = rootComp.occurrences.item(rootComp.occurrences.count-1)\n\n Description = formatMsg(args)\n gost8328_75.run(occurence,Description)\n ui.messageBox(Description)\n\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\n# class OpeningFromURLEventHandler(adsk.core.WebRequestEventHandler):\n# def __init__(self):\n# super().__init__()\n\n# def notify(self, args):\n# ui = None\n# try:\n# app = adsk.core.Application.get()\n# ui = app.userInterface\n\n# # temp.bearing20001(app.activeProduct)\n\n# # args.isCanceled = True\n# msg = \"The OpeningFromURL event is fired.\\n\\n\"\n# msg += formatMsg(args)\n# ui.messageBox(msg)\n\n# except:\n# if ui:\n# ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\n# class OpenedFromURLEventHandler(adsk.core.WebRequestEventHandler):\n# def __init__(self):\n# super().__init__()\n\n# def notify(self, args):\n# ui = None\n# try:\n# app = adsk.core.Application.get()\n# ui = app.userInterface\n# design = app.activeProduct\n# rootComp = design.rootComponent\n# occurence = rootComp.occurrences.item(rootComp.occurrences.count-1)\n# parametres = occurence.component.parentDesign.allParameters\n\n# msg = \"The OpenedFromURL event is fired.\\n\\n\"\n# msg += formatMsg(args)\n# ui.messageBox(msg)\n\n# except:\n# if ui:\n# ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\ndef run(context):\n ui = None\n try:\n commandId = 'OpenFileFromWebCommandIdPy'\n commandName = 'Open Files from a Web Page'\n commandDescription = 'This is a sample of opening files from web page.'\n panelId = 'SolidScriptsAddinsPanel'\n\n app = adsk.core.Application.get()\n ui = app.userInterface\n\n # create the command definition\n commandDefinition = ui.commandDefinitions.itemById(commandId)\n # delete any existing command definition, and just recreate it\n if commandDefinition:\n commandDefinition.deleteMe()\n commandDefinition = ui.commandDefinitions.addButtonDefinition(\n commandId, commandName, commandDescription)\n onCommandCreated = OpenFromWebCreatedEventHandler()\n commandDefinition.commandCreated.add(onCommandCreated)\n # keep the handler referenced beyond this function\n handlers.append(onCommandCreated)\n\n # insert the command into the model:add-ins toolbar\n toolbarControls = ui.allToolbarPanels.itemById(panelId).controls\n # delete any existing control, and just recreate it\n global toolbarControl\n toolbarControl = toolbarControls.itemById(commandId)\n if toolbarControl:\n toolbarControl.deleteMe()\n toolbarControl = toolbarControls.addCommand(commandDefinition)\n\n # onInsertingFromURL = InsertingFromURLEventHandler()\n # app.insertingFromURL.add(onInsertingFromURL)\n # handlers.append(onInsertingFromURL)\n\n onInsertedFromURL = InsertedFromURLEventHandler()\n app.insertedFromURL.add(onInsertedFromURL)\n handlers.append(onInsertedFromURL)\n\n # onOpeningFromURL = OpeningFromURLEventHandler()\n # app.openingFromURL.add(onOpeningFromURL)\n # handlers.append(onOpeningFromURL)\n\n # onOpenedFromURL = OpenedFromURLEventHandler()\n # app.openedFromURL.add(onOpenedFromURL)\n # handlers.append(onOpenedFromURL)\n\n # ui.messageBox(\"The command is added to MODEL:ADD-INS panel.\")\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n\ndef stop(context):\n ui = None\n try:\n global commandDefinition\n if commandDefinition:\n commandDefinition.deleteMe()\n commandDefinition = None\n global toolbarControl\n if toolbarControl:\n toolbarControl.deleteMe()\n toolbarControl = None\n\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n","sub_path":"_OpenFileFromWeb/OpenFileFromWeb.py","file_name":"OpenFileFromWeb.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395213453","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n__author__ = \"MPZinke\"\n\n###########################################################################\n#\n#\tcreated by: MPZinke\n#\ton ..\n#\n#\tDESCRIPTION:\n#\tBUGS:\n#\tFUTURE:\n#\n###########################################################################\n\n\nfrom Adafruit_IO import MQTTClient\nfrom time import sleep, time\nfrom threading import Thread\n\nfrom Definitions import *\nimport DBFunctions\nimport ErrorWriter\n\n# —————————————————— UTILITY ——————————————————–\n\ndef steps_to_take(cursor, event_position):\n\ttotal_steps = DBFunctions.curtain_length(cursor)\n\tevent_position_steps = total_steps * event_position / 100\n\treturn DBFunctions.current_position() - event_position_steps\n\n\n# —————————————— ADAFRUIT CLIENT —————————————————\n\ndef connect_to_feeds(client):\n\tfor feed in [OPEN_KEY, CLOSE_KEY]:\n\t\tclient.subscribe(feed)\n\n\ndef disconnect(client):\n\traise Exception(\"MQTTClient disconnected\")\n\n\ndef feed_actions(client, feed_id, payload):\n\tfrom datetime import datetime\n\n\tcnx, cursor = DBFunctions.connect_to_DB()\n\n\ttry: curtain = int(payload)\n\texcept: return\n\tif feed_id == OPEN_KEY:\n\t\tDBFunctions.full_open_immediate_event(cnx, cursor, curtain)\n\telif feed_id == CLOSE_KEY:\n\t\tDBFunctions.close_immediate_event(cnx, cursor, curtain)\n\n\tcnx.close()\n\n\ndef active_feed(client):\n\tclient.connect()\n\tclient.loop_blocking()\n\n\ndef feed_loop(client):\n\twhile True:\n\t\tcnx, cursor = DBFunctions.connect_to_DB()\n\n\t\tfor curtain in DBFunctions.curtain_ids(cursor):\n\t\t\tfeed_option_is_selected = DBFunctions.adafruit_feed(cursor, curtain) \n\t\t\tif feed_option_is_selected and not client.is_connected():\n\t\t\t\tthread = Thread(target=activate_feed, args=(client,))\n\t\t\t\tthread.start()\n\t\t\t\tthread.join()\n\t\t\telif not feed_option_is_selected and client.is_connected():\n\t\t\t\tclient.disconnect()\n\n\t\tcnx.close()\n\t\tsleep(FEED_CLIENT_CHECK_LOOP)\n\n\ndef start_client_loop():\n\tclient = MQTTClient(USER_FEED_NAME, USER_FEED_KEY)\n\n\tclient.on_connect = connect_to_feeds\n\tclient.on_disconnect = disconnect\n\tclient.on_message = feed_actions\n\n\tfeed_loop(client)\n","sub_path":"DatabasePortal/Python/AdafruitFeed.py","file_name":"AdafruitFeed.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"104433220","text":"T = int(input())\nfor t in range(1, T+1):\n N, M = map(int, input().split())\n raw = list(map(int, input().split()))\n chz = [[raw[i], i+1] for i in range(len(raw))]\n pot = chz[:N]\n rest = chz[N:]\n \n idx = 0\n while rest:\n for i in range(len(pot)):\n pot[i][0] //= 2\n if pot[i][0] == 0: \n pot.pop(i)\n pot.insert(i, rest.pop(0))\n idx = i\n if not rest: break\n \n idx = (idx + 1) % len(pot)\n while len(pot) != 1:\n pot[idx][0] //= 2\n if pot[idx][0] == 0:\n if idx == len(pot) - 1:\n pot.pop(idx)\n idx = 0\n else:\n pot.pop(idx)\n else:\n idx = (idx + 1) % len(pot)\n \n print('#{0} {1}'.format(t, pot.pop()[1]))\n\n # while len(rest) != 1:\n","sub_path":"python/swea/intermediate/Queue_3.py","file_name":"Queue_3.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"10919173","text":"# 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tempfile\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom shaker.engine import config\nfrom shaker.engine import image_builder\nfrom shaker.engine import server\nfrom shaker.engine import utils\n\nLOG = logging.getLogger(__name__)\n\n\ndef main():\n utils.init_config_and_logging(\n config.COMMON_OPTS + config.OPENSTACK_OPTS + config.SERVER_OPTS +\n config.REPORT_OPTS + config.IMAGE_BUILDER_OPTS + config.CLEANUP_OPTS,\n use_stderr=True\n )\n\n artifacts_dir = cfg.CONF.artifacts_dir\n if not artifacts_dir:\n artifacts_dir = tempfile.mkdtemp(prefix='shaker')\n cfg.CONF.set_override('artifacts_dir', artifacts_dir)\n\n # image-builder\n LOG.info('Building the image')\n image_builder.build_image()\n\n # core\n if len(cfg.CONF.scenario) > 1:\n cfg.CONF.set_override(\n 'output', utils.join_folder_prefix_ext(\n artifacts_dir, 'aggregated', 'json'))\n cfg.CONF.set_override(\n 'report', utils.join_folder_prefix_ext(\n artifacts_dir, 'aggregated', 'html'))\n cfg.CONF.set_override(\n 'subunit', utils.join_folder_prefix_ext(\n artifacts_dir, 'aggregated', 'subunit'))\n cfg.CONF.set_override(\n 'book', utils.join_folder_prefix_ext(artifacts_dir, 'aggregated'))\n\n LOG.info('Executing scenario(s)')\n server.act()\n\n # cleanup\n LOG.info('Cleaning up')\n image_builder.cleanup()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"shaker/engine/all_in_one.py","file_name":"all_in_one.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"244031036","text":"import torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nimport numpy as np\nimport json\nfrom PIL import Image\nimport download\nfrom tqdm import tqdm\nfrom multiprocessing import Pool\nimport cv2\n\ndef get_image_channels(image):\n shape_length = len(image.shape)\n if shape_length == 2:\n return 1\n else:\n return image.shape[2]\n\ndef process_image(data):\n song = data[\"song\"]\n gray = data[\"gray\"]\n size = data[\"shape\"]\n data_path = data[\"path\"]\n index = data[\"i\"]\n\n image_file_name = \"{}.wikiart\".format(song[\"id\"])\n image_path = \"{}/raw_images/{}\".format(data_path, image_file_name)\n image = cv2.imread(image_path)\n image_channels = get_image_channels(image)\n\n if gray == False:\n # Not converting to gray\n # Identify non rgb images and convert them to rgb\n if image_channels == 1:\n # Image is grayscale, convert to rgb\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n elif image_channels == 4:\n # Image is rgba remove the alpha channel\n image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGR)\n else:\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n else:\n # Convert all images to grayscale\n if image_channels != 1:\n if image_channels == 4:\n image = cv2.cvtColor(image, cv2.COLOR_RGBA2GRAY)\n else:\n image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n resize = cv2.resize(image, size, interpolation = cv2.INTER_AREA)\n pil_image = Image.fromarray(np.uint8(resize))\n tensor = transforms.ToTensor()(pil_image)\n return tensor\n\nclass PaintPoseDatset(Dataset):\n def __init__(self, data_path, gray=False, image_shape=(28, 28), verbose=True):\n self.gray = gray\n self.image_shape = image_shape\n self.verbose = verbose\n\n if verbose:\n print(\"Downloading WikiArt Images\")\n # Download image dataset if needed\n download.retrieve_images()\n if verbose:\n print(\"Download Complete\")\n print(\"Loading Paintpose from storage...\")\n # Get the encoded song files\n encoded_songs_file_name = \"encoded_songs.json\"\n encoded_songs_file_path = \"{}/{}\".format(data_path, encoded_songs_file_name)\n encoded_songs_input = open(encoded_songs_file_path, \"r\")\n encoded_songs_file_text = encoded_songs_input.read()\n encoded_songs_input.close()\n\n encoded_songs = json.loads(encoded_songs_file_text)\n processing_list = []\n for i in range(len(encoded_songs)):\n song = encoded_songs[i]\n processing_list.append({\"path\": data_path, \n \"song\": song,\n \"gray\": self.gray,\n \"shape\": self.image_shape,\n \"i\": i})\n \n pbar = tqdm(total=len(encoded_songs))\n self.data = []\n for i in range(len(encoded_songs)):\n result = process_image(processing_list[i])\n self.data.append(result)\n pbar.update()\n \"\"\"\n pool = Pool(processes=25)\n \n for i, result in enumerate(pool.imap_unordered(process_image, processing_list)):\n pbar.update()\n self.data.append(result)\n pbar.close()\n pool.close()\n pool.join()\n \"\"\"\n print(\"Loaded Paintpose!\")\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n image = self.data[idx]\n return image","sub_path":"src/tofu/train/paintpose.py","file_name":"paintpose.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"160346448","text":"import socket\nfrom pykeyboard import PyKeyboard\nfrom pymouse import PyMouse\n\ndef main():\n # 1.创建套接字socket\n keyboard=PyKeyboard()\n\n tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # 2.连接服务器\n #dest_ip = input(\"请输入服务器ip:\")\n #dest_port = int(input(\"请输入服务器port:\"))\n #dest_addr = (dest_ip, dest_port)\n #dest_addr = ('172.17.130.107', 8866)\n\n dest_addr = ('192.168.3.100', 8668)\n tcp_socket.connect(dest_addr)\n\n\n # send_data = input(\"请输入要发送的数据:\")\n # send_data = send_data + '\\r'\n # tcp_socket.send(send_data.encode('utf-8'))\n\n for i in range(5000):\n # 3. 接收/发送数据\n # 接收服务器发送的数据\n recv_data = tcp_socket.recv(10240)\n\n recv_data=recv_data[1:].decode('GB2312')\n recv_data=recv_data.replace('\\r\\n','')\n print('读到:',recv_data,len(recv_data.replace('\\r\\n','')))\n\n\n if len(recv_data)==13:\n keyboard.type_string(recv_data)\n\n\n\n #tcp_socket.send('BCLR\\r'.encode('utf-8'))\n\n if len(recv_data)!=100:\n print('顺序',i)\n tcp_socket.send('BCLR\\r'.encode('GB2312'))\n print('清除',tcp_socket.recv(10240).decode('GB2312'))\n\n\n # 4. 关闭套接字socket\n # if send_data=='close':\n #\n # tcp_socket.close()\n # return\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Tcp_Client.py","file_name":"Tcp_Client.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"270381175","text":"from PIL import Image\nimport os\nfrom .logger import Logger\n\n\nclass Resizer:\n def __init__(self,\n output_directory: str = None,\n max_width: int = None,\n max_height: int = None,\n logger: Logger = None):\n self.max_width: int or None = max_width\n self.max_height: int or None = max_height\n self.output_directory: str = output_directory\n self.logger: Logger = logger\n if output_directory is not None:\n if not os.path.exists(output_directory):\n os.mkdir(output_directory)\n\n def resize(self, path: str, max_width: int = None, max_height: int = None) -> str:\n if not os.path.exists(path):\n raise RuntimeError('File not found!')\n if self.output_directory is not None:\n output_path: str = f'{self.output_directory}/{os.path.basename(path)}'\n else:\n output_path: str = path\n original_image: Image = Image.open(path)\n w, h = original_image.size\n input_size: int = os.path.getsize(path)\n if max_width or max_height:\n width: int = max_width if max_width else w\n height: int = max_height if max_height else h\n else:\n width: int = self.max_width if self.max_width else w\n height: int = self.max_height if self.max_height else h\n if self.max_height is self.max_width is max_height is max_width is None:\n raise RuntimeError('Width or height required!')\n if w <= width and h <= height:\n width = w\n height = h\n original_image.thumbnail((width, height), Image.ANTIALIAS)\n original_image.save(output_path)\n if self.logger is not None:\n self.logger.resizing_message(path, (h, w), (height, width), input_size, os.path.getsize(output_path))\n return output_path\n","sub_path":"ImageProcessor/resizer.py","file_name":"resizer.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"249248006","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom cart.models import CarModel\nfrom order.models import OrderModel, OrderGoodsModel\nfrom utils.functions import get_order_num\n\n\ndef order(request):\n if request.method == 'GET':\n user = request.user\n carts = CarModel.objects.filter(user=user, is_select=True)\n # 订单号\n o_num = get_order_num()\n order = OrderModel.objects.create(user=user, o_num=o_num)\n for cart in carts:\n OrderGoodsModel.objects.create(order=order, goods=cart.goods, goods_num=cart.c_num)\n # 删除购物车中已经下单的商品信息\n # carts.delete()\n order = OrderModel.objects.filter(user=user, o_num=o_num).first()\n order_info = OrderGoodsModel.objects.filter(order_id=order.id)\n return render(request, 'place_order.html', {'order_info': order_info})\n\n\ndef orderchange(request):\n if request.method == 'POST':\n user = request.user\n carts = CarModel.objects.filter(user=user, is_select=True)\n carts.delete()\n order_id = request.POST.get('order_id')\n order = OrderModel.objects.get(id=order_id)\n order.o_status = 1\n order.save()\n return JsonResponse({'code': 200})\n\n\ndef amountprice(request):\n if request.method == 'GET':\n user = request.user\n orders = OrderModel.objects.filter(user=user, o_status=0)\n price_list = []\n b_list = []\n for order in orders:\n order_infos = OrderGoodsModel.objects.filter(order_id=order.id)\n amount = 0\n\n for order_info in order_infos:\n price = order_info.goods_num * int(order_info.goods.goodsprice)\n amount += price\n data = {\n 'order_id': order_info.id,\n 'price': price\n }\n price_list.append(data)\n b = {\n 'order_id': order.id,\n 'amount': amount\n }\n b_list.append(b)\n return JsonResponse({'b_list': b_list, 'price_list': price_list, 'code': 200})\n\n\ndef price(request):\n if request.method == 'GET':\n user = request.user\n orders = OrderModel.objects.filter(user=user, o_status=1)\n price_list = []\n b_list = []\n for order in orders:\n order_infos = OrderGoodsModel.objects.filter(order_id=order.id)\n amount = 0\n\n for order_info in order_infos:\n price = order_info.goods_num * int(order_info.goods.goodsprice)\n amount += price\n data = {\n 'order_id': order_info.id,\n 'price': price\n }\n price_list.append(data)\n b = {\n 'order_id': order.id,\n 'amount': amount\n }\n b_list.append(b)\n return JsonResponse({'b_list': b_list, 'price_list': price_list, 'code': 200})\n\n\n\n\n","sub_path":"fruitshop/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"613868868","text":"# python abundant.py\n\nfrom divisors import find\n\nL, s = 28123, 0\nabn = set()\n\nfor n in range(1, L + 1):\n if find(n, \"sum\") > n:\n abn.add(n)\n\n if not any( (n - a in abn) for a in abn ):\n s += n\n\nprint(s)","sub_path":"abundant.py","file_name":"abundant.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"348497785","text":"from abc import ABC, abstractmethod\nimport parametros as p\nfrom criaturas import Augurey, Niffler, Erkling, str_a_bool\nimport random\n\nclass Magizoologo(ABC):\n def __init__(self, nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad):\n self.nombre = nombre\n self.__sickles = int(sickles)\n self.criaturas = criaturas\n self.alimentos = alimentos\n self.licencia = str_a_bool(licencia)\n self.magia = int(magia)\n self.destreza = int(destreza)\n self.energia_total = int(energia)\n self.__energia = int(energia)\n self.responsabilidad = int(responsabilidad)\n self.habilidad = str_a_bool(habilidad)\n self.aprobacion = 0\n self.copia_energia = 0\n self.copia_sickles = 0\n self.criatura_elegida = \"\"\n self.criat_elegida = None\n\n def __str__(self):\n n_tartas = self.alimentos.count(\"Tarta de Melaza\")\n n_higados = self.alimentos.count(\"Hígado de Dragón\")\n n_buñuelos = self.alimentos.count(\"Bueñuelo de Gusarajo\")\n return (f'Nombre: {self.nombre} ({type(self).__name__}) | '\n f'Sickles: {self.sickles} | '\n f'Energia actual: {self.energia} | '\n f'Licencia: {self.licencia} | '\n f'Aprobación: {self.aprobacion} | '\n f'Magia: {self.magia} | '\n f'Destreza: {self.destreza} | '\n f'Habilidad: {self.habilidad} | '\n f'''Responsabilidad: {self.responsabilidad} |\n''' f'''Alimento Cantidad Salud\n''' f'Tarta de Melaza {n_tartas}'\n f''' {p.SALUD_TARTA} \n''' f'Hígado de Dragón {n_higados}'\n f''' {p.SALUD_HIGADO} \n''' f'Bueñuelo de Gusarajo {n_buñuelos:}'\n f' {p.SALUD_BUÑUELO}')\n\n def archivar(self):\n mis_alim = \"\"\n mis_criat = \"\"\n for criat in self.criaturas:\n mis_criat += f\"{criat};\"\n for alim in self.alimentos:\n mis_alim += f\"{alim};\"\n return (f\"{self.nombre},{type(self).__name__},{self.sickles},{mis_criat[:-1]}\"\n f\",{mis_alim[:-1]},{self.licencia},{self.magia},\"\n f\"{self.destreza},{self.energia_total}\"\n f\",{self.responsabilidad},{self.habilidad}\") \n\n @property\n def sickles(self):\n if self.copia_sickles != self.__sickles:\n return self.__sickles\n else:\n self.copia_sickles = -5\n return False\n @sickles.setter\n def sickles(self, cambio_sickles):\n self.copia_sickles = self.__sickles\n if cambio_sickles < 0:\n print(f\"No tienes suficientes sickles\")\n else:\n self.__sickles = cambio_sickles \n \n @property\n def energia(self):\n if self.copia_energia != self.__energia:\n return self.__energia\n else:\n self.copia_energia = -1 #es un valor que nunca va a tener la energia así retorna en las otras la energia y no False\n return False\n @energia.setter\n def energia(self, cambio_energia):\n self.copia_energia = self.__energia\n if cambio_energia > self.energia_total:\n self.__energia = self.energia_total\n elif cambio_energia < 0:\n print(f\"No tienes suficiente energía\")\n else:\n self.__energia = cambio_energia\n \n @abstractmethod\n def alimentar(self):\n p_ataque = 0\n self.energia -= p.ENERGIA_ALIMENTAR\n while self.energia != False:\n if len(self.alimentos) == 0:\n self.energia += 5 \n print(f\"No tienes alimentos, anda al menú DCC para comprar más\")\n return False\n print(f\"Seleccione que criatura quiere alimentar:\")\n iterador = 1\n for nombres in self.criaturas:\n print(f\"[{iterador}] {nombres}\")\n iterador += 1\n criatura_a_alimentar = input()\n if criatura_a_alimentar.isnumeric():\n if int(criatura_a_alimentar) in range(1, len(self.criaturas) + 1):\n iterador = 1\n for nombre_posible in self.criaturas:\n if int(criatura_a_alimentar) == iterador:\n self.criatura_elegida = nombre_posible\n iterador += 1\n self.criat_elegida = self.criaturas[self.criatura_elegida]\n if not self.criat_elegida.fugitiva: \n while True:\n print(f\"Seleccione el alimento que le quiere dar:\")\n for num_alimentos in range(len(self.alimentos)):\n print(f\"[{num_alimentos}] {self.alimentos[num_alimentos]}\")\n alimento_seleccionado = input()\n if alimento_seleccionado.isnumeric():\n if int(alimento_seleccionado) in range(len(self.alimentos)):\n alimento_seleccionado = int(alimento_seleccionado)\n dias_sin_c_copia = self.criat_elegida.dias_sin_comida\n if \"Tarta\" in self.alimentos[alimento_seleccionado]:\n self.criat_elegida.salud_actual += p.SALUD_TARTA\n self.criat_elegida.hambre = \"satisfecha\"\n if type(self.criat_elegida).__name__ == \"Niffler\":\n if random.random() <= 0.15:\n self.criat_elegida.agresividad = \"inofensiva\"\n p_ataque = self.criat_elegida.ataque()\n self.criat_elegida.dias_sin_comida -= dias_sin_c_copia\n elif \"Hígado\" in self.alimentos[alimento_seleccionado]:\n self.criat_elegida.salud_actual += p.SALUD_HIGADO\n self.criat_elegida.enferma = False\n p_ataque = self.criat_elegida.ataque()\n self.criat_elegida.dias_sin_comida -= dias_sin_c_copia\n self.criat_elegida.hambre = \"satisfecha\"\n else:\n if random.random() <= 0.65:\n self.criat_elegida.salud_actual += p.SALUD_BUÑUELO\n self.criat_elegida.hambre = \"satisfecha\"\n self.criat_elegida.dias_sin_comida -= dias_sin_c_copia\n else:\n print(f\"Tu criatura ha rechazado el buñuelo\")\n p_ataque = self.criat_elegida.ataque()\n self.alimentos.pop(alimento_seleccionado)\n if random.random() <= p_ataque:\n energia_ataque = max(10, \\\n self.magia - self.criat_elegida.magia)\n print(f\"Tu mascota te ha atacado\")\n if energia_ataque < self.energia:\n self.energia -= energia_ataque\n self.energia\n else:\n self.energia = 1\n return True\n print(f\"No existe esa opción\")\n print(f\"Esa mascota ha escapado, no puedes darle alimento, vuelves al menú\")\n return True\n print(f\"No existe esa opción\") \n \n @abstractmethod\n def recuperar(self):\n self.energia -= p.ENERGIA_RECUPERAR\n while self.energia != False:\n print(f\"Seleccione que criatura quiere recuperar:\")\n iterador = 1\n for nombres in self.criaturas:\n if self.criaturas[nombres].fugitiva:\n print(f\"[{iterador}] {nombres}\")\n iterador += 1\n if iterador == 1:\n self.energia += 10\n return print(\"No tienes criaturas que recuperar\")\n criatura_recuperar = input()\n if criatura_recuperar.isnumeric():\n if int(criatura_recuperar) in range(1,len(self.criaturas)+1):\n iterador = 1\n for nombre_posible in self.criaturas:\n if self.criaturas[nombre_posible].fugitiva:\n if int(criatura_recuperar) == iterador:\n self.criatura_elegida = nombre_posible\n iterador += 1\n self.criat_elegida = self.criaturas[self.criatura_elegida]\n destreza_magia = self.destreza + self.magia\n magia_criat = self.criat_elegida.magia\n p_esc = min(1, max(0, (destreza_magia - magia_criat)\\\n / (destreza_magia + magia_criat)))\n if random.random() <= p_esc:\n self.criat_elegida.fugitiva = False\n print(\"Tiene su criatura de vuelta\")\n return False\n print(f\"No ha podido recuperar a su criatura\")\n return True\n print(f\"No existe esa opción\") \n return True\n\n def sanar(self):\n self.energia -= p.ENERGIA_SANAR\n while self.energia != False:\n print(f\"Seleccione que criatura quiere sanar:\")\n iterador = 0\n for nombres in self.criaturas:\n if self.criaturas[nombres].enferma and not self.criaturas[nombres].fugitiva:\n print(f\"[{iterador}] {nombres}\")\n iterador += 1\n if iterador == 0:\n self.energia += p.ENERGIA_SANAR\n return print(\"No tienes criaturas enfermas en cautiverio\")\n criatura_sanar = input()\n if criatura_sanar.isnumeric():\n if int(criatura_sanar) in range(len(self.criaturas)):\n iterador = 0\n for nombre_posible in self.criaturas:\n if self.criaturas[nombre_posible].enferma and\\\n not self.criaturas[nombres].fugitiva:\n if int(criatura_sanar) == iterador:\n self.criatura_elegida = nombre_posible\n iterador += 1\n self.criat_elegida = self.criaturas[self.criatura_elegida]\n magia_criatura = self.criat_elegida.magia\n p_sanar = min(1, max(0, (self.magia - magia_criatura)\\\n / (self.magia + magia_criatura)))\n if random.random() <= p_sanar:\n self.criat_elegida.enferma = False\n print(\"Su criatura se ha sanado\")\n return False\n print(f\"No ha podido sanar a su criatura\")\n return True\n print(f\"No existe esa opción\") \n return True\n\n @abstractmethod\n def usar_habilidad(self):\n pass\n\nclass Docencio(Magizoologo):\n def __init__(self, nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad):\n super().__init__(nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad)\n\n def alimentar(self):\n if super().alimentar():\n if self.energia == False:\n return None\n self.criat_elegida.salud_max += p.ALIMENTO_DOCENCIO\n\n def recuperar(self):\n fugitivas = super().recuperar()\n if not fugitivas:\n self.criat_elegida.salud_actual -= 7\n return fugitivas\n \n def usar_habilidad(self):\n if self.habilidad:\n for criaturas in self.criaturas:\n if not self.criaturas[criaturas].fugitiva:\n dias_sin_c = self.criaturas[criaturas].dias_sin_comida\n self.criaturas[criaturas].hambre = \"satisfecha\"\n self.criaturas[criaturas].dias_sin_comida -= dias_sin_c\n print(\"Todas tus criaturas en cautiverio están satisfechas\")\n else:\n print(f\"Ya no puedes ocupar la habilidad\")\n self.habilidad = False\n\nclass Tareo(Magizoologo):\n def __init__(self, nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad):\n super().__init__(nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad)\n \n def alimentar(self):\n if super().alimentar():\n if self.energia == False:\n return None\n if random.random() <= 0.7:\n sal_max = self.criat_elegida.salud_max \n self.criat_elegida.salud_actual += sal_max\n \n def recuperar(self):\n return super().recuperar()\n \n def usar_habilidad(self):\n if self.habilidad:\n for criaturas in self.criaturas:\n if self.criaturas[criaturas].fugitiva:\n self.criaturas[criaturas].fugitiva = False\n print(\"Todas tus criaturas han sido recuperadas\")\n else:\n print(f\"Ya no puedes ocupar la habilidad\") \n self.habilidad = False\n\nclass Hibrido(Magizoologo):\n def __init__(self, nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad):\n super().__init__(nombre, sickles, criaturas, alimentos, licencia,\\\n magia, destreza, energia, responsabilidad, habilidad)\n \n \n def alimentar(self):\n if super().alimentar():\n if self.energia == False:\n return None\n self.criat_elegida.salud_actual += p.ALIMENTO_HIBRIDO\n\n def recuperar(self):\n return super().recuperar()\n \n def usar_habilidad(self):\n if self.habilidad:\n for criaturas in self.criaturas:\n if not self.criaturas[criaturas].fugitiva:\n self.criaturas[criaturas].enferma = False\n print(\"Todas tus criaturas en cautiverio están sanadas\")\n else:\n print(f\"Ya no puedes ocupar la habilidad\")\n self.habilidad = False\n","sub_path":"magizoologos.py","file_name":"magizoologos.py","file_ext":"py","file_size_in_byte":14911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380807501","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom fractions import Fraction\nfrom ._abstract import AbstractScraper\nfrom ._utils import normalize_string\n\n\nclass BudgetBytesv2(AbstractScraper):\n\n @classmethod\n def host(self):\n return 'budgetbytes.com-v2'\n\n def title(self):\n return self.soup.find('h1').get_text()\n\n def total_time(self):\n try:\n prep = self.soup.find(\n 'span',\n {'class': 'wprm-recipe-prep_time-minutes'}\n ).get_text()\n except AttributeError:\n prep = '0'\n try:\n cook = self.soup.find(\n 'span',\n {'class': 'wprm-recipe-cook_time-minutes'}\n ).get_text()\n except AttributeError:\n cook = '0'\n return {prep, cook}\n\n def servings(self):\n try:\n return self.soup.find('span', {'itemprop': 'recipeYield'}).get_text().split(' ', 1)[0]\n except:\n return ''\n\n def ingredients(self):\n ingredients_html = self.soup.findAll('li', {'class': 'wprm-recipe-ingredient'})\n ingredients = []\n\n for ingredient in ingredients_html:\n try:\n ingredient_dict = {\n 'quantity': round(float(sum(Fraction(s) for s in ingredient.find(\n 'span',\n {'class': 'wprm-recipe-ingredient-amount'}\n ).get_text().split())), 3),\n 'measurement': ingredient.find(\n 'span',\n {'class': 'wprm-recipe-ingredient-unit'}\n ).get_text(),\n 'title': ingredient.find(\n 'span',\n {'class': 'wprm-recipe-ingredient-name'}\n ).get_text()\n }\n except AttributeError:\n ingredient_dict = {\n 'title': normalize_string(ingredient.find(\n 'span',\n {'class': 'wprm-recipe-ingredient-name'}\n ).get_text())\n }\n except:\n ingredient_dict = {\n 'title': normalize_string(ingredient.get_text())\n }\n\n ingredients.append(ingredient_dict)\n\n return ingredients\n\n def instructions(self):\n instructions_html = self.soup.findAll('li', {'class': 'wprm-recipe-instruction'})\n\n return [\n normalize_string(instruction.get_text())\n for instruction in instructions_html\n ]\n\n def description(self):\n try:\n li = self.soup.find('article', {'class': 'post'}).findAll('p')\n return li[0].get_text()\n except:\n return ''\n\n def image(self):\n try:\n return self.soup.find('img', {'class': 'alignnone'})[\"src\"]\n except:\n return ''\n","sub_path":"recipe_scrapers/budgetbytesv2.py","file_name":"budgetbytesv2.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"58614687","text":"from Model.Planificadores.CortoPlazo.FCFS import FCFS\r\n\r\n__author__ = 'Martin Alejandro Melo y Marcelo Rubini'\r\n\r\n#Es una cola multinivel que utiliza 3 colas del mismo tipo de planificador\r\n#pero que varia en la cantidad de rafagas que le da a cada proceso.\r\n#Posee envejecimiento.\r\nclass RoundRobin:\r\n\r\n def __init__(self, cantidadQuantum1, cantidadQuantum2):\r\n self.primerQuantum = FCFS()\r\n self.segundoQuantum = FCFS()\r\n self.fifo = FCFS()\r\n\r\n self.cantidadQuantum1 = cantidadQuantum1\r\n self.cantidadQuantum2 = cantidadQuantum2\r\n\r\n self.contador = 0\r\n self.cantidadAgregados = 0\r\n\r\n def agregar(self, pcb , irq=None):\r\n if irq is None:\r\n self.primerQuantum.agregar(pcb)\r\n else:\r\n if irq.getRafagas() == self.cantidadQuantum1:\r\n self.segundoQuantum.agregar(pcb)\r\n if irq.getRafagas() == self.cantidadQuantum2:\r\n self.fifo.agregar(pcb)\r\n self.cantidadAgregados +=1\r\n self.contador +=1\r\n\r\n #retorna el siguiente elemento.\r\n def obtener(self):\r\n self.cantidadAgregados -=1\r\n self.contador+=1\r\n if self.contador.__mod__(4)==0 and (not self.segundoQuantum.estaVacia()):\r\n return self.segundoQuantum.obtener()[0], self.cantidadQuantum2\r\n if self.contador.__mod__(7)==0 and (not self.fifo.estaVacia()):\r\n return self.fifo.obtener()\r\n\r\n if not self.primerQuantum.estaVacia():\r\n return self.primerQuantum.obtener()[0], self.cantidadQuantum1\r\n if not self.segundoQuantum.estaVacia():\r\n return self.segundoQuantum.obtener()[0], self.cantidadQuantum2\r\n if not self.fifo.estaVacia():\r\n return self.fifo.obtener()\r\n\r\n\r\n\r\n #retorna si esta vacio.\r\n def estaVacia(self):\r\n return self.cantidadAgregados == 0","sub_path":"Model/Planificadores/CortoPlazo/RoundRobin.py","file_name":"RoundRobin.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"278013282","text":"from typing import List\n\nfrom myia.game_element.Character import Character\nfrom myia.game_element.Game import Game\nfrom myia.game_element.Path import Path\nfrom myia.game_element.Room import Room\nfrom myia.ia.process.selector.CharacterSelector import CharacterSelector\n\n\nclass GhostCharacterSelector(CharacterSelector):\n\n def __init__(self, game: Game):\n super().__init__(game)\n\n def get_selected_character(self, remaining_characters: List[Character]) -> (Character, List[List[Room]]):\n remaining_characters_out_dark_room: List[Character] = super() \\\n .get_remaining_characters_out_dark_room(remaining_characters, self.game)\n remaining_characters_in_group: List[Character] = super() \\\n .get_remaining_characters_in_group(remaining_characters, self.game)\n\n if len(remaining_characters_out_dark_room) > 0:\n return self.__find_most_efficient_move(remaining_characters_out_dark_room)\n elif len(remaining_characters_in_group) > 0:\n return self.__find_most_efficient_move(remaining_characters_in_group)\n return self.__find_most_efficient_move(remaining_characters)\n\n def __find_most_efficient_move(self, remaining_characters: List[Character]) -> (Character, List[List[Room]]):\n aggregator: List[(Character, List[List[Room]], int)] = []\n higher_score: int = 0\n most_efficient_move: (Character, List[Room]) = ()\n\n for remaining_character in remaining_characters:\n available_paths: List[Path] = super().get_character_available_paths(remaining_character, self.game)\n paths_ordered_by_preference: List[List[Room]] = self \\\n .__get_adjacent_rooms_ordered_by_preference(remaining_character, available_paths, self.game)\n aggregator.append((\n remaining_character,\n paths_ordered_by_preference,\n len(available_paths) + len(paths_ordered_by_preference[0])))\n\n for elem in aggregator:\n if elem[2] > higher_score:\n higher_score = elem[2]\n most_efficient_move = (elem[0], elem[1])\n\n return most_efficient_move\n\n @staticmethod\n def __get_adjacent_rooms_ordered_by_preference(character: Character, available_paths: List[Path],\n game: Game) -> List[List[Room]]:\n inhabiting_room: Room = game.get_map().get_list_of_rooms()[character.get_current_position()]\n efficient_move: List[Room] = []\n neutral_move: List[Room] = []\n inefficient_move: List[Room] = []\n\n for available_path in available_paths:\n adjacent_room: Room = available_path.get_adjacent_room(inhabiting_room)\n inhabitant_adjacent_room: List[Character] = adjacent_room.get_inhabitant()\n\n if adjacent_room.get_id() != game.get_map().get_dark_room().get_id():\n neutral_move.append(adjacent_room)\n elif len(inhabitant_adjacent_room) == 1:\n efficient_move.append(adjacent_room)\n elif len(inhabitant_adjacent_room) > 1:\n inefficient_move.append(adjacent_room)\n else:\n inefficient_move.append(adjacent_room)\n\n return [efficient_move, neutral_move, inefficient_move]\n","sub_path":"myia/ia/process/selector/GhostCharacterSelector.py","file_name":"GhostCharacterSelector.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14426111","text":"import argparse\nimport re\nimport math\nimport struct\n\ndesp = '''\nテキストファイルに書かれた3次元点群のデータを pcd 形式のファイルにする。\nテキストファイルには、\nx1 y1 z1 r1 g1 b1 \nx2 y2 z2 r2 g2 b2\n・・・\nという具合に空白文字区切りで3次元座標値と色を1行1点で書いておく。\nx, y, z は、任意の実数値。\nr, g, b は、[0,255] の 8bit の値。\n'''\nparser = argparse.ArgumentParser(description=desp)\nparser.add_argument(\"input.txt\", help='入力テキストファイル')\nparser.add_argument(\"output.pcd\", help='出力ファイル名')\nargs = parser.parse_args()\n\n# 引数処理\nin_fn = vars(args)['input.txt']\nout_fn = vars(args)['output.pcd']\n\n# 入力データをしまうバッファ\ninp_dat = []\n\n# 入力ファイルのオープン\nfor line in open(in_fn):\n\n # 空白文字でスプリット\n la = line.split()\n\n # スプリットした結果の要素数が所定の数だったら有効な行と見なす\n if len(la) == 6:\n x = float(la[0])\n y = float(la[1])\n z = float(la[2])\n r = int(la[3])\n g = int(la[4])\n b = int(la[5])\n inp_dat.append([x, y, z, r, g, b])\n \n# 情報出力\nprint(\"Input data read: \", len(inp_dat))\n\n# 出力ファイルのオープン(一旦テキストモードで開く)\nout_pcd = open(vars(args)['output.pcd'],'w')\n\n# PCD ファイルのヘッダーの書き込み\nout_pcd.write(\"# .PCD v0.7 - Point Cloud Data file format\\n\")\nout_pcd.write(\"VERSION 0.7\\n\")\nout_pcd.write(\"FIELDS x y z rgb\\n\")\nout_pcd.write(\"SIZE 4 4 4 4\\n\")\nout_pcd.write(\"TYPE F F F F\\n\")\nout_pcd.write(\"COUNT 1 1 1 1\\n\")\nout_pcd.write(\"WIDTH %d\\n\" % len(inp_dat))\nout_pcd.write(\"HEIGHT 1\\n\")\nout_pcd.write(\"VIEWPOINT 0 0 0 1 0 0 0\\n\")\nout_pcd.write(\"POINTS %d\\n\" % len(inp_dat))\nout_pcd.write(\"DATA binary\\n\" )\n\n# 出力ファイルを一旦閉じてバイナリモードで再オープン\nout_pcd.close()\nout_pcd = open(vars(args)['output.pcd'],'ab')\n\n# 書き込み\nfor a in inp_dat:\n x, y, z, r, g, b = a[0], a[1], a[2], a[3], a[4], a[5]\n out_pcd.write(struct.pack('fffI', x, y, z, (r << 16) | (g << 8) | b))\n\n# ファイルのクローズ\nout_pcd.close()\n\n# 情報表示\nprint(\"Output file: \", out_fn)","sub_path":"0308_lidar_tools/text_to_pcd.r01.py","file_name":"text_to_pcd.r01.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"115295011","text":"#dice_game.py\n\nfrom random import randint\n\nn = input(\"Enter numer of sides: \")\nn = int(n)\n\nplayer1_name = input(\"Enter player1 name: \")\nplayer2_name = input(\"Enter player2 name: \")\n\nplayer1_number = randint(1, n)\nplayer2_number = randint(1, n)\n\nprint(player1_name + \" rolls \" + str(player1_number))\nprint(player2_name + \" rolls \" + str(player2_number))\n\nif player1_number > player2_number:\n print(player1_name + \" wins!\")\nelif player1_number < player2_number:\n print(player2_name + \" wins!\")\nelse:\n print(\"Noboy wins, because the result is equal.\")\n","sub_path":"week-1/2-If-Elif-Else-Simple-Problems/dice_game.py","file_name":"dice_game.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"35462465","text":"#coding: utf-8\nfrom __future__ import unicode_literals, absolute_import\n\nfrom django.utils.text import force_unicode\n\nfrom django_select2.fields import HeavyModelSelect2ChoiceField\n\nfrom fias import widgets\n\n\nclass AddressSelect2Field(HeavyModelSelect2ChoiceField):\n\n widget = widgets.AddressSelect2\n\n def __init__(self, *args, **kwargs):\n super(AddressSelect2Field, self).__init__(*args, **kwargs)\n self.widget.field = self\n\n def _txt_for_val(self, value):\n if not value:\n return\n obj = self.queryset.get(pk=value)\n lst = [force_unicode(obj)]\n\n def make_list(o):\n if o.aolevel > 1:\n try:\n parent = self.queryset.get(aoguid=o.parentguid)\n except self.queryset.model.DoesNotExist:\n return\n else:\n lst.append(force_unicode(parent))\n make_list(parent)\n\n make_list(obj)\n return ', '.join(lst[::-1])\n","sub_path":"fias/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"562602842","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 30 18:57:54 2021\n\n@author: charles\n\"\"\"\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\ndef scrape():\n # Setup splinter\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=False)\n \n url = 'https://redplanetscience.com/'\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n \n items = soup.find_all('div', id='news')[0]\n item0 = items.find_all('div', class_='col-md-12')[0]\n news_title = item0.find_all('div', class_='content_title')[0].text\n \n news_p = item0.find_all('div', class_='article_teaser_body')[0].text\n \n url = 'https://spaceimages-mars.com/'\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n featured_image_url = url + \\\n soup.find_all('img', class_='headerimage')[0].attrs['src']\n \n \n import pandas as pd\n url = 'https://galaxyfacts-mars.com/'\n tables = pd.read_html(url)\n tables\n df0 = tables[0]\n df0 = df0.set_index(0)\n df0.index.name = 'Description'\n df0.columns = ['Mars', 'Earth']\n mars_fact_table = df0.to_html()\n \n \n import time\n url = 'https://marshemispheres.com/'\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n \n items = soup.find_all('div', class_='item')\n \n hemisphere_image_urls = []\n for i in range(len(items)):\n # i = 0\n item = items[i]\n title = item.find_all('h3')[0].text\n browser.find_by_css('img.thumb')[i].click()\n html2 = browser.html\n soup2 = BeautifulSoup(html2, 'html.parser')\n img_url = url + soup2.find_all('div', class_='downloads')[0]\\\n .find_all('li')[0]\\\n .find_all('a')[0]\\\n .attrs['href']\n hemisphere_image_urls.append({'title': title,\n 'img_url': img_url})\n time.sleep(1)\n browser.visit(url)\n time.sleep(1)\n \n res = {'redplanetscience': {'news_title': news_title,\n 'news_p': news_p},\n 'spaceimages-mars': featured_image_url,\n 'galaxyfacts-mars': mars_fact_table,\n 'marshemispheres': hemisphere_image_urls\n }\n browser.quit()\n return res\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"202625633","text":"# Confeccionar un programa que lea n pares de datos,\n# cada par de datos corresponde a la medida de la base y la altura de un triángulo.\n# El programa deberá informar: a) De cada triángulo la medida de su base, su altura y su superficie.\n# b) La cantidad de triángulos cuya superficie es mayor a 12.\n\n# lista = []\n# n1 = input()\n# n2 = input()\n# lista.append([n1, n2])\n# lista.append([n1, n2])\n# print(lista)\n\ndef for_exercise1():\n \n \n lista_triangulos = []\n n = int(input('how may triangles are you doing today? '))\n\n for i in range(n):\n base = int(input(f'Inserte base del triangulo {i + 1}: '))\n altura = int(input(f'Inserte altura del triangulo {i + 1}: '))\n lista_triangulos.append([base, altura, base * altura / 2])\n\n print(lista_triangulos)\n\n mayor_12 = 0\n\n i = 1\n \n for x in lista_triangulos:\n y = 0\n print('------------------------------------------------')\n print(f'la base del triangulo {i} is {x[y]}')\n print(f'la altura del triangulo {i} is {x[y + 1]}')\n print(f'la superficie del triangulo {i} is {x[y + 2]}')\n i += 1\n if (x[ y + 2] > 12):\n mayor_12 += 1\n \n\n print(f'there are {mayor_12} triangles whose superfice is grather than 12.') \n return 1\n\nfor_exercise1()\n\n","sub_path":"week3/for1.py","file_name":"for1.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"291941935","text":"import logging\nfrom datetime import datetime\nimport os\n\nfrom dotenv import load_dotenv\n\nfrom scraper import IcelandReviewScraper\nfrom twitter import TwitterAccount, Tweet\n\nload_dotenv()\n\nSITEMAP_URL = 'https://www.iceland.co.uk/sitemap_1-product.xml'\n\nLOG_DIR_NAME = 'logs'\nLOG_FILE_NAME = f'iceland_review_bot_{datetime.now():%Y%m%d_%H%M%S}.log'\n\n\nclass Logger(object):\n def __init__(self):\n \"\"\" Opens new logfile with timestamped name. Configures logging. \"\"\"\n\n if not os.path.exists(LOG_DIR_NAME):\n os.mkdir(LOG_DIR_NAME)\n\n self.log_file_path = os.path.join(LOG_DIR_NAME, LOG_FILE_NAME)\n\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s '\n '%(name)-12s '\n '%(levelname)-8s '\n '%(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n handlers=[\n logging.FileHandler(self.log_file_path),\n logging.StreamHandler()\n ]\n )\n\n def get_current_log(self):\n with open(self.log_file_path, 'r') as logfile:\n return logfile.read()\n\n def count_warnings(self):\n logfile = self.get_current_log()\n return logfile.count('WARNING')\n\n\ndef find_random_review():\n scraper = IcelandReviewScraper(SITEMAP_URL)\n review = None\n while not review:\n product_page = scraper.get_random_product_page()\n if not product_page.has_reviews:\n continue\n review = product_page.get_random_review()\n return product_page, review\n\n\ndef write_new_random_review_tweet(twitter_account):\n # This isn't very clean, feel free to contribute a better solution\n successful = False\n while not successful:\n product_page, review = find_random_review()\n tweet = Tweet(product_page, review)\n if tweet.too_long or tweet.is_in_timeline(twitter_account):\n continue\n else:\n successful = True\n return product_page, review, tweet\n\n\nif __name__ == '__main__':\n logger = Logger()\n twitter_account = TwitterAccount()\n product_page, review, tweet = write_new_random_review_tweet(\n twitter_account)\n logging.info(product_page.product_image_url)\n logging.info(tweet.text)\n twitter_account.tweet_image(product_page.product_image_url, tweet.text)\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"106520794","text":"#!/usr/bin/env python3.5\n\nimport os\nimport sys\nimport numpy as np\nimport glob, random\nimport merge_isomaps\n\n#import tf_utils\n#import cnn_tf_graphs\n#import cnn_db_loader\nimport cv2\n#from shutil import copyfile\n\n\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\n\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_boolean('log_device_placement', False,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"Whether to log device placement.\"\"\")\n\nINPUT_ISOMAP_BASE = '/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30_256/verification_templates/'\nINPUT_CONF_BASE = '/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30_256_conf13_sm/verification_templates/'\n\n#OUTPUT_MERGE_BASE = '/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30_256_conf13_sm/verification_templates_merge_best3/'\nOUTPUT_MERGE_BASE = '/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30_256_conf13_sm/verification_templates_pixelwise_max_merge3/'\n\n\n#print('globing all files together first')\nos.environ['CUDA_VISIBLE_DEVICES']='0'\n\nisomap_file_ending = '.isomap.png'\nconfidence_file_ending = '.isomap_conf.npy'\nmean_name = 'total_mean.png'\n\n\ntemplate_list=glob.glob(INPUT_ISOMAP_BASE+'*/*')\n#template_list=glob.glob(INPUT_ISOMAP_BASE+'split1/1??')\n\nprint('found all templates')\n\n\nif not os.path.exists(OUTPUT_MERGE_BASE):\n\tos.mkdir(OUTPUT_MERGE_BASE)\n\n#create split folders\nfor split in range(1,11):\n\tif not os.path.exists(OUTPUT_MERGE_BASE+'split'+str(split)):\n\t\tos.mkdir(OUTPUT_MERGE_BASE+'split'+str(split))\n\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\n\nmerging_lists = []\nconfidence_lists=[]\nmerged_image_output_paths = []\n\n\nfor template_path in template_list:\n\tisomaps = glob.glob(template_path+'/*'+isomap_file_ending)\n\tconfidence_maps = [i.replace(INPUT_ISOMAP_BASE, INPUT_CONF_BASE) for i in isomaps]\n\tconfidence_maps = [c.replace(isomap_file_ending, confidence_file_ending) for c in confidence_maps]\n\t#template_num = os.path.basename(os.path.normpath(template_path))\n\timage_output_path = template_path.replace(INPUT_ISOMAP_BASE, OUTPUT_MERGE_BASE)+'.png'\n\n\t#print (isomaps)\n\t#print (confidence_maps)\n\t#print (image_output_path)\n\n\tmerging_lists.append(isomaps)\n\tconfidence_lists.append(confidence_maps)\n\tmerged_image_output_paths.append(image_output_path)\n\nprint('found all files! Let\\'s do the work now')\t\n\n#print (confidence_lists[:5])\n\n#1) merge all images in a template together to one image\n#merge_isomaps.merge_sm_with_tf(merging_lists, confidence_lists, merged_image_output_paths)\n\n\n#2) calc mean for each confidence and take highest\n#for i in range(len(merging_lists)):\n#\n#\tmean_conf=[]\n#\tif len(confidence_lists[i])>0:\n#\t\tfor j in range(len(confidence_lists[i])):\n#\t\t\tmean_conf.append( np.mean(np.load(confidence_lists[i][j])) )\n#\t\t\t#print ('image',merging_lists[i][j],'has mean conf',mean_conf[-1])\n#\t\tindex_heighest_mean = mean_conf.index(max(mean_conf))\n#\t\t#print('copying',merging_lists[i][index_heighest_mean])\n#\n#\t\tos.symlink(merging_lists[i][index_heighest_mean], merged_image_output_paths[i])\n\n\n#3) calc mean for each confidence, take highest 3 and merge them\n#for i in range(len(merging_lists)):\n#\n#\tmean_conf=[]\n#\tif len(confidence_lists[i])>0:\n#\t\tif len(confidence_lists[i])<=3:\n#\t\t\tcontinue\n#\t\tfor j in range(len(confidence_lists[i])):\n#\t\t\tmean_conf.append( np.mean(np.load(confidence_lists[i][j])) )\n#\t\t\t#print ('image',merging_lists[i][j],'has mean conf',mean_conf[-1])\n\t\t#\n#\t\tbest_3 = sorted(zip(mean_conf, range(len(mean_conf))), reverse=True)[:3]\n#\t\tbest_3_indices = [x[1] for x in best_3]\n#\t\t#print ('best 3 indices are', best_3_indices, 'of total',mean_conf)\n#\n#\t\tnew_confidence_list = [confidence_lists[i][best_index] for best_index in best_3_indices]\n#\t\tnew_isomap_list = [merging_lists[i][best_index] for best_index in best_3_indices]\n#\n#\t\t#print ('orig', confidence_lists[i], 'new', new_confidence_list)\n#\t\t#print ('orig', merging_lists[i], 'new', new_isomap_list)\n#\t\tconfidence_lists[i] = new_confidence_list\n#\t\tmerging_lists[i] = new_isomap_list\n#\n#\t\t#index_heighest_mean = mean_conf.index(max(mean_conf))\n#\t\t#print('copying',merging_lists[i][index_heighest_mean])\n#\n#\t\t#os.symlink(merging_lists[i][index_heighest_mean], merged_image_output_paths[i])\n\n#4) for each pixel search the isomaps with 3 highest confidences and merge them\nINTERIM_BASE = '/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30_256_conf13_sm/verification_templates_pixelwise_max/'\n#make split folders first\nfor i in range(1,11):\n\tif not os.path.exists(INTERIM_BASE+'split'+str(i)):\n\t\tos.mkdir(INTERIM_BASE+'split'+str(i))\n\nfor i in range(len(merging_lists)):\n\n\tprint ('preparing pixelwise max merging (',i,'of',len(merging_lists),')')\n\n\tif len(confidence_lists[i])>0:\n\n\t\tif not os.path.exists(os.path.dirname(confidence_lists[i][0].replace(INPUT_CONF_BASE, INTERIM_BASE))):\n\t\t\tos.mkdir(os.path.dirname(confidence_lists[i][0].replace(INPUT_CONF_BASE, INTERIM_BASE)))\n\n\t\t#if len(confidence_lists[i])==1:\n\t\t#\tcontinue\n\n\t\t#first load all confidences of this merge\n\t\tconfidences = np.zeros((np.load(confidence_lists[i][0]).shape[0],np.load(confidence_lists[i][0]).shape[1],len(confidence_lists[i])))\n\t\tfor j in range(len(confidence_lists[i])):\n\t\t\tconfidences[:,:,j] = np.load(confidence_lists[i][j])[...,0]\n\n\t\tisomaps = np.zeros((np.load(confidence_lists[i][0]).shape[0],np.load(confidence_lists[i][0]).shape[1],3,len(confidence_lists[i])))\n\t\tfor j in range(len(merging_lists[i])):\n\t\t\tisomaps[:,:,:,j] = cv2.imread(merging_lists[i][j], cv2.IMREAD_COLOR) #cv2.IMREAD_UNCHANGED\n\n\t\t\n\t\t#print (confidences[100, 100, :])\n\t\t#print (isomaps[100,100,:,:])\n\n\t\t# https://stackoverflow.com/questions/11253495/numpy-applying-argsort-to-an-array\n\t\tconf_indices = list(np.ix_(*[np.arange(i) for i in confidences.shape]))\n\t\tisomap_indices = list(np.ix_(*[np.arange(i) for i in isomaps.shape]))\n\t\tconf_indices[-1] = np.argsort(confidences)\n\t\tisomap_indices[-1] = np.zeros((isomaps.shape), dtype=np.uint8)\n\t\t\n\t\t# as the isomaps have one dimension more (colour) we have to do some more fancy stuff here\n\t\tisomap_indices[-1][:,:,0,:] = conf_indices[-1]\n\t\tisomap_indices[-1][:,:,1,:] = conf_indices[-1]\n\t\tisomap_indices[-1][:,:,2,:] = conf_indices[-1]\n\t\t\n\t\t#print ('highest:')\n\t\t#highest = confidences[indices[range(confidences.shape[0]),range(confidences.shape[1]),0]]\n\t\tordered_confidences = confidences[conf_indices]\n\t\tordered_isomaps\t\t= isomaps[isomap_indices]\n\n\n\t\tnew_confidence_list =[]\n\t\tnew_isomap_list =[]\n\t\tnumber_max_to_store = 3\n\t\tif len(confidence_lists[i])<number_max_to_store:\n\t\t\tnumber_max_to_store = len(confidence_lists[i])\n\t\tfor k in range(1,number_max_to_store+1):\n\t\t\t#save new confidence and add path to new confidence list\n\t\t\tinterim_conf = os.path.dirname(confidence_lists[i][0].replace(INPUT_CONF_BASE, INTERIM_BASE))+'/max'+str(k)+'.isomap_conf.npy'\n\t\t\tnp.save(interim_conf, np.expand_dims(ordered_confidences[:,:,-k],-1))\n\t\t\tnew_confidence_list.append(interim_conf)\n\n\t\t\t#save new isomap and add path to new isomap list\n\t\t\tinterim_isomap = os.path.dirname(merging_lists[i][0].replace(INPUT_ISOMAP_BASE, INTERIM_BASE))+'/max'+str(k)+'.isomap.png'\n\t\t\t#print (interim_isomap)\n\t\t\tcv2.imwrite(interim_isomap, ordered_isomaps[:,:,:,-k])\n\t\t\tnew_isomap_list.append(interim_isomap)\n\n\t\tconfidence_lists[i] = new_confidence_list\n\t\tmerging_lists[i] = new_isomap_list\n\t\t#print (merged_image_output_paths[i])\n\n#print (confidence_lists[:5])\n\nmerge_isomaps.merge_sm_with_tf(merging_lists, confidence_lists, merged_image_output_paths)\n","sub_path":"IJB_A_merge_isomaps.py","file_name":"IJB_A_merge_isomaps.py","file_ext":"py","file_size_in_byte":7422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633728609","text":"#!/home/ruolin/Software/anaconda3/bin/python\nimport sys\nimport argparse\nimport re\n\n\"\"\"\nremedy cuffcompare output gff.\nmake the transcript_id and gene_id to be the gene_name and nearsest_ref\n\"\"\"\n\nif __name__ == \"__main__\":\n gene_id = re.compile(\"gene_id \\\"(.*?)\\\";\")\n trans_id = re.compile(\"transcript_id \\\"(.*?)\\\";\")\n nearest = re.compile(\"nearest_ref \\\"(.*?)\\\";\")\n gene_name = re.compile(\"gene_name \\\"(.*?)\\\";\")\n\n collector = {} \n\n for line in sys.stdin:\n if line.startswith('#'): continue\n else:\n fields = line.strip().split(\"\\t\");\n try:\n g = gene_name.search(fields[8]).group(1)\n t = nearest.search(fields[8]).group(1)\n except AttributeError:\n sys.stderr.write(\"Malformatted line: {}\".format(line))\n continue\n g = 'gene_id \"' + g + '\";'\n t = 'transcript_id \"' + t + '\";'\n newline = re.sub(gene_id, g, line.strip())\n newline = re.sub(trans_id, t, newline)\n print (newline)\n","sub_path":"util/cuff_anno.py","file_name":"cuff_anno.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"440139447","text":"from serialise import serialise, bfs_console, getHeight\nfrom tkinter import *\nfrom algorithms import *\n\n\n\nroot = Tk()\nroot.title(\"Group Alpha\")\nroot.geometry(\"3840x2340\")\n\ncanvas = Canvas(root, width=1840, height=450, bg='cyan')\n\ncanvas.pack(pady=10)\n\nframe = Frame(root, bg = \"orange\", width=1000, height=300)\nframe.place(x=10, y=750)\n\n\ntextBox=Entry(frame, width=30)\ntextBox.grid(row=2, column=2)\n\ndef init():\n values = [1,2,3,4,5, 6, 7,8, 9]\n\n coords = [ [720, 20, 780, 80], [500, 140, 560, 200], [950, 140, 1010, 200], [330, 260, 390, 320], [660, 260, 720, 320], [830, 260, 890, 320], [1080, 260, 1140, 320], [210, 380, 270, 440], [460, 380, 520, 440], [540, 380, 600, 440],[790, 380, 850, 440]]\n\n tree = serialise(values, coords)\n\n height = getHeight(tree)\n\n createTree(tree, height)\n\n return tree\n\n\ndef clear():\n canvas.delete(\"all\")\n init()\n textBox.delete(0, END)\n \n\n\n\n\ndef createTree(node, depth):\n if not node:\n return\n # Elements of the node are its label and Edges \n [x, y, xn, yn] = node.coords\n createOval(x, y ,xn, yn)\n label = createLabel(node.val, x+20, y+25)\n if node.left:\n createEdges(x, y+60, xn-150, yn+50)\n createTree(node.left, depth)\n if node.right:\n createEdges(x+60, y+60, xn+100, yn+50)\n createTree(node.right, depth)\n\n \n\n\ndef createOval(x, y, xn, yn):\n canvas.create_oval(x, y, xn, yn)\n\n\n\n\ndef createLabel(text, x, y):\n return Label(\n root,\n text=text,\n font=(\"Helvetica\", 14)).place(x=x, y=y)\n\n\n\ndef createEdges(x, y, xn, yn):\n canvas.create_line(x, y, xn, yn)\nhead = init()\n\n\ntextBox=Entry(frame, width=30)\ntextBox.grid(row=2, column=2)\n\ndef retrieve_input():\n if textBox.get():\n return int(textBox.get())\n messagebox.show('Please enter Input')\n\n\n\n\ndef createButtons(canvas, head):\n Button(frame, text='Clear Result', command=clear, width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0,column=0)\n Button(frame, text='Depth First Search', command=lambda: DFS(canvas, head, retrieve_input()), width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0,column=1)\n Button(frame, text='Breath First Search', command=lambda: BFS(canvas, head, retrieve_input()), width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0, column=2)\n Button(frame, text='Depth Limiting Search', command=lambda: DLS(canvas, head, retrieve_input()), width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0, column=3)\n Button(frame, text='Iterative Deepening Search', command=lambda: IDFS(canvas, head, retrieve_input()), width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0, column=4)\n Button(frame, text='Uniform Cost Search', command=lambda: UCS(canvas, head, retrieve_input()), width=22, height=4, bg='#ffb3fe', fg=\"black\").grid(row=0, column=5)\n\n\n \n\n\n\n\n\n\n\nhead = init()\n\n\nfind = 6\n\ncreateButtons(canvas, head)\n\n\n\n\n\nroot.mainloop()\n\n\n","sub_path":"new-514/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"366628692","text":"#Defining medical conditions\nimport random\n\nclass MedicalCondition(object):\n \"\"\"Basic foe in the game\n \"\"\"\n def __init__(self, name, symptoms, vs_effects, lethality, speed, cure):\n self.name = name\n self.symptoms = symptoms\n self.vs_effects = vs_effects\n self.lethality = lethality\n self.speed = speed\n self.cure = cure\n\n def treatment(self, action):\n return action.lower() == self.cure\n\n def worse(self, patient):\n damage = self.lethality * self.speed\n hp = patient.hp - damage\n return hp\n\nheartAttack = MedicalCondition(\"heart attack\", [\"chest pain\", \"difficulty breathing\"], \"shock\", 5, 2, \"aspirin\")\npneumonia = MedicalCondition(\"pneumonia\",[\"a bad cough\", \"green sputum\", \"chills\", \"difficulty breathing\"], \"fever\", 5, 1, \"antibiotics\")\nmeningitis = MedicalCondition(\"meningitis\", [\"headache\", \"neck pain\", \"chills\"], (\"high fever\", \"pain\"), 5, 3, \"antibiotics\")\nappendicitis = MedicalCondition(\"appendicitis\", [\"lower abdominal pain\", \"no appetite\"],\"pain\", 5, 1, \"surgery\")\nearInfection = MedicalCondition(\"ear infection\", [\"pain in my ear\", \"loss of hearing on one side\"], \"fever\", 3, 1, \"antibiotics\")\ngastroenteritis = MedicalCondition(\"gastroenteritis\",[\"diarhea\", \"stomach cramps\", \"vomiting\"], \"pain\", 3,2, \"hydration\")\npulmonaryEmbolism = MedicalCondition(\"pulmonary embolism\", [\"sudden difficulty breathing\", \"bloody sputum\"], \"pain\", 5, 3, \"anticoagulants\")\n\n\nconditionList = [heartAttack,pneumonia,meningitis,appendicitis,earInfection, gastroenteritis]\n\ndef generate_medicalCondition():\n random.shuffle(conditionList)\n if len(conditionList) > 0:\n return conditionList.pop()\n else:\n return None\n","sub_path":"condition.py","file_name":"condition.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"597854839","text":"# -*- coding: utf-8 -*-#\n# -------------------------------------------------------------------------------\n# Name: ConvertBST\n# Description: 把二叉搜索树转换为累加树\n# Author: skymoon9406@gmail.com\n# Date: 2020/3/2\n# -------------------------------------------------------------------------------\n\"\"\"\n概念:二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)\n它或者是一棵空树,或者是具有下列性质的二叉树:\n - 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;\n - 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;\n - 它的左、右子树也分别为二叉排序树。\n\"\"\"\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self):\n self.sum = 0\n\n def convertBST1(self, root: TreeNode):\n \"\"\"\n (1)思路:\n 反序的中序遍历。区别于常规的左-中-右的中序遍历,结合二叉搜索树的右>根>左的特定,遍历过程应采用右-中-左的顺序\n 进行,也就是反序中序遍历。\n 基于这样的遍历思路,那么对于任意节点i,之前遍历过的所有节点都应大于i,所以可以利用一个全局变量sum来记录遍历\n 过的值的和,然后将这个和 和 节点i的值 求和后赋给i,这就是递归的的通式。(该方法也叫回溯法)\n (2)复杂度:\n - 时间复杂度:O(N)\n - 空间复杂度:O(N)\n \"\"\"\n if root is not None:\n self.convertBST1(root.right)\n self.sum += root.val\n root.val = self.sum\n self.convertBST1(root.left)\n return root\n\n def convertBST2(self, root: TreeNode):\n \"\"\"\n (1)思路:\n 利用迭代和栈的思想来完成遍历。python中用list来代替栈(后进先出),每次pop最后一个。\n 首先我们初始化一个空的栈并把根节点作为当前节点。然后只要在栈中有未遍历节点或者 node 节点不为空,\n 我们就将当前节点到最右边叶子路径上的点全部压入栈中。这与递归过程中我们总是先走右子树的思路是一致的,\n 这个思路确保我们总是降序遍历所有���点的值。接下来,我们访问栈顶节点,并考虑它的左子树,\n 这就像我们递归中先遍历当前节点再遍历它的左子树的思路。最后,我们的栈为空并且 node 指向树中最小节点的\n 左孩子 null ,循环结束。\n\n fz:实际就是将最右边叶子路径上的点,推进到栈里面,然后根据栈的特性,就可以降序遍历最右边叶子路径上的点。遍历\n 过程中,将每个节点的左节点也推进到栈里面,由于每个节点遍历时,他的右边节点一定在他之前遍历过了,所以跟上面\n 一样,仍然是右-中-左的顺序遍历\n (2)复杂度:\n - 时间复杂度:O(N)\n - 空间复杂度:O(N)\n \"\"\"\n node = root\n temp_stack = []\n while len(temp_stack) > 0 and node is not None:\n while node is not None:\n temp_stack.append(node)\n node = node.right\n node = temp_stack.pop(-1)\n self.sum += node.val\n node.val = self.sum\n node = node.left\n return root\n","sub_path":"Day28_ConvertBST/ConvertBST.py","file_name":"ConvertBST.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"633495870","text":"#!/usr/bin/env python\r\n# -- coding: utf-8 --\r\nimport sys\r\nimport operator\r\n\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf-8\")\r\n\r\nclass Classifyresultdiff():\r\n '''\r\n 比较不同分类方法各类分类结果的变化\r\n '''\r\n def __init__(self,classify_result_1_path,classify_result_2_path,diff_dict_path):\r\n '''\r\n 将要比较的两类的分类结果路径\r\n :param classify_result_1_path:\r\n :param classify_result_2_path:\r\n '''\r\n self.classify_result_1_path=classify_result_1_path\r\n self.classify_result_2_path=classify_result_2_path\r\n self.diff_dict_path=diff_dict_path\r\n\r\n def get_diff(self):\r\n with open(self.diff_dict_path,'w') as fw:\r\n type_line_num_dict={line.strip().split('\\x01')[0]:int(line.strip().split('\\x01')[1]) for line in open(self.classify_result_1_path,'r').readlines()}\r\n res_1_dict={line.strip().split('\\x01')[0]:float(line.strip().split('\\x01')[3]) for line in open(self.classify_result_1_path,'r').readlines()}\r\n res_2_dict = {line.strip().split('\\x01')[0]: float(line.strip().split('\\x01')[3]) for line in\r\n open(self.classify_result_2_path, 'r').readlines()}\r\n diff_dict={k:(res_2_dict[k]-res_1_dict[k]) for k in res_2_dict}\r\n sort_dict=sorted(diff_dict.iteritems(),key=operator.itemgetter(1),reverse=True)\r\n for k,v in sort_dict:\r\n fw.write(k+'\\x01'+str(type_line_num_dict[k])+'\\x01'+format(v,'.5f')+'\\n')\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # classify_result_1_path='D:/wrokmy/position_rec/target_datas/1_plus_remove_0.6_1.0/test_result_0.60_1.00'\r\n # classify_result_2_path = 'D:/wrokmy/position_rec/target_datas/remove_0.6_1.0/test_result_0.60_1.00'\r\n # diff_dict_path='D:/wrokmy/position_rec/target_datas/remove_vs_1plus_0.6_1.0_diff'\r\n\r\n classify_result_1_path = 'D:/wrokmy/position_rec/target_datas/remove_0.6_1.0/test_result_0.60_1.00'\r\n classify_result_2_path = 'D:/wrokmy/position_rec/target_datas/combine_0.6_1.0_remove/combine_test_result'\r\n diff_dict_path = 'D:/wrokmy/position_rec/target_datas/combine_vs_remove_0.6_1.0_diff'\r\n model=Classifyresultdiff(classify_result_1_path=classify_result_1_path,classify_result_2_path=classify_result_2_path,diff_dict_path=diff_dict_path)\r\n model.get_diff()","sub_path":"position_rec/data_classify/classify_result_diff.py","file_name":"classify_result_diff.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"6858265","text":"\"\"\"\r\nFast R-CNN:\r\ndata =\r\n {'data': [num_images, c, h, w],\r\n 'rois': [num_rois, 5]}\r\nlabel =\r\n {'label': [num_rois],\r\n 'bbox_target': [num_rois, 4 * num_classes],\r\n 'bbox_weight': [num_rois, 4 * num_classes]}\r\nroidb extended format [image_index]\r\n ['image', 'height', 'width', 'flipped',\r\n 'boxes', 'gt_classes', 'gt_overlaps', 'max_classes', 'max_overlaps', 'bbox_targets']\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport numpy.random as npr\r\n\r\nfrom ..config import config\r\nfrom ..fio.image import get_image, tensor_vstack\r\nfrom ..processing.bbox_transform import bbox_overlaps, bbox_transform\r\nfrom ..processing.bbox_regression import expand_bbox_regression_targets\r\n\r\n\r\ndef get_rcnn_testbatch(roidb):\r\n \"\"\"\r\n return a dict of testbatch\r\n :param roidb: ['image', 'flipped'] + ['boxes']\r\n :return: data, label, im_info\r\n \"\"\"\r\n assert len(roidb) == 1, 'Single batch only'\r\n imgs, roidb = get_image(roidb)\r\n im_array = imgs[0]\r\n im_info = np.array([roidb[0]['im_info']], dtype=np.float32)\r\n\r\n im_rois = roidb[0]['boxes']\r\n rois = im_rois\r\n batch_index = 0 * np.ones((rois.shape[0], 1))\r\n rois_array = np.hstack((batch_index, rois))[np.newaxis, :]\r\n\r\n data = {'data': im_array,\r\n 'rois': rois_array}\r\n label = {}\r\n\r\n return data, label, im_info\r\n\r\n\r\ndef get_rcnn_batch(roidb):\r\n \"\"\"\r\n return a dict of multiple images\r\n :param roidb: a list of dict, whose length controls batch size\r\n ['images', 'flipped'] + ['gt_boxes', 'boxes', 'gt_overlap'] => ['bbox_targets']\r\n :return: data, label\r\n \"\"\"\r\n num_images = len(roidb)\r\n imgs, roidb = get_image(roidb)\r\n im_array = tensor_vstack(imgs)\r\n\r\n assert config.TRAIN.BATCH_ROIS % config.TRAIN.SAMPLES_PER_BATCH == 0, \\\r\n 'BATCHIMAGES {} must divide BATCH_ROIS {}'.format(config.TRAIN.SAMPLES_PER_BATCH, config.TRAIN.BATCH_ROIS)\r\n rois_per_image = config.TRAIN.BATCH_ROIS / config.TRAIN.SAMPLES_PER_BATCH\r\n fg_rois_per_image = np.round(config.TRAIN.FG_FRACTION * rois_per_image).astype(int)\r\n\r\n rois_array = list()\r\n labels_array = list()\r\n bbox_targets_array = list()\r\n bbox_weights_array = list()\r\n\r\n for im_i in range(num_images):\r\n roi_rec = roidb[im_i]\r\n\r\n # infer num_classes from gt_overlaps\r\n num_classes = roi_rec['gt_overlaps'].shape[1]\r\n\r\n # label = class RoI has max overlap with\r\n rois = roi_rec['boxes']\r\n labels = roi_rec['max_classes']\r\n overlaps = roi_rec['max_overlaps']\r\n bbox_targets = roi_rec['bbox_targets']\r\n\r\n im_rois, labels, bbox_targets, bbox_weights = \\\r\n sample_rois(rois, fg_rois_per_image, rois_per_image, num_classes,\r\n labels, overlaps, bbox_targets)\r\n\r\n # project im_rois\r\n # do not round roi\r\n rois = im_rois\r\n batch_index = im_i * np.ones((rois.shape[0], 1))\r\n rois_array_this_image = np.hstack((batch_index, rois))\r\n rois_array.append(rois_array_this_image)\r\n\r\n # add labels\r\n labels_array.append(labels)\r\n bbox_targets_array.append(bbox_targets)\r\n bbox_weights_array.append(bbox_weights)\r\n\r\n rois_array = np.array(rois_array)\r\n labels_array = np.array(labels_array)\r\n bbox_targets_array = np.array(bbox_targets_array)\r\n bbox_weights_array = np.array(bbox_weights_array)\r\n\r\n data = {'data': im_array,\r\n 'rois': rois_array}\r\n label = {'label': labels_array,\r\n 'bbox_target': bbox_targets_array,\r\n 'bbox_weight': bbox_weights_array}\r\n\r\n return data, label\r\n\r\n\r\ndef sample_rois(rois, fg_rois_per_image, rois_per_image, num_classes,\r\n labels=None, overlaps=None, bbox_targets=None, gt_boxes=None):\r\n \"\"\"\r\n generate random sample of ROIs comprising foreground and background examples\r\n :param rois: all_rois [n, 4]; e2e: [n, 5] with batch_index\r\n :param fg_rois_per_image: foreground roi number\r\n :param rois_per_image: total roi number\r\n :param num_classes: number of classes\r\n :param labels: maybe precomputed\r\n :param overlaps: maybe precomputed (max_overlaps)\r\n :param bbox_targets: maybe precomputed\r\n :param gt_boxes: optional for e2e [n, 5] (x1, y1, x2, y2, cls)\r\n :return: (labels, rois, bbox_targets, bbox_weights)\r\n \"\"\"\r\n if labels is None:\r\n overlaps = bbox_overlaps(rois[:, 1:].astype(np.float), gt_boxes[:, :4].astype(np.float))\r\n gt_assignment = overlaps.argmax(axis=1)\r\n overlaps = overlaps.max(axis=1)\r\n labels = gt_boxes[gt_assignment, 4]\r\n\r\n # foreground RoI with FG_THRESH overlap\r\n fg_indexes = np.where(overlaps >= config.TRAIN.FG_THRESH)[0]\r\n # guard against the case when an image has fewer than fg_rois_per_image foreground RoIs\r\n fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_indexes.size)\r\n # Sample foreground regions without replacement\r\n if fg_indexes.size > 0:\r\n if fg_indexes.size < fg_rois_per_image and config.TRAIN.RCNN_POS_UPSAMPLE: # yk added 040317\r\n fg_rois_per_this_image = fg_rois_per_image\r\n fg_indexes = npr.choice(fg_indexes, size=fg_rois_per_this_image, replace=True)\r\n if len(fg_indexes) > fg_rois_per_this_image:\r\n fg_indexes = npr.choice(fg_indexes, size=fg_rois_per_this_image, replace=False)\r\n\r\n # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)\r\n bg_indexes = np.where((overlaps < config.TRAIN.BG_THRESH_HI) & (overlaps >= config.TRAIN.BG_THRESH_LO))[0]\r\n # Compute number of background RoIs to take from this image (guarding against there being fewer than desired)\r\n bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image\r\n bg_rois_per_this_image = np.minimum(bg_rois_per_this_image, bg_indexes.size)\r\n # Sample foreground regions without replacement\r\n if len(bg_indexes) > bg_rois_per_this_image:\r\n bg_indexes = npr.choice(bg_indexes, size=bg_rois_per_this_image, replace=False)\r\n\r\n # indexes selected\r\n keep_indexes = np.append(fg_indexes, bg_indexes)\r\n neg_idx = np.where(overlaps < config.TRAIN.FG_THRESH)[0]\r\n neg_rois = rois[neg_idx]\r\n # pad more to ensure a fixed minibatch size\r\n while keep_indexes.shape[0] < rois_per_image:\r\n gap = np.minimum(len(neg_rois), rois_per_image - keep_indexes.shape[0])\r\n gap_indexes = npr.choice(range(len(neg_rois)), size=gap, replace=False)\r\n keep_indexes = np.append(keep_indexes, neg_idx[gap_indexes])\r\n\r\n # select labels\r\n labels = labels[keep_indexes]\r\n # set labels of bg_rois to be 0\r\n labels[fg_rois_per_this_image:] = 0\r\n rois = rois[keep_indexes]\r\n\r\n # load or compute bbox_target\r\n if bbox_targets is not None:\r\n bbox_target_data = bbox_targets[keep_indexes, :]\r\n else:\r\n targets = bbox_transform(rois[:, 1:], gt_boxes[gt_assignment[keep_indexes], :4])\r\n if config.TRAIN.BBOX_NORMALIZE_TARGETS and config.TRAIN.BBOX_NORMALIZATION_PRECOMPUTED:\r\n targets = ((targets - np.array(config.TRAIN.BBOX_MEANS))\r\n / np.array(config.TRAIN.BBOX_STDS))\r\n bbox_target_data = np.hstack((labels[:, np.newaxis], targets))\r\n\r\n bbox_targets, bbox_weights = \\\r\n expand_bbox_regression_targets(bbox_target_data, num_classes)\r\n\r\n return rois, labels, bbox_targets, bbox_weights\r\n\r\n","sub_path":"lesion_detector_3DCE/rcnn/fio/rcnn.py","file_name":"rcnn.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"105694842","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport os.path\nimport fnmatch\nimport xml.dom.minidom as minidom\nimport xml.etree.ElementTree as ET\n\n# fun stuff\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef printBold(*args):\n print(bcolors.BOLD + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printHeader(*args):\n print(bcolors.HEADER + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printBule(*args):\n print(bcolors.OKBLUE + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printGreen(*args):\n print(bcolors.OKGREEN + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printWarning(*args):\n print(bcolors.WARNING + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printFail(*args):\n print(bcolors.FAIL + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef printUnderline(*args):\n print(bcolors.UNDERLINE + \"\".join(map(str, args)) + bcolors.ENDC)\n\n\ndef findAllFileWithName(modulePath, name):\n result = []\n for root, dirs, files in os.walk(modulePath):\n if name in files:\n result.append(os.path.join(root, name))\n return result\n\n\ndef findAllFileWithPattern(path, pattern):\n result = []\n for root, dirs, files in os.walk(path):\n for name in files:\n if fnmatch.fnmatch(name, pattern):\n result.append(os.path.join(root, name))\n return result\n\n\ndef safeGet(dict, setName):\n if setName in dict.keys():\n return dict[setName]\n else:\n return set()\n\n\ndef prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\n\nKEYS = []\nTR_VALUES = []\nEN_VALUES = []\n\nTR_KV = {}\nEN_KV = {}\nCN_KV = {}\n\n\ndef extractXML(xmlpath, kv):\n tree = ET.parse(xmlpath)\n root = tree.getroot()\n for element in root.iter('string'):\n key = element.get('name')\n kv[key] = element.text\n\n\ndef process(respath):\n tr_xml = respath + \"values-tr\" + os.path.sep + \"strings.xml\"\n cn_xml = respath + \"values-zh-rCN\" + os.path.sep + \"strings.xml\"\n en_xml = respath + \"values\" + os.path.sep + \"strings.xml\"\n extractXML(tr_xml, TR_KV)\n extractXML(en_xml, EN_KV)\n extractXML(cn_xml, CN_KV)\n\n tree = ET.parse(tr_xml)\n root = tree.getroot()\n for element in root.iter('string'):\n key = element.get('name')\n KEYS.append(key)\n TR_VALUES.append(element.text)\n if key in CN_KV:\n EN_VALUES.append(CN_KV[key])\n else:\n EN_VALUES.append(EN_KV[key])\n\n outpath = respath + \"output\" + os.path.sep\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n\n with open(outpath + \"result.csv\", \"w\") as of:\n for k in KEYS:\n en = \"\"\n if k not in CN_KV:\n en = EN_KV[k]\n else:\n en = CN_KV[k]\n of.write('\"' + k + '\",' + '\"' + TR_KV[k].encode('utf-8') +'\",' + '\"'+ en.encode('utf-8') + '\"\\n')\n of.close()\n\n with open(outpath + \"keys.txt\", \"w\") as of:\n for k in KEYS:\n of.write(k + \"\\n\")\n of.close()\n\n with open(outpath + \"values.txt\", \"w\") as of:\n for v in TR_VALUES:\n of.write(v.encode('utf-8') + \"\\n\")\n of.close()\n\n with open(outpath + \"en.txt\", \"w\") as of:\n for v in EN_VALUES:\n of.write(v.encode('utf-8') + \"\\n\")\n of.close()\n\n printBule('🍺 All done, have a nice day!')\n\n\ndef main(argv):\n if len(argv) < 1:\n printBold(\"Usage: extract\")\n exit(-1)\n\n printHeader(\"extract v0.1 by MG © 2017\")\n printHeader('🌐 processing...')\n\n process(argv[0])\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"python/android/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"279373306","text":"\"\"\" This file is meant to perform classification and should be run in the command\nline. \n\"\"\"\n\n\nimport pandas as pd\nimport os\nfrom os.path import join\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sys\nfrom datetime import datetime \nfrom copy import deepcopy\nimport time\n\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, KFold\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_selection import SelectKBest, VarianceThreshold\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.naive_bayes import GaussianNB\n\n# Local imports\nsys.path.insert(1, \"..\")\nfrom mri_learn_quick import MRILearn, pbcc\nfrom confounds import *\n\n# Define settings for the experiment \nDATA_DIR = \"/ritter/share/data/IMAGEN\"\nN_TRIALS = 10\nN_SPLITS = 5\n# Number of permutati\n# ons for standard PT. Set to None if no PT should be done.\nN_PERMUTATIONS = 100\n# Number of permutations for within-block PT. Set to None if no WBPT should be done.\nN_WBPERMUTATIONS = None\nsave_coefs = False\n\n# The random states are loaded from a pre-made file to keep computations reproducible.\nrandom_states = np.load(\"random_states.npy\")[:N_TRIALS]\n\n# Parameters for the MRILearn object\nparams = {\n \"verbose\" : 3, \n \"n_jobs\" : 5, \n \"conf_list\" : [\"c\", \"s\", \"group\"]\n}\n\npipes = [\n Pipeline([\n (\"varth\", VarianceThreshold()),\n (\"feature_selection\", SelectKBest()),\n (\"scale\", StandardScaler()),\n (\"model\", LogisticRegression(max_iter=2500))\n ]),\n Pipeline([\n (\"varth\", VarianceThreshold()),\n (\"feature_selection\", SelectKBest()),\n (\"scale\", MinMaxScaler(feature_range=(-1,1))),\n (\"model\", LinearSVC(max_iter=2500))\n\n ]),\n Pipeline([\n (\"varth\", VarianceThreshold()),\n (\"feature_selection\", SelectKBest()),\n (\"scale\", MinMaxScaler(feature_range=(-1,1))),\n (\"model\", SVC(kernel=\"rbf\"))\n ]),\n Pipeline([\n (\"feature_selection\", SelectKBest()), # Only added for compatibility, k is always \"all\"!\n (\"model\", GradientBoostingClassifier(max_depth=5, n_estimators=100, max_features=\"sqrt\"))\n ]), \n Pipeline([\n (\"varth\", VarianceThreshold()),\n (\"feature_selection\", SelectKBest()),\n (\"scale\", StandardScaler()),\n (\"model\", GaussianNB())\n ])\n]\ngrids = [\n {\n \"model__C\" : [1e-8, 1e-5, 1e-3, 1, 1e3, 1e5, 1e8]\n },\n {\n \"model__C\" : [1e-8, 1e-5, 1e-3, 1, 1e3, 1e5, 1e8]\n },\n {\n \"model__C\" : [1e-8, 1e-5, 1e-3, 1, 1e3, 1e5, 1e8],\n \"model__gamma\" : [1e-5, 1e-3, 0.01, 0.1, 1]\n },\n {}, \n {}\n]\n\n# Here you could select which pipelines you want to run\n\npipes = [pipes[i] for i in [1,3]]\ngrids = [grids[i] for i in [1,3]]\n\n#pipes = [pipes[0,1,3]]\n#grids = [grids[0,1,3]]\n\n# Here you can select which HDF5 files you want to include in analysis. \n# Each entry should be (file_name, k_features).\nfiles = [\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_FU2-FU2_n789_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_FU2-FU2_n403_sex1_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_FU2-FU2_n386_sex0_z0.525_d0.h5\"), 10000)\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_BL-FU2_n507_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_BL-FU2_n269_sex1_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/T1w/T1w_BL-FU2_n238_sex0_z0.525_d0.h5\"), 10000)\n\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_FU2-FU2_n789_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_FU2-FU2_n403_sex1_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_FU2-FU2_n386_sex0_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_BL-FU2_n269_sex1_z0.525_d0.h5\"), 10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_BL-FU2_n238_sex0_z0.525_d0.h5\"),10000),\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/dti-FA/dti-FA_BL-FU2_n507_z0.525_d0.h5\"), 10000)\n\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_BL-FU2_n507.h5\"), \"all\")\n (join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_FU2-FU2_n789.h5\"), \"all\")\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_FU2-FU2_n403_sex1.h5\"), \"all\")\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_FU2-FU2_n386_sex0.h5\"), \"all\")\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_BL-FU2_n269_sex1.h5\"), \"all\")\n #(join(DATA_DIR, \"h5files/ESPAD19a_01_56/fs-stats/fs-stats_BL-FU2_n238_sex0.h5\"), \"all\")\n]\n\n\n# The experiments dict is a grid where you can select which technique and io you want to \nexperiments = {\n #\"technique\" : [\"baseline\"],\n \"technique\" : [\"baseline\", \"cb\", \"wdcr\", \"cvcr\", \"cbcvcr\"],\n \"io\" : [\n (\"X\", \"y\")\n #(\"X\", \"s\"), \n #(\"X\", \"c\"),\n #(\"s\", \"y\"),\n #(\"c\", \"y\")\n ], \n \"trial\" : range(N_TRIALS), \n \"pipesgrids\" : zip(pipes, grids)\n}\n\n\nfor f, k_features in files:\n\n params[\"data_dir\"] = f\n\n # Create the folder in which to save the results\n SAVE_DIR = \"results/{}/{}\".format(os.path.basename(params[\"data_dir\"]).replace(\".h5\",\"\"),\\\n datetime.now().strftime(\"%Y%m%d-%H%M\"))\n if not os.path.isdir(SAVE_DIR):\n os.makedirs(SAVE_DIR)\n\n # DataFrames to store results in \n df = pd.DataFrame(columns=[\"model\", \"technique\", \"trial\", \"io\", \"train_score\", \"valid_score\", \"test_score\", \"roc_auc\", \"sensitivity\",\"specificity\"])\n df_pt = pd.DataFrame(columns=[\"model\", \"technique\", \"trial\", \"io\", \"permutation_scores\", \"permutation_scores_auc\"])\n df_ptwb = pd.DataFrame(columns=[\"model\", \"technique\", \"trial\", \"io\", \"permutation_scores\", \"permutation_scores_auc\"])\n\n\n if save_coefs:\n coefs_matrix = np.empty([N_TRIALS, 1050624])\n else:\n pass\n\n\n # Go through all combinations of experiments\n for p in ParameterGrid(experiments):\n \n technique = p[\"technique\"]\n i, o = p[\"io\"]\n io = \"{}-{}\".format(i,o)\n pipe = p[\"pipesgrids\"][0]\n grid = p[\"pipesgrids\"][1]\n trial = p[\"trial\"]\n model_name = type(pipe[\"model\"]).__name__\n random_state = random_states[trial]\n\n\n if (i == \"X\" and model_name != \"GradientBoostingClassifier\"):\n grid[\"feature_selection__k\"] = [k_features]\n else:\n grid[\"feature_selection__k\"] = [\"all\"]\n\n # Some parameter combinations do not work\n # CVCR or CBCVCR does not work with models other than LR\n if ((technique == \"cvcr\" or technique == \"cbcvcr\") and model_name != \"LogisticRegression\"):\n print(\"Skipping CVCR because model != LR.\")\n continue\n # When taking only male or female data, sex is not a confound\n if (\"sex\" in f and (io == \"X-s\" or io == \"s-y\")):\n print(\"Skipping X-s and s-y because sex is the same among subjects.\")\n continue\n # CBCVCR can only be done on combined data\n if (\"sex\" in f and technique == \"cbcvcr\"):\n print(\"Skipping CBCVCR because sex is the same among subjects.\")\n continue\n \n\n # What happens during the confound correction techniques: \n if technique == \"baseline\":\n m = MRILearn(params)\n m.load_data()\n m.train_test_split(random_state=random_state)\n skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state)\n # Whole Dataset Confound Regression both confounds\n elif (technique == \"wdcr\") and (i == \"X\"):\n m = MRILearn(params)\n m.load_data()\n m.X = np.concatenate([m.X, m.conf_dict[\"group\"].reshape(-1,1)], axis=1)\n crc = ConfoundRegressorCategoricalX()\n m.wd_transform(crc)\n m.train_test_split(random_state=random_state)\n skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state)\n elif (technique == \"wdcr\") and (i != \"X\"):\n m = MRILearn(params)\n m.load_data()\n m.train_test_split(random_state=random_state)\n skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state)\n # CrossValidated Confound Regression both confounds\n elif (technique == \"cvcr\") and (i == \"X\"):\n m = MRILearn(params)\n m.load_data()\n m.X = np.concatenate([m.X, m.conf_dict[\"group\"].reshape(-1,1)], axis=1)\n crc = (\"crc\", ConfoundRegressorCategoricalX())\n pipe = deepcopy(pipe)\n pipe.steps.insert(0, crc)\n m.train_test_split(random_state=random_state)\n skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state)\n elif (technique == \"cvcr\") and (i != \"X\"):\n m = MRILearn(params)\n m.load_data()\n m.train_test_split(random_state=random_state)\n skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state)\n # CounterBalancing both confounds\n elif technique == \"cb\":\n m = MRILearn(params)\n m.load_data()\n\n # Counterbalance for both sex and site, which is \"group\"\n cb = CounterBalance(m.conf_dict[\"group\"], random_state)\n m.X = cb.fit_transform(m.X, m.y)\n m.y = cb.transform(m.y)\n m.conf_dict[\"c\"] = cb.transform(m.conf_dict[\"c\"])\n m.conf_dict[\"s\"] = cb.transform(m.conf_dict[\"s\"])\n m.conf_dict[\"group\"] = cb.transform(m.conf_dict[\"group\"])\n\n # Ensure groups are stratified within splits\n m.train_test_split(random_state=random_state, stratify_group=\"group\")\n stratify_groups = m.conf_dict_tv[\"group\"] + 100 * m.y_tv\n skf = tuple(StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state).split(m.X_tv, stratify_groups))\n # CB-CVCR: counterbalancing sex and CVCR for site\n elif (technique == \"cbcvcr\") and (i == \"X\"):\n m = MRILearn(params)\n m.load_data()\n # Counterbalance for sex ONLY \n cb = CounterBalance(m.conf_dict[\"s\"], random_state)\n m.X = cb.fit_transform(m.X, m.y)\n m.y = cb.transform(m.y)\n m.conf_dict[\"c\"] = cb.transform(m.conf_dict[\"c\"])\n m.conf_dict[\"s\"] = cb.transform(m.conf_dict[\"s\"])\n m.conf_dict[\"group\"] = cb.transform(m.conf_dict[\"group\"])\n\n # The CVCR part for site ONLY\n m.X = np.concatenate([m.X, m.conf_dict[\"c\"].reshape(-1,1)], axis=1)\n crc = (\"crc\", ConfoundRegressorCategoricalX())\n pipe = deepcopy(pipe)\n pipe.steps.insert(0, crc)\n\n # Ensure groups are stratified within splits\n m.train_test_split(random_state=random_state, stratify_group=\"s\")\n stratify_groups = m.conf_dict_tv[\"s\"] + 100 * m.y_tv\n skf = tuple(StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state).split(m.X_tv, stratify_groups))\n elif (technique == \"cbcvcr\") and (i != \"X\"):\n m = MRILearn(params)\n m.load_data()\n\n cb = CounterBalance(m.conf_dict[\"s\"], random_state)\n m.X = cb.fit_transform(m.X, m.y)\n m.y = cb.transform(m.y)\n m.conf_dict[\"c\"] = cb.transform(m.conf_dict[\"c\"])\n m.conf_dict[\"s\"] = cb.transform(m.conf_dict[\"s\"])\n m.conf_dict[\"group\"] = cb.transform(m.conf_dict[\"group\"])\n\n # Ensure groups are stratified within splits\n m.train_test_split(random_state=random_state, stratify_group=\"s\")\n stratify_groups = m.conf_dict_tv[\"s\"] + 100 * m.y_tv\n skf = tuple(StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state).split(m.X_tv, stratify_groups))\n elif technique == \"cb_sex\":\n m = MRILearn(params)\n m.load_data()\n\n # Counterbalance for both sex and site, which is \"group\"\n cb = CounterBalance(m.conf_dict[\"s\"], random_state)\n m.X = cb.fit_transform(m.X, m.y)\n m.y = cb.transform(m.y)\n m.conf_dict[\"c\"] = cb.transform(m.conf_dict[\"c\"])\n m.conf_dict[\"s\"] = cb.transform(m.conf_dict[\"s\"])\n m.conf_dict[\"group\"] = cb.transform(m.conf_dict[\"group\"])\n\n # Ensure groups are stratified within splits\n m.train_test_split(random_state=random_state, stratify_group=\"s\")\n stratify_groups = m.conf_dict_tv[\"s\"] + 100 * m.y_tv\n skf = tuple(StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=random_state).split(m.X_tv, stratify_groups))\n\n \n print(\"D\")\n\n # Change input and output if so defined \n if i != \"X\":\n m.change_input_to(i, onehot=True)\n if o != \"y\":\n m.change_output_to(o)\n\n start = time.time()\n # Run the actual classification\n run, best_params = m.run(pipe, grid, cv_splitter=skf)\n\n if save_coefs:\n coefs = m.estimator.named_steps[\"model\"].coef_\n coefs = m.estimator.named_steps[\"feature_selection\"].inverse_transform(coefs)\n coefs = m.estimator.named_steps[\"varth\"].inverse_transform(coefs)\n coefs = coefs.flatten()\n coefs_matrix[trial, :] = coefs\n np.save(join(SAVE_DIR, \"coefs\"), coefs_matrix)\n\n\n # Calculate PBCC D2 values\n if (technique==\"baseline\") and (i == \"X\" and o ==\"y\"):\n d2_pred, d2_conf, d2_conf_pred = pbcc(m.estimator, m.X_test, m.y_test, m.conf_dict_test[\"s\"], m.conf_dict_test[\"c\"])\n else:\n d2_pred, d2_conf, d2_conf_pred = np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan\n\n # Append results\n result = {\n \"model\" : model_name,\n \"technique\" : technique,\n \"trial\" : trial,\n \"io\" : \"{}-{}\".format(i,o), \n **run,\n \"runtime\" : time.time() - start, \n **best_params, \n \"d2_pred\" : d2_pred, \n \"d2_conf\" : d2_conf, \n \"d2_conf_pred\" : d2_conf_pred\n }\n\n print(result)\n df = df.append(result, ignore_index=True)\n # Save classification results\n df.to_csv(join(SAVE_DIR, \"run.csv\"))\n\n \n # RUN PERMUTATION TEST \n if N_PERMUTATIONS:\n # In this case a permtest with PBCC values is done\n if (technique==\"baseline\") and (i == \"X\" and o ==\"y\"):\n start = time.time()\n pt = m.permutation_test_pbc(pipe, grid, n_permutations=N_PERMUTATIONS, cv_splitter=skf)\n pt_result = {\n \"model\" : [model_name]*N_PERMUTATIONS,\n \"technique\" : [technique]*N_PERMUTATIONS,\n \"trial\" : [trial]*N_PERMUTATIONS,\n **pt,\n \"io\" : [\"{}-{}\".format(i,o)]*N_PERMUTATIONS, \n \"runtime\" : time.time() - start\n }\n print(result)\n df_pt = pd.concat([df_pt, pd.DataFrame(pt_result)])\n df_pt.to_csv(join(SAVE_DIR, \"pt.csv\"))\n # In other cases, PBCC values are not computed\n else:\n start = time.time()\n pt = m.permutation_test(pipe, grid, n_permutations=N_PERMUTATIONS, cv_splitter=skf)\n pt_result = {\n \"model\" : [model_name]*N_PERMUTATIONS,\n \"technique\" : [technique]*N_PERMUTATIONS,\n \"trial\" : [trial]*N_PERMUTATIONS,\n **pt,\n \"io\" : [\"{}-{}\".format(i,o)]*N_PERMUTATIONS, \n \"runtime\" : time.time() - start\n }\n print(result)\n df_pt = pd.concat([df_pt, pd.DataFrame(pt_result)])\n df_pt.to_csv(join(SAVE_DIR, \"pt.csv\"))\n\n # Add Within-Block PT. \n if N_WBPERMUTATIONS:\n if (technique==\"baseline\") and (i == \"X\" and o ==\"y\"):\n # WBPT only works if there is only one confound site, so sex is all one.\n if len(np.unique(m.conf_dict[\"s\"])) == 1:\n start = time.time()\n ptwb = m.permutation_test_pbc(pipe, grid, n_permutations=N_WBPERMUTATIONS, groups_tv=m.conf_dict_tv[\"c\"], \\\n groups_test=m.conf_dict_test[\"c\"], cv_splitter=skf)\n ptwb_result = {\n \"model\" : [model_name]*N_WBPERMUTATIONS,\n \"technique\" : [technique]*N_WBPERMUTATIONS,\n \"trial\" : [trial]*N_WBPERMUTATIONS,\n **ptwb,\n \"io\" : [\"{}-{}\".format(i,o)]*N_WBPERMUTATIONS, \n \"runtime\" : time.time() - start\n }\n print(result)\n df_ptwb = pd.concat([df_ptwb, pd.DataFrame(ptwb_result)])\n df_ptwb.to_csv(join(SAVE_DIR, \"ptwb.csv\"))\n\n\n","sub_path":"analysis/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":17233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"138662506","text":"import role.baseRole, pygame\nimport bullet.baseBullet\nimport time\nfrom global_parameter import *\n\n\nclass BaseEnemy(role.baseRole.Role):\n ntime = 0.0\n attackInterval = 0.0\n def __init__(self, name, life, speed, blt, ntime=time.time(), attackInterval=1.0):\n super().__init__()\n if speed is None:\n self.speed = [0, 0]\n self.name = name\n self.life = life\n self.speed = speed\n self.blt = blt\n self.ntime = ntime\n self.attackInterval = attackInterval\n\n def updateBullet(self):\n self.blt.repr.center = self.repr.center\n self.blt.jrange = self.blt.repr\n\n def move(self):\n width = combat_width\n height = combat_height*2/3\n if self.repr.left < 0 or self.repr.right > width:\n self.speed[0] *= -1\n if width < self.repr.right < self.repr.right + self.speed[0]:\n self.speed[0] *= -1\n if self.repr.left + self.speed[0] < self.repr.left < 0:\n self.speed[0] *= -1\n if self.repr.bottom > height or self.repr.top < 0:\n self.speed[1] *= -1\n if height < self.repr.bottom < self.repr.bottom + self.speed[1]:\n self.speed[1] *= -1\n if self.repr.top + self.speed[1] < self.repr.top < 0:\n self.speed[1] *= -1\n self.jrange = self.repr = self.repr.move(self.speed[0], self.speed[1])\n self.updateBullet()\n\n\n\n\n\n","sub_path":"Pygame_woke/role/enemy/baseEnemy.py","file_name":"baseEnemy.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"263763586","text":"\"\"\"\nisup.py - Simple website status check with isup.me\nAuthor: Edward Powell http://embolalia.net\nAbout: http://willie.dftba.net\n\nThis allows users to check if a website is up through isup.me.\n\"\"\"\n\nimport willie.web as web\nimport re\n\ndef isup(willie, trigger):\n \"\"\"isup.me website status checker\"\"\"\n site = trigger.group(2)\n if not site:\n return willie.reply(\"What site do you want to check?\")\n uri = 'http://www.isup.me/' + site\n try:\n response = web.get(uri)\n except Exception as e:\n willie.say(site + ' is ' + str(e))\n return\n result = re.search('(?:<title>)(http://\\S* Is )(Down|Up)',\\\n response)\n if result:\n willie.say(site + ' is ' + result.group(2))\n else:\n willie.say('Couldn\\'t read the result from isup.me -- sorry!')\nisup.commands = ['isup']\n","sub_path":"willie/modules/isup.py","file_name":"isup.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"324040805","text":"from backend import anonymizing\nfrom rapport_snippets.figs import *\n\n\ndef compile(output_dir=\"./rapport_snippets/output\"):\n \"\"\"\n Compiles a .tex file for the anonymizing function\n\n Parameters\n ----------\n output_dir : str\n the location to store the .tex with images\n \"\"\"\n make_dir(output_dir)\n epoch_count = {\n 0.25: [1, 10, 100],\n 0.5: [1, 10, 100],\n 0.75: [1, 10, 100],\n }\n\n for color in [True, False]:\n naming = \"color\" if color else \"gray\"\n output_path_location = \"{}/{}/\".format(output_dir, naming)\n path_latex = \"anonymisering/resultat/{}\".format(naming)\n\n make_dir(output_path_location)\n\n anon_obj = anonymizing.Anonymous(\"./files/test_images/lena.png\", color)\n\n results_doc = compile_doc(anon_obj, epoch_count, output_path=output_path_location, path_latex=path_latex)\n results_doc.save(\"{}/resultat.tex\".format(output_path_location))\n\n\ndef compile_faces(output_dir=\"./rapport_snippets/output\"):\n \"\"\"\n Compiles a .tex file for the anonymizing function for the faces image\n\n Parameters\n ----------\n output_dir : str\n the location to store the .tex with images\n \"\"\"\n anon_obj = anonymizing.Anonymous(\"./files/test_images/workshop-photo-small.jpeg\", True)\n anon_obj.save(output_dir + \"mange.png\")\n\n anon_obj.fit(300)\n anon_obj.save(output_dir + \"mange_out.png\")\n\n results_doc = doc()\n results_doc.add_row_element(subfigure(path=\"anonymisering/mange_out.png\", text=\"Bilde med glitch\"))\n results_doc.add_row_element(subfigure(path=\"anonymisering/mange.png\", text=\"Bilde med glitch\"))\n results_doc.add_row()\n results_doc.add_caption(\"Metoden funker også for mange ansikt\")\n results_doc.save(\"{}/resultat.tex\".format(output_dir))\n","sub_path":"src/rapport_snippets/anonymizing.py","file_name":"anonymizing.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"328937627","text":"#!/usr/bin/env python\n#Ryan A. Melnyk\n#schmelnyk@gmail.com\n#UBC Microbiology - Haney Lab\n\nimport os, argparse,re\nfrom Bio import SeqIO\n\ndef parse_args():\n\tparser = argparse.ArgumentParser(description='''\nReplacing the locus tags in the IMG genbank file with accession numbers.\n\t''')\n\tparser.add_argument('strain', type=str,help='strain ID for genomedb files')\n\tparser.add_argument(\"genomedb\",type=str,help='path to genomedb')\n\tparser.add_argument(\"output\",type=str,help=\"\")\n\treturn parser.parse_args()\n\n\ndef get_tags(strain,genomedb):\n\ttags = {}\n\tfor seq in SeqIO.parse(open(os.path.join(genomedb,\"pep\",\"{}.pep.fa\".format(strain)),'r'),'fasta'):\n\t\ttags[seq.description.split()[1]] = seq.id\n\treturn tags\n\ndef replace_names(strain,genomedb,tags,output):\n\to = open(output,'w')\n\tfor line in open(os.path.join(genomedb,\"gbk\",\"{}.gbk\".format(strain)),'r'):\n\t\tvals = line.split()\n\t\tif vals[0].startswith(\"/locus_tag=\\\"\"):\n\t\t\ttry:\n\t\t\t\to.write(line.replace(vals[0].split(\"\\\"\")[1],tags[vals[0].split(\"\\\"\")[1]]))\n\t\t\texcept KeyError:\n\t\t\t\to.write(line)\n\t\telse:\n\t\t\to.write(line)\n\to.close()\n\treturn\n\ndef main():\n\targs = parse_args()\n\tstrain = args.strain\n\tgenomedb = os.path.abspath(args.genomedb)\n\toutput = os.path.abspath(args.output)\n\n\ttags = get_tags(strain,genomedb)\n\n\treplace_names(strain,genomedb,tags,output)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"FixGenbankIMG.py","file_name":"FixGenbankIMG.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"141079276","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'Dean'\r\n\r\nfrom xml.parsers.expat import ParserCreate\r\nfrom datetime import datetime , timedelta\r\nfrom collections import OrderedDict\r\n\r\nclass WeatherSaxHandler(object):\r\n Result = OrderedDict( )\r\n __strToday = ''\r\n __strTomorrow = ''\r\n\r\n def start_element(self, name, attrs):\r\n if 'city' in attrs:\r\n self.Result['city'] = attrs['city']\r\n if 'country' in attrs:\r\n self.Result['country'] = attrs['country']\r\n if name == 'yweather:condition' :\r\n if 'date' in attrs:\r\n today = datetime.strptime( attrs['date'] , '%a, %d %b %Y %I:%M %p %Z')\r\n self.__strToday = today.strftime( '%d %b %Y')\r\n self.__strTomorrow = ( today + timedelta( days = 1 ) ).strftime( '%d %b %Y' )\r\n if name == 'yweather:forecast' :\r\n self.GetWeatherofDay( attrs )\r\n\r\n def end_element(self, name):\r\n pass\r\n\r\n def char_data(self, text):\r\n pass\r\n def GetWeatherofDay( self , attrs ):\r\n if 'date' in attrs:\r\n WeatherVals = OrderedDict( )\r\n if 'text' in attrs:\r\n WeatherVals['text'] = attrs['text']\r\n if 'low' in attrs:\r\n WeatherVals['low'] = int( attrs['low'] )\r\n if 'high' in attrs:\r\n WeatherVals['high'] = int( attrs['high'] )\r\n if 'date' in attrs:\r\n if self.__strToday == attrs['date']:\r\n self.Result['today'] = WeatherVals\r\n elif self.__strTomorrow == attrs['date']:\r\n self.Result['tomorrow'] = WeatherVals\r\n\r\ndate = data = r'''<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\r\n<rss version=\"2.0\" xmlns:yweather=\"http://xml.weather.yahoo.com/ns/rss/1.0\" xmlns:geo=\"http://www.w3.org/2003/01/geo/wgs84_pos#\">\r\n <channel>\r\n <title>Yahoo! Weather - Beijing, CN\r\n Wed, 27 May 2015 11:00 am CST\r\n \r\n \r\n \r\n \r\n \r\n \r\n 39.91\r\n 116.39\r\n Wed, 27 May 2015 11:00 am CST\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n'''\r\ndef parse_weather(xml):\r\n handler = WeatherSaxHandler( )\r\n parser = ParserCreate()\r\n parser.StartElementHandler = handler.start_element\r\n parser.EndElementHandler = handler.end_element\r\n parser.CharacterDataHandler = handler.char_data\r\n parser.Parse( xml )\r\n\r\n return handler.Result\r\n\r\nweather = parse_weather(data)\r\nassert weather['city'] == 'Beijing', weather['city']\r\nassert weather['country'] == 'China', weather['country']\r\nassert weather['today']['text'] == 'Partly Cloudy', weather['today']['text']\r\nassert weather['today']['low'] == 20, weather['today']['low']\r\nassert weather['today']['high'] == 33, weather['today']['high']\r\nassert weather['tomorrow']['text'] == 'Sunny', weather['tomorrow']['text']\r\nassert weather['tomorrow']['low'] == 21, weather['tomorrow']['low']\r\nassert weather['tomorrow']['high'] == 34, weather['tomorrow']['high']\r\nprint('Weather:', str(weather))\r\n","sub_path":"XML作业.py","file_name":"XML作业.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"353713732","text":"import torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nimport torch.utils.data as Data\n\nimport json\nimport os, sys, re\n\nfrom PIL import Image\nimport json, time\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n# from tqdm import tqdm_notebook as tqdm\nfrom random import shuffle\nimport random\nfrom collections import defaultdict\nfrom nltk.tokenize import word_tokenize\nfrom utils import imread\nimport h5py\nRANDOM_SEED = 9001\nann_path = 'data/v2_mscoco_val2014_annotations.json'\nq_path = 'data/v2_OpenEnded_mscoco_val2014_questions.json'\ni_path = 'data/val2014'\ni_prefix = 'COCO_val2014_'\nDEBUG = False\nPP = lambda parsed: print(json.dumps(parsed, indent=4, sort_keys=True))\ndef clean(words):\n # token = re.sub(r'\\W+', '', word)\n tokens = words.lower()\n tokens = word_tokenize(tokens)\n return tokens\n\ndef clean_answer(answer):\n token = re.sub(r'\\W+', '', answer)\n token = clean(token)\n if (len(token)>1): return None\n return token[0]\n\ndef collate_sort_by_q_wrap(dataset):\n def collate_sort_by_q(minibatch):\n max_seq_len = 0\n minibatch.sort(key=lambda minibatch_tuple: minibatch_tuple[-1], reverse=True)\n for row in minibatch:\n idx, v,q,a,l = row\n max_seq_len = max(max_seq_len, l)\n for row in minibatch:\n idx, v,q,a,l = row\n q += [dataset.qtoi[''] for _i in range(max_seq_len-len(q))]\n \n return Data.dataloader.default_collate(minibatch)\n return collate_sort_by_q\n\nclass VQADataSet():\n def __init__(self, ann_path=ann_path, ques_path=q_path, img_path=i_path, \n TEST_SPLIT=0.2, Q=5, one_answer=True):\n t0 = time.time()\n self.one_answer = one_answer\n self.answer_maps = []\n self.question_maps = {}\n self.splits = {'train':[], 'test':[]}\n self.Q = Q\n self.ann_path = ann_path\n self.quest_path = ques_path\n self.img_path = img_path\n\n self.special_tokens = ['','', '', '']\n self.itoa, self.atoi = [], {}\n self.itoq, self.qtoi = [], {}\n self.vocab = {'answer': [] ,'question': []}\n self.max_length = -1\n self.TEST_SPLIT = TEST_SPLIT\n \n self.qdf = None # Panda Frame of questions\n self.anns = None # List of annotations (with answers, quesiton_id, image_id)\n \n ### Load Dataset ###\n q_json = None\n with open(q_path, 'r') as q_f:\n q_json = json.load(q_f);\n self.qdf = pd.DataFrame(q_json['questions'])\n\n with open(ann_path, 'r') as ann_f:\n self.anns = json.load(ann_f)['annotations']\n\n ### Initialize Data ###\n if (self.Q == -1):\n self.Q = len(self.anns)\n self._init_qa_maps()\n self._build_vocab()\n self._encode_qa_and_set_img_path()\n self._randomize_equally_distributed_splits()\n del self.anns\n # if DEBUG:\n print('VQADataSet init time: {}'.format(time.time() - t0))\n \n @staticmethod\n def batchify_questions(q):\n return torch.stack(q).t()\n\n def build_data_loader(self, train=False, test=False, args=None):\n if (args is None):\n args = {'batch_size': 32}\n\n if test:\n args['shuffle'] = False\n elif train:\n args['shuffle'] = True\n batch_size = args['batch_size']\n shuffle = args['shuffle']\n print('batch_size: {} shuffle: {}'.format(batch_size, shuffle))\n data_loader_split = VQADataLoader(self, train=train, test=test)\n data_generator = Data.DataLoader(dataset=data_loader_split, \n batch_size=batch_size, \n shuffle=shuffle,\n collate_fn=collate_sort_by_q_wrap(self))\n return data_generator\n\n # set qdf, question_maps\n def _init_qa_maps(self):\n cnt = 0 \n for ann_idx in tqdm(range(self.Q)):\n ann = self.anns[ann_idx];\n answer_set = set()\n answers = []\n question_id = ann['question_id']\n for ans in ann['answers']:\n ans_text = ans['answer']\n \n ans_tokens = clean(ans_text)\n if (len(ans_tokens) != 1): continue\n ans_text = ans_tokens[0] \n if ans_text not in answer_set:\n ans['question_id'] = question_id\n answers.append(ans)\n answer_set.add(ans_text)\n if (self.one_answer):\n break\n \n if (len(answers) == 0): continue\n question = self.qdf.query('question_id == {}'.format(question_id))\n\n self.answer_maps += answers\n self.question_maps[question_id] = question.to_dict(orient='records')[0]\n\n if (cnt >= self.Q): break\n cnt+=1\n\n def _build_vocab(self):\n q_vocab = set()\n a_vocab = set()\n if DEBUG: print('build answer vocab')\n for ann in tqdm(self.answer_maps):\n answer = ann['answer']\n # answer_tokens = clean(answer)\n # ann['tokens'] = answer_tokens\n ann['tokens'] = [answer]\n a_vocab.add(answer)\n if DEBUG: print('build question vocab)')\n for question_id, question_json in tqdm(self.question_maps.items()):\n question = question_json['question']\n question_tokens = clean(question)\n question_json['tokens'] = [\"\"] + question_tokens + [\"\"]\n self.max_length = max(len(question_json['tokens']), self.max_length)\n q_vocab = q_vocab.union(set(question_tokens))\n \n q_vocab_list = self.special_tokens + list(q_vocab)\n a_vocab_list = list(a_vocab)\n\n self.vocab['answer'] = a_vocab_list\n self.vocab['question'] = q_vocab_list\n self.itoq = self.vocab['question']\n self.itoa = self.vocab['answer']\n self.qtoi = {q: i for i,q in enumerate(q_vocab_list)}\n self.atoi = {a: i for i,a in enumerate(a_vocab_list)}\n \n def _encode_qa_and_set_img_path(self):\n if DEBUG: print('encode answers')\n for ann in tqdm(self.answer_maps):\n a_tokens = ann['tokens']\n ann['encoding'] = [self.atoi[w]for w in a_tokens]\n if DEBUG: print('encode questions')\n for question_id, question_json in tqdm(self.question_maps.items()):\n image_id = question_json['image_id']\n q_tokens = question_json['tokens']\n question_json['encoding'] = [self.qtoi[w] for w in q_tokens]\n question_json['image_path'] = self._img_id_to_path(str(image_id))\n \n def _img_id_to_path(self, img_id):\n eg = '000000000192'\n total = len(eg)\n full_img_id = '0'*(total-len(img_id)) + img_id\n img_f = i_path + \"/\" + i_prefix + full_img_id + \".jpg\"\n img_f = img_f.strip()\n return img_f\n\n def _randomize_equally_distributed_splits(self):\n cntr = defaultdict(int)\n dist = defaultdict(list)\n for i, ann in enumerate(self.answer_maps):\n ans = ann['answer']\n cntr[ans]+=1\n dist[ans].append(i)\n\n splits = {'train': [], 'test': []}\n z_cnt = 0\n for ans, idxes in tqdm(dist.items()):\n random.Random(RANDOM_SEED).shuffle(idxes)\n c = int(len(idxes)*self.TEST_SPLIT)\n splits['train'] += idxes[c:]\n splits['test'] += idxes[:c]\n sorted(splits['train'])\n sorted(splits['test'])\n self.splits = splits\n\n def __len__(self):\n return len(self.answer_maps)\n\n def get(self, idx, split_type):\n v,q,a = None, None, None\n try:\n split_keys = self.splits[split_type]\n ans_key = split_keys[idx]\n answer_json = self.answer_maps[ans_key]\n question_key = answer_json['question_id']\n question_json = self.question_maps[question_key]\n except:\n print(\"ERR\")\n return question_json, answer_json\n \n def size(self):\n return (len(self.question_maps), len(self.answer_maps))\n\n def get_max_sequence_len(self):\n return self.max_length\n\n def decode_question(self, encoding):\n for x in encoding:\n if x < 0 or x >= len(self.itoq):\n raise Exception(\"DECODE_ERR: cannot find word-idx: {}\".format(x))\n sen_vec = [self.itoq[x] for x in encoding]\n sen = \" \".join(sen_vec)\n return sen\n \n def decode_answer(self, encoding):\n if encoding < 0 or encoding >= len(self.itoa):\n raise Exception(\"DECODE_ERR: cannot find word-idx: {}\".format(encoding))\n return self.itoa[encoding] \n\nclass VQADataLoader(data.Dataset):\n def __init__(self, dataset, train=False, test=False):\n assert(train+test==1)\n split_type = None\n if train: split_type = 'train'\n elif test: split_type = 'test'\n self.split_keys = dataset.splits[split_type]\n self.dataset = dataset\n self.split_type=split_type\n\n def __len__(self):\n return len(self.split_keys)\n \n '''\n Returns:\n v: torch.Size([BATCH_SIZE, 3, 224, 224])\n q: [tensor(a_0, a_1,...), tensor(a_0..)]\n a: tensor([ans_1, ans_2,...])\n q_len: tensor([len_1, len_2,...])\n,\n '''\n def __getitem__(self, idx):\n v,q,a = -1, -1, -1\n try:\n question_json, answer_json = self.dataset.get(idx, self.split_type)\n img_path = question_json['image_path']\n v = imread(img_path)\n q = question_json['encoding']\n a = answer_json['encoding'][0]\n q_len = len(q)\n except Exception as e:\n print(\"DATALOAD-ERR: \" + str(e))\n return idx, v, q, a, q_len\n \n\n \nif __name__ == '__main__':\n print(\"hello\")\n\n","sub_path":"S19 VQA/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":9971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"386417842","text":"\"\"\"\nDjango settings for shop project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '77@x5g%!ukshsy0bwo77@c6c)-kyetvk^)xitt7qa2++2i#7wv'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nTEMPLATE_DIRS = (\n BASE_DIR + '/shop/templates/',\n)\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'grappelli',\n 'rest_framework',\n 'sorl.thumbnail',\n 'topnotchdev.files_widget',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'commerce',\n 'djangobower',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'shop.urls'\n\nWSGI_APPLICATION = 'shop.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.db'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'fa-ir'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nLOCALE_PATHS = (\n os.path.join(BASE_DIR, 'shop/locale'),\n)\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATICFILES_DIRS = (\n BASE_DIR + \"/static\",\n os.path.join(BASE_DIR, \"shop\", \"templates\", \"front\"),\n)\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'djangobower.finders.BowerFinder',\n)\n\nBOWER_COMPONENTS_ROOT = BASE_DIR + '/static/'\n\nBOWER_INSTALLED_APPS = (\n 'bootstrap-rtl',\n)\n\nMEDIA_URL = '/static/media/'\nMEDIA_ROOT = BASE_DIR + '/static/media/'\nTHUMBNAIL_DEBUG = False\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ],\n\n # 'DEFAULT_RENDERER_CLASSES': (\n # 'rest_framework.renderers.JSONRenderer',\n # ),\n\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework.parsers.JSONParser',\n )\n}\n\nGRAPPELLI_ADMIN_TITLE = 'Shop Administration'","sub_path":"shop/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"34701890","text":"import os\nimport time\nfrom config import *\nfrom random import *\n\n\nclass background:\n def __init__(self):\n self.arr = [' '] * r\n for i in range(r):\n self.arr[i] = [' '] * c\n for i in range(c):\n self.arr[17][i] = \"_\"\n if i % 4 != 0:\n self.arr[18][i] = \"_\"\n else:\n self.arr[18][i] = \"|\"\n if i % 4 != 2:\n self.arr[19][i] = \"_\"\n else:\n self.arr[19][i] = \"|\"\n self.arr[0][i] = \"*\"\n self.arr[21][i] = \"*\"\n self.arr[14][2000] = '<'\n self.arr[15][2000] = '|'\n self.arr[16][2000] = '|'\n self.arr[17][2000] = '|'\n for i in range(10):\n j = enemy_pos[i] - 21\n for k in range(2):\n self.arr[15][j - k] = '='\n self.arr[16][j - k] = '|'\n self.arr[17][j - k] = '_'\n h = enemy_pos[i] + 2\n for l in range(2):\n self.arr[15][h - l] = '='\n self.arr[16][h - l] = '|'\n self.arr[17][h - l] = '_'\n for j in range(4):\n for i in range(6):\n self.arr[17][trench[j] + i] = ' '\n self.arr[18][trench[j] + i] = ' '\n self.arr[19][trench[j] + i] = ' '\n for j in range(12):\n for i in range(10):\n self.arr[14][obs[j] + i] = brick[i]\n if(i % randint(1, 5)):\n self.arr[13][obs[j] + i] = '0'\n for j in range(12):\n for k in range(4):\n for i in range(12):\n self.arr[k + 2][cl[j] + i] = clouds[k][i]\n for j in range(12):\n for k in range(3):\n for i in range(11):\n self.arr[k + 3][cl2[j] + i] = clouds2[k][i]\n for j in range(4):\n for k in range(3):\n for i in range(9):\n self.arr[k + 3][s[j] + i] = sun[k][i]\n\n def print_back(self, pos, bd):\n for i in range(22):\n for j in range(pos, pos + 100):\n if(bd.arr[i][j] == '*'):\n print('\\033[31m' + bd.arr[i][j], end=\"\")\n elif(bd.arr[i][j] == '0'):\n print('\\033[33m' + bd.arr[i][j], end=\"\")\n elif(bd.arr[i][j] == \"::\" or bd.arr[i][j] == \"||\" or bd.arr[i][j] == \"/\\\\\"):\n print('\\033[32m' + bd.arr[i][j], end=\"\")\n elif(bd.arr[i][j] == '<' or bd.arr[i][j] == '@'):\n print('\\033[34m' + bd.arr[i][j], end=\"\")\n elif(bd.arr[i][j] == '='):\n print('\\033[35m' + bd.arr[i][j], end=\"\")\n else:\n print('\\033[37m' + bd.arr[i][j], end=\"\")\n print()\n","sub_path":"background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"370747246","text":"import datetime\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.test import TestCase, override_settings, SimpleTestCase, tag, RequestFactory\nfrom django.urls import reverse\nfrom django.conf import settings\n\nfrom django.utils.timezone import now\nfrom extended_choices.helpers import ChoiceEntry\nfrom factory.django import DjangoModelFactory\nfrom factory.fuzzy import FuzzyChoice\nfrom freezegun import freeze_time\nfrom rest_framework.exceptions import ValidationError\n\nfrom alice.tests.client import AliceClient\nfrom csvfiles.constants import FILE_TYPES\nfrom csvfiles.serializers import FileTypeChoiceField, MetadataField, FileSerializer\nfrom csvfiles.validators import is_valid_s3_url\nfrom csvfiles.views import CSVBaseView, CSVFileView, PingdomCustomCheckView\nfrom users.factories import UserFactory\n\nfrom users.models import User\n\n\nclass FileFactory(DjangoModelFactory):\n\n file_type = FuzzyChoice([x[0] for x in FILE_TYPES])\n\n class Meta:\n model = 'csvfiles.File'\n\n\nclass CSVUploadPermissionTestCase(TestCase):\n\n VALID_BUCKET = settings.AWS_BUCKET_CSV\n VALID_S3_PATH = 's3://{}/export-wins/2017/11/2017-11-01T15:11:42.566651+00:00.csv'.format(\n VALID_BUCKET)\n\n def setUp(self):\n self.alice_client = AliceClient()\n\n def _login(self, is_staff=False):\n normal_user = User.objects.create_user(\n name='dummy', password=\"dummy\", email='dummy@dummy.com', is_staff=is_staff)\n self.alice_client.force_login(\n normal_user, 'django.contrib.auth.backends.ModelBackend')\n\n def _admin_login(self):\n admin_user = User.objects.create_superuser(\n name='admin', password=\"dummy\", email='admin@dummy.com')\n self.alice_client.force_login(\n admin_user, 'django.contrib.auth.backends.ModelBackend')\n\n @override_settings(ADMIN_SECRET=AliceClient.SECRET)\n def test_csv_upload_allowed_admin_secret(self):\n self._admin_login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': self.VALID_S3_PATH})\n self.assertEqual(response.status_code, 201)\n\n @override_settings(MI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_mi_secret(self):\n self._admin_login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(UI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_ui_secret(self):\n self._admin_login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(ADMIN_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_admin_secret_but_non_staff_normal_user(self):\n self._login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(ADMIN_SECRET=AliceClient.SECRET)\n def test_csv_upload_allowed_admin_secret_but_staff_normal_user(self):\n self._login(is_staff=True)\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': self.VALID_S3_PATH})\n self.assertEqual(response.status_code, 201)\n\n @override_settings(MI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_mi_secret_non_staff_normal_user(self):\n self._login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(UI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_ui_secret_non_staff_normal_user(self):\n self._login()\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(MI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_mi_secret_staff_normal_user(self):\n self._login(is_staff=True)\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n @override_settings(UI_SECRET=AliceClient.SECRET)\n def test_csv_upload_not_allowed_ui_secret_staff_normal_user(self):\n self._login(is_staff=True)\n upload_url = reverse(\"csv:ew_csv_upload\")\n response = self.alice_client.post(\n upload_url, data={'path': 'dummy path'})\n self.assertEqual(response.status_code, 403)\n\n\nGOOD_FILE_TYPE = 'EXPORT_WINS'\nFROZEN_DATE = now()\n\n\nclass CSVFileBaseViewTestCase(SimpleTestCase):\n\n def test_bad_filetype(self):\n with self.assertRaises(ValueError):\n CSVBaseView.as_view(file_type='foo')\n\n f = CSVBaseView.as_view(file_type=GOOD_FILE_TYPE)\n self.assertEqual(f.view_initkwargs['file_type'], GOOD_FILE_TYPE)\n\n def test_filetype_kwarg_resolves_to_correct_choices_object(self):\n view = CSVBaseView(file_type=GOOD_FILE_TYPE)\n self.assertIsInstance(view.file_type_choice, ChoiceEntry)\n self.assertEqual(view.file_type_choice.constant, GOOD_FILE_TYPE)\n\n\nclass AuthenticatedRequestFactoryMixin():\n\n factory = RequestFactory()\n\n def req(self, path='/', user=None):\n request = self.factory.get(path)\n request.user = user or UserFactory()\n return request\n\n\n@freeze_time(FROZEN_DATE)\nclass CSVFileViewTestCase(AuthenticatedRequestFactoryMixin, TestCase):\n\n def test_immutable_data(self):\n request = self.req()\n view = CSVFileView(file_type=GOOD_FILE_TYPE, request=request)\n self.assertEqual({'user': request.user.id}, view.immutable_data())\n\n def test_immutable_data_no_user(self):\n request = self.req(user=AnonymousUser())\n view = CSVFileView(file_type=GOOD_FILE_TYPE, request=request)\n self.assertEqual({}, view.immutable_data())\n\n def test_default_data(self):\n request = self.req()\n view = CSVFileView(file_type=GOOD_FILE_TYPE, request=request)\n self.assertEqual({\n 'file_type': FILE_TYPES[GOOD_FILE_TYPE].constant,\n 'name': FILE_TYPES[GOOD_FILE_TYPE].display,\n 'report_start_date': FROZEN_DATE,\n 'report_end_date': FROZEN_DATE\n }, view.default_data())\n\n\n@tag('csvfiles', 'validation')\nclass CSVFileValidatorsTestCase(SimpleTestCase):\n\n @override_settings(AWS_BUCKET_CSV='foo')\n def test_is_valid_s3_url_is_valid(self):\n # will not raise validation error if input is ok\n self.assertEqual(None, is_valid_s3_url(\"s3://foo/bar\"))\n\n @override_settings(AWS_BUCKET_CSV='foo')\n def test_is_valid_s3_url_is_not_valid(self):\n with self.assertRaises(ValidationError):\n is_valid_s3_url(\"http://foo/bar\")\n\n @override_settings(AWS_BUCKET_CSV='foo')\n def test_is_valid_s3_url_is_not_valid_mismatch_bucket(self):\n with self.assertRaises(ValidationError) as ve:\n self.assertEqual(None, is_valid_s3_url(\"s3://bar/foo\"))\n ve.msg.contains('bucket')\n\n\n@tag('csvfiles', 'field')\nclass CSVFileSerializerFieldTestCase(SimpleTestCase):\n\n choices = (\n (1, 'test1'),\n (2, 'test2')\n )\n\n def test_file_type_choice_field(self):\n f = FileTypeChoiceField(self.choices)\n self.assertEqual('test1', f.to_representation(1))\n\n def test_file_type_choice_field_blank_value(self):\n f = FileTypeChoiceField(self.choices)\n self.assertEqual('', f.to_representation(''))\n\n def test_file_type_choice_field_null_value(self):\n f = FileTypeChoiceField(self.choices)\n self.assertEqual(None, f.to_representation(None))\n\n def test_file_type_choice_field_bad_value(self):\n f = FileTypeChoiceField(self.choices)\n with self.assertRaises(KeyError):\n f.to_representation(3)\n\n def test_metadata_field(self):\n f = MetadataField(metadata_keys=['a', 'b'])\n self.assertEqual({'a': 1, 'b': 2}, f.get_value(\n {'a': 1, 'b': 2, 'c': 3}))\n\n def test_metadata_field_subset_keys_in_dict(self):\n f = MetadataField(metadata_keys=['a', 'b'])\n self.assertEqual({'b': 2}, f.get_value({'b': 2, 'c': 3}))\n\n def test_metadata_field_no_subset_keys_in_dict(self):\n f = MetadataField(metadata_keys=['q', 'z'])\n self.assertEqual(None, f.get_value({'b': 2, 'c': 3}))\n\n def test_metadata_not_required_field(self):\n f = MetadataField(metadata_keys=['q', 'z'], required=False)\n self.assertEqual({}, f.get_value({}))\n\n\n@tag('csvfiles', 'serializer')\nclass CSVFileSerializerTestCase(TestCase):\n\n @override_settings(AWS_BUCKET_CSV='foo')\n def test_fileserializer(self):\n fs = FileSerializer(data={\n 'file_type': 'EXPORT_WINS',\n 'path': 's3://foo/bar'\n })\n self.assertTrue(fs.is_valid())\n self.assertEqual({}, fs.errors)\n self.assertEqual({\n 's3_path': 's3://foo/bar',\n 'file_type': 1,\n 'metadata': {}\n }, dict(fs.validated_data))\n\n\n@tag('csvfiles')\n@freeze_time(FROZEN_DATE)\nclass PingdomViewTestCase(TestCase):\n\n expected_keys = {'status', 'response_time', 'last_uploaded'}\n\n def assertKeys(self, data):\n self.assertEqual(set(data.keys()), self.expected_keys)\n\n def test_files_notok_because_none_ever_uploaded(self):\n v = PingdomCustomCheckView()\n data = v.get_context_data()\n self.assertKeys(data)\n self.assertEqual('NOT OK', data['status'])\n\n def test_files_ok(self):\n for ft_id, ft_const in FILE_TYPES:\n with self.subTest(file_type=ft_id, constant=ft_const):\n f = FileFactory(created=now(), file_type=ft_id)\n v = PingdomCustomCheckView()\n data = v.get_context_data()\n self.assertKeys(data)\n expected_status = 'OK' if ft_id in v._get_filtered_filetypes else 'NOT OK'\n self.assertEqual(expected_status, data['status'], msg=data)\n # it's a subTest so clean up after ourselves\n f.delete()\n\n def test_files_notok_too_old(self):\n v = PingdomCustomCheckView()\n yesterday_time = now() - datetime.timedelta(seconds=v.error_after_seconds + 1)\n f = FileFactory(file_type=2)\n f.created = yesterday_time\n f.save()\n data = v.get_context_data()\n self.assertKeys(data)\n self.assertEqual('NOT OK', data['status'], msg=data)\n\n def test_files_notok_wrong_type_uploaded(self):\n v = PingdomCustomCheckView()\n f = FileFactory(file_type=1)\n f.save()\n data = v.get_context_data()\n self.assertKeys(data)\n self.assertEqual('NOT OK', data['status'], msg=data)\n","sub_path":"csvfiles/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":11179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"221977249","text":"# -*- coding: utf-8 -*-\n__author__ = 'lz31'\n\nfrom log.loggerwrapper import get_logger\nimport http.client\nimport redis\nimport urllib.parse\n\nwarm_up_connection_list = [{'hostAndPort': 'localhost:8501', 'timeout': 10, 'method': 'PUT', 'url': '/cowbird-deploy/v1/keyword?keyword=%s&boost=true&synonyms=true&format=true'}]\nwarm_up_redis_list = [{'host':'10.16.40.61', 'port':8800, 'dbindex':43}]\n\nlog = get_logger('warmup.py')\n\ndef get_keyword():\n\n result = []\n for redis_conf in warm_up_redis_list:\n\n if not redis_conf.__contains__('host'):\n continue\n host = redis_conf['host']\n\n if not redis_conf.__contains__('port'):\n continue\n port = redis_conf['port']\n\n if not redis_conf.__contains__('dbindex'):\n continue\n db_index = redis_conf['dbindex']\n\n redis_connection = redis.StrictRedis(host=host, port=port, db=db_index, charset='utf-8')\n\n cursor = 0\n scan = redis_connection.scan(cursor)\n cursor = scan[0]\n while cursor != 0:\n\n result += scan[1]\n scan = redis_connection.scan(cursor)\n cursor = scan[0]\n\n if len(scan) >1 and len(scan[1]) > 0:\n result += scan[1]\n\n return result\n\n\n\ndef request(client, m, u):\n try:\n client.request(m, u)\n return client.getresponse()\n except Exception as exception:\n log.error(exception)\n\ndef warm_up():\n\n for warn_up_connection_map in warm_up_connection_list:\n\n if not warn_up_connection_map.__contains__('hostAndPort'):\n continue\n host_and_port = warn_up_connection_map['hostAndPort']\n\n if not warn_up_connection_map.__contains__('method'):\n continue\n method = warn_up_connection_map['method']\n\n if not warn_up_connection_map.__contains__('url'):\n continue\n url = warn_up_connection_map['url']\n\n timeout = 5;\n if warn_up_connection_map.__contains__('timeout'):\n timeout = warn_up_connection_map['timeout']\n\n\n http_client = http.client.HTTPConnection(host_and_port, timeout=timeout)\n try:\n keyword_list = get_keyword()\n if keyword_list is not None:\n for keyword in keyword_list:\n try :\n r = request(http_client, method, url%urllib.parse.quote(keyword))\n s = r.read().decode('utf-8')\n log.info(s)\n except Exception as e2:\n log.error(e2)\n except Exception as e:\n log.error(e)\n finally:\n http_client.close()\n","sub_path":"warmup/warmup.py","file_name":"warmup.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"600875012","text":"def check_bad_revision(n):\n n_list = list(range(n))\n return n_list\n\n\nprint(check_bad_revision(4)) # [0, 1, 2, 3]\n\n\n# call a method from another method\n\ndef add(a, b):\n return a + b\n\ndef calculate(x, y, operation=\"add\"):\n if operation == \"add\":\n print(add(x, y))\n elif operation == \"multiply\":\n print(x * y)\n else:\n print(\"try another operation\")\n\n\n\n# merge intervals\n\n\nxyz = [1, 2, 4, 8]\n\nprint(xyz[-1]) #8\nprint(xyz[-2]) #4\n\n\na = [[2, 6], [1, 3], [15, 18], [8, 10]]\n\n\ndef merge(arr):\n solution = []\n\n # k is every individual list ... sorting by the first index\n\n for i in sorted(a, key=lambda k: k[0]):\n # on the first try there is nothing in the list so just append the first list\n # -1 is the last index (list) of the solution\n if solution != [] and i[0] <= solution[-1][1]:\n # ^that is the 0th index of a specific list\n solution[-1][1] = max(i[1], solution[-1][1])\n # taking the last element of the solution set, and changing the boundary\n # b/c we sorted the first element\n else:\n solution.append(i)\n\n return solution\n\n\nprint(merge(a))\n\n# first interation\n # solution = [[1, 3]]\n\n# second interation\n # can only have something greater than or equal to 1\n\n\nmy_list = list(range(1, 10))\nprint(my_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\n# \\d is a number\n# \\w is any alphanumeric\n# [a-z] is a character class, /w without numbers\n# [A-Za-z] # no delimiting\n# + a plus is needed if you want multiple matches, without the + it only returns the first instance\n# * if it's possible for no matches\n# ^ .... $\n# ^ means the start .... ^/d+$ ... means must start and end with a number\n# $ means the end\n# [^a-z] when in a character class the ^ means 'not' ... in this case matches when doesn't start with a-z\n# () gives you groups\n\nimport re\n\ndef computeGains(holdings, trades):\n portfolio = {}\n gains_report = []\n\n for h in holdings:\n # 4 AAPL valued $100 each\n regex = re.match(r'^(\\d+) (\\w+) valued \\$(\\d+) each$', h)\n quantity, symbol, price = int(regex.group(1)), regex.group(2), int(regex.group(3))\n portfolio[symbol] = quantity * price\n\n for t in trades:\n regex = re.match(r'^(\\w+) (\\d+) (\\w+) at \\$(\\d+)$', t)\n side, quantity, symbol, price = regex.group(1), int(regex.group(2)), regex.group(3), int(regex.group(4))\n if symbol not in portfolio:\n portfolio[symbol] = 0\n if side == 'bought':\n portfolio[symbol] -= quantity * price\n else:\n portfolio[symbol] += quantity * price\n\n total = sum(portfolio.values())\n gains_report.append('Total $%d' % total)\n portfolio = reversed(sorted(portfolio.items(), key=lambda p: p[1]))\n for item in portfolio:\n if item[1] >= 0:\n gains_report.append('%s $%d' % (item[0], item[1]))\n else:\n gains_report.append('%s -$%d' % (item[0], abs(item[1])))\n return gains_report\n\n\n\n# delete the key with the highest value\nsample1 = {'A': 100, 'B': 10, 'C': 55, 'Z': 3}\nkey_to_delete = max(sample1, key=lambda k: sample1[k])\ndel sample1[key_to_delete]\nprint(sample1)\n\n\n# camel case strings\n# foo_bar => fooBar\n\nsample2 = \"frank\"\n\ndef capitilzeFirstLetter(word):\n word = word[0].upper() + word[1:]\n return word\n\n# print(capitilzeFirstLetter(sample2))\n\nsample3 = \"hey_how_are_you\"\n\ndef camelCase(input_sentence):\n sentence = input_sentence.split(\"_\")\n transform = [capitilzeFirstLetter(w) for w in sentence]\n # without the brackets (w) throws a syntax error\n result = \" \".join(transform)\n return result\n\nprint(camelCase(sample3))\n","sub_path":"Basic/general1.py","file_name":"general1.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"7538244","text":"# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom unittest import mock\n\nfrom servicecatalog_puppet.workflow import tasks_unit_tests_helper\n\n\nclass LambdaInvocationTaskTest(tasks_unit_tests_helper.PuppetTaskUnitTest):\n lambda_invocation_name = \"lambda_invocation_name\"\n manifest_file_path = \"manifest_file_path\"\n puppet_account_id = \"puppet_account_id\"\n should_use_sns = False\n\n def setUp(self) -> None:\n from servicecatalog_puppet.workflow.lambda_invocations import (\n lambda_invocation_task,\n )\n\n self.module = lambda_invocation_task\n\n self.sut = self.module.LambdaInvocationTask(\n lambda_invocation_name=self.lambda_invocation_name,\n manifest_file_path=self.manifest_file_path,\n puppet_account_id=self.puppet_account_id,\n )\n\n self.wire_up_mocks()\n\n def test_params_for_results_display(self):\n # setup\n expected_result = {\n \"puppet_account_id\": self.puppet_account_id,\n \"lambda_invocation_name\": self.lambda_invocation_name,\n \"cache_invalidator\": self.cache_invalidator,\n }\n\n # exercise\n actual_result = self.sut.params_for_results_display()\n\n # verify\n self.assertEqual(expected_result, actual_result)\n\n def test_run(self):\n # setup\n # exercise\n self.sut.run()\n\n # verify\n self.assert_output(self.sut.params_for_results_display())\n\n @mock.patch(\n \"servicecatalog_puppet.workflow.manifest.manifest_mixin.ManifestMixen.manifest\"\n )\n def test_requires(self, manifest_mock):\n # setup\n requirements = list()\n\n klass = self.sut.get_klass_for_provisioning()\n for (\n account_id,\n regions,\n ) in self.sut.manifest.get_account_ids_and_regions_used_for_section_item(\n self.sut.puppet_account_id,\n self.sut.section_name,\n self.sut.lambda_invocation_name,\n ).items():\n for region in regions:\n for (\n task\n ) in self.sut.manifest.get_tasks_for_launch_and_account_and_region(\n self.sut.puppet_account_id,\n self.sut.section_name,\n self.sut.lambda_invocation_name,\n account_id,\n region,\n ):\n requirements.append(\n klass(**task, manifest_file_path=self.sut.manifest_file_path)\n )\n\n expected_result = requirements\n\n # exercise\n actual_result = self.sut.requires()\n\n # assert\n self.assertEqual(expected_result, actual_result)\n","sub_path":"servicecatalog_puppet/workflow/lambda_invocations/lambda_invocation_task_test.py","file_name":"lambda_invocation_task_test.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"291805661","text":"from __future__ import unicode_literals\n\nfrom clients.models import User, Company\nfrom sandwiches.models import Allergen, IngredientGroup, Ingredient, Sandwich\nfrom orders.models import Order, OrderSandwiches, OrderStatus\nimport csv\n\n\nclass DbManager:\n\n allergens_csv_name = \"doc/demo_data_in_csv/allergens.csv\"\n clients_csv_name = \"doc/demo_data_in_csv/clients.csv\"\n ingredient_groups_csv_name = \"doc/demo_data_in_csv/ingredient_groups.csv\"\n ingredients_csv_name = \"doc/demo_data_in_csv/ingredients.csv\"\n sandwiches_csv_name = \"doc/demo_data_in_csv/sandwiches.csv\"\n companies_csv_name = \"doc/demo_data_in_csv/companies.csv\"\n sandwich_images_path = \"/sandwiches/images/{}\"\n allergen_images_path = \"/allergens/images/{}\"\n\n def import_allergens(self):\n with open(self.allergens_csv_name, encoding=\"utf-8\") as allergens_csv_file:\n csv_reader = csv.reader(allergens_csv_file, delimiter=',')\n for name, image_filename in csv_reader:\n allergen = Allergen()\n allergen.name = name\n allergen.image = \"/allergens/images/{}\".format(image_filename)\n allergen.save()\n\n def import_ingredient_groups(self):\n with open(self.ingredient_groups_csv_name, encoding=\"utf-8\") as ingredient_groups_csv_file:\n csv_reader = csv.reader(ingredient_groups_csv_file, delimiter=',')\n for name in csv_reader:\n ingredient_group = IngredientGroup()\n ingredient_group.name = name[0]\n ingredient_group.save()\n\n def import_ingredients(self):\n with open(self.ingredients_csv_name, encoding=\"utf-8\") as ingredients_csv_file:\n csv_reader = csv.reader(ingredients_csv_file, delimiter=',')\n for name, ingredient_group_name, calories_per_portion, portion_size_grams, price, allergen_names in csv_reader:\n ingredient = Ingredient()\n ingredient.name = name\n ingredient.group = IngredientGroup.objects.get(name=ingredient_group_name)\n ingredient.calories_per_portion = calories_per_portion\n ingredient.portion_size_grams = portion_size_grams\n ingredient.price = price\n ingredient.save()\n allergen_list = allergen_names.split(\"|\")\n for allergen_name in allergen_list:\n allergen_name = allergen_name.strip()\n if allergen_name:\n if Allergen.objects.filter(name=allergen_name).exists():\n allergen = Allergen.objects.get(name=allergen_name)\n ingredient.allergen.add(allergen)\n ingredient.save()\n\n def import_sandwiches(self):\n with open(self.sandwiches_csv_name, encoding=\"utf-8\") as sandwiches_csv_file:\n csv_reader = csv.reader(sandwiches_csv_file, delimiter=',')\n for name, price, accessible, image_filename, ingredient_names in csv_reader:\n sandwich = Sandwich()\n sandwich.name = name\n sandwich.price = price\n sandwich.accessible = accessible\n sandwich.image = \"/sandwiches/images/{}\".format(image_filename)\n sandwich.save()\n ingredient_list = ingredient_names.split(\"|\")\n for ingredient_name in ingredient_list:\n ingredient_name = ingredient_name.strip()\n if Ingredient.objects.filter(name=ingredient_name).exists():\n ingredient = Ingredient.objects.get(name=ingredient_name)\n sandwich.ingredients.add(ingredient)\n sandwich.save()\n\n def import_companies(self):\n with open(self.companies_csv_name, encoding=\"utf-8\") as companies_csv_file:\n csv_reader = csv.reader(companies_csv_file, delimiter=',')\n for name, address in csv_reader:\n company = Company()\n company.name = name\n company.address = address\n company.save()\n\n def import_clients(self):\n with open(self.clients_csv_name, encoding=\"utf-8\") as clients_csv_file:\n csv_reader = csv.reader(clients_csv_file, delimiter=',')\n for email, name, surname, active, company_name, staff, admin in csv_reader:\n client = User()\n client.email = email\n client.name = name\n client.surname = surname\n if staff in ['True', 'true']:\n client.set_password('admin')\n else:\n client.set_password('user')\n client.active = active\n company = Company.objects.get(name=company_name)\n client.group = company\n client.staff = staff\n client.save()\n\n def create_statuses(self):\n statuses = ['W koszyku', 'Potwierdzone', 'Anulowane', 'Zrealizowane']\n for status_name in statuses:\n status = OrderStatus()\n status.status = status_name\n status.save()\n\n def delete_orders(self):\n Order.objects.all().delete()\n OrderSandwiches.objects.all().delete()\n OrderStatus.objects.all().delete()\n\n def delete_clients(self):\n User.objects.all().delete()\n #User.objects.exclude(email=\"admin@kanapka.com\").delete()\n\n def delete_companies(self):\n Company.objects.all().delete()\n\n def delete_allergens(self):\n Allergen.objects.all().delete()\n\n def delete_ingredients(self):\n Ingredient.objects.all().delete()\n\n def delete_ingredient_groups(self):\n IngredientGroup.objects.all().delete()\n\n def delete_sandwiches(self):\n Sandwich.objects.all().delete()\n\n def delete_all(self):\n self.delete_orders()\n self.delete_clients()\n self.delete_companies()\n self.delete_allergens()\n self.delete_ingredients()\n self.delete_ingredient_groups()\n self.delete_sandwiches()","sub_path":"PanKanapka/tools/csv2db.py","file_name":"csv2db.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"629775231","text":"#-*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport xlrd\r\nimport matplotlib.pyplot as pl\r\n\r\n \r\n# Use numpy to load the data contained in the file\r\n\r\n# ’mof5.txt’ into a 2-D array called data\r\n\r\n# import the data\r\ndata = xlrd.open_workbook('RMSD.xlsx')\r\ntable = data.sheet_by_name('Sheet1')\r\n# get values\r\nx1 = table.col_values(0)\r\ny1 = table.col_values(1)\r\n#y2 = table.col_values(2)\r\n#y3 = table.col_values(3)\r\n#y4 = table.col_values(4)\r\n#y5 = table.col_values(5)\r\n\r\n# drop the 1st line of the data, which is the name of the data\r\nx1.pop(0)\r\ny1.pop(0)\r\n#y2.pop(0)\r\n#y3.pop(0)\r\n#y5.pop(0)\r\n#y4.pop(0)\r\n \r\n# plot the first column as x, and second column as y\r\n\r\np1=pl.plot(x1, y1,'r-',label='Complex')# use pylab to plot x and y\r\n#p1=pl.plot(x1, y2,'k-',label='$espilon_{1zz}$')# use pylab to plot x and y\r\n#p1=pl.plot(x1, y3,'bo-',label='N2/273K Ads')\r\n#p1=pl.plot(x1, y5,'yv-',label='CH3CH2OH/273K Ads')\r\n#p1=pl.plot(x1, y4,'k*-',label='H2O/273K Ads')\r\n\r\n\r\n\r\npl.title('pure-$Bi_2O_3$',color=\"w\",fontweight=\"bold\", fontsize=10)# give plot a title\r\npl.ylabel('RMSD(Angstrom)',fontweight=\"bold\", fontsize=10)# make axis labels\r\npl.xlabel('t(ps)',fontweight=\"bold\", fontsize=10)\r\npl.subplots_adjust(left=0.18, bottom=None, right=None, top=None, wspace=None, hspace=None)\r\n#pl.xlim(50, 800)# set axis limits\r\n#pl.ylim(0.0, 1.0)\r\npl.legend(loc = 0)# make legend\r\n#pl.show()# show the plot on the screen\r\npl.savefig('RMSD.png',dpi = 600)\r\n\r\n","sub_path":"python/RMSD/RMSD.py","file_name":"RMSD.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"237342218","text":"# find quotient of two numbers with handling of simple exceptions\ndef find_quotient(a, b):\n try:\n ans = float(a) / float(b)\n print(f\"The quotient of {a} by {b} is equal to {ans:.3f}\")\n return ans\n except (ZeroDivisionError, ValueError) as e:\n print(\"Oops. Please, enter two non-zero float numbers. Current error:\", e)\n\n\na, b = input(\"Enter dividend and divisor: \").split()\nquotient = find_quotient(a, b)\n","sub_path":"lesson-3/task-1.py","file_name":"task-1.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"243304572","text":"import functools\nimport inspect\nimport sys\nfrom itertools import chain\nfrom six import iteritems, iterkeys, itervalues, string_types\n\nfrom ..iterutils import iterate, listify\nfrom ..platforms.basepath import BasePath\n\nstring_or_path_types = string_types + (BasePath,)\n\n\nclass Builtins(object):\n def __init__(self):\n self._default = {}\n self._post = {}\n\n def add(self, kind, name, value):\n assert kind in ('default', 'post')\n getattr(self, '_' + kind)[name] = value\n\n def bind(self, **kwargs):\n builtins = {}\n for k, v in iteritems(self._default):\n builtins[k] = v.bind(builtins=builtins, **kwargs)\n\n builtins['__bfg9000__'] = builtins\n return builtins\n\n def run_post(self, builtins, **kwargs):\n for v in itervalues(self._post):\n v(builtins=builtins, **kwargs)\n\n\nbuild = Builtins()\noptions = Builtins()\ntoolchain = Builtins()\n_allbuiltins = {\n 'build': build,\n 'options': options,\n 'toolchain': toolchain,\n}\n\n\ndef _add_builtin(context, kind, name, value):\n if context == '*':\n context = iterkeys(_allbuiltins)\n for i in iterate(context):\n _allbuiltins[i].add(kind, name, value)\n\n\nclass _Binder(object):\n def __init__(self, fn):\n self._fn = fn\n\n def bind(self, **kwargs):\n return self._fn\n\n\nclass _PartialFunctionBinder(_Binder):\n def __init__(self, fn, *args):\n _Binder.__init__(self, fn)\n self._args = args\n\n def bind(self, **kwargs):\n if not self._args:\n return _Binder.bind(self, **kwargs)\n pre_args = tuple(kwargs[i] for i in self._args)\n\n @functools.wraps(self._fn)\n def wrapper(*args, **kwargs):\n return self._fn(*(pre_args + args), **kwargs)\n\n if sys.version_info >= (3, 3):\n sig = inspect.signature(wrapper)\n params = list(sig.parameters.values())[len(kwargs):]\n wrapper.__signature__ = inspect.Signature(params)\n return wrapper\n\n\nclass _GetterBinder(_Binder):\n def __init__(self, fn, *args):\n _Binder.__init__(self, fn)\n self._args = args\n\n def bind(self, **kwargs):\n return self._fn(*[kwargs[i] for i in self._args])\n\n\nclass _PostWrapper(object):\n def __init__(self, fn, *args):\n self._fn = fn\n self._args = args\n\n def __call__(self, **kwargs):\n args = tuple(kwargs[i] for i in self._args)\n return self._fn(*args)\n\n\nclass _Decorator(object):\n def __init__(self, kind, binder):\n self.__kind = kind\n self.__binder = binder\n\n def __call__(self, *args, **kwargs):\n context = kwargs.pop('context', 'build')\n name = kwargs.pop('name', None)\n\n def decorator(fn):\n _add_builtin(context, self.__kind, name or fn.__name__,\n self.__binder(fn, *args))\n fn._builtin_bound = len(args)\n return fn\n return decorator\n\n\nfunction = _Decorator('default', _PartialFunctionBinder)\ngetter = _Decorator('default', _GetterBinder)\npost = _Decorator('post', _PostWrapper)\n\n\ndef _get_argspec(fn):\n if sys.version_info >= (3, 3):\n return list(inspect.signature(fn).parameters.keys())\n return inspect.getargspec(fn).args\n\n\ndef _get_value(argspec, index, args, kwargs):\n # Get the value of the nth argument to this function, whether it's\n # passed positionally or as a keyword argument. Note that `index` should be\n # at least as large as the number of builtins bound to the function.\n if len(args) > index:\n return args[index]\n name = argspec[index]\n if name in kwargs:\n return kwargs[name]\n raise IndexError('unable to find user-provided argument')\n\n\ndef check_types(thing, expected_types, extra_types=[]):\n if not isinstance(thing, expected_types):\n types = chain(extra_types, expected_types)\n raise TypeError('expected {}; but got {}'.format(\n ', '.join(i.__name__ for i in types),\n __builtins__['type'](thing).__name__\n ))\n\n\ndef type(out_type, in_type=string_or_path_types, extra_in_type=(),\n short_circuit=True, first_optional=False):\n in_type = listify(in_type, type=tuple) + listify(extra_in_type, type=tuple)\n if first_optional:\n in_type = in_type + (__builtins__['type'](None),)\n\n def decorator(fn):\n spec = _get_argspec(fn)\n all_types = (out_type,) + in_type\n\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n bound = getattr(wrapper, '_builtin_bound', 0)\n if first_optional and len(args) < 2 + bound:\n args = args[:bound] + (None, ) + args[bound:]\n\n # Try to get the first argument to this function. If it's the\n # output type, just return it immediately; otherwise, check if it's\n # a valid input type and then call the function.\n try:\n thing = _get_value(spec, bound, args, kwargs)\n if short_circuit:\n if isinstance(thing, wrapper.type):\n return thing\n check_types(thing, wrapper.in_type, [wrapper.type])\n else:\n check_types(thing, all_types)\n except IndexError:\n pass\n return fn(*args, **kwargs)\n\n wrapper.type = out_type\n wrapper.in_type = in_type\n return wrapper\n return decorator\n","sub_path":"bfg9000/builtins/builtin.py","file_name":"builtin.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"588656734","text":"import sys\r\nimport json\r\n\r\njsonString = sys.argv[1]\r\n\r\nfile = open(\"C:/testfile.txt\", \"w\")\r\n\r\nfile.write(jsonString)\r\n\r\nfile.close()\r\n\r\njsonObject = json.loads(jsonString)\r\n\r\njsonObject['data'] = 'modified'\r\n\r\n\r\n\r\nsys.stdout.write(json.dumps(jsonObject));\r\n ","sub_path":"AME/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"497960377","text":"'Tuples Are Like Lists' #unmodifable lists...\n\nx = ('Glenn', 'Sally', 'Joseph')\nprint(x[2]) #>>Joseph\ny = (1, 9, 2 )\nprint(y) #(1, 9, 2 )\nprint(max(y)) #>>9\n\nfor iter in y :\n print(iter)\n\n'but... Tuples are \"immutable\"'\n#Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string\n\nz = (5, 4, 3)\n#z[2] = 0\n#Traceback Error\n\n'A Tale of Two Sequences'\nl = list()\ndir(1)\n#fat list\nt = tuple()\ndir(t)\n#['count', 'index']\n\n'Tuples and Assignment'\n#we can also put tuples on the left-hand side of an assignment statement\n#you can even omit the parantheses\n(x, y) = (4, 'fred')\nprint(y) #fred\n(a, b) = (99, 98)\nprint(a) #99\n\n'Tuples and Dictionaries'\n#The items() method in dictionaries returns a list of (key, value) tuples\nd = dict()\nd['csev'] = 2\nd['cwen'] = 4\nfor (k, v) in d.items() :\n print(k, v)\n\ntups = d.items()\nprint(tups) #dict_items([('csev', 2), ('cwen', 4)])\n\n'Tuples are Comparable'\nprint((0, 1, 2) < (5, 1, 2)) #True\nprint((0, 1, 200000) < (0, 3, 4)) # True\nprint(('Jones', 'Sally') < ('Jones', 'Same')) #True\nprint(('Jones', 'Sally') > ('Adams', 'Sam')) #True\n\n'Sorting Lists of Tuples'\nd = {'a':10, 'b':1, 'c':22}\nd.items()\n#dict_items([('a', 10), ('c', 22), ('b', 1)])\nsorted(d.items())\n#[('a', 10). ('b', 1), ('c', 22)]\n\n'Using sorted()'\nd = {'a':10, 'b':1, 'c':22}\nt = sorted(d.items())\n#[('a', 10), ('b', 1), ('c', 22)]\nfor k, v in sorted(d.items()) :\n print(k, v)\n'''\na 10\nb 1\nc 22\n '''\n\n'Sort by Values Instead of Key'\nc = {'a':10, 'b':1, 'c':22}\ntmp = list()\nfor k, v in c.items():\n tmp.append( (v, k) )\nprint(tmp) #[(10, 'a'), (22, 'c'), (1, 'b')]\ntmp = sorted(tmp, reverse = True) #sorts backwards\nprint(tmp) #[(22, 'c'), (10, 'a'), (1, 'b')]\n\n\n\n'The 10 most common words'\nfhand = open('romeo.txt')\ncounts = dict()\nfor line in fhand :\n words = line.split()\n for word in words:\n counts[word] = counts.get(word, 0) + 1\n \nlst = list()\nfor key, val in counts.items() :\n newtup = (val, key)\n lst.append(newtup)\n\nlst = sorted(lst, reverse = True)\n\nfor val, key in lst[:10] :\n print(key, val)\n\n'EVEN SHORTER VERSION. THE ONE LINER'\n\nc = {'a':10, 'b':1, 'c':22}\nprint( sorted([ (v, k) for k,v in c.items() ], reverse = True))\n#[(1, 'b'), (10, 'a'), (22, 'c')]\n#List comprehension creates a dynamic list. In this case,\n#we make a list of reversed tuples and then sort it\n\n#TODO Search List Comprehension - creates a dynamic list. In this case, we make a list of reserved tuples and then sort it.\n","sub_path":"Course 2 - Python Data Structures/Chapter 10/Lecture Materials/Tuples.py","file_name":"Tuples.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518862527","text":"import logging\nfrom logging.handlers import RotatingFileHandler\n\n\ndef create_rotating_log(path):\n logger = logging.getLogger(\"[TREOLAN]\")\n logger.setLevel(logging.INFO)\n \n handler = RotatingFileHandler(path, maxBytes=1024*1024*3, backupCount=1)\n \n format = \"\"\"%(levelname) -10s %(asctime)s %(processName) -15s %(name) -25s: %(message)s\"\"\"\n formatter = logging.Formatter(format)\n handler.setFormatter(formatter)\n \n logger.addHandler(handler)\n return logger\n","sub_path":"utils/logging/loggers.py","file_name":"loggers.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"468946848","text":"import processingfileclass as pfc\n\nclass ProcessingUnit:\n\tdef __init__(self,inputArg=False):\n\t\tself.performReturnStack = []\n\t\tself.performEndStack = []\n\t\tself.paraStack = [\"\"]\n\t\tself.processedLines = []\t\t#list of all lines processed\n\t\tself.programCounter = 0\t\t\t#points to next sentence to be executed\n\t\tself.inputFile = []\n\t\tself.paraCall = False\n\t\tself.paraReturn = False\n\t\tself.paraBranches = {}\n\n\t\tif inputArg.__class__ is ProcessingUnit:\n\t\t\tself.performReturnStack = inputArg.performReturnStack[:]\n\t\t\tself.performEndStack = inputArg.performEndStack[:]\n\t\t\tself.paraStack = inputArg.paraStack[:]\n\t\t\tself.processedLines = inputArg.processedLines[:]\n\t\t\tself.programCounter = inputArg.programCounter - 0\n\t\t\tself.inputFile = inputArg.inputFile\n\t\t\tself.paraBranches = dict(inputArg.paraBranches)\n\t\t\n\t\tif inputArg.__class__ is pfc.ProgramProcessingFile:\n\t\t\tself.inputFile = inputArg\n\t\t\tself.programCounter = 0\n\n\tdef peekStatement(self,lineNo):\n\t\treturn self.inputFile.procedureDivision[lineNo]\n\t\n\tdef peekCurrentStatement(self):\n\t\tcurrentLine = self.processedLines[-1]\n\t\treturn self.inputFile.procedureDivision[currentLine]\n\t\n\tdef peekNextStatement(self):\n\t\treturn self.inputFile.procedureDivision[self.programCounter]\n\t\n\tdef incrementProgramCounter(self):\n\t\tself.paraReturn = False\n\t\t\n\t\tif self.processedLines and not self.paraCall:\n\t\t\tif self.processedLines[-1] in self.inputFile.paraEnd.keys():\n\t\t\t\tparaName = self.inputFile.paraEnd[self.processedLines[-1]]\n\t\t\t\tif paraName in self.performEndStack:\n\t\t\t\t\tpoppedPara = False\n\t\t\t\t\twhile poppedPara != paraName:\n\t\t\t\t\t\tpoppedPara = self.performEndStack.pop()\n\t\t\t\t\t\tself.paraStack.pop()\n\t\t\t\t\t\tself.programCounter = self.performReturnStack.pop()\n\t\t\t\t\tself.paraReturn = True\n\t\t\n\t\tself.paraCall = False\n\t\tself.processedLines.append(self.programCounter)\n\t\tself.programCounter += 1\n\t\n\tdef getNextStatement(self):\n\t\tself.incrementProgramCounter()\n\t\treturn self.peekCurrentStatement()\n\t\n\tdef pushStack(self,performStart,performEnd):\n\t\tself.paraStack.append(\"\")\n\t\tself.performReturnStack.append(self.processedLines[-1])\n\t\tself.performEndStack.append(performEnd)\n\t\t\n\t\tself.jumpToPara(performStart)\n\t\t\n\tdef jumpToPara(self,paraName):\n\t\tself.programCounter = self.inputFile.paraStart[paraName]\n\t\tself.paraCall = True\n\t\n\t","sub_path":"src/processingunitclass.py","file_name":"processingunitclass.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"23566121","text":"import os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport dateutil\nfrom datetime import datetime\nimport re\n\nproject_path = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '../../'))\nif project_path not in sys.path:\n sys.path.append(project_path)\n\nfrom scripts.data import raw_data\n\n\nBETTING_LABEL = 'afl_betting'\nMATCH_LABEL = 'ft_match_list'\nBETTING_TEAM_TRANSLATIONS = {\n 'Tigers': 'Richmond',\n 'Blues': 'Carlton',\n 'Demons': 'Melbourne',\n 'Giants': 'GWS',\n 'Suns': 'Gold Coast',\n 'Bombers': 'Essendon',\n 'Swans': 'Sydney',\n 'Magpies': 'Collingwood',\n 'Kangaroos': 'North Melbourne',\n 'Crows': 'Adelaide',\n 'Bulldogs': 'Western Bulldogs',\n 'Dockers': 'Fremantle',\n 'Power': 'Port Adelaide',\n 'Saints': 'St Kilda',\n 'Eagles': 'West Coast',\n 'Lions': 'Brisbane',\n 'Cats': 'Geelong',\n 'Hawks': 'Hawthorn',\n 'Adelaide Crows': 'Adelaide',\n 'Brisbane Lions': 'Brisbane',\n 'Gold Coast Suns': 'Gold Coast',\n 'GWS Giants': 'GWS',\n 'Geelong Cats': 'Geelong',\n 'West Coast Eagles': 'West Coast',\n 'Sydney Swans': 'Sydney'\n}\nVENUE_TRANSLATIONS = {\n 'AAMI': 'AAMI Stadium',\n 'ANZ': 'ANZ Stadium',\n 'Adelaide': 'Adelaide Oval',\n 'Aurora': 'UTAS Stadium',\n 'Aurora Stadium': 'UTAS Stadium',\n 'Blacktown': 'Blacktown International',\n 'Blundstone': 'Blundstone Arena',\n \"Cazaly's\": \"Cazaly's Stadium\",\n 'Domain': 'Domain Stadium',\n 'Etihad': 'Etihad Stadium',\n 'GMHBA': 'GMHBA Stadium',\n 'Gabba': 'Gabba',\n 'Jiangwan': 'Jiangwan Stadium',\n 'MCG': 'MCG',\n 'Mars': 'Mars Stadium',\n 'Metricon': 'Metricon Stadium',\n 'Perth': 'Optus Stadium',\n 'SCG': 'SCG',\n 'Spotless': 'Spotless Stadium',\n 'StarTrack': 'Manuka Oval',\n 'TIO': 'TIO Stadium',\n 'UTAS': 'UTAS Stadium',\n 'Westpac': 'Westpac Stadium',\n 'TIO Traegar Park': 'TIO Stadium'\n}\nBETTING_COL_INDICES = [0, 1, 2, 3, 4, 5, 6, 7, 8]\nCOL_LABEL_ROW = 2\nMATCH_COL_INDICES = [0, 1, 2, 3, 4, 5, 6, 7]\nROUND_REGEX = re.compile(r'(round\\s+\\d\\d?|.*final.*)', flags=re.I)\nMATCH_STATUSES = ['BYE', 'MATCH CANCELLED']\nHOME_INDEX = 0\nAWAY_INDEX = 1\nHOME_V_AWAY_INDEX = 2\nHOME_V_AWAY_LABELS = ['home_team', 'v', 'away_team']\n\n\ndef translate_venue(venue):\n return VENUE_TRANSLATIONS[venue] if venue in VENUE_TRANSLATIONS.keys() else venue\n\n\ndef translate_date(df):\n # year is a float, so we have to convert it to int, then str to concatenate\n # with the date string (date parser doesn't recognize years as floats)\n return (df['date'].astype(str) + ' ' + df['year'].astype(int).astype(str))\n\n\ndef translate_score(idx):\n return lambda scores: float(scores[idx]) if type(scores) == list and len(scores) == 2 else None\n\n\ndef get_score(idx):\n return lambda df: df['result'].str.split('-').map(translate_score(idx))\n\n\ndef translate_home_team(df):\n return df['home_team'].map(lambda x: None if x in MATCH_STATUSES else x)\n\n\ndef get_season_round(df):\n # Round label just appears at top of round in table,\n # so forward fill to apply it to all relevant matches\n return df['date'].str.extract(ROUND_REGEX, expand=True).ffill()\n\n\ndef clean_match_data(data):\n # Ignore useless columns that are result of BeautifulSoup table parsing\n df = pd.DataFrame(data).iloc[:, MATCH_COL_INDICES]\n # First column is year inserted during scraping\n column_labels = (df.loc[COL_LABEL_ROW, :]\n .astype(str)\n .str.lower()\n .str.replace(' ', '_')\n .values)\n # Data rows split v into 3 columns, but label rows use 1 column,\n # so we have to split labels manually\n expanded_column_labels = (['year'],\n [column_labels[HOME_V_AWAY_INDEX - 1]],\n HOME_V_AWAY_LABELS,\n column_labels[HOME_V_AWAY_INDEX + 1:-(len(HOME_V_AWAY_LABELS) - 1)])\n df.columns = np.concatenate(expanded_column_labels)\n\n # We need to do this in two steps because there's at least one case of the website's data table\n # being poorly organised, leading to specious duplicates.\n # So, we fill the season_round column before dropping duplicates, then we assign home_score,\n # away_score, and date to avoid NaNs that will raise errors.\n return (df.assign(season_round=get_season_round,\n home_team=translate_home_team,\n venue=df['venue'].map(translate_venue))\n # Check all columns except for round #, because round # would make all rows unique.\n # Duplicate rows are from table labels/headers that are not useful\n .drop_duplicates(subset=df.columns.values[:-1], keep=False)\n # The only rows with NaNs are the round label rows that we no longer need\n .dropna()\n # Result column has format: 'home_score-away_score'\n .assign(home_score=get_score(HOME_INDEX),\n away_score=get_score(AWAY_INDEX),\n date=translate_date)\n .drop(['result', 'year', 'v'], axis=1)\n .reset_index(drop=True))\n\n\ndef translate_betting_teams(df):\n return df['team'].map(lambda x: BETTING_TEAM_TRANSLATIONS[x] if x in BETTING_TEAM_TRANSLATIONS.keys() else x)\n\n\ndef clean_betting_data(data):\n # Ignore useless columns that are result of BeautifulSoup table parsing\n df = pd.DataFrame(data).iloc[:, BETTING_COL_INDICES]\n df.columns = df.loc[COL_LABEL_ROW, :].map(\n lambda x: x.lower().replace(' ', '_')).rename(None)\n\n df = (df.assign(team=translate_betting_teams,\n date=lambda x: x['date'].ffill(),\n venue=df['venue'].ffill().map(translate_venue))\n .dropna()\n # Duplicate rows are from table labels/headers that are not useful, so remove all\n .drop_duplicates(keep=False)\n .reset_index(drop=True)\n # Save date parsing till the end to avoid ValueErrors\n # .assign(date=lambda x: x['date'].apply(dateutil.parser.parse))\n .drop(['score', 'win_paid', 'margin', 'line_paid'], axis=1))\n\n if len(df) % 2 != 0:\n raise Exception(\n f'Betting DataFrame should have an even number of rows, but has {len(df)} instead')\n\n return df.assign(home=([1, 0] * int(len(df) / 2)))\n\n\ndef main(data, csv=False):\n dfs = []\n\n for key, value in data.items():\n if key == BETTING_LABEL:\n df = clean_betting_data(value)\n if key == MATCH_LABEL:\n df = clean_match_data(value)\n\n if csv:\n project_path = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '../../'))\n data_directory = os.path.join(project_path, 'data')\n\n if not os.path.isdir(data_directory):\n os.makedirs(data_directory)\n\n df.to_csv(os.path.join(data_directory, f'{key}.csv'), index=False)\n\n dfs.append(df)\n\n return tuple(dfs)\n\n\nif __name__ == '__main__':\n main(raw_data.main(), csv=True)\n","sub_path":"scripts/data/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":7045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"20805309","text":"# Author: Skander Marnissi \n\nimport os\nimport sys\nimport numpy as np\nfrom QAgent import QAgent\n\nos.system(\"clear\")\n\nstart, end, it = 'L4', 'L6', 1000\n\nif len(sys.argv) == 3:\n if 1 <= int(sys.argv[1]) <= 9 and 1 <= int(sys.argv[2]) <= 9:\n start, end = 'L' + str(sys.argv[1]), 'L' + str(sys.argv[2])\n\n# Print map\nprint(\"+--------------+\")\nprint(\"| L1 L2 L3 |\")\nprint(\"+----+ + |\")\nprint(\"| L4 | L5 | L6 |\")\nprint(\"| + +----|\")\nprint(\"| L7 L8 L9 |\")\nprint(\"+--------------+\")\nprint(\"\\n\")\nprint(f\"From {start} to {end}:\")\n\n# Define the states\nlocation_to_state = {\n 'L1': 0,\n 'L2': 1,\n 'L3': 2,\n 'L4': 3,\n 'L5': 4,\n 'L6': 5,\n 'L7': 6,\n 'L8': 7,\n 'L9': 8\n}\n\n# Maps indices to locations\nstate_to_location = dict((state, location) for location, state in location_to_state.items())\n\n# Define the actions\nactions = [0, 1, 2, 3, 4, 5, 6, 7, 8]\n\nrewards = np.array([\n [0, 1, 0, 0, 0, 0, 0, 0, 0],\n [1, 0, 1, 0, 1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1, 0, 1, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 1, 0]\n])\n\n# Initialize parameters\nlearning_rate = 0.9\ndiscount_factor = 0.75\n\n# Initialize q-values\nq = np.array(np.zeros([9, 9]))\n\nq_agent = QAgent(learning_rate, discount_factor, location_to_state, actions, rewards, state_to_location, q)\nq_agent.training(start, end, it)\n","sub_path":"Mathematical-modeling-for-intelligent-systems/qlearning/example3/qlearning.py","file_name":"qlearning.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"181212355","text":"### source: http://chrisstrelioff.ws/sandbox/2014/11/13/getting_started_with_latent_dirichlet_allocation_in_python.html\n\n### running lda on the documents and checking the topic overlap\nimport lda\nimport textmining\nimport numpy as np\nimport csv\nimport matplotlib.pyplot as plt\n\ntdm = textmining.TermDocumentMatrix()\n\nf1 = open(os.path.join('allfiles', 'document01-finance.txt'), \"r\")\nf2 = open(os.path.join('allfiles', 'document02-finance.txt'), \"r\")\nf3 = open(os.path.join('allfiles', 'document03-finance.txt'), \"r\")\nf4 = open(os.path.join('allfiles', 'document04-ee.txt'), \"r\")\nf5 = open(os.path.join('allfiles', 'document05-ee.txt'), \"r\")\n\nreadfile_1 = f1.read()\ntdm.add_doc(readfile_1)\n\nreadfile_2 = f2.read()\ntdm.add_doc(readfile_2)\n\nreadfile_3 = f3.read()\ntdm.add_doc(readfile_3)\n\nreadfile_4 = f4.read()\ntdm.add_doc(readfile_4)\n\nreadfile_5 = f5.read()\ntdm.add_doc(readfile_5)\n\n#print type(tdm)\n#print tdm.shape\n\ntdm.write_csv('tdmResult.csv', cutoff=1)\n\nvocab = []\nfp = csv.reader(open('tdmResult.csv','rb'))\nfor row in fp:\n vocab = row\n break\nvocab = tuple(vocab)\n\ndata = np.genfromtxt('tdmResult.csv', dtype=None, delimiter=',', skip_header=1)\n\nmodel = lda.LDA(n_topics=2, n_iter=500, random_state=1)\nmodel.fit(data)\n\ntopic_word = model.topic_word_\nprint(\"type(topic_word): {}\".format(type(topic_word)))\nprint(\"shape: {}\".format(topic_word.shape))\n\nn_top_words = 5\n\nfor i, topic_dist in enumerate(topic_word):\n topic_words = np.array(vocab)[np.argsort(topic_dist)][:-n_top_words:-1]\n print('Topic {}: {}'.format(i, ' '.join(topic_words)))\n \n\n# use matplotlib style sheet\ntry:\n plt.style.use('ggplot')\nexcept:\n # version of matplotlib might not be recent\n pass\n\ndoc_topic = model.doc_topic_\nprint(\"type(doc_topic): {}\".format(type(doc_topic)))\nprint(\"shape: {}\".format(doc_topic.shape))\n\nf, ax= plt.subplots(2, 1, figsize=(8, 6), sharex=True)\nfor i, k in enumerate([1, 2]):\n ax[i].stem(doc_topic[k,:], linefmt='r-',\n markerfmt='ro', basefmt='w-')\n ax[i].set_xlim(-1, 21)\n ax[i].set_ylim(0, 1)\n ax[i].set_ylabel(\"Prob\")\n ax[i].set_title(\"Document {}\".format(k))\n\nax[1].set_xlabel(\"Topic\")\n\nplt.tight_layout()\nplt.show()","sub_path":"ps3/lda_test.py","file_name":"lda_test.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"134317087","text":"def num_inversions(nums):\r\n\treturn helper(nums)[1]\r\n\r\ndef helper(nums):\r\n\tif len(nums)<=1:\r\n\t\treturn nums,0\r\n\tmid=len(nums)/2\r\n\tlleft,nleft=helper(nums[:mid])\r\n\tlright,nright=helper(nums[mid:])\r\n\ti=0\r\n\tj=0\r\n\tres=[]\r\n\tans=nleft+nright\r\n\twhile i= 1:\n if args[0] == \"misc\":\n for command in commands_list:\n if hasattr(command, \"type\") and command[\"type\"] == \"Misc\":\n if hasattr(command, \"args\"):\n help_embed.add_field(name = f\"**{os.environ['PREFIX']} {command['name']} {command['args']}**\", value = f\"*{command['description']}*\");\n else:\n help_embed.add_field(name = f\"**{os.environ['PREFIX']}{command['name']}**\", value = f\"*{command['description']}*\");\n elif args[0] == \"mod\" or args[0] == \"moderation\":\n for command in commands_list:\n if hasattr(command, \"type\") and command[\"type\"] == \"Moderation\":\n if hasattr(command, \"args\"):\n help_embed.add_field(name = f\"**{os.environ['PREFIX']}{command['name']} {command['args']}**\", value = f\"{command['description']}\");\n else:\n help_embed.add_field(name = f\"**{os.environ['PREFIX']}{command['name']} {command['args']}**\", value = f\"*{command['description']}*\");\n elif args[0] == \"nsfw\" or args[0] == \"adult\":\n for command in commands_list:\n if hasattr(command, \"type\") and command[\"type\"] == \"NSFW\":\n if hasattr(command, \"args\"):\n help_embed.add_field(name = f\"**{os.environ['PREFIX']}{command['name']} {command['args']}**\", value = f\"{command['description']}\");\n else:\n help_embed.add_field(name = f\"**{os.environ['PREFIX']}{command['name']}**\", value = f\"{command['description']}\");\n else:\n help_embed.add_field(name = \"**Misc:**\", value = \"*Misc Commands.*\", inline = True);\n help_embed.add_field(\"**Moderation:***\", value = \"*Moderation Commands.*\", inline = True);\n help_embed.add_field(name = \"NSFW\", value = \"NSFW Commands.\", inline = True);\n\n await ctx.send(embed = help_embed);\n\n# MISC Commands #\n\n@bot.command(name = \"forest\", aliases = [\"maverick\"])\nasync def forest(ctx):\n lp_embed = discord.Embed(title = \"You stumble across a wild Logan Paul\", color = discord.Color.from_rgb(255, 255, 255));\n lp_embed.set_image(url = \"attachment://Assets/emo_logan_paul.png\")\n pass;\n\n@bot.command(name = \"snipe\")\nasync def snipe(ctx):\n snipe = qik.get(f\"snipe.{ctx.guild.id}\");\n\n snipe_embed = discord.Embed(title = f\"***{snipe['author']}:***\", description = f\"{snipe['content']}\", color = discord.Color.from_rgb(255, 255, 255));\n snipe_embed.set_footer(text = f\"Sent at: {snipe['sent-at']}\");\n snipe_embed.set_image(url = snipe['avatar']);\n\n await ctx.send(embed = snipe_embed);\n\n@bot.command(name = \"predict\", aliases = [\"8ball\", \"guess\"])\nasync def predict(ctx):\n responses = [\"Yes.\", \"No.\", \"Maybe.\", \"Certainly.\", \"For sure.\", \"Never.\", \"In your dreams.\"];\n \n predict_embed = discord.Embed(title = \"***Prediction:***\", description = f\"{random.choice(responses)}\", color = discord.Color.from_rgb(255, 255, 255));\n predict_embed.set_footer(text = f\"Sent at {timestamp}\");\n\n await ctx.send(embed = predict_embed);\n\n# VC Commands #\n@bot.command(name = \"join\", aliases = [\"summon\", \"connect\"])\nasync def join(ctx):\n if ctx.author.voice:\n try:\n channel = ctx.author.voice.channel;\n await channel.connect();\n except Exception as err:\n await ctx.send(f\"I could not connect to the voice channel.\\n\\nDiscord PY Exception: {err}\");\n else:\n await ctx.send(\"You are not connected to a VC.\");\n\n@bot.command(name = \"leave\", aliases = [\"disconnect\", \"unsummon\", \"fuckoff\"])\nasync def leave(ctx):\n if ctx.author.voice.channel and ctx.voice_client:\n try:\n await ctx.voice_client.disconnect();\n except Exception as err:\n await ctx.send(f\"I could not disconnect from the voice channel.\\n\\nDiscord PY Exception: {err}\"); \n\n@bot.command(name = \"play\", aliases = [\"q\", \"queue\"])\nasync def play(ctx, *args):\n if not ctx.voice_client and ctx.author.voice.channel:\n try: \n vc = ctx.author.voice.channel;\n await vc.connect();\n except Exception as err:\n print(err)\n title = \" \".join(args);\n\n search = VideosSearch(title, limit = 4);\n URL = search.result()[\"result\"][0][\"link\"];\n\n Title = search.result()[\"result\"][0][\"title\"];\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }],\n 'outtmpl': f'./Assets/{Title}.mp3'\n }\n\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n try:\n ydl.download([\"https://www.youtube.com/watch?v=ZoG5jJ3E8rg\"]);\n except:\n print(\"I could not find the given video link.\");\n\n vc.play(discord.FFmpegPCMAudio(f\"./Assets/{Title}.mp3\"))\n\n# Automation Commands #\n@bot.command(name = \"automod\", aliases = [\"amod\"])\nasync def automod(ctx, *args):\n args = args.lower();\n admin = ctx.author.guild_permissions.administrator;\n\n if admin or isadmin(ctx):\n if len(args) >= 1:\n if args[0] == \"enabled\" or args[0] == \"true\" or args[0] == \"on\":\n qik.set(f\"automod.{ctx.guild.id}\", True);\n elif args[0] == \"disabled\" or args[0] == \"false\" or args[0] == \"off\":\n qik.set(f\"automod.{ctx.guild.id}\", False);\n else:\n error_embed = discord.Embed(title = \"***Error:***\", description = \"*Error - Invalid argument provided (enabled/disables).\", color = colors[\"err\"]);\n\n await ctx.send(embed = error_embed);\n else:\n error_embed = discord.Embed(title = \"***Invalid Args Amount:**\", description = \"*Error - `Invalid amount of arguments provided.`*\");\n\n await ctx.send(embed = error_embed);\n else:\n error_embed = discord.Embed(title = \"***Invalid Permissions:***\", description = \"*Error - `You do not have valid permissions to enable/disable automod in this guild.`*\", color = colors[\"err\"]);\n\n await ctx.send(embed = error_embed);\n\n@bot.command(name = \"bannedwords\", aliases = [\"bw\", \"wordsbanned\"])\nasync def bannedwords(ctx, *args):\n words = qik.get(f\"banned_words.{ctx.guild.id}\");\n admin = ctx.author.guild_permission.administrator;\n\n if admin or isadmin(ctx):\n if len(args) >= 1:\n if args[0] == \"add\":\n words.append(args[1]);\n elif args[0] == \"remove\" or args[0] == \"delete\":\n num = words.index(args[1])\n words.pop(num);\n qik.set(f\"banned_words.{ctx.guild.id}\", words);\n\n# Moderation Commands #\n@bot.command(name = \"kick\", aliases = [\"boot\", \"italy\", \"shapeofitaly\"])\nasync def kick(ctx, member : discord.Member, *args):\n kick_perms = ctx.author.guild_permissions.kick_members;\n\n if kick_perms or isadmin(ctx):\n try:\n given_reason = \" \".join(args[0:]);\n dm = await member.create_dm();\n \n if given_reason == None:\n given_reason = \"Breaking the rules.\";\n\n notify_embed = discord.Embed(title = f\"Moderation Notice:\", description = f\"You have been kicked from {ctx.guild.name}.\\n\\nReason: {given_reason}\", color = colors['mod'])\n\n await dm.send(embed = notify_embed);\n\n await member.kick(reason = given_reason);\n\n kicked_embed = discord.Embed(title = \"**Moderation:***\", description = f\"*Kicked: {member.mention}\\nReason: `{given_reason}`*\", color = colors[\"mod\"]);\n kicked_embed.set_footer(text = f\" Sent at: {timestamp}\");\n\n await ctx.send(embed = kicked_embed);\n except Exception as err:\n error_embed = discord.Embed(title = \"***Error:***\", description = f\"*Error Message - `{err}`*\");\n error_embed.set_footer(text = f\" Sent at: {timestamp}\");\n \n print(err)\n await ctx.send(embed = error_embed);\n\n@bot.command(name = \"ban\")\nasync def ban(ctx, member: discord.Member, *args):\n ban_perms = ctx.author.guild_permissions.ban_members;\n \n if ban_perms or isadmin(ctx):\n try:\n given_reason = \" \".join(args[0:]);\n dm = await member.create_dm();\n \n if given_reason == None:\n given_reason = \"Breaking the rules.\";\n\n notify_embed = discord.Embed(title = f\"Moderation Notice:\", description = f\"You have been banned from {ctx.guild.name}.\\n\\nReason: {given_reason}\", color = colors['mod'])\n\n await dm.send(embed = notify_embed);\n\n await member.ban(reason = given_reason);\n\n banned_embed = discord.Embed(title = \"***Moderation:***\", description = f\"*Banned: {member.mention}\\nReason: `{given_reason}`*\", color = discord.Color.from_rgb(87, 64, 255));\n banned_embed.set_footer(text = f\" Sent at: {timestamp}\");\n\n await ctx.send(embed = banned_embed);\n except Exception as err:\n error_embed = discord.Embed(title = \"***Error:***\", description = f\"*Error Message - `{err}`*\");\n error_embed.set_footer(text = f\"Sent at: {timestamp}\");\n\n await ctx.send(embed = error_embed);\n else:\n error_embed = discord.Embed(title = \"***Invalid Permissions:***\", description = \"*Error - `You do not have the permissions to ban this user.`*\", color = colors[\"err\"]);\n error_embed.set_footer(text = f\" Sent at: {timestamp}\");\n\n await ctx.send(embed = error_embed);\n\n# NSFW Commands #\n@bot.command(name = \"neko\")\nasync def neko(ctx):\n if ctx.channel.nsfw:\n try:\n res = requests.get(\"https://nekos.life/lewd\");\n bs = BeautifulSoup(res.content, \"html.parser\");\n img_url = bs.find(\"img\").attrs[\"src\"];\n\n neko_embed = discord.Embed(title = \"***Neko:***\", color = colors[\"nsfw\"], url = img_url)\n neko_embed.set_image(url = img_url);\n neko_embed.set_footer(text = f\"Sent at {timestamp} || Scraped from https://nekos.life/lewd\");\n\n await ctx.send(embed = neko_embed)\n except Exception as err:\n owner = ctx.guild.owner;\n dm = await owner.create_dm();\n await dm.send(err);\n else:\n error_embed = discord.Embed(title = \"***error:***\", description = \"*error - `this command can only be used in NSFW channels.`*\", color = colors['err'])\n\n await ctx.send(embed = error_embed);\n\n@bot.command(name = \"hentai\")\nasync def hentai(ctx, *args):\n gb = Gel();\n if ctx.channel.nsfw:\n try:\n if len(args) < 1:\n posts = await gb.search_posts(tags = [\"hentai\"], exclude_tags = [\"video\", \"mp4\", \"gif\"]);\n img_url = random.choice(posts);\n\n else:\n posts = await gb.search_posts(tags = args, exclude_tags = [\"video\", \"mp4\"]);\n img_url = random.choice(posts);\n \n hentai_embed = discord.Embed(title = \"***Hentai:***\", color = colors[\"nsfw\"], url = img_url);\n hentai_embed.set_image(url = img_url);\n hentai_embed.set_footer(text = f\"Sent at {timestamp} || Scraped from https://gelbooru.com\");\n\n await ctx.send(embed = hentai_embed);\n except Exception as err:\n await ctx.send(err);\n else:\n error_embed = discord.Embed(title = \"***error:***\", description = \"*error - `this command can only be used in NSFW channels.`*\", color = colors['err'])\n\n await ctx.send(embed = error_embed);\n# END OF COMMANDS #\n\n# COGS #\nping_server();\nbot.run(os.environ[\"TOKEN\"]); ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200277214","text":"## Manages the webcam feed in a thread so it doesn't impact main program performance.\n#Dakota Madden-Fong May 2018\nimport sys\nfrom PyQt5.QtWidgets import QWidget, QToolTip, QMessageBox, QPushButton, QApplication, QDesktopWidget, QLabel, QHBoxLayout, QVBoxLayout, QGridLayout, QComboBox, QPlainTextEdit, QSizePolicy, QFileDialog\nfrom PyQt5.QtGui import QFont, QIcon, QPixmap, QImage\nfrom PyQt5.QtCore import Qt, pyqtSlot, QThread, pyqtSignal\nimport numpy as np\nimport cv2\nimport time\n\nfrom compare2set import compare2set\nfrom mtg_json_get import getSets\n\nclass QWebcamThread(QThread):\n \n sig = pyqtSignal()\n\n \n def WebCamMissing(self):\n # emit signal to trigger error message in MTGCardReader.py\n self.sig.emit()\n \n def __del__(self):\n self.wait()\n\n def __init__(self,imgwindow, parent = None):\n super(QWebcamThread,self).__init__(parent=parent)\n self.imgwindow = imgwindow\n self.done = False\n # on initialization, start reading from the webcam using OpenCV\n try:\n self.cap = cv2.VideoCapture(0)\n self.ret, self.cvframe = self.cap.read()\n except: \n self.WebCamMissing()\n\n def getFrame(self):\n return self.cvframe\n \n def run(self):\n try:\n while not self.done:# update Webcam image every loop\n cvimg = self.cvframe\n height, width, _ = cvimg.shape\n while (width > 1000): #resize webcam images that are far too high resolution for the UI to handle\n new_width = int(width/2)\n new_height = int(height/2)\n cvimg = cv2.resize(cvimg, (new_width,new_height) )#, fx=1, fy=1) \n height, width, _ = cvimg.shape\n cvimgRGB = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB)\n qpiximg = QPixmap(QImage(cvimgRGB, cvimgRGB.shape[1], cvimgRGB.shape[0], cvimgRGB.shape[1] * 3,QImage.Format_RGB888))\n self.imgwindow.setPixmap(qpiximg)\n self.imgwindow.update()\n self.ret, self.cvframe = self.cap.read()\n except:\n # if exception, signal for error message\n self.WebCamMissing()\n #QApplication.processEvents()","sub_path":"QWebcamThread.py","file_name":"QWebcamThread.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"395104217","text":"from new_python import *\n\nsol = [Point(1,1), Point(2,1), Point(3,1), Point(7,1), Point(8,1), \n Point(2,2), Point(2,5), Point(2,6), Point(3,5), Point(3,6),\n Point(6,4), Point(6,5), Point(6,6)]\nevt = [Point(1,2), Point(3,2), Point(0,6), Point(8,0), Point(2,0), Point(6,0)]\n\nrs = 2.1\nprint(len(event_couvert(sol, evt, rs)), len(evt))\nfft = fitnessFunction([sol], evt, rs)\nfor f in fft:\n print(f[1])\nshow_genome(rs, rs, sol, evt)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"310825234","text":"import unittest\nimport os\nimport sys\nimport json\nsys.path.insert(0, '../Source')\nfrom FileManager import FileManager\n\n\nclass TestFileManagerMethods(unittest.TestCase):\n\n def test_getData(self):\n file = open('testing.txt', 'w')\n file.write('{\"1234\": 133}')\n file.close()\n\n fileManager = FileManager('testing.txt')\n data = fileManager.getData()\n self.assertEqual(data, {\"1234\": 133})\n\n os.remove('testing.txt')\n\n\n def test_getSessionData(self):\n file = open('testing.txt', 'w')\n sessionDataOriginal = [[[0, 28563], \"U2 F2 L2 D2 L' U2 L' F2 L F2 U L' D B' F' L' U2 F' L'\", \"\", 1563232395]]\n sessionDict = {\"session1\": sessionDataOriginal}\n json.dump(sessionDict, file)\n file.close()\n\n fileManager = FileManager('testing.txt')\n sessionData = fileManager.getSessionData(\"session1\")\n self.assertEqual(sessionData, sessionDataOriginal)\n\n os.remove('testing.txt')\n\n def test_getMultipleSessionData(self):\n file = open('testing.txt', 'w')\n sessionData1 = [[[0, 28563], \"U2 F2 L2 D2 L' U2 L' F2 L F2 U L' D B' F' L' U2 F' L'\", \"\", 1563232395],[[0, 32727], \"R F U F' L' D' B L B2 D2 R2 F' D2 R2 F' B2 D2 F D\", \"\", 1563232454],[[0, 28053], \"D F2 R2 U R2 F2 L2 U2 B2 D' L2 U L' R' F' D2 U B F2 U2 R'\", \"\", 1563232519]]\n sessionData2 = [[[0, 73228], \"L' U B2 L B R D2 F' U2 F2 U B2 R2 U2 B2 R2 U' R2 F\", \"\", 1563233503],[[0, 30163], \"D2 R2 F' U2 B R2 D2 U2 B' L2 R2 D' B U R2 F L B' R' F R'\", \"\", 1563233644],[[0, 28436], \"U' L2 D2 R2 B' D2 B R2 B' F2 U2 B' U' L D B' D L2 B F R'\", \"\", 1563233713]]\n sessionDataList = [sessionData1, sessionData2]\n sessionDict = {\"session1\": sessionData1, \"session2\": sessionData2}\n json.dump(sessionDict, file)\n file.close()\n\n fileManager = FileManager('testing.txt')\n\n for i in range(2):\n sessionName = 'session' + str(i + 1)\n self.assertEqual(fileManager.getSessionData(sessionName), sessionDataList[i])\n\n os.remove('testing.txt')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Test/FileManagerTest.py","file_name":"FileManagerTest.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"527838830","text":"#!/bin/python\n# -*- coding:utf-8 -*-\n\n# 写1个函数unique,\n# 参数是一个数组,返回去重后的元素(保持原有顺序)\n#\n\n\ndef Unique(arg):\n seen = set()\n result = []\n for item in arg:\n if item not in seen:\n seen.add(item)\n result.append(item)\n\n for item in result:\n yield item\n","sub_path":"interview/42qu/unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"264086994","text":"import unittest\n\nfrom tests.event.mock_docker import MockDockerClient, MockContainer\nfrom tests.utils import DEFAULT_TEST_MEM, DEFAULT_TEST_DISK, DEFAULT_TEST_NETWORK, DEFAULT_TEST_IMAGE, \\\n DEFAULT_TEST_APP_NAME, DEFAULT_TEST_OWNER_EMAIL, DEFAULT_TEST_JOB_TYPE, get_test_workload\nfrom titus_isolate import log\nfrom titus_isolate.event.constants import STATIC, CPU_LABEL_KEY, WORKLOAD_TYPE_LABEL_KEY\nfrom titus_isolate.event.utils import get_current_workloads\nfrom titus_isolate.model.workload import Workload\n\n\nclass BadContainer:\n def update(self, **kwargs):\n log.info(\"bad container update called with: '{}'\".format(kwargs))\n threads = kwargs[\"cpuset_cpus\"].split(',')\n self.update_calls.append(threads)\n\n\nclass TestUtils(unittest.TestCase):\n\n def test_get_current_workloads(self):\n docker_client = MockDockerClient()\n self.assertEqual(0, len(get_current_workloads(docker_client)))\n\n c0_name = \"c0\"\n c0_thread_count = 1\n docker_client.add_container(self.__get_test_container(c0_name, c0_thread_count))\n\n c1_name = \"c1\"\n c1_thread_count = 2\n docker_client.add_container(self.__get_test_container(c1_name, c1_thread_count))\n\n current_workloads = get_current_workloads(docker_client)\n self.assertEqual(2, len(current_workloads))\n\n workload0 = get_current_workloads(docker_client)[0]\n self.assertEqual(c0_name, workload0.get_id())\n self.assertEqual(c0_thread_count, workload0.get_thread_count())\n\n workload1 = get_current_workloads(docker_client)[1]\n self.assertEqual(c1_name, workload1.get_id())\n self.assertEqual(c1_thread_count, workload1.get_thread_count())\n\n def test_get_current_missing_label_workload(self):\n # The BadContainer is missing an expected label\n class BadContainer:\n def __init__(self):\n self.name = \"bad-container\"\n self.labels = {\n CPU_LABEL_KEY: 2,\n }\n self.update_calls = []\n\n def update(self, **kwargs):\n log.info(\"bad container update called with: '{}'\".format(kwargs))\n threads = kwargs[\"cpuset_cpus\"].split(',')\n self.update_calls.append(threads)\n\n docker_client = MockDockerClient()\n self.assertEqual(0, len(get_current_workloads(docker_client)))\n\n docker_client.add_container(BadContainer())\n\n current_workloads = get_current_workloads(docker_client)\n self.assertEqual(0, len(current_workloads))\n\n def test_get_current_missing_label_workload(self):\n # The container is missing an expected label\n class BadLabelContainer(BadContainer):\n def __init__(self):\n self.name = \"bad-container\"\n self.labels = {\n CPU_LABEL_KEY: 2,\n }\n self.update_calls = []\n\n self.__test_get_current_bad_workload(BadLabelContainer())\n\n def test_get_current_incorrect_type_workload(self):\n # The BadTypeContainer has a non-integer CPU label\n class BadTypeContainer(BadContainer):\n def __init__(self):\n self.name = \"bad-container\"\n self.labels = {\n CPU_LABEL_KEY: \"x\",\n WORKLOAD_TYPE_LABEL_KEY: STATIC\n }\n self.update_calls = []\n\n self.__test_get_current_bad_workload(BadTypeContainer())\n\n def __test_get_current_bad_workload(self, bad_container):\n docker_client = MockDockerClient()\n self.assertEqual(0, len(get_current_workloads(docker_client)))\n\n docker_client.add_container(bad_container)\n\n current_workloads = get_current_workloads(docker_client)\n self.assertEqual(0, len(current_workloads))\n\n @staticmethod\n def __get_test_container(name, thread_count):\n return MockContainer(get_test_workload(name, thread_count, STATIC))\n","sub_path":"tests/event/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"162372828","text":"\"\"\"Utility functions that check the comments of a file\"\"\"\n\nimport re\n\nFILE_SEPARATOR = \"/\"\n\n# References:\n# https://stackoverflow.com/questions/15423658/regular-expression-for-single-line-comments\n# https://blog.ostermiller.org/find-comment\n\nMULTILINECOMMENT_RE = r\"\"\"/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/\"\"\"\nSINGLELINECOMMENT_RE_JAVA = r\"\"\"^(?:[^\"/\\\\]|\\\"(?:[^\\\"\\\\]|\\\\.)*\n\\\"|/(?:[^/\"\\\\]|\\\\.)|/\\\"(?:[^\\\"\\\\]|\\\\.)*\\\"|\\\\.)*//(.*)$\"\"\"\nSINGLELINECOMMENT_RE_PYTHON = r\"\"\"^(?:[^\"#\\\\]|\\\"(?:[^\\\"\\\\]|\\\\.)*\\\"|\n/(?:[^#\"\\\\]|\\\\.)|/\\\"(?:[^\\\"\\\\]|\\\\.)*\\\"|\\\\.)*#(.*)$\"\"\"\nMULTILINECOMMENT_RE_PYTHON = r'\"\"\".*?\\n.*?\"\"\"'\n\n\ndef count_singleline_java_comment(contents):\n \"\"\"Counts the number of singleline Java comments in the code\"\"\"\n pattern = re.compile(SINGLELINECOMMENT_RE_JAVA, re.MULTILINE | re.VERBOSE)\n matches = pattern.findall(contents)\n return len(matches)\n\n\ndef count_singleline_python_comment(contents):\n \"\"\"Counts the number of singleline Python comments in the code\"\"\"\n pattern = re.compile(SINGLELINECOMMENT_RE_PYTHON, re.MULTILINE)\n matches = pattern.findall(contents)\n return len(matches)\n\n\ndef count_multiline_java_comment(contents):\n \"\"\"Counts the number of multiline Java comments in the code\"\"\"\n pattern = re.compile(MULTILINECOMMENT_RE, re.MULTILINE)\n matches = pattern.findall(contents)\n return len(matches)\n\n\ndef count_multiline_python_comment(contents):\n \"\"\"Counts the number of multiline Python comments in the code\"\"\"\n pattern = re.compile(MULTILINECOMMENT_RE_PYTHON, re.DOTALL)\n matches = pattern.findall(contents)\n return len(matches)\n","sub_path":"gator/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"522541051","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\n\nINPUT_NODE = 784\nOUTPUT_NODE = 10\nLAYER1_NODE = 500\n\ndef get_weight_variable(shape,regularizer):\n weights = tf.get_variable('weights',shape,initializer = tf.truncated_normal_initializer(stddev=0.1))\n if(regularizer!=None):\n tf.add_to_collection('losses',regularizer(weights))\n return weights\n\ndef inference(input_tensor,regularizer):\n with tf.variable_scope('layer1',reuse=True):\n weights = get_weight_variable([INPUT_NODE,LAYER1_NODE],regularizer)\n biases = tf.get_variable('biases',[LAYER1_NODE],initializer = tf.constant_initializer(0.0))\n layer1 = tf.nn.relu(tf.matmul(input_tensor,weights) + biases) \n with tf.variable_scope('layer2',reuse=True):\n weights = get_weight_variable([LAYER1_NODE,OUTPUT_NODE],regularizer)\n biases = tf.get_variable('biases',[OUTPUT_NODE],initializer = tf.constant_initializer(0.0))\n layer2 = tf.matmul(layer1,weights) + biases\n return layer2\n\n#take care of the reuse param, you need to set it to true if you want to resue the layer1 and layer2 variable\n","sub_path":"DL/BP-tensorflow-mnist-inference.py","file_name":"BP-tensorflow-mnist-inference.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"520973415","text":"# -*- coding: utf-8 -*-\n\n# ***************************************************************************\n# * Copyright (C) 2019 by Hilscher GmbH *\n# * netXsupport@hilscher.com *\n# * *\n# * This program is free software; you can redistribute it and/or modify *\n# * it under the terms of the GNU General Public License as published by *\n# * the Free Software Foundation; either version 2 of the License, or *\n# * (at your option) any later version. *\n# * *\n# * This program is distributed in the hope that it will be useful, *\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n# * GNU General Public License for more details. *\n# * *\n# * You should have received a copy of the GNU General Public License *\n# * along with this program; if not, write to the *\n# * Free Software Foundation, Inc., *\n# * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n# ***************************************************************************\n\n# Limitations:\n# No define mechanism (-D)\n# Limited alias mechanism (only for files), also used to replace segments\n# and headeraddress\n# No String datatype in concat.\n# One or two data blocks\n\nimport argparse\nimport array\nimport base64\nimport binascii\nimport elf_support\nimport hashlib\nimport logging\nimport os\nimport re\nimport string\nimport platform\nimport subprocess\nimport tempfile\nimport xml.dom.minidom\nimport xml.etree.ElementTree\n\n\n# Is this a standalone script?\nif __name__ != '__main__':\n # No -> import the SCons module.\n import SCons.Script\n\n\nclass AppImage:\n # This is the environment.\n __tEnv = None\n\n # This is a list of all include paths.\n __astrIncludePaths = None\n\n # This is a dictionary of all resolved files.\n __atKnownFiles = None\n\n # This is a two-layer dictionary mapping ELF file paths and segment names\n # to an entry for each segment. It is used to keep track of which segments\n # have been used in a boot image.\n __tElfSegments = None\n\n # No data blocks yet.\n __atDataBlocks = None\n\n # No SDRamOffset yet.\n __ulSDRamSplitOffset = None\n\n __strNetxType = None\n\n __XmlKeyromContents = None\n __cfg_openssl = 'openssl'\n __cfg_openssloptions = None\n __fOpensslRandOff = False\n __signed_binding = False\n\n def __init__(self, tEnv, strNetxType, astrIncludePaths, atKnownFiles,\n ulSDRamSplitOffset, strOpensslExe, fOpensslRandOff):\n self.__tEnv = tEnv\n self.__astrIncludePaths = astrIncludePaths\n self.__atKnownFiles = atKnownFiles\n self.__ulSDRamSplitOffset = ulSDRamSplitOffset\n self.__strNetxType = strNetxType\n\n self.__cfg_openssl = strOpensslExe\n # No SSL options yet.\n self.__cfg_openssloptions = []\n self.__fOpensslRandOff = fOpensslRandOff\n\n def segments_init(self):\n self.__tElfSegments = {}\n\n # check if the segment list for ELF is already in the list and add it,\n # if not.\n def segments_get_elf_segments(self, strElfPath):\n if strElfPath not in self.__tElfSegments:\n atSegmentsAll = elf_support.get_segment_table(\n self.__tEnv,\n strElfPath,\n None\n )\n\n # construct a name to segment mapping\n tSegments = {}\n for tSegment in atSegmentsAll:\n if elf_support.segment_is_loadable(tSegment):\n strName = elf_support.segment_get_name(tSegment)\n ulSize = elf_support.segment_get_size(tSegment)\n tEntry = {\n 'name': strName,\n 'size': ulSize,\n 'used': False\n }\n tSegments[strName] = tEntry\n\n self.__tElfSegments[strElfPath] = tSegments\n\n return self.__tElfSegments[strElfPath]\n\n # mark a segment in an ELF file as used\n # todo: We only warn if the segment is not known in this ELF file.\n def segments_mark_used(self, strElfPath, strSegmentName):\n tSegments = self.segments_get_elf_segments(strElfPath)\n if strSegmentName in tSegments:\n tSegments[strSegmentName]['used'] = True\n\n # mark all segments of an ELF file as used\n def segments_mark_used_all(self, strElfPath):\n tSegments = self.segments_get_elf_segments(strElfPath)\n for tSegment in tSegments.values():\n tSegment['used'] = True\n\n # check if there are any unused segments which contain data\n def segments_check_unused(self):\n fUnusedSegments = False\n for strElfPath, tSegments in self.__tElfSegments.items():\n for tSegment in tSegments.values():\n if tSegment['used'] is not True:\n if tSegment['size'] == 0:\n print(\"Info: Unused empty segment '%s' in %s\" % (\n tSegment['name'],\n strElfPath\n ))\n else:\n print(\"Warning: Unused segment '%s' in file %s\" % (\n tSegment['name'],\n strElfPath\n ))\n fUnusedSegments = True\n if fUnusedSegments is False:\n print(\"No unused segments found\")\n return fUnusedSegments\n\n def read_keyrom(self, strKeyromFile):\n # Read the keyrom file if specified.\n if strKeyromFile is not None:\n # Parse the XML file.\n tFile = open(strKeyromFile, 'rt')\n strXml = tFile.read()\n tFile.close()\n self.__XmlKeyromContents = xml.etree.ElementTree.fromstring(strXml)\n\n # If strVal begins with the @ character:\n # If the remainder of the string can be resolved as an alias, return the\n # resolved value.\n # If not, raise an error.\n # If strVal does not begin with the @ character, return strVal.\n def resolve_alias(self, strVal):\n if len(strVal) > 0 and strVal[0] == '@':\n strAlias = strVal[1:]\n if strAlias in self.__atKnownFiles:\n strVal = self.__atKnownFiles[strAlias]\n else:\n raise Exception('Missing definition for alias: %s' % strAlias)\n\n return strVal\n\n # If strVal begins with the @ character:\n # If the remainder of the string can be resolved as an alias, return\n # the resolved value.\n # If not, return the empty string.\n # If strVal does not begin with the @ character, return strVal.\n def safe_resolve_alias(self, strVal):\n if len(strVal) > 0 and strVal[0] == '@':\n strAlias = strVal[1:]\n if strAlias in self.__atKnownFiles:\n strVal = self.__atKnownFiles[strAlias]\n else:\n strVal = \"\"\n return strVal\n\n def is_alias(self, strVal):\n return len(strVal) > 0 and strVal[0] == '@'\n\n def __find_file(self, strFilePath):\n strAbsFilePath = None\n\n # Is this a file reference?\n if strFilePath[0] == '@':\n strFileId = strFilePath[1:]\n if strFileId in self.__atKnownFiles:\n strAbsFilePath = self.__atKnownFiles[strFileId]\n else:\n # Try the current working directory first.\n if os.access(strFilePath, os.R_OK) is True:\n strAbsFilePath = os.path.abspath(strFilePath)\n else:\n # Loop over all include folders.\n for strIncludePath in self.__astrIncludePaths:\n strPath = os.path.abspath(\n os.path.join(strIncludePath, strFilePath)\n )\n if os.access(strPath, os.R_OK) is True:\n strAbsFilePath = strPath\n break\n\n return strAbsFilePath\n\n # Robustly convert boolean strings into boolean values.\n def __string_to_bool(self, strBool):\n strBool = strBool.upper()\n if(\n (strBool == 'TRUE') or\n (strBool == 'T') or\n (strBool == 'YES') or\n (strBool == 'Y') or\n (strBool == '1')\n ):\n fBool = True\n elif(\n (strBool == 'FALSE') or\n (strBool == 'F') or\n (strBool == 'NO') or\n (strBool == 'N') or\n (strBool == '0')\n ):\n fBool = False\n else:\n fBool = None\n return fBool\n \n # Get a boolean value from a tag attribute.\n # If fDefault is defined, the attribute is optional,\n # if fDefault is None, it is mandatory.\n def __xml_get_boolean_attribute_value(self, tNode, strAttribName, \n fDefault = None):\n fBool = fDefault\n strBool = tNode.getAttribute(strAttribName)\n if len(strBool) == 0:\n if fBool == None:\n raise Exception(\"The attribute %s in node %s is missing!\" \n % (strAttribName, tNode.tag))\n else:\n fBool = self.__string_to_bool(strBool)\n if fBool == None:\n raise Exception(\n \"The attribute '%s' in node '%s' has an illegal value!\" \n % (strAttribName, tNode.localName))\n \n return fBool\n \n def __xml_get_all_text(self, tNode):\n astrText = []\n for tChild in tNode.childNodes:\n if(\n (tChild.nodeType == tChild.TEXT_NODE) or\n (tChild.nodeType == tChild.CDATA_SECTION_NODE)\n ):\n astrText.append(str(tChild.data))\n return ''.join(astrText)\n\n def __remove_all_whitespace(self, strData):\n astrWhitespace = [' ', '\\t', '\\n', '\\r']\n for strWhitespace in astrWhitespace:\n strData = strData.replace(strWhitespace, '')\n return strData\n\n def __parse_numeric_expression(self, strData):\n ulValue = int(strData, 0)\n return ulValue\n\n def __get_tag_id(self, cId0, cId1, cId2, cId3):\n # Combine the 4 ID characters to a 32 bit value.\n ulId = (\n ord(cId0) |\n (ord(cId1) << 8) |\n (ord(cId2) << 16) |\n (ord(cId3) << 24)\n )\n return ulId\n\n def __get_data_contents_elf(self, tNode, strAbsFilePath):\n # Get the segment names to dump. It is a comma separated string.\n # This is optional. If no segment names are specified, all sections\n # with PROGBITS are dumped.\n strSegmentsToDump = self.resolve_alias(\n tNode.getAttribute('segments').strip()\n )\n astrSegmentsToDump = None\n if strSegmentsToDump == ',':\n # Note: astrSegmentsToDump must be empty, not None\n astrSegmentsToDump = []\n elif len(strSegmentsToDump) != 0:\n astrSegmentsToDump = [\n strSegment.strip() for strSegment in\n strSegmentsToDump.split(',')\n ]\n print('Elf file: %s Used segments: %s' % (\n strAbsFilePath,\n strSegmentsToDump\n ))\n else:\n print('Elf file: %s Selecting segments automatically' %\n strAbsFilePath)\n\n # Extract the segments.\n atSegments = elf_support.get_segment_table(\n self.__tEnv,\n strAbsFilePath,\n astrSegmentsToDump\n )\n\n print(\"%d segments found\" % len(atSegments))\n for tSegment in atSegments:\n print(tSegment)\n\n # atSegments is the list of segments contained in the elf file.\n # astrSegmentsToDump is the list of names of the segments to\n # dump (from the XML file).\n\n # If astrSegmentsToDump is not None and non-empty,\n # filter the segments and the list of segments to dump.\n #\n # For each segment name in astrSegmentsToDump:\n # If the segment is not present in atSegments, print a warning and\n # remove the name from astrSegmentsToDump.\n # If the segment is in atSegments but its size is 0, warn and remove\n # it from astrSegmentsToDump and atSegments.\n # If the segment is in atSegments but not marked as loadable, warn\n # and remove it from astrSegmentsToDump and atSegments.\n\n # If astrSegmentsToDump is None:\n # Do we have to do anything?\n\n if astrSegmentsToDump is not None:\n atName2Segment = dict({})\n astrSegments2 = []\n atSegments2 = []\n\n # prepare a segment name to segment mapping from atSegments\n for tSegment in atSegments:\n strName = elf_support.segment_get_name(tSegment)\n atName2Segment[strName] = tSegment\n\n for strName in astrSegmentsToDump:\n if strName not in atName2Segment:\n print(\"Warning: Requested segment %s not found \"\n \"- ignoring\" % strName)\n else:\n tSegment = atName2Segment[strName]\n if elf_support.segment_get_size(tSegment) == 0:\n print(\"Warning: Requested segment %s is empty \"\n \"- ignoring\" % strName)\n self.segments_mark_used(strAbsFilePath, strName)\n elif elf_support.segment_is_loadable(tSegment) is False:\n print(\"Warning: Requested segment %s is not loadable \"\n \"- ignoring\" % strName)\n else:\n print(\"Found requested segment %s\" % strName)\n astrSegments2.append(strName)\n atSegments2.append(tSegment)\n self.segments_mark_used(strAbsFilePath, strName)\n\n astrSegmentsToDump = astrSegments2\n atSegments = atSegments2\n\n if len(atSegments) == 0:\n strData = ''\n pulLoadAddress = 0\n self.segments_mark_used_all(strAbsFilePath)\n\n else:\n # Get the estimated binary size from the segments.\n ulEstimatedBinSize = elf_support.get_estimated_bin_size(atSegments)\n # Do not create files larger than 512MB.\n if ulEstimatedBinSize >= 0x20000000:\n raise Exception('The resulting file seems to extend '\n '512MBytes. Too scared to continue!')\n\n strOverwriteAddress = tNode.getAttribute(\n 'overwrite_address'\n ).strip()\n if len(strOverwriteAddress) == 0:\n pulLoadAddress = elf_support.get_load_address(atSegments)\n else:\n pulLoadAddress = int(strOverwriteAddress, 0)\n\n # Extract the binary.\n tBinFile, strBinFileName = tempfile.mkstemp()\n os.close(tBinFile)\n astrCmd = [\n self.__tEnv['OBJCOPY'],\n '--output-target=binary'\n ]\n if astrSegmentsToDump is not None:\n for strSegment in astrSegmentsToDump:\n astrCmd.append('--only-section=%s' % strSegment)\n astrCmd.append(strAbsFilePath)\n astrCmd.append(strBinFileName)\n subprocess.check_call(astrCmd)\n\n # Get the application data.\n tBinFile = open(strBinFileName, 'rb')\n strData = tBinFile.read()\n tBinFile.close()\n\n # Remove the temp file.\n os.remove(strBinFileName)\n\n return strData, pulLoadAddress\n\n def __get_data_contents(self, tDataNode):\n strData = None\n pulLoadAddress = None\n\n # Loop over all child nodes.\n for tNode in tDataNode.childNodes:\n # Is this a node element?\n if tNode.nodeType == tNode.ELEMENT_NODE:\n # Is this a \"File\" node?\n if tNode.localName == 'File':\n # Get the file name.\n strFileName = tNode.getAttribute('name')\n if len(strFileName) == 0:\n raise Exception(\n \"The file node has no name attribute!\"\n )\n\n # Search the file in the current working folder and all\n # include paths.\n strAbsFilePath = self.__find_file(strFileName)\n if strAbsFilePath is None:\n raise Exception('File %s not found!' % strFileName)\n\n # Is this an ELF file?\n strRoot, strExtension = os.path.splitext(strAbsFilePath)\n if strExtension == '.elf':\n strData, pulLoadAddress = self.__get_data_contents_elf(\n tNode,\n strAbsFilePath\n )\n\n elif strExtension == '.bin':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The File node points to a binary file '\n 'and has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n tBinFile = open(strAbsFilePath, 'rb')\n strData = tBinFile.read()\n tBinFile.close()\n\n else:\n raise Exception('The File node points to a file with '\n 'an unknown extension: %s' %\n strExtension)\n # Is this a node element with the name 'Hex'?\n elif tNode.localName == 'Hex':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The Hex node has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n # Get the text in this node and parse it as hex data.\n strDataHex = self.__xml_get_all_text(tNode)\n if strDataHex is None:\n raise Exception('No text in node \"Hex\" found!')\n\n strDataHex = self.__remove_all_whitespace(strDataHex)\n strData = binascii.unhexlify(strDataHex)\n\n elif tNode.localName == 'UInt32':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The UInt32 node has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n # Get the text in this node and split it by whitespace.\n strDataUint = self.__xml_get_all_text(tNode)\n if strDataUint is None:\n raise Exception('No text in node \"UInt32\" found!')\n\n astrNumbers = strDataUint.split()\n aulNumbers = array.array('I')\n for strNumber in astrNumbers:\n ulNumber = int(strNumber, 0)\n aulNumbers.append(ulNumber)\n\n strData = aulNumbers.tostring()\n\n elif tNode.localName == 'UInt16':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The UInt16 node has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n # Get the text in this node and split it by whitespace.\n strDataUint = self.__xml_get_all_text(tNode)\n if strDataUint is None:\n raise Exception('No text in node \"UInt16\" found!')\n\n astrNumbers = strDataUint.split()\n ausNumbers = array.array('H')\n for strNumber in astrNumbers:\n usNumber = int(strNumber, 0)\n ausNumbers.append(usNumber)\n\n strData = ausNumbers.tostring()\n\n elif tNode.localName == 'UInt8':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The UInt8 node has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n # Get the text in this node and split it by whitespace.\n strDataUint = self.__xml_get_all_text(tNode)\n if strDataUint is None:\n raise Exception('No text in node \"UInt8\" found!')\n\n astrNumbers = strDataUint.split()\n aucNumbers = array.array('B')\n for strNumber in astrNumbers:\n ucNumber = int(strNumber, 0)\n aucNumbers.append(ucNumber)\n\n strData = aucNumbers.tostring()\n\n elif tNode.localName == 'Concat':\n strLoadAddress = tNode.getAttribute('load_address')\n if len(strLoadAddress) == 0:\n raise Exception(\n 'The Concat node has no load_address attribute!'\n )\n\n pulLoadAddress = self.__parse_numeric_expression(\n strLoadAddress\n )\n\n astrData = []\n\n # Loop over all sub-nodes.\n for tConcatNode in tNode.childNodes:\n # Is this a node element?\n if tConcatNode.nodeType == tConcatNode.ELEMENT_NODE:\n # Is this a node element with the name 'Hex'?\n if tConcatNode.localName == 'Hex':\n # Get the text in this node and parse it\n # as hex data.\n strDataHex = self.__xml_get_all_text(\n tConcatNode\n )\n if strDataHex is None:\n raise Exception('No text in node '\n '\"Hex\" found!')\n\n strDataHex = self.__remove_all_whitespace(\n strDataHex\n )\n strDataChunk = binascii.unhexlify(strDataHex)\n astrData.append(strDataChunk)\n\n elif tConcatNode.localName == 'UInt32':\n # Get the text in this node and split it\n # by whitespace.\n strDataUint = self.__xml_get_all_text(\n tConcatNode\n )\n if strDataUint is None:\n raise Exception('No text in node '\n '\"UInt32\" found!')\n\n astrNumbers = strDataUint.split()\n aulNumbers = array.array('I')\n for strNumber in astrNumbers:\n ulNumber = int(strNumber, 0)\n aulNumbers.append(ulNumber)\n\n strDataChunk = aulNumbers.tostring()\n astrData.append(strDataChunk)\n\n elif tConcatNode.localName == 'UInt16':\n # Get the text in this node and split it\n # by whitespace.\n strDataUint = self.__xml_get_all_text(\n tConcatNode\n )\n if strDataUint is None:\n raise Exception('No text in node '\n '\"UInt16\" found!')\n\n astrNumbers = strDataUint.split()\n ausNumbers = array.array('H')\n for strNumber in astrNumbers:\n usNumber = int(strNumber, 0)\n ausNumbers.append(usNumber)\n\n strDataChunk = ausNumbers.tostring()\n astrData.append(strDataChunk)\n\n elif tConcatNode.localName == 'UInt8':\n # Get the text in this node and split it\n # by whitespace.\n strDataUint = self.__xml_get_all_text(\n tConcatNode\n )\n if strDataUint is None:\n raise Exception('No text in node \"UInt8\" '\n ' found!')\n\n astrNumbers = strDataUint.split()\n aucNumbers = array.array('B')\n for strNumber in astrNumbers:\n ucNumber = int(strNumber, 0)\n aucNumbers.append(ucNumber)\n\n strDataChunk = aucNumbers.tostring()\n astrData.append(strDataChunk)\n\n strData = ''.join(astrData)\n\n else:\n raise Exception('Unexpected node: %s' % tNode.localName)\n\n # Check if all parameters are there.\n if strData is None:\n raise Exception('No data specified!')\n if pulLoadAddress is None:\n raise Exception('No load address specified!')\n\n return strData, pulLoadAddress\n\n def __cert_parse_binding(self, tNodeParent, strName):\n # The binding is not yet set.\n strBinding = None\n\n # Loop over all child nodes.\n for tNode in tNodeParent.childNodes:\n if(\n (tNode.nodeType == tNode.ELEMENT_NODE) and\n (tNode.localName == strName)\n ):\n strBinding = self.__xml_get_all_text(tNode)\n\n if strBinding is None:\n raise Exception('No \"%s\" node found!' % strName)\n\n strBinding = self.__remove_all_whitespace(strBinding)\n aucBinding = array.array('B', binascii.unhexlify(strBinding))\n sizBinding = len(aucBinding)\n\n # A binding block has a size of 28 bytes on the netX90.\n sizBindingExpected = 28\n\n if sizBinding != sizBindingExpected:\n raise Exception('The binding in node \"%s\" has an invalid size '\n 'of %d bytes.' % (strName, sizBinding))\n\n return aucBinding\n\n # This function gets a data block from the OpenSSL output.\n def __openssl_get_data_block(self, strStdout, strID):\n aucData = array.array('B')\n tReData = re.compile('^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*:?$')\n iState = 0\n for strLine in iter(strStdout.splitlines()):\n strLine = strLine.strip()\n if iState == 0:\n if strLine == strID:\n iState = 1\n elif iState == 1:\n tMatch = tReData.search(strLine)\n if tMatch is None:\n break\n else:\n for strDataHex in strLine.split(':'):\n strDataHexStrip = strDataHex.strip()\n if len(strDataHexStrip) != 0:\n strDataBin = binascii.unhexlify(strDataHexStrip)\n aucData.append(ord(strDataBin))\n\n return aucData\n\n def __openssl_cut_leading_zero(self, aucData):\n # Does the number start with \"00\" and is the third digit >= 8?\n if aucData[0] == 0x00 and aucData[1] >= 0x80:\n # Remove the leading \"00\".\n aucData.pop(0)\n\n def __openssl_convert_to_little_endian(self, aucData):\n aucData.reverse()\n\n def __openssl_uncompress_field(self, aucData):\n # The data must not be compressed.\n if aucData[0] != 0x04:\n raise Exception('The data is compressed. '\n 'This is not supported yet.')\n # Cut off the first byte.\n aucData.pop(0)\n\n def __openssl_cut_in_half(self, aucData):\n # Cut the public key in equal parts.\n sizDataHalf = len(aucData) / 2\n aucData0 = array.array('B', aucData[:sizDataHalf])\n aucData1 = array.array('B', aucData[sizDataHalf:])\n return aucData0, aucData1\n\n def __keyrom_get_key(self, uiIndex):\n # This needs the keyrom data.\n if self.__XmlKeyromContents is None:\n raise Exception('No Keyrom contents specified!')\n\n # Find the requested key and hash.\n tNode = self.__XmlKeyromContents.find('Entry/[@index=\"%d\"]' % uiIndex)\n if tNode is None:\n raise Exception('Key %d was not found!' % uiIndex)\n tNode_key = tNode.find('Key')\n if tNode_key is None:\n raise Exception('Key %d has no \"Key\" child!' % uiIndex)\n tNode_hash = tNode.find('Hash')\n if tNode_hash is None:\n raise Exception('Key %d has no \"Hash\" child!' % uiIndex)\n\n strKeyBase64 = tNode_key.text\n\n # Decode the BASE64 data. Now we have the key pair in DER format.\n strKeyDER = base64.b64decode(strKeyBase64)\n\n return strKeyDER\n\n def __get_cert_mod_exp(self, tNodeParent, strKeyDER, fIsPublicKey):\n # Extract all information from the key.\n if len(strKeyDER) > 1000:\n astrCmd = [\n self.__cfg_openssl,\n 'pkey',\n '-inform',\n 'DER',\n '-text',\n '-noout'\n ]\n else:\n astrCmd = [\n self.__cfg_openssl,\n 'ec',\n '-inform',\n 'DER',\n '-text',\n '-noout',\n '-param_enc', 'explicit',\n '-no_public'\n ]\n if fIsPublicKey is True:\n astrCmd.append('-pubin')\n if platform.system() == 'Windows':\n tProcess = subprocess.Popen(\n astrCmd,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n shell=True\n )\n else:\n tProcess = subprocess.Popen(\n astrCmd,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE\n )\n (strStdout, strStdErr) = tProcess.communicate(strKeyDER)\n if tProcess.returncode != 0:\n raise Exception('OpenSSL failed with return code %d.' %\n tProcess.returncode)\n\n # Try to guess if this is an RSA or ECC key.\n # The text dump of an RSA key has \" modulus:\", while an ECC key has\n # \"priv:\".\n iKeyTyp_1ECC_2RSA = None\n atAttr = None\n if strStdout.find('modulus:') != -1:\n # Looks like this is an RSA key.\n iKeyTyp_1ECC_2RSA = 2\n\n strMatchExponent = 'publicExponent:'\n strMatchModulus = 'modulus:'\n if fIsPublicKey is True:\n strMatchExponent = 'Exponent:'\n strMatchModulus = 'Modulus:'\n\n # Extract the public exponent.\n tReExp = re.compile(\n r'^%s\\s+(\\d+)\\s+\\(0x([0-9a-fA-F]+)\\)' % strMatchExponent,\n re.MULTILINE\n )\n tMatch = tReExp.search(strStdout)\n if tMatch is None:\n raise Exception('Can not find public exponent!')\n ulExp = int(tMatch.group(1))\n ulExpHex = int(tMatch.group(2), 16)\n if ulExp != ulExpHex:\n raise Exception('Decimal version differs from hex version!')\n if (ulExp < 0) or (ulExp > 0xffffff):\n raise Exception('The exponent exceeds the allowed range of a '\n '24bit unsigned integer!')\n strData = (\n chr(ulExp & 0xff) +\n chr((ulExp >> 8) & 0xff) +\n chr((ulExp >> 16) & 0xff)\n )\n aucExp = array.array('B', strData)\n\n # Extract the modulus \"N\".\n aucMod = self.__openssl_get_data_block(strStdout, strMatchModulus)\n self.__openssl_cut_leading_zero(aucMod)\n self.__openssl_convert_to_little_endian(aucMod)\n\n __atKnownRsaSizes = {\n 0: {'mod': 256, 'exp': 3, 'rsa': 2048},\n 1: {'mod': 384, 'exp': 3, 'rsa': 3072},\n 2: {'mod': 512, 'exp': 3, 'rsa': 4096}\n }\n\n sizMod = len(aucMod)\n sizExp = len(aucExp)\n uiId = None\n for uiElementId, atAttr in __atKnownRsaSizes.items():\n if (sizMod == atAttr['mod']) and (sizExp == atAttr['exp']):\n uiId = uiElementId + 1\n break\n\n if uiId is None:\n strErr = (\n 'The modulo has a size of %d bytes. '\n 'The public exponent has a size of %d bytes.\\n'\n 'These values can not be mapped to a RSA bit size. '\n 'Known sizes are:\\n' % (\n sizMod,\n sizExp\n )\n )\n for uiElementId, atAttr in __atKnownRsaSizes.items():\n strErr += (\n ' RSA%d: %d bytes modulo, '\n '%d bytes public exponent\\n' % (\n atAttr['rsa'],\n atAttr['mod'],\n atAttr['exp']\n )\n )\n raise Exception(strErr)\n\n atAttr = {\n 'id': uiId,\n 'mod': aucMod,\n 'exp': aucExp\n }\n\n elif strStdout.find('priv:') != -1:\n # Looks like this is an ECC key.\n iKeyTyp_1ECC_2RSA = 1\n\n aucPriv = self.__openssl_get_data_block(strStdout, 'priv:')\n self.__openssl_cut_leading_zero(aucPriv)\n self.__openssl_convert_to_little_endian(aucPriv)\n\n aucPub = self.__openssl_get_data_block(strStdout, 'pub:')\n self.__openssl_uncompress_field(aucPub)\n aucPubX, aucPubY = self.__openssl_cut_in_half(aucPub)\n self.__openssl_convert_to_little_endian(aucPubX)\n self.__openssl_convert_to_little_endian(aucPubY)\n\n aucPrime = self.__openssl_get_data_block(strStdout, 'Prime:')\n self.__openssl_cut_leading_zero(aucPrime)\n self.__openssl_convert_to_little_endian(aucPrime)\n\n aucA = self.__openssl_get_data_block(strStdout, 'A:')\n self.__openssl_cut_leading_zero(aucA)\n self.__openssl_convert_to_little_endian(aucA)\n\n aucB = self.__openssl_get_data_block(strStdout, 'B:')\n self.__openssl_cut_leading_zero(aucB)\n self.__openssl_convert_to_little_endian(aucB)\n\n strData = self.__openssl_get_data_block(\n strStdout,\n 'Generator (uncompressed):'\n )\n aucGen = array.array('B', strData)\n self.__openssl_uncompress_field(aucGen)\n aucGenX, aucGenY = self.__openssl_cut_in_half(aucGen)\n self.__openssl_convert_to_little_endian(aucGenX)\n self.__openssl_convert_to_little_endian(aucGenY)\n\n aucOrder = self.__openssl_get_data_block(strStdout, 'Order:')\n self.__openssl_cut_leading_zero(aucOrder)\n self.__openssl_convert_to_little_endian(aucOrder)\n\n # Extract the cofactor.\n tReExp = re.compile(r'^Cofactor:\\s+(\\d+)\\s+\\(0x([0-9a-fA-F]+)\\)',\n re.MULTILINE)\n tMatch = tReExp.search(strStdout)\n if tMatch is None:\n raise Exception('Can not find cofactor!')\n ulCofactor = int(tMatch.group(1))\n ulCofactorHex = int(tMatch.group(2), 16)\n if ulCofactor != ulCofactorHex:\n raise Exception('Decimal version differs from hex version!')\n\n __atKnownEccSizes = {\n 0: 32,\n 1: 48,\n 2: 64\n }\n\n sizD = len(aucPriv)\n sizQx = len(aucPubX)\n sizQy = len(aucPubY)\n sizP = len(aucPrime)\n sizA = len(aucA)\n sizB = len(aucB)\n sizGx = len(aucGenX)\n sizGy = len(aucGenY)\n sizN = len(aucOrder)\n uiId = None\n for uiElementId, sizNumbers in __atKnownEccSizes.items():\n if(\n (sizNumbers == sizD) and\n (sizNumbers == sizQx) and\n (sizNumbers == sizQy) and\n (sizNumbers == sizP) and\n (sizNumbers == sizA) and\n (sizNumbers == sizB) and\n (sizNumbers == sizGx) and\n (sizNumbers == sizGy) and\n (sizNumbers == sizN)\n ):\n # Found the ECC type.\n uiId = uiElementId + 1\n break\n\n if uiId is None:\n raise Exception('Invalid ECC key.')\n\n atAttr = {\n 'id': uiId,\n 'd': aucPriv,\n 'Qx': aucPubX,\n 'Qy': aucPubY,\n 'p': aucPrime,\n 'a': aucA,\n 'b': aucB,\n 'Gx': aucGenX,\n 'Gy': aucGenY,\n 'n': aucOrder,\n 'cof': ulCofactor\n }\n\n else:\n raise Exception('Unknown key format.')\n\n return iKeyTyp_1ECC_2RSA, atAttr\n\n def __usip_parse_trusted_path(self, tNodeParent, atData):\n strKeyDER = None\n # Get the index.\n strIdx = tNodeParent.getAttribute('idx')\n if len(strIdx) != 0:\n ulIdx = self.__parse_numeric_expression(strIdx)\n\n # Get the key in DER encoded format.\n strKeyDER = self.__keyrom_get_key(ulIdx)\n\n else:\n # Search for a \"File\" child node.\n tFileNode = None\n for tNode in tNodeParent.childNodes:\n if(\n (tNode.nodeType == tNode.ELEMENT_NODE) and\n (tNode.localName == 'File')\n ):\n tFileNode = tNode\n break\n if tFileNode is not None:\n strFileName = tFileNode.getAttribute('name')\n\n # Search the file in the current path and all include paths.\n strAbsName = self.__find_file(strFileName)\n if strAbsName is None:\n raise Exception(\n 'Failed to read file \"%s\": file not found.' %\n strFileName\n )\n\n # Read the complete key.\n tFile = open(strAbsName, 'rb')\n strKeyDER = tFile.read()\n tFile.close()\n\n if strKeyDER is None:\n raise Exception('No \"idx\" attribute and no child \"File\" found!')\n\n iKeyTyp_1ECC_2RSA, atAttr = self.__get_cert_mod_exp(\n tNodeParent,\n strKeyDER,\n False\n )\n\n atData['iKeyTyp_1ECC_2RSA'] = iKeyTyp_1ECC_2RSA\n atData['atAttr'] = atAttr\n atData['der'] = strKeyDER\n\n def __build_chunk_asig(self, tChunkNode, aulFWHash):\n aulChunk = None\n\n # Generate an array with default values where possible.\n __atCert = {\n # The key must be set by the user.\n 'Key': {\n 'type': None,\n 'id': None,\n 'mod': None,\n 'exp': None,\n 'der': None\n },\n\n # The Binding must be set by the user.\n 'Binding': {\n 'mask': None,\n 'ref': None\n }\n }\n\n # Loop over all children.\n for tNode in tChunkNode.childNodes:\n if tNode.nodeType == tNode.ELEMENT_NODE:\n if tNode.localName == 'Key':\n self.__usip_parse_trusted_path(tNode, __atCert['Key'])\n\n elif tNode.localName == 'Binding':\n __atCert['Binding']['value'] = self.__cert_parse_binding(\n tNode,\n 'Value'\n )\n __atCert['Binding']['mask'] = self.__cert_parse_binding(\n tNode,\n 'Mask'\n )\n\n else:\n raise Exception('Unexpected node: %s' %\n tNode.localName)\n\n # Check if all required data was set.\n astrErr = []\n if __atCert['Key']['der'] is None:\n astrErr.append('No key set in USIP.')\n if __atCert['Binding']['mask'] is None:\n astrErr.append('No \"mask\" set in the Binding.')\n if __atCert['Binding']['value'] is None:\n astrErr.append('No \"value\" set in the Binding.')\n if len(astrErr) != 0:\n raise Exception('\\n'.join(astrErr))\n\n iKeyTyp_1ECC_2RSA = __atCert['Key']['iKeyTyp_1ECC_2RSA']\n atAttr = __atCert['Key']['atAttr']\n if iKeyTyp_1ECC_2RSA == 1:\n sizKeyInDwords = len(atAttr['Qx']) / 4\n sizSignatureInDwords = 2 * sizKeyInDwords\n elif iKeyTyp_1ECC_2RSA == 2:\n sizKeyInDwords = len(atAttr['mod']) / 4\n sizSignatureInDwords = sizKeyInDwords\n\n # The size of the ASIG thing without the signature is...\n # 4 bytes ID\n # 4 bytes length\n # 56 bytes binding\n # 48 bytes hash\n # ----------------------\n # 112 bytes or\n # 28 DWORDs\n\n # Combine all data to the chunk.\n aulChunk = array.array('I')\n aulChunk.append(self.__get_tag_id('A', 'S', 'I', 'G'))\n aulChunk.append(28 + sizSignatureInDwords)\n\n # Add the binding.\n aulChunk.fromstring(__atCert['Binding']['value'].tostring())\n aulChunk.fromstring(__atCert['Binding']['mask'].tostring())\n\n if self.__signed_binding:\n # Append fw hash\n aulChunk.extend(aulFWHash)\n print(\"fw hash: %s\" % aulFWHash)\n else:\n # Build a hash over the first part of the chunk.\n tHash = hashlib.sha384()\n tHash.update(aulChunk.tostring())\n strHash = tHash.digest()\n aulHash = array.array('I', strHash)\n aulChunk.extend(aulHash)\n\n # Get the key in DER encoded format.\n strKeyDER = __atCert['Key']['der']\n\n # Create a temporary file for the keypair.\n iFile, strPathKeypair = tempfile.mkstemp(\n suffix='der',\n prefix='tmp_hboot_image',\n dir=None,\n text=False\n )\n os.close(iFile)\n\n # Create a temporary file for the data to sign.\n iFile, strPathSignatureInputData = tempfile.mkstemp(\n suffix='bin',\n prefix='tmp_hboot_image',\n dir=None,\n text=False\n )\n os.close(iFile)\n\n # Write the DER key to the temporary file.\n tFile = open(strPathKeypair, 'wb')\n tFile.write(strKeyDER)\n tFile.close()\n\n tFile = open(strPathSignatureInputData, 'wb')\n if self.__signed_binding is False:\n # Write the data from the fw to the file\n # Write the data to sign to the temporary file.\n aulChunk0Data = self.__atDataBlocks[0]['data']\n tFile.write(aulChunk0Data[0:112])\n tFile.write(aulChunk0Data[128:])\n sizDataBlocks = len(self.__atDataBlocks)\n for sizCnt in range(1, sizDataBlocks):\n tFile.write(self.__atDataBlocks[sizCnt]['header'])\n tFile.write(self.__atDataBlocks[sizCnt]['data'])\n else:\n # Write the data from the chunk to the file instead of the whole fw\n tFile.write(aulChunk)\n tFile.close()\n\n if iKeyTyp_1ECC_2RSA == 1:\n astrCmd = [\n self.__cfg_openssl,\n 'dgst',\n '-sign', strPathKeypair,\n '-keyform', 'DER',\n '-sha384'\n ]\n astrCmd.extend(self.__cfg_openssloptions)\n astrCmd.append(strPathSignatureInputData)\n strEccSignature = subprocess.check_output(astrCmd)\n aucEccSignature = array.array('B', strEccSignature)\n\n # Parse the signature.\n aucSignature = self.__openssl_ecc_get_signature(\n aucEccSignature,\n sizKeyInDwords * 4\n )\n\n elif iKeyTyp_1ECC_2RSA == 2:\n astrCmd = [\n self.__cfg_openssl,\n 'dgst',\n '-sign', strPathKeypair,\n '-keyform', 'DER',\n '-sha384'\n ]\n if self.__cfg_openssloptions:\n astrCmd.extend(self.__cfg_openssloptions)\n if not self.__fOpensslRandOff:\n astrCmd.extend([\n '-sigopt', 'rsa_padding_mode:pss',\n '-sigopt', 'rsa_pss_saltlen:-1'])\n astrCmd.append(strPathSignatureInputData)\n strSignatureMirror = subprocess.check_output(astrCmd)\n aucSignature = array.array('B', strSignatureMirror)\n # Mirror the signature.\n aucSignature.reverse()\n\n # Remove the temp files.\n os.remove(strPathKeypair)\n os.remove(strPathSignatureInputData)\n\n # Append the signature to the chunk.\n aulChunk.fromstring(aucSignature.tostring())\n # print(\"signature: %s \" % aucSignature.tostring())\n\n return aulChunk\n\n ROMLOADER_CHIPTYP_NETX90_MPW = 10\n ROMLOADER_CHIPTYP_NETX90 = 13\n ROMLOADER_CHIPTYP_NETX90B = 14\n ROMLOADER_CHIPTYP_NETX90C = 17\n\n atChipTypeMapping = {\n # These names are for compatibility with the COM side HBoot image tool\n # 'NETX90': ROMLOADER_CHIPTYP_NETX90,\n # 'NETX90B': ROMLOADER_CHIPTYP_NETX90B,\n # 'NETX90_MPW': ROMLOADER_CHIPTYP_NETX90_MPW,\n # These names are for compatibility with the netx 90 HWConfig tool.\n 'netx90': ROMLOADER_CHIPTYP_NETX90C, # Alias for the latest chip\n # revision.\n 'netx90_rev0': ROMLOADER_CHIPTYP_NETX90,\n 'netx90_rev1': ROMLOADER_CHIPTYP_NETX90B,\n 'netx90_rev2': ROMLOADER_CHIPTYP_NETX90C,\n 'netx90_mpw': ROMLOADER_CHIPTYP_NETX90_MPW,\n }\n\n BUS_SPI = 1\n BUS_IFlash = 2\n atDeviceMapping_netx90 = [\n {\n 'name': 'INTFLASH2',\n 'start': 0x00000000,\n 'end': 0x0007ffff,\n 'bus': BUS_IFlash,\n 'unit': 2,\n 'chip_select': 0\n },\n {\n 'name': 'SQIROM',\n 'start': 0x64000000,\n 'end': 0x67ffffff,\n 'bus': BUS_SPI,\n 'unit': 0,\n 'chip_select': 0\n },\n ]\n\n def __openssl_ecc_get_signature(self, aucSignature, sizKeyInBytes):\n # Get the start of the firt element, which is \"r\".\n uiLen = aucSignature[1]\n if uiLen >= 128:\n uiLen -= 128\n else:\n uiLen = 0\n uiElementStart = 2 + uiLen\n\n sizR = aucSignature[uiElementStart + 1]\n aucR = aucSignature[uiElementStart + 2:uiElementStart + 2 + sizR]\n\n if sizR > sizKeyInBytes + 1:\n raise Exception('The R field is too big. Expected %d bytes, '\n 'but got %d.' % (sizKeyInBytes, sizR))\n elif sizR == sizKeyInBytes + 1:\n self.__openssl_cut_leading_zero(aucR)\n elif sizR < sizKeyInBytes:\n # The signature data is smaller than expected. Pad it with 0x00.\n aucR.extend([0] * (sizKeyInBytes - sizR))\n self.__openssl_convert_to_little_endian(aucR)\n\n # Get the start of the second element, which is \"s\".\n uiElementStart = 2 + uiLen + 2 + sizR\n\n sizS = aucSignature[uiElementStart + 1]\n aucS = aucSignature[uiElementStart + 2:uiElementStart + 2 + sizS]\n\n if sizS > sizKeyInBytes + 1:\n raise Exception('The S field is too big. Expected %d bytes, '\n 'but got %d.' % (sizKeyInBytes, sizS))\n elif sizS == sizKeyInBytes + 1:\n self.__openssl_cut_leading_zero(aucS)\n elif sizS < sizKeyInBytes:\n # The signature data is smaller than expected. Pad it with 0x00.\n aucS.extend([0] * (sizKeyInBytes - sizS))\n self.__openssl_convert_to_little_endian(aucS)\n\n # Combine R and S.\n aucSignature = array.array('B')\n aucSignature.extend(aucR)\n aucSignature.extend(aucS)\n\n return aucSignature\n\n # Insert information for use by the flasher:\n # chip type, target flash device and flash offset.\n def __set_flasher_parameters(self, aulHBoot, ulHeaderAddress):\n if self.__strNetxType not in self.atChipTypeMapping:\n raise Exception(\"Cannot set flasher parameters for chip type %s\" %\n self.__strNetxType)\n ucChipType = self.atChipTypeMapping[self.__strNetxType]\n\n tDevInfo = None\n for tDev in self.atDeviceMapping_netx90:\n if(\n tDev['start'] <= ulHeaderAddress and\n ulHeaderAddress <= tDev['end']\n ):\n tDevInfo = tDev\n break\n\n if tDevInfo is None:\n raise Exception('No device found for header address 0x%08x' %\n ulHeaderAddress)\n\n print('Found flash device %s for address 0x%08x' % (\n tDevInfo['name'],\n ulHeaderAddress\n ))\n\n ulFlashDevice = (\n 1 * ucChipType +\n 0x100 * tDevInfo['bus'] +\n 0x10000 * tDevInfo['unit'] +\n 0x1000000 * tDevInfo['chip_select']\n )\n ulFlashOffset = ulHeaderAddress\n\n aulHBoot[0x01] = ulFlashOffset\n aulHBoot[0x05] = ulFlashDevice\n\n # Get the header address of the next data block (sizIdx+1),\n # if there is another data block left.\n # If the next block is in intflash 2, its header address is in the\n # address range for the APP CPU. Since the COM CPU is evaluating the\n # image, we convert the address to the range for the COM CPU.\n # Intflash 2 is located at 0x00000000..0x0007ffff for the APP CPU,\n # and at 0x00200000..0x0027ffff for the COM CPU.\n def get_next_header_address(self, sizIdx):\n ulNextHeaderAddress = 0\n sizDataBlocks = len(self.__atDataBlocks)\n if sizIdx + 1 < sizDataBlocks:\n ulNextHeaderAddress = self.__atDataBlocks[sizIdx + 1]['headeraddress']\n if ulNextHeaderAddress<=0x0007ffff:\n ulNextHeaderAddress += 0x00200000\n \n return ulNextHeaderAddress\n \n def patch_first_data_block(self):\n sizDataBlocks = len(self.__atDataBlocks)\n tAttr = self.__atDataBlocks[0]\n aulInputImage = tAttr['data']\n sizInputImageDWORDs = len(aulInputImage)\n\n # The input image must have at least...\n # 448 bytes of CM4 header,\n # 64 bytes of APP HBOOT header,\n # 4 bytes of application data.\n # In total this is 516 bytes or 129 DWORDs.\n if sizInputImageDWORDs < 129:\n raise Exception(\n 'The first data block is too small. '\n 'It must have at least 516 bytes.'\n )\n\n # Extract the HBOOT header.\n aulHBoot = array.array('I')\n aulHBoot.fromstring(aulInputImage[112:128])\n\n # Check the magic and signature.\n if aulHBoot[0x00] != 0xf3beaf00:\n raise Exception('The input image has no valid HBOOT magic.')\n if aulHBoot[0x06] != 0x41505041:\n raise Exception(\n 'The input image has no valid netX90 APP signature.'\n )\n\n # Set the next pointer.\n aulHBoot[2] = self.get_next_header_address(0)\n\n # Set the new length.\n # This is the complete file size except the CM4 header (448 bytes)\n # and the APP HBOOT header (64 bytes). The remaining size if converted\n # from bytes to DWORDS.\n sizApplicationInDwords = sizInputImageDWORDs - 128\n aulHBoot[4] = sizApplicationInDwords\n\n # Offset 5+1: set the destination device and offset for the flasher.\n ulHeaderAddress = self.__atDataBlocks[0]['headeraddress']\n self.__set_flasher_parameters(aulHBoot, ulHeaderAddress)\n\n # Create a SHA384 hash over the cm4 vectors, the complete application\n # and all other blocks.\n # (i.e. everything except the first header).\n tHash = hashlib.sha384()\n tHash.update(aulInputImage[0:112])\n tHash.update(aulInputImage[128:])\n for sizCnt in range(1, sizDataBlocks):\n tHash.update(self.__atDataBlocks[sizCnt]['header'])\n tHash.update(self.__atDataBlocks[sizCnt]['data'])\n aulHash = array.array('I', tHash.digest())\n\n # Write the first 7 DWORDs of the hash to the HBOOT header.\n aulHBoot[0x08] = aulHash[0]\n aulHBoot[0x09] = aulHash[1]\n aulHBoot[0x0a] = aulHash[2]\n aulHBoot[0x0b] = aulHash[3]\n aulHBoot[0x0c] = aulHash[4]\n aulHBoot[0x0d] = aulHash[5]\n aulHBoot[0x0e] = aulHash[6]\n\n # print(\"header hash: %s\" % aulHash)\n # Create the header checksum.\n ulBootblockChecksum = 0\n for iCnt in range(0, 15):\n ulBootblockChecksum += aulHBoot[iCnt]\n ulBootblockChecksum &= 0xffffffff\n ulBootblockChecksum = (ulBootblockChecksum - 1) ^ 0xffffffff\n\n # Finalize the header with the checksum.\n aulHBoot[0x0f] = ulBootblockChecksum\n\n # Copy the header into the data.\n for iCnt in range(0, 16):\n aulInputImage[112 + iCnt] = aulHBoot[iCnt]\n\n tAttr['data'] = aulInputImage\n return aulHash\n\n def build_header(self, sizIdx):\n # Get the attributes.\n tAttr = self.__atDataBlocks[sizIdx]\n\n # Create an empty array.\n aulHBoot = array.array('I', [0] * 16)\n\n # Set the magic cookie.\n aulHBoot[0] = 0xf3beaf00\n\n # Set the next pointer.\n aulHBoot[2] = self.get_next_header_address(sizIdx)\n\n # Is the block XIP?\n if tAttr['destination'] == tAttr['headeraddress'] + 64:\n aulHBoot[3] = 0\n # Is the block in the SDRAM?\n elif(\n tAttr['destination'] >= 0x10000000 and\n tAttr['destination'] < 0x20000000\n ):\n aulHBoot[3] = tAttr['destination'] + self.__ulSDRamSplitOffset\n else:\n aulHBoot[3] = 0\n\n # Set the data size in DWORDs.\n aulHBoot[4] = len(tAttr['data'])\n\n # Offset 5+1: set the destination device and offset for the flasher.\n ulHeaderAddress = tAttr['headeraddress']\n self.__set_flasher_parameters(aulHBoot, ulHeaderAddress)\n\n # Set the signature.\n aulHBoot[6] = 0x41505041\n\n # Offset 7: image parameter\n # Keep at 0.\n\n # Offsets 8-14 store the hash, which is only valid for the first\n # header.\n # Keep at 0.\n\n # Create the header checksum.\n ulBootblockChecksum = 0\n for iCnt in range(0, 15):\n ulBootblockChecksum += aulHBoot[iCnt]\n ulBootblockChecksum &= 0xffffffff\n ulBootblockChecksum = (ulBootblockChecksum - 1) ^ 0xffffffff\n\n aulHBoot[15] = ulBootblockChecksum\n\n tAttr['header'] = aulHBoot\n\n # If the output file name is omitted, there must not be a segment list\n # specified. The segment list attribute must be either\n # - absent\n # - empty\n # - \",\"\n # - not resolvable\n # If the attribute is present and\n # - contains a non-alias value (other than \",\")\n # - or contains an alias that can be resolved,\n # raise an error.\n def data_node_check_no_segments(self, tNodeData):\n # print(\"*** data_node_check_no_segments *****\")\n for tNodeChild in tNodeData.childNodes:\n # print (tNodeChild.localName)\n if tNodeChild.localName == 'File':\n strVal = tNodeChild.getAttribute('segments').strip()\n strVal2 = self.safe_resolve_alias(strVal)\n # print(\"segments: %s -> %s\" % (strVal, strVal2))\n if len(strVal2) > 0 and strVal2 != ',':\n # print(\"Exception\")\n # Error, no segment list should be supplied\n raise Exception('Output filename is empty but a segment '\n 'list is specified')\n # else:\n # print(\"Accept\")\n\n def process_app_image(self, strSourcePath, astrDestinationPaths):\n # No data blocks yet.\n self.__atDataBlocks = []\n\n self.segments_init()\n\n tXml = xml.dom.minidom.parse(strSourcePath)\n tNodeRoot = tXml.documentElement\n if tNodeRoot.localName != 'AppImage':\n raise Exception('Unexpected root tag!')\n\n # Loop over all data elements.\n tNodeAsig = None\n\n # Offset into the list of output file paths\n iDestPathIndex = 0\n\n for tNodeChild in tNodeRoot.childNodes:\n if tNodeChild.localName == 'data':\n if iDestPathIndex >= len(astrDestinationPaths):\n print('Skipping data node because no output file name '\n 'is supplied')\n self.data_node_check_no_segments(tNodeChild)\n\n elif astrDestinationPaths[iDestPathIndex] == '':\n iDestPathIndex = iDestPathIndex + 1\n print('destination path: %d >%s<' % (iDestPathIndex, ''))\n print('Skipping data node because output file name '\n 'is empty')\n self.data_node_check_no_segments(tNodeChild)\n\n else:\n strDesinationPath = astrDestinationPaths[iDestPathIndex]\n iDestPathIndex = iDestPathIndex + 1\n print('destination path: %d >%s<' % (\n iDestPathIndex,\n strDesinationPath\n ))\n\n # Get one data block.\n strData, pulLoadAddress = self.__get_data_contents(\n tNodeChild\n )\n # The input image must be a multiple of DWORDS.\n if (len(strData) % 4) != 0:\n raise Exception(\n 'The size of the input image is not a '\n 'multiple of DWORDS.'\n )\n # Convert the data to an array.\n aulData = array.array('I')\n aulData.fromstring(strData)\n\n # Get the header address.\n if tNodeChild.hasAttribute('headeraddress') is not True:\n raise Exception('Missing \"headeraddress\" attribute.')\n strHeaderAddress = self.resolve_alias(\n tNodeChild.getAttribute('headeraddress')\n )\n ulHeaderAddress = int(strHeaderAddress, 0)\n if ulHeaderAddress is None:\n raise Exception(\n 'Failed to parse number: \"%s\".',\n strHeaderAddress\n )\n\n # Get the padding.\n ulPaddingPreSize = 0\n ucPaddingPreValue = 0xff\n strPaddingPreSize = tNodeChild.getAttribute(\n 'padding_pre_size'\n )\n if len(strPaddingPreSize) != 0:\n ulPaddingPreSize = int(strPaddingPreSize, 0)\n if ulPaddingPreSize < 0:\n raise Exception(\n 'The padding pre size is invalid: %d' %\n ulPaddingPreSize\n )\n strPaddingPreValue = tNodeChild.getAttribute(\n 'padding_pre_value'\n )\n if len(strPaddingPreValue) != 0:\n ucPaddingPreValue = int(strPaddingPreValue, 0)\n if(\n ucPaddingPreValue < 0 or\n ucPaddingPreValue > 0xff\n ):\n raise Exception(\n 'The padding pre value is invalid: %d' %\n ucPaddingPreValue\n )\n\n tAttr = {\n 'prePaddingSize': ulPaddingPreSize,\n 'prePaddingValue': ucPaddingPreValue,\n 'header': None,\n 'data': aulData,\n 'headeraddress': ulHeaderAddress,\n 'destination': pulLoadAddress,\n 'asig': None,\n 'destinationPath': strDesinationPath\n }\n self.__atDataBlocks.append(tAttr)\n\n elif tNodeChild.localName == 'asig':\n if tNodeAsig is not None:\n raise Exception('More than one \"asig\" node found.')\n tNodeAsig = tNodeChild\n \n self.__signed_binding = self.__xml_get_boolean_attribute_value(\n tNodeAsig, 'signed_binding', False)\n if self.__signed_binding == True:\n print(\"---- use signed binding method -----\")\n\n # There must be at least one data block.\n sizDataBlocks = len(self.__atDataBlocks)\n if sizDataBlocks == 0:\n raise Exception('No data blocks found.')\n\n # Raise an error if there are any unused output file paths remaining\n if len(astrDestinationPaths) > iDestPathIndex:\n raise Exception(\n '%d output files specified, but only %d were used' %\n (len(astrDestinationPaths), iDestPathIndex)\n )\n\n # Check if any loadable segments recorded for the elf file(s)\n # have not been used\n if self.segments_check_unused() is True:\n raise Exception('There are unused segments containing data')\n\n # The first header must have a header address of 0x00000000.\n tFirstAttr = self.__atDataBlocks[0]\n if tFirstAttr['headeraddress'] != 0x00000000:\n raise Exception(\n 'The first data block must have a header address of '\n '0x00000000, but it has 0x%08x.' %\n tFirstAttr['headeraddress']\n )\n\n # Build headers for all data blocks after the first one.\n for sizIdx in range(1, sizDataBlocks):\n self.build_header(sizIdx)\n\n # Patch the first data block.\n aulFWHash = self.patch_first_data_block()\n\n # Append ASIG thing to the last block if requested.\n if tNodeAsig is not None:\n tAttr = self.__atDataBlocks[-1]\n tAttr['asig'] = self.__build_chunk_asig(tNodeAsig, aulFWHash)\n\n\n # Write the data blocks.\n for iCnt in range(0, len(self.__atDataBlocks)):\n tAttr = self.__atDataBlocks[iCnt]\n strDestinationPath = tAttr['destinationPath']\n\n print('Writing file %s' % strDestinationPath)\n tFile = open(strDestinationPath, 'wb')\n\n ulPrePaddingSize = tAttr['prePaddingSize']\n ucPrePaddingValue = tAttr['prePaddingValue']\n if ulPrePaddingSize != 0:\n aucPrePad = array.array(\n 'B',\n [ucPrePaddingValue] * ulPrePaddingSize\n )\n aucPrePad.tofile(tFile)\n\n aucData = tAttr['header']\n if aucData is not None:\n aucData.tofile(tFile)\n\n aucData = tAttr['data']\n if aucData is not None:\n aucData.tofile(tFile)\n\n aucData = tAttr['asig']\n if aucData is not None:\n aucData.tofile(tFile)\n\n tFile.close()\n\n\ndef __get_clean_known_files(atKnownFiles):\n atClean = {}\n\n # Iterate over all known files.\n for strKey, tFile in atKnownFiles.items():\n # The file must be either a string, a SCons.Node.FS.File object or a\n # SCons.Node.NodeList object.\n if isinstance(tFile, str):\n strFile = tFile\n elif isinstance(tFile, SCons.Node.FS.File):\n strFile = tFile.get_path()\n elif isinstance(tFile, SCons.Node.NodeList):\n # The list must have exactly one entry.\n if len(tFile) != 1:\n raise Exception(\n 'Key \"%s\" has more than one file in the known files.' %\n strKey\n )\n strFile = tFile[0].get_path()\n else:\n raise Exception(\n 'Unknown type for key \"%s\" in the known files.' %\n strKey\n )\n\n atClean[strKey] = strFile\n\n return atClean\n\n\ndef __app_image_action(target, source, env):\n atKnownFiles = {}\n if 'APPIMAGE_KNOWN_FILES' in env:\n atK = env['APPIMAGE_KNOWN_FILES']\n if atK is not None:\n atKnownFiles = __get_clean_known_files(atK)\n\n astrIncludePaths = []\n if 'APPIMAGE_INCLUDE_PATHS' in env:\n atValues = env['APPIMAGE_INCLUDE_PATHS']\n if (atValues is not None) and (len(atValues) != 0):\n astrIncludePaths.extend(atValues)\n\n # fVerbose = False\n # if 'APPIMAGE_VERBOSE' in env:\n # fVerbose = bool(env['APPIMAGE_VERBOSE'])\n\n strKeyRomPath = None\n if 'APPIMAGE_KEYROM_XML' in env:\n strKeyRomPath = env['APPIMAGE_KEYROM_XML']\n\n strSourcePath = source[0].get_path()\n astrDestinationPaths = []\n for tTarget in target:\n astrDestinationPaths.append(tTarget.get_path())\n\n tAppImage = AppImage(env, astrIncludePaths, atKnownFiles)\n if strKeyRomPath is not None:\n tAppImage.read_keyrom(strKeyRomPath)\n\n tAppImage.process_app_image(\n strSourcePath,\n astrDestinationPaths\n )\n\n return 0\n\n\ndef __app_image_emitter(target, source, env):\n if 'APPIMAGE_KNOWN_FILES' in env:\n atKnownFiles = env['APPIMAGE_KNOWN_FILES']\n if atKnownFiles is not None:\n atKnownFiles = __get_clean_known_files(atKnownFiles)\n for strId, strPath in atKnownFiles.items():\n env.Depends(\n target,\n SCons.Script.File(strPath)\n )\n env.Depends(\n target,\n SCons.Node.Python.Value(\n 'KNOWN_FILE:%s:%s' %\n (strId, strPath))\n )\n\n if 'APPIMAGE_INCLUDE_PATHS' in env:\n astrIncludePaths = env['APPIMAGE_INCLUDE_PATHS']\n if astrIncludePaths is not None and len(astrIncludePaths) != 0:\n env.Depends(\n target,\n SCons.Node.Python.Value(\n 'INCLUDE_PATH:' + ':'.join(astrIncludePaths)\n )\n )\n\n if 'APPIMAGE_KEYROM_XML' in env:\n strKeyRomPath = env['APPIMAGE_KEYROM_XML']\n if strKeyRomPath is not None and len(strKeyRomPath) != 0:\n env.Depends(\n target,\n SCons.Script.File(strKeyRomPath)\n )\n\n fVerbose = False\n if 'APPIMAGE_VERBOSE' in env:\n fVerbose = bool(env['APPIMAGE_VERBOSE'])\n env.Depends(target, SCons.Node.Python.Value(str(fVerbose)))\n\n return target, source\n\n\ndef __app_image_string(target, source, env):\n return 'AppImage %s' % target[0].get_path()\n\n\n# ---------------------------------------------------------------------------\n#\n# Add AppImage builder.\n#\ndef ApplyToEnv(env):\n env['APPIMAGE_KNOWN_FILES'] = None\n env['APPIMAGE_INCLUDE_PATHS'] = None\n env['APPIMAGE_VERBOSE'] = False\n env['APPIMAGE_KEYROM_XML'] = None\n\n app_image_act = SCons.Action.Action(\n __app_image_action,\n __app_image_string\n )\n app_image_bld = SCons.Script.Builder(\n action=app_image_act,\n emitter=__app_image_emitter,\n suffix='.xml',\n single_source=1)\n env['BUILDERS']['AppImage'] = app_image_bld\n\n\nif __name__ == '__main__':\n tParser = argparse.ArgumentParser(\n description='Translate an XML APP image description file.'\n )\n tParser.add_argument(\n 'strInputFile',\n metavar='INPUT_FILE',\n help='read the XML data from INPUT_FILE'\n )\n tParser.add_argument(\n 'astrOutputFiles',\n nargs='+',\n metavar='OUTPUT_FILE',\n help='write the output to OUTPUT_FILE'\n )\n tParser.add_argument(\n '-n', '--netx-type',\n dest='strNetxType',\n required=True,\n choices=[\n # For compatibility with hboot_image.py\n # 'NETX90',\n # 'NETX90B',\n # 'NETX90_MPW',\n # For compatibility with HWConfig tool\n 'netx90', # Alias for the latest chip revision, currently rev. 2\n 'netx90_mpw',\n 'netx90_rev0',\n 'netx90_rev1',\n 'netx90_rev2',\n ],\n metavar='NETX',\n help='Build the image for netx type NETX.'\n )\n tParser.add_argument(\n '-c', '--objcopy',\n dest='strObjCopy',\n required=False,\n default='objcopy',\n metavar='FILE',\n help='Use FILE as the objcopy tool.'\n )\n tParser.add_argument(\n '-d', '--objdump',\n dest='strObjDump',\n required=False,\n default='objdump',\n metavar='FILE',\n help='Use FILE as the objdump tool.'\n )\n tParser.add_argument(\n '-r', '--readelf',\n dest='strReadElf',\n required=False,\n default='readelf',\n metavar='FILE',\n help='Use FILE as the readelf tool.'\n )\n tParser.add_argument(\n '-A', '--alias',\n dest='astrAliases',\n required=False,\n action='append',\n metavar='ALIAS=FILE',\n help='Add an alias in the form ALIAS=FILE.'\n )\n tParser.add_argument(\n '-I', '--include',\n dest='astrIncludePaths',\n required=False,\n action='append',\n metavar='PATH',\n help='Add PATH to the list of include paths.'\n )\n tParser.add_argument(\n '-k', '--keyrom',\n dest='strKeyRomPath',\n required=False,\n default=None,\n metavar='FILE',\n help='Read the keyrom data from FILE.'\n )\n tParser.add_argument(\n '-s',\n '--sdram_split_offset',\n dest='strSDRamSplitOffset',\n default=\"0x00000000\",\n required=False,\n metavar=\"SDRAM\",\n help='Address offset for COM CPU to access APP side SDRAM.'\n )\n tParser.add_argument(\n '-v',\n '--verbose',\n dest='fVerbose',\n action='store_true',\n default=False,\n help='be verbose'\n )\n tParser.add_argument(\n '--openssl-exe',\n dest='strOpensslExe',\n required=False,\n default='openssl',\n metavar='PATH',\n help='Add individual OpenSSL Path.'\n )\n tParser.add_argument(\n '--openssl-rand-off',\n dest='fOpensslRandOff',\n required=False,\n default=False,\n action='store_const', const=True,\n metavar='SSLRAND',\n help='Set openssl randomization true or false.'\n )\n tArgs = tParser.parse_args()\n\n # Use a default logging level of \"WARNING\". Change it to \"DEBUG\" in\n # verbose mode.\n tLoggingLevel = logging.WARNING\n if tArgs.fVerbose is True:\n tLoggingLevel = logging.DEBUG\n logging.basicConfig(level=tLoggingLevel)\n\n # Parse all alias definitions.\n atKnownFiles = {}\n if tArgs.astrAliases is not None:\n tPattern = re.compile('([a-zA-Z0-9_]+)=(.*)$')\n for strAliasDefinition in tArgs.astrAliases:\n tMatch = re.match(tPattern, strAliasDefinition)\n if tMatch is None:\n raise Exception(\n 'Invalid alias definition: \"%s\". '\n 'It must be \"ALIAS=FILE\" instead.' % strAliasDefinition\n )\n strAlias = tMatch.group(1)\n strFile = tMatch.group(2)\n if strAlias in atKnownFiles:\n raise Exception(\n 'Double defined alias \"%s\". The old value \"%s\" should be '\n 'overwritten with \"%s\".' % (\n strAlias,\n atKnownFiles[strAlias],\n strFile\n )\n )\n atKnownFiles[strAlias] = strFile\n\n # Set an empty list of include paths if nothing was specified.\n if tArgs.astrIncludePaths is None:\n tArgs.astrIncludePaths = []\n\n tEnv = {\n 'OBJCOPY': tArgs.strObjCopy,\n 'OBJDUMP': tArgs.strObjDump,\n 'READELF': tArgs.strReadElf,\n 'HBOOT_INCLUDE': tArgs.astrIncludePaths\n }\n\n ulSDRamSplitOffset = int(tArgs.strSDRamSplitOffset, 0)\n tAppImg = AppImage(\n tEnv,\n tArgs.strNetxType,\n tArgs.astrIncludePaths,\n atKnownFiles,\n ulSDRamSplitOffset,\n tArgs.strOpensslExe,\n tArgs.fOpensslRandOff\n )\n if tArgs.strKeyRomPath is not None:\n tAppImg.read_keyrom(tArgs.strKeyRomPath)\n\n # print (\"===================================\")\n # print (\"Number of destination paths: %d\" % (len(tArgs.astrOutputFiles)))\n # for strDesinationPath in tArgs.astrOutputFiles:\n # print('>%s<' % strDesinationPath)\n # print (\"===================================\")\n\n tAppImg.process_app_image(\n tArgs.strInputFile,\n tArgs.astrOutputFiles\n )\n","sub_path":"site_scons/hboot_image_compiler/netx90_app_image.py","file_name":"netx90_app_image.py","file_ext":"py","file_size_in_byte":75617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"553251013","text":"from django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom django.http import Http404\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom apps.jmutube.util import *\nfrom tagging.models import Tag, TaggedItem\nfrom rooibos.util import json_view\nfrom rooibos.data.models import Record\nfrom rooibos.util.models import OwnedWrapper\nfrom rooibos.presentation.models import Presentation, PresentationItem, PresentationItemInfo\n\n\ndef playlist_rss_feed(request, user, title):\n playlist = get_object_or_404(Presentation,\n Q(name=title) | Q(id=title),\n owner__username=user,\n source='jmutube')\n storage = get_jmutube_storage()\n\n def items():\n for item in playlist.items.all():\n media = item.record.media_set.filter(storage=storage)[0]\n yield item.record, media, item.type\n\n return render_to_response('jmutube-playlist.rss',\n { 'title': playlist.title,\n 'user': playlist.owner,\n 'url': 'http://%s/' % (settings.JMUTUBE_URL_HOST,),\n 'jmutube_player': request.GET.get('player') == 'jmutube',\n 'playlist': (\n {'file': record,\n 'url': storage.storage_system.get_absolute_media_url(storage, media, delivery),\n 'jmutube_player_url': storage.storage_system.get_jmutube_player_url(storage, media, delivery),\n 'mimetype': media.mimetype,\n 'size': media.file_size,\n }\n for record, media, delivery in items() )},\n context_instance = RequestContext(request))\n\ndef single_file_rss_feed(request, user, id, name):\n storage = get_jmutube_storage()\n user = User.objects.get(username=user)\n record = get_object_or_404(Record,\n owner=user,\n source__startswith='jmutube-',\n id=id)\n media = record.media_set.filter(storage=storage)[0]\n jmutube_player = request.GET.get('player') == 'jmutube'\n\n return render_to_response('jmutube-playlist.rss',\n { 'title': record.title,\n 'user': user,\n 'url': 'http://%s/' % (settings.JMUTUBE_URL_HOST,),\n 'jmutube_player': jmutube_player,\n 'playlist': ({'file': record,\n 'url': storage.storage_system.get_absolute_media_url(storage, media),\n 'jmutube_player_url': storage.storage_system.get_jmutube_player_url(storage, media),\n 'mimetype': media.mimetype,\n 'size': media.file_size,\n },) },\n context_instance = RequestContext(request))\n\ndef playlist_play(request, user, title):\n playlist = get_object_or_404(Presentation,\n Q(name=title) | Q(id=title),\n owner__username=user,\n source='jmutube')\n return render_to_response('jmutube-playlist.html',\n { 'title': playlist.title,\n 'feed': '%s://%s%s' % (\n 'https' if request.META.get('HTTPS', 'off') == 'on' else 'http',\n request.get_host(),\n reverse('jmutube-playlist-rss-feed', args=(user, playlist.id))) },\n context_instance = RequestContext(request))\n\ndef playlist_download(request, user, title):\n playlist = get_object_or_404(Presentation,\n Q(name=title) | Q(id=title),\n owner__username=user,\n source='jmutube')\n res = render_to_response('jmutube-playlist.html',\n { 'title': playlist.title,\n 'feed': 'http://%s%s' % (request.get_host(), reverse('jmutube-playlist-rss-feed', args=(user, playlist.id))) },\n context_instance = RequestContext(request),\n mimetype = 'application/binary')\n res[\"Content-Disposition\"] = \"attachment; filename=playlist.html\"\n return res\n\n\ndef verify_user(func):\n def call_func(*args, **kwargs):\n if args[0].user.username != args[1]:\n raise Http404()\n return func(*args, **kwargs)\n return call_func\n\n\n@json_view\n@verify_user\ndef playlist_json(request, user, title):\n playlist = get_object_or_404(Presentation, owner=request.user, name=title)\n return {\n 'id': playlist.id,\n 'user': playlist.owner.username,\n 'title': playlist.title,\n 'urltitle': playlist.name,\n 'files': [{'id': item.record.id,\n 'title': item.record.title,\n 'delivery': item.type,\n 'deliveryoptions': 'B'} for item in playlist.items.all()]\n }\n\n\n@json_view\n@verify_user\ndef playlists_json(request, user):\n playlists = Presentation.objects.filter(owner__username=user, source='jmutube')\n return dict(playlists=[{'title': playlist.title, 'urltitle': playlist.name} for playlist in playlists])\n\n\n@json_view\n@verify_user\ndef store_playlist(request, user):\n id = int(request.POST.get('id', 0))\n title = request.POST['title']\n items = map(int, request.POST['items'].split(','))\n deliveries = request.POST['delivery'].split(',')\n # Filter to make sure all playlist items are owned by user\n records = Record.objects.filter(owner=request.user,\n source__startswith='jmutube-',\n id__in=items).values_list('id', flat=True)\n if id == 0:\n playlist = Presentation.objects.create(owner=request.user, title=title, source='jmutube')\n else:\n playlist = get_object_or_404(Presentation, owner=request.user, id=id, source='jmutube')\n playlist.title = title\n playlist.save()\n\n playlist.items.all().delete()\n count = 0\n for (item, delivery) in zip(items, deliveries):\n if item in records:\n count += 1\n PresentationItem.objects.create(presentation=playlist, record_id=item, order=count, type=delivery)\n return { 'message': 'Playlist saved', 'id': playlist.id, }\n\n\n@json_view\n@verify_user\ndef delete_playlist(request, user):\n id = int(request.POST['id'])\n playlist = get_object_or_404(Presentation, owner=request.user, id=id)\n playlist.delete();\n return { 'message': 'Playlist deleted' }\n\n\n@json_view\n@verify_user\ndef delete_tag(request, user):\n fileid = int(request.POST['id'])\n tag = int(request.POST['tag'])\n record = get_object_or_404(Record, owner__username=user, id=fileid)\n wrapper = OwnedWrapper.objects.get_for_object(user=record.owner, object=record)\n TaggedItem.objects.filter(object_id=wrapper.id, content_type=OwnedWrapper.t(OwnedWrapper), tag__id=tag).delete()\n return { 'message': 'Tag deleted' }\n","sub_path":"jmutube/repository/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"213004025","text":"import subprocess\nfrom pathlib import Path\nfrom typing import Iterable, Sequence\n\nfrom joblib import delayed\n\nfrom ..utils import PathOrStr, TqdmParallel\n\n\ndef get_audio_paths(file: PathOrStr) -> Sequence[Path]:\n \"\"\"Given a path to a file containing a list of audio files, returns\n a sequence of absolute paths to the audio files.\n\n Args:\n -----\n file: pathlike or str\n Path to a file containing a list of paths to audio clips.\n\n Returns:\n --------\n Sequence of paths to audio files.\n \"\"\"\n file = Path(file)\n paths = []\n with open(file) as fid:\n for line in fid:\n p = Path(line.strip())\n paths.append(p if p.is_absolute() else (file.parent / p).resolve())\n return paths\n\n\ndef resample_audio(paths: Iterable[Path], dir: PathOrStr):\n \"\"\"Resample given audio clips to 16 kHz 16-bit WAV, and place in\n direcotory given by `dir`.\n \"\"\"\n paths = list(paths)\n if len(paths) == 0:\n raise FileNotFoundError(\"No audio files found.\")\n\n dir = Path(dir)\n dir.mkdir(exist_ok=True, parents=True)\n print(f\"Resampling {len(paths)} audio files to {dir}\")\n\n opts = [\"-nostdin\", \"-ar\", \"16000\", \"-sample_fmt\", \"s16\", \"-ac\", \"1\", \"-y\"]\n print(f\"Using FFmpeg options: {' '.join(opts)}\")\n TqdmParallel(\n desc=\"Resampling audio\", total=len(paths), unit=\"file\", n_jobs=-1\n )(\n delayed(subprocess.run)(\n [\"ffmpeg\", \"-i\", str(path), *opts, str(dir / (path.stem + \".wav\"))],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.STDOUT,\n )\n for path in paths\n )\n\n\ndef write_filelist(paths: Iterable[Path], out: PathOrStr = \"files.txt\"):\n \"\"\"Write sorted file list.\"\"\"\n paths = sorted(paths, key=lambda p: p.stem)\n with open(out, \"w\") as fid:\n fid.write(\"\\n\".join(list(map(str, paths))) + \"\\n\")\n print(\"Wrote file list to files.txt\")\n","sub_path":"emorec/dataset/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"32038941","text":"\"\"\"\nUseful links:\n Code used in this example was found : \n https://github.com/aziezahmed/podcast-player/blob/master/podcast_player/podcast_player.py\n\n Website to find Podcast RSS feeds\n https://www.listennotes.com/\n\nExample Podcasts:\n \"https://tonyrobbins.libsyn.com/rss\"\n \"https://www.npr.org/rss/podcast.php?id=510289\"\n\"\"\"\nimport os\nimport sys\nfrom os.path import expanduser\nimport feedparser\nimport listparser\nimport random\n\nplayer = \"mpv --no-video\"\n\ndef get_newest_episode(podcast):\n feed = feedparser.parse(podcast)\n entry = feed.entries[random.randrange(0,len(feed))]\n return entry\n\ndef get_episode_audio_url(podcast_entry):\n links = podcast_entry[\"links\"]\n for link in links:\n if \"audio\" in link[\"type\"]:\n return link[\"href\"]\n\ndef play_podcast_episode(url):\n os.system('clear')\n os.system(player + \" \" + url)\n\ndef play_podcast():\n podcast_rss_url = \"https://rss.art19.com/tim-ferriss-show\"\n episode_info = get_newest_episode(podcast_rss_url)\n episode_url = get_episode_audio_url(episode_info)\n play_podcast_episode(episode_url)\n\n","sub_path":"Other/Alarm/Podcast.py","file_name":"Podcast.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"200644049","text":"# Copyright 2019 Red Hat\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import\n\nimport os\n\nimport testtools\n\nimport tobiko\nfrom tobiko.openstack import glance\nfrom tobiko.openstack import keystone\nfrom tobiko.openstack import nova\nfrom tobiko.openstack import tests\n\n\nclass MyServerStack(tests.TestServerCreationStack):\n pass\n\n\n@keystone.skip_unless_has_keystone_credentials()\nclass ServerCreationTest(testtools.TestCase):\n\n def test_server_creation(self):\n all_servers_ids = {server.id for server in nova.list_servers()}\n\n stack = tests.test_server_creation()\n\n self.assertIsInstance(stack, tests.TestServerCreationStack)\n class_name = tobiko.get_fixture_name(tests.TestServerCreationStack)\n pid = os.getpid()\n self.assertEqual(f\"{class_name}-{pid}-0\", stack.stack_name)\n self.assertNotIn(stack.server_id, all_servers_ids)\n self.assertEqual('ACTIVE', nova.get_server(stack.server_id).status)\n\n def test_server_creation_with_stack(self):\n stack = tests.test_server_creation(stack=MyServerStack)\n self.assertIsInstance(stack, tests.TestServerCreationStack)\n\n def test_evacuable_server_creation(self):\n stack = tests.test_evacuable_server_creation()\n self.assertIsInstance(stack, tests.TestEvacuableServerCreationStack)\n self.assertIn('evacuable', glance.get_image(stack.image).tags)\n\n def test_server_creation_and_shutoff(self):\n stack = tests.test_server_creation_and_shutoff()\n self.assertIsInstance(stack, tests.TestServerCreationStack)\n self.assertEqual('SHUTOFF', nova.get_server(stack.server_id).status)\n\n def test_servers_creation(self):\n all_servers_ids = {server.id for server in nova.list_servers()}\n stacks = tests.test_servers_creation()\n self.assertEqual(2, len(stacks))\n pid = os.getpid()\n for i, stack in enumerate(stacks):\n self.assertIsInstance(stack, tests.TestServerCreationStack)\n class_name = tobiko.get_fixture_name(tests.TestServerCreationStack)\n self.assertEqual(f\"{class_name}-{pid}-{i}\", stack.stack_name)\n self.assertNotIn(stack.server_id, all_servers_ids)\n self.assertEqual('ACTIVE', nova.get_server(stack.server_id).status)\n","sub_path":"tobiko/tests/functional/openstack/tests/test_nova.py","file_name":"test_nova.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"557524284","text":"##################\n# Tue Oct 11 16:42:42 BST 2011\n# EXAMPLE OF A CONTEXT PROCESSOR THAT KEEP IN MEMORY THE LATEST SEARCHES BEING PERFORMED \n#\n##################\n\n\n\n\n\n\nfrom settings import printdebug\nfrom myapp.models import *\n\n\n# CONTEXT PROCESSORS: takes an HttpRequest object and returns a dictionary of variables to use in \n# the template context. That's all it does!\n\n# updates information about the recently searched/viewed objects \n# 1. gets the data from session (each variable is a list of dicts containing the necessary info)\n# 2. updates the data based on info contained in 'request' object\n# 3. return the updated context that will be used in the templates\n\ndef add_session(request):\n\tksearch_history = request.session.get('ksearch', None)\n\tfsearch_history = request.session.get('fsearch', None)\n\trecord_history = request.session.get('record', None)\n\tmemory = update_memory(request, ksearch_history, fsearch_history, record_history)\n\tif memory:\n\t\trequest.session['ksearch'] = memory[0]\n\t\trequest.session['fsearch'] = memory[1]\n\t\trequest.session['record'] = memory[2]\n\t\treturn {\n\t\t\t\t'ksearch_history' : memory[0] , \n\t\t\t\t'fsearch_history': memory[1] , \n\t\t\t\t'record_history': memory[2] , \n\t\t\t\t}\n\telse:\n\t\treturn {\n\t\t\t\t'ksearch_history' : ksearch_history , \n\t\t\t\t'fsearch_history': fsearch_history ,\n\t\t\t\t'record_history': record_history , \n\t\t\t\t}\n\n\ndef update_memory(request, ksearch_history, fsearch_history, record_history):\n\tpath = request.path\n\t# KEYWORD SEARCH PAGE\n\tif path.find('/db/search') >= 0:\n\t\tquery = request.GET.get('query', False) \n\t\tbasic_search_type = request.GET.get('basic_search_type', False)\n\t\tif query and basic_search_type:\n\t\t\tnewdict = {'query' : query, 'basic_search_type' : basic_search_type}\n\t\t\tif ksearch_history:\n\t\t\t\tif newdict not in ksearch_history:\n\t\t\t\t\tksearch_history.insert(0, newdict)\n\t\t\t\tif len(ksearch_history) > 20:\n\t\t\t\t\tksearch_history.pop()\n\t\t\telse:\n\t\t\t\tksearch_history = [newdict]\n\t\treturn [ksearch_history, fsearch_history, record_history]\n\t# FACETED SEARCH PAGE\t\n\telif path.find('/db/faceted') >= 0:\n\t\tprintdebug(\"Context Processor: ..... detected call to faceted page .... but handler still not implemented....\")\n\t\t# AJAX calls don't come through here!!!!!!!!!! \n\t\t# the dict element 'fsearch_history' is left untouched....\n\t\treturn None\n\t\t\n\t#\tRECORD PAGE\n\telif path.find('/db/record') >= 0:\n\t\tlista = path.split(\"/\")\n\t\ttry:\n\t\t# if True:\n\t\t\tnumber = int(lista[-2])\t # even though the number seems in last position, it's the penultimate\n\t\t\trectype = lista[-3]\n\t\t\ttry:\n\t\t\t\tif rectype == 'document':\n\t\t\t\t\tname = Document.objects.filter(id=number).values('title')[0]['title']\n\t\t\t\telif rectype == 'event':\n\t\t\t\t\tname = Event.objects.filter(id=number).values('short_title')[0]['short_title']\n\t\t\t\telif rectype == 'person':\n\t\t\t\t\tname = nicename(Person.objects.get(id=number)) \n\t\t\t\telif rectype == 'troupe':\n\t\t\t\t\tname = Troupe.objects.filter(id=number).values('name')[0]['name']\n\t\t\t\telif rectype == 'venue':\n\t\t\t\t\tname = Venue.objects.filter(id=number).values('name')[0]['name']\n\t\t\t\telif rectype == 'emlot-record':\n\t\t\t\t\tname = \"\"\n\t\t\texcept:\n\t\t\t\tname = \"[error retrieving name]\"\n\t\t\tnewdict = {'number' : number, 'type' : rectype, 'name' : name}\n\t\t\tif record_history:\n\t\t\t\tif newdict not in record_history:\n\t\t\t\t\trecord_history.insert(0, newdict)\n\t\t\t\tif len(record_history) > 20:\n\t\t\t\t\trecord_history.pop()\n\t\t\telse:\n\t\t\t\trecord_history = [newdict]\n\t\texcept:\n\t\t\tpass\n\t\t# printdebug(\"noise\")\n\t\t# printdebug(record_history)\n\t\treturn [ksearch_history, fsearch_history, record_history]\t\t\t\n\t\n\telse:\n\t\treturn None\n\t\t\n\t\t\n\t\t\n\n\n","sub_path":"bproject/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"182287561","text":"from webserver import *\nfrom uthread import *\nimport network\nimport socket\nfrom time import sleep\nimport sys\n\nclass MeshNetWebServer(thread):\n def __init__(self, config, name=\"MeshNetWebServer\", apmode=True, display=None):\n super().__init__(name, stack=8192)\n self._config = config\n self._apmode = apmode\n self._display = display if display else lambda text : None\n\n self._wlan = None\n\n # Loop to run server in apmode or host\n def run(self):\n rc = 0\n while rc == 0 and self.running:\n if ( self._apmode and self.create_accesspoint(self._config.get('apmode'))) or \\\n (not self._apmode and self.connect_to_accesspoint(self._config.get('host.ap'))):\n\n self._display(\"Web start\", clear=False, line=5)\n\n # Created network connection\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(('', 80))\n\n # Terminate server if running drops\n server = WebServer(term_request = lambda : not self.running)\n\n self._display(\"Web running\", clear = False, line=5)\n\n server.run(s,\n page_data={\n '/': self.home_page,\n '/config': self.config_page,\n '/reboot': self.reboot_page,\n # Default for invalid page reference\n None: self.not_found_page,\n })\n \n s.close()\n\n self.disconnect()\n seld._display(\"Web stopped\", clear=False, line=5)\n else:\n self._display(\"Web failed\", clear=False, line=5)\n rc = -1\n\n return rc\n\n def connect_to_accesspoint(self, config):\n try:\n self._wlan = network.WLAN(network.STA_IF)\n\n # print(\"connect_to_accesspoint '%s'\" % (config))\n # Connect to lan\n self._wlan.active(True)\n self._wlan.connect(config['essid'], config['password'])\n # print(\"connect_to_accesspoint with %s %s\" % (config['essid'], config['password']))\n \n # Wait until connected or 30 second timeout\n # Cannot use lightsleep as it kills the network\n timer = utime.time() + 30\n while not self._wlan.isconnected() and utime.time() < timer:\n pass\n \n if self._wlan.isconnected():\n # print(\"connect_to_accesspoint: %s\" % (str(self._wlan.ifconfig())))\n self._display(\"%s\" % self._wlan.ifconfig()[0], clear=False)\n else:\n self.disconnect()\n\n except Exception as e:\n sys.print_exception(e)\n self.disconnect()\n\n return self._wlan != None\n\n def disconnect(self):\n if self._wlan:\n try:\n self._wlan.disconnect()\n except:\n pass\n finally:\n self._wlan.active(False)\n\n self._wlan = None\n\n def create_accesspoint(self, config):\n\n try:\n self._wlan = network.WLAN(network.AP_IF)\n self._wlan.active(True)\n\n essid = config['essid']\n password = config['password']\n if password != \"\":\n self._wlan.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=password)\n else:\n self._wlan.config(essid=essid)\n\n print(\"create_accesspoint: %s\" % str(self._wlan.ifconfig()))\n self._display(\"%s\" % self._wlan.ifconfig()[0], clear=False)\n\n except Exception as e:\n sys.print_exception(e)\n self.disconnect()\n\n return self._wlan != None\n\n def home_page(self, request=None, notice=None):\n if request is None or request.method == \"GET\":\n # Create simple webserver access\n header = build_header(\"200 OK\", \"text/html\")\n \n html = open(\"html/index.html\").read().format(device=self._config.get(\"device.name\"), notice=\"

\"+notice+\"

\" if notice else \"\",)\n \n else:\n header, html = self.home_page(notice=\"Invalid type: %s\" % request.method)\n \n return header, html\n \n def not_found_page(self, request=None, notice=None):\n return build_header(\"404 Not Found\", \"text/html\"), open(\"html/not_found.html\").read()\n\n def config_page(self, request=None, notice=None):\n if request is None or request.method == \"GET\":\n var_list = self._config.list()\n \n # Sort them\n var_list.sort()\n \n rows = []\n for var in var_list:\n value = self._config.get(var)\n try:\n # print(\"trying options\")\n # Split var into subvars and final var\n subvar, endvar = var.rsplit('.', 1)\n # print(\"Looking at %s.%%%s%%options\" % (subvar, endvar))\n selector = self._config.get(\"%s.%%%s%%options\" % (subvar, endvar))\n # print(\"selector is %s (%s)\" % (selector, type(selector)))\n # Selector with option list\n rows.append(\"%s\")\n\n except Exception as e:\n # sys.print_exception(e)\n # Simple table data entry\n rows.append(\"%s\" % (var, var, value))\n \n header = build_header(\"200 OK\", \"text/html\")\n html = open(\"html/config.html\").read().format( device=self._config.get(\"device.name\"), table='\\n'.join(rows), notice=\"

\"+notice+\"

\" if notice else \"\",)\n \n elif request.method == 'POST':\n \n response = request.post_response()\n \n help(response)\n\n try:\n # Put the results into the persistent data field\n for item in response:\n # print(\"config_page: processing '%s'\" % item)\n name, value = item.split('=', 1)\n self._config.set(name, value)\n \n self._config.flush()\n notice = \"Configuration updated\"\n \n except Exception as e:\n sys.print_exception(e)\n notice = str(e)\n \n header, html = self.config_page(notice=notice)\n \n else:\n header, html = self.config_page(notice=\"Invalid type: %s\" % request.method)\n \n return header, html\n\n def reboot_page(self, request=None, notice=None):\n if request is None or request.method == \"GET\":\n\n header = build_header(\"200 OK\", \"text/html\")\n html = open(\"html/reboot.html\").read().format(device=self._config.get(\"device.name\"), notice=\"

\"+notice+\"

\" if notice else \"\",)\n \n elif request.method == 'POST':\n header, html = self.home_page(notice=\"Rebooting\")\n \n # Set a thread to do a reboot after five seconds\n thread(run=self.reboot_delay).start()\n\n else:\n header, html = self.reboot_page(notice=\"Invalid type: %s\" % request.method)\n \n return header, html\n\n def reboot_delay(self, t):\n sleep(1)\n import machine\n machine.reset()\n\n \n","sub_path":"meshnetwebserver.py","file_name":"meshnetwebserver.py","file_ext":"py","file_size_in_byte":7886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399572546","text":"import numpy as np\nfrom collections import namedtuple\n\nclass TrainingReport():\n \"\"\"\n This class is used to store the results in a form which can later be easily plotted.\n \"\"\"\n def __init__(self, training_episodes):\n \"\"\"\n Creating the data structure which is later given to the plotting function.\n \"\"\"\n self.training_episodes = training_episodes\n zero_vector = np.zeros(self.training_episodes)\n self.EpisodeStats = namedtuple(\"Stats\", [\"length\", \"reward\"])\n self.report = self.EpisodeStats(length=zero_vector, reward=zero_vector)\n self.test_report = self.EpisodeStats(length=zero_vector, reward=zero_vector)\n\n def add2testreport(self, ep, length, reward):\n self.report[ep](length=length, reward=reward)\n","sub_path":"project/nico/backups/nico_backup/code backups/nico_working_backup_2/assets/reports/Report.py","file_name":"Report.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6488084","text":"# Строка состоит из слов, разделенных одним или несколькими пр��белами.\n# Поменяйте местами наибольшее по длине слово и наименьшее.\n\ndef max_to_min_to_max(text):\n\n min_word = text.split(' ')[0]\n max_word = ''\n num_min, num_max = 0, 0\n\n#\n\n for i in text.split(' '):\n\n if i.isalpha():\n if len(i) < len(min_word):\n min_word = i\n if len(i) > len(max_word):\n max_word = i\n else:\n if ((len(i) - 1) < len(min_word)) and (i != ''):\n min_word = i[:-1]\n if (len(i) - 1) > len(max_word):\n max_word = i[:-1]\n\n#\n\n word_array = text.split(' ')\n\n for j in word_array:\n if (j != max_word) and (j[:-1] != max_word):\n num_max += 1\n else:\n break\n for j in word_array:\n if (j != min_word) and (j[:-1] != min_word):\n num_min += 1\n else:\n break\n\n#\n\n if word_array[num_min].isalpha():\n word_array[num_min] = max_word\n else:\n word_array[num_min] = max_word + word_array[num_min][-1]\n\n if word_array[num_max].isalpha():\n word_array[num_max] = min_word\n else:\n word_array[num_max] = min_word + word_array[num_max][-1]\n\n#\n\n result = ''\n\n for i in word_array:\n result += i + ' '\n\n result = result.rstrip()\n\n print(text)\n print(result)\n\nmax_to_min_to_max('These nested replacement fields may contain a field name, conversion flag and format '\n 'specification, but deeper nesting is not allowed.')","sub_path":"HW_2_#52.py","file_name":"HW_2_#52.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"453228907","text":"# CS300 Periodic MQTT traffic generator\nimport paho.mqtt.client as mqtt\nimport time\nimport os\n\n# Constants\nBROKER = 'mqtt.eclipse.org'\nPORT = 1883\nQOS = 0\nDELAY = 5.0\nTOPIC = 'zc26/test'\n\n# Callback when connecting to the MQTT broker\ndef on_connect(client, userdata, flags, rc):\n if rc==0:\n print('Connected to',BROKER)\n else:\n print('Connection to',BROKER,'failed. Return code=',rc)\n os._exit(1)\n\n# Setup MQTT client and callbacks\nclient = mqtt.Client()\nclient.on_connect = on_connect\n\n# Connect to MQTT broker\nclient.connect(BROKER, PORT, 60)\nclient.loop_start()\n\n# Continuously publish message\ntry:\n while True:\n print('Sending MQTT message')\n client.publish(TOPIC, 'hello world')\n time.sleep(DELAY)\nexcept KeyboardInterrupt:\n print(\"Done\")\n client.disconnect()\n","sub_path":"Labs/Lab10/mqtt-hello.py","file_name":"mqtt-hello.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"642597250","text":"import os, string\n\ndef rename_files():\n # Get filenames\n file_list = os.listdir(r\"/Users/ryanmanthey/Desktop/python/prank\")\n # print(file_list)\n cwd = os.getcwd()\n #print(\"Current working directory is \" +cwd)\n os.chdir(r\"/Users/ryanmanthey/Desktop/python/prank\")\n # Rename each filename, drop the numbers\n for file_name in file_list:\n translation = str.maketrans(string.ascii_letters, string.ascii_letters, string.digits)\n os.rename(file_name, file_name.translate(translation))\n print(file_list)\n\nrename_files() \n","sub_path":"secret.py","file_name":"secret.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"408549846","text":"#!/usr/bin/env python2\n\nimport random\nfrom sys import argv\n\nout = open('./data.csv', 'w')\nout.write('')\nout.flush()\n\ncols = int(argv[1])\n\nfor i in range(60000):\n\tfor i in range(cols-1):\n\t\tout.write(str(random.random()) + \",\")\n\t\tout.flush()\n\tout.write(str(random.random()) + '\\n')\n\tout.flush()\nout.close()\n","sub_path":"docker/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"465738664","text":"#!/usr/bin/env python\n\"\"\"\nticker.py\n---------\n\"\"\"\nimport rospy\nfrom std_msgs.msg import Empty\n\n\nclass Ticker(object):\n \"\"\"\n A simple object that publish 'tick' messages on a ROS topic at a given rate.\n\n Args:\n node_name (str): The desired ROS node name.\n topic (str): The topic on which to send the ticks.\n param3 (double): The rate of tick's pubblication.\n \"\"\"\n\n def __init__(self, node_name, topic, rate):\n self._node_name = node_name\n self._topic = topic\n self._rate = rate\n\n def spin(self):\n \"\"\"\n Start the ticker.\n \"\"\"\n rospy.init_node(self._node_name)\n pub = rospy.Publisher(self._topic, Empty, queue_size=10)\n rate = rospy.Rate(self._rate)\n while not rospy.is_shutdown():\n pub.publish(Empty())\n rate.sleep()\n","sub_path":"mapek_framework/src/mapek_framework/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"345848838","text":"#!/usr/bin/env python\n\nfrom termcolor import colored\nfrom libtest import *\n\nprint(colored('Iniciando test de diferencias C vs. la catedra...', 'blue'))\n\ntodos_ok = True\n\narchivos = archivos_tests()\nfor corrida in corridas:\n for imagen in archivos:\n ok = verificar(corrida['filtro'], corrida['params'], corrida['tolerancia'], 'asm', imagen)\n todos_ok = todos_ok and ok\n\nif todos_ok:\n print(colored(\"Test de filtros finalizados correctamente\", 'green'))\nelse:\n print(colored(\"se encontraron diferencias en algunas de las imagenes\", 'red'))\n","sub_path":"src/tests/2_test_diff_cat_asm.py","file_name":"2_test_diff_cat_asm.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"39169742","text":"import pandas as pd\nfrom itertools import chain\nfrom pgmpy.models import BayesianModel\nfrom pgmpy.models import DynamicBayesianNetwork as DBN\nfrom pgmpy.inference import DBNInference\nfrom pgmpy.estimators import ParameterEstimator\nfrom pgmpy.factors.discrete import TabularCPD\nfrom sklearn.preprocessing import KBinsDiscretizer\nimport numpy as np\nimport json\n# ------------------------------------------------------------------------------------------------------\n# File Handling\n\n\ndef load_model(model_name, path='../../Models/'):\n '''\n Inputs:\n model_name: model name (string).\n path: path to model (optional).\n 1 - Load model from path.\n 2 - Check if model is valid.\n Returns: PGMPY model object.\n '''\n\n import pickle\n pickle_in = open(f\"{path}{model_name}.pickle\", \"rb\")\n model = pickle.load(pickle_in)\n\n if model.check_model():\n print(\"Model Loaded and Checked!\")\n\n return model\n\n\ndef build_porcentagem(data):\n date=data['DATA']\n date=date.iloc[12:len(date)]\n date = date.reset_index(drop=True)\n data=data.drop(['DATA'],axis=1)\n dados=[]\n for linha in range(0,len(data)-12):\n valores=[]\n for coluna in data:\n #x = dataframe.loc[linha][coluna]\n x = ((data.iloc[linha + 12][coluna] * 100) / data.iloc[linha][coluna])-100\n valores.append('%.2f'%float(x))\n dados.append(valores)\n dataset=pd.DataFrame(dados,columns=data.columns)\n dataset=pd.concat([date,dataset],axis=1)\n return dataset\n\n#--- Cria as bases por mês no formato VARIAVEL_0, VARIAVEL_1\ndef criar_base_mes(mes,Data):\n month=['January','February','March','April','May','June','July','August','September','October','November','December']\n #0 - Janeiro | 1 - Fevereiro ... | 11 - Dezembro\n Data=pd.DataFrame(Data)\n date=Data['DATA']\n date=pd.DatetimeIndex(date)\n \n mat = []\n for i in range(len(Data)):\n if date[i].month_name()==month[mes]:\n mat.append(i)\n elif date[i].month_name()!=month[mes]:\n continue\n Data_t = Data.iloc[mat]\n Data_t = Data_t.reset_index(drop=True)\n Data_t=Data_t.drop(['DATA'],axis=1)\n \n if len(Data_t)%2!=0:\n Data_t = Data_t.iloc[1:len(mat)]\n Data_t = Data_t.reset_index(drop=True)\n t0 = []\n for i in range(0,len(Data_t),2):\n t0.append(i)\n matrix_t0 = Data_t.iloc[t0]\n \n t1 = []\n for i in range(1,len(Data_t),2):\n t1.append(i)\n \n \n matrix_t1 = Data_t.iloc[t1]\n \n matrix_t0=matrix_t0.rename(columns=lambda x: x+'_0')\n matrix_t1=matrix_t1.rename(columns=lambda x: x+'_1')\n \n matrix_t0=pd.concat([matrix_t0.reset_index(drop=True), matrix_t1.reset_index(drop=True)], axis=1)\n \n else:\n t0 = []\n for i in range(0,len(mat),2):\n t0.append(i)\n matrix_t0 = Data_t.iloc[t0]\n \n t1 = []\n for i in range(1,len(mat),2):\n t1.append(i)\n \n \n matrix_t1 = Data_t.iloc[t1]\n \n matrix_t0=matrix_t0.rename(columns=lambda x: x+'_0')\n matrix_t1=matrix_t1.rename(columns=lambda x: x+'_1')\n \n matrix_t0=pd.concat([matrix_t0.reset_index(drop=True), matrix_t1.reset_index(drop=True)], axis=1)\n return matrix_t0\n\n#--- Cria um doc JSON com o nome completo das variaveis e suas faixas de discretização\ndef build_doc_variavel_discretizacao(dados_brutos,legendas,bins=3,type_disc='kmeans',usuario='user'):\n data = dados_brutos.drop(['DATA'],axis=1)\n df=pd.DataFrame(data)\n lista=list(df.columns)\n meses=['JANEIRO','FEVEREIRO','MARCO','ABRIL','MAIO','JUNHO','JULHO','AGOSTO','SETEMBRO','OUTUBRO','NOVEMBRO','DEZEMBRO']\n dict_meses=dict()\n for m in range(len(meses)):\n mat = []\n for i in range(m,len(df),12):\n mat.append(i)\n Data_t = df.iloc[mat]\n Data_t = Data_t.reset_index(drop=True)\n est = KBinsDiscretizer(n_bins=bins,encode='ordinal', strategy=type_disc.lower())\n r = est.fit(Data_t)\n x=r.bin_edges_\n faixas=dict()\n for j,i in zip(lista,x):\n faixas[j]=list(i)\n df_legenda = legendas\n dict_legenda=dict()\n for i in range(len(df_legenda)):\n legenda=list(df_legenda[i])\n dict_legenda[legenda[1]]=legenda[0]\n\n var_discretize=dict()\n for var,value in zip(lista,faixas.values()):\n if var in dict_legenda:\n var_discretize[dict_legenda[var]]=value\n dict_meses[meses[m]]=var_discretize\n\n with open('../Data/JSON_files/FAIXAS_'+usuario+'.json', 'w') as json_fl:\n json.dump(dict_meses, json_fl, indent=4)\n\n#--- Disrcetiza as bases para a Rede Dinâmica\n\ndef discretize_data_quantile(dataframe,bins=3,type_discr='kmeans'):\n # kmeans | quantile | uniform\n #n_bins=3 (Default)\n # dataframe: Base que foi passada pela função \"criar_base_mes\"\n lista=list(dataframe.columns)\n est = KBinsDiscretizer(n_bins=bins,encode='ordinal', strategy=type_discr.lower())\n r = est.fit(dataframe)\n disc = est.transform(dataframe)\n discretized_dataframe=pd.DataFrame(disc,columns=lista)\n #####################################\n x=r.bin_edges_\n faixas=dict()\n for j,i in zip(lista,x):\n faixas[j]=i \n #####################################\n\n return discretized_dataframe, faixas\n\n\n#--- Cria as arestas no formato pedido pela Rede Bayesiana Dinâmica\n\ndef build_edges(ed):\n edges=list(ed)\n edges_0=[]\n for i in range(len(edges)):\n x=(tuple(edges[i][0].split('_')),tuple(edges[i][1].split('_')))\n edges_0.append(x)\n edge=[]\n for j in range(len(edges_0)):\n y=((edges_0[j][0][0],int(edges_0[j][0][1])),(edges_0[j][1][0],int(edges_0[j][1][1])))\n edge.append(y)\n return edge\n\n#--- Constroi as Tabelas de Probabilidades Condicionais (CPDs) para a Rede Dinâmica\n\ndef build_dbn_cpds(edges,dbn_model,nodes_dbn, discretized_data):\n nodes=list(nodes_dbn)\n model = BayesianModel(edges)\n estimator = BayesianEstimator_V2(model, discretized_data)\n cpds=[] \n for no in nodes:\n node=(no[0]+'_'+str(no[1]))\n valor,card,cardi=estimator.estimate_cpd(node, prior_type=\"BDeu\")\n if len(dbn_model.get_parents(no))==0:\n cpd=TabularCPD(no,\n card,\n valor)\n cpds.append(cpd)\n else:\n cpd=TabularCPD(no,\n card,\n valor,\n evidence=dbn_model.get_parents(no),\n evidence_card=cardi[1:]\n )\n cpds.append(cpd)\n return cpds\n\n#--- Classe que cria os valores de probabilidades para estimação bayesiana (Alterada para se adequar à Rede Dinâmica)\n\nclass BayesianEstimator_V2(ParameterEstimator):\n def __init__(self, model, data, **kwargs):\n \n self.model=model\n self.data=data\n\n super(BayesianEstimator_V2, self).__init__(model, data, **kwargs)\n\n def estimate_cpd(\n self, node, prior_type=\"BDeu\", pseudo_counts=[], equivalent_sample_size=5\n ):\n\n node_cardinality = len(self.state_names[node])\n parents = sorted(self.model.get_parents(node))\n parents_cardinalities = [len(self.state_names[parent]) for parent in parents]\n cpd_shape = (node_cardinality, np.prod(parents_cardinalities, dtype=int))\n\n if prior_type == \"K2\":\n pseudo_counts = np.ones(cpd_shape, dtype=int)\n elif prior_type == \"BDeu\":\n alpha = float(equivalent_sample_size) / (\n node_cardinality * np.prod(parents_cardinalities)\n )\n pseudo_counts = np.ones(cpd_shape, dtype=float) * alpha\n elif prior_type == \"dirichlet\":\n pseudo_counts = np.array(pseudo_counts)\n if pseudo_counts.shape != cpd_shape:\n raise ValueError(\n \"The shape of pseudo_counts for the node: {node} must be of shape: {shape}\".format(\n node=node, shape=str(cpd_shape)\n )\n )\n else:\n raise ValueError(\"'prior_type' not specified\")\n\n state_counts = self.state_counts(node)\n bayesian_counts = state_counts + pseudo_counts\n\n cpd = TabularCPD(\n node,\n node_cardinality,\n np.array(bayesian_counts),\n evidence=parents,\n evidence_card=parents_cardinalities,\n state_names={var: self.state_names[var] for var in chain([node], parents)},\n )\n cpd.normalize()\n values=cpd.get_values()\n card=cpd.variable_card\n cardi=cpd.cardinality\n valor=[]\n for value in values:\n v=[]\n for value_1 in value:\n v.append(round(value_1, 8))\n valor.append(v)\n return valor,card,cardi\n\n#--- Função que cria as inferencias das Redes Dinâmicas Criadas\n \ndef Dynamic_Bayesian_Inference(topologia, top, discretized_df,data,data_sup,mes,faixas,json_doc):\n \n #REDE BAYESIANA DINÂMICA\n dbn = DBN()\n dbn.add_edges_from(topologia)\n CPDs=build_dbn_cpds(top,dbn,dbn.nodes(),discretized_df)\n for cpds in CPDs:\n dbn.add_cpds(cpds)\n dbn.initialize_initial_state()\n \n dbn_inf = DBNInference(dbn)\n meses_=['JANEIRO','FEVEREIRO','MARCO','ABRIL','MAIO','JUNHO','JULHO','AGOSTO','SETEMBRO','OUTUBRO','NOVEMBRO','DEZEMBRO']\n with open(json_doc, 'r') as js_file:\n inferencia = json.load(js_file)\n key=list(inferencia.keys())\n value=list(inferencia.values())\n target=(key[0],value[0])\n \n flag=float(data_sup[target[0]+'_1'][len(data)-1])\n\n dicio=dict()\n dicio_target=[]\n print(meses_[mes],'-------------------------------------------------------------------------------|')\n for i in range(int(target[1])):\n g_key=list(inferencia['ANO_'+str(i)].keys())\n # SE O ANO TIVER EVIDENCIA, SERÁ FEITO INFERENCIA COM EVIDENCIA REFERENTE AO TEMPO E MÊS CORRENTE\n if len(inferencia['ANO_'+str(i)])!=0 and 'MES_'+str(mes) in g_key and len(inferencia['ANO_'+str(i)]['MES_'+str(mes)])!=0:\n dict_local=dict()\n # SEÁ PEGO AS EVIDENCIAS DO MÊS REFERENTE A BASE USADA\n evidencias=inferencia['ANO_'+str(i)].get('MES_'+str(mes))\n l_key=list(evidencias.keys())\n l_value=list(evidencias.values())\n # SERÁ CRIADO UM DICIONARIO PARA A FUNÇÃO DE INFERENCIA REFERENTE AO TEMPO E MÊS ESPECIFICO\n d=dict()\n for k in range(len(l_key)):\n evi=(l_key[k],i)\n d[evi]=int(l_value[k])\n \n inf=list(dbn_inf.backward_inference([(target[0],i)],d)[(target[0],i)].values)\n \n prob=max(inf)\n index_prob=inf.index(prob)\n f=list(faixas[target[0]+'_'+'0'])\n print('faixas ',f)\n pormed = ((float(f[int(index_prob)])+float(f[int(index_prob)+1]))/2)/100\n medflag = flag*pormed+flag\n maxflag =(flag*(f[int(index_prob)+1]/100))+flag \n flag= (flag*(f[int(index_prob)]/100))+flag\n \n nivel=['Baixo', 'Medio', 'Alto']\n print(target[0],'--- Tempo'+'_'+str(i),'--- Probabilidade: ',prob,'--- Nivel: ',nivel[index_prob])\n print('Min: ',flag)\n print(\"Media\",medflag)\n print('Max: ',maxflag,'\\n')\n dict_local['VALOR TOTAL']=flag\n dict_local['PROBABILIDADE']=prob\n dict_local['NIVEL']=nivel[index_prob]\n dict_local['MEDIO']= medflag#(float(f[int(index_prob)])+float(f[int(index_prob)+1]))/2\n dict_local['MAX']=maxflag#f[int(index_prob)+1]\n dict_local['MIN']=flag#f[int(index_prob)]\n dicio_target.append(dict_local)\n \n elif len(inferencia['ANO_'+str(i)])!=0 and 'MES_'+str(mes) not in g_key:\n continue\n \n \n else:\n dict_local=dict()\n inf=list(dbn_inf.backward_inference([(target[0], i)])[(target[0],i)].values)\n prob=max(inf)\n index_prob=inf.index(prob)\n f=list(faixas[target[0]+'_'+'0'])\n \n pormed = ((float(f[int(index_prob)])+float(f[int(index_prob)+1]))/2)/100\n medflag = flag*pormed+flag\n maxflag =(flag*(f[int(index_prob)+1]/100))+flag \n \n flag=(flag*(f[int(index_prob)]/100))+flag\n nivel=['Baixo', 'Medio', 'Alto']\n print(target[0],'--- Tempo'+'_'+str(i),'--- Probabilidade: ',prob,'--- Nivel: ',nivel[index_prob])\n print('Min: ',flag)\n print(\"Media\",medflag)\n print('Max: ',maxflag,'\\n')\n \n dict_local['VALOR TOTAL']=flag\n dict_local['PROBABILIDADE']=prob\n dict_local['NIVEL']=nivel[index_prob]\n dict_local['MEDIO']= medflag#(float(f[int(index_prob)])+float(f[int(index_prob)+1]))/2\n dict_local['MAX']=maxflag#f[int(index_prob)+1]\n dict_local['MIN']=flag#f[int(index_prob)]\n dicio_target.append(dict_local)\n dicio[target[0]]=dicio_target\n\n \n return dicio\n\ndef build_dbn(topologia, top, nodes, dataframe, n_bins, tipo_discretizacao, json_doc, usuario):\n meses=['JANEIRO','FEVEREIRO','MARCO','ABRIL','MAIO','JUNHO','JULHO','AGOSTO','SETEMBRO','OUTUBRO','NOVEMBRO','DEZEMBRO']\n dic_infer=dict()\n \n dataset=build_porcentagem(dataframe)\n dataframe = dataframe.loc[12:len(dataframe)]\n dataframe = dataframe.reset_index(drop=True)\n #dataset=dt.loc[12:len(dt)]\n for m in range(len(meses)):\n mes=m\n \n data = criar_base_mes(mes,dataset)\n data_sup=criar_base_mes(mes,dataframe)\n #data_sup=data_sup.loc[1:len(data_sup)]\n \n #DISCRETIZA CADA DATASET\n # Tipos de discrcetização: kmeans (Default) | quantile | uniform\n # def discretize_data_quantile(dataframe,lista,bins,type_discr='kmeans')\n\n discretized_data,faixas = discretize_data_quantile(data, n_bins, tipo_discretizacao)\n\n #INFERENCIA DE CADA MÊS\n infer=Dynamic_Bayesian_Inference(topologia, top,discretized_data,data,data_sup,mes, faixas, json_doc)\n\n dic_infer[meses[mes]]=infer\n\n # ----- Salva modelo (pickle) e intervalos de discretização (csv? json?)\n\n with open('../Data/JSON_files/SAIDA_'+usuario+'.json', 'w') as json_file:\n json.dump(dic_infer, json_file, indent=4)\n \n return dic_infer\n \n","sub_path":"Source/Utilities/utilities_old.py","file_name":"utilities_old.py","file_ext":"py","file_size_in_byte":14632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"70434046","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 3 12:31:03 2019\n\n@author: Isaiah Lemmon isaiah.lemmon@pnnl.gov\n\nThis is the main file to be execeuted, tying all the of the other modules together\nand creating the gui. Some important things are hardcoded here:\n \n - The regex's to match the file names of the raw spectra and the InStep autosave to\n \n - The pump that the PID will dispense from to (currently the first one connected to this PC)\n \n - Defaults for the PID:\n These can be changed in the gui:\n - 200mL max volume\n - The index of the Autosave file that is tracked (currently 0)\n \n These must be changed in this file:\n - The location of the pid log_file (currently the same directory as \n the autosave file)\n \n\"\"\"\n\nimport asyncio\nfrom watchgod import awatch, RegExpWatcher\nimport classes\nimport gui \nimport tkinter as tk\nfrom pathlib import Path\nfrom datetime import datetime\n\n\nasync def run_tk(root, loop, interval=0.06):\n '''\n Async way to run the tkinter main loop. Allows other processes to run for interval.\n \n Not very kosher, but works. Pass this method as a task to the asyncio loop\n and the mainloop for tkinter will exceute asynchronously, allowing time\n for other taks to run. The interval refers to the time in seconds between\n gui updates, reccomended to keep at least below 0.1s (10fps).\n \n If the tkinter root is closed, the event loop is stopped with no error. Otherwise,\n an exception is raised normally.\n \n Parameters\n ----------\n root : tk.Tk subclass\n The root of the tkinter application\n \n loop : asyncio.event_loop\n The asyncio event loop - used to end all tasks in loop when root is closed\n \n interval : float\n Time in seconds between gui updates\n '''\n try:\n while True:\n root.update() \n await asyncio.sleep(interval)\n except tk.TclError as e:\n if \"application has been destroyed\" not in e.args[0]:\n raise e\n else:\n loop.stop()\n\nasync def instep_watcher(path, regex, pred_handler, pid_handler, app, log_file):\n '''\n Async file watcher for InStep autosave files.\n \n Given a path to a directory, watches that path for files matching the regex value\n of the 're_files' key in watch_kwargs. Passes that info to the prediction handler,\n then calls the pid handler to update. It then retrieves the response from the\n pid handler and uses the app to dispense that volume to the pump. Finally, \n it updates all the plots in the app.\n \n This function is what ties together most of the functionality of the prediction\n control loop. Currently, the PID ordering a specific pump to dispense volume\n is hard-coded here as pump 1.\n \n Parameters\n ----------\n path : string\n full path to directory to watch for InStep autosave files.\n \n regex : string\n A regex that will match the name of the InStep Autosave file\n \n pred_handler : classes.PredictionHandler\n The prediction handler to pass updates of the autosave file to. This should\n be the same prediction handler that the pid_handler is tied to, but\n is left explicit here for clairity.\n \n pid_handler : classes.PIDHandler\n The PIDHandler that will be updating based on the new predicted value.\n \n app : gui.App\n The main app holding all the tabs required.\n '''\n # By changing the value of re_files, the regex to match the name of an\n # autosave file can be changed\n watch_kwargs = {'re_files' : regex, \n 're_dirs' : None}\n \n # Update every 1000ms\n async for changes in awatch(path, watcher_cls=RegExpWatcher, \n watcher_kwargs=watch_kwargs, min_sleep = 1000):\n \n # Handle an event in the directory matching the regex of re_files\n for event, path in changes:\n await pred_handler.on_any_event(event, path) # Let pred_handle update\n await pid_handler.trigger_PID() # Trigger the PID with the new values\n vol = pid_handler.last() # Get the most recent PID output\n \n selected_pump = app.pages[\"PID Control\"].get_selected_pump()\n \n if selected_pump != '':\n await app.pages[\"Pump\"].dispense_vol(selected_pump, vol) # Dispense that to the pump\n ratio = app.pages[\"Pump\"].get_ratio(selected_pump)\n \n else: \n ratio = \"N/A\"\n \n with open(log_file, 'a') as f:\n line = ', '.join([str(selected_pump), str(ratio)])\n f.write(line)\n f.write('\\n')\n \n app.update_plots() # Update the plots\n \n \nasync def raw_watcher(path, regex, raw_handler):\n '''\n Async file watcher for raw raman spectrum files in a directory.\n \n Calls raw_handler when an event matching regex in path occurs\n \n Parameters\n ----------\n path : string\n Full path to directory to watch for raw spectra files\n \n regex : string\n Regex to match raw spectra file names to\n \n raw_handler : classes.RawFileProcessor\n The RawFileProcessor that will process the raw file into an Instep format\n '''\n watch_kwargs = {'re_files' : regex, \n 're_dirs' : None}\n # Check for events every 1000ms\n async for changes in awatch(path, watcher_cls=RegExpWatcher, \n watcher_kwargs=watch_kwargs, min_sleep = 1000):\n # For every change \n for event, path in changes:\n await raw_handler.on_any_event(event, path) # Pass to raw_handler\n \ndef init_paths():\n '''\n Prompt user for file paths to the raw in_directory and the Instep autosave directory.\n \n Also creates the directory in_directory/Output to place InStep in files to\n if it does not already exist.\n \n Returns\n -------\n dict{string : string}\n A dictionary in which file paths are stored. 'raw' corresponds to the path\n where raw spectra files will be placed. 'instep' corresponds to the path\n that the InStep autosave file will appear in\n '''\n paths = {}\n \n root = tk.Tk() # Create parent window and hide it\n root.withdraw()\n \n tk.messagebox.showinfo('Python', 'Select the directory where raw spectra will be placed')\n paths['raw'] = tk.filedialog.askdirectory()\n \n output_path = Path(paths['raw']) / 'Output' # Add output folder to that dir if it doesn't exist\n if not output_path.exists():\n output_path.mkdir()\n tk.messagebox.showinfo('Python', f'Set InStep In location to {output_path}')\n\n # Prompt for directory where InStep will place the autosave file\n tk.messagebox.showinfo('Python', 'Select the directory where the predicted' +\n ' autosave file will be placed')\n \n paths['instep'] = tk.filedialog.askdirectory()\n \n root.destroy()\n \n return paths\n \ndef main():\n '''\n Excutes full program. Sets up all handlers and initailzes the gui\n '''\n time_string = datetime.now().strftime('%Y%m%d %H%M')\n \n \n # Get necessary file paths\n paths = init_paths()\n# paths = {'instep':'C:/Users/Raman/Desktop/Instep_out', 'raw':'C:/Users/Raman/Desktop/Raman/Input'}\n \n raman_regex = r'.+\\.txt' # Raman file is any that ends in .txt\n \n # InStepAutosave is any that ends in InStepAutoSave.txt\n instep_regex = r'.+InStepAutoSave\\.txt' \n \n # Create the raw spectrum handler\n raw_handler = classes.RawFileProcessor()\n \n # Create the plotter for the prediction handler, then create the prediction handler\n prediction_plotter = classes.Plotter()\n prediction_plotter.set_ylabel('Concentration (g/L)')\n prediction_handler = classes.PredictionHandler(prediction_plotter)\n \n # Create the plotter for the PID handler, then create the PID handler\n pid_plotter = classes.Plotter()\n pid_plotter.set_ylabel('Cumulative Vol. (mL)')\n \n # Here the log file of the PID handler is set to be in the same directory as\n # the InStep autosave file.\n # Other defaults are set, like the 200mL max volume, and that it's tracking index 0 of\n # the autosave file\n \n paths['log_file'] = paths['instep'] + f'/pid_log_{time_string}.txt' # Where to save PID output\n pid_handler = classes.PIDHandler(200, prediction_handler, pid_plotter, 0, \n paths['log_file'])\n \n # Create the plotting_dict and pass it to the App\n plot_dict = {'Raman Plot' : prediction_plotter, 'PID Plot' : pid_plotter}\n app = gui.App(plot_dict, pid_handler)\n \n # Get the current event loop\n loop = asyncio.get_event_loop()\n \n # Add the three async tasks defined above to event loop\n loop.create_task(run_tk(app, loop))\n loop.create_task(raw_watcher(paths['raw'], raman_regex, raw_handler))\n loop.create_task(instep_watcher(paths['instep'], instep_regex, prediction_handler,\n pid_handler, app, paths['log_file']))\n \n # Run the loop forever\n loop.run_forever()\n \nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"548220930","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 3 11:06:21 2020\r\n\r\n@author: jlang\r\n\"\"\"\r\n\r\n###########################################\r\n############ ATR / BOLLINGER BANDS ########\r\n###########################################\r\n\r\n# Bollinger bands comprises of two lines at n std above ma, and m std below ma\r\n# ATR takes into acocunt the market movement each day\r\n\r\n# Typically used in conjunction as they approach volatility differently\r\n\r\nimport pandas_datareader.data as pdr\r\nimport datetime\r\n\r\nticker = \"MSFT\"\r\n\r\nohlcv = pdr.get_data_yahoo(ticker,\r\n datetime.date.today()-datetime.timedelta(1825),\r\n datetime.date.today())\r\n\r\n###########################################\r\n############ ATR ##########################\r\n###########################################\r\n\r\ndef ATR(DF,n):\r\n df = DF.copy()\r\n df['H-L']=abs(df['High']-df['Low'])\r\n df['H-PC']=abs(df['High']-df['Adj Close']).shift(1)\r\n df['L-PC']=abs(df['Low']-df['Adj Close']).shift(1)\r\n df['TR']=df[['H-L','H-PC','L-PC']].max(axis=1,skipna=False)\r\n df['ATR'] = df['TR'].rolling(n).mean()\r\n \r\n df2 = df.drop(['H-L','H-PC','L-PC'], axis=1)\r\n return df2\r\n\r\nATR(ohlcv,20)\r\n\r\n###########################################\r\n############ BOLLINGER BANDS ##############\r\n###########################################\r\n\r\ndef BollBands(DF,n):\r\n df = DF.copy()\r\n df['MA'] = df['Adj Close'].rolling(n).mean()\r\n df['BB_up'] = df['MA'] + df['MA'].rolling(n).std()\r\n df['BB_down'] = df['MA'] - df['MA'].rolling(n).std()\r\n df['BB_range'] = df['BB_up'] - df['BB_down']\r\n df.dropna(inplace = True)\r\n return df\r\n\r\nBollBands(ohlcv, 2)\r\n\r\nBollBands(ohlcv, 20).iloc[-100:,[-4,-3,-2]].plot()\r\n","sub_path":"Algorithm Structures/Technical Indicators/ATR_BollingerBands.py","file_name":"ATR_BollingerBands.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"293226965","text":"#!/usr/bin/python3\n\"\"\"\n Python script to export data in the JSON format.\n\"\"\"\n\nif __name__ == \"__main__\":\n import requests\n import sys\n import json\n\n id = sys.argv[1]\n user = requests.get(\"http://jsonplaceholder.typicode.com/users/{}\"\n .format(id)).json().get(\"username\")\n todo = requests.get(\"http://jsonplaceholder.typicode.com/todos\").json()\n\n mylist = []\n for task in todo:\n if (task.get(\"userId\") == int(id)):\n d = {}\n d[\"task\"] = task.get(\"title\")\n d[\"completed\"] = task.get(\"completed\")\n d[\"username\"] = user\n mylist.append(d)\n\n with open(\"{}.json\".format(id), 'w+') as jsonfile:\n json.dump({id: mylist}, jsonfile)\n","sub_path":"0x15-api/2-export_to_JSON.py","file_name":"2-export_to_JSON.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"148507700","text":"#-*- coding: utf-8 -*-\n#!/usr/bin/env python\n\nfrom django.shortcuts import render\nfrom .models import Projeto, Equipe, Alarme, ItemAlarme, FocoFIRMS, FocoWFABBA\nfrom .fma import FMA\nfrom .dashboard import DashBoard\nfrom django.template import RequestContext, loader\nfrom datetime import datetime\nfrom django.http import HttpResponse\nfrom django.contrib.gis.geos import Point\nfrom djgeojson.serializers import Serializer as GeoJSONSerializer\nfrom django.contrib.gis.gdal import DataSource\nfrom django.contrib.gis.gdal import OGRGeometry\nfrom django.contrib.gis.gdal.envelope import Envelope\nfrom .alarme import FocoToItemAlarme\nfrom django.contrib.auth.decorators import login_required\nfrom .pontoproximo import processa\nfrom .previsao import Previsao\nfrom toolbox import sitetools\nfrom django.shortcuts import redirect\nfrom geomet import wkt\nimport requests\nimport ogr\nfrom settings import \\\n GEOSERVER_AUTH,\\\n FIREMONITOR_DASHBOARD_URL001,\\\n FIREMONITOR_DASHBOARD_URL002, \\\n FIREMONITOR_DASHBOARD_URL003, \\\n FIREMONITOR_DASHBOARD_URL004, \\\n FIREMONITOR_GEONODE_URL\n\n\ndef getGeonodeJson(url):\n result = requests.post(url, headers=dict(referer=url), auth=GEOSERVER_AUTH)\n data = result.json()\n result.close()\n return data\n\ndef ponto_proximo(request, latitude, longitude):\n\n saida = processa(float(latitude), float(longitude))\n\n print(saida)\n\n previsao = None\n if saida['cidade']['ibge'] != '':\n previsao = Previsao(saida['cidade']['ibge'])\n\n\n urlcall1 = '/clima/automaticas/grafautomaticatotal/' + saida['automatica']['id'] + '/grafico/';\n urlcall2 = '/clima/automaticas/grafautomatica/' + saida['automatica']['codigo'] + '/0/2016/grafico/';\n\n urlcall3 = '/clima/normais/grafnormais/' + saida['normal']['id'] + '/grafico/'\n\n\n\n html = ''\n html +='

' + saida['cidade']['nome'] + '

'\n\n html += ''\n html +=''\n html += ''\n html += u''\n html += ''\n html +=''\n html += ''\n html += ''\n html += '
TipoNomeDistancia
Automatica' + saida['automatica']['estacao'] + '{0}'.format(saida['automatica']['dist']) + 'km
'\n html += 'Geral|
'\n html += 'Anual
Normal' + saida['normal']['estacao'] + '{0}'.format(saida['normal']['dist']) + 'km
'\n html += u'Gráfico
'\n\n if previsao:\n html += ''\n html +=''\n html += ''\n html += u''\n html += u''\n html += ''\n html +=''\n\n for item in previsao[:3]:\n html +=''\n html += ''\n html += ''\n html += ''\n html += ''\n html +=''\n html += '
DataMáxMinTempo
' + item.data + '' + str(item.temp_max) + 'C' + str(item.temp_min) + 'C\"\"
'\n\n return HttpResponse(html,content_type='text/html')\n\n\ndef focoPopUp(request, chave):\n\n campos = chave.split('X')\n key = int(campos[1])\n registro = None\n if campos[0] == 'F':\n registro = FocoFIRMS.objects.get(pk=key)\n else:\n registro = FocoWFABBA.objects.get(pk=key)\n\n objRegra = ItemAlarme()\n objRegra = FocoToItemAlarme()\n saida = objRegra.getMixin(registro, objRegra)\n\n html = ''\n html += ''\n html += '
  • ID :' + str(saida.foco_id) + '
  • '\n html += '
  • Registro :' + str(saida.dataregUTC) + '
  • '\n html += '
  • Data :' + str(saida.dataUTC) + '
  • '\n html += '
  • Posicao :' + u'[{0},{1}]'.format(saida.posicao[0], saida.posicao[1]) + '
  • '\n html += '
  • Temperatura :' + str(saida.temp) + '
  • '\n html += '
  • Confiabilidade :' + str(saida.confianca) + '
  • '\n html += '
  • Satellite :' + saida.satellite+ '
  • '\n html += '
  • Tam.PIxel :' + str(saida.pixsize) + '
  • '\n html += '
  • Tamanho do Foco :' + str(saida.firesize) + '
  • '\n html += '
  • Alogritmo :' + str(saida.alg)+ '
  • '\n html += ''\n\n return HttpResponse(html,content_type='text/html')\n\n\ndef OGREnvelope(geom):\n minX, maxX, minY, maxY = geom.GetEnvelope()\n\n ring = ogr.Geometry(ogr.wkbLinearRing)\n ring.AddPoint(minX, minY)\n ring.AddPoint(maxX, minY)\n ring.AddPoint(maxX, maxY)\n ring.AddPoint(minX, maxY)\n ring.AddPoint(minX, minY)\n\n # Create polygon\n poly_envelope = ogr.Geometry(ogr.wkbPolygon)\n poly_envelope.AddGeometry(ring)\n return poly_envelope\n\n\ndef firmsLayer(request, start, end):\n data = getGeonodeJson(FIREMONITOR_GEONODE_URL)\n geo_wkt = wkt.dumps(data['features'][0]['geometry'])\n wkt_geometry = ogr.CreateGeometryFromWkt(geo_wkt)\n bounds = OGREnvelope(wkt_geometry)\n dataRef1 = datetime.fromtimestamp(int(start)/1000)\n dataRef2 = datetime.fromtimestamp(int(end)/1000)\n\n query = FocoFIRMS.objects\\\n .filter(dataUTC__range= (dataRef1, dataRef2))\\\n .filter(posicao__intersects=bounds.ExportToWkt())\n geojson_data = GeoJSONSerializer().serialize( query, use_natural_keys=True)\n\n return HttpResponse(geojson_data,content_type='text/javascript')\n\ndef wfabbaLayer(request, start, end):\n data = getGeonodeJson(FIREMONITOR_GEONODE_URL)\n geo_wkt = wkt.dumps(data['features'][0]['geometry'])\n wkt_geometry = ogr.CreateGeometryFromWkt(geo_wkt)\n bounds = OGREnvelope(wkt_geometry)\n dataRef1 = datetime.fromtimestamp(int(start)/1000)\n dataRef2 = datetime.fromtimestamp(int(end)/1000)\n\n query = FocoWFABBA.objects\\\n .filter(dataUTC__range= (dataRef1, dataRef2))\\\n .filter(posicao__intersects=bounds.ExportToWkt())\n geojson_data = GeoJSONSerializer().serialize( query, use_natural_keys=True)\n\n return HttpResponse(geojson_data,content_type='text/javascript')\n\n\n\n@login_required()\ndef dashboard(request, idProjeto):\n context = RequestContext(request)\n page = sitetools.sitemap ( request.get_full_path ( ) ).context\n context.update ( page )\n\n if request.method == \"POST\":\n start = request.POST.get('txtStart')\n end = request.POST.get('txtEnd')\n data = datetime.strptime(start, '%d-%m-%Y')\n else:\n data = datetime.today()\n start = data.strftime('%d-%m-%Y')\n end = data.strftime('%d-%m-%Y')\n\n obj = DashBoard()\n resultado = obj.execute(idProjeto, data)\n context['result'] = resultado\n context['start'] = start\n context['end'] = end\n\n context['lyr001'] = getGeonodeJson(FIREMONITOR_DASHBOARD_URL001)\n context['lyr002'] = getGeonodeJson(FIREMONITOR_DASHBOARD_URL002)\n context['lyr003'] = getGeonodeJson(FIREMONITOR_DASHBOARD_URL003)\n context['lyr004'] = getGeonodeJson(FIREMONITOR_DASHBOARD_URL004)\n\n return render(request, 'firemonitor/dashboard_old.html', context)\n\n\n@login_required()\ndef dash(request):\n context = RequestContext(request)\n page = sitetools.sitemap(request.get_full_path()).context\n context.update(page)\n return redirect('/firemonitor/dashboard/1/')\n\n\n\n\ndef mailalertafoco(request, idAlarme):\n\n obj = Alarme.objects.get(id = idAlarme)\n\n objFMA = FMA()\n objFMA = objFMA.formula(obj.Projeto_FK.wmo_automatica, obj.data)\n\n foco = {}\n foco['alarm'] = obj\n\n foco['focos'] = ItemAlarme.\\\n objects.\\\n filter(Alarme_FK = obj).\\\n order_by('dataUTC')\n\n foco['para'] = Equipe.objects.filter(Projeto_FK = obj.Projeto_FK)[0]\n foco['fma'] = objFMA\n foco['caminho'] = 'http://{0}'.format( request.META['HTTP_HOST'] )\n\n context = RequestContext(request, { 'result' : foco, } )\n template = loader.get_template('mailalertafoco.html')\n\n return HttpResponse(template.render(context))\n\n\n\n","sub_path":"firemonitor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"573050047","text":"import re\n\nimport pytest\n\nfrom cognite.experimental import CogniteClient\nfrom cognite.experimental.data_classes import ContextualizationJob\nfrom cognite.experimental.exceptions import ModelFailedException\nfrom tests.utils import jsgz_load\n\nCOGNITE_CLIENT = CogniteClient()\nEEAPI = COGNITE_CLIENT.entity_extraction\n\n\n@pytest.fixture\ndef mock_complete(rsps):\n response_body = {\"jobId\": 123, \"status\": \"Queued\"}\n rsps.add(\n rsps.POST,\n EEAPI._get_base_url_with_base_path() + EEAPI._RESOURCE_PATH + \"/extract\",\n status=200,\n json=response_body,\n )\n yield rsps\n\n\n@pytest.fixture\ndef mock_status_ok(rsps):\n response_body = {\"jobId\": 123, \"status\": \"Completed\", \"items\": \"x\"}\n rsps.add(\n rsps.GET,\n re.compile(EEAPI._get_base_url_with_base_path() + EEAPI._RESOURCE_PATH + \"/\\\\d+\"),\n status=200,\n json=response_body,\n )\n yield rsps\n\n\n@pytest.fixture\ndef mock_status_failed(rsps):\n response_body = {\"jobId\": 123, \"status\": \"Failed\", \"errorMessage\": \"error message\"}\n rsps.add(\n rsps.GET,\n re.compile(EEAPI._get_base_url_with_base_path() + EEAPI._RESOURCE_PATH + \"/\\\\d+\"),\n status=200,\n json=response_body,\n )\n yield rsps\n\n\nclass TestEntityExtraction:\n def test_extract(self, mock_complete, mock_status_ok):\n entities = [\"a\", \"b\"]\n file_ids = [1, 2]\n job = EEAPI.extract(file_ids, entities)\n assert isinstance(job, ContextualizationJob)\n assert \"Queued\" == job.status\n assert {\"items\": \"x\"} == job.result\n assert \"Completed\" == job.status\n assert 123 == job.job_id\n\n extract_calls = 0\n n_status_calls = 0\n for call in mock_complete.calls:\n if call.request.method == \"POST\":\n extract_calls += 1\n assert {\"entities\": entities, \"fileIds\": file_ids} == jsgz_load(call.request.body)\n else:\n n_status_calls += 1\n assert \"/123\" in call.request.url\n assert 1 == extract_calls\n assert 1 == n_status_calls\n\n def test_run_fails(self, mock_complete, mock_status_failed):\n job = EEAPI.extract([1], [])\n with pytest.raises(ModelFailedException) as exc_info:\n job.result()\n assert \"ContextualizationJob 123 failed with error 'error message'\" == str(exc_info.value)\n","sub_path":"tests/tests_unit/test_contextualization/test_entity_extraction.py","file_name":"test_entity_extraction.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"481266242","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom copy import copy\n\n\ndef show_image(im):\n #image = mpimg.imread(im)\n plt.imshow(im, interpolation='nearest')\n plt.show()\n\n\ndef n_channels(altura, largura, nchannels):\n return nchannels\n\n\ndef size(altura, largura, nchannels):\n return altura, largura\n\n\ndef imreadgray(im):\n image = mpimg.imread(im)\n # Array slicing. A aplicação de uma pseudo cor só é relevante em um único canal,\n # por isso lum_img só recebe um canal. (Tanto faz o qual. R, G ou B)!\n lum_img = image[:, :, 0] \n plt.imshow(lum_img, cmap=\"gray\")\n plt.show()\n\n\ndef rgb2gray(im, altura, largura):\n for row in range(altura):\n for col in range(largura):\n red = im[row][col][0]\n green = im[row][col][1]\n blue = im[row][col][2]\n\n weight_average = (0.299*red + 0.587*green + 0.144*blue)/(0.299 + 0.587 + 0.144)\n im[row][col] = [weight_average]\n lum_img = im[:, :, 0]\n return lum_img\n\n\ndef negative(im, altura, largura):\n for row in range(altura):\n for col in range(largura):\n red = 255 - im[row][col][0]\n green = 255 - im[row][col][1]\n blue = 255 - im[row][col][2]\n im[row][col] = [red, green, blue]\n return im\n\n\n# Organizar Direito a função.\ndef thresh(im, altura, largura, value):\n rgb2gray(im, altura, largura)\n numpy_iterator = np.nditer(im, flags=['multi_index'], op_flags=['writeonly'])\n while not numpy_iterator.finished:\n if numpy_iterator[0] > value:\n numpy_iterator[0] = 255\n else:\n numpy_iterator[0] = 0\n numpy_iterator.iternext()\n return im\n\n\n# Garante que os valores fiquem \"presos\" entre 0 e 255\ndef truncate(value):\n if value < 0:\n value = 0\n elif value > 255:\n value = 255\n return value\n\n\n# 'r' modifica o contraste e 'm' o brilho\ndef contrast(im, r, m):\n shape = im.shape\n altura_largura = size(*shape)\n for row in range(altura_largura[0]):\n for col in range(altura_largura[1]):\n red = im[row][col][0]\n green = im[row][col][1]\n blue = im[row][col][2]\n\n # Fator de correção do contraste\n f = (259*(r + 255)) / (255*(259 - r))\n\n new_red = truncate(f*(red - 128) + 128 + m)\n new_green = truncate(f*(green - 128) + 128 + m)\n new_blue = truncate(f*(blue - 128) + 128 + m)\n\n im[row][col] = [new_red, new_green, new_blue]\n return im\n\n\ndef main():\n path = 'Images/emiliaclarke.jpg'\n #path = 'Images/emilia.png'\n\n # Exibe a imagem em nd.array\n img = mpimg.imread(path)\n print(img)\n tipo_da_imagem = img.dtype\n print(img.dtype)\n\n # Verifica se a imagem está no formato desejado uint8 e a converte caso negativo\n if tipo_da_imagem != 'uint8':\n img = (img * 255).round().astype(np.uint8) \n\n print(img)\n print(img.dtype)\n\n # Converte a imagem en nd.array para uma imagem de fato\n imgplot = plt.imshow(img)\n plt.show(imgplot)\n\n # Mostra a imagem original no console\n # Recebe uma imagem como parametro e a exibe. Só isso.\n # show_image(path)\n\n # Recebe uma imagem como parametro e a retorna em escala de cinza.\n imreadgray(path)\n #show_image(img)\n\n shape = img.shape\n\n # Numero de canais da imagem\n print('O número de canais da imagem é de: {0}'\n .format(n_channels(*shape)))\n\n # Altura e Largura da imagem\n altura_largura = size(*shape)\n print('A altura da imagem é de: {0} e a largura é de: {1}'\n .format(altura_largura[0], altura_largura[1]))\n\n # negative() função ==NEGATIVA DA IMAGEM==\n copy_negative = copy(img)\n negative_image = negative(copy_negative, altura_largura[0], altura_largura[1])\n plt.imshow(copy_negative)\n plt.show()\n\n\n # Rg2toGray() função ==ESCALA DE CINZA DA IMAGEM==\n copy_grey = copy(img)\n grey_image = rgb2gray(copy_grey, altura_largura[0], altura_largura[1])\n plt.imshow(grey_image, cmap=plt.cm.gray)\n plt.show()\n \n\n # thresh() função ==THRESHOLD DA IMAGEM==\n copy_thresh = copy(img)\n thresh_image = thresh(copy_thresh, altura_largura[0], altura_largura[1], 100)\n plt.imshow(copy_thresh, cmap=plt.cm.gray)\n plt.show()\n\n # contrast() função == MODIFICANDO O CONSTRASTE ==\n copy_contrast = copy(img)\n contrast_image = contrast(copy_contrast, -90 , 1)\n plt.imshow(contrast_image, vmin=0, vmax=255)\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"2Questao.py","file_name":"2Questao.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"119515114","text":"#!/usr/bin/env python3\n#! -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom abc import abstractmethod\nfrom scipy import integrate\nfrom scipy.interpolate import splrep, splev, interp1d\nfrom scipy.optimize import root\n\nR = 8.314459\nK = 273.15\n\n\ndef parse_comp(**comp):\n \"\"\"\n Parse a composition dictionary and returns default values if\n values not set\n \"\"\"\n C = comp.pop('C', 0)\n Mn = comp.pop('Mn', 0)\n Si = comp.pop('Si', 0)\n Ni = comp.pop('Ni', 0)\n Cr = comp.pop('Cr', 0)\n Mo = comp.pop('Mo', 0)\n Co = comp.pop('Co', 0)\n return C, Mn, Si, Ni, Cr, Mo, Co\n\n\ndef FahrenheitToCelsius(TF):\n return (TF - 32.)*5./9.\n\n\ndef FC(**comp):\n \"\"\"\n Function that expresses the effects of the alloying elements on\n on the kinetics of ferrite transformation\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return np.exp((1.0 + 6.31*C + 1.78*Mn + 0.31*Si + 1.12*Ni + 2.7*Cr + 4.06*Mo))\n\n\ndef PC(**comp):\n \"\"\"\n Function that expresses the effects of the alloying elements on\n on the kinetics of pearlite transformation\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return np.exp(-4.25 + 4.12*C + 4.36*Mn + 0.44*Si + 1.71*Ni + 3.33*Cr + 5.19*np.sqrt(Mo))\n\n\ndef BC(**comp):\n \"\"\"\n Function that expresses the effects of the alloying elements on\n on the kinetics of bainite transformation\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return np.exp(-10.23 + 10.18*C + 0.85*Mn + 0.55*Ni + 0.9*Cr + 0.36*Mo)\n\n\ndef Ae1_Grange(**comp):\n \"\"\"\n Grange's equation for Ae1\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return FahrenheitToCelsius(1333 - 25*Mn + 40*Si - 26*Ni - 42*Cr)\n\n\ndef Ae3_Grange(**comp):\n \"\"\"\n Grange's equation for Ae3\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return FahrenheitToCelsius(1570 - 323*C - 25*Mn + 80*Si - 32*Ni - 3*Cr)\n\n\ndef Ae1_Andrews(**comp):\n \"\"\"\n Andrews' equation for Ae1\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 712 - 17.8*Mn + 20.1*Si - 19.1*Ni + 11.9*Cr + 9.8*Mo\n\n\ndef Ae3_Andrews(**comp):\n \"\"\"\n Andrews' equation for Ae3\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 871 - 254.4*np.sqrt(C) + 51.7*Si - 14.2*Ni\n\n\ndef Bs_Li(**comp):\n \"\"\"\n Bs calculation from Li's work\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 637 - 58*C - 35*Mn - 15*Ni - 34*Cr - 41*Mo\n\n\ndef Bs_VanBohemen(**comp):\n \"\"\"\n [1] S.M.C. van Bohemen, Mater. Sci. Technol. 28 (2012) 487–495.\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 839 - (86*Mn + 23*Si + 67*Cr + 33*Ni + 75*Mo) - 270*(1 - np.exp(-1.33*C))\n\n\ndef Ms_Andrews(**comp):\n \"\"\"\n Andrews' equation for Ms\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 539 - 423*C - 30.4*Mn - 17.7*Ni - 12.1*Cr - 7.5*Mo + 10*Co - 7.5*Si\n\n\ndef Ms_VanBohemen(**comp):\n \"\"\"\n [1] S.M.C. van Bohemen, Mater. Sci. Technol. 28 (2012) 487–495.\n \"\"\"\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**comp)\n return 565 - (31*Mn + 13*Si + 10*Cr + 18*Ni + 12*Mo) - 600*(1-np.exp(-0.96*C))\n\n\nclass Alloy:\n \"\"\"\n Alloy properties (composition in wt.% and prior austenite grain size)\n \"\"\"\n\n def __init__(self, gs, **w):\n # Grain size\n self.gs = gs\n\n # Alloy composition\n self.w = w\n # Main elements\n self.C, self.Mn, self.Si, self.Ni, self.Cr, self.Mo, self.Co = parse_comp(**w)\n\n self.FC = FC(**w)\n self.PC = PC(**w)\n self.BC = BC(**w)\n # self.Ae3 = Ae3_Andrews(**w)\n # self.Ae1 = Ae1_Andrews(**w)\n self.Ae3 = Ae3_Grange(**w)\n self.Ae1 = Ae1_Grange(**w)\n # self.Ae3 = 970\n # self.Ae1 = 590\n # self.Bs = Bs_Li(**w)\n # self.Ms = Ms_Andrews(**w)\n self.Bs = Bs_VanBohemen(**w)\n self.Ms = Ms_VanBohemen(**w)\n\n def format_composition(self, vmin=0):\n fmt = []\n for k, v in self.w.items():\n if v > vmin:\n fmt.append('{:g}{:}'.format(v, k))\n fmt.insert(0, 'Fe') # assumes it is steel\n return '-'.join(fmt) + ' (wt.%)'\n\n\nclass SigmoidalFunction(object):\n \"\"\"\n Abstract class for S(X) and I(X) functions. Once initialized,\n calculates values of the function for a given [xmin, xmax]\n interval and then creates a spline interpolator. The returned\n values are calculated by the interpolator. This method has the\n advantage of being able to process x as an array (or any other\n kind of iterator)\n \"\"\"\n tck = None # tck spline knots, coefficients and degree\n tck_inv = None # spline parameters of the inverse function\n\n def __new__(cls, x):\n \"\"\"\n __new__ behaviour is modified to return the interpolated\n value of the function\n \"\"\"\n if cls is SigmoidalFunction:\n raise TypeError(\"Can't instantiate abstract class SigmoidalFunction\")\n\n # Check for compulsory subclass attributes\n for var in ['xmin', 'xmax', 'ymin', 'ymax', 'n']:\n if not hasattr(cls, var):\n raise NotImplementedError('Class {} lacks required `{}` class attribute'.format(cls, var))\n\n # This is were S(X) or I(X) is returned\n return cls.val(x)\n\n @staticmethod\n def f(x):\n \"\"\"\n Function to be integrated\n \"\"\"\n pass\n\n @classmethod\n def val(cls, x):\n \"\"\"\n Evaluates SigmoidalFunction(x)\n \"\"\"\n if hasattr(x, '__iter__') and not isinstance(x, str):\n x = np.array(x)\n xmin = x[x > 0].min()\n else:\n xmin = x\n xmin = min(cls.xmin, xmin)\n\n # init spline if not initialized yet or if xmin is lower than lower bound\n if xmin < cls.xmin or cls.tck is None:\n cls.xmin = xmin\n cls.init_spline()\n\n return splev(x, cls.tck)\n\n @classmethod\n def inv(cls, y):\n \"\"\"\n Evaluates inverse function SigmoidalFunction^-1(y)\n \"\"\"\n if hasattr(y, '__iter__') and not isinstance(y, str):\n y = np.array(y)\n ymin, ymax = y.min(), y.max()\n else:\n ymin, ymax = y, y\n\n if cls.tck_inv is None:\n cls.init_spline()\n\n if ymin < cls.ymin or ymax > cls.ymax:\n print('Be careful! y value out of bounds [{:g}:{:g}]. '\n 'Returned value is an extrapolation'.format(cls.ymin, cls.ymax))\n\n return splev(y, cls.tck_inv)\n\n @classmethod\n def init_spline(cls):\n \"\"\"\n Initializes spline\n \"\"\"\n X = np.linspace(cls.xmin, cls.xmax, cls.n)\n Y = np.array([integrate.quad(cls.f, 0, x)[0] for x in X])\n cls.ymin = Y.min()\n cls.ymax = Y.max()\n cls.tck = splrep(X, Y)\n cls.tck_inv = splrep(Y, X)\n\n\nclass S(SigmoidalFunction):\n n = 999\n xmin = 0.001\n xmax = 0.999\n ymin = 0.02638507\n ymax = 2.02537893\n\n \"\"\"\n S(X) function calculated using numerical integration and\n spline interpolation\n \"\"\"\n @staticmethod\n def f(x):\n return 1./(x**(0.4*(1. - x))*(1. - x)**(0.4*x))\n\n\nclass I(SigmoidalFunction):\n \"\"\"\n I(X) function calculated using numerical integration and\n spline interpolation\n \"\"\"\n n = 999\n xmin = 0.001\n xmax = 0.999\n ymin = 0.29961765\n ymax = 4.05928646\n\n @staticmethod\n def f(x):\n return 1./(x**(2.*(1. - x)/3.)*(1. - x)**(2.*x/3.))\n\n\nclass PhaseTransformation(object):\n \"\"\"\n Abstract class for calculating kinetics of diffusional phase\n transformations\n \"\"\"\n\n def __init__(self, alloy):\n self.alloy = alloy\n self.initialize()\n # Check for compulsory object attributes\n for var in ['comp_factor', 'Ts', 'Tf']:\n if not hasattr(self, var):\n raise NotImplementedError('Object {} lacks required `{}` attribute'.format(self, var))\n\n @classmethod\n def __init_subclass__(cls):\n # Check for compulsory subclass attributes\n for var in ['Q', 'n1', 'n2']:\n if not hasattr(cls, var):\n raise NotImplementedError('Class {} lacks required `{}` class attribute'.format(cls, var))\n\n @abstractmethod\n def initialize(self):\n pass\n\n def get_transformation_factor(self, T):\n return self.comp_factor/(2**(self.n1*self.alloy.gs)*(self.Ts - T)**self.n2*np.exp(-self.Q/(R*(T + K))))\n\n def get_transformation_time(self, T, f):\n return S(f)*self.get_transformation_factor(T)\n\n def get_transformation_temperature(self, Tmax, Tmin, cooling_rate, f, dT=1.0):\n \"\"\"\n cooling_rate : iterable\n \"\"\"\n import time\n t0 = time.time()\n dt = dT/np.array(cooling_rate)\n nt = len(dt) if hasattr(dt, '__len__') else 1\n T = np.arange(Tmax, Tmin, -dT)\n nucleation_time = np.full((nt, len(T)), 0, dtype=float)\n\n filtr = T < self.Ts\n nucleation_time[:, filtr] = np.outer(dt, 1./self.get_transformation_factor(T[filtr]))\n nucleation_time = nucleation_time.cumsum(axis=1)\n\n Tt = np.full(nt, np.nan, dtype=float) # Transformation temperature for a given fraction f\n\n # Check for indices of nucleation_time larger than threshold S(f)\n # First occurrence is the transformation temperature\n Sf = S(f)\n for i, n_time in enumerate(nucleation_time):\n idx, = np.where(n_time >= Sf)\n if len(idx) > 0:\n Tt[i] = T[idx[0]]\n\n return float(Tt) if nt == 1 else Tt\n\n def get_transformed_fraction(self, t, T, n=1000):\n \"\"\"\n t, T : iterables\n \"\"\"\n if len(t) > 3:\n # Fits T(t) by spline\n def t2T(t_): return splev(t_, splrep(t, T))\n else:\n # Uses linear interpolator\n t2T = interp1d(t, T)\n\n # To ensure convergence of the algorithm, the T(t) thermal cycle is\n # adjusted by a spline and the nucleation time is calculated by\n # increments dt = (max(t) - min(t))/n\n dt = (max(t) - min(t))/(n - 1)\n t = np.linspace(min(t), max(t), n)\n T = t2T(t)\n nucleation_time = np.full(t.shape, 0, dtype=float)\n f = np.full(T.shape, 0, dtype=float)\n\n # Calculates nucleation time only for T lower than transformation\n # start temperature and higher than Tf\n filtr = (T < self.Ts) & (T > self.Tf)\n if np.any(filtr):\n nucleation_time[filtr] = dt/self.get_transformation_factor(T[filtr])\n nucleation_time = nucleation_time.cumsum()\n if T[0] < self.Ts:\n # This is the factor corresponding to the transformed fraction at t[0]\n nucleation_time += min(t)/self.get_transformation_factor(T[0])\n\n # New filter: calculates f only for nucleation_time inside the bounds\n # of S.inv(y)\n filtr = (nucleation_time >= S.ymin) & (nucleation_time <= S.ymax)\n if np.any(filtr):\n f[filtr] = S.inv(nucleation_time[filtr])\n f[nucleation_time < S.ymin] = 0\n f[nucleation_time > S.ymax] = 1\n\n return t, T, f\n\n\nclass Ferrite(PhaseTransformation):\n \"\"\"\n Austenite to ferrite phase transformation\n \"\"\"\n Q = 27500*4.184 # activation energy\n n1 = 0.41 # exponential factor 1\n n2 = 3 # exponential factor 2\n\n def initialize(self):\n self.comp_factor = self.alloy.FC # composition factor for calculating transformation time\n self.Ts = self.alloy.Ae3 # transformation start temperature\n self.Tf = self.alloy.Bs # transformation finish temperature\n\n\nclass Pearlite(PhaseTransformation):\n \"\"\"\n Austenite to pearlite phase transformation\n \"\"\"\n Q = 27500*4.184 # activation energy\n n1 = 0.32 # exponential factor 1\n n2 = 3 # exponential factor 2\n\n def initialize(self):\n self.comp_factor = self.alloy.PC # composition factor for calculating transformation time\n self.Ts = self.alloy.Ae1 # transformation start temperature\n self.Tf = self.alloy.Bs # transformation finish temperature\n\n\nclass Bainite(PhaseTransformation):\n \"\"\"\n Austenite to bainite phase transformation\n \"\"\"\n Q = 27500*4.184 # activation energy\n n1 = 0.29 # exponential factor 1\n n2 = 2 # exponential factor 2\n\n def initialize(self):\n self.comp_factor = self.alloy.BC # composition factor for calculating transformation time\n self.Ts = self.alloy.Bs # transformation start temperature\n self.Tf = self.alloy.Ms # transformation finish temperature\n\n\nclass Martensite:\n \"\"\"\n Athermal austenite to martensite transformation\n \"\"\"\n\n def __init__(self, alloy):\n self.alloy = alloy\n self.Ts = self.alloy.Ms\n\n C, Mn, Si, Ni, Cr, Mo, Co = parse_comp(**self.alloy.w)\n self.alloy.alpha = 1e-3*(27.2 - (0.14*Mn + 0.21*Si + 0.11*Cr + 0.08*Ni + 0.05*Mo) - 19.8*(1-np.exp(-1.56*C)))\n\n def get_transformed_fraction(self, t, T, n=1000):\n \"\"\"\n t, T : iterables\n Koistinen-Marburger equation\n \"\"\"\n if len(t) > 3:\n # Fits T(t) by spline\n def t2T(t_): return splev(t_, splrep(t, T))\n else:\n # Uses linear interpolator\n t2T = interp1d(t, T)\n\n t = np.linspace(min(t), max(t), n)\n T = t2T(t)\n f = np.full(T.shape, 0, dtype=float)\n\n filtr = T < self.alloy.Ms\n if np.any(filtr):\n f[filtr] = 1 - np.exp(-self.alloy.alpha*(self.alloy.Ms - T[filtr]))\n return t, T, f\n\n\nclass TransformationDiagrams:\n col_label_dict = dict(t='Time (s)', T=u'Temperature (°C)',\n ferrite='Ferrite', pearlite='Pearlite',\n martensite='Martensite', austenite='Austenite')\n\n def __init__(self, alloy):\n self.alloy = alloy\n\n self.ferrite = Ferrite(self.alloy)\n self.pearlite = Pearlite(self.alloy)\n self.bainite = Bainite(self.alloy)\n self.martensite = Martensite(self.alloy)\n\n def get_transformed_fraction(self, t, T, n=1000):\n \"\"\"\n Get transformation curves for a given T(t) thermal cycle\n \"\"\"\n t, T, f_ferr = self.ferrite.get_transformed_fraction(t, T, n)\n t, T, f_pear = self.pearlite.get_transformed_fraction(t, T, n)\n t, T, f_bain = self.bainite.get_transformed_fraction(t, T, n)\n t, T, f_mart = self.martensite.get_transformed_fraction(t, T, n)\n\n f_ferr_inc = np.diff(f_ferr, prepend=0)\n f_pear_inc = np.diff(f_pear, prepend=0)\n f_bain_inc = np.diff(f_bain, prepend=0)\n f_mart_inc = np.diff(f_mart, prepend=0)\n f_ferr_inc[f_ferr < 1] /= (1. - f_ferr[f_ferr < 1])\n f_pear_inc[f_pear < 1] /= (1. - f_pear[f_pear < 1])\n f_bain_inc[f_bain < 1] /= (1. - f_bain[f_bain < 1])\n f_mart_inc[f_mart < 1] /= (1. - f_mart[f_mart < 1])\n f_ferr_inc[f_ferr == 1] = 0\n f_pear_inc[f_pear == 1] = 0\n f_bain_inc[f_bain == 1] = 0\n f_mart_inc[f_mart == 1] = 0\n\n f_corr = pd.DataFrame(columns=['t', 'T', 'ferrite', 'pearlite', 'bainite', 'martensite', 'austenite'])\n f_corr['t'] = t\n f_corr['T'] = T\n f_corr['austenite'] = 1.\n f_corr.fillna(0, inplace=True)\n\n def f1(i, x, y, z, w): return f_corr.loc[i-1, 'ferrite'] + f_ferr_inc[i]*(1 - x - y - z - w) - x\n\n def f2(i, x, y, z, w): return f_corr.loc[i-1, 'pearlite'] + f_pear_inc[i]*(1 - x - y - z - w) - y\n\n def f3(i, x, y, z, w): return f_corr.loc[i-1, 'bainite'] + f_bain_inc[i]*(1 - x - y - z - w) - z\n\n def f4(i, x, y, z, w): return f_corr.loc[i-1, 'martensite'] + f_mart_inc[i]*(1 - x - y - z - w) - w\n\n for i in range(len(f_corr))[1:]:\n x0 = [f_corr.loc[i-1, 'ferrite'], f_corr.loc[i-1, 'pearlite'],\n f_corr.loc[i-1, 'bainite'], f_corr.loc[i-1, 'martensite']]\n\n res = root(lambda x: [f1(i, *x), f2(i, *x), f3(i, *x), f4(i, *x)], x0=x0)\n\n f_corr.loc[i, 'ferrite'] = res.x[0]\n f_corr.loc[i, 'pearlite'] = res.x[1]\n f_corr.loc[i, 'bainite'] = res.x[2]\n f_corr.loc[i, 'martensite'] = res.x[3]\n f_corr.loc[i, 'austenite'] = 1. - res.x.sum()\n\n return f_corr\n\n def draw_thermal_cycle(self, t, T, n=100, ax=None, **kwargs):\n \"\"\"\n Draw thermal cycle (cooling curve) over AxesSubplot object\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n if len(t) > 3:\n # Fits T(t) by spline\n def t2T(t_): return splev(t_, splrep(t, T))\n else:\n # Uses linear interpolator\n t2T = interp1d(t, T)\n\n t = np.linspace(min(t), max(t), n)\n T = t2T(t)\n\n kw = dict(color='k', ls='--')\n kw.update(kwargs)\n\n return ax.plot(t, T, **kw)\n\n def TTT(self, fs=1e-2, ff=.99, ax=None, **kwargs):\n \"\"\"\n Plot TTT diagram\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=(6, 6))\n else:\n fig = ax.get_figure()\n\n color_cycle = ax._get_lines.prop_cycler\n\n # Ferrite\n T = np.arange(self.alloy.Bs, self.alloy.Ae3)\n ts = self.ferrite.get_transformation_time(T, fs) # start\n tf = self.ferrite.get_transformation_time(T, ff) # finish\n line_ferr, = ax.plot(ts, T, label='Ferrite {:g}%'.format(100*fs), **kwargs)\n ax.plot(tf, T, color=line_ferr.get_color(), ls='--', label='Ferrite {:g}%'.format(100*ff), **kwargs)\n\n # Pearlite\n T = np.arange(self.alloy.Bs, self.alloy.Ae1)\n ts = self.pearlite.get_transformation_time(T, fs)\n tf = self.pearlite.get_transformation_time(T, ff)\n line_pear, = ax.plot(ts, T, label='Pearlite {:g}%'.format(100*fs), **kwargs)\n ax.plot(tf, T, color=line_pear.get_color(), ls='--', label='Pearlite {:g}%'.format(100*ff), **kwargs)\n\n # Bainite\n T = np.arange(self.alloy.Ms, self.alloy.Bs)\n ts = self.bainite.get_transformation_time(T, fs)\n tf = self.bainite.get_transformation_time(T, ff)\n line_bain, = ax.plot(ts, T, label='Bainite {:g}%'.format(100*fs), **kwargs)\n ax.plot(tf, T, color=line_bain.get_color(), ls='--', label='Bainite {:g}%'.format(100*ff), **kwargs)\n\n ax.axhline(self.alloy.Bs, color=line_bain.get_color(), ls=':', label='Bs')\n ax.axhline(self.alloy.Ms, color=next(color_cycle)['color'], label='Ms')\n\n ax.set_xscale('log')\n ax.set_ylim(25)\n ax.set_xlabel('Time (s)')\n ax.set_ylabel(u'Temperature (°C)')\n ax.set_title(self.alloy.format_composition())\n ax.legend(loc='upper center', ncol=4, bbox_to_anchor=(0.5, -.15))\n fig.tight_layout()\n\n return ax\n\n def CCT(self, Tini=900, fs=1e-2, ff=.99, cooling_rates=10**np.linspace(-4, 4, 320), ax=None, **kwargs):\n \"\"\"\n Plot CCT diagram\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=(6, 6))\n else:\n fig = ax.get_figure()\n\n color_cycle = ax._get_lines.prop_cycler\n cooling_rates = np.array(cooling_rates)\n draw_cooling = kwargs.pop('draw_cooling', True)\n\n # Ferrite\n Ts = self.ferrite.get_transformation_temperature(Tini, self.alloy.Bs, cooling_rates, fs) # start\n Tf = self.ferrite.get_transformation_temperature(Tini, self.alloy.Bs, cooling_rates, ff) # finish\n line_ferr, = ax.plot(Ts/cooling_rates, Ts, label='Ferrite {:g}%'.format(100*fs), **kwargs)\n ax.plot(Tf/cooling_rates, Tf, color=line_ferr.get_color(),\n ls='--', label='Ferrite {:g}%'.format(100*ff), **kwargs)\n\n # Pearlite\n Ts = self.pearlite.get_transformation_temperature(Tini, self.alloy.Bs, cooling_rates, fs)\n Tf = self.pearlite.get_transformation_temperature(Tini, self.alloy.Bs, cooling_rates, ff)\n line_pear, = ax.plot(Ts/cooling_rates, Ts, label='Pearlite {:g}%'.format(100*fs), **kwargs)\n ax.plot(Tf/cooling_rates, Tf, color=line_pear.get_color(),\n ls='--', label='Pearlite {:g}%'.format(100*ff), **kwargs)\n\n # Bainite\n Ts = self.bainite.get_transformation_temperature(Tini, self.alloy.Ms, cooling_rates, fs)\n Tf = self.bainite.get_transformation_temperature(Tini, self.alloy.Ms, cooling_rates, ff)\n line_bain, = ax.plot(Ts/cooling_rates, Ts, label='Bainite {:g}%'.format(100*fs), **kwargs)\n ax.plot(Tf/cooling_rates, Tf, color=line_bain.get_color(),\n ls='--', label='Bainite {:g}%'.format(100*ff), **kwargs)\n\n ax.axhline(self.alloy.Bs, color=line_bain.get_color(), ls=':', label='Bs')\n ax.axhline(self.alloy.Ms, color=next(color_cycle)['color'], label='Ms')\n\n # Draw cooling curves\n if draw_cooling:\n for cooling_rate in cooling_rates[::10]:\n T = np.linspace(Tini, 25, 100)\n t = (Tini - T)/cooling_rate\n kw = dict(lw=.5)\n kw.update(kwargs)\n ax.plot(t, T, 'k:', **kw)\n\n ax.set_xscale('log')\n ax.set_ylim(25)\n ax.set_xlabel('Time (s)')\n ax.set_ylabel(u'Temperature (°C)')\n ax.set_title(self.alloy.format_composition())\n ax.legend(loc='upper center', ncol=4, bbox_to_anchor=(0.5, -.15))\n fig.tight_layout()\n\n return ax\n\n def plot_phase_fraction(self, t, T, n=1000, xaxis='t', ax=None, **kwargs):\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n if len(t) > 3:\n # Fits T(t) by spline\n def t2T(t_): return splev(t_, splrep(t, T))\n else:\n # Uses linear interpolator\n t2T = interp1d(t, T)\n\n t = np.linspace(min(t), max(t), n)\n T = t2T(t)\n\n f = self.get_transformed_fraction(t, T, n)\n ax.plot(f[xaxis], f['ferrite'], label='Ferrite')\n ax.plot(f[xaxis], f['pearlite'], label='Pearlite')\n ax.plot(f[xaxis], f['bainite'], label='Bainite')\n ax.plot(f[xaxis], f['martensite'], label='Martensite')\n ax.plot(f[xaxis], f['austenite'], label='Austenite')\n\n ax.set_xlabel(self.col_label_dict[xaxis])\n ax.set_ylabel('Phase fraction')\n ax.legend()\n\n return ax\n\n\nif __name__ == '__main__':\n # Defines alloy (grain size gs and composition)\n alloy = Alloy(gs=7, C=0.37, Mn=0.77, Si=0.15, Ni=0.04, Cr=0.98, Mo=0.21)\n\n # Initializes diagrams object\n diagrams = TransformationDiagrams(alloy)\n\n # Example 1: Plot TTT and CCT diagrams\n\n fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\n fig1.subplots_adjust(wspace=.2)\n\n diagrams.TTT(ax=ax1)\n ax1.set_xlim(1e-2, 1e8)\n ax1.set_ylim(300, 1000)\n\n diagrams.CCT(ax=ax2)\n ax2.set_xlim(1e-2, 1e8)\n ax2.set_ylim(300, 1000)\n\n fig1.suptitle(ax1.get_title())\n ax1.set_title('')\n ax2.set_title('')\n\n # Example 2: Plot CCT diagram and transformed fraction\n\n fig2, (ax3, ax4) = plt.subplots(1, 2, figsize=(12, 6))\n fig2.subplots_adjust(wspace=.2)\n\n # Plot CCT diagram\n diagrams.CCT(Tini=1000, ax=ax3)\n\n # Chooses a thermal cycle (continuous cooling from 1000 to 0 oC in\n # 2000 s), draws cooling curve in the CCT and plots phase fraction\n t, T = [0, 2000], [1000, 0]\n # t, T = [0, 10000], [700, 700]\n diagrams.draw_thermal_cycle(t, T, ax=ax3)\n diagrams.plot_phase_fraction(t, T, xaxis='T', ax=ax4)\n\n fig2.suptitle(ax3.get_title())\n ax3.set_title('')\n ax4.set_title('')\n\n plt.show()\n","sub_path":"transformation_models.py","file_name":"transformation_models.py","file_ext":"py","file_size_in_byte":23620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"354029560","text":"import torch\nfrom torchsummary import summary\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\ndef imshow(img):\n\timg = denormalize(img)\n\tnpimg = img.numpy()\n\tplt.imshow(np.transpose(npimg, (1, 2, 0)))\n\ndef normalize(tensor, mean=[0.4914, 0.4822, 0.4465],\n\t\t\t\t\t\tstd=[0.2023, 0.1994, 0.2010]):\n\tsingle_img = False\n\tif tensor.ndimension() == 3:\n\t\tsingle_img = True\n\t\ttensor = tensor[None,:,:,:]\n\n\tif not tensor.ndimension() == 4:\n\t raise TypeError('tensor should be 4D')\n\n\tmean = torch.FloatTensor(mean).view(1, 3, 1, 1).expand_as(tensor).to(tensor.device)\n\tstd = torch.FloatTensor(std).view(1, 3, 1, 1).expand_as(tensor).to(tensor.device)\n\tret = tensor.sub(mean).div(std)\n\treturn ret[0] if single_img else ret\n\ndef denormalize(tensor, mean=[0.4914, 0.4822, 0.4465],\n\t\t\t\t\t\tstd=[0.2023, 0.1994, 0.2010]):\n\tsingle_img = False\n\tif tensor.ndimension() == 3:\n\t\tsingle_img = True\n\t\ttensor = tensor[None,:,:,:]\n\n\tif not tensor.ndimension() == 4:\n\t raise TypeError('tensor should be 4D')\n\n\tmean = torch.FloatTensor(mean).view(1, 3, 1, 1).expand_as(tensor).to(tensor.device)\n\tstd = torch.FloatTensor(std).view(1, 3, 1, 1).expand_as(tensor).to(tensor.device)\n\tret = tensor.mul(std).add(mean)\n\treturn ret[0] if single_img else ret\n\ndef plot_images(img_data,classes,img_name):\n figure = plt.figure(figsize=(10, 10))\n \n num_of_images = len(img_data)\n print(num_of_images)\n for index in range(1, num_of_images + 1):\n img = denormalize(img_data[index-1][0]) # unnormalize\n plt.subplot(5, 5, index)\n plt.axis('off')\n plt.imshow(np.transpose(img.cpu().numpy(), (1, 2, 0)))\n plt.title(\"Actual: %s\\nPredicted: %s\" % (classes[img_data[index-1][1]], classes[img_data[index-1][2]]))\n \n plt.tight_layout()\n plt.savefig(img_name)\n\n\ndef print_triangular_lr(iteration, stepsize, base_lr, max_lr):\n cycle = np.floor(1 + iteration/(2 * stepsize))\n x = np.abs(iteration/stepsize - 2 * cycle + 1)\n lr = base_lr + (max_lr - base_lr) * np.maximum(0, (1-x))\n return lr\n\n ","sub_path":"S11/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"197172392","text":"import logging\nimport re\nfrom datetime import datetime\n\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.renderers import render as render_template, render_to_response\nfrom sqlalchemy import func\nfrom sqlalchemy.sql.expression import or_\n\nfrom alchemist.helpers.emails import send_mail\nfrom alchemist.helpers.misc import gen_ver_code\nfrom alchemist.models import User, Connection, BaseCompany\nfrom alchemist.models.base import DBSession\nfrom alchemist.system.route import route\n\n\n@route(path='/connect/render/{to_id}', permission='connect', renderer='connect_me/connect_me_modal.jinja2')\ndef connect_me_ajax(request):\n conn = None\n existing_connection = request.params.get('conn_id')\n if existing_connection:\n conn = DBSession.query(Connection).get(int(existing_connection))\n # type = request.matchdict.get('type')\n # if not type and conn and conn.user.primary_type:\n # type = conn.user.primary_type\n return {'to': conn.user if conn else User.bid(request.matchdict.get('to_id')),\n 'from': conn.by_user if conn else request.user,\n 'conn': conn,\n 'message': conn.message if conn else ''}\n\n\n@route(path='/connect/render/meeting_request/{to_id}', permission='connect', renderer='mentoring/request_meeting_modal.jinja2')\ndef request_meeting_ajax(request):\n conn = None\n existing_connection = request.params.get('conn_id')\n if existing_connection:\n conn = DBSession.query(Connection).get(int(existing_connection))\n\n by_user = conn.by_user if conn else request.user\n to = conn.user if conn else User.bid(request.matchdict.get('to_id'))\n if not existing_connection:\n conn_data = {'by_user_cust_name': by_user.nicename,\n 'by_user_cust_email': by_user.email,\n 'by_user_cust_linkedin': by_user.linkedin_profile,\n 'by_user_cust_co_name': by_user.company.name if by_user.company else '',\n 'by_user_cust_co_website': by_user.company.website if by_user.company else '',\n 'by_user_cust_co_desc': by_user.company.description if by_user.company else '',\n 'by_user_cust_co_teamdesc': by_user.company.startup_teamdescription if by_user.company else '',\n 'type': 'RM'\n }\n else:\n conn_data = {}\n conn = create_or_update_conn(by_user.id, existing_connection, to.id, **conn_data)\n message = conn.message if conn and conn.message else ''\n deleteonclose = 'connect/list' not in request.referrer\n return {'to': to,\n 'from': by_user,\n 'conn': conn,\n 'deleteonclose': deleteonclose,\n 'message': message}\n\n\n@route(path='/connect/render/t/company/{to_id}', permission='connect', renderer='company/connect_company_modal.jinja2')\ndef connect_company_ajax(request):\n conn = None\n existing_connection = request.params.get('conn_id')\n if existing_connection:\n conn = DBSession.query(Connection).get(int(existing_connection))\n\n if conn:\n company = conn.company\n else:\n company = DBSession.query(BaseCompany).get(request.matchdict.get('to_id'))\n main_poc = find_poc(company, request)\n return {'to': company,\n 'main_poc': main_poc[0],\n 'conn': conn,\n 'by_user': conn.by_user if conn else request.user,\n 'message': conn.message if conn else ''}\n\n\ndef find_poc(company, request):\n poc_id = request.params.get('poc_id')\n main_poc = False\n if poc_id:\n try:\n main_poc = [DBSession.query(User).get(int(poc_id))]\n except:\n pass\n if not main_poc:\n main_poc = [u for u in company.employees if u.email and u.point_of_contact]\n if not main_poc:\n main_poc = [company.employees[0]]\n return main_poc\n\n\n@route(path='/connect/save', permission='connect')\ndef save(request):\n existing_id = request.params.get('conn_id')\n message = request.params.get('message')\n by_user = request.user.id\n to_id = request.params.get('to')\n conn = create_or_update_conn(by_user, existing_id, to_id, message=message)\n uri = request.referer or '/connections'\n uri = re.sub('(\\?|&)message_saved=.+', '', uri)\n conn_type = 'request_meeting' if conn.type == 'RM' else 'connect_me'\n return HTTPFound('%s%smessage_saved=%s' % (uri, '&' if '?' in uri else '?', conn_type))\n\n\ndef create_conn(by_user_id, to_id):\n try:\n conn = Connection(by_user_id=by_user_id, user_id=to_id)\n except:\n logging.error('Please specify by_user_id and to_id fields', exc_info=1)\n return\n DBSession.add(conn)\n DBSession.flush()\n _, conn.code = gen_ver_code(conn.id, 14)\n return conn\n\n\ndef update_conn(conn, **kwargs):\n for field, value in kwargs.iteritems():\n if hasattr(conn, field):\n setattr(conn, field, value)\n\n\ndef create_or_update_conn(by_user, existing_id, to_id, **kwargs):\n if existing_id:\n conn = DBSession.query(Connection).get(int(existing_id))\n if conn and not conn.created_at:\n kwargs['created_at'] = datetime.now()\n else:\n kwargs['created_at'] = datetime.now()\n conn = create_conn(by_user, to_id)\n if not conn.sent_at:\n update_conn(conn, **kwargs)\n return conn\n\n\ndef check_quota(user):\n count = DBSession.query(func.count(Connection.id)).filter(Connection.by_user == user,\n Connection.sent_at != None,\n or_(Connection.type == 'CM',\n Connection.type == None)).scalar()\n assert user.connect_me_quota >= count, \\\n 'Your connect me messages quota is full, use the help icon in bottom right corner or email vault@alchemistaccelerator.com'\n return count\n\n\n@route(path='/connect/send', permission='connect')\ndef send(request):\n message = request.params.get('message')\n conn_data = {\n 'message': message\n }\n if request.params.get('type'):\n conn_data['type'] = request.params.get('type')\n conn = create_or_update_conn(request.user.id, request.params.get('conn_id'), request.params.get('to'), **conn_data)\n to = User.bid(int(request.params.get('to')))\n subject_type = request.params.get('subject_type', '')\n if subject_type != 'mentor':\n count_left = check_quota(request.user) - 1\n if count_left in (10, 5, 2, 0):\n request.user.notificate('%s messages left in quota' % count_left)\n\n message = prep_message(message)\n data = {'to': to, 'from': request.user, 'message': message, 'hash': conn.code}\n conn.sent_at = datetime.now()\n if subject_type == 'mentor' or subject_type == 'faculty':\n data['conn'] = conn\n request.session.flash(render_template('/messaging/mentoring/success_requestmentoring.jinja2', {}, request),\n 'popup')\n to.send_mail('mentoring_request', request, data)\n return HTTPFound(request.referer or '/mentors')\n else:\n data['cname'] = (' of %s' % request.user.company.name) if request.user.company else ''\n if request.params.get('send_copy'):\n data_copy = data.copy()\n data_copy['hash'] = 'dummy'\n request.user.send_mail('connect_request', request, data_copy)\n request.session.flash(render_template('/messaging/connect_me/success_connectme.jinja2', {}, request), 'popup')\n to.send_mail('connect_request', request, data)\n return HTTPFound(request.referer or '/connections')\n\n\ndef prep_message(message):\n return \"
    \".join(message.split(\"\\n\")).replace('\\r', '') \\\n if message is not None else None\n\n\n@route(path='/connect/send_company', permission='connect')\ndef send_company(request):\n cid = int(request.params.get('to'))\n data = {'company_id': cid,\n 'message': request.params.get('message')}\n conn = create_or_update_conn(request.user.id, None, None, **data)\n DBSession.flush()\n main_poc = find_poc(conn.company, request)\n poc_emails = [main_poc[0].email]\n if not request.params.get('poc_id'):\n poc_emails = [u.email for u in conn.company.employees if u.point_of_contact and u.email]\n conn.user = main_poc[0]\n send_mail(poc_emails, 'company_connect_request', request, {'main_poc': main_poc[0],\n 'conn': conn,\n 'hash': conn.code,\n 'message': prep_message(conn.message)})\n request.session.flash(render_template('/messaging/company/success_requestcompany.jinja2', {}, request), 'popup')\n return HTTPFound(request.referer or '/alchemist_startups')\n\n\n@route(path='/connect/accept/{code}', renderer='/messaging/success_accept.jinja2')\ndef accept(request):\n code = request.matchdict.get('code')\n if code == 'dummy':\n return {}\n conn = DBSession.query(Connection).filter(Connection.code == code).first()\n template = 'mentoring_request_intro' if conn.user.primary_type == 'mentor' or conn.user.primary_type == 'faculty' \\\n else 'connect_intro'\n if conn.by_user.primary_type == 'customer' and conn.company:\n template = 'company_connect_intro'\n if not conn.accepted:\n message = prep_message(conn.message)\n send_mail([conn.user.email, conn.by_user.email], template, request,\n {'to': conn.user, 'from': conn.by_user, 'message': message, 'conn': conn})\n conn.accepted = True\n conn.accept_at = datetime.now()\n return {}\n","sub_path":"alchemist/messaging/connect_me.py","file_name":"connect_me.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"272954960","text":"import pygame as pg\n# import tkinter as tk\nimport sys\nsys.path.insert(1,'C:\\\\Users\\\\karim\\\\OneDrive\\\\Documents\\\\Code\\\\PYTHON\\\\trans-auto')\n\nfrom components.IconButton import IconButton\nfrom components.SubmitButton import SubmitButton\nfrom components.Label import Label\n\n\nfrom FRAMES.MENU.AddCardWin import AddCardWin\nfrom FRAMES.MENU.RemoveCardWin import RemoveCardWin\nfrom FRAMES.MENU.AddLinkWin import AddLinkWin\nfrom FRAMES.MENU.RemoveLinkWin import RemoveLinkWin\n\nclass Maps :\n def __init__(self,screen,x,y,w,h,updateFunc,connectionToDatabase):\n self.State ={\n 'AC':False,\n 'RC':False,\n 'AL':False,\n 'RL':False,\n }\n self.redColor = '#C72026'\n self.grayColor = '#1D1D1D'\n\n self.screen = screen\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n \n self.frame = pg.Rect(x, y, w, h)\n\n\n self.fontH2 = pg.font.Font(None, 50)\n self.fontH3 = pg.font.Font(None, 30)\n self.fontP = pg.font.Font(None, 20)\n\n\n self.Title = Label(60,20,self.fontH3,text='Customize Map',textColor=pg.Color(self.grayColor))\n \n self.LinksLabel = Label(60,50,self.fontH3,text='Links :',textColor=pg.Color(self.redColor))\n self.AddLink = SubmitButton(60,80,200,30,self.fontP,border_radius=5,border_thikness=0,textColor=self.redColor,bgColor=self.grayColor,text='Add Link')\n self.RemoveLink = SubmitButton(60,120,200,30,self.fontP,border_radius=5,border_thikness=0,textColor=self.redColor,bgColor=self.grayColor,text='Remove Link')\n \n self.CardsLabel = Label(60,200,self.fontH3,text='Cards :',textColor=pg.Color(self.redColor))\n self.AddCard = SubmitButton(60,230,200,30,self.fontP,border_radius=5,border_thikness=0,textColor=self.redColor,bgColor=self.grayColor,text='Add Card')\n self.RemoveCard = SubmitButton(60,270,200,30,self.fontP,border_radius=5,border_thikness=0,textColor=self.redColor,bgColor=self.grayColor,text='Remove Card')\n \n\n #! windows tkinter\n \n\n self.AC = AddCardWin(self.screen,self.State,x,y,w,h,updateFunc,connectionToDatabase) \n self.RC = RemoveCardWin(self.screen,self.State,x,y,w,h,updateFunc,connectionToDatabase) \n self.AL = AddLinkWin(self.screen,self.State,x,y,w,h,updateFunc,connectionToDatabase) \n self.RL = RemoveLinkWin(self.screen,self.State,x,y,w,h,updateFunc,connectionToDatabase) \n \n\n def ACButtonsFunc(self):\n self.State ={\n 'AC':True,\n 'RC':False,\n 'AL':False,\n 'RL':False,\n }\n def RCButtonsFunc(self):\n self.State ={\n 'AC':False,\n 'RC':True,\n 'AL':False,\n 'RL':False,\n }\n def ALButtonsFunc(self):\n self.State ={\n 'AC':False,\n 'RC':False,\n 'AL':True,\n 'RL':False,\n }\n def RLButtonsFunc(self):\n self.State ={\n 'AC':False,\n 'RC':False,\n 'AL':False,\n 'RL':True,\n }\n \n\n def draw(self):\n pg.draw.rect(self.screen, \"#DDDDDD\", self.frame,\n 0, 0)\n\n self.Title.draw(self.screen)\n\n self.LinksLabel.draw(self.screen)\n self.AddLink.draw(self.screen)\n self.RemoveLink.draw(self.screen)\n \n self.CardsLabel.draw(self.screen)\n self.AddCard.draw(self.screen)\n self.RemoveCard.draw(self.screen)\n\n if self.State['AC'] :\n self.AC.draw()\n if self.State['RC'] :\n self.RC.draw()\n if self.State['AL'] :\n self.AL.draw()\n if self.State['RL'] :\n self.RL.draw()\n\n def handleEvent(self,event):\n if event.type == pg.MOUSEBUTTONDOWN:\n if not self.frame.collidepoint(event.pos):\n self.State = {\n 'AC':False,\n 'RC':False,\n 'AL':False,\n 'RL':False,\n }\n\n if self.State['AC'] :\n self.AC.handleEvent(event)\n return\n if self.State['RC'] :\n self.RC.handleEvent(event)\n return\n if self.State['AL'] :\n self.AL.handleEvent(event)\n return\n if self.State['RL'] :\n self.RL.handleEvent(event)\n return\n \n self.AddCard.handleEvent(event,self.ACButtonsFunc ,True)\n self.RemoveCard.handleEvent(event,self.RCButtonsFunc ,True)\n \n self.AddLink.handleEvent(event,self.ALButtonsFunc ,True)\n self.RemoveLink.handleEvent(event,self.RLButtonsFunc ,True)","sub_path":"FRAMES/MENU/Maps.py","file_name":"Maps.py","file_ext":"py","file_size_in_byte":4730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"352287946","text":"from pathlib import Path\n\nimport xgboost\n\n\ntraining_columns_options = {\n \"2020-10-12_16:16:25_55\": [\n \"mH\", \"mHRecoil\", \"cosTZ\",\n \"nChargedHadrons\", \"nNeutralHadrons\", \"nGamma\", \"nElectrons\", \"nMuons\",\n \"principleThrustZ\", \"principleThrust\", \"majorThrust\", \"minorThrust\",\n \"sphericity\", \"aplanarity\",\n \"cosTIsoLep\", \"eHighestIsoLep\", \"nIsoLeptons\",\n ],\n \"2020-10-25_23:16:24_46\": [\n \"mH\",\n \"nChargedHadrons\", \"nNeutralHadrons\", \"nGamma\", \"nElectrons\", \"nMuons\",\n \"nIsoLeptons\",\n\n ]\n}\n\n\ndef getXGBModel(\n model_location=Path(__file__).parent / \"data/best_booster.bin\", \n training_columns=training_columns_options[\"2020-10-25_23:16:24_46\"],\n):\n model = xgboost.XGBClassifier()\n # If an error occurs when loading the model, make sure the xgboost version\n # used for building is the same one that is used here.\n model.load_model(model_location)\n\n # Column names must be adapted for the non-invisible Z decay samples.\n nuToEl = dict(mVis=\"mH\", mMiss=\"mHRecoil\", cosTMiss=\"cosTH\")\n training_columns = list(training_columns) # Avoid overwriting the input.\n for i in range(len(training_columns)):\n if training_columns[i] in nuToEl:\n training_columns[i] = nuToEl[training_columns[i]]\n return model, training_columns\n","sub_path":"higgs_only_model.py","file_name":"higgs_only_model.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"401863518","text":"import os\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport pandas as pd\nimport zigzag\nfrom matplotlib.finance import candlestick2_ohlc\n\nfpath = os.path.dirname(os.path.abspath(__file__))\nfpath += '/data/ingest_data/'\nload_file_name = 'binance_btc_usdt_4h_sm.csv'\nwrite_up_down_file_name = 'up_down_binance_btc_usdt_4h.csv'\nchart_data = pd.read_csv(fpath + load_file_name, thousands=',', header=None)\nchart_data.columns = ['date', 'open', 'high', 'low', 'close', 'volume']\n\n# chart_data['date'] = pd.to_datetime(chart_data['date'])\n# chart_data = chart_data[(chart_data['date'] >= '2018-09-01') & (chart_data['date'] <= '2018-09-17')]\n\nhigh_low = []\ntrend = 0\n\nopen_a = chart_data.open.values\nclose_a = chart_data.close.values\nlow_a = chart_data.low.values\nhigh_a = chart_data.high.values\n\nfor i in range(len(chart_data.date)):\n open = open_a[i]\n close = close_a[i]\n low = low_a[i]\n high = high_a[i]\n ohlcv4 = open + high + low + close / 4\n if i == 0:\n high_low.append(high if open < close else low)\n continue\n\n p_open = open_a[i - 1]\n p_close = close_a[i - 1]\n p_low = low_a[i - 1]\n p_high = high_a[i - 1]\n p_ohlcv4 = p_open + p_high + p_low + p_close / 4\n\n if p_ohlcv4 < ohlcv4:\n high_low.append(high)\n else:\n high_low.append(low)\n\nX = np.array(high_low)\npivots = zigzag.peak_valley_pivots(X, 0.03, -0.03)\n\"\"\"\n위 변곡점: 1\n아래 변곡점: -1\n나머지: 0\n\"\"\"\nactions = []\naction = None\nfor pivot in pivots:\n if pivot == 1:\n action = 'D'\n elif pivot == -1:\n action = 'U'\n\n actions.append(action)\n\nchart_data['actions'] = np.array(actions)\nchart_data.to_csv(fpath + write_up_down_file_name, mode='w', index=False, header=False)\nprint('저장 완료.')\n\ndef ohlcv_plot(data):\n fig, ax = plt.subplots()\n date = data.date.values\n open = data.open.values\n high = data.high.values\n low = data.low.values\n close = data.close.values\n volume = data.volume.values\n candlestick2_ohlc(ax, open, high, low, close, width=0.6)\n ax.xaxis.set_major_locator(ticker.MaxNLocator(10))\n def mydate(x, pos):\n try:\n return pd.to_datetime(date[int(x)]).strftime('%Y.%m.%d %H:%M')\n except IndexError:\n return ''\n ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))\n fig.autofmt_xdate()\n fig.tight_layout()\n\n\ndef plot_pivots(X, pivots):\n # plt.xlim(0, len(X))\n # plt.ylim(X.min()*0.99, X.max()*1.01)\n # # plt.plot(np.arange(len(X)), X, 'k:', alpha=0.5)\n plt.plot(np.arange(len(X))[pivots != 0], X[pivots != 0], 'k-')\n plt.scatter(np.arange(len(X))[pivots == 1], X[pivots == 1], color='g')\n plt.scatter(np.arange(len(X))[pivots == -1], X[pivots == -1], color='r')\n\n\nohlcv_plot(chart_data)\nplot_pivots(X, pivots)\nplt.show()\n\n","sub_path":"data_zigzag.py","file_name":"data_zigzag.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"87659676","text":"# -*- coding: utf-8 -*-\nimport os\nimport errno\nimport sys\nimport time\nimport json\nfrom invoke import task, run\nimport boto3\nimport contextlib\nimport shutil\n# from botocore.errorfactory import ExecutionAlreadyExists\nfrom core.ec2_utils import AWS_S3_ROLE_NAME\nfrom core.utils import create_jobid\nfrom core.utils import AWS_REGION, AWS_ACCOUNT_NUMBER\nfrom core.utils import TIBANNA_DEFAULT_STEP_FUNCTION_NAME, STEP_FUNCTION_ARN\nfrom core.utils import run_workflow as _run_workflow\nfrom core.utils import create_stepfunction as _create_stepfunction\nfrom core.utils import _tibanna\nfrom core.launch_utils import rerun as _rerun\nfrom core.launch_utils import rerun_many as _rerun_many\nfrom core.utils import kill as _kill\nfrom core.utils import log as _log\nfrom core.utils import kill_all as _kill_all\nfrom core.iam_utils import create_tibanna_iam\nfrom core.iam_utils import get_ec2_role_name, get_lambda_role_name\nfrom contextlib import contextmanager\nimport aws_lambda\nimport requests\nimport random\n\nROOT_DIR = os.path.abspath(os.path.dirname(__file__))\nPOSITIVE = 'https://gist.github.com/j1z0/bbed486d85fb4d64825065afbfb2e98f/raw/positive.txt'\nNEGATIVE = 'https://gist.github.com/j1z0/bbed486d85fb4d64825065afbfb2e98f/raw/negative.txt'\nAMI_ID_CWL_V1 = 'ami-0f06a8358d41c4b9c'\nAMI_ID_CWL_DRAFT3 = 'ami-0f06a8358d41c4b9c'\nAMI_ID_WDL = 'ami-0f06a8358d41c4b9c'\nTIBANNA_REPO_NAME = os.environ.get('TIBANNA_REPO_NAME', '4dn-dcic/tibanna')\nTIBANNA_REPO_BRANCH = os.environ.get('TIBANNA_REPO_BRANCH', 'master')\nTIBANNA_PROFILE_ACCESS_KEY = os.environ.get('TIBANNA_PROFILE_ACCESS_KEY', '')\nTIBANNA_PROFILE_SECRET_KEY = os.environ.get('TIBANNA_PROFILE_SECRET_KEY', '')\nUNICORN_LAMBDAS = ['run_task_awsem', 'check_task_awsem']\n\n\ndef get_random_line_in_gist(url):\n listing = requests.get(url)\n return random.choice(listing.text.split(\"\\n\"))\n\n\ndef play(ctx, positive=False):\n type_url = POSITIVE if positive else NEGATIVE\n # no spaces in url\n media_url = '%20'.join(get_random_line_in_gist(type_url).split())\n run(\"vlc -I rc %s --play-and-exit -q\" % (media_url))\n\n\n@contextmanager\ndef setenv(**kwargs):\n # Backup\n prev = {}\n for k, v in kwargs.items():\n if k in os.environ:\n prev[k] = os.environ[k]\n os.environ[k] = v\n\n yield\n\n # Restore\n for k in kwargs.keys():\n if k in prev:\n os.environ[k] = prev[k]\n else:\n del os.environ[k]\n\n\ndef get_all_core_lambdas():\n return [\n 'validate_md5_s3_trigger',\n 'validate_md5_s3_initiator',\n 'start_run_awsem',\n 'run_task_awsem',\n 'check_task_awsem',\n 'update_ffmeta_awsem',\n 'run_workflow',\n ]\n\n\ndef env_list(name):\n # don't set this as a global, since not all tasks require it\n secret = os.environ.get(\"SECRET\", '')\n envlist = {\n 'run_workflow': {'SECRET': secret,\n 'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER},\n 'start_run_awsem': {'SECRET': secret,\n 'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER},\n 'run_task_awsem': {'AMI_ID_CWL_V1': AMI_ID_CWL_V1,\n 'AMI_ID_CWL_DRAFT3': AMI_ID_CWL_DRAFT3,\n 'AMI_ID_WDL': AMI_ID_WDL,\n 'TIBANNA_REPO_NAME': TIBANNA_REPO_NAME,\n 'TIBANNA_REPO_BRANCH': TIBANNA_REPO_BRANCH,\n 'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER,\n 'AWS_S3_ROLE_NAME': AWS_S3_ROLE_NAME},\n 'check_task_awsem': {'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER},\n 'update_ffmeta_awsem': {'SECRET': secret,\n 'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER},\n 'validate_md5_s3_initiator': {'SECRET': secret,\n 'TIBANNA_AWS_REGION': AWS_REGION,\n 'AWS_ACCOUNT_NUMBER': AWS_ACCOUNT_NUMBER}\n }\n if TIBANNA_PROFILE_ACCESS_KEY and TIBANNA_PROFILE_SECRET_KEY:\n envlist['run_task_awsem'].update({\n 'TIBANNA_PROFILE_ACCESS_KEY': TIBANNA_PROFILE_ACCESS_KEY,\n 'TIBANNA_PROFILE_SECRET_KEY': TIBANNA_PROFILE_SECRET_KEY}\n )\n return envlist.get(name, '')\n\n\n@contextlib.contextmanager\ndef chdir(dirname=None):\n curdir = os.getcwd()\n try:\n if dirname is not None:\n os.chdir(dirname)\n yield\n finally:\n os.chdir(curdir)\n\n\ndef upload(keyname, data, s3bucket, secret=None):\n # don't set this as a global, since not all tasks require it\n if secret is None:\n secret = os.environ.get(\"SECRET\")\n if secret is None:\n raise RuntimeError(\"SECRET should be defined in env\")\n\n s3 = boto3.client('s3')\n s3.put_object(Bucket=s3bucket,\n Key=keyname,\n Body=data,\n SSECustomerKey=secret,\n SSECustomerAlgorithm='AES256')\n\n\ndef copytree(src, dst, symlinks=False, ignore=None):\n skipfiles = ['.coverage', 'dist', 'htmlcov', '__init__.pyc', 'coverage.xml', 'service.pyc']\n for item in os.listdir(src):\n src_file = os.path.join(src, item)\n dst_file = os.path.join(dst, item)\n if src_file.split('/')[-1] in skipfiles:\n print(\"skipping file %s\" % src_file)\n continue\n if os.path.isdir(src_file):\n mkdir(dst_file)\n shutil.copytree(src_file, dst_file, symlinks, ignore)\n else:\n shutil.copy2(src_file, dst_file)\n\n\ndef mkdir(path):\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\n@task\ndef test(ctx, watch=False, last_failing=False, no_flake=False, k='', extra='',\n ignore='', ignore_pony=False, ignore_webdev=False):\n \"\"\"Run the tests.\n Note: --watch requires pytest-xdist to be installed.\n \"\"\"\n import pytest\n if not no_flake:\n flake()\n args = ['-rxs', ]\n if k:\n args.append('-k %s' % k)\n args.append(extra)\n if watch:\n args.append('-f')\n else:\n args.append('--cov-report')\n args.append('xml')\n args.append('--cov-report')\n args.append('html')\n if last_failing:\n args.append('--lf')\n if ignore:\n args.append('--ignore')\n args.append(ignore)\n if ignore_pony:\n args.append('--ignore')\n args.append('tests/core/pony')\n if ignore_webdev:\n args.append('--ignore')\n args.append('tests/core/pony/test_webdev.py')\n retcode = pytest.main(args)\n try:\n good = True if retcode == 0 else False\n play(ctx, good)\n except:\n print(\"install vlc for more exciting test runs...\")\n if retcode != 0:\n print(\"test failed exiting\")\n sys.exit(retcode)\n return retcode\n\n\ndef flake():\n \"\"\"Run flake8 on codebase.\"\"\"\n run('flake8 .', echo=True)\n print(\"flake8 passed!!!\")\n\n\ndef clean():\n run(\"rm -rf build\")\n run(\"rm -rf dist\")\n print(\"Cleaned up.\")\n\n\n@task\ndef deploy_core(ctx, name, tests=False, suffix=None, usergroup=None):\n \"\"\"deploy/update lambdas only\"\"\"\n print(\"preparing for deploy...\")\n if tests:\n print(\"running tests...\")\n if test(ctx) != 0:\n print(\"tests need to pass first before deploy\")\n return\n else:\n print(\"skipping tests. execute with --tests flag to run them\")\n if name == 'all':\n names = get_all_core_lambdas()\n\n elif name == 'unicorn':\n names = UNICORN_LAMBDAS\n else:\n names = [name, ]\n print('deploying the following lambdas: %s' % names)\n\n # dist directores are the enemy, clean them all\n for name in get_all_core_lambdas():\n print(\"cleaning house before deploying\")\n with chdir(\"./core/%s\" % (name)):\n clean()\n\n for name in names:\n print(\"=\" * 20, \"Deploying lambda\", name, \"=\" * 20)\n with chdir(\"./core/%s\" % (name)):\n print(\"clean up previous builds.\")\n clean()\n print(\"building lambda package\")\n deploy_lambda_package(ctx, name, suffix=suffix, usergroup=usergroup)\n # need to clean up all dist, otherwise, installing local package takes forever\n clean()\n\n\ndef deploy_lambda_package(ctx, name, suffix=None, usergroup=None):\n # create the temporary local dev lambda directories\n if usergroup:\n if suffix:\n suffix = usergroup + suffix\n else:\n suffix = usergroup\n if suffix:\n new_name = name + '_' + suffix\n new_src = '../' + new_name\n cmd_mkdir = \"rm -fr %s; mkdir -p %s\" % (new_src, new_src)\n cmd_copy = \"cp -r * %s\" % new_src\n cmd_cd = \"cd %s\" % new_src\n cmd_modify_cfg = \"sed 's/%s/%s/g' config.yaml > config.yaml#\" % (name, new_name)\n cmd_replace_cfg = \"mv config.yaml# config.yaml\"\n cmd = ';'.join([cmd_mkdir, cmd_copy, cmd_cd, cmd_modify_cfg, cmd_replace_cfg])\n print(cmd)\n run(cmd)\n else:\n new_name = name\n new_src = '../' + new_name\n # use the lightweight requirements for the lambdas to simplify deployment\n if name in UNICORN_LAMBDAS:\n requirements_file = '../../requirements-lambda-unicorn.txt'\n else:\n requirements_file = '../../requirements-lambda-pony.txt'\n with chdir(new_src):\n aws_lambda.deploy(os.getcwd(), local_package='../..', requirements=requirements_file)\n # add environment variables\n lambda_update_config = {'FunctionName': new_name}\n envs = env_list(name)\n if envs:\n lambda_update_config['Environment'] = {'Variables': envs}\n if name == 'run_task_awsem':\n if usergroup:\n lambda_update_config['Environment']['Variables']['AWS_S3_ROLE_NAME'] \\\n = get_ec2_role_name('tibanna_' + usergroup)\n else:\n lambda_update_config['Environment']['Variables']['AWS_S3_ROLE_NAME'] = 'S3_access' # 4dn-dcic default(temp)\n # add role\n print('name=%s' % name)\n if name in ['run_task_awsem', 'check_task_awsem']:\n role_arn_prefix = 'arn:aws:iam::' + AWS_ACCOUNT_NUMBER + ':role/'\n if usergroup:\n role_arn = role_arn_prefix + get_lambda_role_name('tibanna_' + usergroup, name)\n else:\n role_arn = role_arn_prefix + 'lambda_full_s3' # 4dn-dcic default(temp)\n print(role_arn)\n lambda_update_config['Role'] = role_arn\n client = boto3.client('lambda')\n resp = client.update_function_configuration(**lambda_update_config)\n print(resp)\n # delete the temporary local dev lambda directories\n if suffix:\n old_src = '../' + name\n run('cd %s; rm -rf %s' % (old_src, new_src))\n\n\ndef _PROD():\n return _tbenv() == 'PROD'\n\n\ndef _tbenv(env_data=None):\n if env_data and env_data.get('env'):\n return env_data('env')\n return os.environ.get('ENV_NAME')\n\n\n@task\ndef run_workflow(ctx, input_json='', sfn='', jobid=''):\n \"\"\"run a workflow\"\"\"\n if not jobid:\n jobid = create_jobid()\n with open(input_json) as input_file:\n data = json.load(input_file)\n if sfn == '':\n resp = _run_workflow(data, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME, jobid=jobid)\n else:\n resp = _run_workflow(data, sfn=sfn, jobid=jobid)\n print(\"JOBID %s submitted\" % resp['jobid'])\n print(\"EXECUTION ARN = %s\" % resp[_tibanna]['exec_arn'])\n if 'cloudwatch_dashboard' in resp['config'] and resp['config']['cloudwatch_dashboard']:\n cw_db_url = 'https://console.aws.amazon.com/cloudwatch/' + \\\n 'home?region=%s#dashboards:name=awsem-%s' % (AWS_REGION, jobid)\n print(\"Cloudwatch Dashboard = %s\" % cw_db_url)\n run('open %s' % resp[_tibanna]['url'])\n\n\n@task\ndef setup_tibanna_env(ctx, buckets='', usergroup_tag='default', no_randomize=False, verbose=False):\n \"\"\"set up usergroup environment on AWS\n This function is called automatically by deploy_tibanna or deploy_unicorn\n Use it only when the IAM permissions need to be reset\"\"\"\n print(\"setting up tibanna usergroup environment on AWS...\")\n if not AWS_ACCOUNT_NUMBER or not AWS_REGION:\n print(\"Please set and export environment variable AWS_ACCOUNT_NUMBER and AWS_REGION!\")\n exit(1)\n if not buckets:\n print(\"WARNING: Without setting buckets (using --buckets),\" +\n \"Tibanna would have access to only public buckets.\" +\n \"To give permission to Tibanna for private buckets,\" +\n \"use --buckets=,,...\")\n time.sleep(2)\n if buckets:\n bucket_names = buckets.split(',')\n else:\n bucket_names = None\n tibanna_policy_prefix = create_tibanna_iam(AWS_ACCOUNT_NUMBER, bucket_names,\n usergroup_tag, AWS_REGION, no_randomize=no_randomize,\n verbose=verbose)\n tibanna_usergroup = tibanna_policy_prefix.replace(\"tibanna_\", \"\")\n print(\"Tibanna usergroup %s has been created on AWS.\" % tibanna_usergroup)\n return tibanna_usergroup\n\n\n@task\ndef deploy_tibanna(ctx, suffix=None, sfn_type='pony', usergroup=None, tests=False,\n setup=False, buckets='', setenv=False):\n \"\"\"deploy tibanna unicorn or pony to AWS cloud (pony is for 4DN-DCIC only)\"\"\"\n if setup:\n if usergroup:\n usergroup = setup_tibanna_env(ctx, buckets, usergroup, True)\n else:\n usergroup = setup_tibanna_env(ctx, buckets) # override usergroup\n print(\"creating a new step function...\")\n if sfn_type not in ['pony', 'unicorn']:\n raise Exception(\"Invalid sfn_type : it must be either pony or unicorn.\")\n # this function will remove existing step function on a conflict\n res = _create_stepfunction(suffix, sfn_type, usergroup=usergroup)\n step_function_name = res.get('stateMachineArn').split(':')[6]\n if setenv:\n os.environ['TIBANNA_DEFAULT_STEP_FUNCTION_NAME'] = step_function_name\n with open(os.getenv('HOME') + \"/.bashrc\", \"a\") as outfile: # 'a' stands for \"append\"\n outfile.write(\"\\nexport TIBANNA_DEFAULT_STEP_FUNCTION_NAME=%s\\n\" % step_function_name)\n print(res)\n print(\"deploying lambdas...\")\n if sfn_type == 'pony':\n deploy_core(ctx, 'all', tests=tests, suffix=suffix, usergroup=usergroup)\n else:\n deploy_core(ctx, 'unicorn', tests=tests, suffix=suffix, usergroup=usergroup)\n return step_function_name\n\n\n@task\ndef deploy_unicorn(ctx, suffix=None, no_setup=False, buckets='',\n no_setenv=False, usergroup=None):\n \"\"\"deploy tibanna unicorn to AWS cloud\"\"\"\n deploy_tibanna(ctx, suffix=suffix, sfn_type='unicorn',\n tests=False, usergroup=usergroup, setup=not no_setup,\n buckets=buckets, setenv=not no_setenv)\n\n\n@task\ndef add_user(ctx, user, usergroup):\n \"\"\"add a user to a tibanna group\"\"\"\n boto3.client('iam').add_user_to_group(\n GroupName='tibanna_' + usergroup,\n UserName=user\n )\n\n\n@task\ndef users(ctx):\n \"\"\"list all users along with their associated tibanna user groups\"\"\"\n client = boto3.client('iam')\n marker = None\n while True:\n if marker:\n res = client.list_users(Marker=marker)\n else:\n res = client.list_users()\n print(\"user\\ttibanna_usergroup\")\n for r in res['Users']:\n res_groups = client.list_groups_for_user(\n UserName=r['UserName']\n )\n groups = [rg['GroupName'] for rg in res_groups['Groups']]\n groups = filter(lambda x: 'tibanna_' in x, groups)\n groups = [x.replace('tibanna_', '') for x in groups]\n print(\"%s\\t%s\" % (r['UserName'], ','.join(groups)))\n marker = res.get('Marker', '')\n if not marker:\n break\n\n\n@task\ndef list(ctx, numbers=False, sfn_type=\"unicorn\"):\n \"\"\"list all step functions, optionally with a summary (-n)\"\"\"\n st = boto3.client('stepfunctions')\n res = st.list_state_machines(\n maxResults=1000\n )\n header = \"name\\tcreation_date\"\n if numbers:\n header = header + \"\\trunning\\tsucceeded\\tfailed\\taborted\\ttimed_out\"\n print(header)\n for s in res['stateMachines']:\n if not s['name'].startswith('tibanna_' + sfn_type):\n continue\n line = \"%s\\t%s\" % (s['name'], str(s['creationDate']))\n if numbers:\n counts = count_status(s['stateMachineArn'], st)\n for status in ['RUNNING', 'SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED_OUT']:\n line = line + \"\\t%i\" % counts[status]\n print(line)\n\n\ndef count_status(sfn_arn, client):\n next_token = None\n count = dict()\n while True:\n args = {'stateMachineArn': sfn_arn,\n # 'statusFilter': status,\n 'maxResults': 1000}\n if next_token:\n args['nextToken'] = next_token\n res = client.list_executions(**args)\n for status in ['RUNNING', 'SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED_OUT']:\n count[status] = count.get(status, 0) + sum([r['status'] == status for r in res['executions']])\n if res.get('nextToken', ''):\n next_token = res['nextToken']\n else:\n break\n return count\n\n\n@task\ndef rerun(ctx, exec_arn, sfn='tibanna_pony',\n instance_type=None, shutdown_min=None, ebs_size=None, ebs_type=None, ebs_iops=None,\n overwrite_input_extra=None, key_name=None, name=None):\n \"\"\" rerun a specific job\"\"\"\n override_config = dict()\n if instance_type:\n override_config['instance_type'] = instance_type\n if shutdown_min:\n override_config['shutdown_min'] = shutdown_min\n if ebs_size:\n override_config['ebs_size'] = int(ebs_size)\n if overwrite_input_extra:\n override_config['overwrite_input_extra'] = overwrite_input_extra\n if key_name:\n override_config['key_name'] = key_name\n if ebs_type:\n override_config['ebs_type'] = ebs_type\n if ebs_type == 'gp2':\n override_config['ebs_iops'] = ''\n if ebs_iops:\n override_config['ebs_iops'] = ebs_iops\n _rerun(exec_arn, sfn=sfn, override_config=override_config, name=name)\n\n\n@task\ndef log(ctx, exec_arn=None, job_id=None, exec_name=None, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME, p=False):\n \"\"\"print execution log or postrun json (-p) for a job\"\"\"\n print(_log(exec_arn, job_id, exec_name, sfn, p))\n\n\n@task\ndef kill_all(ctx, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME):\n \"\"\"kill all the running jobs on a step function\"\"\"\n _kill_all(sfn)\n\n\n@task\ndef kill(ctx, exec_arn=None, job_id=None, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME):\n \"\"\"kill a specific job\"\"\"\n _kill(exec_arn, job_id, sfn)\n\n\n@task\ndef rerun_many(ctx, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME, stopdate='13Feb2018', stophour=13,\n stopminute=0, offset=0, sleeptime=5, status='FAILED'):\n \"\"\"rerun all the jobs that failed after a given time point\n filtered by the time when the run failed (stopdate, stophour (24-hour format), stopminute)\n By default, stophour should be the same as your system time zone. This can be changed by setting a different offset.\n If offset=5, for instance, that means your stoptime=12 would correspond to your system time=17.\n Sleeptime is sleep time in seconds between rerun submissions.\n By default, it reruns only 'FAILED' runs, but this can be changed by resetting status.\n\n Examples\n\n rerun_many('tibanna_pony-dev')\n rerun_many('tibanna_pony', stopdate= '14Feb2018', stophour=14, stopminute=20)\n \"\"\"\n _rerun_many(sfn=sfn, stopdate=stopdate, stophour=stophour,\n stopminute=stopminute, offset=offset, sleeptime=sleeptime, status=status)\n\n\n@task\ndef stat(ctx, sfn=TIBANNA_DEFAULT_STEP_FUNCTION_NAME, status=None, verbose=False):\n \"\"\"print out executions with details (-v)\n status can be one of 'RUNNING'|'SUCCEEDED'|'FAILED'|'TIMED_OUT'|'ABORTED'\n \"\"\"\n args = {\n 'stateMachineArn': STEP_FUNCTION_ARN(sfn),\n 'maxResults': 100\n }\n if status:\n args['statusFilter'] = status\n res = dict()\n client = boto3.client('stepfunctions')\n if verbose:\n print(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\".format('jobid', 'status', 'name',\n 'start_time', 'stop_time',\n 'instance_id', 'instance_type',\n 'instance_status', 'ip', 'key',\n 'password'))\n else:\n print(\"{}\\t{}\\t{}\\t{}\\t{}\".format('jobid', 'status', 'name', 'start_time', 'stop_time'))\n res = client.list_executions(**args)\n ec2 = boto3.client('ec2')\n while True:\n if 'executions' not in res or not res['executions']:\n break\n for exc in res['executions']:\n desc = client.describe_execution(executionArn=exc['executionArn'])\n jobid = json.loads(desc['input']).get('jobid', 'no jobid')\n status = exc['status']\n name = exc['name']\n start_time = exc['startDate'].strftime(\"%Y-%m-%d %H:%M\")\n if 'stopDate' in exc:\n stop_time = exc['stopDate'].strftime(\"%Y-%m-%d %H:%M\")\n else:\n stop_time = ''\n if verbose:\n # collect instance stats\n res = ec2.describe_instances(Filters=[{'Name': 'tag:Name', 'Values': ['awsem-' + jobid]}])\n if res['Reservations']:\n instance_status = res['Reservations'][0]['Instances'][0]['State']['Name']\n instance_id = res['Reservations'][0]['Instances'][0]['InstanceId']\n instance_type = res['Reservations'][0]['Instances'][0]['InstanceType']\n if instance_status not in ['terminated', 'shutting-down']:\n instance_ip = res['Reservations'][0]['Instances'][0].get('PublicIpAddress', '-')\n keyname = res['Reservations'][0]['Instances'][0].get('KeyName', '-')\n password = json.loads(desc['input'])['config'].get('password', '-')\n else:\n instance_ip = '-'\n keyname = '-'\n password = '-'\n else:\n instance_status = '-'\n instance_id = '-'\n instance_type = '-'\n instance_ip = '-'\n keyname = '-'\n password = '-'\n print(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\".format(jobid, status, name, start_time, stop_time,\n instance_id, instance_type, instance_status,\n instance_ip, keyname, password))\n else:\n print(\"{}\\t{}\\t{}\\t{}\\t{}\".format(jobid, status, name, start_time, stop_time))\n if 'nextToken' in res:\n res = client.list_executions(nextToken=res['nextToken'], **args)\n else:\n break\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":23632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"351398733","text":"from __future__ import print_function\nfrom __future__ import division\nimport argparse\nimport os\nimport time\nimport torch\nimport torch.utils.data\nimport torch.optim\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\ncudnn.benchmark = True\nfrom utils import net_triplet\nfrom utils.dataset import ContrastiveList\nfrom utils.evaluate_prototype import eval\nfrom utils.layer import ContrastiveLoss\nimport json\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch CosFace')\n\n# DATA\nparser.add_argument('--train_root', type=str, default='/home3/yhw_datasets/face_recognition/NJN_crop/train',help='path to root path of images')\nparser.add_argument('--eval_root',type=str, default='/home3/yhw_datasets/face_recognition/NJN_crop/test',help='path to root path of images')\nparser.add_argument('--database', type=str, default='NJN',help='Which Database for train. (NJN)')\nparser.add_argument('--train_list', type=str, default=\"./Data/NJN_triplet_train.json\",help='path to training list')\nparser.add_argument('--eval_list', type=str, default=\"./Data/NJN_Random_prototype_test.json\",help='path to training list')\nparser.add_argument('--batch_size', type=int, default=512,help='input batch size for training (default: 512)')\n# Network\nparser.add_argument('--network', type=str, default='sphere64',help='Which network for train. (sphere20, sphere64, LResNet50E_IR)')\n#pretrain model\nparser.add_argument('--pre_model', type=str,default=\"./models/checkpoint_msra_AL_2/14_1.pth\",\n help='Which network for train. (sphere20, sphere64, LResNet50E_IR)')\n\n# Classifier\nparser.add_argument('--num_class', type=int, default=None,help='number of people(class)')\n# LR policy\nparser.add_argument('--epochs', type=int, default=30,help='number of epochs to train (default: 30)')\nparser.add_argument('--lr', type=float, default=0.00001,help='learning rate (default: 0.1)')\nparser.add_argument('--step_size', type=list, default=None,help='lr decay step') # [15000, 22000, 26000][80000,120000,140000][100000, 140000, 160000]\nparser.add_argument('--momentum', type=float, default=0.9,help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight_decay', type=float, default=5e-4,metavar='W', help='weight decay (default: 0.0005)')\n# Common settings\nparser.add_argument('--log_interval', type=int, default=2,help='how many batches to wait before logging training status')\nparser.add_argument('--save_path', type=str, default='./models/checkpoint_NJN_Contrastiveloss/',help='path to save checkpoint')\nparser.add_argument('--no_cuda', type=bool, default=False,help='disables CUDA training')\nparser.add_argument('--workers', type=int, default=12,help='how many workers to load data')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if args.cuda else \"cpu\")\nargs.step_size = [5000,12000,18000]\n\ndef main():\n # --------------------------------------model----------------------------------------\n if args.network is 'sphere20':\n model = net_triplet.sphere(type=20)\n model_eval = net_triplet.sphere(type=20)\n elif args.network is 'sphere64':\n model = net_triplet.sphere(type=64)\n model_eval = net_triplet.sphere(type=64)\n elif args.network is 'LResNet50E_IR':\n model = net_triplet.LResNet50E_IR()\n model_eval = net_triplet.LResNet50E_IR()\n else:\n raise ValueError(\"NOT SUPPORT NETWORK! \")\n\n model = torch.nn.DataParallel(model).to(device)\n model_eval = torch.nn.DataParallel(model_eval).to(device)\n if not os.path.exists(args.save_path):\n os.makedirs(args.save_path)\n\n # ------------------------------------load image---------------------------------------\n #train set\n train_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.CenterCrop(128),\n transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) # range [0.0, 1.0] -> [-1.0,1.0]\n ])\n train_loader = torch.utils.data.DataLoader(ContrastiveList(\n root=args.train_root, train_list=args.train_list,transform=train_transform),\n batch_size=args.batch_size, shuffle=True)\n # --------------------------------loss function and optimizer-----------------------------\n optimizer = torch.optim.SGD(model.parameters(),\n lr=args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n criterion = ContrastiveLoss()\n # --------------------------------Load pretrained model parameters-----------------------------\n if args.pre_model:\n checkpoint = torch.load(args.pre_model)\n model.module.load_state_dict(checkpoint)\n # --------------------------------Train-----------------------------\n print(\"start training\")\n for epoch in range(1,args.epochs + 1):\n train(train_loader, model,optimizer,criterion,epoch)\n model_name = args.save_path + str(epoch) + '.pth'\n model.module.save(model_name)\n eval(model_eval, epoch,\n model_name,\n args.eval_root,\n args.eval_list,\n device,\n batch_size=400, workers=12)\n print('Finished Training')\n\ndef train(train_loader,model,optimizer,criterion,epoch):\n model.train()\n print_with_time('Epoch {} start training'.format(epoch))\n time_curr = time.time()\n loss_display = 0.0\n for batch_idx, (data_a,data_p,target) in enumerate(train_loader):\n iteration = (epoch - 1) * int(len(train_loader) / 2) + batch_idx\n # adjust_learning_rate(optimizer, iteration, args.step_size)\n data_a,data_p,target = data_a.to(device), data_p.to(device),target.to(device)\n out_a, out_p = model(data_a),model(data_p)\n loss = criterion(out_a,out_p,target)\n loss_display += loss.item()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0 and batch_idx>0:\n time_used = time.time() - time_curr\n loss_display /= args.log_interval\n print_with_time('Train Epoch: {} [{}/{} ({:.0f}%)]{}, Loss: {:.6f}, Elapsed time: {:.4f}s({} iters)'.format(\n epoch, batch_idx * len(data_a), len(train_loader.dataset), 100. * batch_idx / len(train_loader),\n iteration, loss_display, time_used, args.log_interval))\n time_curr = time.time()\n loss_display = 0.0\n\ndef print_with_time(string):\n print(time.strftime(\"%Y-%m-%d %H:%M:%S \", time.localtime()) + string)\n\ndef adjust_learning_rate(optimizer, iteration, step_size):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 each step size\"\"\"\n if iteration in step_size:\n lr = args.lr * (0.1 ** (step_size.index(iteration) + 1))\n print_with_time('Adjust learning rate to {}'.format(lr))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n else:\n pass\n\nif __name__ == '__main__':\n print(args)\n main()\n","sub_path":"train_contrastive_loss.py","file_name":"train_contrastive_loss.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"380209775","text":"# for general\nimport os\nfrom flask import Flask, render_template, request, jsonify, make_response\nimport werkzeug\nfrom datetime import datetime\nimport random\nimport string\n\n# for データ分析\nimport pandas as pd\nimport xml.etree.ElementTree as et\n\n# for AWS-S3\nimport logging\nimport boto3\nfrom botocore.exceptions import ClientError\n\napp = Flask(__name__, static_folder=\"./build/static\",\n template_folder=\"./build\")\n\napp.config['MAX_CONTENT_LENGTH'] = 30 * 1024 * 1024\napp.config['UPLOAD_FOLDER'] = './uploads'\n\n# S3クライアントの生成\ns3_client = boto3.client(\n 's3',\n aws_access_key_id=os.environ['AWS_ACCESS_KEY'],\n aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY']\n)\ns3_bucket_name = os.environ['AWS_S3_BUCKET']\n\n# ルートpath\n# アプリ起動時にアクセスされて、Reactのトップページを表示する\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n# ファイルアップロード時に呼び出されるREST\n# 受け取ったXMLファイルをparse -> JSON化までしてクライアントに返す\n@app.route('/api/upload', methods=['POST'])\ndef upload():\n\n # ファイルがない場合\n if 'file' not in request.files:\n msg = 'ファイルがありません'\n return make_response(jsonify(msg))\n\n # データの取り出し\n file = request.files['file']\n fileName = file.filename\n\n # ファイル名がない場合\n if fileName == '':\n msg = 'ファイルがありません'\n return make_response(jsonify(msg))\n\n # ランダム文字列の生成\n randStr = ''.join(\n [random.choice(string.ascii_letters + string.digits) for i in range(6)])\n\n # 保存するファイル名とパスを生成\n saveName = datetime.now().strftime(\"%Y%m%d_%H%M%S_\") + randStr + \"_\" + \\\n werkzeug.utils.secure_filename(fileName)\n upload_data_path = os.path.join(app.config['UPLOAD_FOLDER'], saveName)\n # 一時ファイルの保存\n file.save(upload_data_path)\n\n try:\n s3_client.upload_file(\n upload_data_path, s3_bucket_name, 'uploads/' + saveName)\n except ClientError as e:\n logging.error(e)\n\n # 取得したXMLファイルを元にパースするJSONをjsonFileにセット\n df = parseXmlToDf(upload_data_path)\n\n jsonSortBySong = parseDfToJson(df, 'Song')\n jsonSortByArtist = parseDfToJson(df, 'Artist')\n\n # 一時ファイルの削除\n os.remove(upload_data_path)\n\n return jsonify(song=jsonSortBySong, artist=jsonSortByArtist)\n\n\n# アップロードされたXMLファイルをパースしてJSON形式で返す関数\ndef parseXmlToDf(upload_data_path):\n\n # アップロードされたファイルデータをパース\n tree = et.parse(upload_data_path)\n\n # 要素取得\n information = tree.findall(\"dict/dict/dict\")\n\n if len(information) == 0:\n msg = 'XMLファイルの形式が正しくありません'\n return msg\n\n song_info = []\n\n # information > song > elementでdict中の各要素に対して処理\n for song in information:\n song_info_dict = {}\n key = \"\"\n for element in song:\n if element.tag == \"key\":\n key = element.text\n else:\n song_info_dict[key] = element.text\n song_info.append(song_info_dict)\n\n # song_infoをPandasのデータフレームに変換\n df = pd.DataFrame(song_info)\n\n # \"Play Count\"をNull埋めしてint型に変換\n df = df.fillna({\"Play Count\": 0})\n df[\"Play Count\"] = df[\"Play Count\"].astype(int)\n\n return df\n\n\n# 渡されたDataFrameをJson形式で返す\ndef parseDfToJson(df, sortKey):\n\n # app.logger.debug(df.dtypes)\n\n if sortKey == 'Song':\n # 曲の再生数順にソート\n df = df.sort_values(by='Play Count', ascending=False)\n # app.logger.debug(df)\n\n elif sortKey == 'Artist':\n # アーティストごとにGROUP BYしてからソート\n df = df.groupby('Artist')[['Play Count']].sum()\n df = df.sort_values(by='Play Count', ascending=False)\n df = df.reset_index()\n # app.logger.debug(df)\n\n # return件数を20件に絞る\n df = df.head(20)\n\n # record単位のjsonに変換\n json = df.to_json(force_ascii=False, orient=\"records\")\n\n return json\n\n# 画像ファイルアップロード時に呼び出されるREST\n@app.route('/api/image', methods=['POST'])\ndef upload_image():\n # axiosでPOSTされた画像ファイルを取得\n pic = request.files['image']\n app.logger.debug(pic)\n\n # S3に画像をアップロード\n fileName = pic.filename\n app.logger.debug(fileName)\n\n # ランダム文字列の生成\n randStr = ''.join(\n [random.choice(string.ascii_letters + string.digits) for i in range(6)])\n\n # 保存するファイル名とパスを生成\n saveName = datetime.now().strftime(\"%Y%m%d_%H%M%S_\") + randStr + \"_\" + \\\n werkzeug.utils.secure_filename(fileName)\n upload_data_path = os.path.join(app.config['UPLOAD_FOLDER'], saveName)\n # 一時ファイルの保存\n pic.save(upload_data_path)\n\n try:\n s3_client.upload_file(\n upload_data_path, 'itunes-visualize-app', 'uploads/' + saveName)\n except ClientError as e:\n logging.error(e)\n\n bucket_location = s3_client.get_bucket_location(Bucket=s3_bucket_name)\n public_url = \"https://s3-{0}.amazonaws.com/{1}/uploads/{2}\".format(\n bucket_location['LocationConstraint'],\n s3_bucket_name,\n saveName)\n app.logger.debug(public_url)\n\n return make_response(jsonify(public_url))\n\n\n# おまじない\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"backend_flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"508669537","text":"# Copyright 2018 Canonical Ltd\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 inspect\n\nimport charmhelpers.core as ch_core\n\n# the reactive framework unfortunately does not grok `import as` in conjunction\n# with decorators on class instance methods, so we have to revert to `from ...`\n# imports\nfrom charms.reactive import (\n when,\n)\n\nfrom .lib import ovsdb as ovsdb\n\n\nclass OVSDBClusterRequires(ovsdb.OVSDB):\n\n @when('endpoint.{endpoint_name}.joined')\n def joined(self):\n ch_core.hookenv.log('{}: {} -> {}'\n .format(self._endpoint_name,\n type(self).__name__,\n inspect.currentframe().f_code.co_name),\n level=ch_core.hookenv.INFO)\n\n @when('endpoint.{endpoint_name}.broken')\n def broken(self):\n super().broken()\n","sub_path":"src/ovsdb_cluster/requires.py","file_name":"requires.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"16636190","text":"# import libraries\nimport pandas as pd\nimport time\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom copy import deepcopy\n\n# read the data\ndata = pd.read_csv('/Users/huangzijian/Documents/COMP4331/assignment/Assignment_3/a3dataset.txt', header=None)\ndata = data.to_numpy()\n\n# Number of clusters\nk = 9\n# Number of training data\nn = data.shape[0]\n# Number of features in the data\nc = data.shape[1]\n\nstart = time.time()\n\n# Generate random centers\nmean = np.mean(data, axis = 0)\nstd = np.std(data, axis = 0)\ncenters = np.random.randn(k,c)*std + mean\n\ncenters_old = np.zeros(centers.shape) # to store old centers\ncenters_new = deepcopy(centers) # Store new centers\n\n# array of cluster number and distances\nclusters = np.zeros(n)\ndistances = np.zeros((n,k))\n\nerror = np.linalg.norm(centers_new - centers_old)\n\n# When, after an update, the estimate of that center stays the same, exit loop\nwhile error != 0:\n \n for i in range(k):\n distances[:,i] = np.linalg.norm(data - centers[i], axis=1)\n \n clusters = np.argmin(distances, axis = 1)\n \n centers_old = deepcopy(centers_new)\n \n for i in range(k):\n centers_new[i] = np.mean(data[clusters == i], axis=0)\n error = np.linalg.norm(centers_new - centers_old)\n\nend = time.time()\ncolormap = np.array(['r', 'g', 'b', 'c', 'm', 'y', 'k', 'orange', 'lime'])\nplt.scatter(data[:,0], data[:,1], s=7, c=colormap[clusters])\nplt.show()\n\nSSE = np.linalg.norm(distances.min(axis=1))\nprint(SSE)\nprint(str(end-start)+\"s\")","sub_path":"Assignment 3/K-Means-Clustering-9.py","file_name":"K-Means-Clustering-9.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"514618675","text":"from gi.repository import Gtk, Gio, GLib\n\nimport os.path\n\nfrom .editor import NoveltyEditor\n\nclass NoveltyWindow(Gtk.Window):\n\n\tdef __init__(self):\n\t\tGtk.Window.__init__(self, title='Novelty', name='NoveltyWindow')\n\n\t\t# DEBUG\n\t\tscdir = os.path.dirname(os.path.abspath(__file__ + '/../')) + '/schemas'\n\t\tscs = Gio.SettingsSchemaSource.new_from_directory(scdir, Gio.SettingsSchemaSource.get_default(), False)\n\t\tsc = Gio.SettingsSchemaSource.lookup(scs, 'apps.novelty', False)\n\n\t\t# Load configuration\n\t\tself.config = Gio.Settings.new_full(sc)\n\t\t\n\t\t# Title\n\t\tself.title_suffix = ' - Novelty'\n\n\t\t# Layout\n\t\tself.layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n\t\tself.layout.get_style_context().add_class('layout')\n\t\tself.layout.show()\n\t\tself.add(self.layout)\n\n\t\t# Initialize components\n\t\tself._init_titlebar()\n\t\tself._init_editor()\n\t\tself._init_statusbar()\n\t\tself._init_state()\n\n\t\t# Connect signals\n\t\tself.config.connect('changed::show-statusbar', self.toggle_statusbar)\n\t\tself.connect('delete-event', self.save_state)\n\n\tdef _init_titlebar(self):\n\t\t\"\"\" Initialize client-side decorated titlebar \"\"\"\n\t\t\n\t\tself.hb = Gtk.HeaderBar()\n\t\tself.hb_revealer = Gtk.Revealer()\n\n\t\t# Window title\n\t\tself.hb.props.title = 'New File' + self.title_suffix\n\n\t\t# Headerbar properties\n\t\tself.hb.set_show_close_button(True)\n\t\tself.hb.get_style_context().add_class('titlebar')\n\n\t\t# Headerbar revealer\n\t\tself.hb_revealer.add(self.hb)\n\t\tself.hb_revealer.props.transition_duration = 1000\n\t\tself.hb_revealer.props.transition_type = Gtk.RevealerTransitionType.CROSSFADE\n\t\tself.hb_revealer.set_reveal_child(True)\n\n\t\t# Set window titlebar\n\t\tself.set_titlebar(self.hb_revealer)\n\n\t\t# Show\n\t\tself.hb.show()\n\t\tself.hb_revealer.show()\n\n\tdef _init_editor(self):\n\t\t\"\"\" Initialize text view \"\"\"\n\n\t\t# Scrolled window\n\t\tsw = Gtk.ScrolledWindow()\n\t\tsw.set_shadow_type(Gtk.ShadowType.NONE)\n\n\t\t# Editor\n\t\tself.editor = NoveltyEditor(self)\n\t\tself.editor.get_style_context().add_class('editor')\n\n\t\t# Add to layout\n\t\tsw.add(self.editor)\n\t\tself.layout.pack_start(sw, True, True, 0)\n\n\t\t# Show\n\t\tself.editor.show()\n\t\tsw.show()\n\n\tdef _init_statusbar(self):\n\t\t\"\"\" Initialize hbox statusbar, shows word count etc. \"\"\"\n\n\t\t# Status bar\n\t\tself.sb = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)\n\t\tself.sb.get_style_context().add_class('statusbar')\n\n\t\ttest = Gtk.Label('Blabla')\n\t\ttest.show()\n\t\tself.sb.pack_start(test, False, False, 0)\n\n\t\t# Add statusbar to layout\n\t\tself.layout.pack_end(self.sb, False, False, 0)\n\n\t\t# Show\n\t\tif self.config.get_boolean('show-statusbar') is True:\n\t\t\tself.sb.show()\n\n\tdef _init_state(self):\n\t\t\"\"\" Restore last known window state \"\"\"\n\t\twidth, height = self.config.get_value('last-window-size').unpack()\n\t\tx, y = self.config.get_value('last-window-position').unpack()\n\n\t\t# Restore window size\n\t\tself.set_default_size(width, height)\n\n\t\t# Restore window position\n\t\tself.move(x,y)\n\n\n\tdef toggle_statusbar(self, config, key):\n\t\t\"\"\" Toggle statusbar visibility \"\"\"\n\n\t\tif self.config.get_boolean('show-statusbar') is True:\n\t\t\tself.sb.show()\n\t\telse:\n\t\t\tself.sb.hide()\n\n\tdef save_state(self, *args):\n\t\t\"\"\" Save last known position and location \"\"\"\n\t\twidth, height = (self.get_allocated_width(), self.get_allocated_height())\n\t\tx, y = self.get_position()\n\n\t\t# Save window size\n\t\tself.config.set_value('last-window-size', GLib.Variant.new_tuple(GLib.Variant.new_int32(width), GLib.Variant.new_int32(height)))\n\n\t\t# Save window position\n\t\tself.config.set_value('last-window-position', GLib.Variant.new_tuple(GLib.Variant.new_int32(x), GLib.Variant.new_int32(y)))\n","sub_path":"novelty/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"183842581","text":"from functools import reduce\nimport json\nimport operator\nfrom unittest.mock import patch, MagicMock\nfrom django.contrib.auth.models import Group, Permission\nfrom django.db.models import Q\nfrom django.urls import reverse\nfrom django.utils.crypto import get_random_string\nfrom django.test import TestCase, override_settings\nfrom accounts.models import User\nfrom requests.exceptions import ConnectionError, HTTPError\nfrom zentral.core.probes.feeds import sync_feed, update_or_create_feed\n\n\nFEED = {\n \"id\": \"test-feed\",\n \"name\": \"Test feed\",\n \"description\": \"Test feed description\",\n \"probes\": {\n \"zentral-authentication-events\": {\n \"model\": \"BaseProbe\",\n 'name': \"Zentral authentication events\",\n \"body\": {\n \"filters\": {\n \"metadata\": [\n {\"event_types\": ['zentral_failed_login',\n 'zentral_failed_verification',\n 'zentral_login',\n 'zentral_logout']}\n ]\n },\n \"incident_severity\": None\n }\n }\n }\n}\nFEED_URL = \"https://www.example.com/feed.json\"\n\n\n@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')\nclass FeedViewsTestCase(TestCase):\n @classmethod\n def setUpTestData(cls):\n # user\n cls.user = User.objects.create_user(\"godzilla\", \"godzilla@zentral.io\", get_random_string())\n cls.group = Group.objects.create(name=get_random_string())\n cls.user.groups.set([cls.group])\n\n # utility methods\n\n def _login_redirect(self, url):\n response = self.client.get(url)\n self.assertRedirects(response, \"{u}?next={n}\".format(u=reverse(\"login\"), n=url))\n\n def _login(self, *permissions):\n if permissions:\n permission_filter = reduce(operator.or_, (\n Q(content_type__app_label=app_label, codename=codename)\n for app_label, codename in (\n permission.split(\".\")\n for permission in permissions\n )\n ))\n self.group.permissions.set(list(Permission.objects.filter(permission_filter)))\n else:\n self.group.permissions.clear()\n self.client.force_login(self.user)\n\n @patch(\"zentral.core.probes.feeds.fetch_feed\")\n def _create_feed(self, fetch_feed):\n fetch_feed.return_value = FEED\n feed, _ = update_or_create_feed(FEED_URL)\n sync_feed(feed)\n feed_probe = feed.feedprobe_set.all()[0]\n return feed, feed_probe\n\n # feeds\n\n def test_feeds_login_redirect(self):\n self._login_redirect(reverse(\"probes:feeds\"))\n\n def test_feeds_permission_denied(self):\n self._login()\n response = self.client.get(reverse(\"probes:feeds\"))\n self.assertEqual(response.status_code, 403)\n\n def test_feeds(self):\n self._login(\"probes.view_feed\")\n response = self.client.get(reverse(\"probes:feeds\"))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"0 Feeds\", status_code=200)\n\n # add feed\n\n def test_add_feed_redirect(self):\n self._login_redirect(reverse(\"probes:add_feed\"))\n\n def test_add_feed_permission_denied(self):\n self._login()\n response = self.client.get(reverse(\"probes:add_feed\"))\n self.assertEqual(response.status_code, 403)\n\n def test_add_feed_get(self):\n self._login(\"probes.add_feed\")\n response = self.client.get(reverse(\"probes:add_feed\"))\n self.assertContains(response, \"Add feed\", status_code=200)\n\n @patch(\"zentral.core.probes.feeds.requests.get\")\n def test_add_feed_post_connection_error(self, requests_get):\n requests_get.side_effect = ConnectionError(\"Boom!\")\n url = reverse(\"probes:add_feed\")\n feed_url = \"http://dewkjhdkwjhkjedhwdkwj.de/zu\"\n self._login(\"probes.add_feed\")\n response = self.client.post(url, {\"url\": feed_url}, follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"core/probes/add_feed.html\")\n self.assertFormError(response, \"form\", \"url\", \"Connection error\")\n requests_get.assert_called_once_with(feed_url, stream=True)\n\n @patch(\"zentral.core.probes.feeds.requests.get\")\n def test_add_feed_post_http_error_404(self, requests_get):\n error = HTTPError(\"Boom 404!\")\n error.response = MagicMock()\n error.response.status_code = 404\n requests_get.side_effect = error\n feed_url = \"http://dewkjhdkwjhkjedhwdkwj.de/zu\"\n self._login(\"probes.add_feed\")\n response = self.client.post(reverse(\"probes:add_feed\"),\n {\"url\": feed_url},\n follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"core/probes/add_feed.html\")\n self.assertFormError(response, \"form\", \"url\", \"HTTP error 404\")\n requests_get.assert_called_once_with(feed_url, stream=True)\n\n @patch(\"zentral.core.probes.feeds.fetch_feed\")\n def test_add_feed_post_feed_error(self, fetch_feed):\n fetch_feed.side_effect = json.decoder.JSONDecodeError(\"YALA\", \"\", 0)\n feed_url = \"http://dewkjhdkwjhkjedhwdkwj.de/zu\"\n self._login(\"probes.add_feed\")\n response = self.client.post(reverse(\"probes:add_feed\"),\n {\"url\": feed_url},\n follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"core/probes/add_feed.html\")\n self.assertFormError(response, \"form\", \"url\", \"Invalid JSON\")\n fetch_feed.assert_called_once_with(feed_url)\n\n @patch(\"zentral.core.probes.feeds.fetch_feed\")\n def test_add_feed_post_query_pack_ok(self, fetch_feed):\n fetch_feed.return_value = FEED\n self._login(\"probes.add_feed\", \"probes.view_feed\")\n response = self.client.post(reverse(\"probes:add_feed\"),\n {\"url\": FEED_URL},\n follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"core/probes/feed.html\")\n self.assertIn(\"object\", response.context)\n feed = response.context[\"object\"]\n self.assertEqual(feed.url, FEED_URL)\n self.assertEqual(feed.name, FEED[\"name\"])\n\n # feed\n\n def test_feed_redirect(self):\n feed, _ = self._create_feed()\n self._login_redirect(feed.get_absolute_url())\n\n def test_feed_permission_denied(self):\n feed, _ = self._create_feed()\n self._login()\n response = self.client.get(feed.get_absolute_url())\n self.assertEqual(response.status_code, 403)\n\n def test_feed_ok(self):\n feed, _ = self._create_feed()\n self._login(\"probes.view_feed\")\n response = self.client.get(feed.get_absolute_url())\n self.assertContains(response, FEED[\"name\"], status_code=200)\n\n # delete feed\n\n def test_delete_feed_redirect(self):\n feed, _ = self._create_feed()\n self._login_redirect(reverse(\"probes:delete_feed\", args=(feed.id,)))\n\n def test_delete_feed_permission_denied(self):\n feed, _ = self._create_feed()\n self._login()\n response = self.client.get(reverse(\"probes:delete_feed\", args=(feed.id,)))\n self.assertEqual(response.status_code, 403)\n\n def test_delete_feed_get(self):\n feed, _ = self._create_feed()\n self._login(\"probes.delete_feed\")\n response = self.client.get(reverse(\"probes:delete_feed\", args=(feed.id,)))\n self.assertContains(response, \"Delete feed\", status_code=200)\n\n def test_delete_feed_post(self):\n feed, _ = self._create_feed()\n self._login(\"probes.delete_feed\", \"probes.view_feed\")\n response = self.client.post(reverse(\"probes:delete_feed\", args=(feed.id,)), follow=True)\n self.assertContains(response, \"0 Feed\", status_code=200)\n\n # sync feed\n\n def test_sync_feed_redirect(self):\n feed, _ = self._create_feed()\n self._login_redirect(reverse(\"probes:sync_feed\", args=(feed.id,)))\n\n def test_sync_feed_permission_denied(self):\n feed, _ = self._create_feed()\n self._login()\n response = self.client.get(reverse(\"probes:sync_feed\", args=(feed.id,)))\n self.assertEqual(response.status_code, 403)\n\n def test_sync_feed_post(self):\n feed, _ = self._create_feed()\n self._login(\"probes.change_feed\", \"probes.view_feed\")\n response = self.client.post(reverse(\"probes:sync_feed\", args=(feed.id,)), follow=True)\n self.assertContains(response, feed.name, status_code=200)\n self.assertTemplateUsed(response, \"core/probes/feed.html\")\n\n # feed probe\n\n def test_feed_probe_redirect(self):\n _, feed_probe = self._create_feed()\n self._login_redirect(reverse(\"probes:feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n\n def test_feed_probe_permission_denied(self):\n _, feed_probe = self._create_feed()\n self._login()\n response = self.client.get(reverse(\"probes:feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n self.assertEqual(response.status_code, 403)\n\n def test_feed_probe(self):\n _, feed_probe = self._create_feed()\n self._login(\"probes.view_feedprobe\")\n response = self.client.get(reverse(\"probes:feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n self.assertContains(response, feed_probe.name, status_code=200)\n\n # feed probe import\n\n def test_feed_probe_import_redirect(self):\n feed, feed_probe = self._create_feed()\n self._login_redirect(reverse(\"probes:import_feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n\n def test_feed_probe_import_permission_denied(self):\n feed, feed_probe = self._create_feed()\n self._login()\n response = self.client.get(reverse(\"probes:import_feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n self.assertEqual(response.status_code, 403)\n\n def test_feed_probe_import_get(self):\n feed, feed_probe = self._create_feed()\n self._login(\"probes.view_feedprobe\", \"probes.add_probesource\")\n response = self.client.get(reverse(\"probes:import_feed_probe\", args=(feed_probe.feed.id, feed_probe.id)))\n self.assertContains(response, \"Import feed probe\", status_code=200)\n\n def test_feed_probe_import_post(self):\n feed, feed_probe = self._create_feed()\n url = reverse(\"probes:import_feed_probe\", args=(feed_probe.feed.id, feed_probe.id))\n probe_name = \"Godzilla probe\"\n self._login(\"probes.view_feedprobe\", \"probes.add_probesource\", \"probes.view_probesource\")\n response = self.client.post(url, {\"probe_name\": probe_name},\n follow=True)\n self.assertContains(response, \"Probe {}\".format(probe_name), status_code=200)\n self.assertContains(response, feed.name)\n self.assertContains(response, feed_probe.name)\n","sub_path":"tests/probes/test_feeds_views.py","file_name":"test_feeds_views.py","file_ext":"py","file_size_in_byte":11172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"296450602","text":"# -*- coding: utf-8 -*-\nfrom .base import BaseBackend\n\nfrom django.template.loader import render_to_string\nfrom django.core import mail\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.utils import translation\n\nfrom ..models import NewsletterSubscriber\nfrom ..settings import DEFAULT_FROM_EMAIL, PRE_PROCESSORS\nfrom ..utils import load_class\nfrom ..compat import update_fields\n\n\nclass SimpleBackend(BaseBackend):\n model = NewsletterSubscriber\n\n def subscribe(self, email, newsletter_list, lang=None, user=None):\n return self.model.objects.create(email=email, user=user,\n newsletter_list=newsletter_list, lang=lang)\n\n def register(self, email, newsletter_list, lang=None, user=None):\n if not self.exists(email, newsletter_list, lang=lang):\n subscriber = self.subscribe(email, newsletter_list, lang, user)\n else:\n for subscriber in self.all(email=email, newsletter_list=newsletter_list, lang=lang):\n if subscriber.is_unsubscribed:\n subscriber.subscribe()\n\n def unregister(self, email, newsletter_list=None, user=None, lang=None):\n qs = self.model.objects.filter(email__iexact=email)\n\n if lang:\n qs = qs.filter(lang=lang)\n\n if not newsletter_list:\n for subscriber in qs:\n subscriber.unsubscribe(commit=True)\n else:\n if self.exists(email, newsletter_list):\n for subscriber in qs.filter(newsletter_list=newsletter_list):\n subscriber.unsubscribe(commit=True)\n\n def exists(self, email, newsletter_list=None, user=None, lang=None):\n return self.all(email, user=user, lang=lang, newsletter_list=newsletter_list).exists()\n\n def all(self, email, user=None, lang=None, newsletter_list=None):\n qs = self.model.objects.filter(email__iexact=email).select_related('newsletter_list')\n\n if user:\n qs = qs.filter(user=user)\n\n if lang:\n qs = qs.filter(lang=lang)\n\n if newsletter_list:\n qs = qs.filter(newsletter_list=newsletter_list)\n\n return qs\n\n def subscribed(self, email, newsletter_list=None, user=None, lang=None):\n return (self.all(email, user=user, lang=lang, newsletter_list=newsletter_list)\n .filter(is_unsubscribed=False)\n .exists())\n\n def send_mails(self, newsletter, fail_silently=False):\n qs = self.model.objects.filter(newsletter_list=newsletter.newsletter_list).subscribed()\n\n if newsletter.languages:\n subscribers = qs.has_langs(newsletter.languages).prefetch_related('user')\n else:\n subscribers = qs.prefetch_related('user')\n\n connection = mail.get_connection(fail_silently=fail_silently)\n\n emails = []\n\n old_language = translation.get_language()\n\n for subscriber in subscribers:\n translation.activate(subscriber.lang)\n\n email = EmailMultiAlternatives(newsletter.name,\n render_to_string('courriers/newsletter_raw_detail.txt', {\n 'object': newsletter,\n 'subscriber': subscriber\n }),\n DEFAULT_FROM_EMAIL,\n [subscriber.email, ],\n connection=connection)\n\n html = render_to_string('courriers/newsletter_raw_detail.html', {\n 'object': newsletter,\n 'items': newsletter.items.all().prefetch_related('newsletter'),\n 'subscriber': subscriber\n })\n\n for pre_processor in PRE_PROCESSORS:\n html = load_class(pre_processor)(html)\n\n email.attach_alternative(html, 'text/html')\n\n emails.append(email)\n\n translation.activate(old_language)\n\n results = connection.send_messages(emails)\n\n newsletter.sent = True\n update_fields(newsletter, fields=('sent', ))\n\n return results\n","sub_path":"courriers/backends/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"9848438","text":"\ndef letterToIndex(word):\n index = [0] * len(word)\n for i in range (len(word)):\n index[i] = ord(word[i])\n return(index)\n\ndef indexToLetter(indexList):\n word = [0] * len(indexList)\n for i in range (len(indexList)):\n word[i] = chr(indexList[i])\n print(\"\".join(word))\n\n\ndef shift(key, word):\n indexList = letterToIndex(word)\n key = key % 27\n for i in range (len(indexList)):\n if (indexList[i] >= 97) and (indexList[i] <= 122):\n indexList[i] = (((indexList[i] - 97 + key) % 26)+ 97)\n elif (indexList[i] >= 65) and (indexList[i] <= 90):\n indexList[i] = (((indexList[i] - 65 + key) % 26)+ 65)\n indexToLetter(indexList)\n\nprint(\"This program will encrypt a given text to the caesar cypher. Only letters will be shifted, nothing else.\")\nword = input(\"Please enter the sentence to encrypt: \")\nkey = int(input(\"Please enter your key (between 1 and 26 included): \"))\n\nshift(key, word)\n","sub_path":"Caesar.py","file_name":"Caesar.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"516469824","text":"# Assignment 3 | Elements of A.I. | Fall 2015\n\n# Pruthvi N. Shetty | shettypr\n\n# Based on skeleton code by D. Crandall\n\n#Modus operandi of the program:\n\n# A player has 13 turns in each game where he/she throws five fair dice simultaneously. Scoring is divided into a set of given categories and the program provides intelligence so that the game can be played smartly\n# with the intention of obtaining the maximum score as per the readings of the third/final dice roll, from the given scoring categories.\n# 100 such games will be played and the objective of the game is to obtain the maximum mean score.\n# Post each roll, the program checks if the maximum score can be retrieved from any of the available scoring categories and assigns that scoring category\n# Else, it chooses the subset of dice to be re-rolled based on the next best possibility of attaining a good score.\n# The prioritizing of the scoring categories is depending on the Max to Min ordering of the gettable available_category.\n# Since each catogory can be used only once in each game, the probablity of obtaining the best suited category decreases as we proceed with each turn.\n\nfrom ZacateState import Dice\nfrom ZacateState import Scorecard\nimport copy\n\nd1 = Dice()\ns1 = Scorecard()\n\ndefault_dice = [1,2,3,4,5]\n\nclass ZacateAutoPlayer:\n\n def __init__(self): #Initializing default values to all score categories\n self.assign_category = {\"unos\":0, \"doses\":0, \"treses\":0, \"cuatros\":0, \"cincos\":0, \"seises\":0, \"quintupulo\":0, \"pupusa de queso\":0, \"pupusa de frijol\":0, \"elote\":0, \"triple\":0, \"cuadruple\":0, \"tamal\":0}\n\n#====================================== Start game ======================================#\n\n def first_roll(self, dice, scorecard): #For first roll of the dice we check the count and readings\n count_dice = [dice.dice.count(which_dice) for which_dice in range(1,7)]\n self.set_category(dice, count_dice)\n\n #Checking availibility of the first 3 maximum possible scoring categories in the mentioned order of preference\n if \"quintupulo\" not in scorecard.scorecard or \"pupusa de queso\" not in scorecard.scorecard or \"elote\" not in scorecard.scorecard:\n if self.assign_category[\"quintupulo\"] == 5 or self.assign_category[\"pupusa de queso\"] == 5 or self.assign_category[\"elote\"] == 5:\n return []\n\n elif self.assign_category[\"quintupulo\"] >= 3: #For quintupulo category\n return self.for_quintupulo(dice, self.assign_category[\"quintupulo\"])\n\n elif self.assign_category[\"pupusa de queso\"] >= 3: #For pupusa de queso category\n return self.for_pdq(dice, self.assign_category[\"pupusa de queso\"])\n\n elif self.assign_category[\"elote\"]: #For elote category\n return self.for_elote(dice, self.assign_category[\"elote\"], count_dice)\n\n #Checking for the next-best set of categories\n if \"seises\" not in scorecard.scorecard or \"triple\" not in scorecard.scorecard or \"cuadruple\" not in scorecard.scorecard or \"pupusa de frijol\" not in scorecard.scorecard:\n if self.assign_category[\"seises\"] == 5 or self.assign_category[\"triple\"] == 5 or self.assign_category[\"cuadruple\"] == 5 or self.assign_category[\"pupusa de frijol\"]==5:\n return []\n\n elif self.assign_category[\"seises\"] >= 3:\n return self.for_unos_to_seises(dice, self.assign_category[\"seises\"], 6)\n\n elif self.assign_category[\"triple\"] >= 3:\n return self.for_triple(dice, self.assign_category[\"triple\"], count_dice)\n\n elif self.assign_category[\"cuadruple\"] >= 3:\n return self.for_cuadruple(dice, self.assign_category[\"cuadruple\"], count_dice)\n\n elif self.assign_category[\"pupusa de frijol\"] >= 3:\n return self.for_pdf(dice, self.assign_category[\"pupusa de frijol\"])\n\n return default_dice #Worst case\n\n def second_roll(self, dice, scorecard): #For second roll of dice\n\n count_dice = [dice.dice.count(which_dice) for which_dice in range(1,7)]\n self.set_category(dice, count_dice)\n\n #Similarly, checking availibility of the first 3 maximum possible scoring categories in the mentioned order of preference.\n if \"quintupulo\" not in scorecard.scorecard or \"pupusa de queso\" not in scorecard.scorecard or \"elote\" not in scorecard.scorecard:\n\n if self.assign_category[\"quintupulo\"] == 5 or self.assign_category[\"pupusa de queso\"] == 5 or self.assign_category[\"elote\"]==5:\n return []\n\n elif self.assign_category[\"quintupulo\"] == 4:\n return self.for_quintupulo(dice, self.assign_category[\"quintupulo\"])\n\n elif self.assign_category[\"pupusa de queso\"] == 4:\n return self.for_pdq(dice, self.assign_category[\"pupusa de queso\"])\n\n elif self.assign_category[\"elote\"] == 4:\n return self.for_elote(dice, self.assign_category[\"elote\"], count_dice)\n\n #Checking for the next-best set of categories\n if \"seises\" not in scorecard.scorecard or \"triple\" not in scorecard.scorecard or \"cuadruple\" not in scorecard.scorecard or \"pupusa de frijol\" not in scorecard.scorecard:\n\n if self.assign_category[\"seises\"] == 5 or self.assign_category[\"triple\"] == 5 or self.assign_category[\"cuadruple\"] == 5 or self.assign_category[\"pupusa de frijol\"]==5:\n return []\n elif self.assign_category[\"seises\"] == 4:\n return self.for_unos_to_seises(dice, self.assign_category[\"seises\"], 6)\n\n elif self.assign_category[\"triple\"] == 4:\n return self.for_triple(dice, self.assign_category[\"triple\"], count_dice)\n\n elif self.assign_category[\"cuadruple\"] == 4:\n return self.for_cuadruple(dice, self.assign_category[\"cuadruple\"], count_dice)\n\n elif self.assign_category[\"pupusa de frijol\"] == 4:\n return self.for_pdf(dice, self.assign_category[\"pupusa de frijol\"])\n\n #Checking for the final set of categories\n if \"cincos\" not in scorecard.scorecard or \"cuatros\" not in scorecard.scorecard or \"treses\" not in scorecard.scorecard or \"doses\" not in scorecard.scorecard or \"unos\" not in scorecard.scorecard:\n\n if self.assign_category[\"seises\"] == 5 or self.assign_category[\"triple\"] == 5 or self.assign_category[\"cuadruple\"] == 5 or self.assign_category[\"pupusa de frijol\"]==5:\n return []\n\n elif self.assign_category[\"seises\"] == 4:\n return self.for_unos_to_seises(dice, self.assign_category[\"seises\"], 6)\n\n elif self.assign_category[\"triple\"] == 4:\n return self.for_triple(dice, self.assign_category[\"triple\"], count_dice)\n\n elif self.assign_category[\"cuadruple\"] == 4:\n return self.for_cuadruple(dice, self.assign_category[\"cuadruple\"], count_dice)\n\n elif self.assign_category[\"pupusa de frijol\"] == 4:\n return self.for_pdf(dice, self.assign_category[\"pupusa de frijol\"])\n\n return default_dice #Worst case\n\n def third_roll(self, dice, scorecard): #For the third roll of dice\n\n count_dice = [dice.dice.count(which_dice) for which_dice in range(1,7)] #Checking count of dice for third roll\n self.set_category(dice, count_dice) #Initializing category for third roll's dice's readings\n get_category = [] #For storing category\n\n for which_dice in range(6, 0, -1): #Assigning new category\n temp = self.prioritize_score(dice, scorecard, which_dice)\n if temp!= \"null\" and temp not in get_category:\n get_category.append(temp)\n\n if len(get_category)>1: #Checking if all categories are used\n return self.score_category(get_category, dice, scorecard)\n\n return get_category[0] if len(get_category)> 0 else self.rest_check(dice, scorecard)\n\n#====================================== User-defined functions ======================================#\n\n def for_unos_to_seises(self, dice, max_category, number): #For Numbers 1's to 6's - Unos, Duos, treses, cuatros, cincos, seises\n\n dice_to_select = []\n\n for which_dice in dice.dice:\n if dice.dice[which_dice] != number:\n dice_to_select.append(which_dice)\n\n return dice_to_select\n\n def for_pdq(self, dice, count_max): #Checking Pupusa de queso\n\n dice_to_select = []\n\n if 1 not in dice.dice and 2 in dice.dice and 3 in dice.dice and 4 in dice.dice and 5 in dice.dice and 6 not in dice.dice:\n\n for which_dice in range(0, 5): #Checking for 2,3,4,5 readings of dice\n\n if dice.dice[which_dice] == 2:\n dice_to_select.append(which_dice)\n\n if dice.dice[which_dice] == 3:\n dice_to_select.append(which_dice)\n\n if dice.dice[which_dice] == 4:\n dice_to_select.append(which_dice)\n\n if dice.dice[which_dice] == 5:\n dice_to_select.append(which_dice)\n\n return dice_to_select\n else:\n return default_dice\n\n def for_pdf(self, dice, max_category): #Checking Pupusa de frijol\n\n if max_category == 5:\n return []\n else:\n return default_dice\n\n def for_quintupulo(self, dice, count_max): #Checking Quintupulo\n\n dice_readings = []\n if count_max == 5:\n return []\n\n elif count_max == 4 or count_max == 3:\n dice_max = max(dice.dice)\n for which_dice in range(0, len(dice.dice)):\n if dice.dice[which_dice] != dice_max:\n dice_readings.append(which_dice)\n return dice_readings\n\n else:\n return default_dice\n\n def for_elote(self, dice, max_category, count_dice): #Checking Elote\n dice_readings = []\n if max_category == 5:\n return []\n elif max_category == 4 or max_category == 3:\n dice_max = self.dice_check(count_dice)\n counter = 0\n for which_dice in range(0, len(dice.dice)):\n if dice.dice[which_dice] != dice_max:\n counter += 1\n dice_readings.append(which_dice)\n if counter>0:\n return dice_readings\n else:\n return default_dice\n else:\n return default_dice\n\n def for_triple(self, dice, max_category, count_dice): #Checking Triple\n return self.for_elote(dice, max_category, count_dice)\n\n def for_cuadruple(self, dice, max_category, count_dice): #Checking Cuadruple\n return self.for_elote(dice, max_category, count_dice)\n\n def set_category(self, dice, count_dice): #Assigning score category\n\n self.assign_category[\"seises\"] = dice.dice.count(6)\n self.assign_category[\"cincos\"] = dice.dice.count(5)\n self.assign_category[\"cuatros\"] = dice.dice.count(4)\n self.assign_category[\"treses\"] = dice.dice.count(3)\n self.assign_category[\"doses\"] = dice.dice.count(2)\n self.assign_category[\"unos\"] = dice.dice.count(1)\n self.assign_category[\"quintupulo\"] = max(count_dice)\n self.assign_category[\"pupusa de queso\"] = 5 if (sorted(dice.dice) == [1,2,3,4,5] or sorted(dice.dice) == [2,3,4,5,6]) else 4\n self.assign_category[\"elote\"] = 5 if (2 in count_dice) and (3 in count_dice) else (4 if (3 in count_dice) and (2 not in count_dice) else 3 if (2 in count_dice) and (3 not in count_dice) else 2)\n self.assign_category[\"triple\"] = 5 if max(count_dice) >= 3 else 4 if max(count_dice) >= 2 else 3\n self.assign_category[\"cuadruple\"] = 5 if max(count_dice) >= 4 else 4 if max(count_dice) >= 3 else 3 if max(count_dice) >= 2 else 2\n self.assign_category[\"pupusa de frijol\"] = 5 if ((len(set([1,2,3,4]) - set(dice.dice)) == 0 or len(set([2,3,4,5]) - set(dice.dice)) == 0 or len(set([3,4,5,6]) - set(dice.dice)) == 0)) else 2\n\n def dice_check(self, count_dice): #For taken dice readings\n\n dice_max = max(count_dice)\n\n for dice_key in range(1,len(count_dice)):\n if count_dice[dice_key] == dice_max:\n return dice_key\n\n def rest_check(self, dice, scorecard): #For remaining dice readings\n current_score = Scorecard()\n current_score.scorecard = scorecard.scorecard.copy()\n current_score.Categories = copy.deepcopy(scorecard.Categories)\n current_score.Numbers = scorecard.Numbers.copy()\n available_category = { \"unos\" : 0, \"doses\" : 0, \"treses\" : 0, \"cuatros\" : 0, \"cincos\" : 0, \"seises\" : 0, \"pupusa de queso\" : 0, \"pupusa de frijol\" : 0, \"elote\" : 0, \"triple\" : 0, \"cuadruple\" : 0, \"quintupulo\" : 0, \"tamal\" : 0 }\n check_possibilty = False\n\n for current_category in available_category:\n if current_category not in current_score.scorecard:\n current_score.record(current_category, dice)\n if available_category[current_category]==0:\n available_category[current_category] = current_score.scorecard[current_category]\n\n best_available_score = max(available_category.values()) #Checking for next best\n\n if len(available_category)>0:\n for my_index, label in available_category.items():\n if label == best_available_score:\n return my_index\n\n if check_possibilty == False:\n return \"null\"\n\n def score_check(self, category, dice, scorecard): #For current score\n\n current_score = Scorecard()\n current_score.scorecard = scorecard.scorecard.copy()\n current_score.Categories = copy.deepcopy(scorecard.Categories)\n current_score.Numbers = scorecard.Numbers.copy()\n current_score.record(category,dice)\n return current_score.scorecard[category]\n\n def score_category(self, set_of_scores, dice, scorecard): #For the given set of scoring categories\n\n set_of_categories = {}\n for next_best_category in set_of_scores:\n set_of_categories[next_best_category] = self.score_check(next_best_category, dice, scorecard)\n\n best_available_score = max(set_of_categories.values())\n if len(set_of_categories)>0:\n for my_index, label in set_of_categories.items():\n if label == best_available_score:\n return my_index\n\n#====================================== Score category priority List ======================================#\n\n def prioritize_score(self, dice, scorecard, my_val): #Prioprity based on decreasing order of obtainable score\n\n if \"quintupulo\" not in scorecard.scorecard and self.assign_category[\"quintupulo\"] == my_val:\n return \"quintupulo\"\n\n elif \"pupusa de queso\" not in scorecard.scorecard and self.assign_category[\"pupusa de queso\"] == my_val:\n return \"pupusa de queso\"\n\n elif \"elote\" not in scorecard.scorecard and self.assign_category[\"elote\"] == my_val:\n return \"elote\"\n\n elif \"seises\" not in scorecard.scorecard and self.assign_category[\"seises\"] == my_val:\n return \"seises\"\n\n elif \"pupusa de frijol\" not in scorecard.scorecard and self.assign_category[\"pupusa de frijol\"] == my_val:\n return \"pupusa de frijol\"\n\n elif \"triple\" not in scorecard.scorecard and self.assign_category[\"triple\"] == my_val:\n return \"triple\"\n\n elif \"cuadruple\" not in scorecard.scorecard and self.assign_category[\"cuadruple\"] == my_val:\n return \"cuadruple\"\n\n elif \"cincos\" not in scorecard.scorecard and self.assign_category[\"cincos\"] == my_val:\n return \"cincos\"\n\n elif \"cuatros\" not in scorecard.scorecard and self.assign_category[\"cuatros\"] == my_val:\n return \"cuatros\"\n\n elif \"treses\" not in scorecard.scorecard and self.assign_category[\"treses\"] == my_val:\n return \"treses\"\n\n elif \"doses\" not in scorecard.scorecard and self.assign_category[\"doses\"] == my_val:\n return \"doses\"\n\n elif \"unos\" not in scorecard.scorecard and self.assign_category[\"unos\"] == my_val:\n return \"unos\"\n\n else:\n return \"null\"\n\n#====================================== Game over ======================================#","sub_path":"shettypr-a3-master/part2/ZacateAutoPlayer.py","file_name":"ZacateAutoPlayer.py","file_ext":"py","file_size_in_byte":16303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"631535311","text":"from tool.runners.python import SubmissionPy\nimport numpy as np\n\n\ndef print_grid(grid):\n print(\"********* BEGINNING *********\")\n int_to_char = {0: \" \", 1: \"#\", 2: \"|\", 3: \"~\", 10: \"o\"}\n for line in grid:\n for c in line[494:508]:\n print(int_to_char[c], end=\"\")\n print()\n print(\"************ END ***********\")\n print()\n\n\nclass ThomasSubmission(SubmissionPy):\n def run(self, s):\n lines = s.splitlines()\n clays = []\n min_x = float(\"inf\")\n max_x = float(\"-inf\")\n min_y = float(\"inf\")\n max_y = float(\"-inf\")\n\n for line in lines:\n first, second = line.split(\", \")\n width_pos = int(first[2:])\n length_dir = second[0]\n length_from, length_to = second[2:].split(\"..\")\n length_from = int(length_from)\n length_to = int(length_to)\n clays.append((width_pos, length_dir, length_from, length_to))\n if length_dir == \"x\":\n max_x = max(max_x, length_from, length_to)\n min_x = min(min_x, length_from, length_to)\n max_y = max(max_y, width_pos)\n min_y = min(min_y, width_pos)\n else:\n max_y = max(max_y, length_from, length_to)\n max_x = max(max_x, width_pos)\n min_y = min(min_y, length_from, length_to)\n min_x = min(min_x, width_pos)\n\n grid = np.zeros((max_y + 2, max_x + 2))\n for width_pos, length_dir, length_from, length_to in clays:\n if length_dir == \"x\":\n grid[width_pos, length_from : length_to + 1] = 1\n else:\n grid[length_from : length_to + 1, width_pos] = 1\n\n y, x = 0, 500\n stack = [(y, x)]\n while len(stack):\n y, x = stack.pop()\n if y > max_y:\n continue\n if grid[y + 1][x] in [0, 2]:\n grid[y][x] = 2\n stack.append((y + 1, x))\n continue\n else:\n fill_left = x\n while grid[y][fill_left] in [0, 2] and grid[y + 1][fill_left] in [1, 3]:\n grid[y][fill_left] = 2\n fill_left -= 1\n fill_right = x\n while grid[y][fill_right] in [0, 2] and grid[y + 1][fill_right] in [\n 1,\n 3,\n ]:\n grid[y][fill_right] = 2\n fill_right += 1\n if grid[y][fill_left] == 1 and grid[y][fill_right] == 1:\n grid[y][fill_left + 1 : fill_right] = 3\n stack.append((y - 1, x))\n continue\n if grid[y + 1][fill_left] == 0:\n stack.append((y, fill_left))\n if grid[y + 1][fill_right] == 0:\n stack.append((y, fill_right))\n\n # import matplotlib.pyplot as plt\n # plt.imsave(\"test.png\", grid)\n\n return np.sum(grid[min_y : max_y + 1, :] == 3)\n\n","sub_path":"day-17/part-2/thomas.py","file_name":"thomas.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"427142784","text":"from helpers.node import Node\n\n\nclass AStarNode(Node):\n def __init__(self, board, parent, token, **kwargs):\n super().__init__(board, parent, token, **kwargs)\n\n self.f = kwargs.get('f', 0)\n self.g = kwargs.get('g', 0)\n self.h = kwargs.get('h', 0)\n\n def __lt__(self, other):\n \"\"\"\n Verifies which one of the nodes is considered smaller than the other. Used when sorting the list of\n possibilities by the smaller f(n).\n\n :param AStarNode other: Other Node\n :return: The smaller node.\n \"\"\"\n # flattens multi-array board to 1D array\n flattened_board = self.board.board.flatten()\n flattened_other = other.board.board.flatten()\n\n if self.board.size != other.board.size:\n raise ValueError('Boards should be the same size to compare.')\n\n if self.f < other.f:\n return True\n elif self.f > other.f:\n return False\n else: # if f(n) is a tie, evaluate first white token(s)\n for original_board, other_board in zip(flattened_board, flattened_other):\n if original_board < other_board:\n return True\n elif other_board < original_board:\n return False\n\n return True\n","sub_path":"helpers/h_node.py","file_name":"h_node.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"131395740","text":"def dashes(word):\n if word == '':\n return ''\n result = ''\n for ch in word:\n result += ch + '-'\n return result[:-1]\n\ndef full_name(name):\n index = name.find(\",\")\n last_name = name[:index]\n first_name = name[index+2:]\n return first_name.capitalize() + ' ' + last_name.capitalize()\n\ndef is_num(num_string):\n if num_string == '':\n return False\n if num_string[0] == '-':\n num_string = num_string[1:]\n num_string = num_string.replace('.', '', 1)\n num_string = num_string.replace(',', '', len(num_string))\n return num_string.isdigit()\n\n\ndef underscored(string):\n '''\n aStringThatLooksLikeThis => a_string_that_looks_like_this\n '''\n if string == '':\n return ''\n else:\n result = ''\n for ch in string:\n if ch.isupper():\n result += '_' + ch.lower()\n else:\n result += ch\n return result\n\ndef phone_nums(filename):\n name = open(filename, 'r')\n newlist = []\n for line in name:\n word = line.split('-')\n print(word)\n if len(word[0]) == 3 and word[0].isdigit() and \\\n len(word[1]) == 3 and word[1].isdigit() and \\\n len(word[2].strip()) == 4 and word[2].isdigit():\n newlist.append(word[0]+'-'+word[1]+'-'+word[2])\n print(newlist)\n return newlist\n\ndef separator(string1, sep):\n temp = string1.split() # if ? was passed in for a?trtew?asdf?re? --> [a,trtew,asdf,re]\n for i in range(len(temp)):\n if i != len(temp)-1:\n temp[i] += sep\n else:\n break\n newString = ''\n return newString.join(temp)\n\ndef main():\n # print(dashes('dog')) # should prin d-o-g\n #\n # print(full_name('deeran, cody'))# should print Cody Deeran\n #\n # print(is_num('3442424244324234')) # TRUE\n # print(is_num('-3442424244324234')) # TRUE\n # print(is_num('3AA2A24244324234')) # FALSE\n # print(is_num('1.00')) #TRUE\n # print(is_num('1,000')) #TRUE\n # print(is_num('1,000,000,000')) #TRUE\n # print(is_num('1,000,000')) #TRUE\n # print(is_num('-1,000,000,000,000,000,000,000,000,000,000.00')) #TRUE\n #\n #\n # newlist = ['Arizona', 'California', 'New Mexico']\n # newlist.append('Utah')\n # newlist.insert(0,'Oregon')\n # # newlist.insert(len(newlist)/2, 'Oregon') # Insert into middle\n # for i in range(len(newlist)):\n # newlist[i] = newlist[i].lower()\n # print(newlist[i])\n # i = 0\n # while i < len(newlist):\n # newlist[i] = newlist[i].upper()\n # print(newlist[i])\n # i += 1\n # newlist.pop(0)\n # newlist.pop(len(newlist)-1)\n # for i in range(len(newlist)):\n # print(newlist[i])\n\n # list1 = [1,2,3,4,5]\n # list2 = [6,7,8,9,10]\n # result = []\n # for i in range(len(list1)):\n # result.append(list1[i] + list2[i])\n # print(result[i])\n\n # print('aStringThatLooksLikeThis --> ' + underscored('aStringThatLooksLikeThis'))\n\n x = 2.0\n day = \"8\"\n # print(str((int(day) * int(x)) % 3))\n # print(str(5/2) + ' - ' + str(5//2) + ' = ' + str((5/2) - (5//2)))\n #print(('Groot!' + str(12))*2)\n\n # sum = 0\n # for i in range(0,16):\n # if i % 2 == 0:\n # sum += i\n # print('Sum of 0 to 16 evens is:', sum)\n\n\n #print(phone_nums('phone_nums.txt'))\n print(separator('I heart Rocket','---'))\n\nif __name__ == '__main__':\n main()\n","sub_path":"final/demo7.py","file_name":"demo7.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"232225910","text":"# -*- coding: utf-8 -*-\n# author: jinwilliam\n\nfrom taskqueue import tqueue as pq\nimport time\n\nclass producer(object):\n \"\"\"producer\n\n \"\"\"\n def __init__(self):\n print('producer loaded.')\n\n def init(self):\n print('producer init.')\n return pq.init()\n\n def monitor(self):\n print('producer start to monitor.')\n while True:\n time.sleep(1)\n print(time.time())\n pq.push('echo ' + str(time.time())) \n\n\nproducer = producer()\n\n\nif __name__ == '__main__':\n producer.init()\n producer.monitor()\n","sub_path":"core/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"635504107","text":"'''\n 문제설명\n 리트코드 819 가장 흔한 단어\n 금지된 단어를 제외한 가장 흔하게 등장하는 단어 출력. 대소문자 구분 없고 구두점 무시.\n 해결전략\n 입력값에 대한 전처리를 위해 정규식을 이용한다. \\w는 단어 문자를 뜻하며 ^는 not을 의미한다. \n 따라서 사용된 정규식은 단어 문자가 아닌 모든 문자를 공백으로 치환한다는 의미이다. \n 그리고 소문자로 변환하고 공백을 기준으로 분리한다. 이 중 금지된 단어를 제외하고 리스트 컴프리핸션으로 words에 할당한다. \n 가장 많이 사용된 단어를 추출하기 위해 Counter 객체를 사용한다. \n most_common() 메소드는 데이터 개수가 많은 순으로 정렬된 배열을 리턴한다. 인���로 숫자를 넘기면 그 숫자만큼 리턴한다.\n 여기서 리턴값은 (단어, 빈도)이므로 단어를 인덱싱으로 선택한다.\n'''\nclass Solution(object):\n def mostCommonWord(self, paragraph, banned):\n words = [word for word in re.sub(r'[^\\w]', ' ', paragraph)\n .lower().split() \n if word not in banned]\n counts = collections.Counter(words)\n return counts.most_common(1)[0][0]\n","sub_path":"week5/HongheeLee/LeetCode_819_210130.py","file_name":"LeetCode_819_210130.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"254735376","text":"from datetime import datetime\n\nfrom django.http.response import HttpResponseRedirect\nfrom django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom matplotlib.sphinxext.mathmpl import latex_math\nfrom .forms import ReviewForm\nfrom django.core.urlresolvers import reverse\n\nfrom .models import Review,Wine\n# Create your views here.\n\ndef review_list(request):\n latest_review_list = Review.objects.order_by('-pub_date')[:9]\n context = {'latest_review_list':latest_review_list}\n return render(request,'reviews/review_list.html',context)\n\ndef review_detail(request,review_id):\n review= get_object_or_404(Review,pk=review_id)\n return render(request,'reviews/review_detail.html',{'review':review})\n\ndef wine_list(request):\n wine_list= Wine.objects.order_by('-name')\n context = {'wine_list':wine_list}\n return render(request,'reviews/wine_list.html',context)\n\ndef wine_detail(request,wine_id):\n wine = get_object_or_404(Wine,pk=wine_id)\n return render(request,'reviews/wine_detail.html',{'wine':wine})\n\ndef add_review(request, wine_id):\n wine = get_object_or_404(Wine,pk=wine_id)\n form = ReviewForm(request.POST)\n if form.is_valid():\n rating = form.cleaned_data['rating']\n comment = form.cleaned_data['comment']\n user_name = form.cleaned_data['user_name']\n review = Review()\n review.wine = wine\n review.user_name = user_name\n review.rating = rating\n review.comment = comment\n review.pub_date = datetime.datetime.now()\n review.save()\n #return HttpResponseRedirect(reverse('reviews:wine_detail',args=(wine.id,)))\n return HttpResponseRedirect(reverse('reviews:wine_detail', args=(wine.id,)))\n\n return render(request,'reviews/wine_detail.html',{'wine':wine,'form':form})\n\n","sub_path":"reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"202495918","text":"import random\nimport races\nimport jobs\n\nclass livingThing:\n r = races.races()\n j = jobs.jobs()\n alive = True\n gender = 0 #0 = Male, #1 = Female\n attack = 0\n defense = 0\n maxHealth = 0\n health = 0\n maxMana = 0\n mana = 0\n\n def getGender(self):\n return self.gender;\n\n def isAlive(self):\n return self.alive\n\n def getMaxHealth(self):\n return self.maxHealth\n\n def getAttack(self):\n return self.attack\n\n def getDefense(self):\n return self.defense\n\n def heal(self, hp):\n if self.health + hp > self.maxHealth:\n self.health = self.maxHealth\n else:\n self.health = self.health + hp\n\n def hurt(self, pain):\n if self.health - pain < 0:\n self.health = 0\n self.alive = False\n else:\n self.health = self.health - pain\n\n def attackOther(self, target):\n strike = random.randint(0,20)\n if(strike > target.getDefense()):\n target.hurt(self.attack)\n\n def getStats(self):\n print(\"Alive: \"+str(self.alive)+\"\\nHealth: \" + str(self.health)+\"/\"+str(self.maxHealth)+\"\\nAttack: \"+str(self.attack)+\"\\nDefense: \"+str(self.defense))\n\n\n\n\nclass hero(livingThing):\n\n job = \"\"\n race = {}\n def __init__(self, ra = None, jo = None, tMaxHealth = None, tAttack = None, tDefense = None):\n alive = True\n j = jobs.jobs()\n r = races.races()\n if ra is not None:\n self.race = ra\n else:\n self.race = r.getRandomRace(random.randint(0,2))\n if jo is not None:\n self.job = jo\n else:\n self.job = j.getRandomJob(random.randint(0,1))\n\n if tMaxHealth is not None:\n self.maxHealth = tMaxHealth + j.jobHPBonus(self.job) + r.racialHPBonus(self.race)\n else:\n self.maxHealth = 10 + j.jobHPBonus(self.job) + r.racialHPBonus(self.race)\n self.health = self.maxHealth\n if tAttack is not None:\n self.attack = tAttack + j.jobAttackBonus(self.job) + r.racialAttackBonus(self.race)\n else:\n self.attack = 3 + j.jobAttackBonus(self.job) + r.racialAttackBonus(self.race)\n if tDefense is not None:\n self.defense = tDefense + j.jobDefenseBonus(self.job) + r.racialDefenseBonus(self.race)\n else:\n self.defense = 3 + j.jobDefenseBonus(self.job) + r.racialDefenseBonus(self.race)\n if self.defense > 19:\n self.defense = 19\n self.gender = random.randint(0,1)\n\n def getRace(self):\n return self.race\n\n def getJob(self):\n return self.job\n\n def setAttack(self):\n r = races.races()\n j = jobs.jobs()\n\n\n def createChild(self, parent):\n p1Job = self.getJob()\n p2Job = parent.getJob()\n p1Race = self.getRace()\n p2Race = parent.getRace()\n #Initializes and creates inherited race\n race = {}\n race[\"Human\"] = 100*(p1Race[\"Human\"]/200 + p2Race[\"Human\"]/200)\n race[\"Elf\"] = 100*(p1Race[\"Elf\"]/200 + p2Race[\"Elf\"]/200)\n race[\"Orc\"] = 100*(p1Race[\"Orc\"]/200 + p2Race[\"Orc\"]/200)\n jobNum = random.randint(0,3)\n job = \"\"\n if jobNum == 0:\n job = p1Job\n elif jobNum == 1:\n job = p2Job\n else:\n j = jobs.jobs()\n job = j.getRandomJob(random.randint(0,3))\n maxHealth = (self.getMaxHealth() + parent.getMaxHealth())/2\n attack = (self.getAttack() + parent.getAttack())/2\n defense = (self.getDefense() + parent.getDefense())/2\n return hero(race, job, maxHealth, attack, defense)\n\n\n def getStats(self):\n print(\"Alive: \"+str(self.alive)+\"\\nRace: \"+str(self.race)+\"\\nGender: \"+str(self.gender)+\"\\nJob: \"+str(self.job)+\"\\nHealth: \" + str(self.health)+\"/\"+str(self.maxHealth)+\"\\nAttack: \"+str(self.attack)+\"\\nDefense: \"+str(self.defense))\n","sub_path":"livingThing.py","file_name":"livingThing.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"474814370","text":"'''\nStatement\nThe text is given in a single line. For each word of the text count the number of its occurrences before it.\n\nExample input\none two one two three two four three\n\nExample output\n0 0 1 1 0 2 0 1\n'''\nnum_dic = {}\narr = input().split()\n\nfor val in arr:\n if val in num_dic.keys():\n num_dic[val] += 1\n print(num_dic[val], end=\" \")\n\n else:\n num_dic[val] = 0\n print(num_dic[val], end=\" \")\n","sub_path":"Python_Challenge_115/A/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"106953297","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\nimport MySQLdb\n\nimport happybase\n\nreq_count = 1000\n\n\nclass FinalitemPipeline(object):\n\n def __init__(self):\n # self.conn1 = MySQLdb.connect(\n # host='127.0.0.1', port=3306,\n # user='root', password='123456', charset='utf8', db='spider'\n # ) # mysql 连接\n\n self.conn2 = happybase.Connection(host='192.168.43.195', port=9090, autoconnect=True, table_prefix='finalitems')\n # pool = happybase.ConnectionPool(size=3, host='192.168.43.195', port=9090,\n # table_prefix='myproject_hw') # 设置连接池 # self.conn2 = happybase.Connection(host=\"hadoop1.hxd.com\", port=50070, autoconnect=True)\n # with pool.connection() as self.conn2: # 建立网络连接\n self.conn2.open()\n families = {\n \"common\": dict(),\n \"uncommon\": dict(),\n }\n self.conn2.create_table('zp', families) # 建表\n self.table = self.conn2.table('zp') # 创建表实例\n\n def process_item(self, item, spider):\n self.save(item)\n return item\n\n def save(self, item):\n global req_count\n\n # 从mysql数据库查询条数[目前只能想到这个笨方法]\n # req_count = 'select count(id) from finalitems'\n # if int(req_count) <= 1000:\n # print(req_count, '+++++++++++++++++++++++++++++++')\n # sql = 'insert into finalitems(positionName,companyFullName,salary,jobNature,workYear,education,city,positionAdvantage,companySize,district,businessZones)values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'\n # self.conn1.cursor().execute(sql, [item['positionName'], item['companyFullName'], item['salary'],\n # item['jobNature'], item['workYear'], item['education'], item['city'],\n # item['positionAdvantage'], item['companySize'], item['district'],\n # item['businessZones']])\n # self.conn1.commit()\n # else:\n # print(req_count, '+++++++++++++++++++++++++++++')\n\n print(req_count,item['city'], '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n self.table.put(item['city'] + item['positionName'] + str(req_count), # rowkey\n {'common:positionName': item['positionName'],\n 'common:companyFullName': item['companyFullName'],\n 'common:salary': item['salary'],\n 'common:jobNature': item['jobNature'],\n 'common:workYear': item['workYear'],\n 'common:education': item['education'],\n 'common:city': item['city'],\n # # common 展示的数据\n 'uncommon:positionAdvantage': item['positionAdvantage'],\n 'uncommon:companySize': item['companySize'],\n # 'uncommon:businessZones': item['businessZones'],\n }) # uncommon 非展示的数据入库\n print('haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n req_count = req_count + 1\n print('+++++ahhhhhhhhhhh++++++++++++')\n","sub_path":"Scrapy/finalitem/finalitem/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"257498435","text":"from __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nfrom datetime import datetime\nimport json\nimport os\n\nimport librosa\nimport numpy as np\nimport tensorflow as tf\n\nfrom wavenet import WaveNetModel, mu_law_decode, mu_law_encode, audio_reader\n\nSAMPLES = 16000\nTEMPERATURE = 1.0\nLOGDIR = './logdir'\nWAVENET_PARAMS = './wavenet_params.json'\nSAVE_EVERY = None\nSILENCE_THRESHOLD = 0.1\n\n\ndef get_arguments():\n def _str_to_bool(s):\n \"\"\"Convert string to bool (in argparse context).\"\"\"\n if s.lower() not in ['true', 'false']:\n raise ValueError('Argument needs to be a '\n 'boolean, got {}'.format(s))\n return {'true': True, 'false': False}[s.lower()]\n\n def _ensure_positive_float(f):\n \"\"\"Ensure argument is a positive float.\"\"\"\n if float(f) < 0:\n raise argparse.ArgumentTypeError(\n 'Argument must be greater than zero')\n return float(f)\n\n parser = argparse.ArgumentParser(description='WaveNet generation script')\n parser.add_argument(\n 'checkpoint', type=str, help='Which model checkpoint to generate from')\n parser.add_argument(\n '--samples',\n type=int,\n default=SAMPLES,\n help='How many waveform samples to generate')\n parser.add_argument(\n '--temperature',\n type=_ensure_positive_float,\n default=TEMPERATURE,\n help='Sampling temperature')\n parser.add_argument(\n '--logdir',\n type=str,\n default=LOGDIR,\n help='Directory in which to store the logging '\n 'information for TensorBoard.')\n parser.add_argument(\n '--wavenet_params',\n type=str,\n default=WAVENET_PARAMS,\n help='JSON file with the network parameters')\n parser.add_argument(\n '--wav_out_path',\n type=str,\n default=None,\n help='Path to output wav file')\n parser.add_argument(\n '--save_every',\n type=int,\n default=SAVE_EVERY,\n help='How many samples before saving in-progress wav')\n parser.add_argument(\n '--fast_generation',\n type=_str_to_bool,\n default=True,\n help='Use fast generation')\n parser.add_argument(\n '--wav_seed',\n type=str,\n default=None,\n help='The wav file to start generation from')\n parser.add_argument(\n '--gc_channels',\n type=int,\n default=None,\n help='Number of global condition embedding channels. Omit if no '\n 'global conditioning.')\n parser.add_argument(\n '--gc_cardinality',\n type=int,\n default=None,\n help='Number of categories upon which we globally condition.')\n parser.add_argument(\n '--gc_id',\n type=int,\n default=None,\n help='ID of category to generate, if globally conditioned.')\n arguments = parser.parse_args()\n if arguments.gc_channels is not None:\n if arguments.gc_cardinality is None:\n raise ValueError(\"Globally conditioning but gc_cardinality not \"\n \"specified. Use --gc_cardinality=377 for full \"\n \"VCTK corpus.\")\n\n if arguments.gc_id is None:\n raise ValueError(\"Globally conditioning, but global condition was \"\n \"not specified. Use --gc_id to specify global \"\n \"condition.\")\n\n return arguments\n\n\ndef write_wav(waveform, sample_rate, filename):\n y = np.array(waveform)\n librosa.output.write_wav(filename, y, sample_rate)\n print('Updated wav file at {}'.format(filename))\n\n\ndef create_seed(filename,\n sample_rate,\n quantization_channels,\n window_size,\n silence_threshold=SILENCE_THRESHOLD):\n audio, _ = librosa.load(filename, sr=sample_rate, mono=True)\n audio = audio_reader.trim_silence(audio, silence_threshold)\n\n quantized = mu_law_encode(audio, quantization_channels)\n cut_index = tf.cond(tf.size(quantized) < tf.constant(window_size),\n lambda: tf.size(quantized),\n lambda: tf.constant(window_size))\n\n return quantized[:cut_index]\n\n\n\n\ndef main():\n args = get_arguments()\n started_datestring = \"{0:%Y-%m-%dT%H-%M-%S}\".format(datetime.now())\n logdir = os.path.join(args.logdir, 'generate', started_datestring)\n with open(args.wavenet_params, 'r') as config_file:\n wavenet_params = json.load(config_file)\n\n sess = tf.Session()\n\n net = WaveNetModel(\n batch_size=1,\n dilations=wavenet_params['dilations'],\n filter_width=wavenet_params['filter_width'],\n residual_channels=wavenet_params['residual_channels'],\n dilation_channels=wavenet_params['dilation_channels'],\n quantization_channels=wavenet_params['quantization_channels'],\n skip_channels=wavenet_params['skip_channels'],\n use_biases=wavenet_params['use_biases'],\n scalar_input=wavenet_params['scalar_input'],\n initial_filter_width=wavenet_params['initial_filter_width'],\n global_condition_channels=args.gc_channels,\n global_condition_cardinality=args.gc_cardinality)\n\n samples = tf.placeholder(tf.int32)\n\n# next_sample = net.predict_proba_incremental(samples, args.gc_id)\n\n sess.run(tf.global_variables_initializer())\n# sess.run(net.init_ops) # TODO\n\n variables_to_restore = {\n var.name[:-2]: var for var in tf.global_variables()\n if not ('state_buffer' in var.name or 'pointer' in var.name)}\n saver = tf.train.Saver(variables_to_restore)\n\n print('Restoring model from {}'.format(args.checkpoint))\n saver.restore(sess, args.checkpoint)\n\n decode = mu_law_decode(samples, wavenet_params['quantization_channels'])\n\n quantization_channels = wavenet_params['quantization_channels']\n if args.wav_seed:\n seed = create_seed(args.wav_seed,\n wavenet_params['sample_rate'],\n quantization_channels,\n net.receptive_field)\n waveform = sess.run(seed).tolist() # TODO\n else:\n # Silence with a single random sample at the end.\n waveform = [quantization_channels / 2] * (net.receptive_field - 1)\n waveform.append(np.random.randint(quantization_channels))\n\n# if args.fast_generation and args.wav_seed:\n # When using the incremental generation, we need to\n # feed in all priming samples one by one before starting the\n # actual generation.\n # TODO This could be done much more efficiently by passing the waveform\n # to the incremental generator as an optional argument, which would be\n # used to fill the queues initially.\n# outputs = [next_sample]\n# outputs.extend(net.push_ops)\n\n# print('Priming generation...')\n# for i, x in enumerate(waveform[-net.receptive_field: -1]):\n# if i % 100 == 0:\n# print('Priming sample {}'.format(i))\n# sess.run(outputs, feed_dict={samples: x}) # TODO\n# print('Done.')\n\n last_sample_timestamp = datetime.now()\n\n\n def create_cached_activation_queues(dilations, # List of dilations\n quantization_channels,\n residual_channels,\n batch_size\n ):\n cached_activation_queues = ()\n shape_invariants = () # TODO\n\n q = tf.zeros([1, batch_size, quantization_channels], tf.float32)\n cached_activation_queues += (q,)\n shape_invariants += (tf.TensorShape([1, batch_size, quantization_channels]),)\n\n for layer_index, dilation in enumerate(dilations):\n q = tf.zeros([dilation, batch_size, residual_channels], tf.float32)\n cached_activation_queues += (q,)\n shape_invariants += (tf.TensorShape([dilation, batch_size, residual_channels]),)\n\n return cached_activation_queues, shape_invariants\n\n def dequeue_cached_activation_queues(queues, dilations):\n acts = ()\n new_queues = ()\n\n e = queues[0][0, :, :]\n new_queues += (queues[0][1:, :, :],)\n\n acts += (e,)\n\n for layer_index, dilation in enumerate(dilations):\n e = queues[1+layer_index][0, :, :]\n new_queues += (queues[1+layer_index][1:, :, :],)\n acts += (e,)\n\n return acts, new_queues\n\n def enqueue_cached_activation_queues(queues, dilations, acts):\n new_queues = ()\n\n new_queues += (tf.concat([queues[0][1:,:,:], tf.expand_dims(acts[0], 0)], 0),)\n\n for layer_index, dilation in enumerate(dilations):\n new_queues += (tf.concat([queues[1+layer_index][1:,:,:], \\\n tf.expand_dims(acts[1+layer_index], 0)], 0),)\n return new_queues\n\n tf_step = tf.constant(0)\n tf_waveform = tf.cast(tf.constant(waveform), tf.int32)\n tf_window = tf.cast(tf.constant([waveform[-1],]), tf.int32)\n cached_activation_queues, queue_si = create_cached_activation_queues(net.dilations,\n net.quantization_channels,\n net.residual_channels,\n net.batch_size)\n\n\n\n c = lambda tf_step, tf_waveform, tf_window, *queues: tf.less(tf_step, args.samples)\n\n def body(tf_step, tf_waveform, tf_window, *queues):\n tf_step = tf.add(tf_step, 1)\n\n cached_activations, new_queues = dequeue_cached_activation_queues(queues, net.dilations)\n\n next_sample_proba, new_cached_activations = net.predict_proba_incremental(tf_window,\n cached_activations, args.gc_id)\n\n queues = enqueue_cached_activation_queues(queues, net.dilations, new_cached_activations)\n\n next_sample = tf.cast(tf.multinomial(tf.log([next_sample_proba]), 1), tf.int32)[0]\n\n return (tf_step,\\\n tf.concat([tf_waveform, next_sample], axis=0),\\\n next_sample) + queues\n\n\n result = tf.while_loop(c,\n body,\n [tf_step, tf_waveform, tf_window] + list(cached_activation_queues),\n shape_invariants = [tf.TensorShape([]), tf.TensorShape([None]),\n tf.TensorShape([1])] + list(queue_si)\n )\n\n waveform = sess.run(result)[1]\n\n # Save the result as an audio summary.\n datestring = str(datetime.now()).replace(' ', 'T')\n writer = tf.summary.FileWriter(logdir)\n tf.summary.audio('generated', decode, wavenet_params['sample_rate'])\n summaries = tf.summary.merge_all()\n summary_out = sess.run(summaries,\n feed_dict={samples: np.reshape(waveform, [-1, 1])}) # TODO\n writer.add_summary(summary_out)\n\n # Save the result as a wav file.\n if args.wav_out_path:\n out = sess.run(decode, feed_dict={samples: waveform}) # TODO\n write_wav(out, wavenet_params['sample_rate'], args.wav_out_path)\n\n print('Finished generating. The result can be viewed in TensorBoard.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"generate0.py","file_name":"generate0.py","file_ext":"py","file_size_in_byte":11092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"242369710","text":"import json\n\nfrom Products.CMFCore.utils import getToolByName\nfrom plone.app.content.browser.interfaces import IFolderContentsView\nfrom plone.app.layout.globals.interfaces import IViewView\nfrom zope.interface import implements\n\nfrom bika.lims import bikaMessageFactory as _\nfrom bika.sanbi.browser.multimage import MultimagesView\nfrom bika.sanbi.interfaces import IBioSpecimenStorage\n\n\nclass AjaxBoxPositions:\n def __init__(self, context, request):\n self.context = context\n self.request = request\n\n def __call__(self):\n form = self.request.form\n uc = getToolByName(self.context, 'uid_catalog')\n bsc = getToolByName(self.context, 'bika_setup_catalog')\n brains = uc(UID=form['uid'])\n box = brains[0].getObject()\n brains = bsc.searchResults(\n portal_type='StorageLocation',\n object_provides = IBioSpecimenStorage.__identifier__,\n inactive_state='active',\n sort_on='sortable_title',\n path={'query': \"/\".join(box.getPhysicalPath()), 'level': 0})\n\n if not brains:\n msg = 'No free storage position. Please select another container.'\n return json.dumps({'error': self.context.translate(_(msg))})\n\n return json.dumps({'uid': brains[0].UID, 'address': brains[0].title})\n\n\nclass BiospecimenMultimageView(MultimagesView):\n implements(IFolderContentsView, IViewView)\n\n def __init__(self, context, request):\n super(BiospecimenMultimageView, self).__init__(context, request)\n self.context = context\n self.request = request\n self.show_workflow_action_buttons = False\n self.title = self.context.translate(_(\"Biospecimen Files\"))\n self.description = \"Different interesting documents, files and \" \\\n \"images to be attached to the biospecimen.\"\n","sub_path":"bika/sanbi/browser/biospecimen/biospecimen.py","file_name":"biospecimen.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"340051553","text":"from os import makedirs, remove, rename\nfrom os.path import join, exists\nfrom subprocess import run\nfrom zipfile import ZipFile\nimport re\n\n# target-name :: (gcc, g++)\nCONFIG = {\n\t'i686': ('i686-w64-mingw32-gcc', 'i686-w64-mingw32-g++'),\n\t'x86_64': ('x86_64-w64-mingw32-gcc', 'x86_64-w64-mingw32-g++'),\n\tNone: ('gcc', 'g++') # revert Makefile changes\n}\n\n# tool-name :: file containing version\nTOOLS = {\n\t'ctrtool': 'main.c',\n\t'makerom': 'user_settings.c'\n}\n\nfor type, (gcc, gpp) in CONFIG.items():\n\tprint('='*100)\n\tprint('>>', 'COMPILE', type)\n\tprint('='*100)\n\tprint()\n\t\n\tfor tool, version_file in TOOLS.items():\n\t\tprint('>>', 'COMPILE', type, tool)\n\t\tprint()\n\t\t\n\t\t# change makefile\n\t\twith open(join(tool, 'Makefile'), 'r', encoding='UTF-8') as file: makefile = file.read().splitlines(True)\n\t\tdef replace(line):\n\t\t\tif line.startswith('CC = '): return 'CC = %s\\n' % gcc\n\t\t\tif line.startswith('CXX = '): return 'CXX = %s\\n' % gpp\n\t\t\treturn line\n\t\tmakefile = [replace(line) for line in makefile]\n\t\twith open(join(tool, 'Makefile'), 'w', encoding='UTF-8') as file: file.write(''.join(makefile))\n\t\t\n\t\t# find version\n\t\twith open(join(tool, version_file), 'r', encoding='UTF-8') as file: srcfile = file.read()\n\t\tversion = re.search('v\\d(\\.\\d+)+', srcfile)[0]\n\t\t\n\t\tif type is not None:\n\t\t\t# clean\n\t\t\tzip = join('build', '%s-%s-win_%s.zip' % (tool, version, type))\n\t\t\tif exists(zip): remove(zip)\n\t\t\t\n\t\t\t# make\n\t\t\trun('make', cwd=tool)\n\t\t\t\n\t\t\t# copy\n\t\t\tmakedirs('build', exist_ok=True)\n\t\t\texe = join('build', tool+'.exe')\n\t\t\tif exists(exe): remove(exe)\n\t\t\trename(join(tool, tool+'.exe'), exe)\n\t\t\twith ZipFile(zip, 'w') as zip: zip.write(exe, arcname=tool+'.exe')\n\t\t\tremove(exe)\n\t\t\n\t\t# clean\n\t\trun('make clean', cwd=tool)\n\t\tprint()\n","sub_path":"build-all.py","file_name":"build-all.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"628498501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 01 09:20:36 2014\n\n@author: nhpnp3\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nel = 21\n# select the desired number of bins in the histogram\nbn = 100\n\n\nmined_fft = np.load(\"FE_results_fft_1test.npy\")\nmined_lin = np.absolute(np.reshape(mined_fft,el**3))/np.mean(np.absolute(mined_fft))\n\ngoali_fft = np.fft.fftn(np.load(\"dat2.npy\"),axes=[0,1,2])\ngoali_lin = np.absolute(np.reshape(goali_fft,el**3))/np.mean(np.absolute(goali_fft))\n\n\nplt.close()\n\ndmin = np.amin([mined_lin,goali_lin])\ndmax = 8 #np.amax([mined_lin,goali_lin])\n\nweight = np.ones_like(mined_lin)/(mined_lin.size)\n\n#plt.subplot(211)\n#plt.plot(mined_lin[1:],'k.')\n#plt.title('MINED FFT Frequencies')\n\nn, bins, patches = plt.hist(mined_lin, bins = bn, histtype = 'step', hold = True,\n range = (dmin, dmax), weights=weight, color = 'white')\nbincenters = 0.5*(bins[1:]+bins[:-1])\nmined_lin, = plt.plot(bincenters,n,'k', linestyle = '-', lw = 0.5)\n\n\n#plt.subplot(212)\n#plt.plot(goali_lin[1:],'k.')\n#plt.title('GOALI FFT Frequencies')\n\nn, bins, patches = plt.hist(goali_lin, bins = bn, histtype = 'step', hold = True,\n range = (dmin, dmax), weights=weight, color = 'white')\nbincenters = 0.5*(bins[1:]+bins[:-1])\ngoali_lin, = plt.plot(bincenters,n,'b', linestyle = '-', lw = 0.5)\n\nplt.legend([mined_lin, goali_lin], [\"MINED FFT response, C3D8\", \"GOALI FFT response, C3D8R\"])\n\nplt.xlabel(\"Normalized frequency-space strain amplitude\")\nplt.ylabel(\"Frequency of occurrence\")\nplt.title(\"Comparison of FFT frequency spectra\")\n","sub_path":"fip_collab/BC_comparison/BC_compare_polycrystal/attempt_9-5-14-1230pm/periodicity_check_v2.py","file_name":"periodicity_check_v2.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"276173942","text":"import sys\n\nfrom models.html_parser import HTMLToTreeParser\n\n\ndef parse_htm_to_tree(file_path):\n html_file = open(file_path, \"r\")\n htm_file_readlines = html_file.readlines()\n html_to_tree_parser = HTMLToTreeParser()\n clean_lines = [l.strip() for l in htm_file_readlines if l.strip()]\n # for line in htm_file_readlines:\n html_to_tree_parser.feed(data=' '.join(clean_lines))\n\n\n return html_to_tree_parser.get_html_tree()\n\n\ndef analize_html(input_origin_file_path, input_other_sample_file_path, node_id=\"make-everything-ok-button\"):\n origin_html_tree = parse_htm_to_tree(input_origin_file_path)\n origin_node = origin_html_tree.find_node_by_id(node_id)\n other_sample_html_tree = parse_htm_to_tree(input_other_sample_file_path)\n other_same_node = other_sample_html_tree.find_nodes_like_input_node(origin_node)\n return other_same_node.get_absolute_path()\n\n\nif __name__ == \"__main__\":\n arg = sys.argv\n print(analize_html(arg[1], arg[2]))\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"390355740","text":"#!/usr/bin/env python\n\n# TODOs:\n# - inserir ProgressDialog ao clicar em cada um dos botoes (ex: juntar PDFs ou separar PDFs).\n# - fazer um interface gráfica para o PDF Highlight\n# OK - inserir a opcao de excluir paginas de um PDF\n# OK - inserir visualizador de PDF\n# OK - inserir a configuracao em json(ex: ultimo diretorio escolhido) \n# OK - inserir os botões (mover para cima ou para baixo) para reajustar a ordem dos arquivos exibidos\n\nimport os, wx, fitz, time, math\nfrom natsort import natsorted\nimport json, sys\nimport wx.lib.sized_controls as sc\nfrom wx.lib.pdfviewer import pdfViewer, pdfButtonPanel\n\n\n###\n# Funcionalidade de PDF VIEWER dentro da UI\n###\nclass PDFViewer(sc.SizedFrame):\n def __init__(self, parent, **kwds):\n super(PDFViewer, self).__init__(parent, **kwds)\n\n paneCont = self.GetContentsPane()\n self.buttonpanel = pdfButtonPanel(paneCont, wx.NewId(),\n wx.DefaultPosition, wx.DefaultSize, 0)\n self.buttonpanel.SetSizerProps(expand=True)\n self.viewer = pdfViewer(paneCont, wx.NewId(), wx.DefaultPosition,\n wx.DefaultSize,\n wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)\n self.viewer.UsePrintDirect = False\n self.viewer.SetSizerProps(expand=True, proportion=1)\n\n # introduce buttonpanel and viewer to each other\n self.buttonpanel.viewer = self.viewer\n self.viewer.buttonpanel = self.buttonpanel\n\n###\n# Funcionalidade de MERGE\n###\nclass PDF():\n\n @staticmethod\n def merge(dir, files, ofile, maxsize=10):\n pdfs_count = 1\n if len(files) > 0:\n # files = [f for f in os.listdir(dir) if f.endswith(\".pdf\")]\n # pip install natsort\n # files = natsorted(files)\n # files = sorted(files)\n print(\"merge : Diretorio: \"+str(dir)+\"\\tTamanho maximo dos arquivos de saida: \"+str(maxsize))\n print(\"\\tArquivos ordenados: \"+str(files))\n result = fitz.open()\n output_pdf = dir+'/'+ofile\n for pdf in files:\n pdfs_count += 1\n with fitz.open(dir+'/'+pdf) as mfile:\n result.insert_pdf(mfile)\n result.save(output_pdf)\n print(\"Arquivos juntados!\")\n output_pdf_size = os.path.getsize(output_pdf)/(1024*1024)\n if output_pdf_size > 0:\n print(\"Tamanho do novo arquivo gerado: %.2f \" %(output_pdf_size) )\n return pdfs_count\n return 0\n\n###\n# Funcionalidade de SPLIT : POR TAMANHO ou POR PAGINAS\n###\n @staticmethod\n def sizeSplit(filename, max_size):\n #filename = 'C:\\\\Users\\\\apsampaio\\\\Downloads\\\\4145916_1.pdf'\n print(\"sizeSplit : arquivo = \"+ str(filename) +\" , tamanho =\"+ str(max_size))\n doc = fitz.open(filename)\n # Verificar tamanho o PDF em MB\n pdf_size = os.path.getsize(filename)/(1024*1024)\n total_pages = len(doc)\n avg_size = pdf_size / total_pages\n #Transformando em MB:\n #avg_size = avg_size/(1024*1024)\n print(\"\\tDocumento '%s' tem %i paginas com tamanho total %.2f MB\" % (doc.name,total_pages,pdf_size))\n print(\"\\t Páginas de tamanho em torno de %.2f MB.\" % (avg_size))\n # exemplo de leitura do documento\n #for page in doc:\n # text = page.getText()\n if pdf_size > max_size:\n avg_step = int(max_size / avg_size)\n pdfs_count = 1\n current_page = 0\n end_page = current_page + avg_step\n out_pdf_size = 0\n while current_page != total_pages:\n if end_page > total_pages:\n end_page = total_pages\n incluir_paginas = str(current_page+1) + \"-\" + str(end_page)\n print(\"\\tProcessando Documento '%s' : Parte %i : pag_inicial = %i : pag_final = %i\" % (doc.name,pdfs_count,current_page, end_page))\n pages = PDF.auxiliar(incluir_paginas) # ajustar os indices começando em zero\n print(\"\\tProcessando Documento : intervalo = %s\" % (pages))\n # tratamento para quando há somente 1 página e ainda é maior que o tamanho máximo\n if current_page == end_page:\n print(\"\\t\\t\\t\\tErro no tamanho máximo %i, pois a pagina %i é maior que isso : %.2f MB\" %(max_size,end_page, out_pdf_size))\n return 0\n #gerando novo pdf\n docout = fitz.open()\n # get the pages\n try : # inserir paginas\n outdoc = fitz.open(filename)\n outdoc.select(pages) # delete all others\n ofile = filename.replace(\".pdf\", \"-{}.pdf\".format(pdfs_count))\n outdoc.ez_save(ofile) # save and clean new PDF\n outdoc.close()\n # verificar se o tamanho do arquivo ainda ficou menor, e pegar menos páginas\n out_pdf_size = os.path.getsize(ofile)/(1024*1024)\n print(\"\\tProcessando Documento : Parte %i : ficou com tamanho de %.2f MB\" % (pdfs_count, out_pdf_size))\n if out_pdf_size > max_size:\n # refazer essa parte do arquivo com menos páginas (metade da qtd de páginas)\n # qtd_digitos = len(str(end_page))\n # tratamento para arquivos com muitas paginas\n #end_page = current_page + int(avg_step/2)\n end_page = int(end_page * 0.95)\n # diminui mais do que deveria\n if end_page < current_page:\n end_page = current_page\n print(end_page)\n #return\n continue\n except Exception as e1: #falha na tentativa\n print(\"\\t\\t\\t\\tErro no processamento com mensagem de erro: \",str(e1))\n break\n #continuar o loop\n current_page = end_page\n end_page = current_page + avg_step\n pdfs_count += 1\n return pdfs_count\n return 0\n\n###\n# Funcionalidade de DELETE PAGES\n###\n #==============================================================================\n # Delimitadores, função auxiliar\n # Input: recebe as páginas iniciando em 1 (como o usuario ve o doc)\n # Retorno: lista de paginas iniciando em 0 (como o fitz ve o doc)\n #==============================================================================\n @staticmethod\n def auxiliar(data):\n #def auxiliar(self, data):\n delimiters = \"\\n\\r\\t,;\"\n for d in delimiters:\n data = data.replace(d, ' ')\n lines = data.split(' ')\n numbers = []\n i = 0\n for line in lines:\n if line == '':\n continue\n elif '-' in line:\n t = line.split('-')\n #numbers += range(int(t[0]), int(t[1]) + 1)\n numbers += range(int(t[0])-1, int(t[1]))\n else:\n #numbers.append(int(line))\n numbers.append(int(line)-1)\n return numbers\n\n @staticmethod\n def pageSplit(filename, pages, ofile):\n print(\"pageSplit : arquivo = \"+filename+\"\\n paginas a serem excluidas: \" + pages+\"\\n arquivo de saida : \"+ofile)\n\n doc = fitz.open(filename)\n excluir_paginas = PDF.auxiliar(pages) # ajustar os indices começando em zero\n incluir_paginas = range(len(doc))\n pages = set(incluir_paginas) - set(excluir_paginas)\n\n # exemplo de leitura de texto do documento\n #for page in doc:\n # text = page.getText()\n\n print(\"\\tDocumento '%s' tem %i paginass.\" % (doc.name, len(doc)))\n print(\"\\t %i Paginas que serao EXCLUIDAS no documento: %s\" % (len(excluir_paginas), str(excluir_paginas)))\n print(\"\\t %i Paginas que VAO FICAR no documento: %s\" % (len(pages), str(pages)))\n\n #gerando novo pdf\n docout = fitz.open()\n\n # get the pages\n try : # inserir paginas\n doc.select(list(pages)) # delete all others\n doc.ez_save(ofile) # save and clean new PDF\n doc.close()\n return len(excluir_paginas)\n except Exception as e1: #falha na tentativa\n print(\"\\t\\tErro no processamento com mensagem de erro: \",str(e1))\n return 0\n\n###\n# Interface grafica\n###\nclass AppFrame(wx.Frame): \n def __init__(self):\n # Init de componentes\n super().__init__(parent=None, title='SEFAZ PDF Utils', size=(530,580))\n panel = wx.Panel(self) \n vbox = wx.BoxSizer(wx.VERTICAL)\n\n #------------\n # Lista de arquivos\n #------------\n self.list = wx.ListCtrl(panel, size=(300,180), style=wx.LC_REPORT)\n self.list.EnableCheckBoxes()\n # Evento: Botao direito na Lista abre o PDF Viewer\n self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_rightclick_list)\n self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_itemselected_list)\n # Adicionar componente na UI\n vbox.Add(self.list, 0, wx.EXPAND)\n\n #------------\n # Texto que descreve o tamanho total\n #------------\n self.text_total_size = wx.TextCtrl(panel, style=wx.TE_READONLY | wx.TE_CENTRE)\n #self.text_ctrl_size.AppendText(\"Tamanho estimado (soma dos arquivos) = \"+ str(f'{tamanhoTotal/(1024*1024):.2f}') +\" MBs\")\n vbox.Add(self.text_total_size, 0, wx.ALL | wx.EXPAND, 5)\n\n #------------\n # Botao para mudar arquivos de posição na lista : Up ou Down + Select All ou Deselect All\n #------------\n hbox_pos = wx.BoxSizer(wx.HORIZONTAL)\n btn_pos_up = wx.Button(panel, label='Up')\n btn_pos_up.Bind(wx.EVT_BUTTON, self.on_press_up)\n hbox_pos.Add(btn_pos_up)\n btn_pos_down = wx.Button(panel, label='Down')\n btn_pos_down.Bind(wx.EVT_BUTTON, self.on_press_down)\n hbox_pos.Add(btn_pos_down)\n btn_pos_select_all = wx.Button(panel, label='Selecionar Todos')\n btn_pos_select_all.Bind(wx.EVT_BUTTON, self.on_press_select_all)\n hbox_pos.Add(btn_pos_select_all)\n btn_pos_select_clear = wx.Button(panel, label='Limpar seleção')\n btn_pos_select_clear.Bind(wx.EVT_BUTTON, self.on_press_select_clear)\n hbox_pos.Add(btn_pos_select_clear)\n vbox.Add(hbox_pos, flag=wx.CENTER)\n\n #------------\n # Diretorio selecionado\n #------------\n # Atualiza a Lista de arquivos e o campo com o tamanho total\n # ler configuracao do arquivo json\n self.arquivo_config = \"config.json\"\n self.dados = dict()\n try:\n with open(self.arquivo_config) as jsonFile:\n self.dados = json.load(jsonFile)\n jsonFile.close()\n if len(self.dados) > 0:\n idir = str(self.dados['diretorio_selecionado'])\n self.atualizarFileListCtrl(diretorio=idir)\n else:\n self.atualizarFileListCtrl(diretorio='.')\n except Exception as e1: #falha\n print(\"\\tErro o carregar arquivo config.json: \",str(e1))\n self.dados['diretorio_selecionado'] = '.' \n self.atualizarFileListCtrl(diretorio='.')\n \n # Diretorio Selecionado\n titulo_box_diretorio = wx.StaticBox( panel, -1, \"Diretorio selecionado\" )\n box_diretorio = wx.StaticBoxSizer( titulo_box_diretorio, wx.VERTICAL )\n # Texto do Diretorio selecionado\n self.text_ctrl_dir = wx.TextCtrl(panel, style=wx.TE_READONLY|wx.TE_WORDWRAP|wx.TE_MULTILINE, size=(-1, 55))\n #self.text_ctrl_dir = wx.TextCtrl(panel, style=wx.TE_READONLY)\n if len(self.dados) > 0:\n idir = str(self.dados['diretorio_selecionado'])\n self.text_ctrl_dir.AppendText(idir)\n else:\n self.text_ctrl_dir.AppendText(\"Clique no botão abaixo para selecionar um diretorio\")\n box_diretorio.Add(self.text_ctrl_dir, 0, wx.ALL | wx.EXPAND, 5)\n # Botao para selecionar Dir\n my_btn_dir = wx.Button(panel, label='Mudar diretorio')\n my_btn_dir.Bind(wx.EVT_BUTTON, self.on_press_dir)\n box_diretorio.Add(my_btn_dir, 0, wx.ALL | wx.CENTER, 5)\n \n vbox.Add( box_diretorio, 0, wx.ALL | wx.EXPAND, 5)\n\n #------------\n # Linha separadora : Processar Arquivo com Checkboxes: merge + tamanho máximo\n #------------\n\n #------------\n # Opções de procesamento\n #------------\n titulo_box_opcoes_processamento = wx.StaticBox( panel, -1, \"Opções de procesamento\" )\n box_opcoes_processamento = wx.StaticBoxSizer( titulo_box_opcoes_processamento, wx.VERTICAL )\n grid_opcoes_processamento = wx.FlexGridSizer( cols=2 )\n # Check boxes\n self.cb_juntar_arquivos = wx.CheckBox(panel, -1, \"Juntar os arquivos selecionados\")\n self.cb_juntar_arquivos.SetValue(True)\n text_ctrl_juntar = wx.TextCtrl(panel)\n text_vazio = wx.StaticText(panel, -1, \"\")\n grid_opcoes_processamento.Add( self.cb_juntar_arquivos, 0, wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n grid_opcoes_processamento.Add( text_vazio, 0, wx.LEFT|wx.RIGHT|wx.TOP, 5 ) # ocupa item vazio\n #grid_opcoes_processamento.Add( text_ctrl_juntar, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n self.cb_tamanho_maximo = wx.CheckBox(panel, -1, \"Gerar arquivos com tamanhos máximos em MB\")\n self.cb_tamanho_maximo.SetValue(True)\n self.text_ctrl_size = wx.TextCtrl(panel)\n self.text_ctrl_size.AppendText(\"10\")\n grid_opcoes_processamento.Add( self.cb_tamanho_maximo, 0,wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n grid_opcoes_processamento.Add( self.text_ctrl_size, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n self.cb_deletar_paginas = wx.CheckBox(panel, -1, \"Deletar páginas do intervalo selecionado\")\n self.text_ctrl_delete = wx.TextCtrl(panel)\n self.text_ctrl_delete.AppendText(\"2-7\")\n grid_opcoes_processamento.Add( self.cb_deletar_paginas, 0, wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n grid_opcoes_processamento.Add( self.text_ctrl_delete, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )\n # Add na interface\n box_opcoes_processamento.Add( grid_opcoes_processamento )\n vbox.Add( box_opcoes_processamento, 0, wx.ALL | wx.EXPAND, 5)\n\n #------------\n # Botão para processar\n #------------\n titulo_box_processar = wx.StaticBox( panel, -1, \"Defina o nome do arquivo de saída\" )\n hbox_processar = wx.StaticBoxSizer( titulo_box_processar, wx.HORIZONTAL )\n #hbox_processar = wx.BoxSizer(wx.HORIZONTAL)\n #texto_processar = wx.StaticText(panel, -1, \"Defina o nome do arquivo de saída: \")\n #hbox_processar.Add(texto_processar)\n self.text_ctrl_ofile = wx.TextCtrl(panel)\n self.text_ctrl_ofile.AppendText(\"_output.pdf\")\n hbox_processar.Add(self.text_ctrl_ofile, 0, wx.ALL | wx.CENTER, 5)\n btn_processar = wx.Button(panel, label='Processar os arquivos selecionados')\n btn_processar.Bind(wx.EVT_BUTTON, self.on_press_processar)\n hbox_processar.Add(btn_processar, 0, wx.CENTER, 5)\n vbox.Add(hbox_processar, 0, wx.ALL | wx.EXPAND | wx.CENTER, 5)\n\n #------------\n # Atualizar tela\n #------------\n panel.SetSizer(vbox) \n self.Show()\n\n###\n# Classe: AppFrame\n# Método para atualizar os arquivos do Diretorio selecionado\n###\n def atualizarFileListCtrl(self, diretorio):\n j = 0\n totalsize = 0\n self.list.ClearAll()\n # Criar campos:\n self.list.InsertColumn(0, 'Nome')\n self.list.InsertColumn(1, 'Extensão')\n self.list.InsertColumn(2, 'Tamanho', wx.LIST_FORMAT_RIGHT)\n self.list.InsertColumn(3, 'Data motificação')\n self.list.SetColumnWidth(0, 250)\n self.list.SetColumnWidth(1, 60)\n self.list.SetColumnWidth(2, 70)\n self.list.SetColumnWidth(3, 110)\n #self.list.InsertItem(0, '..')\n # Exibir arquivos\n files = os.listdir(diretorio)\n files = natsorted(files)\n for i in files:\n (name, ext) = os.path.splitext(i)\n ex = ext[1:]\n # continua somente para inserir aquivo pdf\n if ex not in [\"pdf\", \"PDF\"] :\n continue\n size = os.path.getsize(diretorio+\"/\"+i)\n sec = os.path.getmtime(diretorio+\"/\"+i)\n\n self.list.InsertItem(j, name)\n self.list.SetItem(j, 1, ex)\n self.list.SetItem(j, 2, str(f'{size/(1024*1024):.2f}') + ' MB')\n self.list.SetItem(j, 3, time.strftime('%Y-%m-%d %H:%M', time.localtime(sec)))\n\n if (j % 2) == 0:\n self.list.SetItemBackgroundColour(j, '#e6f1f5')\n j = j + 1\n totalsize += size\n if totalsize > 0:\n self.text_total_size.SetValue(\"Tamanho estimado (soma dos arquivos) = \"+ str(f'{totalsize/(1024*1024):.2f}') +\" MBs\")\n\n###\n# Classe: AppFrame\n# Eventos ao clicar em item com botão esquerdo ou direito na lista de arquivos da Interface grafica\n###\n def on_itemselected_list(self, event):\n select = self.list.GetItemText(event.Index)\n print(\"Capturado click em um item : \"+str(select))\n if self.list.IsItemChecked(event.Index):\n self.list.CheckItem(event.Index,False)\n else:\n self.list.CheckItem(event.Index,True)\n\n def on_rightclick_list(self, event):\n select = self.list.GetItemText(event.Index)\n print(\"Capturado duplo click : \"+str(select))\n #wx.MessageBox('Selecionado item %s' % str(select))\n pdfV = PDFViewer(self, size=(800, 600))\n #pdfV.viewer.UsePrintDirect = False\n dir = self.text_ctrl_dir.GetValue()\n filepath = str(dir)+'/'+str(select)+'.pdf'\n print(\"Tentando abrir PDF Viewer para : \"+str(filepath))\n #pdfV.viewer.LoadFile(r'a path to a .pdf file')\n pdfV.viewer.LoadFile(filepath)\n pdfV.Show()\n\n###\n# Classe: AppFrame\n# Eventos relacionados ao Drag and Drop da lista de arquivos da Interface grafica\n# Código fonte: https://wiki.wxpython.org/How%20to%20create%20a%20list%20control%20with%20drag%20and%20drop%20%28Phoenix%29\n###\n\n\n def on_press_up(self, event):\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando : Mudar posição UP de arquivo selecionado.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n for i in itemschecked:\n if i == 0: \n print(\"\\tPrimeiro item não pode subir mais\")\n continue\n else:\n print(\"\\tTrocar a posição \"+str(i)+\" com o anterior \"+str(i-1))\n # salva os valores do elemento anterior\n nome1 = self.list.GetItemText(i-1)\n ex1 = self.list.GetItemText(i-1, col=1)\n tamanho1 = self.list.GetItemText(i-1, col=2)\n data1 = self.list.GetItemText(i-1, col=3)\n # salva os valores do elemento posterior\n nome2 = self.list.GetItemText(i)\n ex2 = self.list.GetItemText(i, col=1)\n tamanho2 = self.list.GetItemText(i, col=2)\n data2 = self.list.GetItemText(i, col=3)\n # reescreve anterior\n self.list.SetItem(i-1, 0, nome2)\n self.list.SetItem(i-1, 1, ex2)\n self.list.SetItem(i-1, 2, tamanho2)\n self.list.SetItem(i-1, 3, data2)\n # reescreve posterior\n self.list.SetItem(i, 0, nome1)\n self.list.SetItem(i, 1, ex1)\n self.list.SetItem(i, 2, tamanho1)\n self.list.SetItem(i, 3, data1)\n # ajusta itens selecionados\n self.list.CheckItem(i-1,True)\n self.list.CheckItem(i,False)\n\n def on_press_down(self, event):\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando : Mudar posição DOWN de arquivo selecionado.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n for i in itemschecked:\n if i == itemcount-1: \n print(\"\\tUltimo item não pode descer mais\")\n continue\n else:\n print(\"\\tTrocar a posição \"+str(i)+\" com o posterior \"+str(i+1))\n # salva os valores do elemento anterior\n nome1 = self.list.GetItemText(i+1)\n ex1 = self.list.GetItemText(i+1, col=1)\n tamanho1 = self.list.GetItemText(i+1, col=2)\n data1 = self.list.GetItemText(i+1, col=3)\n # salva os valores do elemento posterior\n nome2 = self.list.GetItemText(i)\n ex2 = self.list.GetItemText(i, col=1)\n tamanho2 = self.list.GetItemText(i, col=2)\n data2 = self.list.GetItemText(i, col=3)\n # reescreve anterior\n self.list.SetItem(i+1, 0, nome2)\n self.list.SetItem(i+1, 1, ex2)\n self.list.SetItem(i+1, 2, tamanho2)\n self.list.SetItem(i+1, 3, data2)\n # reescreve posterior\n self.list.SetItem(i, 0, nome1)\n self.list.SetItem(i, 1, ex1)\n self.list.SetItem(i, 2, tamanho1)\n self.list.SetItem(i, 3, data1)\n # ajusta itens selecionados\n self.list.CheckItem(i+1,True)\n self.list.CheckItem(i,False)\n\n def on_press_select_all(self, event):\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando : Selecionar todos os arquivo.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n for i in range(itemcount):\n self.list.CheckItem(i,True)\n\n def on_press_select_clear(self, event):\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando : Limpar seleção de todos os arquivo.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n for i in range(itemcount):\n self.list.CheckItem(i,False)\n\n###\n# Classe: AppFrame\n# Eventos ao clicar nos botoes da Interface grafica\n###\n def on_press_dir(self, event):\n # In this case we include a \"New directory\" button.\n dlg = wx.DirDialog(self, \"Escolha o diretorio:\",\n style=wx.DD_DEFAULT_STYLE\n #| wx.DD_DIR_MUST_EXIST\n #| wx.DD_CHANGE_DIR\n )\n # If the user selects OK, then we process the dialog's data.\n # This is done by getting the path data from the dialog - BEFORE\n # we destroy it.\n if dlg.ShowModal() == wx.ID_OK:\n #print('You selected: %s\\n' % dlg.GetPath())\n self.text_ctrl_dir.ChangeValue(dlg.GetPath())\n # Only destroy a dialog after you're done with it.\n dir = self.text_ctrl_dir.GetValue()\n self.atualizarFileListCtrl(dir)\n # salvar novo diretorio no arquivo de configuracao json\n self.dados['diretorio_selecionado'] = dir\n print(self.dados)\n with open(self.arquivo_config, \"w\") as jsonFile:\n configJSON = json.dumps(self.dados)\n jsonFile.write(configJSON)\n jsonFile.close()\n # retirar janela que pergunta o dir\n dlg.Destroy()\n\n def on_press_merge(self, event):\n dir = self.text_ctrl_dir.GetValue()\n if not os.path.isdir(dir):\n print(\"Nenhum diretorio foi selecionado! \\n: \"+str(dir))\n return\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando : Merge de arquivos selecionados.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n arquivos = []\n for index in itemschecked:\n item = self.list.GetItemText(index)\n ex = self.list.GetItemText(index, col=1)\n file = str(item)+'.'+str(ex)\n print(\"\\tAnalisando item: \"+str(file)) \n # Processar cada arquivo selecionado\n arquivos.append(file)\n if len(arquivos) <= 0:\n print(\"Nenhum arquivo foi selecionado! \\n: \"+str(arquivos))\n return\n # Nome do arquivo de saida\n ofile = self.text_ctrl_ofile.GetValue()\n if len(ofile) <= 0:\n print(\"Nome do arquivo de saida nao foi definido! \\n: \"+str(arquivos))\n return\n # Tamanho deve ser int\n tamanho = int(self.text_ctrl_size.GetValue())\n if tamanho < 1:\n print(\"Tamanho dos arquivos deve ser maior que 1! \\n: \"+str(tamanho))\n return\n print(f'Diretorio: \"{dir}\" | Processando arquivos: \"{arquivos}\"')\n print(f'Arquivo de saida: \"{ofile}\" | Tamanho Máximo: \"{tamanho}\"')\n resposta = PDF.merge(dir, arquivos, ofile,tamanho)\n # Dialog de resposta\n if resposta > 0:\n dlg = wx.MessageDialog(self, 'Arquivos juntados com sucesso: '+str(len(itemschecked)),\n 'Juntar Arquivos',\n wx.OK | wx.ICON_INFORMATION\n #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION\n )\n dlg.ShowModal()\n dlg.Destroy()\n self.atualizarFileListCtrl(dir)\n\n def on_press_size(self, event):\n dir = self.text_ctrl_dir.GetValue()\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando baseado no tamanho.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n for index in itemschecked:\n item = self.list.GetItemText(index)\n ex = self.list.GetItemText(index, col=1)\n file = str(item)+'.'+str(ex)\n print(\"\\tAnalisando item: \"+str(file)) \n # Processar cada arquivo selecionado\n arquivo = dir+\"/\"+file\n # Tamanho deve ser int\n tamanho = int(self.text_ctrl_size.GetValue())\n if not ( os.path.isdir(dir) or os.path.isfile(arquivo) ):\n print(\"Diretorio ou arquivo invalido! \\n: \"+str(arquivo))\n else:\n print(f'Processando arquivo: \"{arquivo}\"')\n resposta = PDF.sizeSplit(arquivo, tamanho)\n # Dialog de resposta\n if resposta > 0:\n dlg = wx.MessageDialog(self, 'Arquivos separados com sucesso: '+str(len(itemschecked)),\n 'Separar Arquivos',\n wx.OK | wx.ICON_INFORMATION\n #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION\n )\n dlg.ShowModal()\n dlg.Destroy()\n self.atualizarFileListCtrl(dir)\n\n def on_press_delete(self, event):\n dir = self.text_ctrl_dir.GetValue()\n itemcount = self.list.GetItemCount()\n itemschecked = [i for i in range(itemcount) if self.list.IsItemChecked(item=i)]\n print('Processando exclusão de páginas do intervalo.')\n #print('Qtd de arquivos disponiveis na lista: ' + str(self.list.GetItemCount())\n print('Qtd de arquivos selecionados: '+str(len(itemschecked)))\n print(\"ItemsChecked: \" + str(itemschecked))\n parte = 0 # usado para o caso de ser selecionado multiplos arquivos\n for index in itemschecked:\n item = self.list.GetItemText(index)\n ex = self.list.GetItemText(index, col=1)\n file = str(item)+'.'+str(ex)\n print(\"\\tAnalisando item: \"+str(file)) \n # Processar cada arquivo selecionado\n arquivo = dir+\"/\"+file\n # Excluindo paginas do intervalo\n excluir_paginas = self.text_ctrl_delete.GetValue()\n if len(excluir_paginas) <= 0:\n print(\"Intervalo das páginas a serem excluidas dos arquivos nao foi definido! \\n: \"+str(excluir_paginas))\n return\n # Nome do arquivo de saida\n ofile = self.text_ctrl_ofile.GetValue()\n # Verifica se há vários arquivos selecionados para colocar um identificador no final\n if len(itemschecked) > 1:\n nome, ext = os.path.splitext(ofile)\n ofile = nome+\"-\"+str(parte)+ext\n print('Arquivo de saida ao deletar paginas será : ' + ofile)\n parte += 1\n output_arquivo = dir+\"/\"+ofile\n if len(ofile) <= 0:\n print(\"Nome do arquivo de saida nao foi definido! \\n: \"+str(ofile))\n return 0\n resposta = PDF.pageSplit(arquivo, excluir_paginas, output_arquivo)\n # Dialog de resposta\n if resposta > 0:\n dlg = wx.MessageDialog(self, 'Paginas excluidas com sucesso: '+str(file)+ '\\nIntervalo excluído: '+str(excluir_paginas),\n 'Excluir paginas',\n wx.OK | wx.ICON_INFORMATION\n #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION\n )\n dlg.ShowModal()\n dlg.Destroy()\n self.atualizarFileListCtrl(dir)\n\n def on_press_processar(self, event):\n if self.cb_juntar_arquivos.GetValue():\n print(\"Item Selecionado : CheckBox Juntar Arquivos\")\n self.on_press_merge(event)\n if self.cb_deletar_paginas.GetValue():\n print(\"Item Selecionado : CheckBox Deletar páginas dos Arquivos\")\n self.on_press_delete(event)\n if self.cb_tamanho_maximo.GetValue():\n print(\"Item Selecionado : CheckBox Tamanho máximo dos Arquivos\")\n # Atualizar o item selecionado somente para o Arquivo gerado (output)\n self.on_press_select_clear(event)\n ofile = self.text_ctrl_ofile.GetValue()\n print(\"ofile : \" + ofile)\n itemcount = self.list.GetItemCount()\n index_ofile = -1\n for i in range(itemcount):\n arquivo = self.list.GetItemText(i) + \".\" + self.list.GetItemText(i, col=1) \n print(\"\\t Arquivo : \" + arquivo + \" : \" + str( (str(arquivo) == str(ofile)) ))\n if str(arquivo) == str(ofile):\n print(\"\\t\\t Achei o index do Arquivo : \" + str(i))\n index_ofile = i\n break\n print(\"Encontrado index_ofile : \"+str(index_ofile))\n if index_ofile >= 0:\n self.list.CheckItem(index_ofile,True)\n self.on_press_size(event)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = AppFrame()\n app.MainLoop()\n","sub_path":"ui_pdf/ui_checkbox.py","file_name":"ui_checkbox.py","file_ext":"py","file_size_in_byte":32164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"485890553","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import login, logout\nfrom qa.models import Question, Answer\nfrom qa.forms import AskForm, AnswerForm\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.contrib.auth.models import AnonymousUser, User\n\n\ndef test(request, *args, **kwargs):\n return HttpResponse('OK')\n\n\ndef paginate(request, qs):\n try:\n limit = int(request.GET.get('limit', 10))\n except ValueError:\n limit = 10\n if limit > 100:\n limit = 10\n\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n raise Http404\n\n paginator = Paginator(qs, limit)\n\n try:\n page = paginator.page(page)\n except EmptyPage:\n page = paginator.page(paginator.num_pages)\n return page, paginator\n\n\ndef question_list(request):\n qs = Question.objects.all()\n qs = qs.order_by('-added_at')\n page, paginator = paginate(request, qs)\n paginator.baseurl = reverse('question_list') + '?page='\n\n return render(request, 'qa/list.html', {\n 'questions': page.object_list,\n 'page': page,\n 'paginator': paginator,\n })\n\n\ndef popular(request):\n qs = Question.objects.all()\n qs = qs.order_by('-rating')\n page, paginator = paginate(request, qs)\n paginator.baseurl = reverse('popular') + '?page='\n\n return render(request, 'qa/list_rating.html', {\n 'questions': page.object_list,\n 'page': page,\n 'paginator': paginator,\n })\n\n\ndef question_detail(request, pk):\n question = get_object_or_404(Question, id=pk)\n\n #answers = question.answer_set.all()\n form = AnswerForm(initial={'question': str(pk)})\n answers = Answer.objects.filter(question_id=pk)\n #answers = answers.get_text()\n return render(request, 'qa/detail.html', {\n 'question': question,\n 'answers': answers,\n 'form': form,\n # 'pk': pk,\n })\n\n\ndef question_ask(request):\n if request.method=='POST':\n form = AskForm(request.POST)\n\n if request.user.is_authenticated():\n pass\n else:\n\n if form.is_valid():\n post = form.save(commit=False)\n post.author = User(id=1)\n post.added_at = timezone.now()\n post.save()\n url = reverse('question_detail', args=[post.id])\n\n return HttpResponseRedirect(url)\n else:\n form = AskForm()\n return render(request, 'qa/ask.html', {'form': form})\n\n\ndef question_answer(request, pk):\n\n if request.method == 'POST':\n '''\n form = AnswerForm(request.POST)\n\n if request.user.is_authenticated():\n pass\n else:\n\n if form.is_valid():\n post = form.save(commit=False)\n post.author = User(id=1)\n post.added_at = timezone.now()\n post.question = Question(id=pk)\n post.save()\n url = reverse('answer_st', args=[pk])\n\n\n return HttpResponseRedirect(url)\n '''\n url = reverse('answer_st', args=[pk])\n return HttpResponseRedirect(url)\n else:\n\n return HttpResponseRedirect('/', args=0)\n\ndef answer_st(request, pk):\n if request.method=='POST':\n form = AnswerForm(request.POST)\n\n if request.user.is_authenticated():\n pass\n else:\n if form.is_valid():\n post = form.save(commit=False)\n post.author = User(id=1)\n #q = Question.objects.filter(id=2)\n post.added_at = timezone.now()\n post.question = Question(id=pk)\n post.save()\n\n return HttpResponseRedirect('/answers/')\n else:\n form = AskForm()\n return render(request, 'qa/answer.html', {'form': form})\n\ndef answer_list(request):\n answ = Answer.objects.all()\n\n page, paginator = paginate(request, answ)\n paginator.baseurl = reverse('answers') + '?page='\n\n return render(request, 'qa/answers.html', {\n 'answ': page.object_list,\n 'page': page,\n 'paginator': paginator,\n })\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"484973600","text":"# from __future__ import print_function\n\nfrom System.Collections.Generic import *\nfrom rpw import revit, DB, UI\n\nfrom pyrevit import forms, script\n\nfrom collections import OrderedDict\nfrom System.Collections.Generic import List\n\nimport re\n\n\n\n\n__doc__ = \"Select by by IFC GUID\"\n__title__ = \"Select by IFC GUID\"\n__author__ = \"Thomas Holth\"\n\nuidoc = revit.uidoc\ndoc = revit.doc\n\n\ndef element_from_ifc_guid(guid_string):\n ifc_param = DB.BuiltInParameter.IFC_GUID\n\n pvp = DB.ParameterValueProvider(DB.ElementId(ifc_param))\n filter_rule = DB.FilterStringRule(\n pvp, DB.FilterStringContains(), guid_string, False)\n epf = DB.ElementParameterFilter(filter_rule)\n\n collector = DB.FilteredElementCollector(doc)\n collector.WherePasses(epf)\n\n # return collector.ToElements()\n\n return collector.FirstElement()\n\n\nguids = forms.ask_for_string(\n prompt=\"Enter IFC GUID\",\n title=\"IFC GUID\"\n)\n\n# print(dir(forms))\n\nif guids:\n elements = []\n output = script.get_output()\n\n for guid in re.split('[;,]', guids):\n guid = guid.strip()\n\n if guid == '':\n continue\n\n found = element_from_ifc_guid(guid)\n\n id = None\n\n if found:\n id = output.linkify(found.Id)\n elements.append(found)\n\n print(\"'{}': {}\".format(guid, id))\n\n element_id_collection = List[DB.ElementId]()\n\n for element in elements:\n\n element_id_collection.Add(element.Id)\n\n # uidoc.Selection.SetElementIds(element_id_collection)\n","sub_path":"PyRevit Extension/Antler.extension/Antler.tab/Selection.panel/FindByGUID.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"59953505","text":"import xml.etree.ElementTree as ET\nfrom xml.dom import minidom\n\ndef prettify(elem):\n rough = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough)\n return reparsed.toprettyxml(indent=\" \")\n\n\ntree = ET.parse('esplanner.xml')\nroot = tree.getroot()\nnewdoc = ET.Element('newRoot')\n\nfor child in root:\n for day in child:\n if day.get('year'):\n day.tag = child.tag\n nTag = '_y'+day.get('year')\n if newdoc.find(nTag):\n newdoc.find(nTag).append(day)\n else:\n b = ET.Element(nTag)\n b.append(day)\n newdoc.append(b)\n\n\nf = open('output.xml', 'w')\nf.write(prettify(newdoc))\nf.close\n\n\n\n\n","sub_path":"esplanner.py","file_name":"esplanner.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"558239204","text":"import media\nimport fresh_tomatoes\n\ntoy_story = media.Movie(\"Toy Story\",\"The story of a boy whose toys come to life\",\n \"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\",\n \"https://www.youtube.com/watch?v=SgoiKLFBA3Q\")\n\nannable_two = media.Movie(\"Annabelle 2\",\"Former toy maker Sam Mullins and his wife, Esther, are happy to welcome a nun and six orphaned girls into their California farmhouse.\",\n \"https://upload.wikimedia.org/wikipedia/en/0/08/Annabelle_Creation.jpg\",\n \"https://www.youtube.com/watch?v=EjZkJa6Z-SY\")\n\navatar_movie = media.Movie(\"Avatar\",\"On the lush alien world of Pandora live the Na'vi, beings who appear primitive but are highly evolved.\",\n \"https://www.movieposter.com/posters/archive/main/98/MPW-49246\",\n \"https://www.youtube.com/watch?v=d1_JBMrrYw8\")\n \nmovies = [toy_story, annable_two, avatar_movie]\n\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"media_centre.py","file_name":"media_centre.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"341369820","text":"# coding=utf-8\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.tabbedpanel import TabbedPanelHeader\nfrom kivy.properties import NumericProperty, StringProperty, ObjectProperty\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.logger import Logger\nfrom kivy.clock import Clock\nfrom .. import roboprinter\nimport math\n\n\nclass PrinterStatusTab(TabbedPanelHeader):\n \"\"\"\n Represents the Printer Status tab header and dynamic content\n \"\"\"\n pass\n\n\nclass PrinterStatusContent(GridLayout):\n \"\"\"\n \"\"\"\n\n filename = StringProperty(\"\")\n status = StringProperty(\"[ref=status][/ref]\")\n extruder_one_temp = NumericProperty(0)\n extruder_one_max_temp = NumericProperty(200)\n extruder_two_max_temp = NumericProperty(200)\n extruder_two_temp = NumericProperty(0)\n bed_max_temp = NumericProperty(200)\n bed_temp = NumericProperty(0)\n progress = StringProperty('')\n\n def update(self, dt):\n temps = roboprinter.printer_instance._printer.get_current_temperatures()\n current_data = roboprinter.printer_instance._printer.get_current_data()\n filename = current_data['job']['file']['name']\n is_operational = current_data['state']['flags']['operational']\n is_ready = current_data['state']['flags']['ready']\n is_printing = current_data['state']['flags']['printing']\n is_paused = current_data['state']['flags']['paused']\n progress = current_data['progress']['completion']\n status = current_data['state']['text']\n #TODO: REFACTOR because the following variable assignments WILL fail when we starting implementing lcd_large.kv since these widgets wont exists for that iteration\n left_of_extruder = self.ids.left_of_extruder_status\n right_of_extruder = self.ids.right_of_extruder_status\n e_children = left_of_extruder.children + right_of_extruder.children\n\n self.filename = filename.replace('.gcode','') if filename else 'No File Loaded'\n\n if is_printing and progress is None or is_printing and progress < 1:\n self.progress = '[size=30]Preparing[/size]'\n elif (is_printing and progress >= 1) or (is_paused and progress >=1):\n p_transformed = int(progress)\n self.progress = '[size=50]{}%[/size]'.format(p_transformed)\n else:\n self.progress = ''\n\n if progress == 100:\n roboprinter.printer_instance._printer.unselect_file()\n\n if 'tool0' in temps.keys():\n self.extruder_one_temp = temps['tool0']['actual']\n self.extruder_one_max_temp = temps['tool0']['target']\n else:\n self.extruder_one_temp = 0\n self.extruder_one_max_temp = 0\n\n if 'bed' in temps.keys():\n self.bed_temp = temps['bed']['actual']\n self.bed_max_temp = temps['bed']['target']\n else:\n self.bed_temp = 0\n self.bed_max_temp = 0\n\n if 'tool1' in temps.keys():\n self.extruder_two_temp = temps['tool1']['actual']\n self.extruder_two_max_temp = temps['tool1']['target']\n else:\n self.extruder_two_temp = 0\n self.extruder_two_max_temp = 0\n\n if is_printing and len(e_children) == 0:\n left_of_extruder.add_widget(StartPauseButton())\n right_of_extruder.add_widget(CancelButton())\n elif len(e_children) > 0 and not is_printing and not is_paused:\n left_of_extruder.clear_widgets()\n right_of_extruder.clear_widgets()\n\n def start_print(self):\n roboprinter.printer_instance._printer.start_print()\n\nclass StartPauseButton(Button):\n def __init__(self, **kwargs):\n super(StartPauseButton, self).__init__(**kwargs)\n # Clock.schedule_interval(self.sync_with_devices, .1)\n Clock.schedule_interval(self.colors, .1)\n\n def toggle_pause_print(self):\n roboprinter.printer_instance._printer.toggle_pause_print()\n # if self.text == 'Start':\n # self.text = 'Pause'\n # else:\n # self.text = 'Start'\n\n def sync_with_devices(self, dt):\n '''makes sure that button's state syncs up with the commands that other devices push to the printer '''\n is_paused = roboprinter.printer_instance._printer.is_paused()\n if is_paused and self.text == 'Pause':\n self.text = 'Start'\n elif not is_paused and self.text == 'Start':\n self.text = 'Pause'\n\n def colors(self, dt):\n '''updates the color of the button based on Start or Pause state. Green for Start'''\n is_paused = roboprinter.printer_instance._printer.is_paused()\n if is_paused:\n self.background_normal = 'Icons/button_start.png'\n else:\n self.background_normal = 'Icons/button_pause.png'\n\nclass CancelButton(Button):\n def cancel_print(self):\n roboprinter.printer_instance._printer.cancel_print()\n Logger.info('Cancellation: Successful')\n roboprinter.printer_instance._printer.unselect_file()\n Logger.info('Unselect: Successful')\n","sub_path":"RoboLCD/lcd/printerstatus.py","file_name":"printerstatus.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"565385691","text":"import os\nimport pandas as pd\nfrom dash import Dash, callback_context, no_update\nfrom dash.dependencies import Input, Output\nfrom dash_table import DataTable\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport plotly.express as px\n\npath = \"ExampleMac/output.csv\"\ndf = pd.read_csv(path)\nlastmt = os.stat(path).st_mtime\nprint(lastmt)\n\n# fig = go.Figure()\n# fig.add_trace(go.Scatter(df, x=\"date\", y=\"happy\", mode='lines', name='happy'))\n# fig = px.line(df, x=\"date\", y=\"happy\")\n\nfig = go.Figure()\nfig = fig.add_trace(go.Scatter(y=list(df[\"neutral\"]), x=list(df.index), name=\"neutral\"))\nfig = fig.add_trace(go.Scatter(y=list(df[\"happy\"]), x=list(df.index), name=\"happy\"))\n\napp = Dash(__name__)\napp.layout = html.Div(\n [\n # DataTable(\n # id=\"table\",\n # columns=[{\"name\": i, \"id\": i} for i in df.columns],\n # data=df.to_dict(\"records\"),\n # export_format=\"csv\",\n # ),\n # dcc.Graph(\n # id='example-graph',\n # figure=fig\n # ),\n dcc.Graph(\n figure=fig,\n style={'height': 300},\n id='my-graph'\n ), \n dcc.Interval(id='interval', interval=1000, n_intervals=0)\n ]\n)\n\n@app.callback(Output('my-graph', 'figure'), [Input('interval', 'n_intervals')])\ndef trigger_by_modify(n):\n global lastmt\n if os.stat(path).st_mtime > lastmt:\n print(\"modified\")\n lastmt = os.stat(path).st_mtime\n df = pd.read_csv(path)\n\n fig = go.Figure()\n fig = fig.add_trace(go.Scatter(y=list(df[\"neutral\"]), x=list(df.index), name=\"neutral\"))\n fig = fig.add_trace(go.Scatter(y=list(df[\"happy\"]), x=list(df.index), name=\"happy\"))\n fig.update_layout(transition_duration=100)\n return fig\n\n return no_update\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)","sub_path":"emotion.py","file_name":"emotion.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"287650482","text":"import cv2\n\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n# eye_casecade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")\n#smile_casecade = cv2.CascadeClassifier(\"haarcascade_smile.xml\")\n\n\nimg = cv2.imread(\"cat.jpg\")\n\ngray_img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n\nfaces =face_cascade.detectMultiScale(gray_img,scaleFactor=1.05,\n minNeighbors=5)\n\n#smile =smile_casecade.detectMultiScale(gray_img,scaleFactor=1.05,\n# minNeighbors=100)\n\n# eye =eye_casecade.detectMultiScale(gray_img,scaleFactor=1.05,\n# minNeighbors=52)\n\n# for x,y,w,h in faces:\n# img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\n# resized = cv2.resize(img,(int(img.shape[1]*1),int(img.shape[0]*1)))\n\n\n# for x,y,w,h in eye:\n# img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\n# resized = cv2.resize(img,(int(img.shape[1]*1),int(img.shape[0]*1)))\n\nfor x,y,w,h in faces:\n img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\nresized = cv2.resize(img,(int(img.shape[1]*1),int(img.shape[0]*1)))\n\n\ncv2.imshow(\"Gray\",resized)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"Face_Detection_From_Image.py","file_name":"Face_Detection_From_Image.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"55"} +{"seq_id":"268448351","text":"\"\"\"\nModule with the AboutMe serializer.\n\"\"\"\nfrom rest_framework import serializers\n\nfrom ..models.about_me import AboutMe\n\n\nclass AboutMeSerializer(serializers.ModelSerializer):\n \"\"\"\n ModelSerializer for the AboutMe model.\n \"\"\"\n\n image_url = serializers.SerializerMethodField()\n resume_url = serializers.SerializerMethodField()\n\n class Meta:\n model = AboutMe\n fields = (\n \"first_name\",\n \"last_name\",\n \"city\",\n \"age\",\n \"marital_status\",\n \"languages\",\n \"description\",\n \"image_url\",\n \"resume_url\",\n )\n\n def get_image_url(self, about_me: AboutMe) -> str:\n \"\"\" Builds the URL of the image. \"\"\"\n\n return about_me.image.url\n\n def get_resume_url(self, about_me: AboutMe) -> str:\n \"\"\" Builds the URL of the resume file. \"\"\"\n\n return about_me.resume.url\n","sub_path":"backbits/serializers/about_me.py","file_name":"about_me.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"210176097","text":"import pytest\nimport datetime\n\nfrom ingest import bootstrap\n\n\n@pytest.mark.parametrize('n,expected', [\n (3, ['2018-09-17']),\n (5, ['2018-09-17', '2018-09-14', '2018-09-13']),\n ]\n)\ndef test_get_weekdays(n, expected):\n today = datetime.date(2018, 9, 17)\n assert list(map(str, bootstrap.get_weekdays(today, n=n))) == expected\n","sub_path":"test/test_bootstrap.py","file_name":"test_bootstrap.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"167070470","text":"# -*- coding: utf-8 -*- #\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Flags and helpers for the compute target-grpc-proxies commands.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.command_lib.compute import completers as compute_completers\nfrom googlecloudsdk.command_lib.compute import flags as compute_flags\n\nDEFAULT_LIST_FORMAT = \"\"\"\\\n table(\n name,\n urlMap.basename(),\n validateForProxyless\n )\"\"\"\n\n\nclass TargetGrpcProxiesCompleter(compute_completers.ListCommandCompleter):\n\n def __init__(self, **kwargs):\n super(TargetGrpcProxiesCompleter, self).__init__(\n collection='compute.targetGrpcProxies',\n list_command='compute target-grpc-proxies list --uri',\n **kwargs)\n\n\ndef AddDescription(parser):\n parser.add_argument(\n '--description',\n help='An optional, textual description for the target gRPC proxy.')\n\n\ndef AddValidateForProxyless(parser):\n \"\"\"Adds the validate_for_proxyless argument.\"\"\"\n parser.add_argument(\n '--validate-for-proxyless',\n action='store_true',\n default=False,\n help=\"\"\"\\\n If specified, indicates that the BackendServices referenced by the urlMap\n may be accessed by gRPC applications without using a sidecar proxy. This\n will enable configuration checks on urlMap and its referenced\n BackendServices to not allow unsupported features. A gRPC application must\n use \"xds-experimental:///\" scheme in the target URI of the service it is\n connecting to.\n\n If unspecified, indicates that the BackendServices referenced by the\n urlMap will be accessed by gRPC applications via a sidecar proxy. In this\n case, a gRPC application must not use \"xds-experimental:///\" scheme in the\n target URI of the service it is connecting to.\n \"\"\")\n\n\ndef TargetGrpcProxyArgument(required=True, plural=False):\n return compute_flags.ResourceArgument(\n resource_name='target gRPC proxy',\n completer=TargetGrpcProxiesCompleter,\n plural=plural,\n custom_plural='target gRPC proxies',\n required=required,\n global_collection='compute.targetGrpcProxies')\n","sub_path":"Data/GoogleCloud/google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/target_grpc_proxies/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"185316173","text":"import textEditor as te\nimport stemmer as stm\nimport classifier\n\n\nclass Analyzer(object):\n\n def __init__(self):\n self.textEditor = te.TextEditor()\n self.stemmer = stm.Stemmer()\n self.classifire = classifier.Classifier()\n\n def work(self, text, need_stemm):\n text = self.textEditor.delete_punctuation(text)\n text = self.textEditor.delete_stop_words_eng(text)\n if need_stemm:\n text = self.stemmer.stemm(text)\n text = self.classifire.analyze(text)\n\n return text\n","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"164396058","text":"def Reconstruct_Fields(test , Uref , dimensions ):\n\n\tdUx_tot = test.dUx_tot\n\tdUy_tot = test.dUy_tot\n\tdUz_tot = test.dUz_tot\n\n\tdKI_tild = test.dKI_tild\n\tdKII_tild = test.dKII_tild\n\tdKIII_tild = test.dKIII_tild\n\n\tdRhoI = test.dRhoI\n\tdRhoII = test.dRhoII\n\tdRhoIII = test.dRhoIII\n\n\tlistN_F_len = dimensions.listN_F_len\n\ttime_len = dimensions.time_len\n\n\tUx_EL_ref_I = Uref.EL.I.x\n\tUy_EL_ref_I = Uref.EL.I.y\n\tUz_EL_ref_I = Uref.EL.I.z\n\n\tUx_EL_ref_II = Uref.EL.II.x\n\tUy_EL_ref_II = Uref.EL.II.y\n\tUz_EL_ref_II = Uref.EL.II.z\n\n\tUx_EL_ref_III = Uref.EL.III.x\n\tUy_EL_ref_III = Uref.EL.III.y\n\tUz_EL_ref_III = Uref.EL.III.z\n\n\tUx_PL_ref_I = Uref.PL.I.x\n\tUy_PL_ref_I = Uref.PL.I.y\n\tUz_PL_ref_I = Uref.PL.I.z\n\n\tUx_PL_ref_II = Uref.PL.II.x\n\tUy_PL_ref_II = Uref.PL.II.y\n\tUz_PL_ref_II = Uref.PL.II.z\n\n\tUx_PL_ref_III = Uref.PL.III.x\n\tUy_PL_ref_III = Uref.PL.III.y\n\tUz_PL_ref_III = Uref.PL.III.z\n\n\tCeR_tmp = []\n\tCcR_tmp = []\n\tSum_EL = 0\n\tSum = 0\n\tNorme_tot = 0\n\n\tfor t in range(time_len-1):\n\t\tSum_tmp_I = 0\n\t\tSum_tmp_II = 0\n\t\tSum_tmp_III = 0\n\t\tSum_EL_tmp_I = 0\n\t\tSum_EL_tmp_II = 0\n\t\tSum_EL_tmp_III = 0\n\t\tNorme_tot_tmp = 0\n\t\tfor j in range(listN_F_len):\n\t\t\tUx_decomp_EL_I = dKI_tild[t] * Ux_EL_ref_I[j] \t\t\t\n\t\t\tUy_decomp_EL_I = dKI_tild[t] * Uy_EL_ref_I[j]\n\t\t\tUz_decomp_EL_I = dKI_tild[t] * Uz_EL_ref_I[j]\n\t\t\t\n\t\t\tUx_decomp_EL_II = dKII_tild[t] * Ux_EL_ref_II[j]\n\t\t\tUy_decomp_EL_II = dKII_tild[t] * Uy_EL_ref_II[j]\t\n\t\t\tUz_decomp_EL_II = dKII_tild[t] * Uz_EL_ref_II[j]\t\n\t\t\t\n\t\t\tUx_decomp_EL_III = dKIII_tild[t] * Ux_EL_ref_III[j]\n\t\t\tUy_decomp_EL_III = dKIII_tild[t] * Uy_EL_ref_III[j]\t\n\t\t\tUz_decomp_EL_III = dKIII_tild[t] * Uz_EL_ref_III[j]\t\n\t\t\t\n\t\t\tUx_decomp_PL_I = dRhoI[t] * Ux_PL_ref_I[j] \n\t\t\tUy_decomp_PL_I = dRhoI[t] * Uy_PL_ref_I[j]\n\t\t\tUz_decomp_PL_I = dRhoI[t] * Uz_PL_ref_I[j]\n\t\t\t\n\t\t\tUx_decomp_PL_II = dRhoII[t] * Ux_PL_ref_II[j] \n\t\t\tUy_decomp_PL_II = dRhoII[t] * Uy_PL_ref_II[j]\t\n\t\t\tUz_decomp_PL_II = dRhoII[t] * Uz_PL_ref_II[j]\t\n\t\t\t\n\t\t\tUx_decomp_PL_III = dRhoIII[t] * Ux_PL_ref_III[j] \n\t\t\tUy_decomp_PL_III = dRhoIII[t] * Uy_PL_ref_III[j]\t\n\t\t\tUz_decomp_PL_III = dRhoIII[t] * Uz_PL_ref_III[j]\t\n\t\t\t\n\t\t\tUx_decomp_I = Ux_decomp_EL_I + Ux_decomp_PL_I\n\t\t\tUy_decomp_I = Uy_decomp_EL_I + Uy_decomp_PL_I\n\t\t\tUz_decomp_I = Uz_decomp_EL_I + Uz_decomp_PL_I\n\t\t\t\n\t\t\tUx_decomp_II = Ux_decomp_EL_II + Ux_decomp_PL_II\n\t\t\tUy_decomp_II = Uy_decomp_EL_II + Uy_decomp_PL_II\n\t\t\tUz_decomp_II = Uz_decomp_EL_II + Uz_decomp_PL_II\n\t\t\t\n\t\t\tUx_decomp_III = Ux_decomp_EL_III + Ux_decomp_PL_III\n\t\t\tUy_decomp_III = Uy_decomp_EL_III + Uy_decomp_PL_III\n\t\t\tUz_decomp_III = Uz_decomp_EL_III + Uz_decomp_PL_III\n\t\t\t\n\t\t\tSum_EL_tmp_I += pow(dUx_tot[j][t] - Ux_decomp_EL_I - Ux_decomp_EL_II - Ux_decomp_EL_III , 2) + pow(dUy_tot[j][t] - Uy_decomp_EL_I - Uy_decomp_EL_II - Uy_decomp_EL_III , 2) + pow(dUz_tot[j][t] - Uz_decomp_EL_I - Uz_decomp_EL_II - Uz_decomp_EL_III , 2)\n\t\t\t#Sum_EL_tmp_II += pow(dUx_tot[j][t] - Ux_decomp_EL_II , 2) + pow(dUy_tot[j][t] - Uy_decomp_EL_II , 2) + pow(dUz_tot[j][t] - Uz_decomp_EL_II , 2)\n\t\t\t#Sum_EL_tmp_III += pow(dUx_tot[j][t] - Ux_decomp_EL_III , 2) + pow(dUy_tot[j][t] - Uy_decomp_EL_III , 2) + pow(dUz_tot[j][t] - Uz_decomp_EL_III , 2)\n\t\t\t\n\t\t\tSum_tmp_I += pow(dUx_tot[j][t] - Ux_decomp_I -Ux_decomp_II - Ux_decomp_III , 2) + pow(dUy_tot[j][t] - Uy_decomp_I - Uy_decomp_II - Uy_decomp_III , 2) + pow(dUz_tot[j][t] - Uz_decomp_I - Uz_decomp_II - Uz_decomp_III , 2)\n\t\t\t#Sum_tmp_II += pow(dUx_tot[j][t] - Ux_decomp_II , 2) + pow(dUy_tot[j][t] - Uy_decomp_II , 2) + pow(dUz_tot[j][t] - Uz_decomp_II , 2)\n\t\t\t#Sum_tmp_III += pow(dUx_tot[j][t] - Ux_decomp_III , 2) + pow(dUy_tot[j][t] - Uy_decomp_III , 2) + pow(dUz_tot[j][t] - Uz_decomp_III , 2)\n\t\t\tNorme_tot_tmp += pow(dUx_tot[j][t] , 2) + pow(dUy_tot[j][t] , 2) + pow(dUz_tot[j][t] , 2)\n\t\t\t#Sum_EL_tmp += pow(dUx_tot[j][t] - Ux_decomp_EL_I + dUy_tot[j][t] - Uy_decomp_EL_I + dUz_tot[j][t] - Uz_decomp_EL_I , 2)\n\t\t\t#Sum_EL_tmp += pow(dUx_tot[j][t] - Ux_decomp_EL_II + dUy_tot[j][t] - Uy_decomp_EL_II + dUz_tot[j][t] - Uz_decomp_EL_II , 2)\n\t\t\t#Sum_EL_tmp += pow(dUx_tot[j][t] - Ux_decomp_EL_III + dUy_tot[j][t] - Uy_decomp_EL_III + dUz_tot[j][t] - Uz_decomp_EL_III , 2)\n\t\t\t#Sum_tmp_I += pow(dUx_tot[j][t] - Ux_decomp_I + dUy_tot[j][t] - Uy_decomp_I + dUz_tot[j][t] - Uz_decomp_I , 2)\n\t\t\t#Sum_tmp_II += pow(dUx_tot[j][t] - Ux_decomp_II + dUy_tot[j][t] - Uy_decomp_II + dUz_tot[j][t] - Uz_decomp_II , 2)\n\t\t\t#Sum_tmp_III += pow(dUx_tot[j][t] - Ux_decomp_III + dUy_tot[j][t] - Uy_decomp_III + dUz_tot[j][t] - Uz_decomp_III , 2)\n\t\t\t#Norme_tot_tmp += pow(dUx_tot[j][t] + dUy_tot[j][t] + dUz_tot[j][t] , 2)\n\t\tNorme_tot += Norme_tot_tmp \n\t\tSum_EL += Sum_EL_tmp_I + Sum_EL_tmp_II + Sum_EL_tmp_III\n\t\tSum += Sum_tmp_I + Sum_tmp_II + Sum_tmp_III\n\t\tCeR_tmp += [sqrt( ( Sum_EL_tmp_I + Sum_EL_tmp_II + Sum_EL_tmp_III) / Norme_tot_tmp )]\n\t\tCcR_tmp += [sqrt( ( Sum_tmp_I + Sum_tmp_II + Sum_tmp_III ) / Norme_tot_tmp )]\n\tCeR = sqrt(Sum_EL / Norme_tot)\n\tCcR = sqrt(Sum / Norme_tot)\n\treturn CeR, CcR, CeR_tmp, CcR_tmp\n\n\ndef Reconstruct_Fields_Flavien_Fremy(temps,Ux_tot, Uy_tot, KI_tild, KII_tild, RhoI_tild, RhoII_tild, Uref , listN_F_len, radlong, half_thetalong ):\n\tUx_EL_ref_I = Uref.EL.I.x\n\tUy_EL_ref_I = Uref.EL.I.y\n\tUx_EL_ref_II = Uref.EL.II.x\n\tUy_EL_ref_II = Uref.EL.II.y\n\tUx_PL_ref_I = Uref.PL.I.x\n\tUy_PL_ref_I = Uref.PL.I.y\n\tUx_PL_ref_II = Uref.PL.II.x\n\tUy_PL_ref_II = Uref.PL.II.y\n\tUx_I, Uy_I, Ux_II, Uy_II = PL_Sym_Asym_Decomp(Ux_tot, Uy_tot, temps, radlong, half_thetalong)\n\tCeR_tmp = []\n\tCcR_tmp = []\n\tNorme_tot = []\n\tfor t in range(len(temps)-1):\n\t\tSum_tmp = 0\n\t\tSum_EL_tmp = 0\n\t\tNorme_tot_tmp = 0\n\t\tfor j in range(listN_F_len):\n\t\t\tUx_decomp_EL_I = KI_tild[t] * Ux_EL_ref_I[j] \n\t\t\tUy_decomp_EL_I = KI_tild[t] * Uy_EL_ref_I[j]\n\t\t\tUx_decomp_EL_II = KII_tild[t] * Ux_EL_ref_II[j]\n\t\t\tUy_decomp_EL_II = KII_tild[t] * Uy_EL_ref_II[j]\t\n\n\t\t\tUx_decomp_PL_I = RhoI_tild[t] * Ux_PL_ref_I[j] \n\t\t\tUy_decomp_PL_I = RhoI_tild[t] * Uy_PL_ref_I[j]\n\t\t\tUx_decomp_PL_II = RhoII_tild[t] * Ux_PL_ref_II[j] \n\t\t\tUy_decomp_PL_II = RhoII_tild[t] * Uy_PL_ref_II[j]\t\n\n\t\t\tUx_decomp_I = Ux_decomp_EL_I + Ux_decomp_PL_I\n\t\t\tUy_decomp_I = Uy_decomp_EL_I + Uy_decomp_PL_I\n\t\t\tUx_decomp_II = Ux_decomp_EL_II + Ux_decomp_PL_II\n\t\t\tUy_decomp_II = Uy_decomp_EL_II + Uy_decomp_PL_II\n\n\t\t\tSum_EL_tmp += pow( (Ux_I[j][t] - Ux_decomp_EL_I) + (Ux_II[j][t] - Ux_decomp_EL_II) , 2)\n\t\t\tSum_EL_tmp += pow( (Uy_I[j][t] - Uy_decomp_EL_I) + (Uy_II[j][t] - Uy_decomp_EL_II) , 2)\n\n\t\t\tSum_tmp += pow( (Ux_I[j][t] - Ux_decomp_I) + (Ux_II[j][t] - Ux_decomp_II) , 2)\n\t\t\tSum_tmp += pow( (Uy_I[j][t] - Uy_decomp_I) + (Uy_II[j][t] - Uy_decomp_II) , 2)\n\n\t\t\tNorme_tot_tmp += pow(Ux_I[j][t] + Ux_II[j][t] , 2)\n\t\t\tNorme_tot_tmp += pow(Uy_I[j][t] + Uy_II[j][t] , 2)\n\n\t\tNorme_tot_tmp = 1000.*sqrt(Norme_tot_tmp/listN_F_len)\n\t\tSum_EL_tmp = 1000.*sqrt(Sum_EL_tmp/listN_F_len)\n\t\tSum_tmp = 1000.*sqrt(Sum_tmp/listN_F_len)\n\n\t\tif ( Norme_tot_tmp < 0.00005 ) :\n\t\t\tCeR = 0.\n\t\t\tCcR = 0.\n\t\telse :\n\t\t\tCeR = Sum_EL_tmp / Norme_tot_tmp\n\t\t\tCcR = Sum_tmp / Norme_tot_tmp\n\n\t\tCeR_tmp += [ CeR ]\n\t\tCcR_tmp += [ CcR ]\n\t\tNorme_tot+= [Norme_tot_tmp]\n\n\treturn CeR_tmp, CcR_tmp, Norme_tot\n","sub_path":"Verify_material_orientation_Zmat_Abaqus/src_Post_Proc/Reconstruct_Fields.py","file_name":"Reconstruct_Fields.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"284502594","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nfet_class.py\n============\nCette classe contient toutes les procédures nécessaires au programme fet_main.py\nIl doit se trouver dans le même directory que le programme fet_main.py\nfichier : fet_class.py\nutilisé par : fet_main.py\nprocédure de lancement : new_job\nauteur : josmet\ndate : 21.06.2018\n\"\"\"\n\nimport os\nimport subprocess\nimport time\nimport tkinter as tk\nimport uuid\nimport zipfile\nimport shutil\n\nfrom datetime import datetime\nfrom os import listdir\nfrom os import walk\nfrom os.path import isfile, join\nfrom shutil import copyfile\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nfrom fet_lib import ClasseFetLib\nfrom fet_ini import ClasseIni\ny = ClasseFetLib()\nini = ClasseIni()\n# from fet_xml_formatter import ClasseFetXmlFormatter\n# f = ClasseFetLib()\n\n\nclass ClasseFet:\n \"\"\"\n this class content all the fonctionnalities to improve the epub files generated by the Publiwide platform\n input :\n var_msg : to write message on the main window\n msg_list : listView where the messages are displayed\n msg_display : ref on the window where the message box is\n output :\n write the process steps in the information window\n \"\"\"\n\n def __init__(self, var_msg, msg_list, msg_display, btn_frame):\n\n # Pseudo constantes\n self.DEBUG = False # print debug messages\n self.LOG_THIS_RUN = True # log debug messages\n\n # max size for the images in ppp\n self.IMG_SIZE_MAX = 20000\n # waiting another action finished\n self.ERROR_WAIT_TIME = 0.5\n self.LOG_FILE_NAME = \"fet_log.txt\"\n self.INI_FILE_NAME = \"fet_epub.ini\"\n self.CONTENT_OPF_FILE_NAME = \"content.opf\"\n\n #TOC\n self.TOC_DEEP = \"h1+h2\"\n self.FONT_NAME = \"Comic sans MS\"\n\n # initialisation variables\n self.var_msg = var_msg\n self.msg_list = msg_list\n self.msg_display = msg_display\n self.btn_frame = btn_frame\n # prepare the files info to display\n self.txt_in_file = \"Sce file : \"\n self.txt_out_file = \"Dst file : \"\n\n self.t_start = 0\n self.t_stop = 0\n self.pause_time = 2\n\n self.in_file_name = \"\"\n self.out_file_name = \"\"\n\n self.temp_path_dir = \"\"\n self.ops_dir = \"\"\n self.ops_path_dir = \"\"\n self.textPathDir = \"\"\n self.pw_path_dir = \"\"\n self.image_path_dir = \"\"\n self.content_path_file_name = \"\"\n self.in_path_file_name = \"\"\n self.out_path_file_name = \"\"\n self.log_fileName = \"\"\n self.log_path_file_name = \"\"\n self.style_file_name = \"\"\n self.style_path_file_name = \"\"\n self.style_exercices_path_file_name = \"\"\n self.style_pw_table_path_file_name = \"\"\n self.misc_path_file_name = \"\"\n self.nav_path_file_name = \"\"\n\n self.asked_2_quit = False\n\n # Current working directory\n self.cwd = \"\".join([str(os.getcwd()).replace(\"\\\\\", \"/\").replace(\"\\n\", \"\"), \"/\"])\n # self.cwd = \"\".join([str(os.getcwd()).replace(\"\\\\\" or \"\\n\", \"/\"), \"/\"])\n\n # a file to log opérations\n self.log_path = \"\".join([self.cwd, \"log/\"])\n self.log_path_file_name = \"\".join([self.log_path, self.LOG_FILE_NAME])\n if not os.path.isdir(self.log_path):\n os.mkdir(self.log_path)\n\n self.nbre_passes = 0\n self.nbre_erreurs = 0\n self.second_try = 0\n\n self.program_in_test = False\n self.dir_job_status = False\n\n org_ok = False\n new_ok = False\n tmp_ok = False\n log_ok = False\n js_ok = False\n\n self.org_path = \"\"\n self.new_path = \"\"\n self.tmp_path = \"\"\n self.js_path = \"\"\n\n # constantes pour msg_display\n self.DISPLAY_ONLY = 1\n self.DISPLAY_AND_LOG = 2\n self.LOG_ONLY = 3\n\n self.COLOR_RED = 1\n self.COLOR_BLUE = 2\n self.COLOR_GREEN = 3\n self.COLOR_ORANGE = 5\n self.COLOR_PURPLE = 6\n self.COLOR_BLACK = 7\n self.COLOR_RED_ON_YELLOW = 4\n\n # init variables\n self.cwd = \"\".join([str(os.getcwd()).replace(\"\\\\\", \"/\").replace(\"\\n\", \"\"), \"/\"])\n # self.org_path = \"\"\n # self.new_path = \"\"\n # self.tmp_path = \"\"\n # self.new_nav_path = \"\"\n # self.new_js_path = \"\"\n # self.new_moo_path = \"\"\n # self.new_police_path = \"\"\n # self.js_css_path = \"\"\n self.log_path = \"\".join([self.cwd, \"log/\"])\n self.log_path_file_name = \"\".join([self.log_path, self.LOG_FILE_NAME])\n # self.strings_names_js = []\n # self.strings_names_css = []\n # self.mandatory_names_js = []\n # self.mandatory_names_css = []\n\n # initialisation des variable de la classe à partir de la classe ini qui le fichier fet_epub.ini\n self.strings_names_js = ini.strings_names_js\n self.strings_names_css = ini.strings_names_css\n self.mandatory_names_js = ini.mandatory_names_js\n self.mandatory_names_css = ini.mandatory_names_css\n self.org_path = ini.org_path\n self.new_path = ini.new_path\n self.tmp_path = ini.tmp_path\n self.new_nav_path = ini.new_nav_path\n self.new_js_path = ini.new_js_path\n self.new_moo_path = ini.new_moo_path\n self.new_police_path = ini.new_police_path\n self.js_css_path = ini.js_css_path\n self.DEBUG = ini.DEBUG\n self.LOG_THIS_RUN = ini.LOG_THIS_RUN\n self.VERBOSE = ini.VERBOSE\n self.WITH_DIR = ini.WITH_DIR\n self.WITH_ZIP = ini.WITH_ZIP\n self.IMG_SIZE_MAX = ini.IMG_SIZE_MAX\n self.TOC_DEEP = ini.TOC_DEEP\n self.FONT_NAME = ini.FONT_NAME\n self.VERIF_EPUB = ini.VERIF_EPUB\n\n def file_improve_pw_epub(self):\n \"\"\"\n Here will be started the operations needed to\n improve the quality of the epubs generated by the Publiwide platform.\n input : none\n return : none\n \"\"\"\n\n # disable all buttons that can not be used during this task\n self.manage_buttons(\"btnFileJob\", \"in\")\n\n self.var_msg.set(\"\")\n self.program_in_test = False\n\n # clear the listbox\n self.msg_list.delete(0, END)\n self.msg_display.update()\n\n # ask for the filename to work with\n self.in_path_file_name = filedialog.askopenfilename(title=\"Sélectionnez le fichier epub à améliorer\",\n initialdir=self.org_path,\n filetypes=[('epub files', '.epub'), ('all files', '.*')])\n # if the len of filename is not = to 0 start the job\n if len(str(self.in_path_file_name)) > 0:\n self.t_start = time.time() # store the start time\n self.in_file_name = os.path.basename(self.in_path_file_name)\n self.improve_epub() # start the optimisation\n else:\n self.msg_list.insert(tk.END, \"Select a epub to improve\")\n self.msg_display.update()\n # enable all buttons\n self.manage_buttons(\"btnFileJob\", \"out\")\n\n def verify_job(self):\n \"\"\"\n This function checks an epub file based on the java epubcheck software of the international digital publishing forum\n input : none\n return : none\n \"\"\"\n # disable all buttons that can not be used during this task\n self.manage_buttons(\"btnVerif\", \"in\")\n # clear the listbox\n self.msg_list.delete(0, END)\n self.msg_display.update()\n\n epub_check_dir = \"\".join([self.cwd, \"epubcheck/\"])\n epub_check_file = \"epubcheck.jar\"\n java_epub_check_path_file_name = \"\".join([epub_check_dir, epub_check_file])\n\n # check if the java validation program is present\n if not os.path.isfile(java_epub_check_path_file_name):\n msg_info = \"\".join([\n \"Le répertoire contenant le programme de validation java n'existe pas. \"\n \"Il doit se trouver dans le répertoire de \"\n \"lancement de l'application. Il peut être téléchargé sur le site internet : \"\n \"https://github.com/idpf/epubcheck et doit se nommer epubcheck\\n\\n\"\n \"Veuillez corriger le problème avant de relancer le programme\\n\\n\" \n \"Le programme se termine ici.\\n\"])\n messagebox.showerror(\"Fichier ini défectueux \\n\", \"\".join([msg_info]), icon='error')\n sys.exit()\n\n # ask for the filename to work with\n self.in_file_name = filedialog.askopenfilename(title=\"Sélectionnez le fichier epub à vérifier\",\n initialdir=self.new_path,\n filetypes=[('epub files', '.epub'), ('all files', '.*')])\n if len(str(self.in_file_name)) > 0:\n\n self.t_start = time.time() # store the start time\n\n self.manage_info(\"---------------------------------------------------------\", self.LOG_ONLY, self.COLOR_BLUE)\n self.manage_info(\"\".join([\"VERIFICATION EPUB : \", datetime.now().strftime(\"%Y%m%d-%H%M%S\")]), self.LOG_ONLY, self.COLOR_BLUE)\n self.manage_info(\"\".join([\"Fichier : \", os.path.basename(self.in_file_name)]), self.DISPLAY_AND_LOG, self.COLOR_BLUE)\n self.manage_info(\"en cours de vérification. Patientez SVP ...\", self.DISPLAY_AND_LOG, self.COLOR_BLUE)\n\n # execution de l'application java\n out_file_name = \"\".join([self.log_path, \"epub_verif.xml\"])\n f_ok, n_err, n_fatal, n_error, n_warn, epub_status = self.w3c_epub_check (self.in_file_name, out_file_name)\n # inscrire les résultats en clair dans le fichier txt de sortie\n with open(\"\".join([self.log_path, \"epub_prob.txt\"]), \"w\", encoding=\"utf-8\") as prob_file:\n # msg = \"\".join([self.in_file_name, \"\\n\"])\n # prob_file.write(msg)\n for l in epub_status:\n prob_file.write(l)\n elapsed_time = time.time() - self.t_start\n self.msg_list.delete(0, END)\n self.msg_display.update()\n\n # the result of the analyse to the user\n if f_ok:\n # all is ok\n self.t_stop = time.time()\n msg = \"\".join([\"Statut du EPUB : \", os.path.basename(self.in_file_name),\n \"\\n\\nFélicitations aucun problème constaté : \", \"EPUB OK\", \"\\n\",\n \"Fichier analysé en: \", str(int(elapsed_time)), \"s\\n\"])\n messagebox.showinfo(\"Résultat de l'analyse \\n\", msg, icon='info')\n msg = \"\".join(\n [\"Félicitations aucun problème constaté dans le fichier : \", os.path.basename(self.in_file_name)])\n self.manage_info(msg, self.DISPLAY_AND_LOG, self.COLOR_GREEN)\n else:\n # there is problesm(s)\n msg_msgbox = \"\".join(\n [\"Statut du EPUB : \", os.path.basename(self.in_file_name), \"\\n\\n\", \"EPUB PAS OK : \", str(n_err),\n \" problèmes constatés : \", \"\\n\",\n str(n_warn), \" warning(s) - \", str(n_error), \" error(s) - \", str(n_fatal), \" fatal(s)\\n\",\n \"Fichier analysé en: \", str(int(elapsed_time)), \"s\\n\",\n \"Détails des résultats dans le fichier : \", out_file_name, \"\\n\\nVoulez-vous afficher le détail ?\"])\n result = messagebox.askyesno(\"Résultat de l'analyse \\n\", msg_msgbox, icon='error')\n\n if result:\n # the user clicked on yes to see the file\n cmd = \"\".join([\"notepad \", self.log_path, \"epub_prob.txt\"])\n os.system(cmd)\n\n msg_info = \"\".join(\n [\"Fichier : \", os.path.basename(self.in_file_name), \" \", str(n_err), \" problèmes constatés : \",\n str(n_warn), \" warning(s) - \", str(n_error), \" error(s) - \", str(n_fatal), \" fatal(s)\"])\n self.manage_info(msg_info, self.DISPLAY_AND_LOG, self.COLOR_RED_ON_YELLOW)\n self.manage_info(\"---------------------------------------------------------\\n\", self.LOG_ONLY, self.COLOR_BLUE)\n else:\n # no file selected so do nothing\n self.manage_info(\"Select a epub to verify\", self.DISPLAY_ONLY, self.COLOR_RED_ON_YELLOW)\n self.manage_buttons(\"btnVerif\", \"out\")\n\n def check_epub(self, in_path_file_name, out_path_file_name):\n\n # epub_check_dir = \"\".join([self.cwd, \"epubcheck/\"])\n # epub_check_file = \"epubcheck.jar\"\n # java_epub_check_path_file_name = \"\".join([epub_check_dir, epub_check_file])\n\n # execution de l'application java\n out_file_name = \"\".join([self.log_path, \"epub_verif.xml\"])\n f_ok, n_err, n_fatal, n_error, n_warn, epub_status = self.w3c_epub_check (in_path_file_name, out_file_name)\n\n # # inscrire les résultats en clair dans le fichier txt de sortie\n with open(out_path_file_name, \"a\", encoding=\"utf-8\") as prob_file:\n msg = \"\".join([\"============================================================================================ \\n\"])\n prob_file.write(msg)\n for l in epub_status:\n prob_file.write(l)\n return \"\".join([\"Check status : \",str(n_fatal), \" fatal / \", str(n_error), \" errors / \", str(n_warn), \" warnings\"]), n_fatal, n_error, n_warn\n\n\n def dir_improve_pw_epub(self):\n\n \"\"\"\n Cette fonction permet de vérifier tous les epub's contenus dans un répertoire\n Elle parcoure le répertoire choisi, vérifie qu'il y ait bien des fichiers epub puis,\n pour chaque ficheir epub, elle appelle la fonction file_improve_job pour exécuter l'amélioration de façon individelle\n \"\"\"\n # variable qui permet de savoir si l'utilisateur a demandé à interrompre la procédure\n self.asked_2_quit = False\n # disable all buttons that can not be used during this task\n self.manage_buttons(\"btnDirJob\", \"in\")\n\n dirjob_tstart = time.time()\n # variable pour que la fonction sache que l'appel vient d'ici et gère les messages en conséquence\n self.dir_job_status = True\n # demande le nom du répertoire à travailler\n file_options = {}\n file_options['initialdir'] = self.org_path\n file_options['title'] = 'Please select a directory witch content epub files'\n dir_name = filedialog.askdirectory(**file_options)\n\n file_output_result_path_name = \"\".join([self.log_path, \"epub_check_result.txt\"])\n # with open(file_output_result_path_name, \"w\", encoding=\"utf-8\") as prob_file:\n # YY = str(datetime.now().year)\n # MM = str(datetime.now().month)\n # DD = str(datetime.now().day)\n # hh = str(datetime.now().hour)\n # mm = str(datetime.now().minute)\n # ss = str(datetime.now().second)\n # compete_date_time = \"\".join([DD, \".\", MM, \".\", YY, \" \", hh,\":\",mm,\":\", ss, \"\\n\"])\n # prob_file.write(compete_date_time)\n # prob_file.write(\"\".join([str(datetime.now()), \"\\n \"]))\n\n # erreurs totales\n fatal_tot = 0\n error_tot = 0\n warn_tot = 0\n recap_tot = []\n\n # On controle que le répertoire n'est pas vide\n if dir_name != \"\":\n # only the .epub files\n only_epub_files = [f for f in listdir(dir_name) if isfile(join(dir_name, f))\n and os.path.splitext(f)[1] == \".epub\"]\n if len(only_epub_files) > 0:\n # there is .epub files\n for test_file in only_epub_files:\n self.t_start = time.time()\n self.in_path_file_name = \"/\".join([dir_name, test_file])\n self.in_file_name = os.path.basename(self.in_path_file_name)\n self.improve_epub()\n\n if self.VERIF_EPUB:\n self.manage_info(\"---------------------------------------------------------\", self.LOG_ONLY, self.COLOR_PURPLE)\n self.manage_info(\"\".join([\"VERIFICATION EPUB : \", datetime.now().strftime(\"%Y%m%d-%H%M%S\")]), self.LOG_ONLY, self.COLOR_PURPLE)\n self.manage_info(\"\".join([\"Fichier : \", os.path.basename(self.in_file_name)]), self.DISPLAY_AND_LOG, self.COLOR_PURPLE)\n self.manage_info(\"en cours de vérification. Patientez SVP ...\", self.DISPLAY_AND_LOG, self.COLOR_PURPLE)\n\n ret_status, n_fatal, n_error, n_warn = self.check_epub(self.out_path_file_name, file_output_result_path_name)\n fatal_tot += n_fatal\n error_tot += n_error\n warn_tot += n_warn\n recap_tot.append(\"\".join([test_file, \" : \",str(n_fatal), \" fatals / \", str(n_error), \" errors / \", str(n_warn), \" warnings\\n\"]))\n\n self.manage_info(ret_status, self.DISPLAY_AND_LOG, self.COLOR_PURPLE)\n msg = \" \"\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n if self.asked_2_quit:\n break\n else:\n time.sleep(self.pause_time)\n\n msg_err = \"\".join([\"Check status total : \", str(fatal_tot), \" fatal / \", str(error_tot), \" error / \", str(warn_tot), \" warn\"])\n if not self.asked_2_quit:\n elapsed_time = int(time.time() - dirjob_tstart)\n elapsed_min = elapsed_time // 60\n elapsed_sec = elapsed_time % 60\n if elapsed_min > 0 :\n msg = \"\".join([\"DIR job terminated with ok code in \", str(elapsed_min), \" min \", str(elapsed_sec), \" sec\"])\n else:\n msg = \"\".join([\"DIR job terminated with ok code in \", str(elapsed_sec), \" sec\"])\n if self.VERIF_EPUB:\n for r in recap_tot:\n self.manage_info(r, self.DISPLAY_AND_LOG)\n self.manage_info(msg_err, self.DISPLAY_AND_LOG)\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # self.manage_info(msg_err, self.DISPLAY_AND_LOG)\n else:\n msg = \"\".join([\"Job terminated by user !\"])\n self.manage_info(msg_err, self.DISPLAY_AND_LOG)\n self.manage_info(msg, self.DISPLAY_AND_LOG, self.COLOR_RED_ON_YELLOW)\n else:\n # there is no .epub files\n messagebox.showinfo(\"Répertoire d'entrée \\n\", \"Il n'y a pas de fichiers .epub dans ce répertoire. \\nRefaites votre choix\", icon='info')\n\n # rétablir l'état normal des boutons'\n self.manage_buttons(\"btnDirJob\", \"out\")\n\n def test_soft(self):\n\n \"\"\"\n This function is used to test the program by running the improve function as long as the user does not\n interrupt the process. The main goal is to test conflict management when accessing files. The ideal is\n to launch at the same time several occurrences of the application to create conflicts on file access.\n Initially many conflicts were created by the Zoolz application that makes backups as new files appear.\n Now the problem is known but not solved. The interim solution was to stop the Zoolz program.\n \"\"\"\n\n self.nbre_passes = 0\n self.nbre_erreurs = 0\n self.second_try = 0\n # disable all buttons that can not be used during this task\n self.manage_buttons(\"btnTest\", \"in\")\n self.program_in_test = False\n self.asked_2_quit = False\n epub_found = True\n\n dir_name = filedialog.askdirectory(initialdir=self.org_path, title='Please select a directory')\n if dir_name != \"\":\n while True:\n self.nbre_passes += 1\n\n only_epub_files = [f for f in listdir(dir_name) if isfile(join(dir_name, f))\n and os.path.splitext(f)[1] == \".epub\"]\n if len(only_epub_files) > 0:\n\n only_files = [f for f in listdir(dir_name) if isfile(join(dir_name, f))]\n for test_file in only_files:\n v_msg = (\"\".join([self.var_msg.get(), \"Passes : \", str(self.nbre_passes), \" / 2nd try : \",\n str(self.second_try), \" / Erreurs : \", str(self.nbre_erreurs), \"\\n\"]))\n self.msg_list.delete(0, END)\n self.msg_list.insert(tk.END, \"*********************************************************\")\n self.msg_list.itemconfig(tk.END, fg='red')\n self.msg_list.itemconfig(tk.END, bg='lightgreen')\n self.msg_list.insert(tk.END, v_msg)\n self.msg_list.itemconfig(tk.END, fg='red')\n self.msg_list.itemconfig(tk.END, bg='lightgreen')\n self.msg_list.insert(tk.END, \"*********************************************************\")\n self.msg_list.itemconfig(tk.END, fg='red')\n self.msg_list.itemconfig(tk.END, bg='lightgreen')\n self.msg_list.see(\"end\")\n self.msg_display.update()\n time.sleep(self.pause_time)\n self.t_start = time.time()\n self.in_path_file_name = \"/\".join([dir_name, test_file])\n self.in_file_name = os.path.basename(self.in_path_file_name)\n self.improve_epub()\n if self.asked_2_quit:\n break\n else:\n time.sleep(self.pause_time)\n if self.asked_2_quit:\n break\n else:\n # there is no .epub files\n messagebox.showinfo(\"Répertoire d'entrée \\n\", \"Il n'y a pas de fichiers .epub dans ce répertoire. \\nRefaites votre choix\", icon='info')\n epub_found = False\n break\n\n if epub_found:\n msg = \"\".join([\"Job terminated by user !\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG, self.COLOR_RED_ON_YELLOW)\n else:\n self.msg_list.delete(0, END)\n msg = \"\".join([\"Please select a task\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG, self.COLOR_BLUE)\n self.manage_buttons(\"btnTest\", \"out\")\n\n def improve_epub(self):\n \"\"\"\n This function is the heart of the program. It content all the operations in a sequence.\n - defines files names\n - defines directory and path\n - create a temporary directory\n - unzip the epub file in the temporary directory\n - do the next modifications\n #1 : copy images in the images directory\n #2 : resize images\n #3 : delete the empty html pages\n #4 : update the cover of the book\n #5 : import the french js validation script\n #6 : modify for using the french js script\n #7 : change the id of the title of the book\n #8 : add new styles\n #9 : modify the head of the nav file\n #10 : put the title of nav in french\n #10a : rename nav.html to nav.xhtml\n for all th_ .html files\n #11 : change the word validation with validation_fr_jo\n #12 : change the \"\n new_opf_data.insert(index_end_spine, nav_txt)\n with open(opf_file_name, \"w\", encoding=\"utf-8\") as opf_file:\n opf_file.writelines(new_opf_data)\n n_changes += 1\n\n\n # del .js files\n only_files = [f for f in listdir(self.misc_path_file_name) if isfile(join(self.misc_path_file_name, f))]\n for f in only_files:\n os.remove(self.misc_path_file_name + f)\n\n # effacer les références des fichiers supprimés dans le fichier opf\n opf_file_name = \"\".join([self.ops_path_dir, \"content.opf\"])\n with open(opf_file_name, \"r\", encoding=\"utf-8\") as opf_file:\n opf_data = opf_file.readlines()\n opf_data_new = []\n for l in opf_data:\n if not \".js\" in l:\n opf_data_new.append(l)\n with open(opf_file_name, \"w\", encoding=\"utf-8\") as opf_file:\n opf_file.writelines(opf_data_new)\n n_changes += 1\n\n # copy the mandatory .js files\n only_files = [f for f in listdir(self.js_css_path) if isfile(join(self.js_css_path, f))]\n for f in only_files:\n if \".js\" in f:\n for m in self.mandatory_names_js:\n if m in f:\n sce_file = \"\".join([self.js_css_path, f])\n dst_file = \"\".join([self.misc_path_file_name, f])\n copyfile(sce_file, dst_file)\n # add ref in content.opf\n txt2add = \" \\n\"\n v_return, n_changes = self.add_line(\"\".join([self.ops_path_dir, \"content.opf\"]), \"manifest\", txt2add)\n\n # del .css files\n only_files = [f for f in listdir(self.style_path_name) if isfile(join(self.style_path_name, f))]\n for f in only_files:\n os.remove(self.style_path_name + f)\n n_changes += 1\n # traitement fichier opf\n opf_file_name = \"\".join([self.ops_path_dir, \"content.opf\"])\n # lire le fichier\n with open(opf_file_name, \"r\", encoding=\"utf-8\") as opf_file:\n opf_data = opf_file.readlines()\n # supprimer les lignes avec .css\n opf_data_new = []\n for l in opf_data:\n if not \".css\" in l:\n opf_data_new.append(l)\n # ecrire les données dans le fichier\n with open(opf_file_name, \"w\", encoding=\"utf-8\") as opf_file:\n opf_file.writelines(opf_data_new)\n # copy the mandatory .js files\n only_files = [f for f in listdir(self.js_css_path) if isfile(join(self.js_css_path, f))]\n for f in only_files:\n if \".css\" in f:\n for m in self.mandatory_names_css:\n if m in f:\n sce_file = \"\".join([self.js_css_path, f])\n dst_file = \"\".join([self.style_path_name, f])\n copyfile(sce_file, dst_file)\n # add ref in content.opf\n txt2add = \" \\n\"\n v_return, n_changes = self.add_line(\"\".join([self.ops_path_dir, \"content.opf\"]), \"manifest\", txt2add)\n\n # update in all xhtml files for mandatory css and js files\n new_ref_txt = \" \\n\"\n new_ref_txt += \" \\n\"\n new_ref_txt += \" \\n\"\n new_ref_txt += \" \\n\"\n for root, dirs, files in os.walk(self.text_path_name):\n # pour tous les fichiers js et css à jour\n for text_file in files:\n with open(self.text_path_name + text_file, \"r\", encoding=\"utf-8\") as xhtml_r_file:\n xhtml_data = xhtml_r_file.readlines()\n # supprimer les références existante dans le head des fichiers xhtml\n begin_head_found = False\n end_head_found = False\n i = 0\n to_remove_list = []\n for l in xhtml_data:\n if \"\" in l:\n begin_head_found = True\n if begin_head_found and not end_head_found:\n if \"\" in l and not \"/>\" in l:\n while not end_tag_found:\n if \"\" in xhtml_data[j] or \"/>\" in xhtml_data[j]:\n end_tag_found = True\n to_remove_list.append(j)\n j += 1\n if\"\" in l:\n end_head_found = True\n i += 1\n for i in reversed(to_remove_list):\n # print(xhtml_data[i])\n del xhtml_data[i]\n # insérer les nouvelles références\n i = 0\n index = 0\n head_found = False\n for l in xhtml_data:\n if \"\" in l:\n index = i\n head_found = True\n break\n i += 1\n if head_found :\n xhtml_data.insert(index, new_ref_txt)\n with open(self.text_path_name + text_file, \"w\", encoding=\"utf-8\") as xhtml_w_file:\n xhtml_w_file.writelines(xhtml_data)\n\n\n\n\n\n\n\n\n tot_changes += n_changes\n n_content_changes += n_changes\n\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... deleting old validation...js files in ebook\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n #\n # only_files = [f for f in listdir(self.misc_path_file_name) if isfile(join(self.misc_path_file_name, f))]\n # for f in only_files:\n # if \"validation.js\" in f or \"validation_fr.js\" in f or \"validation_fr_jo.js\" in f or \"validation_fr_jo_v02_00.js\" in f or \"validation_fr_jo-v2.js\" in f or \"validation_fr_jo_v2.js\" in f:\n # os.remove(self.misc_path_file_name + f)\n # n_changes += 1\n # tot_changes += n_changes\n # n_content_changes += n_changes\n\n # CHANGE #6c\n # ===================\n # copy the new js validation script in the ebook\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... importing validation_fr_jo_v02_01.js\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # sce_file = \"\".join([self.js_css_path, \"validation_fr_jo_v02_02.js\"])\n # dst_file = \"\".join([self.misc_path_file_name, \"validation_fr_jo_v02_02.js\"])\n # copyfile(sce_file, dst_file)\n # n_styles_changes += 1\n # tot_changes += 1\n\n # CHANGE #6d\n # ===================\n # adapt the content.opf for the new validation_fr_jo_v02_01.js file\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # txt2add = \" \\n\"\n # v_return, n_changes = self.add_line(\"\".join([self.ops_path_dir, \"content.opf\"]), \"manifest\", txt2add)\n # msg = \"\".join([change_str, \"... ops.html modified .validation_fr_jo_v02_01.js added ...\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # if v_return != \"\":\n # self.manage_info(v_return, self.DISPLAY_AND_LOG)\n # n_content_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #7a fet_style file\n # ===================\n # delete old fet_style in content.opf\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... updating content.opf, deleting old_validation_fr lines\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n #\n # v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, \"/fet_styles\")\n # tot_changes += n_changes\n # n_content_changes += n_changes\n #\n # v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, \"/fet_style_v1r\")\n # tot_changes += n_changes\n # n_content_changes += n_changes\n\n # CHANGE #7b\n # ===================\n # delte all fet_style...css files in the ebook\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # n_changes = 0\n # msg = \"\".join([change_str, \"... deleting ols validation...js files in ebook\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n #\n # only_files = [f for f in listdir(self.style_path_name) if isfile(join(self.style_path_name, f))]\n # for f in only_files:\n # if \"fet_styles.css\" in f or \"fet_style_v1r.css\" in f:\n # os.remove(self.style_path_name + f)\n # n_changes += 1\n # tot_changes += n_changes\n # n_content_changes += n_changes\n\n # # CHANGE #7c\n # # ===================\n # # copy the new css fet_style_v1r script in the ebook\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... importing fet_styles_v02_01.css\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # sce_file = \"\".join([self.js_css_path, \"fet_styles_v02_01.css\"])\n # dst_file = \"\".join([self.style_path_name, \"fet_styles_v02_01.css\"])\n # copyfile(sce_file, dst_file)\n # n_styles_changes += 1\n # tot_changes += 1\n #\n # # CHANGE #7d\n # # ===================\n # # adapt the content.opf for the new fet_styles_v02_01.css file\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # n_changes = 0\n # txt2add = \" \\n\"\n # v_return, n_changes = self.add_line(\"\".join([self.ops_path_dir, \"content.opf\"]), \"manifest\", txt2add)\n # msg = \"\".join([change_str, \"... ops.html modified fet_style_v1r added ...\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # if v_return != \"\":\n # self.manage_info(v_return, self.DISPLAY_AND_LOG)\n # n_content_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #8a pw_table_style.css\n # ===================\n # delete old pw_table_stale in content.opf\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... updating content.opf, deleting pw_table_style.ccs lines\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n #\n # v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, \"/pw_table_style\")\n # tot_changes += n_changes\n # n_content_changes += n_changes\n #\n # v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, \"/pw_table_style\")\n # tot_changes += n_changes\n # n_content_changes += n_changes\n\n # CHANGE #8b\n # ===================\n # delte all pw_table_style...css files in the ebook\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # n_changes = 0\n # msg = \"\".join([change_str, \"... deleting old pw_table_style...js files in ebook\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n #\n # only_files = [f for f in listdir(self.style_path_name) if isfile(join(self.style_path_name, f))]\n # for f in only_files:\n # if \"pw_table_style.css\" in f or \"pw_table_style_v1r.css\" in f:\n # os.remove(self.style_path_name + f)\n # n_changes += 1\n # tot_changes += n_changes\n # n_content_changes += n_changes\n\n # # CHANGE #8c\n # # ===================\n # # copy the new css pw_table_style_v1r script in the ebook\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... importing pw_table_style_v02_01.css\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # sce_file = \"\".join([self.js_css_path, \"pw_table_style_v02_01.css\"])\n # dst_file = \"\".join([self.style_path_name, \"pw_table_style_v02_01.css\"])\n # copyfile(sce_file, dst_file)\n # n_styles_changes += 1\n # tot_changes += 1\n #\n # # CHANGE #8d\n # # ===================\n # # adapt the content.opf for the new pw_table_style_v1r.css file\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # n_changes = 0\n # txt2add = \" \\n\"\n # v_return, n_changes = self.add_line(\"\".join([self.ops_path_dir, \"content.opf\"]), \"manifest\", txt2add)\n # msg = \"\".join([change_str, \"... ops.html modified pw_table_style_v02_00 added ...\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # if v_return != \"\":\n # self.manage_info(v_return, self.DISPLAY_AND_LOG)\n # n_content_changes += n_changes\n # tot_changes += n_changes\n\n\n # CHANGE #9\n # ===================\n # change the cover item in content.opf\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... updating cover in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n old_txt = \"\"\n new_txt = \"\"\n v_return, n_changes = self.change_txt(self.content_path_file_name, old_txt, new_txt)\n tot_changes += n_changes\n n_content_changes += n_changes\n\n\n # CHANGE #10\n # ===================\n # change the id of the title\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... correcting the title of the book in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n v_tag = \"dc:title\"\n old_title = self.get_id_value(self.content_path_file_name, v_tag)\n new_title = os.path.basename(self.in_file_name).replace(\".epub\", \"\").replace(\"_\", \" \")\n v_return, n_changes = self.change_txt(self.content_path_file_name, old_title, new_title)\n if v_return != \"\":\n self.manage_info(v_return, self.DISPLAY_AND_LOG)\n n_text_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #11\n # ===================\n # delete line with nav.html in content.opf \n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... deleting line with 'Text/nav.html' line in content.opf\"])\n line2delete = \"Text/nav.html\"\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, line2delete)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_content_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #12\n # ===================\n # delete line in content.opf \n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... deleting line with ''in content.opf\"])\n # line2delete = \"\"\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # v_return, n_changes = self.del_line_in_content_opf(self.content_path_file_name, line2delete)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # n_content_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #13\n # ===================\n # change the the type of js files\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... correcting the type of js files in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n old_type = \"text/javascript\"\n new_type = \"application/javascript\"\n v_return, n_changes = self.change_txt(self.content_path_file_name, old_type, new_type)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_content_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #14\n # ===================\n # change the the cover id in content.opf\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... changing \\\"cover-image\\\" in content=\\\"cover\\\" in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n old_type = \"content=\\\"cover-image\\\"\"\n new_type = \"content=\\\"cover\\\"\"\n v_return, n_changes = self.change_txt(self.content_path_file_name, old_type, new_type)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_content_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #15\n # ===================\n # change the the type linear='no' en linear='yes'\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... changing linear=no in linear=yes in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n old_type = \"linear=\\\"no\\\"/>\"\n new_type = \"linear=\\\"yes\\\"/>\"\n v_return, n_changes = self.change_txt(self.content_path_file_name, old_type, new_type)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_content_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #16\n # ===================\n # change text-align for exercices.css\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \"\".join([change_str, \"... correcting the type of js files in content.opf\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n old_type = \"text-align:initial;\"\n new_type = \"text-align:left;\"\n v_return, n_changes = self.change_txt(self.style_exercices_path_file_name, old_type, new_type)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_styles_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #17\n # ===================\n # change background colors in pw_table_style\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... correcting background colors in pw_table_style\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # old_type = \"background: linear-gradient(to right, #1eb2d7 , #c1e2f1 95%);\"\n # new_type = \"\"\n # v_return, n_changes = self.change_txt(self.style_pw_table_path_file_name, old_type, new_type)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # n_styles_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #18\n # ===================\n # change -webkit-linear-gradient to backgrouncolor\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # msg = \"\".join([change_str, \"... correcting background colors in pw_table_style\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # old_type = \"background: -webkit-linear-gradient(left, #1eb2d7 ,#c1e2f1 95%);\"\n # new_type = \"background-color: #1eb2d7;\"\n # v_return, n_changes = self.change_txt(self.style_pw_table_path_file_name, old_type, new_type)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # n_styles_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #19\n # ===================\n # add new styles\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # n_changes = self.add_fet_style_line(self.style_path_file_name)\n # if n_changes > 0:\n # msg = \" \".join([change_str, self.content_path_file_name, str(n_styles_changes), \"new styles added ...\"])\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_styles_changes += n_changes\n\n # QUALITY IMPROVE #20\n # ===================\n # rename nav.html to nav.xhtml and update content.opf for that\n\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n old_path_name = self.nav_path_file_name.replace(\"//\", \"/\")\n if os.path.isfile(old_path_name):\n x = old_path_name.split(\".\")\n if x[1] == \"html\":\n new_path_name = \"\".join([x[0], \".x\", x[1]])\n v_return = self.rename_file(old_path_name, new_path_name)\n msg = \"\".join([change_str, \"... nav.html modified in nav.xhtml ...\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_nav_toc_changes += n_changes\n tot_changes += n_changes\n self.nav_path_file_name = new_path_name\n\n # self.content_path_file_name = \"\".join([self.ops_path_dir, \"content.opf\"])\n spine_found = False\n with open(self.content_path_file_name, \"r\", encoding=\"utf-8\") as opf_file_readable:\n opf_data = opf_file_readable.readlines()\n opf_file_readable.close()\n with open(self.content_path_file_name, \"w\", encoding=\"utf-8\") as opf_file_writable:\n for l in opf_data:\n l_new = l\n if \"\" in l:\n spine_found = False\n\n if spine_found:\n if \"nav.html\" in l:\n l_new = l.replace(\"nav.html\", \"nav.xhtml\")\n n_content_changes += 1\n tot_changes += 1\n elif \"idref=\\\"nav\\\"\" in l:\n l_new = l.replace(\"idref=\\\"nav\\\"\", \"idref=\\\"nav.xhtml\\\"\")\n n_content_changes += 1\n tot_changes += 1\n\n if \"\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n txt2add = \"\\n\"\n to_add = True\n del_txt = \"id=\\\"nav\\\"\"\n # check if text allready exist\n with open(self.content_path_file_name, \"r\", encoding=\"utf-8\") as opf_file:\n xml_opf_lines = [x.strip() for x in opf_file.readlines()]\n opf_file.close()\n for line in xml_opf_lines:\n if line == txt2add:\n to_add = False\n break\n new_xml = []\n for line in xml_opf_lines:\n if not del_txt in line:\n new_xml.append(line + \"\\n\")\n with open(self.content_path_file_name, \"w\", encoding=\"utf-8\") as opf_file:\n opf_file.writelines(new_xml)\n\n\n\n if to_add:\n v_return, n_changes = self.add_line(self.content_path_file_name, \"manifest\", txt2add)\n msg = \"\".join([change_str, \"... ops.html modified updated ...\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n n_content_changes += n_changes\n tot_changes += n_changes\n\n # CHANGE #22\n # ===================\n # adapt the head of the nav file\n # change_no += 1\n # change_str = \" #\" + str(change_no) + \": \"\n # txt2add = \"\"\n # v_return, n_changes = self.add_line(self.nav_path_file_name, \"head\", txt2add)\n # msg = \"\".join([change_str, \"... nav.html modified ./Styles/pw_table_style.css added ...\"])\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # n_nav_toc_changes += n_changes\n # tot_changes += n_changes\n\n # change 23\n change_no += 1\n change_str = \" #\" + str(change_no) + \": \"\n msg = \" \".join([change_str, \"... correcting the th_... and ex_... xhtml files\"])\n change_str = \" -> #\" + str(change_no) + \": \"\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n\n # for the files th_, ex_, con\n for (v_path, v_dirs, v_files) in walk(self.text_path_dir):\n for v_file in v_files:\n # if v_file[:3] in [\"th_\", \"ex_\", \"con\", \"nav\"]:\n if True: # v_file[:3] in [\"th_\", \"ex_\", \"con\", \"pag\"]:\n v_file_path_name = \"\".join([v_path, v_file])\n\n # QUALITY IMPROVE #23a\n # ===================\n # remove the h1 empty title in all .xhtml files\n change_str = \" -> #\" + str(change_no) + \"a: \"\n v_return, n_changes = self.change_txt(v_file_path_name, \"


    \", \"\")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"h1 empty titles removed\"])\n if self.VERBOSE:\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n else:\n self.manage_info(msg, self.LOG_ONLY)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n tot_changes += n_changes\n n_text_changes += n_changes\n\n # CHANGE #23b\n # ===================\n # delete all old validation reference in all .xhtml files\n # change_str = \" -> #\" + str(change_no) + \"b1: \"\n # # print(v_file_path_name)\n # n_del = 0\n # v_return, n_changes = self.remove_txt(v_file_path_name, \"\")\n # n_del += n_changes\n # v_return, n_changes = self.remove_txt(v_file_path_name, \"\")\n # n_del += n_changes\n # v_return, n_changes = self.remove_txt(v_file_path_name, \"\")\n # n_del += n_changes\n #\n # if n_del > 0:\n # msg = \" \".join([change_str, v_file, str(n_del), \"correcting xhtml files for validation_fr_jo.js\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_del\n # n_text_changes += n_del\n #\n # # insert the right validation reference in all .xhtml files\n # if n_del > 0:\n # change_str = \" -> #\" + str(change_no) + \"b2: \"\n # txt_2_add = \"\\n\"\n # v_return, n_changes = self.add_line(v_file_path_name, \"head\", txt_2_add)\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for validation_fr_jo.js\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_text_changes += n_changes\n #\n # # delete all old fet_styles reference in all .xhtml files\n # change_str = \" -> #\" + str(change_no) + \"b3: \"\n # v_return, n_changes = self.remove_txt(v_file_path_name, \"\")\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for fet_styles...css\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_text_changes += n_changes\n\n # insert the right fet_styles reference in all .xhtml files\n # if n_changes > 0:\n # change_str = \" -> #\" + str(change_no) + \"b4: \"\n # txt_2_add = \"\\n\"\n # v_return, n_changes = self.add_line(v_file_path_name, \"head\", txt_2_add)\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for fet_styles_v02_01.css\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_text_changes += n_changes\n\n # delete all old fet_styles reference in all .xhtml files\n # change_str = \" -> #\" + str(change_no) + \"b5: \"\n # v_return, n_changes = self.remove_txt(v_file_path_name, \"\")\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for pw_table_style...css\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_text_changes += n_changes\n\n # insert the right fet_styles reference in all .xhtml files\n # if n_changes > 0:\n # change_str = \" -> #\" + str(change_no) + \"b6: \"\n # txt_2_add = \"\\n\"\n # v_return, n_changes = self.add_line(v_file_path_name, \"head\", txt_2_add)\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for pw_table_style_v02_01.css\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # tot_changes += n_changes\n # n_text_changes += n_changes\n\n # CHANGE #23c\n # ===================\n # change MathML declaration in all .xhtml files\n change_str = \" -> #\" + str(change_no) + \"c: \"\n old_mathml_txt = \"\"\n new_mathml_txt = \"\"\n v_return, n_changes = \\\n self.change_txt(v_file_path_name, old_mathml_txt, new_mathml_txt)\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for MathML declaration\"])\n if self.VERBOSE:\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n else:\n self.manage_info(msg, self.LOG_ONLY)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n tot_changes += n_changes\n n_text_changes += n_changes\n\n # CHANGE #23d\n # ===================\n # delte the pw_add_cont in the path of file in all .xhtml files\n change_str = \" -> #\" + str(change_no) + \"d: \"\n v_return, n_changes = self.change_txt(v_file_path_name, \"../PW_add_cont/Misc/src\", \"../Misc\")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for pw_add_cont\"])\n if self.VERBOSE:\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n else:\n self.manage_info(msg, self.LOG_ONLY)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n tot_changes += n_changes\n n_text_changes += n_changes\n\n # CHANGE #23e\n # ===================\n # delete the pw_add_cont in the path of file in all .xhtml files\n change_str = \" -> #\" + str(change_no) + \"e: \"\n v_return, n_changes = self.change_txt(v_file_path_name, \"../PW_add_cont/Misc\", \"../Misc\")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for pw_add_cont\"])\n if self.VERBOSE:\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n else:\n self.manage_info(msg, self.LOG_ONLY)\n if v_return != \"\":\n self.manage_info((v_return, self.DISPLAY_AND_LOG))\n tot_changes += n_changes\n n_text_changes += n_changes\n\n # CHANGE #23f\n # ===================\n # change the #\" + str(change_no) + \"f: \"\n v_return, n_changes = self.change_txt(v_file_path_name, \"\", \"\")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for #\" + str(change_no) + \"g: \"\n # txt2add = \"\"\n # v_return, n_changes = self.add_line(v_file_path_name, \"head\", txt2add)\n # if n_changes > 0:\n # msg = \" \".join([change_str, v_file, str(n_changes), \"adapt the head of the text files for the new fet_styles\"])\n # if self.VERBOSE:\n # self.manage_info(msg, self.DISPLAY_AND_LOG)\n # else:\n # self.manage_info(msg, self.LOG_ONLY)\n # if v_return != \"\":\n # self.manage_info((v_return, self.DISPLAY_AND_LOG))\n # n_styles_changes += n_changes\n # tot_changes += n_changes\n\n # CHANGE #23h\n # ===================\n # in all xhtml files Images must begin with à capital letter I\n change_str = \" -> #\" + str(change_no) + \"h: \"\n v_return, n_changes = self.change_txt(v_file_path_name, \"images\", \"Images\")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"correcting xhtml files for #\" + str(change_no) + \"i: \"\n v_return, n_changes = self.change_formula(v_file_path_name, \"

    \", \"

    \",\n \"

    \", \"


    \")\n if n_changes > 0:\n msg = \" \".join([change_str, v_file, str(n_changes), \"inserting the use of the formula style ...\"])\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n if v_return != \"\":\n tot_changes += n_changes\n n_text_changes += n_changes\n if self.VERBOSE:\n self.manage_info(msg, self.DISPLAY_AND_LOG)\n else:\n self.manage_info(msg, self.LOG_ONLY)\n\n # CHANGE #24b\n # ===================\n # change the adapt the text for pw_reflow_elt\n change_str = \" -> #\" + str(change_no) + \"j: \"\n v_return, n_changes = self.comment_out_and_insert(v_file_path_name,\n \"
    \", \" 0:\n msg = \" \".join([change_str, v_file, str(n_changes),\n \"changind the
    #\" + str(change_no) + \"l: \"\n v_return, n_changes = self.remove_txt(v_file_path_name, \"\\n\"\n\n toc_beg = \"\\n\" \\\n \"\\n\" \\\n \"\\n\" \\\n \"\\n\" \\\n \"\tTable des matieres\\n\" \\\n \" \\n\" \\\n \" \\n\" \\\n \" \\n\" \\\n \" \\n\" \\\n \" \\n\" \\\n \"\\n\" \\\n \"\\n\" \\\n \"