diff --git "a/2528.jsonl" "b/2528.jsonl" new file mode 100644--- /dev/null +++ "b/2528.jsonl" @@ -0,0 +1,715 @@ +{"seq_id":"514547019","text":"import copy\nimport json\nfrom itertools import permutations, combinations\nfrom collections import OrderedDict\nfrom math import floor, ceil\nimport build_types\nimport random\n\ntypes = [\"Helmet\", \"Chestplate\", \"Leggings\", \"Boots\", \"Weapon\"]\nweapons = ['Dagger', 'Bow', 'Spear', 'Relik', 'Wand']\nidentifications = [\n 'health', 'healthRegen', 'healthRegenRaw', 'healthBonus',\n 'manaRegen', 'manaSteal',\n 'spellDamage', 'spellDamageRaw',\n 'damageBonus', 'damageBonusRaw',\n 'bonusEarthDamage', 'bonusThunderDamage', 'bonusWaterDamage', 'bonusFireDamage', 'bonusAirDamage',\n 'spellCostPct1', 'spellCostPct2', 'spellCostPct3', 'spellCostPct4',\n 'spellCostRaw1', 'spellCostRaw2', 'spellCostRaw3', 'spellCostRaw4',\n 'damage', 'earthDamage', 'thunderDamage', 'waterDamage', 'fireDamage', 'airDamage',\n 'attackSpeed', 'attackSpeedBonus', 'poison'\n]\nattack_speed_mod = {6: 4.3, 5: 3.1, 4: 2.5, 3: 2.05, 2: 1.5, 1: 0.83,\n 0: 0.51}\nskill_req = ['strength', 'dexterity', 'intelligence', 'defense', 'agility']\nskill_bonus = ['strengthPoints', 'dexterityPoints', 'intelligencePoints', 'defensePoints', 'agilityPoints']\nelement_short = {\"e\": \"earth\", \"t\": \"thunder\", \"w\": \"water\", \"f\": \"fire\", \"a\": \"air\"}\ndamagetype_to_sp = {\"earth\": \"strength\", \"thunder\": \"dexterity\", \"water\": \"intelligence\", \"fire\": \"defense\",\n \"air\": \"agility\"}\nsp_bonuses = {0: 0.0, 1: 0.01, 2: 0.02, 3: 0.029, 4: 0.039, 5: 0.049, 6: 0.058, 7: 0.067, 8: 0.077, 9: 0.086, 10: 0.095,\n 11: 0.104, 12: 0.113, 13: 0.122, 14: 0.131, 15: 0.139, 16: 0.148, 17: 0.157, 18: 0.165, 19: 0.173,\n 20: 0.182, 21: 0.19, 22: 0.198, 23: 0.206, 24: 0.214, 25: 0.222, 26: 0.23, 27: 0.238, 28: 0.246,\n 29: 0.253, 30: 0.261, 31: 0.268, 32: 0.276, 33: 0.283, 34: 0.29, 35: 0.298, 36: 0.305, 37: 0.312,\n 38: 0.319, 39: 0.326, 40: 0.333, 41: 0.34, 42: 0.346, 43: 0.353, 44: 0.36, 45: 0.366, 46: 0.373,\n 47: 0.379, 48: 0.386, 49: 0.392, 50: 0.399, 51: 0.405, 52: 0.411, 53: 0.417, 54: 0.423, 55: 0.429,\n 56: 0.435, 57: 0.441, 58: 0.447, 59: 0.453, 60: 0.458, 61: 0.464, 62: 0.47, 63: 0.475, 64: 0.481,\n 65: 0.486, 66: 0.492, 67: 0.497, 68: 0.503, 69: 0.508, 70: 0.513, 71: 0.518, 72: 0.523, 73: 0.528,\n 74: 0.533, 75: 0.538, 76: 0.543, 77: 0.548, 78: 0.553, 79: 0.558, 80: 0.563, 81: 0.568, 82: 0.572,\n 83: 0.577, 84: 0.581, 85: 0.586, 86: 0.591, 87: 0.595, 88: 0.599, 89: 0.604, 90: 0.608, 91: 0.612,\n 92: 0.617, 93: 0.621, 94: 0.625, 95: 0.629, 96: 0.633, 97: 0.638, 98: 0.642, 99: 0.646, 100: 0.65,\n 101: 0.654, 102: 0.657, 103: 0.661, 104: 0.665, 105: 0.669, 106: 0.673, 107: 0.676, 108: 0.68, 109: 0.684,\n 110: 0.687, 111: 0.691, 112: 0.694, 113: 0.698, 114: 0.701, 115: 0.705, 116: 0.708, 117: 0.712,\n 118: 0.715, 119: 0.718, 120: 0.722, 121: 0.725, 122: 0.728, 123: 0.731, 124: 0.735, 125: 0.738,\n 126: 0.741, 127: 0.744, 128: 0.747, 129: 0.75, 130: 0.753, 131: 0.756, 132: 0.759, 133: 0.762, 134: 0.765,\n 135: 0.768, 136: 0.771, 137: 0.773, 138: 0.776, 139: 0.779, 140: 0.782, 141: 0.784, 142: 0.787, 143: 0.79,\n 144: 0.792, 145: 0.795, 146: 0.798, 147: 0.8, 148: 0.803, 149: 0.805, 150: 0.808}\n\nwith open('powder_values.json', \"r\") as powder_file:\n powder_data = json.load(powder_file)\nwith open('rough_spell_values.json', \"r\") as rough_spell_info_file:\n rough_spell_data = json.load(rough_spell_info_file)\nwith open('set_bonus_values.json', \"r\") as set_bonus_file:\n set_bonus_data = json.load(set_bonus_file)\n\npowder_file.close()\nrough_spell_info_file.close()\nset_bonus_file.close()\n\n\ndef constrict(val, min_val, max_val):\n return max(min_val, min(val, max_val))\n\n\ndef add_req(item_obj, sp_dict):\n for point_type, value in sp_dict.items():\n if item_obj[point_type] > sp_dict[point_type]:\n sp_dict[point_type] = item_obj[point_type]\n return sp_dict\n\n\ndef add_sp(item_obj, sp_dict):\n for point_type, value in sp_dict.items():\n sp_dict[point_type] += item_obj[point_type + \"Points\"]\n return sp_dict\n\n\nclass Build:\n def __init__(self, type_=None, playstyle_=None, attribute_=None):\n self.build_data = {}\n self.build_stats = {}\n self.level = 101\n self.remaining_sp = (self.level - 1) * 2 # 200 sp\n self.type = type_\n self.playstyle = playstyle_\n self.attribute = attribute_\n if (not (self.type and self.playstyle and self.attribute)):\n self.type = build_types.BuildTypes.SPELL\n self.playstyle = build_types.BuildPlaystyles.LIGHT\n self.attribute = build_types.BuildAttributes.OFFENSIVE\n print(\"set default values for build\", self.type, self.playstyle, self.attribute)\n\n def __str__(self):\n gear_index = [\"Helmet\", \"Chestplate\", \"Leggings\",\n \"Boots\", \"Ring\", \"Ring2\", \"Bracelet\", \"Necklace\", \"Weapon\"]\n output = \"----ITEMS----\\n\"\n for gear_type, item in self.build_data.items():\n item_powders = \" \"\n for p in item.item_json[\"powders\"]:\n item_powders += p\n gear_index[gear_index.index(gear_type)] = item.item_json[\"name\"] + item_powders\n for item in gear_index:\n output += item + \"\\n\"\n output += \"----STATS----\\n\"\n for attr, value in self.build_stats.items():\n if value != 0:\n output += f'{attr}: {value}\\n'\n # output += \"----DAMAGE----\\n\"\n return output\n\n def add_item(self, item):\n item_copy = Item(copy.deepcopy(item)) # make a copy so it isn't affected in itemDB\n item_type = \"Weapon\" if item_copy.item_json[\"equipType\"] == \"Weapon\" else item_copy.item_json[\"type\"]\n if item_copy.item_json[\"type\"] == \"Ring\" and \"Ring\" in self.build_data:\n self.build_data['Ring2'] = item_copy\n else:\n self.build_data[item_type] = item_copy\n\n def remove_item(self, category): # Deletes item from specified slot\n try:\n del self.build_data[category]\n except KeyError:\n print(f'Cannot find slot {category}')\n\n def set_weapon_powders(self, powders):\n self.build_data[\"Weapon\"].set_powders(powders)\n\n def get_powdered_dmg(self, conversion):\n return self.build_data[\"Weapon\"].calc_powdered_dmg(conversion)\n\n def calc_exact_dps(self):\n print(self.calc_equip())\n pass\n\n def calc_dps(self, fast=True): # calculates the rough dps of the build efficiently\n if fast:\n stats, weap_damage = self.calc_stats()\n else:\n stats = self.calc_equip()\n print(stats)\n spell_speed_mod = attack_speed_mod[stats[\"attackSpeed\"]]\n melee_speed_mod = attack_speed_mod[constrict(stats[\"attackSpeed\"] + stats['attackSpeedBonus'], 0, 6)]\n\n print(stats)\n total_melee_dps = 0\n total_melee_hit = 0\n total_spell_hit = 0\n weap_type_str = self.build_data[\"Weapon\"].to_json()[\"type\"]\n spell_info = rough_spell_data[weap_type_str]\n powdered_dmg = self.get_powdered_dmg(spell_info[\"conversion\"])\n\n # print(powdered_dmg)\n powdered_dmg = powdered_dmg[0]\n\n for dmg_type, dmg_amount in powdered_dmg.items():\n\n if dmg_type == \"damage\": # neutral damage;\n multiplier = (1 + sp_bonuses[stats[\"dexterityAssigned\"]]) + sp_bonuses[stats[\"strengthAssigned\"]] + (\n stats[\"damageBonus\"] / 100)\n total_melee_hit += dmg_amount[1] * multiplier + (stats[\"damageBonusRaw\"] + max(stats[\"poison\"] / 3, 0))\n total_melee_dps += (dmg_amount[1] * multiplier + (stats[\"damageBonusRaw\"])) * melee_speed_mod + max(\n stats[\"poison\"] / 3, 0)\n\n spell_multiplier = (1 + sp_bonuses[stats[\"dexterityAssigned\"]]) + sp_bonuses[\n stats[\"strengthAssigned\"]] + (stats[\"spellDamage\"] / 100)\n total_spell_hit += (dmg_amount[1] * spell_multiplier * spell_speed_mod * spell_info[\"spell_modifier\"]) + \\\n stats[\"spellDamageRaw\"] * spell_info[\"spell_modifier\"]\n else: # elemental damage\n sp_name = damagetype_to_sp[dmg_type]\n sp_assigned = stats[sp_name + \"Assigned\"]\n multiplier = (1 + sp_bonuses[stats[\"dexterityAssigned\"]] + sp_bonuses[stats[\"strengthAssigned\"]] +\n + sp_bonuses[sp_assigned] + (stats[\"damageBonus\"] + stats[\n \"bonus\" + dmg_type.capitalize() + \"Damage\"]) / 100)\n\n total_melee_hit += dmg_amount[1] * multiplier\n total_melee_dps += dmg_amount[1] * multiplier * melee_speed_mod\n\n spell_multiplier = (1 + sp_bonuses[stats[\"dexterityAssigned\"]] + sp_bonuses[stats[\"strengthAssigned\"]] +\n + sp_bonuses[sp_assigned] + (stats[\"spellDamage\"] + stats[\n \"bonus\" + dmg_type.capitalize() + \"Damage\"]) / 100)\n this_element_hit = dmg_amount[1] * spell_multiplier * spell_speed_mod * spell_info[\"spell_modifier\"]\n total_spell_hit += this_element_hit\n # print(sp_name, spell_multiplier, \"sp assigned\", ( sp_assigned ), \"this element hit\", this_element_hit)\n # print(spell_info)\n spell_cost_pct = stats[\"spellCostPct\" + str(spell_info[\"spell_num\"])]\n spell_cost_raw = stats[\"spellCostRaw\" + str(spell_info[\"spell_num\"])]\n spell_cost = spell_info[\"cost\"]\n int_reduction = sp_bonuses[stats[\"intelligenceAssigned\"]]\n total_spell_cost = max(1, floor(\n ceil(spell_cost * (1 - int_reduction) + spell_cost_raw) * (1 + spell_cost_pct / 100)))\n\n # print(\"pct\",spell_cost_pct,\"raw\",spell_cost_raw,\"spellcost:\",spell_cost,\"spellcostaftercalc\",total_spell_cost)\n # calculate the amount of spells that can be used in 1 cycle and divide by 4 (seconds)\n spells_per_sec = min((5 + 0.8 * min(stats[\"manaRegen\"], 19) + max(stats[\"manaSteal\"], 0)) / total_spell_cost,\n 10) / 4\n total_spell_dps = total_spell_hit * spells_per_sec\n\n # print(\"spell_hit\", total_spell_hit, \"spells per sec\",spells_per_sec,\"new spell dps\",total_spell_dps,\"mana regen:\", stats[\"manaRegen\"],\"mana steal:\",stats[\"manaSteal\"])\n\n # print(\"Melee Hit:\", total_melee_hit)\n # Melee dps = (base_dmg) * (str_bonus + melee_dmg% + ele% + sp_bonus%) * (speed_mod )\n # neutral = (base_dmg) * (str_bonus + melee_dmg%) * (speed_mod) + (raw melee) + max((poison / 3), 0)\n\n return total_melee_dps, total_spell_dps\n\n def calc_damages(self): # calculate the damage of each spell\n pass\n\n def calc_stats(self): # calculate the stats of the build\n # print (self.build_data[\"Weapon\"].calc_powdered_dmg())\n build_stats = {}\n weap_damage = self.build_data[\"Weapon\"].to_json()[\"damages\"].copy()\n for item in self.build_data.values():\n item_json = item.to_json()\n # print(\"calculating \" + item.to_json()[\"name\"])\n\n for identification in identifications + skill_bonus:\n if identification not in build_stats:\n build_stats[identification] = 0\n\n if identification in item.to_json():\n build_stats[identification] += item.to_json()[identification]\n for skill in skill_req:\n if skill not in build_stats:\n build_stats[skill] = 0\n\n if build_stats[skill] < item_json[skill]:\n build_stats[skill] = item_json[skill]\n build_stats[skill + \"Assigned\"] = constrict(build_stats[skill] + build_stats[skill + \"Points\"], 0, 150)\n\n return build_stats, weap_damage\n\n # print(self.build_stats)\n\n # THIS IS CALLED BY calc_equip!!!!!!!!!!!!!!!\n\n def good_equip(self):\n # Used to run every combo of item orders\n permutate_list = []\n # Points the permutations will start with (ex. no req items with pos sp don't need to be permutated)\n starting_points = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n weapon_points = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n # Points added at the end (items with all negative points can always go last)\n last_points = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n # Total sp req of the build\n req = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n for category, item in self.build_data.items():\n item = item.to_json()\n # Req info added in the itemDB, decided what kind of item it is for speed purposes.\n if not item['req_info']['no_req']:\n req = add_req(item, req)\n if item['type'] != 'Weapon':\n if item['req_info']['pos_sp_no_req']:\n for point_type, value in starting_points.items():\n starting_points[point_type] += item[point_type + \"Points\"]\n elif item['req_info']['neg_sp_only']:\n for point_type, value in starting_points.items():\n starting_points[point_type] += item[point_type + \"Points\"]\n elif not item['req_info']['no_sp']:\n permutate_list.append(item)\n else:\n weapon_points = add_sp(item, weapon_points)\n\n best_set_remaining = 99999 # super high because any build will beat this first try\n best_set = {}\n for test_set in permutations(permutate_list, len(permutate_list)):\n set_points = starting_points.copy()\n assigned_points = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0} # Tracks assigned points on the test\n\n for item in test_set:\n # Adding normal skill points from items\n for point_type, value in set_points.items():\n if item[point_type] > value and item[point_type] != 0: # 0 is default req (none) so we ignore them\n # Updating total assigned (can't be over 100 or 200 overall)\n assigned_points[point_type] += item[point_type] - set_points[point_type]\n # Updating the set points and adding bonus from the item\n set_points[point_type] = item[point_type]\n set_points[point_type] += item[point_type + \"Points\"]\n\n # Adding last_points (usually negative sp)\n for point_type, value in last_points.items():\n set_points[point_type] += last_points[point_type]\n if set_points[point_type] < req[point_type] and req[point_type] != 0:\n assigned_points[point_type] += req[point_type] - set_points[point_type]\n set_points[point_type] = req[point_type]\n\n if any(x > 100 for x in assigned_points.values()) or sum(assigned_points.values()) > self.remaining_sp:\n # Impossible Build\n pass\n\n elif sum(assigned_points.values()) < best_set_remaining:\n for item in test_set:\n print(item['name'], end=' ')\n print('is the best set')\n best_set_remaining = sum(assigned_points.values())\n best_set = set_points\n\n # Adding weapon points\n for point_type, value in starting_points.items():\n best_set[point_type] += weapon_points[point_type]\n print('BEST SET:', best_set)\n\n return best_set\n\n def equip_build(self, gear_set, total_req, starting_sp):\n best_set_stats = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0,\n 'assigned': 99999}\n best_assigned = {}\n for test_set in permutations(gear_set, len(gear_set)):\n possible = True\n points = starting_sp\n assigned = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n req = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n\n for item in test_set:\n for attr in skill_req:\n\n if item[attr] > points[attr]:\n assigned[attr] += item[attr] - points[attr]\n points[attr] += item[attr] - points[attr]\n\n if item[attr] > req[attr]: # updates the total reqs of the build\n req[attr] = item[attr]\n\n points[attr] += item[attr + \"Points\"] # adds item skill point bonuses\n\n # for attr in skill_req: # checks if any items would pop\n\n # if req[attr] > points[attr] and req[attr] > 0:\n # #points[\"total\"] += req[attr] - points[attr]\n # assigned[attr] += req[attr] - points[attr]\n # points[attr] = req[attr]\n if req[attr] > points[attr] and req[attr] > 0:\n assigned[attr] += req[attr] - points[attr]\n points[attr] = req[attr]\n\n for attr in skill_req:\n if total_req[attr] > points[attr] and total_req[attr] != 0:\n assigned[attr] += total_req[attr] - points[attr]\n points[attr] = total_req[attr]\n\n # Seeing if build is possible\n for attr in skill_req:\n if assigned[attr] > 100:\n possible = False\n break\n # checking if current set better than old best\n points_sum = sum(assigned.values())\n if points_sum < best_set_stats[\"assigned\"] and self.remaining_sp - points_sum >= 0 and possible == True:\n points['assigned'] = points_sum\n best_set_stats = points.copy()\n best_assigned = assigned.copy()\n\n # weapon_json = self.build_data[\"Weapon\"].to_json() # Add weapons sp to the final value\n # for skill in skill_req:\n # best_set_stats[skill] += weapon_json[skill + \"Points\"]\n print({**{key + \"Assigned\": value for key, value in best_assigned.items()}, **best_set_stats})\n return best_set_stats\n\n def get_build_req(self):\n total_req = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n for item in self.build_data.values():\n item_json = item.to_json()\n for skill in skill_req:\n if total_req[skill] < item_json[skill]:\n total_req[skill] = item_json[skill]\n return total_req\n\n def calc_equip(self):\n\n total_req = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n starting_sp = {\"strength\": 0, \"dexterity\": 0, \"intelligence\": 0, \"defense\": 0, \"agility\": 0}\n gear_set = []\n total_sp_bonus = self.remaining_sp\n\n for category, item in self.build_data.items():\n not_pos_sp_reqless = False\n item_json = item.to_json()\n\n for skill in skill_req:\n if item_json[skill] > total_req[skill]:\n total_req[skill] = item_json[skill]\n\n if item_json[skill + \"Points\"] != 0 and category != \"Weapon\":\n total_sp_bonus += min(item_json[skill + \"Points\"], 0)\n not_pos_sp_reqless = True\n\n if not_pos_sp_reqless: # checks if the item is reqless and only positive sp\n not_pos_sp_reqless = False # first set it to be like vaward\n for skill in skill_req:\n if item_json[skill] != 0 or item_json[\n skill + \"Points\"] < 0: # if it finds a req or -sp, then it will stop the loop\n print(\"marking\", item_json[\"name\"], \"as not positive sp reqless\")\n\n not_pos_sp_reqless = True\n break\n\n if not_pos_sp_reqless:\n # print(\"adding\",item_json[\"name\"],\"as item with sp and req\")\n gear_set.append(item_json)\n elif category != \"Weapon\":\n # print(\"adding\",item_json[\"name\"],\"as item with no req no -sp\")\n for skill in skill_req:\n starting_sp[skill] += item_json[skill + \"Points\"]\n\n if total_sp_bonus < sum(total_req.values()):\n pass\n # RETURN IMPOSSIBLE BUILD\n # print(gear_set)\n # print(total_req)\n # print(starting_sp)\n return self.equip_build(gear_set, total_req, starting_sp)\n\n def get_set_sp(self, gear_set):\n\n pass\n\n\nclass Item:\n def __init__(self, itemjson):\n self.item_json = itemjson\n self.item_json[\"powders\"] = []\n\n def __str__(self):\n return self.item_json[\"name\"]\n\n def add_lists(self, list1, list2): # creates new list\n return [x + y for x, y in zip(list1, list2)]\n\n def multi_list_by_const(self, list1, const):\n return [x * const for x in list1]\n\n def floor_recalculate_avg(self, damages):\n a = floor(damages[0])\n b = floor(damages[2])\n return [a, (a + b) / 2, b]\n\n def set_powders(self, powder_list): # set powder like [\"w6\", \"w6\"]\n if len(powder_list) > self.item_json['sockets']: # Checks if amount of powders is more than supported on item\n self.item_json[\"powders\"] = powder_list[:self.item_json['sockets']] # Uses indexing to find powders\n print(\"Failed to add\", str(powder_list[self.item_json['sockets']:]), \"item only supports\",\n self.item_json['sockets'], \"powders\")\n else:\n self.item_json[\"powders\"] = powder_list # If amount <= than supported on item, just applies adds them on\n\n def calc_powdered_dmg(self, conversion_values={}):\n conversion_values = {x: y for x, y in conversion_values.items() if y != 0}\n conversion_values = OrderedDict(conversion_values)\n if self.item_json[\"equipType\"] == \"Weapon\":\n weapon_dmgs = copy.deepcopy(self.item_json[\"damages\"])\n for powder in self.item_json[\"powders\"]:\n\n element = element_short[powder[0]]\n tier = powder[1]\n powder_specific_data = powder_data[element][tier]\n\n base = powder_specific_data[\"base\"]\n conversion = powder_specific_data[\"conversion\"]\n conversion_sum = sum(conversion_values.values()) # float between 0 and 1\n if element not in conversion_values:\n conversion_values[element] = 0\n if conversion_sum + conversion >= 1: # if conversion exceeds 1, add the remaining value\n conversion_values[element] += (1 - conversion_sum)\n else: # if not, its regular\n conversion_values[element] += conversion\n weapon_dmgs[element] = self.add_lists(base, weapon_dmgs[element])\n conversion_sum = sum(conversion_values.values())\n for convert_element, convert_value in conversion_values.items(): # use the calculated conversion values and update neutral and the element\n convert_damage = self.multi_list_by_const(weapon_dmgs[\"damage\"], convert_value)\n # new_neutral = self.multi_list_by_const(weapon_dmgs[\"damage\"], 1 - convert_value)\n weapon_dmgs[convert_element] = self.add_lists(weapon_dmgs[convert_element], convert_damage)\n weapon_dmgs[\"damage\"] = self.multi_list_by_const(weapon_dmgs[\"damage\"], 1 - conversion_sum)\n for dmg, dmg_list in weapon_dmgs.items(): # floor all values and recalculate the average\n weapon_dmgs[dmg] = self.floor_recalculate_avg(dmg_list)\n return weapon_dmgs, conversion_values\n else:\n raise SyntaxError(\"tried to calculate powdered damage on armor piece\")\n\n def to_json(self):\n return self.item_json\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":24205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"339997538","text":"from re import compile, sub\nfrom scrapy.utils.project import get_project_settings\n\n\ndef cast_number( obj ):\n\tif isinstance( obj, (str, unicode) ):\n\t\tif obj.isdigit():\n\t\t\treturn int( obj )\n\t\telse:\n\t\t\ttry:\n\t\t\t\tf = float( obj )\n\t\t\t\treturn f\n\t\t\texcept ValueError:\n\t\t\t\treturn obj\n\telse:\n\t\treturn obj\n\n\ndef extract_number( string ):\n\tsettings = get_project_settings()\n\t\n\t# convert comma to period (only if using ',' as decimal mark)\n\tif settings.get('DECIMAL_MARK') == ',' :\n\t\tstring = string.replace('.', '').replace(',', '.')\n\n\t# match digits and decimal point\n\tregex = compile( '\\d*\\.?\\d+' )\n\tchars = regex.findall( string )\n\n\treturn cast_number( ''.join( chars ) )\n\n\ndef parse_number_unit( string ):\n\t\"\"\"Return a list consisting in [number, unit]\"\"\"\n\t# extract number\n\tnumber = extract_number(string)\n\t# get unit\n\tunit = sub(r'\\d*\\.?\\d+', r'', string).replace(',', '').strip()\n\treturn [number, unit]\n\n\ndef clean_string( string ):\n\t# remove trailing whitespaces\n\ts = string.strip()\n\n\t# other cleanup here...\n\n\treturn s\n","sub_path":"scraper/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233207866","text":"import random\n\ndef inputList(l):\n size = int (input(\"Введите размер: \"))\n i = 0\n for item in range(0,size):\n l.append(int(input(str(i) + \": \")))\n i+=1\n return l\n\ndef outputList(l):\n print(\"\\n\")\n for item in l:\n print(item, end=\" \")\n\ndef bubleSort(l):\n size = len(l)\n for i in range(0,size - 1):\n for j in range(0,size - 1):\n if l[j] > l[j + 1]:\n l[j] , l[j+1] = l[j+1] , l[j]\n return l\n\ndef getEven(L):\n B = []\n for i in range(0,len(L)):\n if L[i] % 2 != 0 or L[i] == 1 and L[i] != 0:\n B.append(L[i])\n return B","sub_path":"Python/buble/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474810696","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 22 20:15:04 2020\n\n@author: nialb\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\n\nds_dir = 'Coronahack-Chest-XRay-Dataset'\n\nmetadata_names = []\nfile_names = []\n\nmd_names_no_file = []\nfile_names_no_md = []\n\nmetadata = pd.read_csv('Chest_xray_Corona_Metadata.csv')\n\nmetadata.drop(metadata.columns[0], axis = 1, inplace = True)\n\nmetadata_names = metadata['X_ray_image_name'].values\n\nfor root, dirs, files in os.walk(ds_dir):\n for name in files:\n file_names.append(name)\n metadata.loc[metadata['X_ray_image_name'] == name, 'orig_file_path'] = os.path.join(root, name)\n \nfor metadata_name in metadata_names:\n if metadata_name not in file_names:\n md_names_no_file.append(metadata_name)\n \nfor file_name in file_names:\n if file_name not in metadata_names:\n file_names_no_md.append(file_name)\n \nmissing_ds = pd.DataFrame()\nmissing_ds['metadata_without_file_names'] = md_names_no_file\nmissing_ds['files_without_metadata_names'] = file_names_no_md\n\nmissing_ds.to_csv('missing.csv', index=False)\nmetadata.to_csv('metadata_updated.csv', index=False)\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nplots= pd.DataFrame(columns=[])\nfig, ax =plt.subplots(1,3, figsize=(15, 7.5))\nsns.countplot(x=\"Label\", hue=\"Dataset_type\", data=metadata, ax=ax[0])\nsns.countplot(x=\"Label_1_Virus_category\", hue=\"Dataset_type\", data=metadata, ax=ax[1])\nsns.countplot(x=\"Label_2_Virus_category\", hue=\"Dataset_type\", data=metadata, ax=ax[2])\nfig.show()","sub_path":"missing-metadata-file-check.py","file_name":"missing-metadata-file-check.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387683281","text":"from django.shortcuts import HttpResponse\nfrom django.shortcuts import render\n\nfrom django.views.generic import ListView\nimport json\nimport DataFrameRendering.apps as apps\nimport numpy as np\nfrom DataFrameRendering.models import ReviewData\nfrom django import forms\nimport datetime\nimport matplotlib as plt\nfrom matplotlib.pyplot import subplots as sub\nfrom io import StringIO\n\n# todo add a method to add links\n\"\"\"\nThe url of the webpage. Here so it can changed easily later\n\"\"\"\n# todo change\nwebpageUrl = \"http://127.0.0.1:8000\"\n\n# todo add date filtering\n\"\"\"\nfilters the dataframe and only selects the rows in the dataframe that meet the criteria\n:param ReviewDataFrame: A dataframe of all of the reviews\n:param context: a contianer dictonary of all of the url parameters\n:return: A filtered set of data that contains the correct data for the parameters\n\"\"\"\n\n\ndef filter_Data_Frame(ReviewDataFrame, context):\n print(\"Filtering data\")\n\n filteredDataFrame = apps.ReviewDataFrame.copy()\n param = '_param'\n\n customer_id_param = context[\"customer_id\" + param]\n if customer_id_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['customer_id'].str.contains(customer_id_param)]\n\n review_id_param = context[\"review_id\" + param]\n if review_id_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['review_id'].str.contains(review_id_param)]\n\n product_id_param = context[\"product_id\" + param]\n if product_id_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['product_id'].str.contains(product_id_param)]\n\n product_parent_param = context[\"product_parent\" + param]\n if product_parent_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['product_parent'].str.contains(product_parent_param)]\n\n product_title_param = context[\"product_title\" + param]\n if product_title_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['product_title'].str.contains(product_title_param)]\n\n star_rating_min_param = context[\"star_rating_min\" + param]\n if star_rating_min_param != 1:\n filteredDataFrame = filteredDataFrame[filteredDataFrame['star_rating'] >= star_rating_min_param]\n\n star_rating_max_param = context[\"star_rating_max\" + param]\n if star_rating_max_param != 5:\n filteredDataFrame = filteredDataFrame[filteredDataFrame['star_rating'] <= star_rating_max_param]\n\n helpful_votes_min_param = context[\"helpful_votes_min\" + param]\n if helpful_votes_min_param != 0:\n filteredDataFrame = filteredDataFrame[filteredDataFrame['helpful_votes'] >= helpful_votes_min_param]\n\n helpful_votes_max_param = context[\"helpful_votes_max\" + param]\n if helpful_votes_max_param != float('inf'):\n filteredDataFrame = filteredDataFrame[filteredDataFrame['helpful_votes'] <= helpful_votes_max_param]\n\n total_votes_min_param = context[\"total_votes_min\" + param]\n if total_votes_min_param != 0:\n filteredDataFrame = filteredDataFrame[filteredDataFrame['total_votes'] >= total_votes_min_param]\n\n total_votes_max_param = context[\"total_votes_max\" + param]\n if total_votes_max_param != float('inf'):\n filteredDataFrame = filteredDataFrame[filteredDataFrame['total_votes'] <= total_votes_max_param]\n\n vine_param = context[\"vine\" + param]\n print(vine_param)\n if vine_param != \"Both\" and vine_param != \"\":\n print(\"should not trigger \" + vine_param)\n filteredDataFrame = filteredDataFrame[filteredDataFrame['vine'] == vine_param]\n\n Verified_purchase_param = context[\"Verified_purchase\" + param]\n print(Verified_purchase_param)\n if Verified_purchase_param != \"Both\" and Verified_purchase_param != \"\":\n print(Verified_purchase_param + \" Should not trigger\")\n filteredDataFrame = filteredDataFrame[filteredDataFrame['verified_purchase'] == Verified_purchase_param]\n\n\n\n review_headline_param = context[\"review_headline\" + param]\n if review_headline_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['review_headline'].str.contains(review_headline_param)]\n\n review_body_param = context[\"review_body\" + param]\n if review_body_param != \"\":\n filteredDataFrame = filteredDataFrame[filteredDataFrame['review_body'].str.contains(review_body_param)]\n\n start_date_param = context[\"start_date\" + param]\n if start_date_param != \"\" and start_date_param != \"dd/mm/yyyy\":\n pass\n filteredDataFrame = filteredDataFrame[filteredDataFrame['review_date'] >= start_date_param]\n\n end_date_param = context[\"end_date\" + param]\n if end_date_param != \"\" and end_date_param != \"dd/mm/yyyy\":\n pass\n filteredDataFrame = filteredDataFrame[filteredDataFrame['review_date'] <= end_date_param]\n\n duplicate_param = context[\"Duplicate_reviews\" + param]\n print(duplicate_param )\n if duplicate_param != \"Both\" and duplicate_param != \"\":\n duplicates = filteredDataFrame.duplicated(subset=['review_body'], keep=False)\n getOnlyDuplicates = duplicate_param == \"Y\"\n print(getOnlyDuplicates)\n print(\"should not trigger \" + duplicate_param)\n filteredDataFrame = filteredDataFrame[duplicates == getOnlyDuplicates]\n\n print(\"Finished filtering data\")\n numberPerPage = context['number_per_page' + param]\n pageNum = max(int(context['page_num' + param]), 1)\n return filteredDataFrame[(pageNum - 1) * numberPerPage:numberPerPage * pageNum]\n\n\n\"\"\"\nDisplays the table for the reviews as well as the search\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_reviews(request):\n global webpageUrl\n\n # ensure_data_loaded()\n # creates a context object dictoniary to use\n context = create_context(request)\n\n # seperated for testing if parameter is a then load 10 results\n\n filteredDataFrame = filter_Data_Frame(apps.ReviewDataFrame, context)\n\n print(\"Starting adding links\")\n # add a links feild so it can be used in the html to use the link\n links = []\n j = 0\n for i, row in filteredDataFrame.iterrows():\n links.append(webpageUrl + \"/product/?id=\" + filteredDataFrame.iloc[j, 2])\n j += 1\n filteredDataFrame[\"link\"] = links\n print(\"Added links\")\n\n # add a links feild so it can be used in the html to use the link\n customerLinks = []\n j = 0\n for i, row in filteredDataFrame.iterrows():\n customerLinks.append(webpageUrl + \"/customer/?id=\" + filteredDataFrame.iloc[j, 0])\n j += 1\n filteredDataFrame[\"customerLinks\"] = customerLinks\n print(\"Added links\")\n\n # convert to json\n json_records = filteredDataFrame.reset_index().to_json(orient='records')\n data = json.loads(json_records)\n\n context['data'] = data\n print(\"About to render\")\n return render(request, 'DataFrameRendering/Reviews.html', context)\n\n\n\"\"\"\nCreates a context with all of the arguments from the url\n:param request: the request made to the server\n:param data: a panda dataframe to use to display information in the template\n:return: dict_of_parameters a dictonary of the data and any arguments from the url\n\"\"\"\n\n\ndef create_context(request):\n global webpageUrl\n param = \"_param\"\n dict_of_parameters = {'customer_id' + param: request.GET.get(\"customer_id\", \"\"),\n 'review_id' + param: request.GET.get(\"review_id\", \"\"),\n 'product_id' + param: request.GET.get(\"product_id\", \"\"),\n 'product_parent' + param: request.GET.get(\"product_parent\", \"\"),\n 'product_title' + param: request.GET.get(\"product_title\", \"\"),\n 'star_rating_min' + param: request.GET.get(\"star_rating_min\", 1),\n 'star_rating_max' + param: request.GET.get(\"star_rating_max\", 5),\n 'helpful_votes_min' + param: request.GET.get(\"helpful_votes_min\", \"\"),\n 'helpful_votes_max' + param: request.GET.get(\"helpful_votes_max\", \"\"),\n 'total_votes_min' + param: request.GET.get(\"total_votes_min\", \"\"),\n 'total_votes_max' + param: request.GET.get(\"total_votes_max\", \"\"),\n 'vine' + param: request.GET.get(\"vine\", \"Both\"),\n 'Verified_purchase' + param: request.GET.get(\"Verified_purchase\", \"Both\"),\n 'review_headline' + param: request.GET.get(\"review_headline\", \"\"),\n 'review_body' + param: request.GET.get(\"review_body\", \"\"),\n 'start_date' + param: request.GET.get(\"start_date\", \"dd/mm/yyyy\"),\n 'end_date' + param: request.GET.get(\"end_date\", \"dd/mm/yyyy\"),\n 'Duplicate_reviews' + param: request.GET.get(\"Duplicate_reviews\", \"Both\"),\n 'number_per_page' + param: request.GET.get(\"number_per_page\", 100),\n 'page_num' + param: request.GET.get(\"page_num\", 1),\n \"home_url\": webpageUrl + \"/\",\n \"reviews_url\": webpageUrl + \"/reviews\",\n \"products_url\": webpageUrl + \"/products\",\n \"customers_url\": webpageUrl + \"/customers\",\n \"upload_files_url\": webpageUrl + \"/upload\",\n }\n star_ratings = [1, 2, 3, 4, 5, \"1\", \"2\", \"3\", \"4\", \"5\"]\n if dict_of_parameters['star_rating_min' + param] == \"\":\n dict_of_parameters['star_rating_min' + param] = 1\n elif dict_of_parameters['star_rating_min' + param] not in star_ratings:\n dict_of_parameters['star_rating_min' + param] = 1\n else:\n dict_of_parameters['star_rating_min' + param] = int(dict_of_parameters['star_rating_min' + param])\n\n if dict_of_parameters['star_rating_max' + param] == \"\":\n dict_of_parameters['star_rating_max' + param] = 5\n elif dict_of_parameters['star_rating_max' + param] not in star_ratings:\n dict_of_parameters['star_rating_max' + param] = 5\n else:\n dict_of_parameters['star_rating_max' + param] = int(dict_of_parameters['star_rating_max' + param])\n\n if dict_of_parameters['helpful_votes_min' + param] == \"\":\n dict_of_parameters['helpful_votes_min' + param] = 0\n else:\n try:\n dict_of_parameters['helpful_votes_min' + param] = int(dict_of_parameters['helpful_votes_min' + param])\n except:\n dict_of_parameters['helpful_votes_min' + param] = 0\n\n if dict_of_parameters['helpful_votes_min' + param] == \"\":\n dict_of_parameters['helpful_votes_max' + param] = float('inf')\n else:\n try:\n dict_of_parameters['helpful_votes_max' + param] = int(dict_of_parameters['helpful_votes_max' + param])\n except:\n dict_of_parameters['helpful_votes_max' + param] = float('inf')\n\n if dict_of_parameters['total_votes_min' + param] == \"\":\n dict_of_parameters['total_votes_min' + param] = 0\n else:\n try:\n dict_of_parameters['total_votes_min' + param] = int(dict_of_parameters['total_votes_min' + param])\n except:\n dict_of_parameters['total_votes_min' + param] = 0\n\n if dict_of_parameters['total_votes_min' + param] == \"\":\n dict_of_parameters['total_votes_max' + param] = float('inf')\n else:\n try:\n dict_of_parameters['total_votes_max' + param] = int(dict_of_parameters['total_votes_max' + param])\n except:\n dict_of_parameters['total_votes_max' + param] = float('inf')\n\n try:\n date = datetime.datetime.strptime(dict_of_parameters['start_date' + param],'%y/%m/%d')\n if date != None:\n dict_of_parameters['start_date' + param] = date\n else:\n dict_of_parameters['start_date' + param] = \"dd/mm/yyyy\"\n except:\n dict_of_parameters['start_date' + param] = \"dd/mm/yyyy\"\n\n\n try:\n date = datetime.datetime.strptime(dict_of_parameters['end_date' + param],'%y/%m/%d')\n if date != None:\n dict_of_parameters['end_date' + param] = date\n else:\n dict_of_parameters['end_date' + param] = \"dd/mm/yyyy\"\n except:\n dict_of_parameters['end_date' + param] = \"dd/mm/yyyy\"\n\n if dict_of_parameters['number_per_page' + param] == \"\":\n dict_of_parameters['number_per_page' + param] = 100\n else:\n try:\n dict_of_parameters['number_per_page' + param] = int(dict_of_parameters['number_per_page' + param])\n except:\n dict_of_parameters['number_per_page' + param] = 100\n\n if dict_of_parameters['page_num' + param] == \"\":\n dict_of_parameters['page_num' + param] = 1\n else:\n try:\n dict_of_parameters['page_num' + param] = int(dict_of_parameters['page_num' + param])\n except:\n dict_of_parameters['page_num' + param] = 1\n return dict_of_parameters\n\n\n\"\"\"\nDisplays the table for the products\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_products(request):\n # ensure_data_loaded(reviewData=False)\n context = create_context(request)\n\n df = apps.ProductDataFrame[:100]\n\n # add a links feild so it can be used in the html to use the link\n links = []\n j = 0\n for i, row in df.iterrows():\n links.append(webpageUrl + \"/product/?id=\" + df.iloc[j, 1])\n j += 1\n df[\"link\"] = links\n\n # parsing the DataFrame in json format.\n json_records = df.reset_index().to_json(orient='records')\n data = json.loads(json_records)\n\n # creats a context dictonary\n\n context['data'] = data\n return render(request, 'DataFrameRendering/Products.html', context)\n\n\n\n\"\"\"\nDisplays the table for the customers\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_customers(request):\n context = create_context(request)\n\n df = apps.CustomerDataFrame[:100]\n\n # add a links feild so it can be used in the html to use the link\n links = []\n j = 0\n for i, row in df.iterrows():\n links.append(webpageUrl + \"/customer/?id=\" + str(df.iloc[j, 1]))\n j += 1\n df[\"link\"] = links\n\n # parsing the DataFrame in json format.\n json_records = df.reset_index().to_json(orient='records')\n data = json.loads(json_records)\n\n # creats a context dictonary\n\n context['data'] = data\n return render(request, 'DataFrameRendering/Customers.html', context)\n\n\n\"\"\"\nThis displays the info for a product with an id\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_product_with_id(request):\n # ensure_data_loaded()\n context = create_context(request)\n\n # generate data for the review\n row_number = apps.ProductDataFrame['product_id'] == request.GET.get(\"id\", \"b\")\n json_records = apps.ProductDataFrame[row_number].reset_index().to_json(orient='records')\n product_data = json.loads(json_records)\n\n # generate data for the product\n row_numbers_review = apps.ReviewDataFrame['product_id'] == request.GET.get(\"id\", \"b\")\n\n json_records = apps.ReviewDataFrame[row_numbers_review].reset_index().to_json(orient='records')\n review_data = json.loads(json_records)\n\n # generate context dictionary\n\n context[\"reviewData\"] = review_data\n context[\"data\"] = product_data\n context[\"graph\"] = plot_example_grapgh (apps.ReviewDataFrame[row_numbers_review])\n return render(request, 'DataFrameRendering/SingleProduct.html', context)\n\n\n\"\"\"\nThis displays the info for a product with an id\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_customer_with_id(request):\n # ensure_data_loaded()\n context = create_context(request)\n\n # generate data for the review\n row_number = apps.CustomerDataFrame['customer_id'] == request.GET.get(\"id\", \"b\")\n json_records = apps.CustomerDataFrame[row_number].reset_index().to_json(orient='records')\n product_data = json.loads(json_records)\n\n # generate data for the product\n row_numbers_review = apps.ReviewDataFrame['customer_id'] == request.GET.get(\"id\", \"b\")\n json_records = apps.ReviewDataFrame[row_numbers_review].reset_index().to_json(orient='records')\n review_data = json.loads(json_records)\n\n # generate context dictionary\n\n context[\"reviewData\"] = review_data\n context[\"data\"] = product_data\n return render(request, 'DataFrameRendering/SingleCustomer.html', context)\n\n\n\"\"\"\nThis displays the homepage of the website\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef get_homepage(request):\n context = create_context(request)\n return render(request, 'DataFrameRendering/Homepage.html', context)\n\n\n\"\"\"\nThis class is a file form that takes in 2 file inputs which are then uploaded and set as the new data\n\"\"\"\n\n\nclass UploadFileForm(forms.Form):\n ReviewDataFile = forms.FileField()\n ProductDataFile = forms.FileField()\n\n\n\"\"\"\n This method serves the upload file page. If it recieves files then it saves them and loads the new data\n:param request: the request made to the server\n:return: a render object that will be displayed on the browser\n\"\"\"\n\n\ndef upload_file(request):\n context = create_context(request)\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n print(\"Valid\")\n handle_uploaded_file(request.FILES['ReviewDataFile'], 'reviewData.tsv')\n handle_uploaded_file(request.FILES['ProductDataFile'], 'productData.csv')\n handle_uploaded_file(request.FILES['CustomerDataFile'], 'customerData.csv')\n apps.loadNewData('reviewData.tsv', 'productData.csv','customerData.csv')\n return render(request, 'DataFrameRendering/Upload.html', context)\n else:\n print(\"Not Valid\")\n else:\n form = UploadFileForm()\n context[\"form\"] = form\n return render(request, 'DataFrameRendering/Upload.html', context)\n\n\"\"\"\nThis plots an example grapgh of time vs review score\ninputs df: Dataframe the dataframe that contains the data\noutputs data: the imgdata of the graph\n\"\"\"\n\n\ndef plot_example_grapgh(df):\n dates = []\n scores = []\n for index,row in df.iterrows():\n dates.append(row['review_date'])\n scores.append(row['star_rating'])\n fig, ax = sub(figsize=(12, 12))\n ax.bar(dates,\n scores,\n color='purple')\n ax.set(xlabel=\"Date\",\n ylabel=\"Star ratings\",\n title=\"Star ratings over time\")\n ax.plot()\n imgdata = StringIO()\n fig.savefig(imgdata,format = 'svg')\n imgdata.seek(0)\n data = imgdata.getvalue()\n\n return data\n\n\"\"\"\nThis handles saving a file from an upload to the server. It saves it in this directory as the filename.\n:param f: the file object so save\n:param fileName: String what to save the file as\n\"\"\"\n\ndef handle_uploaded_file(f, fileName):\n with open(fileName, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n\n\"\"\"\nFor testing\n\"\"\"\n\n\"\"\"\nFor testing\n\"\"\"\n\n\ndef ProductView(request):\n # ensure_data_loaded(reviewData=False)\n df = apps.ProductDataFrame\n template = 'DataFrameRendering/product.html'\n\n # Format the column headers for the Bootstrap table, they're just a list of field names,\n # duplicated and turned into dicts like this: {'field': 'foo', 'title: 'foo'}\n columns = [{'name': 'tes', 'title': 't'}]\n # Write the DataFrame to JSON (as easy as can be)\n json = df.to_json(orient='records') # output just the records (no fieldnames) as a collection of tuples\n # Proceed to create your context object containing the columns and the data\n context = {\n 'data': json,\n 'columns': columns\n }\n print(columns)\n # And render it!\n return render(request, template, context)\n\n\n\"\"\" # product_id = models.ForeignKey(ProductData, on_delete=models.CASCADE)\n product_id = models.CharField(max_length=20)\n product_parent = models.CharField(max_length=20)\n product_title = models.TextField()\n star_rating = models.IntegerField()\n helpful_votes = models.IntegerField()\n total_votes = models.IntegerField()\n vine = models.BinaryField()\n verified_purchase = models.BinaryField()\n review_headline = models.CharField(max_length=200)\n review_body = models.TextField()\n review_date = models.DateField()\"\"\"\n\n\"\"\"\nFor testing\n\"\"\"\n\n\nclass ReviewForm(forms.Form):\n your_name = forms.CharField(label='Your name', max_length=100)\n","sub_path":"Stefan/Website/Visual/DataFrameRendering/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"603771378","text":"#!/usr/bin/python\r\n# Author: hongguiting\r\n# Date: 2015-12-14\r\nimport time\r\n\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.console_drv.console_drv import Console\r\nfrom libcom.lib_cmd.basic_cmd import BasicCmd\r\nfrom idm_common import *\r\n\r\n__all__ = [\"idm_power_cap\"]\r\n\r\nSUCCESS = 0\r\nFAIL = -1\r\n\r\ndef idm_power_cap_test(cb_arg):\r\n dev_key = cb_arg.dev_names[0]\r\n con = Console(dev_key)\r\n \r\n con.run_cmd('en')\r\n con.run_cmd('run-system-shell')\r\n card_info = con.run_cmd('me')\r\n dev_id = idm_get_devid(card_info) \r\n con.run_idm_mode()\r\n time.sleep(5)\r\n con.run_idm_cmd(\"cmdidm auto_debug_open\" )\r\n \r\n log_info(\"power_cap [dev_id=<1-2>] [is_lack=<0-1>] [redun_num=<1-3>].\\n\")\r\n for redun_num in range(2):\r\n info = con.run_idm_cmd(\"cmdidm power_cap dev_id=%d is_lack=0 redun_num=%d\" % (dev_id, redun_num))\r\n if (info.find('power cap fail') != -1):\r\n log_info(\"power cap fail 1!\")\r\n return FAIL\r\n \r\n if (info.find('POWER_ENOUGH') != -1):\r\n log_info(\"Power supply has been adequate, need not print syslog\")\r\n return FAIL\r\n \r\n for redun_num in range(2):\r\n info = con.run_idm_cmd(\"cmdidm power_cap dev_id=%d is_lack=1 redun_num=%d\" % (dev_id, redun_num))\r\n if (info.find('power cap fail') != -1):\r\n log_info(\"power cap fail 2!\")\r\n return FAIL\r\n \r\n if ((redun_num == 0) and (info.find('current system is in danger') == -1)):\r\n log_info(\"current system is in danger, but not print syslog\")\r\n return FAIL\r\n \r\n if ((redun_num == 1) and (info.find('please change to non-redundancy mode') == -1)):\r\n log_info(\"current system change to non-redundancy mode , but not!\")\r\n return FAIL \r\n \r\n for redun_num in range(2):\r\n info = con.run_idm_cmd(\"cmdidm power_cap dev_id=%d is_lack=0 redun_num=%d\" % (dev_id, redun_num))\r\n if (info.find('power cap fail') != -1):\r\n log_info(\"power cap fail 3!\")\r\n return FAIL \r\n if (info.find('POWER_ENOUGH') == -1 and redun_num == 0):\r\n log_info(\"current system NOT_ENOUGH to ENOUGH , need print syslog!\")\r\n return FAIL\r\n if (redun_num == 0):\r\n info = con.run_idm_cmd(\"cmdidm power_cap dev_id=%d is_lack=1 redun_num=1\" % (dev_id))\r\n \r\n con.quit_idm_mode() \r\n return SUCCESS\r\n \r\ndef idm_power_cap(cb_arg):\r\n if len(cb_arg.dev_names) == 0:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n \r\n dev_name = cb_arg.dev_names[0]\r\n con = Console(dev_name)\r\n con.wake_up()\r\n result = FAIL\r\n try:\r\n result = idm_power_cap_test(cb_arg)\r\n finally:\r\n con.exit()\r\n return result","sub_path":"cases_set/idm/idm_power_cap.py","file_name":"idm_power_cap.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"44967559","text":"#scraper.py\n\n\"\"\"\nThis script use selenium package in order to get information from github.\nIt searchs on github search field the world 'selenium' and check the validation\nof the result's links. After that, it uses get request in order to retrive information\nabout each result. in the end, it will connect to github_scrape database and insert every\nresult as new line in selenium table. The scripts movve between 5 first pages of the search result.\n\"\"\"\n\nimport time\nimport socket\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport mysql.connector\n\n\n# Chrome settings\noption = webdriver.ChromeOptions()\noption.add_argument('--headless')\noption.add_argument(\"--window-size=1920,1080\");\noption.add_argument(\"--disable-gpu\");\noption.add_argument(\"--disable-extensions\");\noption.add_argument(\"--proxy-server='direct://'\");\noption.add_argument(\"--proxy-bypass-list=*\");\noption.add_argument(\"--start-maximized\");\noption.add_argument(\"--headless\")\noption.add_argument('--no-sandbox')\n\ndriver = webdriver.Chrome(chrome_options=option)\n#driver = webdriver.Chrome(executable_path=r'/Scraper/chromedriver', chrome_options=option)\ndriver.get('https://www.github.com')\n\n############################### -db- #####################################\nwith open('host_ip.txt', 'r') as ip_file: \n\thost = ip_file.read()\nuser = 'root'\npasswd = '123'\ndatabase = 'github_scrape'\nprint('\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconnecting to github_scrape database')\ndb_connection = mysql.connector.connect(host=host, user=user, passwd=passwd, database=database, charset='utf8mb4', use_unicode=True)\ncursor = db_connection.cursor()\n###########################################################################\t\n\nXPATHS = {\n\t\t\t'title': \"//a[@class='v-align-middle']\",\n\t\t\t'description': \"//p[@class='col-12 col-md-9 d-inline-block text-gray mb-2 pr-4']\",\n\t\t\t'tags': \"//div[@class='topics-row-container col-12 col-md-9 d-inline-flex flex-wrap flex-items-center f6 my-1']\",\n\t\t\t'time': \"//p[@class='f6 text-gray mr-3 mb-0 mt-2']/relative-time\",\n\t\t\t'language': \"//div[@class='text-gray flex-auto min-width-0']\",\n\t\t\t'rate': \"//a[@class='muted-link']\",\n\t\t\t'next_page': \"//a[@class='next_page']\"\n}\n\n\n\ndef check_new_page_loaded(old_html):\n\t\"\"\"\n\t\t@Get- html body of old page\n\t\t@Description- Checks if html page has changed\n\t\t@Return- True if the page html body has changed, else returns False\n\t\"\"\"\n\tnew_html = driver.find_element_by_tag_name('html').text\n\tif old_html == new_html:\n\t\treturn False\n\treturn True\n\t\n\t\ndef wait_for(old_html, timeout=60):\n\t\"\"\"\n\t\t@Get- html body of old page\n\t\t@Description- confirms that the page has changed using heck_new_page_loaded function\n\t\t\tif the page did not changed, waits 0.1 sec and try again.\n\t\t@Return- page load time\n\t\"\"\"\n\tstart_time = time.time() \n\twhile time.time() < start_time + timeout: \n\t\tif check_new_page_loaded(old_html): \n\t\t\treturn time.time() - start_time \n\t\telse: \n\t\t\ttime.sleep(0.1) \n\traise Exception('WebPage Load Timeout')\n\n\t\ndef search(query):\n\t\"\"\"\n\t\t@Get- string to search in github\n\t\t@Description- confirms that the searched page has loaded using wait_for function\n\t\t@Return- page load time\n\t\"\"\"\n\tprint('-> \tSeraching -> {}'.format(query))\n\told_html = driver.find_element_by_tag_name('html').text\n\ts = driver.find_element_by_name('q')\n\ts.send_keys(query)\n\ts.send_keys(Keys.ENTER) \n\treturn wait_for(old_html)\n\t\n\t\ndef next_page():\n\t\"\"\"\n\t\t@Description- clicks on next-Page button and confirms that the next page has loaded using wait_for function\n\t\t@Return- page load time\n\t\"\"\"\n\tprint('-> \\nClicking next page')\n\told_html = driver.find_element_by_tag_name('html').text\n\tlink = driver.find_element_by_xpath(XPATHS['next_page']) \n\tlink.click()\n\treturn wait_for(old_html)\n\n\t\ndef new_page(page_link):\n\t\"\"\"\n\t\t@Get- link of page to load\n\t\t@Description- confirms that the page has loaded using wait_for function\n\t\t@Return- page load time\n\t\"\"\"\n\told_param = old_param = driver.find_element_by_tag_name('html').text\n\tdriver.get(page_link)\n\treturn wait_for(old_param)\n\n\t\ndef check_link_is_valid(page_link):\n\t\"\"\"\n\t\t@Get- link to a github page\n\t\t@Description- load the new page using new_page function.\n\t\t\tprints if the link is valid or not by checking the page title.\n\t\t\t\n\t\"\"\"\n\tnew_page(page_link)\n\tif driver.title == 'Page not found · GitHub':\n\t\tprint('-> \t{} is not valid'.format(page_link))\n\telse:\n\t\tprint('-> \t{} is valid'.format(page_link))\n\n\t\t\ndef get_page_links(): \n\t\"\"\"\n\t\t@Return- list of all the result links \n\t\"\"\" \n\ttitle = driver.find_elements_by_xpath(XPATHS['title'])\n\tlinks = [link.get_attribute('href') for link in title]\n\treturn links\n\t\n\t\ndef check_page_links():\n\t\"\"\"\n\t\t@Description- check validation of all result links in the current page\n\t\"\"\"\n\tprint(\"\\nChecking page's link\")\n\treturn [check_link_is_valid(link) for link in get_page_links()]\n\n\t\ndef check_description(descriptions, titles):\n\t\"\"\"\n\t\t@Get descriptions list and titles list\n\t\t@ Because not every result have a description, there ia a need to check the list and insert None where there is not description\n\t\t@Return- new description list\n\t\"\"\"\n\tparent = driver.find_elements_by_xpath(\"//div[@class='col-12 col-md-8 pr-md-3']\")\n\tfor i in range(len(titles)):\n\t\tval = parent[i].text.split('\\n')[1]\n\t\tif not val == descriptions[i]:\n\t\t\tdescriptions.insert(i,None)\n\treturn descriptions\n\t\n\t\ndef change_tags_format(page_tags):\n\t\"\"\"\n\t\t@Get- result's tags list\n\t\t@Return- new tag list that instead of \\n between every tag has ,\n\t\"\"\"\n\treturn [tags.replace('\\n', ', ') if not tags == None else None for tags in page_tags]\n\t\t\n\t\t\ndef check_tags(data):\n\t\"\"\"\n\t\t@Description- \tSome of the search results do not have tags, thus, they do not have specific div.\n\t\t\t\t\t\tin order to avoid off-by in the tag's data list, this function looks for\n\t\t\t\t\t\tresults that have only one div, meta div, and do not have tag div.\n\t\t@Gets- tag elements data list\n\t\t@Return- sorted list of tags with None where search result do not have tags\t\n\t\t\n\t\"\"\"\t \n\t#parent div contains tag div and meta_class div\t\n\tparent = driver.find_elements_by_xpath(\"//div[@class='col-12 col-md-8 pr-md-3']/div\") \n\ttag_class = 'topics-row-container col-12 col-md-9 d-inline-flex flex-wrap flex-items-center f6 my-1'\n\tmeta_class = 'd-flex flex-wrap'\n\thave_tag = []\n\t#if the first search result do not have tags\n\tif parent[0].get_attribute('class') == meta_class:\t\t\t\n\t\thave_tag.append(False)\n\tfor i in range(1,len(parent)):\n\t\tdiv_class = parent[i].get_attribute('class')\n\t\tif div_class == meta_class:\n\t\t\tif parent[i-1].get_attribute('class') == meta_class:\n\t\t\t\thave_tag.append(False)\n\t\t\telse:\n\t\t\t\thave_tag.append(True)\n\tnew_tags_data = data\t\t\t\n\tfor i in range(len(have_tag)):\n\t\tif not have_tag[i]:\n\t\t\tnew_tags_data.insert(i,None)\n\treturn change_tags_format(new_tags_data)\t\n\t\n\t\ndef get_element_by_attribure(attribute):\n\t\"\"\"\n\t\t@Get page attribute- one of ['title', 'description', 'tags', 'time', 'language', 'rate']\n\t\t@Return list of the attribute's data\n\t\"\"\"\n\treturn driver.find_elements_by_xpath(XPATHS[attribute])\n\t\n\t\ndef get_attributes_data(attributes_to_scrape):\n\t\"\"\"\n\t\t@Get page arttibutes list ['title', 'description', 'tags', 'time', 'language', 'rate']\n\t\t@Return\n\t\"\"\"\n\tattributes_data = []\n\tfor attribute in attributes_to_scrape:\n\t\tdata = get_element_by_attribure(attribute)\n\t\t#time attribute's handling is different than the rest\n\t\tif attribute == 'time': \t\t\t\t\t\t\t\t\n\t\t\tdata = [x.get_attribute('title') for x in data]\n\t\telse:\n\t\t\tdata = [x.text for x in data]\n\t\t\t#tags attribute's handling is different than the rest\n\t\t\tif attribute == 'tags':\t\t\t\t\t\t\t\t\n\t\t\t\tdata = check_tags(data)\n\t\t\t#description attribute's handling is different than the rest\n\t\t\telif attribute == 'description':\n\t\t\t\tdata = check_description(data, attributes_data[0])\n\t\tattributes_data.append(data)\n\treturn attributes_data\t\n\n\t\ndef insert_page_to_db(page_data):\n\t\"\"\"\n\t\t@Get- list of all page's relevant data\n\t\t@Description- insert the data into MYSQL database- github_scrape to selenium table\n\t\"\"\"\n\tprint('-> Insert page data to database')\n\tfor i in range(len(page_data[0])):\n\t\tsql = \"\"\"INSERT INTO selenium (title, description, tags, time, language, rate)\n\t\t\t\tVALUES (%s, %s, %s, %s, %s, %s)\"\"\"\n\t\t# values = (title[i], description[i], tags[i], time[i], language[i], rate[i])\n\t\tvalues = (page_data[0][i], page_data[1][i], page_data[2][i], page_data[3][i], page_data[4][i], page_data[5][i])\n\t\tcursor.execute(sql, values)\n\tdb_connection.commit()\n\n\ndef main():\t\n\tprint('Start scraping github:')\n\tprint('-> \t\tSearch query took- {}Sec'.format(search('selenium')))\n\t#first five pages\n\tfor i in range(5):\t\t\t\t\n\t\tif not i == 0:\n\t\t\t#Clicking next page\n\t\t\tload_time = next_page()\n\t\t\tprint('-> \tPage {} load took {}Sec'.format(i+1, load_time)) \n\t\t#arttibutes to look for\n\t\tattributes_to_scrape = ['title', 'description', 'tags', 'time', 'language', 'rate']\t\t\n\t\tpage_attributes_data = get_attributes_data(attributes_to_scrape)\n\t\tinsert_page_to_db(page_attributes_data)\n\t\tcurrent_page = driver.current_url\n\t\tcheck_page_links()\n\t\t# check_page_links function changes the driver page\t\n\t\tnew_page(current_page) \t\t\t\t\t\t\t\t\t\t\t\n\tdb_connection.close()\n\tprint('---Finished scraping github---')\n\t\n\t\nif __name__ == '__main__':\n\tmain()\n\n\t\n\t","sub_path":"scraper/trash/scraper_check_links_with_selenium.py","file_name":"scraper_check_links_with_selenium.py","file_ext":"py","file_size_in_byte":9121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"146673213","text":"import FWCore.ParameterSet.Config as cms\n\n# producer template\ndileptonProducer = cms.EDProducer('DileptonProducer',\n electronSrc = cms.InputTag(''),\n muonSrc = cms.InputTag(''),\n cut = cms.string('oppositeSign() && leading().pt() > 20.'),\n)\n\n# filter template\ndilepFilter = cms.EDFilter('DileptonCounter',\n src = cms.InputTag(''),\n min = cms.int32(1),\n)\n\n# monitor template\ndilepMonitor = cms.EDProducer('DileptonMonitor',\n src = cms.InputTag(''),\n categories = cms.PSet(\n ll = cms.string(''),\n ee = cms.string('isElEl()'),\n em = cms.string('isElMu()'),\n me = cms.string('isMuEl()'),\n mm = cms.string('isMuMu()'),\n ),\n)\n\n","sub_path":"DileptonSelector/python/dileptonModules_cfi.py","file_name":"dileptonModules_cfi.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595805645","text":"import inspect\nimport logging\nimport queue\nfrom functools import partial\nfrom itertools import chain, combinations, compress, groupby, product\nfrom pprint import pprint\nfrom time import time\n\nimport graph_tool.all as gt\nimport numpy as np\nfrom dask import bag, compute, delayed\nfrom numba import njit, prange\nfrom pymatgen.analysis.phase_diagram import GrandPotentialPhaseDiagram, PhaseDiagram\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.entries.computed_entries import ComputedEntry, GibbsComputedStructureEntry\nfrom pymatgen.entries.entry_tools import EntrySet\nfrom scipy.special import comb\nfrom tqdm import tqdm\n\nfrom rxn_network.analysis import PathwayAnalysis\nfrom rxn_network.entries import PDEntry, RxnEntries\nfrom rxn_network.helpers import (\n BalancedPathway,\n RxnPathway,\n expand_pd,\n find_interdependent_rxns,\n find_rxn_edges,\n generate_all_combos,\n get_rxn_cost,\n grouper,\n react_interface,\n)\nfrom rxn_network.reaction import (\n BalancedReaction,\n ComputedReaction,\n Reaction,\n ReactionError,\n)\n\n__author__ = \"Matthew McDermott\"\n__copyright__ = \"Copyright 2021, Matthew McDermott\"\n__version__ = \"1.1\"\n\n\nclass ReactionNetwork:\n \"\"\"\n This class creates and stores a weighted, directed graph in graph-tool\n that is a dense network of all possible chemical reactions (edges)\n between phase combinations (vertices) in a chemical system. Reaction\n pathway hypotheses are generated using pathfinding methods.\n \"\"\"\n\n def __init__(\n self,\n entries,\n n=2,\n temp=300,\n interpolate_comps=None,\n extend_entries=None,\n include_metastable=False,\n include_polymorphs=False,\n filter_rxn_energies=0.5,\n ):\n \"\"\"Initializes ReactionNetwork object with necessary preprocessing\n steps. This does not yet compute the graph.\n\n Args:\n entries ([ComputedStructureEntry]): list of ComputedStructureEntry-\n like objects to consider in network. These can be acquired\n from Materials Project (using MPRester) or created manually in\n pymatgen. Entries should have same compatability (e.g.\n MPCompability) for phase diagram generation.\n n (int): maximum number of phases allowed on each side of the\n reaction (default 2). Note that n > 2 leads to significant (\n and often intractable) combinatorial explosion.\n temp (int): Temperature (in Kelvin) used for estimating Gibbs\n free energy of formation, as well as scaling the cost function\n later during network generation. Must select from [300, 400,\n 500, ... 2000] K.\n extend_entries ([ComputedStructureEntry]): list of\n ComputedStructureEntry-like objects which will be included in\n the network even after filtering for thermodynamic stability.\n Helpful if target phase has a significantly high energy above\n the hull.\n include_metastable (float or bool): either a) the specified cutoff\n for energy per atom (eV/atom) above hull, or b) True/False\n if considering only stable vs. all entries. An energy cutoff of\n 0.1 eV/atom is a reasonable starting threshold for thermodynamic\n stability. Defaults to False.\n include_polymorphs (bool): Whether or not to consider non-ground\n state polymorphs. Defaults to False. Note this is not useful\n unless structural metrics are considered in the cost function\n (to be added!)\n filter_rxn_energies (float): Energy filter. Reactions with\n energy_per_atom > filter will be excluded from network.\n \"\"\"\n self.logger = logging.getLogger(\"ReactionNetwork\")\n self.logger.setLevel(\"INFO\")\n\n # Chemical system / phase diagram variables\n self._all_entries = entries\n self._max_num_phases = n\n self._temp = temp\n self._e_above_hull = include_metastable\n self._include_polymorphs = include_polymorphs\n self._elements = {\n elem for entry in self.all_entries for elem in entry.composition.elements\n }\n self._pd_dict, self._filtered_entries = self._filter_entries(\n entries, include_metastable, temp, include_polymorphs\n )\n self._entry_mu_ranges = {}\n self._pd = None\n self._rxn_e_filter = filter_rxn_energies\n\n if (\n len(self._elements) <= 10\n ): # phase diagrams take considerable time to build with 10+ elems\n self._pd = PhaseDiagram(self._filtered_entries)\n\n if interpolate_comps:\n interpolated_entries = []\n for comp in interpolate_comps:\n energy = self._pd.get_hull_energy(Composition(comp))\n interpolated_entries.append(\n PDEntry(comp, energy, attribute={\"interpolated\": True})\n )\n print(\"Interpolated entries:\", \"\\n\")\n print(interpolated_entries)\n self._filtered_entries.extend(interpolated_entries)\n\n if extend_entries:\n self._filtered_entries.extend(extend_entries)\n\n for idx, e in enumerate(self._filtered_entries):\n e.entry_idx = idx\n\n self.num_entries = len(self._filtered_entries)\n\n self._all_entry_combos = [\n set(combo)\n for combo in generate_all_combos(\n self._filtered_entries, self._max_num_phases\n )\n ]\n\n self.entry_set = EntrySet(self._filtered_entries)\n self.entry_indices = {e: idx for idx, e in enumerate(self._filtered_entries)}\n\n # Graph variables used during graph creation\n self._precursors = None\n self._all_targets = None\n self._current_target = None\n self._cost_function = None\n self._complex_loopback = None\n self._precursors_entries = None\n self._most_negative_rxn = None # used in piecewise cost function\n self._g = None # Graph object in graph-tool\n\n filtered_entries_str = \", \".join(\n [entry.composition.reduced_formula for entry in self._filtered_entries]\n )\n self.logger.info(\n f\"Initializing network with {len(self._filtered_entries)} \"\n f\"entries: \\n{filtered_entries_str}\"\n )\n\n def generate_rxn_network(\n self,\n precursors=None,\n targets=None,\n cost_function=\"softplus\",\n complex_loopback=True,\n ):\n \"\"\"\n Generates and stores the reaction network (weighted, directed graph)\n using graph-tool.\n\n Args:\n precursors ([ComputedEntry]): entries for all phases which serve as the\n main reactants; if None, a \"dummy\" node is used to represent any\n possible set of precursors.\n targets ([ComputedEntry]): entries for all phases which are the final\n products; if None, a \"dummy\" node is used to represent any possible\n set of targets.\n cost_function (str): name of cost function to use for entire network\n (e.g. \"softplus\").\n complex_loopback (bool): if True, adds zero-weight edges which \"loop back\"\n to allow for multi-step or autocatalytic-like reactions, i.e. original\n precursors can reappear many times and in different steps.\n \"\"\"\n self._precursors = set(precursors) if precursors else None\n self._all_targets = set(targets) if targets else None\n self._current_target = (\n {targets[0]} if targets else None\n ) # take first entry to be first designated target\n self._cost_function = cost_function\n self._complex_loopback = complex_loopback\n\n if not self._precursors:\n precursors_entries = RxnEntries(None, \"d\") # use dummy precursors node\n\n if self._complex_loopback:\n raise ValueError(\n \"Complex loopback can't be enabled when using a dummy precursors \"\n \"node!\"\n )\n else:\n precursors_entries = RxnEntries(precursors, \"s\")\n\n self._precursors_entries = precursors_entries\n\n g = gt.Graph() # initialization of graph obj in graph-tool\n\n g.vp[\"entries\"] = g.new_vertex_property(\"object\")\n g.vp[\"type\"] = g.new_vertex_property(\n \"int\"\n ) # Type 0: precursors, 1: reactants, 2: products, 3: target\n g.vp[\"bool\"] = g.new_vertex_property(\"bool\")\n g.vp[\"path\"] = g.new_vertex_property(\"bool\") # whether node is part of path\n g.vp[\"chemsys\"] = g.new_vertex_property(\"string\")\n\n g.ep[\"weight\"] = g.new_edge_property(\"double\")\n g.ep[\"rxn\"] = g.new_edge_property(\"object\")\n g.ep[\"bool\"] = g.new_edge_property(\"bool\")\n g.ep[\"path\"] = g.new_edge_property(\"bool\") # whether edge is part of path\n\n precursors_v = g.add_vertex()\n self._update_vertex_properties(\n g,\n precursors_v,\n {\n \"entries\": precursors_entries,\n \"type\": 0,\n \"bool\": True,\n \"path\": True,\n \"chemsys\": precursors_entries.chemsys,\n },\n )\n\n target_chemsys = set(\n list(self._current_target)[0].composition.chemical_system.split(\"-\")\n )\n entries_dict = {}\n idx = 1\n for entries in self._all_entry_combos:\n reactants = RxnEntries(entries, \"R\")\n products = RxnEntries(entries, \"P\")\n chemsys = reactants.chemsys\n if (\n self._precursors_entries.description == \"D\"\n and not target_chemsys.issubset(chemsys.split(\"-\"))\n ):\n continue\n if chemsys not in entries_dict:\n entries_dict[chemsys] = dict({\"R\": {}, \"P\": {}})\n\n entries_dict[chemsys][\"R\"][reactants] = idx\n self._update_vertex_properties(\n g,\n idx,\n {\n \"entries\": reactants,\n \"type\": 1,\n \"bool\": True,\n \"path\": False,\n \"chemsys\": chemsys,\n },\n )\n\n if (\n self._precursors_entries.description == \"D\"\n and not self._all_targets.issubset(entries)\n ):\n idx = idx + 1\n continue\n\n entries_dict[chemsys][\"P\"][products] = idx + 1\n self._update_vertex_properties(\n g,\n idx + 1,\n {\n \"entries\": products,\n \"type\": 2,\n \"bool\": True,\n \"path\": False,\n \"chemsys\": chemsys,\n },\n )\n idx = idx + 2\n\n g.add_vertex(idx) # add ALL precursors, reactant, and product vertices\n target_v = g.add_vertex() # add target vertex\n target_entries = RxnEntries(self._current_target, \"t\")\n self._update_vertex_properties(\n g,\n target_v,\n {\n \"entries\": target_entries,\n \"type\": 3,\n \"bool\": True,\n \"path\": True,\n \"chemsys\": target_entries.chemsys,\n },\n )\n\n self.logger.info(\"Generating reactions by chemical subsystem...\")\n\n all_edges = []\n\n all_rxn_combos = []\n start_time = time()\n\n for chemsys, vertices in entries_dict.items():\n precursor_edges = [\n [precursors_v, v, 0, None, True, False]\n for entry, v in vertices[\"R\"].items()\n if self._precursors_entries.description == \"D\"\n or entry.entries.issubset(self._precursors)\n ]\n\n target_edges = [\n edge\n for edge_list in map(\n partial(\n self._get_target_edges,\n current_target=self._current_target,\n target_v=int(target_v),\n precursors=self._precursors,\n max_num_phases=self._max_num_phases,\n entries_dict=entries_dict,\n complex_loopback=complex_loopback,\n ),\n vertices[\"P\"].items(),\n )\n for edge in edge_list\n if edge\n ]\n\n rxn_combos = product(vertices[\"R\"].items(), vertices[\"P\"].items())\n all_rxn_combos.append(rxn_combos)\n\n all_edges.extend(precursor_edges)\n all_edges.extend(target_edges)\n\n db = bag.from_sequence(\n chain.from_iterable(all_rxn_combos), partition_size=100000\n )\n reaction_edges = db.map_partitions(\n find_rxn_edges,\n cost_function=cost_function,\n rxn_e_filter=self._rxn_e_filter,\n temp=self.temp,\n num_entries=self.num_entries,\n ).compute()\n\n all_edges.extend(reaction_edges)\n\n g.add_edge_list(\n all_edges, eprops=[g.ep[\"weight\"], g.ep[\"rxn\"], g.ep[\"bool\"], g.ep[\"path\"]]\n )\n\n end_time = time()\n self.logger.info(\n f\"Graph creation took {round(end_time - start_time, 1)} seconds.\"\n )\n self.logger.info(\n f\"Created graph with {g.num_vertices()} nodes and {g.num_edges()} edges.\"\n )\n self._g = g\n\n def find_k_shortest_paths(self, k, verbose=True):\n \"\"\"\n Finds k shortest paths to current target using Yen's Algorithm.\n\n Args:\n k (int): desired number of shortest pathways (ranked by cost)\n verbose (bool): whether to print all identified pathways to the console.\n\n Returns:\n [RxnPathway]: list of RxnPathway objects containing reactions traversed on\n each path.\n \"\"\"\n g = self._g\n paths = []\n\n precursors_v = gt.find_vertex(g, g.vp[\"type\"], 0)[0]\n target_v = gt.find_vertex(g, g.vp[\"type\"], 3)[0]\n\n for num, path in enumerate(self._yens_ksp(g, k, precursors_v, target_v)):\n rxns = []\n weights = []\n\n for step, v in enumerate(path):\n g.vp[\"path\"][v] = True\n\n if (\n g.vp[\"type\"][v] == 2\n ): # add rxn step if current node in path is a product\n e = g.edge(path[step - 1], v)\n g.ep[\"path\"][e] = True # mark this edge as occurring on a path\n rxns.append(g.ep[\"rxn\"][e])\n weights.append(g.ep[\"weight\"][e])\n\n rxn_pathway = RxnPathway(rxns, weights)\n paths.append(rxn_pathway)\n\n if verbose:\n for path in paths:\n print(path, \"\\n\")\n\n return paths\n\n def find_all_rxn_pathways(\n self,\n k=15,\n precursors=None,\n targets=None,\n max_num_combos=4,\n chempots=None,\n consider_crossover_rxns=10,\n filter_interdependent=True,\n ):\n \"\"\"\n Builds the k shortest paths to provided targets and then seeks to combine\n them to achieve a \"net reaction\" with balanced stoichiometry. In other\n words, the full conversion of all intermediates to final products.\n Warning: this method can take a significant amount of time depending on the\n size of the network and the max_num_combos parameter. General\n recommendations are k = 15 and max_num_combos = 4, although a higher\n max_num_combos may be required to capture the full pathway.\n\n Args:\n k (int): Number of shortest paths to calculate to each target (i.e. if\n there are 3 targets and k=15, then 3x15 = 45 paths will be generated\n and the reactions from these will be combined.\n precursors ([ComputedEntry]): list of all precursor ComputedEntry\n objects; defaults to precursors provided when network was created.\n targets ([ComputedEntry]): list of all target ComputedEntry objects;\n defaults to targets provided when network was created.\n max_num_combos (int): upper limit on how many reactions to consider at a\n time (default 4).\n chempots ({Element: float}): dictionary of chemical potentials, used for\n identifying intermediate reactions open to a specific element\n consider_crossover_rxns (bool): Whether to consider \"crossover\" reactions\n between intermediates in other pathways. This can be crucial for\n generating realistic predictions and it is highly recommended;\n generally the added computational cost is extremely low.\n filter_interdependent (bool):\n\n Returns:\n ([CombinedPathway], PathwayAnalysis): Tuple containing list of\n CombinedPathway objects (sorted by total cost) and a PathwayAnalysis\n object with helpful analysis methods for hypothesized pathways.\n \"\"\"\n paths_to_all_targets = dict()\n\n if not targets:\n targets = self._all_targets\n else:\n targets = set(targets)\n\n if not precursors or set(precursors) == self._precursors:\n precursors = self._precursors\n else:\n self.set_precursors(precursors, self._complex_loopback)\n\n try:\n net_rxn = ComputedReaction(\n list(precursors), list(targets), num_entries=self.num_entries\n )\n except ReactionError:\n raise ReactionError(\n \"Net reaction must be balanceable to find all reaction pathways.\"\n )\n\n self.logger.info(f\"NET RXN: {net_rxn} \\n\")\n\n for target in targets:\n print(f\"PATHS to {target.composition.reduced_formula} \\n\")\n print(\"--------------------------------------- \\n\")\n self.set_target(target)\n paths = self.find_k_shortest_paths(k)\n paths = {\n rxn: cost\n for path in paths\n for (rxn, cost) in zip(path.rxns, path.costs)\n }\n paths_to_all_targets.update(paths)\n\n print(\"Finding crossover reactions paths...\")\n\n if consider_crossover_rxns:\n intermediates = {\n entry for rxn in paths_to_all_targets for entry in rxn.all_entries\n } - targets\n intermediate_rxns = self.find_intermediate_rxns(\n intermediates, targets, chempots\n )\n paths = {\n rxn: get_rxn_cost(rxn, self._cost_function, self.temp)\n for rxn in intermediate_rxns\n }\n paths_to_all_targets.update(paths)\n paths_to_all_targets.update(\n self.find_crossover_rxns(intermediates, targets)\n )\n\n paths_to_all_targets.pop(net_rxn, None)\n\n paths_to_all_targets = {\n k: v\n for k, v in paths_to_all_targets.items()\n if not (\n self._precursors.intersection(k._product_entries)\n or self._all_targets.intersection(k._reactant_entries)\n or len(k._product_entries) > 3\n )\n }\n\n rxn_list = [r for r in paths_to_all_targets.keys()]\n pprint(rxn_list)\n normalized_rxns = [Reaction.from_string(r.normalized_repr) for r in rxn_list]\n\n num_rxns = len(rxn_list)\n\n self.logger.info(f\"Considering {num_rxns} reactions...\")\n batch_size = 500000\n total_paths = []\n for n in range(1, max_num_combos + 1):\n if n >= 4:\n self.logger.info(f\"Generating and filtering size {n} pathways...\")\n all_c_mats, all_m_mats = [], []\n for combos in tqdm(\n grouper(combinations(range(num_rxns), n), batch_size),\n total=int(comb(num_rxns, n) / batch_size),\n ):\n comp_matrices = np.stack(\n [\n np.vstack([rxn_list[r].vector for r in combo])\n for combo in combos\n if combo\n ]\n )\n c_mats, m_mats = self._balance_path_arrays(\n comp_matrices, net_rxn.vector\n )\n all_c_mats.extend(c_mats)\n all_m_mats.extend(m_mats)\n\n for c_mat, m_mat in zip(all_c_mats, all_m_mats):\n rxn_dict = {}\n for rxn_mat in c_mat:\n reactant_entries = [\n self._filtered_entries[i]\n for i in range(len(rxn_mat))\n if rxn_mat[i] < 0\n ]\n product_entries = [\n self._filtered_entries[i]\n for i in range(len(rxn_mat))\n if rxn_mat[i] > 0\n ]\n rxn = ComputedReaction(\n reactant_entries, product_entries, entries=self.num_entries\n )\n cost = paths_to_all_targets[\n rxn_list[\n normalized_rxns.index(\n Reaction.from_string(rxn.normalized_repr)\n )\n ]\n ]\n rxn_dict[rxn] = cost\n p = BalancedPathway(rxn_dict, net_rxn, balance=False)\n p.set_multiplicities(m_mat.flatten())\n total_paths.append(p)\n\n if filter_interdependent:\n final_paths = set()\n for p in total_paths:\n interdependent, combined_rxn = find_interdependent_rxns(\n p, [c.composition for c in precursors]\n )\n if interdependent:\n continue\n final_paths.add(p)\n else:\n final_paths = total_paths\n\n return sorted(list(final_paths), key=lambda x: x.total_cost)\n\n def find_crossover_rxns(self, intermediates, targets):\n \"\"\"\n Identifies possible \"crossover\" reactions (i.e., reactions where the\n predicted intermediate phases result in one or more targets phases.\n\n Args:\n intermediates ([ComputedEntry]): List of intermediate entries\n targets ([ComputedEntry]): List of target entries\n\n Returns:\n [ComputedReaction]: List of crossover reactions\n \"\"\"\n all_crossover_rxns = dict()\n for reactants_combo in generate_all_combos(intermediates, self._max_num_phases):\n for products_combo in generate_all_combos(targets, self._max_num_phases):\n try:\n rxn = ComputedReaction(\n list(reactants_combo),\n list(products_combo),\n num_entries=self.num_entries,\n )\n except ReactionError:\n continue\n if rxn._lowest_num_errors > 0:\n continue\n path = {rxn: get_rxn_cost(rxn, self._cost_function, self._temp)}\n all_crossover_rxns.update(path)\n return all_crossover_rxns\n\n def find_intermediate_rxns(self, intermediates, targets, chempots=None):\n \"\"\"\n Identifies thermodynamically predicted reactions from intermediate to one or\n more targets using interfacial reaction method. This method has the unique benefit (\n compared to the find_crossover_rxns method) of identifying reactions open to a\n specfic element or producing 3 or more products.\n\n Args:\n intermediates ([ComputedEntry]): List of intermediate entries\n targets ([ComputedEntry]): List of target entries\n chempots ({Element: float}): Dictionary of chemical potentials used to\n create grand potential phase diagram by which interfacial reactions are\n predicted.\n\n Returns:\n [ComputedReaction]: List of intermediate reactions\n \"\"\"\n all_rxns = set()\n combos = list(generate_all_combos(intermediates, 2))\n for entries in tqdm(combos):\n n = len(entries)\n r1 = entries[0].composition.reduced_composition\n chemsys = {\n str(el) for entry in entries for el in entry.composition.elements\n }\n elem = None\n if chempots:\n elem = str(list(chempots.keys())[0])\n chemsys.update(elem)\n if chemsys == {elem}:\n continue\n\n if n == 1:\n r2 = entries[0].composition.reduced_composition\n elif n == 2:\n r2 = entries[1].composition.reduced_composition\n else:\n raise ValueError(\"Can't have an interface that is not 1 to 2 entries!\")\n\n if chempots:\n elem_comp = Composition(elem).reduced_composition\n if r1 == elem_comp or r2 == elem_comp:\n continue\n\n entry_subset = self.entry_set.get_subset_in_chemsys(list(chemsys))\n pd = PhaseDiagram(entry_subset)\n grand_pd = None\n if chempots:\n grand_pd = GrandPotentialPhaseDiagram(entry_subset, chempots)\n\n rxns = react_interface(r1, r2, pd, self.num_entries, grand_pd)\n rxns_filtered = {r for r in rxns if set(r._product_entries) & targets}\n if rxns_filtered:\n most_favorable_rxn = min(\n rxns_filtered,\n key=lambda x: (\n x.calculated_reaction_energy\n / sum([x.get_el_amount(elem) for elem in x.elements])\n ),\n )\n all_rxns.add(most_favorable_rxn)\n\n return all_rxns\n\n def set_precursors(self, precursors=None, complex_loopback=True):\n \"\"\"\n Replaces network's previous precursor node with provided new precursors.\n Finds new edges that link products back to reactants as dependent on the\n complex_loopback parameter.\n\n Args:\n precursors ([ComputedEntry]): list of new precursor entries\n complex_loopback (bool): if True, adds zero-weight edges which \"loop back\"\n to allow for multi-step or autocatalytic-like reactions, i.e. original\n precursors can reappear many times and in different steps.\n\n Returns:\n None\n \"\"\"\n g = self._g\n self._precursors = set(precursors) if precursors else None\n\n if not self._precursors:\n precursors_entries = RxnEntries(None, \"d\") # use dummy precursors node\n if complex_loopback:\n raise ValueError(\n \"Complex loopback can't be enabled when using a dummy precursors \"\n \"node!\"\n )\n else:\n precursors_entries = RxnEntries(precursors, \"s\")\n\n g.remove_vertex(gt.find_vertex(g, g.vp[\"type\"], 0))\n new_precursors_v = g.add_vertex()\n\n self._update_vertex_properties(\n g,\n new_precursors_v,\n {\n \"entries\": precursors_entries,\n \"type\": 0,\n \"bool\": True,\n \"path\": True,\n \"chemsys\": precursors_entries.chemsys,\n },\n )\n\n new_edges = []\n remove_edges = []\n\n for v in gt.find_vertex(g, g.vp[\"type\"], 1): # iterate over all reactants\n phases = g.vp[\"entries\"][v].entries\n\n remove_edges.extend(list(v.in_edges()))\n\n if precursors_entries.description == \"D\" or phases.issubset(\n self._precursors\n ):\n new_edges.append([new_precursors_v, v, 0, None, True, False])\n\n for v in gt.find_vertex(g, g.vp[\"type\"], 2): # iterate over all products\n phases = g.vp[\"entries\"][v].entries\n\n if complex_loopback:\n combos = generate_all_combos(\n phases.union(self._precursors), self._max_num_phases\n )\n else:\n combos = generate_all_combos(phases, self._max_num_phases)\n\n for c in combos:\n combo_phases = set(c)\n if complex_loopback and combo_phases.issubset(self._precursors):\n continue\n combo_entry = RxnEntries(combo_phases, \"R\")\n loopback_v = gt.find_vertex(g, g.vp[\"entries\"], combo_entry)[0]\n new_edges.append([v, loopback_v, 0, None, True, False])\n\n for e in remove_edges:\n g.remove_edge(e)\n\n g.add_edge_list(\n new_edges, eprops=[g.ep[\"weight\"], g.ep[\"rxn\"], g.ep[\"bool\"], g.ep[\"path\"]]\n )\n\n def set_target(self, target):\n \"\"\"\n Replaces network's current target phase with new target phase.\n\n Args:\n target (ComputedEntry): ComputedEntry-like object for new target phase.\n\n Returns:\n None\n \"\"\"\n g = self._g\n\n if target in self._current_target:\n return\n else:\n self._current_target = {target}\n\n g.remove_vertex(gt.find_vertex(g, g.vp[\"type\"], 3))\n new_target_entry = RxnEntries(self._current_target, \"t\")\n new_target_v = g.add_vertex()\n self._update_vertex_properties(\n g,\n new_target_v,\n {\n \"entries\": new_target_entry,\n \"type\": 3,\n \"bool\": True,\n \"path\": True,\n \"chemsys\": new_target_entry.chemsys,\n },\n )\n\n new_edges = []\n\n for v in gt.find_vertex(g, g.vp[\"type\"], 2): # search for all products\n if self._current_target.issubset(g.vp[\"entries\"][v].entries):\n new_edges.append(\n [v, new_target_v, 0, None, True, False]\n ) # link all products to new target\n\n g.add_edge_list(\n new_edges, eprops=[g.ep[\"weight\"], g.ep[\"rxn\"], g.ep[\"bool\"], g.ep[\"path\"]]\n )\n\n def set_cost_function(self, cost_function):\n \"\"\"\n Replaces network's current cost function with new function by recomputing\n edge weights.\n\n Args:\n cost_function (str): name of cost function. Current options are\n [\"softplus\", \"relu\", \"piecewise\"].\n\n Returns:\n None\n \"\"\"\n g = self._g\n self._cost_function = cost_function\n\n for e in gt.find_edge_range(g, g.ep[\"weight\"], (1e-8, 1e8)):\n g.ep[\"weight\"][e] = get_rxn_cost(g.ep[\"rxn\"][e],)\n\n @staticmethod\n def _get_target_edges(\n vertex,\n current_target,\n target_v,\n precursors,\n max_num_phases,\n entries_dict,\n complex_loopback,\n ):\n entry = vertex[0]\n v = vertex[1]\n\n edge_list = []\n phases = entry.entries\n if current_target.issubset(phases):\n edge_list.append([v, target_v, 0, None, True, False])\n\n if complex_loopback:\n combos = generate_all_combos(phases.union(precursors), max_num_phases)\n else:\n combos = generate_all_combos(phases, max_num_phases)\n\n if complex_loopback:\n for c in combos:\n combo_phases = set(c)\n if combo_phases.issubset(precursors):\n continue\n combo_entry = RxnEntries(combo_phases, \"R\")\n loopback_v = entries_dict[combo_entry.chemsys][\"R\"][combo_entry]\n\n edge_list.append([v, loopback_v, 0, None, True, False])\n\n return edge_list\n\n @staticmethod\n def _update_vertex_properties(g, v, prop_dict):\n \"\"\"\n Helper method for updating several vertex properties at once in a graph-tool\n graph.\n\n Args:\n g (gt.Graph): a graph-tool Graph object.\n v (gt.Vertex or int): a graph-tool Vertex object (or its index) for a vertex\n in the provided graph.\n prop_dict (dict): a dictionary of the form {\"prop\": val}, where prop is the\n name of a VertexPropertyMap of the graph and val is the new updated\n value for that vertex's property.\n\n Returns:\n None\n \"\"\"\n for prop, val in prop_dict.items():\n g.vp[prop][v] = val\n return None\n\n @staticmethod\n def _yens_ksp(\n g, num_k, precursors_v, target_v, edge_prop=\"bool\", weight_prop=\"weight\"\n ):\n \"\"\"\n Yen's Algorithm for k-shortest paths. Inspired by igraph implementation by\n Antonin Lenfant. Ref: Jin Y. Yen, \"Finding the K Shortest Loopless Paths\n in a Network\", Management Science, Vol. 17, No. 11, Theory Series (Jul.,\n 1971), pp. 712-716.\n\n Args:\n g (gt.Graph): the graph-tool graph object.\n num_k (int): number of k shortest paths that should be found.\n precursors_v (gt.Vertex): graph-tool vertex object containing precursors.\n target_v (gt.Vertex): graph-tool vertex object containing target.\n edge_prop (str): name of edge property map which allows for filtering edges.\n Defaults to the word \"bool\".\n weight_prop (str): name of edge property map that stores edge weights/costs.\n Defaults to the word \"weight\".\n\n Returns:\n List of lists of graph vertices corresponding to each shortest path\n (sorted in increasing order by cost).\n \"\"\"\n\n def path_cost(vertices):\n \"\"\"Calculates path cost given a list of vertices.\"\"\"\n cost = 0\n for j in range(len(vertices) - 1):\n cost += g.ep[weight_prop][g.edge(vertices[j], vertices[j + 1])]\n return cost\n\n path = gt.shortest_path(g, precursors_v, target_v, weights=g.ep[weight_prop])[0]\n\n if not path:\n return []\n a = [path]\n a_costs = [path_cost(path)]\n\n b = queue.PriorityQueue() # automatically sorts by path cost (priority)\n\n for k in range(1, num_k):\n try:\n prev_path = a[k - 1]\n except IndexError:\n print(f\"Identified only k={k} paths before exiting. \\n\")\n break\n\n for i in range(len(prev_path) - 1):\n spur_v = prev_path[i]\n root_path = prev_path[:i]\n\n filtered_edges = []\n\n for path in a:\n if len(path) - 1 > i and root_path == path[:i]:\n e = g.edge(path[i], path[i + 1])\n if not e:\n continue\n g.ep[edge_prop][e] = False\n filtered_edges.append(e)\n\n gv = gt.GraphView(g, efilt=g.ep[edge_prop])\n spur_path = gt.shortest_path(\n gv, spur_v, target_v, weights=g.ep[weight_prop]\n )[0]\n\n for e in filtered_edges:\n g.ep[edge_prop][e] = True\n\n if spur_path:\n total_path = root_path + spur_path\n total_path_cost = path_cost(total_path)\n b.put((total_path_cost, total_path))\n\n while True:\n try:\n cost_, path_ = b.get(block=False)\n except queue.Empty:\n break\n if path_ not in a:\n a.append(path_)\n a_costs.append(cost_)\n break\n\n return a\n\n @staticmethod\n @njit(parallel=True)\n def _balance_path_arrays(\n comp_matrices, net_coeffs, tol=1e-6,\n ):\n \"\"\"\n Fast solution for reaction multiplicities via mass balance stochiometric\n constraints. Parallelized using Numba.\n\n Args:\n comp_matrices ([np.array]): list of numpy arrays containing stoichiometric\n coefficients of all compositions in all reactions, for each trial\n combination.\n net_coeffs ([np.array]): list of numpy arrays containing stoichiometric\n coefficients of net reaction.\n tol (float): numerical tolerance for determining if a multiplicity is zero\n (reaction was removed).\n\n Returns:\n ([bool],[np.array]): Tuple containing bool identifying which trial\n BalancedPathway objects were successfully balanced, and a list of all\n multiplicities arrays.\n \"\"\"\n shape = comp_matrices.shape\n net_coeff_filter = np.argwhere(net_coeffs != 0).flatten()\n len_net_coeff_filter = len(net_coeff_filter)\n all_multiplicities = np.zeros((shape[0], shape[1]), np.float64)\n indices = np.full(shape[0], False)\n\n for i in prange(shape[0]):\n correct = True\n for j in range(len_net_coeff_filter):\n idx = net_coeff_filter[j]\n if not comp_matrices[i][:, idx].any():\n correct = False\n break\n if not correct:\n continue\n\n comp_pinv = np.linalg.pinv(comp_matrices[i]).T\n multiplicities = comp_pinv @ net_coeffs\n solved_coeffs = comp_matrices[i].T @ multiplicities\n\n if (multiplicities < tol).any():\n continue\n elif not (\n np.abs(solved_coeffs - net_coeffs)\n <= (1e-08 + 1e-05 * np.abs(net_coeffs))\n ).all():\n continue\n all_multiplicities[i] = multiplicities\n indices[i] = True\n\n filtered_indices = np.argwhere(indices != 0).flatten()\n length = filtered_indices.shape[0]\n filtered_comp_matrices = np.empty((length, shape[1], shape[2]), np.float64)\n filtered_multiplicities = np.empty((length, shape[1]), np.float64)\n\n for i in range(length):\n idx = filtered_indices[i]\n filtered_comp_matrices[i] = comp_matrices[idx]\n filtered_multiplicities[i] = all_multiplicities[idx]\n\n return filtered_comp_matrices, filtered_multiplicities\n\n @staticmethod\n def _filter_entries(all_entries, e_above_hull, temp, include_polymorphs=False):\n \"\"\"\n Helper method for filtering entries by specified energy above hull\n\n Args:\n all_entries ([ComputedEntry]): List of ComputedEntry-like objects to be\n filtered\n e_above_hull (float): Thermodynamic stability threshold (energy above hull)\n [eV/atom]\n include_polymorphs (bool): whether to include higher energy polymorphs of\n existing structures\n\n Returns:\n [ComputedEntry]: list of all entries with energies above hull equal to or\n less than the specified e_above_hull.\n \"\"\"\n pd_dict = expand_pd(all_entries)\n pd_dict = {\n chemsys: PhaseDiagram(GibbsComputedStructureEntry.from_pd(pd, temp))\n for chemsys, pd in pd_dict.items()\n }\n\n filtered_entries = set()\n all_comps = dict()\n for chemsys, pd in pd_dict.items():\n for entry in pd.all_entries:\n if (\n entry in filtered_entries\n or pd.get_e_above_hull(entry) > e_above_hull\n ):\n continue\n formula = entry.composition.reduced_formula\n if not include_polymorphs and (formula in all_comps):\n if all_comps[formula].energy_per_atom < entry.energy_per_atom:\n continue\n filtered_entries.remove(all_comps[formula])\n all_comps[formula] = entry\n filtered_entries.add(entry)\n\n return pd_dict, list(filtered_entries)\n\n @property\n def g(self):\n return self._g\n\n @property\n def pd(self):\n return self._pd\n\n @property\n def all_entries(self):\n return self._all_entries\n\n @property\n def filtered_entries(self):\n return self._filtered_entries\n\n @property\n def precursors(self):\n return self._precursors\n\n @property\n def all_targets(self):\n return self._all_targets\n\n @property\n def temp(self):\n return self._temp\n\n def __repr__(self):\n return (\n f\"ReactionNetwork for chemical system: \"\n f\"{'-'.join(sorted([str(e) for e in self._pd.elements]))}, \"\n f\"with Graph: {str(self._g)}\"\n )\n","sub_path":"src/rxn_network/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":41132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22420659","text":"import pandas as pd\n\ndata = pd.read_csv('./data/201812.csv')\n\n\ndef get_size(temp, station):\n if temp == 'rent':\n df_rent = pd.DataFrame(data.groupby(['rent_time', 'rent_station']).size(), columns=['rent_size']).reset_index()\n return df_rent[df_rent['rent_station'].isin([station])].reset_index(drop=True)\n else:\n df_return = pd.DataFrame(data.groupby(['return_time', 'return_station']).size(), columns=['return_size']).reset_index()\n return df_return[df_return['return_station'].isin([station])].reset_index(drop=True)\n\ndef cal_data(temp, station_list):\n df = pd.DataFrame()\n for station in station_list:\n df = df.append(get_size(temp, station))\n if temp == 'rent':\n return df.groupby(['rent_time']).sum().reset_index().rename(columns={'rent_time': 'time', 'rent_size': 'size'})\n else:\n return df.groupby(['return_time']).sum().reset_index().rename(columns={'return_time': 'time', 'return_size': 'size'})\n\n","sub_path":"create_ubike_dataset.py","file_name":"create_ubike_dataset.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"91341966","text":"def prime_first(number): # asal sayı hesaplayan 1. fonksiyonum.\r\n if number !=1 and number !=0:\r\n for i in range(2, number):\r\n if number % i == 0:\r\n break\r\n else:\r\n print(\"Prime numbers between 0-500:\", number)\r\n\r\ndef prime_second(number): # asal sayı hesaplayan 2. fonksiyonum.\r\n if number !=1 and number !=0:\r\n for i in range(2, number):\r\n if number % i == 0:\r\n break\r\n else:\r\n print(\"Prime numbers between 500-1000:\", number)\r\n\r\nfor i in list(range(1000)): # 0-500 ve 500-1000 arası asal sayıları hesaplayıp, ekrana yazdıran döngüm.\r\n if i < 500:\r\n prime_first(i)\r\n else:\r\n prime_second(i)\r\n","sub_path":"Homeworks/HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"507972642","text":"from flask import Flask, jsonify\nfrom flask_restful import Api\nfrom flask_jwt_extended import JWTManager\n\nfrom resources.movie import Movie, MovieList, Search, m_bp\n\nfrom db import db\nfrom blacklist import BLACKLIST\nfrom resources.user import (UserRegister, User, UserLogin,\n TokenRefresh, UserLogout)\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['PROPAGATE_EXCEPTIONS'] = True\n# enable blacklist feature\napp.config['JWT_BLACKLIST_ENABLED'] = True\n# allow blacklisting for access and refresh tokens\napp.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']\n# could do app.config['JWT_SECRET_KEY']\napp.secret_key = 'jose'\napp.register_blueprint(m_bp)\napi = Api(app)\n\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n\njwt = JWTManager(app)\n\n\"\"\"\n`claims` are data we choose to attach to each jwt payload\nand for each jwt protected endpoint, we can retrieve these\nclaims via `get_jwt_claims()one possible use case for claims\nare access level control, which is shown below.\n\"\"\"\n\n\n@jwt.user_claims_loader\ndef add_claims_to_jwt(identity):\n\n if identity == 1:\n return {'is_admin': True}\n return {'is_admin': False}\n\n\n@jwt.token_in_blacklist_loader\ndef check_if_token_in_blacklist(decrypted_token):\n \"\"\"\n This method will check if a token is blacklisted, and will be called\n automatically when blacklist is enabled\n \"\"\"\n # Here we blacklist particular JWTs that have been created in the past.\n return decrypted_token['jti'] in BLACKLIST\n\n\n# The following callbacks are used\n# for customizing jwt response/error messages.\n@jwt.expired_token_loader\ndef expired_token_callback():\n return jsonify({\n 'message': 'The token has expired.',\n 'error': 'token_expired'\n }), 401\n\n\n@jwt.invalid_token_loader\ndef invalid_token_callback(error):\n \"\"\"\n # we have to keep the argument here,\n since it's passed in by the caller internally\n \"\"\"\n return jsonify({\n 'message': 'Signature verification failed.',\n 'error': 'invalid_token'\n }), 401\n\n\n@jwt.unauthorized_loader\ndef missing_token_callback(error):\n return jsonify({\n \"description\": \"Request does not contain an access token.\",\n 'error': 'authorization_required'\n }), 401\n\n\n@jwt.needs_fresh_token_loader\ndef token_not_fresh_callback():\n return jsonify({\n \"description\": \"The token is not fresh.\",\n 'error': 'fresh_token_required'\n }), 401\n\n\n@jwt.revoked_token_loader\ndef revoked_token_callback():\n return jsonify({\n \"description\": \"The token has been revoked.\",\n 'error': 'token_revoked'\n }), 401\n\n\napi.add_resource(Movie, '/movie', methods=['POST'], endpoint='addmovie')\napi.add_resource(Movie, '/movie/',\n methods=['PUT', 'DELETE', 'GET'],\n endpoint=\"movie\")\napi.add_resource(MovieList, '/movies')\napi.add_resource(UserRegister, '/register')\napi.add_resource(User, '/user/')\napi.add_resource(UserLogin, '/login')\napi.add_resource(TokenRefresh, '/refresh')\napi.add_resource(UserLogout, '/logout')\napi.add_resource(Search, '/search/')\n\nif __name__ == '__main__':\n db.init_app(app)\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472837219","text":"from flask_app.config.mysqlconnection import connectToMySQL\nimport re\nfrom flask import flash\n\n\n\nEMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$') \n\nclass User:\n def __init__( self , data ):\n self.id = data['id']\n self.first_name = data['first_name']\n self.last_name = data['last_name']\n self.email = data['email']\n self.pw = data['pw']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n\n @staticmethod\n def validate_user( user ):\n is_valid = True\n if not EMAIL_REGEX.match(user['email']): \n flash(\"Invalid email address!\")\n is_valid = False\n return is_valid\n\n @classmethod\n def get_byid(cls, data:dict):\n query = \"SELECT * FROM users WHERE id = %(user_id)s;\"\n results = connectToMySQL('users').query_db(query, data)\n return cls (results[0])\n\n @classmethod\n def get_all_names(cls, data):\n query = \"SELECT * FROM users.users JOIN users.messages ON users.users.id = users.messages.user_id WHERE receiver_id = %(user_id)s;\"\n results = connectToMySQL('users').query_db(query, data)\n names = []\n for name in results:\n names.append( cls(name) )\n return names\n\n @classmethod\n def get_all(cls):\n query = \"SELECT * FROM users;\"\n results = connectToMySQL('users').query_db(query)\n users = []\n for email in results:\n users.append( cls(email) )\n return users\n \n @classmethod\n def get_by_email(cls,data):\n query = \"SELECT * FROM users WHERE email = %(email)s;\"\n result = connectToMySQL(\"users\").query_db(query,data)\n # Didn't find a matching user\n if len(result) < 1:\n return False\n return cls(result[0])\n\n @classmethod\n def save(cls, data ):\n query = \"INSERT INTO users ( first_name, last_name, email, pw, created_at, updated_at ) VALUES ( %(first_name)s, %(last_name)s, %(email)s, %(pw)s , NOW() , NOW() );\"\n\n return connectToMySQL('users').query_db( query, data )","sub_path":"flask_app/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"617344818","text":"# while True:\r\n# try:\r\n# s = input().strip()\r\n# l = []\r\n# other_l = []\r\n# count = 0\r\n# for i in s:\r\n# if i.isalpha():\r\n# l.append((i, ord(i.lower())))\r\n# else:\r\n# other_l.append((i, count))\r\n# count += 1\r\n# sort_l = sorted(l, key=lambda x: x[1])\r\n# for i in other_l:\r\n# sort_l.insert(i[1], i)\r\n# res_list = [i[0] for i in sort_l]\r\n# print(\"\".join(res_list))\r\n# except:\r\n# break\r\n\r\n\r\n# from collections import Counter\r\n#\r\n#\r\n# def is_brother_word(k, s):\r\n# if k == s or len(k) != len(s):\r\n# return False\r\n# k_counter = Counter(k)\r\n# s_counter = Counter(s)\r\n# if k_counter == s_counter:\r\n# return True\r\n# return False\r\n#\r\n#\r\n# while True:\r\n# try:\r\n# s_list = input().strip().split()\r\n# n = int(s_list[0])\r\n# w_list = s_list[1:n + 1]\r\n# key = s_list[-2]\r\n# res_list_index = int(s_list[-1])\r\n# res_list = []\r\n# for i in w_list:\r\n# if is_brother_word(key, i):\r\n# res_list.append(i)\r\n# n_res_list = len(res_list)\r\n# print(n_res_list)\r\n# res_list.sort()\r\n# if res_list_index -1 < n_res_list:\r\n# print(res_list[res_list_index-1])\r\n# except:\r\n# break\r\n\r\n# def is_prime(n):\r\n# if n < 2:\r\n# return False\r\n# for i in range(2,int(n**0.5)+1):\r\n# if n % i == 0:\r\n# return False\r\n# return True\r\n\r\ndef encode_pwd(s):\r\n res = \"\"\r\n for i in s:\r\n if i.isupper():\r\n if i == \"Z\":\r\n res += \"a\"\r\n continue\r\n res += chr(ord(i) + 1).lower()\r\n elif i.islower():\r\n if i == \"z\":\r\n res += \"A\"\r\n continue\r\n res += chr(ord(i) + 1).upper()\r\n elif i.isdigit():\r\n if i == \"9\":\r\n res += \"0\"\r\n continue\r\n res += chr(ord(i) + 1)\r\n else:\r\n break\r\n return res\r\n\r\n\r\ndef decode_pwd(s):\r\n res = \"\"\r\n for i in s:\r\n if i.isupper():\r\n if i == \"A\":\r\n res += \"z\"\r\n continue\r\n res += chr(ord(i) - 1).lower()\r\n elif i.islower():\r\n if i == \"a\":\r\n res += \"Z\"\r\n continue\r\n res += chr(ord(i) - 1).upper()\r\n elif i.isdigit():\r\n if i == \"0\":\r\n res += \"9\"\r\n continue\r\n res += chr(ord(i) - 1)\r\n else:\r\n break\r\n return res\r\n\r\n\r\nwhile True:\r\n try:\r\n encode_s = input().strip()\r\n decode_s = input().strip()\r\n print(encode_pwd(encode_s))\r\n print(decode_pwd(decode_s))\r\n except:\r\n break\r\n","sub_path":"demo_files/input_sort.py","file_name":"input_sort.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532890785","text":"s1 = 'картошка'\r\ns2 = 'огурец'\r\ns3 = 'помидор'\r\ns1 = s1.upper()\r\ns2 = s2.upper()\r\ns3 = s3.upper()\r\nprint(s1)\r\nprint(s2)\r\nprint(s3)\r\ns1 = s1.lower()\r\ns2 = s2.lower()\r\ns3 = s3.lower()\r\nprint(s1)\r\nprint(s2)\r\nprint(s3)\r\nprint(s1.title())\r\nprint(s2.title())\r\nprint(s3.title())\r\ns1 = \"картош\"\r\na = int(input(\"Введите первое количество \"))\r\nif a == 1:\r\n s1 = s1 + \"ка\"\r\n s11 = \"1 \" + s1\r\nelif a > 4:\r\n s1 = s1 + \"ин\"\r\n s11 = str(a) + s1\r\nelif a > 1:\r\n s1 = s1 + \"ки\"\r\n s11 = str(a) + s1\r\nelse:\r\n print(\" картошин нет \")\r\nb = int(input(\"Введите второе количество \"))\r\nif b == 1:\r\n s12 = \"1 \" + s2\r\nelif b > 4:\r\n s2 = s2 + \"ов\"\r\n s12 = str(b) + s2\r\nelif b > 1:\r\n s2 = s2 + \"а\"\r\n s12 = str(b) + s2\r\nelse:\r\n print(\" огурцов нет \")\r\nc = int(input(\"Введите третье количество \"))\r\nif c == 1:\r\n s13 = \"1 \" + s3\r\nelif c > 4:\r\n s3 = s3 + \"ов\"\r\n s13 = str(c) + s3\r\nelif c > 1:\r\n s3 = s3 + \"а\"\r\n s13 = str(c) + s3\r\nelse:\r\n print(\" помидоров нет \")\r\ntext = \"\"\"Общее количество овощей :{0}, {1} и {2}.\"\"\".format(s11, s12, s13)\r\nprint(text)\r\ninput()\r\n","sub_path":"vegetables.py","file_name":"vegetables.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313434252","text":"from urllib import request\n\nfile_url = r'#put the url the of the here'\n\ndef download_file(url):\n fileOpen = request.urlopen(url) #open the url file\n fileInfo = fileOpen.read() #read the file\n fileInfoStr = str(fileInfo) #convert into string\n fileLines = fileInfoStr.split('\\\\n') #split the lines into the file\n\n newfile = open('file.txt',\"w\") #creating a new file to store information\n for info in fileLines: #store all information of the file we have read\n newfile.write(info + '\\n')\n \n newfile.close() #close the file\n\ndownload_file(file_url)\n\n","sub_path":"Python/Large File Downloader/python_downloader.py","file_name":"python_downloader.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137885742","text":"import json\n\nimport cv2\nimport zmq\nimport base64\nimport numpy as np\nimport sys\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel\nfrom PyQt5.QtGui import QIcon, QPixmap, QImage\nimport cv2\nimport time\nfrom PyQt5.QtCore import *\n\nwidth = 250\nheight = 140\nstatus_icon = \"●\"\nstatuses = {\"connected\": \"'green'\",\n \"outofwindow\": \"'yellow'\",\n \"disconnected\": \"'red'\"\n }\n\n\nclass Thread(QThread):\n changePixmap = pyqtSignal(QImage)\n changeUserName = pyqtSignal(str)\n\n def __init__(self, i):\n super().__init__()\n self.id = i\n\n def run(self):\n frame = sockets[self.id].setsockopt(zmq.RCVTIMEO, 2000)\n while True:\n img = base64.b64decode(frame)\n npimg = np.fromstring(img, dtype=np.uint8)\n source = cv2.imdecode(npimg, 1)\n\n h, w, ch = source.shape\n bytesPerLine = ch * w\n convertToQtFormat = QtGui.QImage(source.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)\n self.changePixmap.emit(convertToQtFormat)\n\n\nclass mymainwindow(QtWidgets.QMainWindow):\n def __init__(self, position=(0, 0)):\n QtWidgets.QMainWindow.__init__(self)\n self.image = QLabel(self)\n self.user_name = QLabel(self)\n self.nick = \"\"\n\n self.shown = True\n self.moving = False\n self.clickXOffset = 0\n self.clickYOffset = 0\n self.currentXPosOffset = 0\n self.currentYPosOffset = 0\n self.posX = 0\n self.posY = 0\n\n self.setAttribute(Qt.WA_TranslucentBackground, True)\n\n self.setWindowFlags(\n QtCore.Qt.WindowStaysOnTopHint |\n QtCore.Qt.FramelessWindowHint |\n QtCore.Qt.X11BypassWindowManagerHint\n )\n self.setGeometry(QtWidgets.QStyle.alignedRect(\n QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter,\n QtCore.QSize(width + 50, height + 50),\n QtWidgets.qApp.desktop().availableGeometry()))\n\n self.move(position[0], position[1])\n\n self.image = QLabel(self)\n pixmap = QPixmap('image.jpeg')\n self.image.setPixmap(pixmap)\n self.image.resize(width, height)\n self.image.move(0, 22)\n\n self.user_name.setText(\"● Wownis \")\n\n def mousePressEvent(self, event):\n self.moving = True\n self.clickXOffset = event.x()\n self.clickYOffset = event.y()\n pass\n # QtWidgets.qApp.qui t\n\n def mouseReleaseEvent(self, event):\n self.moving = False\n\n def mouseMoveEvent(self, event):\n if self.moving:\n self.currentXPosOffset = event.globalX() - self.clickXOffset\n self.currentYPosOffset = event.globalY() - self.clickYOffset\n self.move(self.currentXPosOffset, self.currentYPosOffset)\n pass\n\n def keyPressEvent(self, event):\n if event.key() == QtCore.Qt.Key_Backspace:\n if self.shown:\n self.move(self.currentXPosOffset, self.currentYPosOffset)\n self.shown = False\n else:\n self.move(self.currentXPosOffset - 1000, self.currentYPosOffset)\n self.shown = True\n event.accept()\n\n @pyqtSlot(QImage)\n def setImage(self, image):\n self.image.setPixmap(QPixmap.fromImage(image))\n\n @pyqtSlot(str)\n def setUserName(self, text):\n\n splited = text.split(\" \", 1)\n print(splited)\n status = splited[0]\n if status != \"disconnected\":\n nick = splited[1]\n self.nick = status_icon + \" \" + nick\n\n text = \"\" + self.nick + \"\"\n print(text)\n self.user_name.setText(text)\n\n\n\nfile = open(\"config.json\")\nconfig = json.load(file)\nips = config[\"ips\"]\nport = config[\"port\"]\n\npadding = 10\nbeg = (100, 100)\n\ncontext = zmq.Context()\napp = QtWidgets.QApplication(sys.argv)\nthreads = []\nsockets = []\nwindows = []\nfor i in range(len(ips)):\n window = mymainwindow((beg[0] + (i * (width + padding)), beg[1]))\n window.show()\n windows.append(window)\n\n time.sleep(0.1)\n\n socket = context.socket(zmq.SUB)\n socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))\n adress = 'tcp://' + ips[i] + \":\" + str(port)\n print(adress)\n socket.connect(adress)\n sockets.append(socket)\n\n th = Thread(i)\n th.changePixmap.connect(window.setImage)\n th.changeUserName.connect(window.setUserName)\n th.start()\n\nprint(\"started\")\napp.exec_()\n","sub_path":"viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"291843958","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 16 16:50:11 2018\n\n@author: suezdirie\n\"\"\"\n\nclass Hangman:\n \n def category(self):\n self.tvshow(self)\n self.actors(self)\n self.cartoons(self)\n \n def tvshow(self):\n shows = []\n return shows\n \n def actors(self):\n print('actors')\n \n def cartoons(self):\n print('cartoons')\n \n def checkGuess(self, word, X, guess):\n c = ''\n l = list(X)\n d = {}\n for i in range(0,len(word)):\n d[i] = word[i]\n index = []\n for key, val in d.items():\n if guess == val:\n c = 'correct'\n index.append(key)\n \n for i in range(0,len(index)):\n l[index[i]*2] = guess\n X = ''.join(l)\n \n WORD = ''\n for i in range(0,len(X)):\n if X[i].isalpha():\n WORD += X[i]\n if '_' not in X:\n status = 'Winner'\n else:\n status = 'Keep Guessing'\n \n return X, status, c","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289417589","text":"def duplicados(lista_1, lista_2):\n return list(set(lista_1) & set(lista_2))\n\n\ndef main():\n try:\n happynumbers = open(\"assets/happynumbers.txt\", \"r\")\n primenumbers = open(\"assets/primenumbers.txt\", \"r\")\n lista_1 = happynumbers.read().split(\"\\n\")\n lista_2 = primenumbers.read().split(\"\\n\")\n happynumbers.close()\n primenumbers.close()\n return duplicados(lista_1, lista_2)\n except Exception as ex:\n print(\"Ocorreu algo errado...\")\n raise ex\n\n\nif __name__ == \"__main__\":\n resultado = main()\n print(sorted(resultado, key=lambda x: int(x)))\n","sub_path":"desafios/duplicados.py","file_name":"duplicados.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"447600289","text":"import pandas as pd\nimport os\n#from dfply import * # https://github.com/kieferk/dfply#rename\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import pearsonr\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nfrom sklearn.metrics import r2_score \n\n\n#set working directory\n\n#1) import consumption data from DE.csv into a pandas DataFrame and rename Date (CET) column to Date\n # The LDZ represents gas consumption in GWh, Actual is the Actual temperature and Normal is the normal temperature\nmyData = pd.read_csv('DE.csv', sep = ';')\nmyData.columns = ['Date','LDZ', 'Actual', 'Normal' ]\n # Try to use dfply pipes to rename\n\n\n \n # Plot using Matplotlib all three series on 3 sub plots to see them varying together\n # Do not forget to add a legend and a title to the plot\ni = 0\n\n\n\n \n\n\nDates = list (myData['Date'])\nLDZ = list (myData['LDZ'])\nActualTemperatures = list (myData['Actual'])\nNormalTemperatures = list (myData['Normal'])\n\n\n\n\n###Chasse aux NaNs et autres 'blancs qui existent dans ActualTemperatures\ni = 0\n\n\n\nwhile i < len (ActualTemperatures):\n while np.isnan(ActualTemperatures [i] ) == 1:\n print (i)\n del Dates[i]\n del LDZ [i]\n del ActualTemperatures [i]\n del NormalTemperatures [i]\n i+=1\n\n#indexes = []\n#for i in range (n):\n# if (np.isnan(ActualTemperatures[i]) == 1):\n# print (i, ActualTemperatures[i])\n# indexes.append (i)\n \n\nDates = np.array(Dates)\nLDZ = np.array(LDZ)\nActualTemperatures = np.array(ActualTemperatures)\nNormalTemperatures = np.array(NormalTemperatures)\n\n#fig, axs = plt.subplots(3)\n#fig.suptitle('Vertically stacked subplots')\n#axs[0].plot(Dates, LDZ)\n#axs[1].plot(Dates, ActualTemperatures)\n#axs[2].plot (Dates, NormalTemperatures)\n\ndataFrame = pd.DataFrame ({'Date': Dates ,'LDZ':LDZ , 'Actual':ActualTemperatures , 'Normal': NormalTemperatures })\n \n # Comment on their variation and their relationships\n\n\n \n # use dfply to transform Date column to DateTime type\n\n \n\n#2) work on consumption data (non-linear regression)\n#2)1. Plot with a scatter plot the consumption as a function of temperature\n#plt.scatter (ActualTemperatures, LDZ , c = 'blue')\n#\n#plt.show()\n\n#2)2. define the consumption function (I give it to you since it is hard to know it without experience)\n\n#This function takes temperature and 4 other curve shape parameters and returns a value of consumption\ndef h(t, a, b, c, d):\n return(d+a/(1+(b/(t-40))**c))\n \n\n\n#These are random initial values of a, b, c, d\nguess_values= [900, -35, 6, 300]\n\n#2)3. Fill out this h_hat array with values from the function h\n\n# You will take the 'Actual' column from the DE.csv file as being the input temperature so its length should be the number of rows in the DataFrame imported\n\na,b,c,d = guess_values[0],guess_values[1],guess_values[2],guess_values[3]\nn = len(ActualTemperatures)\nh_hat = np.empty(n)\nfor i in range(n):\n h_hat[i] = h(ActualTemperatures[i], a, b, c, d)\n\n\n\n\n\n#for i in range(len()):\n \n \n # For each value of temmperature of this column you will calculate the consumption using the h function above\n # Use the array guess_values for the curve parameters a, b, c, d that is to say a = guess_values[0], b = guess_values[1], c = guess_values[2], d = guess_values[3]\n\n # Plot on a graph the real consumption (LDZ column) as a function of Actual temperature use blue dots\n # On this same graph add the h_hat values as a function of Actual temperature use a red line for this\n # Do not forget to add a legend and a title to the plot\n # Play around with the parameters in guess_values until you feel like your curve is more or less correct\n \n\n#2)4. optimize the parameters\n\n # Your goal right now is to find the optimal values of a, b, c, d using SciPy\n # Inspire yourselves from the following video\n # https://www.youtube.com/watch?v=4vryPwLtjIY\n\n\nc, cov = scipy.optimize.curve_fit (h, ActualTemperatures, LDZ, guess_values)\nprint (c)\n\nh_hat = h (ActualTemperatures, c[0], c[1], c[2], c[3])\n\nplt.plot (ActualTemperatures, h_hat, c = 'red')\nplt.scatter (ActualTemperatures, LDZ, c = 'blue')\nplt.show ()\n\nprint ('R^2 : ', r2_score(h_hat, LDZ))\nprint (\"h-hat\",h_hat)\nprint (\"ldz\",LDZ)\nprint (ActualTemperatures)\n\n\n#2)5. check the new fit\n\n#Repeat what we did in 2)3. but with the new optimized coefficients a, b, c, d\n\n\n#calculate goodness of fit parameters: correlation, root mean square error (RMSE), Average normalised RMSE, normalized RMSE\n#averaged normalized RMSE is RMSE/(average value of real consumption)\n#normalized RMSE is RMSE/(max value of real consumption - min value of real consumption)\n#Any other metric we could use ?\n\nRMSE = 0.0\naverageValueConsumption = 0\nminValue = min (LDZ)\nfor i in range (n):\n RMSE+= (LDZ[i]-h_hat[i])**2\n averageValueConsumption += LDZ[i]\n \n \nRMSE = np.sqrt (RMSE/n)\naverageValueConsumption /= n\n\n\n\nprint ('RMSE : ', RMSE)\nprint ('Average normalised RMSE : ', RMSE/averageValueConsumption)\nprint ('normalized RMSE : ', RMSE/(averageValueConsumption - minValue))\n\n","sub_path":"Project/consumption_script_raw_to_fill_modified.2.py","file_name":"consumption_script_raw_to_fill_modified.2.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"84187782","text":"from chalice import Chalice\n\nfrom chalice_graphql import GraphQLView\nfrom tests.schema import Schema\n\napp = Chalice(app_name='helloworld')\n\n@app.route('/')\ndef index():\n return {'hello': 'world'}\n\n@app.route(\n '/graphql',\n methods=['GET', 'POST', 'PUT'],\n content_types=['application/graphql', 'application/json', 'application/x-www-form-urlencoded', 'text/plain']\n)\ndef graphql():\n gql_view = GraphQLView(schema=Schema, graphiql=True)\n return gql_view.dispatch_request(app.current_request)\n\n@app.route(\n '/graphql/batch',\n methods=['GET', 'POST'],\n content_types=['application/graphql', 'application/json', 'application/x-www-form-urlencoded', 'text/plain']\n)\ndef graphql_batch():\n gql_view = GraphQLView(schema=Schema, batch=True)\n return gql_view.dispatch_request(app.current_request)\n","sub_path":"tests/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"331870307","text":"import math\n\ndef nextSum(x, y):\n return (y, x+y);\n\ndef fibonacci(n):\n\tt = (0,1)\n\tfor x in range(1,n):\n\t\tt = nextSum(t[0],t[1])\n\tprint(t[1])\n\nnumber = int(input(\"Podaj ktory wyraz ciagu fib chcesz poznac: \"))\nfibonacci(number)\n","sub_path":"lab09/zad2.py","file_name":"zad2.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140125008","text":"import csv\nimport xml.etree.ElementTree as ET\n\ncsvfile = open('PAM_viewer_Flat_v8.csv', 'r')\nreader = csv.DictReader( csvfile)\n\ntree = ET.parse('1-PAMs-Viewer-Flat-file.xml')\nroot = tree.getroot()\n\nrows = [row for row in reader]\n\ndescriptions_simple = []\ndescriptions_multi = []\ndescriptions_missing = []\n\nrowcount = 0\nfor row in rows:\n sd = row['Description']\n if len(sd) > 254:\n sd = ''.join(sd.split(\"_x000D_\"))\n description = {}\n description['csv_row_id'] = rowcount\n description['fromcsv'] = sd\n description['fromxml'] = []\n count = 0;\n for xmlelem in root:\n newdesc = ''\n title = ''\n for elem in xmlelem.getchildren():\n if elem.tag == \"Description\":\n newdesc = elem.text.encode('UTF-8')\n\n if elem.tag == \"Title\":\n title = elem.text.encode('UTF-8')\n\n csv_title = row['Name of policy or measure']\n if csv_title == title:\n try:\n if newdesc.index(sd) == 0:\n if newdesc not in (description['fromxml']):\n description['fromxml'].append(newdesc)\n count += 1\n except:\n pass\n\n if count == 1:\n descriptions_simple.append(description)\n if count > 1:\n descriptions_multi.append(description)\n\n if count == 0:\n for xmlelem in root:\n newdesc = ''\n title = ''\n for elem in xmlelem.getchildren():\n if elem.tag == \"Description\":\n newdesc = elem.text.encode('UTF-8')\n\n if elem.tag == \"Title\":\n title = elem.text.encode('UTF-8')\n\n csv_title = row['Name of policy or measure']\n if csv_title in title and title.index(csv_title) == 0:\n try:\n if newdesc.index(sd) == 0:\n if newdesc not in (description['fromxml']):\n description['fromxml'].append(newdesc)\n count += 1\n except:\n pass\n\n descriptions_simple.append(description)\n\n rowcount+=1\n\nrowcount = 0\nfor row in rows:\n for description_row in descriptions_simple:\n if rowcount == description_row['csv_row_id']:\n if len(description_row['fromxml']) != 0:\n row['Description'] = description_row['fromxml'][0]\n rowcount += 1\ncsvfile_out = open('PAM_2015_v8_merged.csv', 'wb')\nwriter = csv.DictWriter(csvfile_out, fieldnames=reader.fieldnames)\nwriter.writeheader()\nwriter.writerows(rows)\n\n","sub_path":"app/tools/mergecsvwithxml.py","file_name":"mergecsvwithxml.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"537002926","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 27 21:19:04 2016\n\n@author: roboneil\n\"\"\"\n\n# %%\ndef celsius_to_fahrenheit(c):\n if c < -273.15:\n return \"Invalid temperature supplied: {0}\".format(c)\n return c * 9 / 5 + 32\n\n# %%\nprint(celsius_to_fahrenheit(100))\nprint(celsius_to_fahrenheit(-300))\n\n# %%\naccounts = {\"saving_account\":200, \"checking_account\":100, \"under_bed\":[500, 10, 100]}\n \n# exercise 2 - extract the number 100 from money\nanswer = accounts['under_bed'][2]\nprint(answer)\n\n# %%\nemails = ['test@nowhere.com','test2@somewhere.com','you@gmail.com']\nfor email in emails:\n print(email)\n\n# %% excersise 4 - \ntemperatures=[10,-20,-289,100]\nfor temp in temperatures:\n print(celsius_to_fahrenheit(temp))\n\n","sub_path":"getting_started/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"504288172","text":"# Create your views here.\nfrom parceiros.forms import ContratantesForm, CompositoresForm, RadialistaForm,\\\n ParceiroForm\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.forms.formsets import formset_factory\n\ndef parceiros(request,template_name):\n usuario=request.user\n url=str(request.get_full_path())\n pagina=url[1:-1]\n valido=True\n enviado=False\n \n if request.method == 'POST': \n POST=request.POST\n contratante_form = ContratantesForm(request.POST,request.FILES)\n compositor_form = CompositoresForm(request.POST,request.FILES)\n radialista_form = RadialistaForm(request.POST,request.FILES)\n parceiro_form = ParceiroForm(request.POST,request.FILES)\n \n if POST.has_key('contratante'):\n #print \"POST['contratante']\" \n if contratante_form.is_valid(): \n contratante_form.save()\n enviado=True\n else:\n valido=False\n opcao=\"contratante\"\n contratante_form = ContratantesForm(request.POST)\n elif POST.has_key('compositor'):\n #print \"POST['compositor']\"\n if compositor_form.is_valid(): \n compositor_form.save()\n enviado=True\n #return HttpResponseRedirect('/Obrigado/')\n else:\n valido=False\n opcao=\"compositor\"\n compositor_form = CompositoresForm(request.POST)\n elif POST.has_key('radialista'):\n #print \"POST['radialista']\"\n if radialista_form.is_valid(): \n radialista_form.save()\n enviado=True\n #return HttpResponseRedirect('/Obrigado/')\n else:\n valido=False\n opcao=\"radialista\"\n radialista_form = RadialistaForm(request.POST)\n elif POST.has_key('parceiro'):\n #print \"POST['parceiro']\"\n if parceiro_form.is_valid(): \n parceiro_form.save()\n enviado=True\n #return HttpResponseRedirect('/Obrigado/')\n else:\n valido=False\n opcao=\"parceiro\"\n parceiro_form = ParceiroForm(request.POST)\n \n else:\n contratante_form = ContratantesForm() \n compositor_form = CompositoresForm()\n radialista_form = RadialistaForm()\n parceiro_form = ParceiroForm() \n\n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n# contratante_form_set = ContratantesForm(POST, request.FILES, prefix=\"contratante\")\n# book_formset = BookFormSet(request.POST, request.FILES, prefix='books')\n# print POST\n# if POST['compositor']:\n# print \"olaa compositor\"\n# if request.method == 'GET':\n# GET = request.GET \n# if GET.has_key('a'): \n# form = ArtistaForm(request.GET' \n# \n# contratante_form_set = formset_factory(ContratantesForm)\n# compositor_form_set = formset_factory(CompositoresForm)\n# radialista_form_set = formset_factory(RadialistaForm)\n# parceiro_form_set = formset_factory(ParceiroForm)","sub_path":"parceiros/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491795063","text":"#!/usr/bin/env python\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport argparse\nimport multiprocessing\nimport os\nimport platform\nimport sys\nfrom collections import defaultdict\nfrom subprocess import run\nfrom typing import Dict, List, NamedTuple, Optional, Tuple\n\nfrom rich.console import Console\nfrom tabulate import tabulate\n\nfrom docs.exts.docs_build import dev_index_generator, lint_checks # pylint: disable=no-name-in-module\nfrom docs.exts.docs_build.code_utils import (\n CONSOLE_WIDTH,\n DOCKER_PROJECT_DIR,\n ROOT_PROJECT_DIR,\n TEXT_RED,\n TEXT_RESET,\n)\nfrom docs.exts.docs_build.docs_builder import ( # pylint: disable=no-name-in-module\n DOCS_DIR,\n AirflowDocsBuilder,\n get_available_packages,\n)\nfrom docs.exts.docs_build.errors import ( # pylint: disable=no-name-in-module\n DocBuildError,\n display_errors_summary,\n)\nfrom docs.exts.docs_build.fetch_inventories import fetch_inventories # pylint: disable=no-name-in-module\nfrom docs.exts.docs_build.github_action_utils import with_group # pylint: disable=no-name-in-module\nfrom docs.exts.docs_build.package_filter import process_package_filters # pylint: disable=no-name-in-module\nfrom docs.exts.docs_build.spelling_checks import ( # pylint: disable=no-name-in-module\n SpellingError,\n display_spelling_error_summary,\n)\n\nif __name__ != \"__main__\":\n raise SystemExit(\n \"This file is intended to be executed as an executable program. You cannot use it as a module.\"\n \"To run this script, run the ./build_docs.py command\"\n )\n\nCHANNEL_INVITATION = \"\"\"\\\nIf you need help, write to #documentation channel on Airflow's Slack.\nChannel link: https://apache-airflow.slack.com/archives/CJ1LVREHX\nInvitation link: https://s.apache.org/airflow-slack\\\n\"\"\"\n\nERRORS_ELIGIBLE_TO_REBUILD = [\n 'failed to reach any of the inventories with the following issues',\n 'undefined label:',\n 'unknown document:',\n]\n\nON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS', 'false') == \"true\"\n\nconsole = Console(force_terminal=True, color_system=\"standard\", width=CONSOLE_WIDTH)\n\n\ndef _promote_new_flags():\n console.print()\n console.print(\"[yellow]Still tired of waiting for documentation to be built?[/]\")\n console.print()\n if ON_GITHUB_ACTIONS:\n console.print(\"You can quickly build documentation locally with just one command.\")\n console.print(\" [blue]./breeze build-docs[/]\")\n console.print()\n console.print(\"[yellow]Still too slow?[/]\")\n console.print()\n console.print(\"You can only build one documentation package:\")\n console.print(\" [blue]./breeze build-docs -- --package-filter [/]\")\n console.print()\n console.print(\"This usually takes from [yellow]20 seconds[/] to [yellow]2 minutes[/].\")\n console.print()\n console.print(\"You can also use other extra flags to iterate faster:\")\n console.print(\" [blue]--docs-only - Only build documentation[/]\")\n console.print(\" [blue]--spellcheck-only - Only perform spellchecking[/]\")\n console.print()\n console.print(\"For more info:\")\n console.print(\" [blue]./breeze build-docs --help[/]\")\n console.print()\n\n\ndef _get_parser():\n available_packages_list = \" * \" + \"\\n * \".join(get_available_packages())\n parser = argparse.ArgumentParser(\n description='Builds documentation and runs spell checking',\n epilog=f\"List of supported documentation packages:\\n{available_packages_list}\",\n )\n parser.formatter_class = argparse.RawTextHelpFormatter\n parser.add_argument(\n '--disable-checks', dest='disable_checks', action='store_true', help='Disables extra checks'\n )\n parser.add_argument(\n \"--package-filter\",\n action=\"append\",\n help=(\n \"Filter specifying for which packages the documentation is to be built. Wildcard are supported.\"\n ),\n )\n parser.add_argument('--docs-only', dest='docs_only', action='store_true', help='Only build documentation')\n parser.add_argument(\n '--spellcheck-only', dest='spellcheck_only', action='store_true', help='Only perform spellchecking'\n )\n parser.add_argument(\n '--for-production',\n dest='for_production',\n action='store_true',\n help='Builds documentation for official release i.e. all links point to stable version',\n )\n parser.add_argument(\n \"-j\",\n \"--jobs\",\n dest='jobs',\n type=int,\n default=1,\n help=(\n \"\"\"\n Number of parallel processes that will be spawned to build the docs.\n\n This is usually used in CI system only. Though you can also use it to run complete check\n of the documntation locally if you have powerful local machine.\n Default is 1 - which means that doc check runs sequentially, This is the default behaviour\n because autoapi extension we use is not capable of running parallel builds at the same time using\n the same source files.\n\n In parallel builds we are using dockerised version of image built from local sources but the image\n has to be prepared locally (similarly as it is in CI) before you run the docs build. Any changes you\n have done locally after building the image, will not be checked.\n\n Typically you run parallel build in this way if you want to quickly run complete check for all docs:\n\n ./breeze build-image --python 3.6\n ./docs/build-docs.py -j 0\n\n\"\"\"\n ),\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n dest='verbose',\n action='store_true',\n help=(\n 'Increases the verbosity of the script i.e. always displays a full log of '\n 'the build process, not just when it encounters errors'\n ),\n )\n\n return parser\n\n\nclass BuildSpecification(NamedTuple):\n \"\"\"Specification of single build.\"\"\"\n\n package_name: str\n for_production: bool\n verbose: bool\n dockerized: bool\n\n\nclass BuildDocsResult(NamedTuple):\n \"\"\"Result of building documentation.\"\"\"\n\n package_name: str\n log_file_name: str\n errors: List[DocBuildError]\n\n\nclass SpellCheckResult(NamedTuple):\n \"\"\"Result of spellcheck.\"\"\"\n\n package_name: str\n log_file_name: str\n errors: List[SpellingError]\n\n\ndef perform_docs_build_for_single_package(build_specification: BuildSpecification) -> BuildDocsResult:\n \"\"\"Performs single package docs build.\"\"\"\n builder = AirflowDocsBuilder(\n package_name=build_specification.package_name, for_production=build_specification.for_production\n )\n console.print(f\"[blue]{build_specification.package_name:60}:[/] Building documentation\")\n result = BuildDocsResult(\n package_name=build_specification.package_name,\n errors=builder.build_sphinx_docs(\n dockerized=build_specification.dockerized,\n verbose=build_specification.verbose,\n ),\n log_file_name=builder.log_build_filename,\n )\n return result\n\n\ndef perform_spell_check_for_single_package(build_specification: BuildSpecification) -> SpellCheckResult:\n \"\"\"Performs single package spell check.\"\"\"\n builder = AirflowDocsBuilder(\n package_name=build_specification.package_name, for_production=build_specification.for_production\n )\n console.print(f\"[blue]{build_specification.package_name:60}:[/] Checking spelling started\")\n result = SpellCheckResult(\n package_name=build_specification.package_name,\n errors=builder.check_spelling(\n dockerized=build_specification.dockerized,\n verbose=build_specification.verbose,\n ),\n log_file_name=builder.log_spelling_filename,\n )\n console.print(f\"[blue]{build_specification.package_name:60}:[/] Checking spelling completed\")\n return result\n\n\ndef build_docs_for_packages(\n current_packages: List[str],\n docs_only: bool,\n spellcheck_only: bool,\n for_production: bool,\n jobs: int,\n verbose: bool,\n) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:\n \"\"\"Builds documentation for all packages and combines errors.\"\"\"\n all_build_errors: Dict[str, List[DocBuildError]] = defaultdict(list)\n all_spelling_errors: Dict[str, List[SpellingError]] = defaultdict(list)\n with with_group(\"Cleaning documentation files\"):\n for package_name in current_packages:\n console.print(f\"[blue]{package_name:60}:[/] Cleaning files\")\n builder = AirflowDocsBuilder(package_name=package_name, for_production=for_production)\n builder.clean_files()\n if jobs > 1:\n if os.getenv('CI', '') == '':\n console.print(\"[yellow] PARALLEL DOCKERIZED EXECUTION REQUIRES IMAGE TO BE BUILD BEFORE !!!![/]\")\n console.print(\"[yellow] Make sure that you've build the image before runnning docs build.[/]\")\n console.print(\"[yellow] otherwise local changes you've done will not be used during the check[/]\")\n console.print()\n run_in_parallel(\n all_build_errors,\n all_spelling_errors,\n current_packages,\n docs_only,\n for_production,\n jobs,\n spellcheck_only,\n verbose,\n )\n else:\n run_sequentially(\n all_build_errors,\n all_spelling_errors,\n current_packages,\n docs_only,\n for_production,\n spellcheck_only,\n verbose,\n )\n return all_build_errors, all_spelling_errors\n\n\ndef run_sequentially(\n all_build_errors,\n all_spelling_errors,\n current_packages,\n docs_only,\n for_production,\n spellcheck_only,\n verbose,\n):\n \"\"\"Run both - spellcheck and docs build sequentially without multiprocessing\"\"\"\n if not spellcheck_only:\n for package_name in current_packages:\n build_result = perform_docs_build_for_single_package(\n build_specification=BuildSpecification(\n package_name=package_name,\n for_production=for_production,\n dockerized=False,\n verbose=verbose,\n )\n )\n if build_result.errors:\n all_build_errors[package_name].extend(build_result.errors)\n print_build_output(build_result)\n if not docs_only:\n for package_name in current_packages:\n spellcheck_result = perform_spell_check_for_single_package(\n build_specification=BuildSpecification(\n package_name=package_name,\n for_production=for_production,\n dockerized=False,\n verbose=verbose,\n )\n )\n if spellcheck_result.errors:\n all_spelling_errors[package_name].extend(spellcheck_result.errors)\n print_spelling_output(spellcheck_result)\n\n\ndef run_in_parallel(\n all_build_errors,\n all_spelling_errors,\n current_packages,\n docs_only,\n for_production,\n jobs,\n spellcheck_only,\n verbose,\n):\n \"\"\"Run both - spellcheck and docs build sequentially without multiprocessing\"\"\"\n pool = multiprocessing.Pool(processes=jobs)\n # until we fix autoapi, we need to run parallel builds as dockerized images\n dockerized = True\n if not spellcheck_only:\n run_docs_build_in_parallel(\n all_build_errors=all_build_errors,\n for_production=for_production,\n current_packages=current_packages,\n verbose=verbose,\n dockerized=dockerized,\n pool=pool,\n )\n if not docs_only:\n run_spell_check_in_parallel(\n all_spelling_errors=all_spelling_errors,\n for_production=for_production,\n current_packages=current_packages,\n verbose=verbose,\n dockerized=dockerized,\n pool=pool,\n )\n fix_ownership()\n\n\ndef fix_ownership():\n \"\"\"Fixes ownership for all files created with root user,\"\"\"\n console.print(\"Fixing ownership for generated files\")\n python_version = os.getenv('PYTHON_MAJOR_MINOR_VERSION', \"3.6\")\n fix_cmd = [\n \"docker\",\n \"run\",\n \"--entrypoint\",\n \"/bin/bash\",\n \"--rm\",\n \"-e\",\n f\"HOST_OS={platform.system()}\",\n \"-e\" f\"HOST_USER_ID={os.getuid()}\",\n \"-e\",\n f\"HOST_GROUP_ID={os.getgid()}\",\n \"-v\",\n f\"{ROOT_PROJECT_DIR}:{DOCKER_PROJECT_DIR}\",\n f\"apache/airflow:master-python{python_version}-ci\",\n \"-c\",\n \"/opt/airflow/scripts/in_container/run_fix_ownership.sh\",\n ]\n run(fix_cmd, check=True)\n\n\ndef print_build_output(result: BuildDocsResult):\n \"\"\"Prints output of docs build job.\"\"\"\n with with_group(f\"{TEXT_RED}Output for documentation build {result.package_name}{TEXT_RESET}\"):\n console.print()\n console.print(f\"[blue]{result.package_name:60}: \" + \"#\" * 80)\n with open(result.log_file_name) as output:\n for line in output.read().splitlines():\n console.print(f\"{result.package_name:60} {line}\")\n console.print(f\"[blue]{result.package_name:60}: \" + \"#\" * 80)\n\n\ndef run_docs_build_in_parallel(\n all_build_errors: Dict[str, List[DocBuildError]],\n for_production: bool,\n current_packages: List[str],\n verbose: bool,\n dockerized: bool,\n pool,\n):\n \"\"\"Runs documentation building in parallel.\"\"\"\n doc_build_specifications: List[BuildSpecification] = []\n with with_group(\"Scheduling documentation to build\"):\n for package_name in current_packages:\n console.print(f\"[blue]{package_name:60}:[/] Scheduling documentation to build\")\n doc_build_specifications.append(\n BuildSpecification(\n package_name=package_name,\n for_production=for_production,\n verbose=verbose,\n dockerized=dockerized,\n )\n )\n with with_group(\"Running docs building\"):\n console.print()\n result_list = pool.map(perform_docs_build_for_single_package, doc_build_specifications)\n for result in result_list:\n if result.errors:\n all_build_errors[result.package_name].extend(result.errors)\n print_build_output(result)\n\n\ndef print_spelling_output(result: SpellCheckResult):\n \"\"\"Prints output of spell check job.\"\"\"\n with with_group(f\"{TEXT_RED}Output for spelling check: {result.package_name}{TEXT_RESET}\"):\n console.print()\n console.print(f\"[blue]{result.package_name:60}: \" + \"#\" * 80)\n with open(result.log_file_name) as output:\n for line in output.read().splitlines():\n console.print(f\"{result.package_name:60} {line}\")\n console.print(f\"[blue]{result.package_name:60}: \" + \"#\" * 80)\n console.print()\n\n\ndef run_spell_check_in_parallel(\n all_spelling_errors: Dict[str, List[SpellingError]],\n for_production: bool,\n current_packages: List[str],\n verbose: bool,\n dockerized: bool,\n pool,\n):\n \"\"\"Runs spell check in parallel.\"\"\"\n spell_check_specifications: List[BuildSpecification] = []\n with with_group(\"Scheduling spell checking of documentation\"):\n for package_name in current_packages:\n console.print(f\"[blue]{package_name:60}:[/] Scheduling spellchecking\")\n spell_check_specifications.append(\n BuildSpecification(\n package_name=package_name,\n for_production=for_production,\n verbose=verbose,\n dockerized=dockerized,\n )\n )\n with with_group(\"Running spell checking of documentation\"):\n console.print()\n result_list = pool.map(perform_spell_check_for_single_package, spell_check_specifications)\n for result in result_list:\n if result.errors:\n all_spelling_errors[result.package_name].extend(result.errors)\n print_spelling_output(result)\n\n\ndef display_packages_summary(\n build_errors: Dict[str, List[DocBuildError]], spelling_errors: Dict[str, List[SpellingError]]\n):\n \"\"\"Displays a summary that contains information on the number of errors in each packages\"\"\"\n packages_names = {*build_errors.keys(), *spelling_errors.keys()}\n tabular_data = [\n {\n \"Package name\": f\"[blue]{package_name}[/]\",\n \"Count of doc build errors\": len(build_errors.get(package_name, [])),\n \"Count of spelling errors\": len(spelling_errors.get(package_name, [])),\n }\n for package_name in sorted(packages_names, key=lambda k: k or '')\n ]\n console.print(\"#\" * 20, \" Packages errors summary \", \"#\" * 20)\n console.print(tabulate(tabular_data=tabular_data, headers=\"keys\"))\n console.print(\"#\" * 50)\n\n\ndef print_build_errors_and_exit(\n build_errors: Dict[str, List[DocBuildError]],\n spelling_errors: Dict[str, List[SpellingError]],\n) -> None:\n \"\"\"Prints build errors and exists.\"\"\"\n if build_errors or spelling_errors:\n if build_errors:\n display_errors_summary(build_errors)\n console.print()\n if spelling_errors:\n display_spelling_error_summary(spelling_errors)\n console.print()\n console.print(\"The documentation has errors.\")\n display_packages_summary(build_errors, spelling_errors)\n console.print()\n console.print(CHANNEL_INVITATION)\n sys.exit(1)\n else:\n console.print(\"[green]Documentation build is successful[/]\")\n\n\ndef main():\n \"\"\"Main code\"\"\"\n args = _get_parser().parse_args()\n available_packages = get_available_packages()\n docs_only = args.docs_only\n spellcheck_only = args.spellcheck_only\n disable_checks = args.disable_checks\n package_filters = args.package_filter\n for_production = args.for_production\n\n with with_group(\"Available packages\"):\n for pkg in sorted(available_packages):\n console.print(f\" - {pkg}\")\n\n if package_filters:\n console.print(\"Current package filters: \", package_filters)\n current_packages = process_package_filters(available_packages, package_filters)\n\n with with_group(\"Fetching inventories\"):\n # Inventories that could not be retrieved should be retrieved first. This may mean this is a\n # new package.\n priority_packages = fetch_inventories()\n current_packages = sorted(current_packages, key=lambda d: -1 if d in priority_packages else 1)\n\n jobs = args.jobs if args.jobs != 0 else os.cpu_count()\n with with_group(\n f\"Documentation will be built for {len(current_packages)} package(s) with {jobs} parallel jobs\"\n ):\n for pkg_no, pkg in enumerate(current_packages, start=1):\n console.print(f\"{pkg_no}. {pkg}\")\n\n all_build_errors: Dict[Optional[str], List[DocBuildError]] = {}\n all_spelling_errors: Dict[Optional[str], List[SpellingError]] = {}\n package_build_errors, package_spelling_errors = build_docs_for_packages(\n current_packages=current_packages,\n docs_only=docs_only,\n spellcheck_only=spellcheck_only,\n for_production=for_production,\n jobs=jobs,\n verbose=args.verbose,\n )\n if package_build_errors:\n all_build_errors.update(package_build_errors)\n if package_spelling_errors:\n all_spelling_errors.update(package_spelling_errors)\n to_retry_packages = [\n package_name\n for package_name, errors in package_build_errors.items()\n if any(any((m in e.message) for m in ERRORS_ELIGIBLE_TO_REBUILD) for e in errors)\n ]\n if to_retry_packages:\n for package_name in to_retry_packages:\n if package_name in all_build_errors:\n del all_build_errors[package_name]\n if package_name in all_spelling_errors:\n del all_spelling_errors[package_name]\n\n package_build_errors, package_spelling_errors = build_docs_for_packages(\n current_packages=to_retry_packages,\n docs_only=docs_only,\n spellcheck_only=spellcheck_only,\n for_production=for_production,\n jobs=jobs,\n verbose=args.verbose,\n )\n if package_build_errors:\n all_build_errors.update(package_build_errors)\n if package_spelling_errors:\n all_spelling_errors.update(package_spelling_errors)\n\n if not disable_checks:\n general_errors = lint_checks.run_all_check()\n if general_errors:\n all_build_errors[None] = general_errors\n\n dev_index_generator.generate_index(f\"{DOCS_DIR}/_build/index.html\")\n\n if not package_filters:\n _promote_new_flags()\n\n print_build_errors_and_exit(\n all_build_errors,\n all_spelling_errors,\n )\n\n\nmain()\n","sub_path":"docs/build_docs.py","file_name":"build_docs.py","file_ext":"py","file_size_in_byte":21472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"645963054","text":"import telebot\nimport requests\nimport json\n\nproxies = {\n 'http' : \"socks4://145.255.6.171:53177\",\n 'https' : \"socks4://145.255.6.171:53177\"\n }\n\napi_access_token = 'be643fe09cf46af7297f94b25ecc1ace'\ns = requests.Session()\ns.headers['authorization'] = 'Bearer ' + api_access_token\nb = s.get('https://edge.qiwi.com/funding-sources/v1/accounts/current', proxies=proxies)\ninfo = json.loads(b.text)\n\ndef get_balance():\n i = []\n for i in info['accounts']:\n return i['balance']\n print(i)\n\nget = get_balance()\n\nbalanc = get.get('amount')\n\n\ntoken = '764914862:AAGfQycEKhlApnEKOsGBlkmytNbk9NzD0bE'\n\nbot = telebot.TeleBot(token)\n\nbot.send_message(361395559, str(balanc))\n","sub_path":"botEX.py","file_name":"botEX.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"568972315","text":"import cv2\nimport numpy as np\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\n\nn_markers = 10\ncurrent_marker = 1\nmarker_updated = False\n\nroad = cv2.imread('/home/rishisharma/Documents/Computer Vision with OpenCV and Deep Learning/Computer-Vision-with-Python Notebooks/DATA/road_image.jpg')\n\nroad_copy = road.copy()\nmarker = np.zeros(road.shape[:2], dtype = np.int32)\nsegment = np.zeros(road.shape, dtype = np.uint8)\n\ndef color(i):\n x = np.array(cm.tab10(i))[:3]*255\n return tuple(x)\n\ncolors = []\nfor i in range(n_markers):\n colors.append(color(i))\n \ndef mouse_call_back(event, x, y, flags, param):\n \n global marker_updated\n \n if event == cv2.EVENT_LBUTTONDOWN:\n marker_updated = True\n \n cv2.circle(marker, (x, y), 10, (current_marker), -1)\n cv2.circle(road_copy, (x, y), 10, colors[current_marker], -1)\n \n marker_updated = True\n \ncv2.namedWindow('Road Image')\ncv2.setMouseCallback('Road Image', mouse_call_back)\n \nwhile True:\n \n cv2.imshow('Image', segment)\n cv2.imshow('Road Image', road_copy)\n \n k = cv2.waitKey(1)\n if k == 27:\n break\n \n elif k == ord('c'):\n \n road_copy = road.copy()\n marker = np.zeros(road_copy.shape[:2], dtype = np.int32)\n segment = np.zeros(road.shape, dtype = np.uint8)\n \n elif k > 0 and chr(k).isdigit():\n \n current_marker = int(chr(k))\n \n if marker_updated:\n \n marker_image_copy = marker.copy()\n cv2.watershed(road, marker_image_copy)\n \n segment = np.zeros(road.shape,dtype=np.uint8)\n \n for color_ind in range(n_markers):\n segment[marker_image_copy == (color_ind)] = colors[color_ind]\n \n marker_updated = False\n \ncv2.destroyAllWindows()","sub_path":"Python Code/watershed.py","file_name":"watershed.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"373660071","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\n\nresults = []\nnames = []\nscores = []\nfor name, model in models:\n score_dict = {}\n model_scores = []\n for fold in range(10):\n train = pd.read_csv(\n \"mouses/\" + str(fold) + \"/train\" + str(fold) + \".csv\")\n val = pd.read_csv(\n \"mouses/\" + str(fold) + \"/val\" + str(fold) + \".csv\")\n\n train = train.values\n X_train = train[:, :77]\n Y_train = train[:, 77]\n\n val = val.values\n X_val = val[:, :77]\n Y_val = val[:, 77]\n\n model.fit(X_train, Y_train)\n score = model.score(X_val, Y_val)\n model_scores.append(score)\n score_dict[\"Model\"] = name\n score_dict[\"Mean Accuracy\"] = np.mean(model_scores)\n score_dict[\"Std Accuracy\"] = np.std(model_scores)\n scores.append(score_dict)\nscores = pd.DataFrame(scores)\nscores.to_csv(\"cortex_scores_classifiers.csv\", index=False,\n columns=[\"Model\", \"Mean Accuracy\", \"Std Accuracy\"])\n","sub_path":"validation_Cortex.py","file_name":"validation_Cortex.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"361478078","text":"import os,sys\r\nimport random\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport pickle\r\n\r\n\r\n\r\n\r\ndef get_train_data(filePath, wd2Idx, sentence_size): \r\n #读取训练集中的数据,训练集中有五言和七言的数据,这里现在是全部读入五言的并转化为one_hot向量\r\n \"\"\"\r\n 得到训练集\r\n @params:\r\n fileName:文件路径\r\n wd2Idx\r\n sentence_size:5或7;表示五言或七言\r\n @return:\r\n poem_line_lst:古诗列表\r\n poem_vec_lst:映射成one-hot向量后的古诗列表\r\n poem_line_lst\r\n 其它:\r\n 没有为每句诗加上\r\n \"\"\"\r\n poem_line_lst = []\r\n poem_vec_lst = []\r\n with open(filePath, 'r', encoding='utf-8') as fin:\r\n for line in fin:\r\n line = (\" \".join(line.strip().split(\"\\t\"))).split(\" \")\r\n if sentence_size == 5 and len(line) == 20:\r\n poem_line_lst.append(line)\r\n elif sentence_size == 7 and len(line) == 28:\r\n poem_line_lst.append(line)\r\n poem_vec_lst = [[wd2Idx[wd] for wd in line] for line in poem_line_lst]\r\n return poem_line_lst, poem_vec_lst\r\n\r\n\r\ndef get_test_data(filePath, wd2Idx, sentence_size): \r\n \"\"\"\r\n 读取测试集中的数据,并将其转化为one_hot向量\r\n 五言数据测试集中每行为8个字,前5个为第一句诗歌,后3个字为后面3句诗的开头\r\n @params:\r\n fileName:文件路径\r\n wd2Idx\r\n sentence_size:5或7,表示五言或七言\r\n @return:\r\n poem_line_lst5:五言绝句列表\r\n poem_vec_lst5:映射后的五言绝句列表\r\n 其它:\r\n 没有为每句诗加上\r\n \"\"\"\r\n poem_line_lst = []\r\n poem_vec_lst = []\r\n \r\n with open(filePath, 'r', encoding='utf-8') as fin:\r\n for line in fin:\r\n line = (\" \".join(line.strip().split(\"\\t\"))).split(\" \")\r\n if sentence_size == 5 and len(line) == 5+3:\r\n poem_line_lst.append(line)\r\n elif sentence_size == 7 and len(line) == 7+3:\r\n poem_line_lst.append(line)\r\n poem_vec_lst = [[wd2Idx[wd] for wd in line] for line in poem_line_lst]\r\n return poem_line_lst, poem_vec_lst\r\n\r\n\r\n\r\ndef get_batch(data,bat,idx, sentence_size):\r\n \"\"\"\r\n 训练时每个epoch取epoch_size//batch_size次batch,\r\n 分别使idx取0,1,2,3,...,epoch_size//batch_size-1,以取数据集中不同的部分\r\n @params:\r\n data:待划分的数据集\r\n bat:BATCH_SIZE\r\n \r\n @returns:\r\n X_batch:shape: len(data)//bat,bat,seq_len,其中seq_len包含四句诗\r\n Y_batch:shape: len(data)//bat,bat,seq_len,其中seq_len包含后三句诗\r\n \"\"\"\r\n X_batch = []\r\n Y_batch = []\r\n st = idx * bat\r\n ed = st + bat\r\n X_batch.append(data[st:ed])\r\n Y_batch.append([vec[sentence_size:] for vec in data[st:ed]])\r\n return X_batch,Y_batch\r\n\r\n\r\ndef get_test_batch(data,bat,idx):\r\n# 从测试集中的one_hot向量中取一个batch的数据\r\n X_batch = []\r\n \r\n st = idx * bat\r\n ed = st + bat\r\n X_batch.append(data[st:ed])\r\n \r\n\r\n return X_batch\r\n","sub_path":"整合/rnn/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"568801806","text":"import pandas as pd\nimport numpy as np\nimport json\n\ndef fromJson(filename=\"words.json\"):\n dic = {}\n with open(filename, 'r') as f:\n dic = json.loads(f.read())\n return dic\n\ndef toJson(dictionary, filename=\"words.json\"):\n with open(filename, 'w') as f:\n f.write(json.dumps(dictionary))\n\ndef create_hist(filename, dictionary):\n hist = {}\n with open(filename, 'r') as f:\n for line in f:\n for word in line.split():\n if word in dictionary:\n if dictionary[word] in hist.keys():\n hist[dictionary[word]] += 1\n else:\n hist[dictionary[word]] = 1\n else:\n if word in hist:\n hist[word] += 1\n else:\n hist[word] = 1\n\n keyValue = zip(hist.keys(), hist.values())\n return dict(sorted(keyValue, key = lambda x: x[1], reverse=True))\n\ndictionary = fromJson()\n\nfilename = \"file.txt\"# input(\"¿Dónde está el archivo?: \")\nhist = create_hist(filename, dictionary)\n\nprint(hist)\n","sub_path":"histogram/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"507576810","text":"c_locations = ['Bay Tree Bookstore','Base of campus','Classroom Unit 1 & 2','College 8',\n 'College 9','College 10','Cowell','Crown','East Remote Parking Lot',\n 'Hahn Student Services','Kresge','Media Theater','Merrill','Music Center Recital Hall',\n 'Oakes','Porter','Stevenson','Thimann Labs',]\naugments = ['None','Frosh Breakout Session (1)','Frosh Breakout Session (2)',\n 'Frosh Breakout Session (3)','Frosh Class Enrollment','Frosh College Presentations',\n 'Frosh Major Presentations (A)','Frosh Major Presentations (B)','Frosh Open College Advising',\n 'Frosh Resource Fair','Transfer Breakout Session (1)','Transfer Breakout Session (2)',\n 'Transfer Breakout Session (3)','Transfer Class Enrollment','Transfer College Presentation',\n 'Transfer Major Presentations','Transfer Open College/Major Advising',\n 'Transfer Resource Fair',]\n\nfrom datetime import datetime\ndb.define_table('last_update',\n Field('update_time','datetime',readable=False,writable=False,default=datetime.utcnow()),\n)\n\n# coding: utf8\ndb.define_table('program',\n Field('name','string'),\n Field('program_year','datetime',readable=False,writable=False,default=datetime.utcnow()),\n Field('office_note','string',label=\"Office Notes\",comment='This is for internal office notes'),\n Field('days','integer',default=1,comment='amount of days this program runs for'),\n )\n\ndb.define_table('prog_date',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('program_date','date',widget=SQLFORM.widgets.date.widget),\n Field('program_end_date','date',widget=SQLFORM.widgets.date.widget),\n )\n\ndb.define_table('prog_allowable',\n Field('program_ref', 'reference program',readable=False,writable=False),\n Field('user_type','string',requires=IS_IN_SET(['Student Participant',\n 'Student Guest Participant','UCSC Student','Staff','Visitor'])),\n)\n\ndb.define_table('prog_requires',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('features','list:string',requires=IS_IN_SET(['Resource Fair','Maps',\n 'Schedule','How-To\\'s','Special FAQ\\'s'],multiple=True),\n widget=SQLFORM.widgets.checkboxes.widget),\n)\n\ndb.define_table('schedule',\n Field('program_ref', 'reference program',readable=False,writable=False),\n Field('day','integer',requires=IS_NOT_EMPTY(),default=1),\n Field('item','string',requires=IS_NOT_EMPTY()),\n Field('note','string',comment=\"Note will display immediately beneath location, keep under 30 characters\"),\n Field('start','time',widget = SQLFORM.widgets.time.widget),\n Field('end','time',widget = SQLFORM.widgets.time.widget),\n Field('loc','string'),\n Field('augment','string',requires=IS_IN_SET(augments,zero=\"None\")),\n Field('summary','text'),\n)\n\ndb.define_table('breakout_sessions',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('title','string',requires=IS_NOT_EMPTY()),\n Field('location','string',requires=IS_NOT_EMPTY()),\n Field('description','text',requires=IS_NOT_EMPTY()),\n Field('s1','boolean',comment=\"Session 1\"),\n Field('s2','boolean',comment=\"Session 2\"),\n Field('s3','boolean',comment=\"Session 3\"), \n)\n\ndb.define_table('academic_advising',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('college','string',requires=IS_NOT_EMPTY()),\n Field('location','string',requires=IS_NOT_EMPTY()),\n)\n\ndb.define_table('department_advising',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('department','string',requires=IS_NOT_EMPTY()),\n Field('location','string',requires=IS_NOT_EMPTY()),\n Field('sa','boolean',comment=\"Session B\"),\n Field('sb','boolean',comment=\"Session A\"),\n)\n\ndb.define_table('academic_cluster',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('title','string'),\n Field('description','text'),\n)\n\ndb.define_table('afternoon_advising',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('college','string',requires=IS_NOT_EMPTY()),\n Field('location','string',requires=IS_NOT_EMPTY()),\n)\n\ndb.define_table('online_enrollment',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('college','string',requires=IS_NOT_EMPTY()),\n Field('location','string',requires=IS_NOT_EMPTY()),\n)\n\ndb.define_table('flag_path',\n Field('program_ref','reference program',readable=False,writable=False),\n Field('color','string',requires=IS_NOT_EMPTY()),\n Field('color_hex',widget = color_widget.widget,label=\"Color\"),\n Field('start_loc','string',requires=IS_IN_SET(c_locations),label='Starting location'),\n Field('end_loc','string',requires=IS_IN_SET(c_locations),label='Ending location'),\n Field('coor_list','list:string',default='',\n comment=XML(\"Do not fill out if you're uploading a KML file.
\"\n + \" Otherwise enter each coorindate:
(-119.6343, 37.7244)
\"\n + \"(Longitude, Latitude)\")),\n Field('kml_blob','blob'),\n Field('kml','upload',uploadfield='kml_blob'),\n Field('major','boolean',default=False,label='Major Path'),\n)\n\ndb.define_table('classroom',\n Field('name','string',requires=IS_NOT_EMPTY()),\n Field('near','string',requires=IS_IN_SET(c_locations)),\n Field('coor_lat','string',requires=IS_NOT_EMPTY()),\n Field('coor_long','string',requires=IS_NOT_EMPTY()),\n)\n","sub_path":"models/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"483912194","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n # memory\n self.ram = [0] * 256\n # init registers\n self.reg = [0] * 8\n # general-purpose registers\n self.IM = self.reg[5] # interrupt mask\n self.IS = self.reg[6] # interrupt status \n self.SP = 0xF4 # self.reg[7] # stack pointer \n # special-purpose registers \n # internal registers\n self.PC = 0 # Program Counter\n self.IR = 0 # Instruction Register\n self.MAR = 0 # Memory Address Register\n self.MDR = 0 # Memory Data Register\n self.FL = 0 # Flag\n self.halt = False\n \n def ram_read(self, address):\n return self.ram[address] \n \n def ram_write(self, address, value):\n self.ram[address] = value\n \n \n def load(self,program):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n with open(program) as f: \n for instruction in f:\n instruction = instruction.split('#')[0].strip()\n if instruction == '':\n continue\n\n self.ram[address] = int(instruction, 2)\n\n address += 1 \n\n # print(self.ram) \n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n elif op == \"SUB\":\n self.reg[reg_a] -= self.reg[reg_b]\n\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n\n elif op == \"CMP\":\n if self.reg[reg_a] == self.reg[reg_b]:\n self.FL = 1\n else:\n self.FL = 0\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def push(self, reg_a):\n self.SP -= 1\n self.ram[self.SP] = self.reg[reg_a]\n self.PC += 2\n\n def pop(self, reg_a):\n self.reg[reg_a] = self.ram[self.SP]\n self.SP += 1\n self.PC += 2 \n\n def call(self, reg_a):\n self.SP -= 1\n self.ram[self.reg[self.SP]] = self.PC + 2\n self.PC = self.reg[reg_a]\n\n def ret(self): \n self.PC = self.ram[self.reg[self.SP]]\n self.SP += 1 \n\n def ldi(self,reg_a,reg_b):\n self.reg[reg_a] = self.ram[reg_b]\n self.PC += 3\n\n def prn(self,reg_a,reg_b):\n print(self.reg[self.ram[reg_a]])\n self.PC += 2 \n\n def hlt(self):\n self.halt = True \n sys.exit(0)\n\n def jmp(self, reg_a):\n self.PC = self.reg[reg_a]\n\n def jeq(self, reg_a):\n if self.FL == 1:\n self.jmp(reg_a)\n else: \n self.PC += 2\n\n def jne(self, reg_a):\n if self.FL == 0:\n self.jmp(reg_a)\n else:\n self.PC += 2\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.PC,\n #self.fl,\n #self.ie,\n self.ram_read(self.PC),\n self.ram_read(self.PC + 1),\n self.ram_read(self.PC + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n HLT = 0b00000001 # instruction handler\n LDI = 0b10000010 # instruction\n PRN = 0b01000111 # instruction\n MUL = 0b10100010 # multiply instruction\n PUSH = 0b01000101 # stack\n POP = 0b01000110 # stack\n CALL = 0b01010000 # call \n RET = 0b00010001 # return\n CMP = 0b10100111\n JMP = 0b01010100\n JEQ = 0b01010101\n JNE = 0b01010110\n \n self.halt = False\n while self.halt is False:\n if self.ram[self.PC] == LDI:\n self.reg[self.ram[self.PC + 1]] = self.ram[self.PC + 2]\n self.PC += 3\n\n elif self.ram[self.PC] == PRN:\n print(self.reg[self.ram[self.PC + 1]])\n self.PC += 2 \n\n elif self.ram[self.PC] == MUL: \n self.alu('MUL', self.ram[self.PC + 1], self.ram[self.PC + 2])\n self.PC += 3\n\n elif self.ram[self.PC] == PUSH: \n self.push(self.ram[self.PC + 1])\n\n elif self.ram[self.PC] == POP:\n self.pop(self.ram[self.PC + 1]) \n\n elif self.ram[self.PC] == CALL: \n self.call(self.ram_read(self.PC + 1))\n\n elif self.ram[self.PC] == RET: \n self.ret() \n\n elif self.ram[self.PC] == CMP: \n self.alu('CMP', self.ram[self.PC + 1], self.ram[self.PC + 2])\n self.PC += 3 \n\n elif self.ram[self.PC] == JMP: \n self.jmp(self.ram[self.PC + 1]) \n\n elif self.ram[self.PC] == JEQ: \n self.jeq(self.ram[self.PC + 1]) \n\n elif self.ram[self.PC] == JNE: \n self.jne(self.ram[self.PC + 1]) \n\n elif self.ram[self.PC] == HLT:\n self.hlt() \n\n else:\n print('unknown instruction')\n \n \n\n\n ","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"265905356","text":"# -*- coding: cp1251 -*-\nfrom ftplib import FTP\nimport sys\nfl = []\nif len(sys.argv) > 1:\n for i in range(1, len(sys.argv)):\n fl.append(sys.argv[i].split('\\\\')[-1])\nelse:\n fl.append('stream.py')\n\n\nfor j in range(len(fl)):\n print(fl[j])\n\n ftp = FTP()\n HOSTS = ['192.168.68.119']\n PORT = 21\n for i in range(len(HOSTS)):\n ftp.connect(HOSTS[i], PORT)\n print(ftp.login(user='pi', passwd='9'))\n\n ftp.cwd('poses')\n\n with open(fl[j], 'rb') as f:\n ftp.storbinary('STOR ' + fl[j], f, 1024)\n\n print('Done!')\n\n\n","sub_path":"posenet-python-master/commit_2.0.py","file_name":"commit_2.0.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"40631218","text":"from scipy.spatial import distance as dist\nfrom imutils import perspective\nfrom imutils import contours\nimport numpy as np\nimport imutils\nimport cv2\n\ndef midpoint(ptA, ptB):\n return ((ptA[0] + ptB[0]) / 2, (ptA[1] + ptB[1]) / 2)\n\nimage_path = 'example.png'\nwidth_reference_object = 0.955\n# assume reference object is the left_most object\n\n#load the image, convert it to grayscale, blur it\nimage = cv2.imread(image_path)\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ngray = cv2.GaussianBlur(gray, (7,7), 0)\n\n# perform the edge detection, perform dilation and erosion to close\n# gaps in between object edge\nedged = cv2.Canny(gray, 50, 100)\nedged = cv2.dilate(edged, None, iterations= 1)\nedged = cv2.erode(edged, None, iterations= 1)\n\n# find contours in the edge map\ncnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\n\n#sort contour from left to right\n(cnts, _) = contours.sort_contours(cnts, 'left-to-right')\n\n#initialize the pixel per metric\npixelsPerMetric = None\n\n#loop over the contour\nfor c in cnts:\n if cv2.contourArea(c) < 100:\n continue\n\n #compute rotated bounding box of the contour\n orig = image.copy()\n box = cv2.minAreaRect(c)\n box = cv2.boxPoints(box)\n box = np.array(box, dtype= 'int')\n\n # order the points in the contour such that they appear\n # in top-left, top-right, bottom-right, and bottom-left\n # order, then draw the outline of the rotated bounding\n # box\n box = perspective.order_points(box)\n cv2.drawContours(orig, [box.astype(\"int\")], -1, (0, 255, 0), 2)\n\n #loop over the original points and draw them\n for (x, y) in box:\n cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)\n\n # unpack the ordered bounding box, then compute the midpoint\n # between the top-left and top-right coordinates, followed by\n # the midpoint between bottom-left and bottom-right coordinates\n (tl, tr, br, bl) = box\n (tltrX, tltrY) = midpoint(tl, tr)\n (blbrX, blbrY) = midpoint(bl, br)\n\n # compute the midpoint between the top-left and top-right points,\n # followed by the midpoint between the top-righ and bottom-right\n (tlblX, tlblY) = midpoint(tl, bl)\n (trbrX, trbrY) = midpoint(tr, br)\n\n # draw the midpoints on the image\n cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)\n cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)\n\n # draw lines between the midpoints\n cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)), (255, 0, 255), 2)\n cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)), (255, 0, 255), 2)\n\n # compute the Euclidean distance between the midpoints\n dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))\n dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n\n # if the pixels per metric has not been initialized, then\n # compute it as the ratio of pixels to supplied metric\n # (in this case, inches)\n if pixelsPerMetric is None:\n pixelsPerMetric = dB / width_reference_object\n\n # compute the size of the object\n dimA = dA / pixelsPerMetric\n dimB = dB / pixelsPerMetric\n # draw the object sizes on the image\n cv2.putText(orig, \"{:.1f}in\".format(dimA),\n (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.65, (255, 255, 255), 2)\n cv2.putText(orig, \"{:.1f}in\".format(dimB),\n (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.65, (255, 255, 255), 2)\n # show the output image\n cv2.imshow(\"carot\", orig)\n cv2.waitKey(0)","sub_path":"size-of-object/object_size.py","file_name":"object_size.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"28010457","text":"\nimport torch\nimport torch.nn as nn\nfrom sg2im.layers import build_mlp\n\nclass GraphBlock(nn.Module):\n def __init__(self, input_dim, output_dim=None, hidden_dim=512, pooling='avg', mlp_normalization='none'):\n super(GraphBlock, self).__init__()\n if output_dim is None:\n output_dim = input_dim\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.hidden_dim = hidden_dim\n self.pooling = pooling\n self.input_to_hidden = nn.Sequential(\n nn.Linear(in_features=3*input_dim, out_features=3*hidden_dim),\n nn.ReLU()\n )\n self.edgeUpdate = EdgeUpdate(3*hidden_dim, output_dim)\n self.nodeUpdate = NodeUpdate(2*hidden_dim+output_dim, output_dim)\n self.hidden_to_out = nn.Sequential(\n nn.Linear(in_features=hidden_dim, out_features=output_dim),\n nn.ReLU()\n )\n \n def forward(self, obj_vecs, pred_vecs, edges):\n dtype, device = obj_vecs.dtype, obj_vecs.device\n O, T = obj_vecs.size(0), pred_vecs.size(0)\n Din, H, Dout = self.input_dim, self.hidden_dim, self.output_dim\n \n # Get hidden representation of triples\n s_idx = edges[:,0].contiguous()\n o_idx = edges[:,1].contiguous()\n \n cur_s_vecs = obj_vecs[s_idx]\n cur_o_vecs = obj_vecs[o_idx]\n # New shape is (T, 3 * H)\n cur_t_vecs = torch.cat([cur_s_vecs, pred_vecs, cur_o_vecs], dim=1)\n hidden_t_vecs = self.input_to_hidden(cur_t_vecs)\n \n # Update edge attributes\n hidden_s_vecs = hidden_t_vecs[:, :H]\n hidden_p_vecs = hidden_t_vecs[:, H:2*H] #hidden_t_vecs[:, H:(H+Dout)]\n hidden_o_vecs = hidden_t_vecs[:, 2*H:3*H] #hidden_t_vecs[:, (H+Dout) : (2*H+Dout)]\n # New shape is (T, Dout)\n new_pred_vecs = self.edgeUpdate(hidden_s_vecs, hidden_p_vecs, hidden_o_vecs)\n \n # Aggregate edge attributes per node and update note attributes\n # New shape is (T, 2 * H)\n new_t_vecs = self.nodeUpdate(hidden_s_vecs, new_pred_vecs, hidden_o_vecs)\n new_s_vecs = new_t_vecs[:, :H]\n new_o_vecs = new_t_vecs[:, H:2*H]\n \n pooled_obj_vecs = torch.zeros(O, H, dtype=dtype, device=device)\n s_idx_exp = s_idx.view(-1, 1).expand_as(new_s_vecs)\n o_idx_exp = o_idx.view(-1, 1).expand_as(new_o_vecs)\n pooled_obj_vecs = pooled_obj_vecs.scatter_add(0, s_idx_exp, new_s_vecs)\n pooled_obj_vecs = pooled_obj_vecs.scatter_add(0, o_idx_exp, new_o_vecs)\n \n if self.pooling == 'avg':\n # Figure out how many times each object has appeared, again using\n # some scatter_add trickery.\n obj_counts = torch.zeros(O, dtype=dtype, device=device)\n ones = torch.ones(T, dtype=dtype, device=device)\n obj_counts = obj_counts.scatter_add(0, s_idx, ones)\n obj_counts = obj_counts.scatter_add(0, o_idx, ones)\n\n # Divide the new object vectors by the number of times they\n # appeared, but first clamp at 1 to avoid dividing by zero;\n # objects that appear in no triples will have output vector 0\n # so this will not affect them.\n obj_counts = obj_counts.clamp(min=1)\n pooled_obj_vecs = pooled_obj_vecs / obj_counts.view(-1, 1)\n \n # Send pooled object vectors through net2 to get output object vectors,\n # of shape (O, Dout)\n new_obj_vecs = self.hidden_to_out(pooled_obj_vecs)\n return new_obj_vecs, new_pred_vecs\n \n \nclass EdgeUpdate(nn.Module):\n def __init__(self, input_dim, output_dim):\n super(EdgeUpdate, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.linear = nn.Linear(in_features=input_dim, out_features=output_dim)\n self.relu = nn.ReLU()\n \n def forward(self, s_vecs, pred_vecs, o_vecs):\n t_vecs = torch.cat([s_vecs, pred_vecs, o_vecs],dim=1)\n out = self.linear(t_vecs)\n out = self.relu(out)\n return out\n \nclass NodeUpdate(nn.Module):\n def __init__(self, input_dim, output_dim):\n super(NodeUpdate, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.linear = nn.Linear(in_features=input_dim, out_features=output_dim)\n self.relu = nn.ReLU()\n \n def forward(self, s_vecs, pred_vecs, o_vecs):\n t_vecs = torch.cat([s_vecs, pred_vecs, o_vecs],dim=1)\n out = self.linear(t_vecs)\n out = self.relu(out)\n return out\n \nclass GraphTripleConvNet(nn.Module):\n \"\"\" A sequence of scene graph convolution layers \"\"\"\n def __init__(self, input_dim, num_layers=5, hidden_dim=512, pooling='avg',\n mlp_normalization='none'):\n super(GraphTripleConvNet, self).__init__()\n\n self.num_layers = num_layers\n self.gconvs = nn.ModuleList()\n gconv_kwargs = {\n 'input_dim': input_dim,\n 'hidden_dim': hidden_dim,\n 'pooling': pooling,\n 'mlp_normalization': mlp_normalization,\n }\n for _ in range(self.num_layers):\n self.gconvs.append(GraphBlock(**gconv_kwargs))\n\n def forward(self, obj_vecs, pred_vecs, edges):\n for i in range(self.num_layers):\n gconv = self.gconvs[i]\n obj_vecs, pred_vecs = gconv(obj_vecs, pred_vecs, edges)\n return obj_vecs, pred_vecs","sub_path":"sg2im/sg2im/graph_block.py","file_name":"graph_block.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"348676756","text":"\"\"\"\nTo use the python script in Command Prompt:\nWrite 'python your_file_name.py'\nExample: 'python challenge101.py'\n\"\"\"\n# imports the 'month_name' functionality from the calendar module\nfrom calendar import month_name\n# function with int as parameter\ndef MonthName(number):\n # variable holding the name of the month from 'number'\n monthName = month_name[number]\n\n # if number is less than 1\n if(number < 1):\n # prompt the user with a message\n print(\"Number is below 1. Must be between 1 - 12.\")\n # else if number is more than 12\n elif(number > 12):\n # prompt the user with a message\n print(\"Number is above 12. Must be between 1 - 12.\")\n # if everything above is False\n else:\n # print the name of the month\n print(monthName)\n\n# function calls with arguments (must be a number between 1 - 12)\nMonthName(1)\nMonthName(4)\nMonthName(12)","sub_path":"challenge105/challenge105.py","file_name":"challenge105.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"126369217","text":"import numpy\nimport math\nimport cmath\nimport operator\n\n# Methods common to both the transmitter and receiver\ndef modulate(fc, samplerate, samples):\n '''\n A modulator that multiplies samples with a local carrier \n of frequency fc, sampled at samplerate\n '''\n\n ns = numpy.array(range(0, len(samples)))\n ns = numpy.multiply(2.0 * math.pi * fc / samplerate, ns)\n\n mod_samples = numpy.multiply(samples, numpy.cos(ns))\n\n return mod_samples\n\n\ndef demodulate(fc, samplerate, samples):\n '''\n A demodulator that performs quadrature demodulation\n '''\n cutoff_freq = math.pi * fc / samplerate\n\n demod_samples = lpfilter(samples, cutoff_freq)\n\n return demod_samples\n\n\ndef lpfilter(samples_in, omega_cut):\n '''\n A low-pass filter of frequency omega_cut.\n '''\n # set the filter unit sample response\n # building the lpf\n L = 50\n\n lpf = (L * 2 + 1) * [0.0]\n\n for n in range(-1 * L, L+1):\n if n != 0:\n lpf[n + L] = numpy.sin(omega_cut * n) / (n * math.pi)\n else:\n lpf[n + L] = omega_cut / math.pi\n\n # compute demodulated samples\n\n demod_samples = convolve(numpy.array(samples_in), numpy.array(lpf), omega_cut)\n\n demod_samples_mag = [abs(x) for x in demod_samples]\n\n return numpy.array(demod_samples_mag)\n\ndef convolve(arr1, arr2, omega_cut):\n # the equation we're trying to satisfy is:\n # demod_samples[n] = (received[n]*e^(2j * omega_cut * n)) convolved with lpf[n]\n # so in this function, we must BOTH \n # a) multiply the received samples by e^(2j * omega_cut * n) \n # = cmath.exp(complex(0, 2 * omega_cut * n))\n # note that this depends on n and therefore must be done in a for loop (can't use numpy.multiply)\n # b) convolve the multiplied received samples with the low pass filter\n # right now, I'm passing in the received samples as arr1, the lpf as arr2, and omega_cut as itself\n\n len_arr1 = len(arr1)\n len_arr2 = len(arr2)\n\n arr1_modded = len_arr1 * [complex(0.0, 0.0)]\n\n for n in range(0, len_arr1):\n arr1_modded[n] = arr1[n] * cmath.exp(complex(0, 2 * omega_cut * n))\n\n\n len_result = len_arr1 + len_arr2 - 1\n\n result = numpy.array(len_result * [complex(0.0,0.0)])\n\n # we have to iterate over n\n for n in range(0, len_result):\n\n # This calculating the sum is the slow part.\n # What we want is: y[n] = sum over k in range(0, len_arr2) of arr2[k]* arr1[n-k].\n \n # The fastest way to do this is probably to create \n # two arrays of all values of arr2[k] and arr1[n-k],\n # then take the dot product of those arrays using numpy.dot and then using \n # numpy.sum to sum over all of those products quickly. \n \n # What I'm having trouble with is figuring out edge cases. When n-k is out of range,\n # we ideally want to pad with zeros (0.0). But for some reason, I can't wrap my \n # head around the math to do so. \n\n cur = []\n\n if n - (len_arr2 -1) < 0:\n cur = arr1_modded[0:n+1]\n #print str(len(cur)) + str(len(arr2))\n zeros = (len_arr2 - len(cur)) * [0.0]\n #print str(len(zeros))\n cur = numpy.concatenate((zeros,cur),axis=0)\n #print \"padded with zeros at beginning\"\n \n\n else:\n cur = arr1_modded[n - (len_arr2 -1): n+1]\n\n if len(cur) < len_arr2:\n #print str(len(cur)) + str(len(arr2))\n zeros = (len_arr2 - len(cur)) * [0.0]\n cur = numpy.concatenate((cur,zeros),axis=0)\n\n cur = numpy.array(cur[::-1])\n\n #print str(len(cur)) + str(len(arr2))\n result[n] = numpy.sum(numpy.dot(cur, arr2))\n\n # return value should be a numpy array for best results\n return numpy.array(result)\n\n \n# this snippet of code shows that the current function is working\n'''\narr1 = [0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0]\narr2 = [1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0]\n\nprint numpy.convolve(arr1, arr2)\n\nprint convolve(arr1, arr2, 0)\n'''\n\n\n\n\n\n","sub_path":"milestone1_starter/common_txrx_mil3.py","file_name":"common_txrx_mil3.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"380164625","text":"import numpy as np\nimport sys\n\nclass DecisionTree():\n\n def __init__(self, max_depth=5, weights = None):\n \"\"\"\n Initialize the parameters of the decision tree\n\n :param max_depth: the maximum depth of the tree\n \"\"\"\n\n self.tree = None\n self.max_depth = max_depth\n self.weights = weights\n\n def fit(self, X, Y):\n \"\"\"\n Fit a tree to the training data\n\n :param X: the training inputs\n :param Y: the training labels\n :return:\n \"\"\"\n\n self.tree = self.__tree_building(X, Y, np.arange(X.shape[1]))\n\n def predict(self, X):\n \"\"\"\n Run through the inputs data and read the tree for each sample.\n\n :param X: the inputs data\n :return:\n \"\"\"\n\n predictions = []\n for sample in X:\n prediction = self.__tree_prediction(sample, self.tree)\n predictions.append(prediction)\n\n return predictions\n\n def __tree_building(self, X, Y, remaining_features, depth=0, max_depth=10):\n \"\"\"\n Build a tree recursively on the training inputs.\n\n :param X: the training inputs\n :param Y: the training labels\n :param remaining_features: the feature on which to split on\n :param depth: the current depth of the tree\n :param max_depth: the maximum depth allowed for the tree\n :return:\n \"\"\"\n\n # Find the majority class in the split\n if np.sum(Y == 0) > np.sum(Y == 1):\n majority_class = 0\n else:\n majority_class = 1\n\n # Return a leaf if a stopping criterion is reached\n if len(np.unique(Y)) == 1:\n return self.__build_leaf(majority_class)\n if len(remaining_features) == 0:\n return self.__build_leaf(majority_class)\n if depth == max_depth:\n return self.__build_leaf(majority_class)\n\n # Find the best feature and the split value on which to split the data\n best_feature, split = self.__best_feature_selection(X, Y, remaining_features)\n\n # Remove the best feature from the feature on which to split\n index = np.where(remaining_features == best_feature)\n remaining_features = np.delete(remaining_features, index)\n\n # Split the data according to the best feature and the split value\n left_subset_X, right_subset_X, left_subset_Y, right_subset_Y, _, _ = self.__split_data(X, Y, best_feature, split)\n\n # Build the left and right tree according to the two subsets of data made above\n left_tree = self.__tree_building(left_subset_X, left_subset_Y, remaining_features, depth+1)\n right_tree = self.__tree_building(right_subset_X, right_subset_Y, remaining_features, depth+1)\n\n return self.__build_node(best_feature, split, left_tree, right_tree)\n\n def __tree_prediction(self, X, tree):\n \"\"\"\n Run through the tree and make prediction (0, 1) on the sample.\n\n :param X: the sample\n :param tree: the fitted tree\n :return:\n \"\"\"\n\n # If we reach a leaf we make a prediction.\n if tree['is_leaf'] == True:\n prediction = tree['prediction']\n return prediction\n\n # Get the split feature and the split value for this node\n feature = tree['feature_split']\n split_value = tree['split_value']\n\n # Compare the value of the sample for the split feature with the split value and determine\n # in which direction (left or right) to go in the tree\n # print(X)\n # print(feature)\n value_at_feature = X[feature]\n if value_at_feature < split_value:\n prediction = self.__tree_prediction(X, tree['left_child'])\n elif value_at_feature > split_value:\n prediction = self.__tree_prediction(X, tree['right_child'])\n\n return prediction\n\n def __best_feature_selection(self, X, Y, remaining_features):\n \"\"\"\n Find the best feature on which to make a split in the data.\n\n :param X: the inputs data\n :param Y: the labels data\n :param remaining_features: the features on which we can make a split\n :return:\n \"\"\"\n\n best_feature = None\n best_split = None\n best_gini_index = 10\n\n # Run through each features\n for feature in remaining_features:\n\n # Test different interval values on which to make the split\n inter_gap = np.std(X[:,feature]) / 2.0\n split = np.min(X[:,feature]) + inter_gap\n\n # Run through each interval values\n while(split < np.max(X[:,feature])):\n\n # Split the data according to the feature and the split value\n _, _, left_subset_Y, right_subset_Y, left_weights, right_weights = self.__split_data(X, Y, feature, split)\n\n # Evaluate the split that has been made above\n gini_index = self.__gini_index(left_subset_Y, right_subset_Y, left_weights, right_weights)\n\n # if the gini index is the best so far assign the feature and the split\n # to the best feature and best split\n if gini_index < best_gini_index:\n best_feature = feature\n best_split = split\n best_gini_index = gini_index\n\n split += inter_gap\n\n return best_feature, best_split\n\n def __gini_index(self, left_subset_Y, right_subset_Y, left_weights, right_weights):\n \"\"\"\n Compute the gini index for a split in the data.\n\n :param left_subset_Y: the labels on the left side of the parent node\n :param right_subset_Y: the labels on the right side of the parent node\n :return:\n \"\"\"\n\n # Compute the sizes of the nodes\n left_node_size = float(len(left_subset_Y))\n right_node_size = float(len(right_subset_Y))\n parent_node_size = float(left_node_size + right_node_size)\n\n # Compute the probabilities of each class in each subset\n if self.weights is None:\n left_subset_proba_0 = np.sum(left_subset_Y == 0) / left_node_size\n left_subset_proba_1 = np.sum(left_subset_Y == 1) / left_node_size\n right_subset_proba_0 = np.sum(right_subset_Y == 0) / right_node_size\n right_subset_proba_1 = np.sum(right_subset_Y == 1) / right_node_size\n # Compute the weighted proportions if adaboost is used\n else:\n left_subset_proba_0 = np.sum(left_weights * (left_subset_Y == 0)) / left_node_size\n left_subset_proba_1 = np.sum(left_weights * (left_subset_Y == 1)) / left_node_size\n left_subset_proba_0 = left_subset_proba_0 / (left_subset_proba_0 + left_subset_proba_1)\n left_subset_proba_1 = left_subset_proba_1 / (left_subset_proba_0 + left_subset_proba_1)\n right_subset_proba_0 = np.sum(right_weights * (right_subset_Y == 0)) / right_node_size\n right_subset_proba_1 = np.sum(right_weights * (right_subset_Y == 1)) / right_node_size\n right_subset_proba_0 = right_subset_proba_0 / (right_subset_proba_0 + right_subset_proba_1)\n right_subset_proba_1 = right_subset_proba_1 / (right_subset_proba_0 + right_subset_proba_1)\n\n # Compute the gini index\n left_gini_index = (1 - (left_subset_proba_0 * left_subset_proba_0 + left_subset_proba_1 * left_subset_proba_1)) * (left_node_size/parent_node_size)\n right_gini_index = (1 - (right_subset_proba_0 * right_subset_proba_0 + right_subset_proba_1 * right_subset_proba_1)) * (right_node_size/parent_node_size)\n gini_index = left_gini_index + right_gini_index\n\n return gini_index\n\n def __split_data(self, X, Y, feature, split):\n \"\"\"\n Split the data according to the feature and split value\n\n :param X: the data\n :param Y: the labels\n :param feature: the feature on which to make the split\n :param split: the value on which to make the split\n :return:\n \"\"\"\n\n left_indices = np.where(X[:, feature] < split)[0]\n right_indices = np.where(X[:, feature] > split)[0]\n\n left_subset_Y = Y[left_indices]\n right_subset_Y = Y[right_indices]\n\n left_subset_X = X[left_indices, :]\n right_susbset_X = X[right_indices, :]\n\n if self.weights is not None:\n left_weights = self.weights[left_indices]\n rights_weights = self.weights[right_indices]\n return left_subset_X, right_susbset_X, left_subset_Y, right_subset_Y, left_weights, rights_weights\n else:\n return left_subset_X, right_susbset_X, left_subset_Y, right_subset_Y, None, None\n\n def __build_node(self, feature, split, left_child, right_child):\n \"\"\"\n Build a node of the tree.\n\n :param feature: the best feature on which to make a split\n :param split: the best value on which to make a split\n :param left_child: the left child of the node\n :param right_child: the right child of the node\n :return:\n \"\"\"\n\n node = {\n 'is_leaf': False,\n 'feature_split': feature,\n 'split_value': split,\n 'left_child': left_child,\n 'right_child': right_child\n }\n\n return node\n\n def __build_leaf(self, prediction):\n \"\"\"\n Build a leaf of the tree\n\n :param prediction: the prediction to make for this leaf\n :return:\n \"\"\"\n\n leaf = {\n 'is_leaf': True,\n 'prediction': prediction\n }\n\n return leaf","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595802425","text":"#!/usr/bin/env python3\n\n\"\"\"\nRequirements:\nsudo -H pip3 install PrettyTable\n\"\"\"\n\nimport argparse\nimport csv\nimport io\nimport json\nfrom prettytable import PrettyTable\nimport re\nimport sys\nimport zipfile\n\n\ndef find_exact_postcode(lad_data, postcode, results):\n\n postcode = postcode.lower().replace(\" \", \"\")\n\n for row in lad_data:\n if row[\"postcode\"].lower().replace(\" \", \"\") == postcode:\n results.add_row(\n [\n row[\"exchange_1141\"],\n row[\"postcode\"],\n row[\"mdf_id\"],\n row[\"site_id\"],\n row[\"fibre_upto_exchange\"],\n row[\"fibre_upto_postcode\"],\n row[\"exchange_name\"],\n ]\n )\n return True\n\n print(\"Postcode not found in LAD file\")\n return False\n\n\ndef find_postcode(lad_data, postcode, results):\n\n postcode = postcode.lower().replace(\" \", \"\")\n\n for row in lad_data:\n if postcode in row[\"postcode\"].lower().replace(\" \", \"\"):\n results.add_row(\n [\n row[\"exchange_1141\"],\n row[\"postcode\"],\n row[\"mdf_id\"],\n row[\"site_id\"],\n row[\"fibre_upto_exchange\"],\n row[\"fibre_upto_postcode\"],\n row[\"exchange_name\"],\n ]\n )\n\n if len(results._rows) == 0:\n print(\"Postcode not found in LAD file\")\n return False\n else:\n return True\n\n\ndef load_csv(filename):\n\n \"\"\"\n This function returns each CSV row as an OrderedDict containing 2-tuples:\n OrderedDict([('exchange_1141', 'AB/WEST'),\n ('postcode', 'AB10 7LX'),\n ('mdf_id', 'NSWES'),\n ('site_id', 'AB0004A1'),\n ('fibre_upto_exchange', 'Y'),\n ('fibre_upto_postcode', 'N'),\n ('exchange_name', 'WEST AUTO EXCHANGE')])\n OrderedDict([('exchange_1141', 'AB'),\n ('postcode', 'AB10 7LY'),\n ('mdf_id', 'NSLNG'),\n ('site_id', 'AB0006A1'),\n ('fibre_upto_exchange', 'Y'),\n ('fibre_upto_postcode', 'N'),\n ('exchange_name', 'ABERDEEN CENTRAL TE')])\n \"\"\"\n\n if filename == None:\n print(\"LAD file filename not provided\")\n return False\n\n try:\n\n # Check if ZIP archive filename is given\n if filename.split(\".\")[-1] == \"zip\":\n\n try:\n zip_data = zipfile.ZipFile(filename)\n except Exception as e:\n print(\"Couldn't open zip file {}: {}\".format(filename, e))\n return False\n\n # Look for the LAD file inside ZIp archive\n for fname in zip_data.namelist():\n if re.match(\".*LODE_LAD.*\", fname):\n csv_filename = fname\n break\n else:\n print(\"Couldn't find LAD CSV file in ZIP archive\")\n return False\n\n # Decompress it\n try:\n csv_file = io.StringIO(\n zip_data.read(\n csv_filename\n ).decode(\"ISO-8859-1\")\n )\n except Exception as e:\n print(\n \"Couldn't decompression CSV file from ZIP archive \"\n \"to string: {}\".format(e)\n )\n return False\n\n\n # Assume CSV file\n else:\n try:\n csv_file = open(filename, \"r\", encoding=\"ISO-8859-1\")\n except Exception:\n print(\"Couldn't open file {}\".format(filename))\n return False\n\n except Exception as e:\n print(\n \"LAD file name invalid, expected foo.csv or foo.zip: {}\".format(e)\n )\n\n\n try:\n csv_data = csv.DictReader(csv_file)\n except Exception as e:\n print(\"Couldn't parse CSV file: {}\".format(e))\n return False\n\n rows = [row for row in csv_data]\n\n csv_file.close()\n\n print(\"Loaded {} postcodes from LAD file\".format(len(rows)))\n return rows\n\n\ndef parse_cli_args():\n\n parser = argparse.ArgumentParser(\n description=\"Search the OR LAD file for a postcode\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n \"-l\",\n \"--lad-file\",\n help=\"Openreach LAD file, CSV or ZIP containing CSV\",\n type=str,\n default=None\n )\n parser.add_argument(\n \"-n\",\n \"--not-exact\",\n help=\"Disable exact postcode match, return similar postcodes\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"-p\",\n \"--postcode\",\n help=\"Exact postcode to search for\",\n type=str,\n default=None\n )\n\n return vars(parser.parse_args())\n\n\ndef main():\n\n args = parse_cli_args()\n if args == False:\n return False\n\n if not args[\"postcode\"]:\n print(\"Need to specify a postcode to search for\")\n return False\n\n if not args[\"lad_file\"]:\n print(\"Need to specify LAD filename\")\n return False\n\n lad_data = load_csv(args[\"lad_file\"])\n if not lad_data:\n return False\n\n results = PrettyTable(\n [\n \"exchange_1141\",\n \"postcode\",\n \"mdf_id\",\n \"site_id\",\n \"fibre_upto_exchange\",\n \"fibre_upto_postcode\",\n \"exchange_name\",\n ]\n )\n\n if args[\"not_exact\"]:\n if not find_postcode(lad_data, args[\"postcode\"], results):\n return False\n else:\n if not find_exact_postcode(lad_data, args[\"postcode\"], results):\n return False\n\n if len(results._rows) > 0:\n results.sortby = \"postcode\"\n print(results)\n\n return True\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"postcode_search.py","file_name":"postcode_search.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"528803589","text":"\"\"\"\r\n9,852,852\r\n\r\nDokuz Milyon \r\nSekiz Yüz Elli Bin \r\nSekiz Yüz Elli İki\r\n\r\n\"\"\"\r\n\r\nbirler = {\r\n\"0\":\" \",\r\n\"1\":\" Bir\",\r\n\"2\":\" İki\",\r\n\"3\":\" Üç\",\r\n\"4\":\" Dört\",\r\n\"5\":\" Beş\",\r\n\"6\":\" Altı\",\r\n\"7\":\" Yedi\",\r\n\"8\":\" Sekiz\",\r\n\"9\":\" Dokuz\"}\r\n\r\nonlar = {\r\n\"0\":\" \",\r\n\"1\":\" On\",\r\n\"2\":\" Yirmi\",\r\n\"3\":\" Otuz\",\r\n\"4\":\" Kırk\",\r\n\"5\":\" Elli\",\r\n\"6\":\" Altmış\",\r\n\"7\":\" Yetmiş\",\r\n\"8\":\" Seksen\",\r\n\"9\":\" Doksan\"}\r\n\r\nbasamak = {\r\n 0:\" \",\r\n 1:\" Bin\",\r\n 2:\" Milyon\",\r\n 3:\" Milyar\",\r\n 4:\" Trilyon\",\r\n 5:\" Katrilyon\",\r\n}\r\n\r\n\r\nwhile True:\r\n sayi = input(\"Sayıyı Giriniz\").replace(\",\",\"\").replace(\".\",\"\")\r\n if sayi == \"e\":\r\n break\r\n sayi = str(int(sayi))\r\n while len(sayi)%3!=0:\r\n sayi = \"0\" + sayi\r\n \"\"\"\r\n 009852852\r\n\r\n \"\"\"\r\n liste = []\r\n for i in range(0,int(len(sayi)/3)):\r\n liste.append(sayi[(i*3):(i*3)+3])\r\n print(liste)\r\n liste.reverse()\r\n tumSonuc = \"\"\r\n adim = 0\r\n for item in liste:\r\n sonuc = \"\"\r\n if item != \"000\":\r\n if item[0] != \"0\":\r\n if item[0] != \"1\":\r\n sonuc = birler[item[0]] +\" Yüz \"\r\n else:\r\n sonuc = \"Yüz\"\r\n sonuc += onlar[item[1]] + birler[item[2]] \r\n sonuc += basamak[adim]\r\n adim+= 1\r\n tumSonuc = sonuc + tumSonuc\r\n print(tumSonuc)\r\n","sub_path":"Ornek2.py","file_name":"Ornek2.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"203502208","text":"\"\"\"This file handles code for parsing CSV-formatted statfiles into the database.\"\"\"\nfrom __future__ import unicode_literals\nimport os\nimport fnmatch\nimport shutil\nimport sys\nimport datetime\nimport re\nfrom app import app, models, db\nfrom config import STATS_DIR, PROCESSED_DIR, UNPARSABLE_DIR\n\ndatabase_busy = False\n\n\ndef batch_parse():\n \"\"\"Parse all statfiles in configured directory.\"\"\"\n parsed = 0\n errored = 0\n\n database_busy = False # Just in case\n\n if not os.path.exists(STATS_DIR):\n app.logger.debug('!! ERROR: Statfile dir path is invalid. Path used: ' + STATS_DIR)\n return -1\n for file in os.listdir(STATS_DIR):\n if fnmatch.fnmatch(file, 'statistics_*.txt'):\n try:\n parse_file(os.path.join(STATS_DIR, file))\n parsed += 1\n shutil.move(os.path.join(STATS_DIR, file), os.path.join(PROCESSED_DIR, file))\n except:\n if database_busy:\n app.logger.warning('Could not write file changes: database busy. Try again later.')\n return 530\n app.logger.error('!! ERROR: File could not be parsed. Details: \\n${0}'.format(str(sys.exc_info()[0])))\n errored += 1\n shutil.move(os.path.join(STATS_DIR, file), os.path.join(UNPARSABLE_DIR, file))\n raise\n\n app.logger.debug('# DEBUG: Batch parsed ' + str(parsed) + ' files with ' + str(errored) + ' exceptions.')\n\n\ndef parse_file(path):\n \"\"\"Parse the contents of a CSV statfile.\"\"\"\n if not os.path.exists(path):\n app.logger.error('!! ERROR: Tried to parse non-existant path ' + str(path))\n return False\n f = open(path, 'r+')\n contents = f.read()\n f.close()\n filename = os.path.basename(path)\n return parse(contents, filename)\n\n\n# def parse_url(url):\n# \"\"\"Parse the contents of a plain text statfile located at public-facing URL. Unused.\"\"\"\n# r = requests.get(url)\n# if r.status_code != 200:\n# return flask.make_response(\"ERROR - We were denied access to the URL supplied.\", 500)\n# else:\n# # Generate a Match model and store it in the session. This gives us\n# # access to a valid match ID so the other models can be stored properly\n# filename = os.path.basename(url)\n# parseResult = parse(r.text, filename)\n# if parseResult:\n# app.logger.debug(\"PARSED %r\" % filename)\n# return flask.make_response(\"OK\", 200)\n# else:\n# return flask.make_response(\"DUPLICATE ENTRY\", 500)\n\n\ndef parse(text, filename):\n \"\"\"Parse the raw text of a stat file. Requires a file name to check for a duplicate entry.\"\"\"\n q = db.session.query(models.Match.parsed_file).filter(models.Match.parsed_file == filename)\n if(q.first()):\n app.logger.warning(\" ~ ~ Duplicate parse entry detected.)\\n ~ ~ Request filename: %s\\n ~ ~ Stored filename: %s\",\n filename, q.first().parsed_file)\n return False\n else:\n app.logger.debug('Starting parse of %r' % filename)\n\n match = models.Match()\n match.parsed_file = filename\n # Regex is in format yyyy-dd-mm\n search_str = '^statistics_((?:19|20)\\d{2})[\\. .](0[1-9]|[12][0-9]|3[01])[\\. .](0[1-9]|1[012])(?:.*)\\.txt$'\n file_date = re.search(search_str, filename)\n if file_date is None or len(file_date.groups()) != 3:\n app.logger.warning('Invalid filename for timestamp: %r' % filename)\n return False\n match.date = datetime.date(int(file_date.group(1)), int(file_date.group(3)), int(file_date.group(2)))\n db.session.add(match)\n try:\n db.session.flush()\n except:\n # database_busy = True\n return False\n lines = text.splitlines()\n for line in lines:\n try:\n parse_line(line, match)\n except:\n app.logger.error('Error parsing line: %r' % line)\n db.session.rollback()\n raise\n return\n db.session.flush()\n db.session.commit()\n return True\n\n\n# Format is YYYY.MM.DD.HH.MM.SS\ndef format_timestamp(timestamp):\n \"\"\"Format a timestamp stored in stat files to a DateTime.\"\"\"\n expected_timestamp_format = '^(\\d{4})\\.(0?[1-9]|1[012])\\.(0?[1-9]|[12][0-9]|3[01])\\.(?:(?:([01]?\\d|2[0-3])\\.)?([0-5]?\\d)\\.)?([0-5]?\\d)$'\n searched = re.search(expected_timestamp_format, timestamp)\n year = int(searched.group(1))\n month = int(searched.group(2))\n day = int(searched.group(3))\n hour = int(searched.group(4))\n minute = int(searched.group(5))\n second = int(searched.group(6))\n\n dated = datetime.datetime(year, month, day, hour, minute, second)\n return dated\n\n\ndef parse_line(line, match):\n \"\"\"Parse a single line from a stat file.\"\"\"\n x = line.split('|')\n x = nullparse(x)\n\n if x[0] == 'STATLOG_START':\n match.data_version = x[1]\n match.mapname = x[2]\n match.starttime = x[3]\n match.endtime = x[4]\n if float(match.data_version) >= 1.1:\n match.start_datetime = format_timestamp(match.starttime)\n match.end_datetime = format_timestamp(match.endtime)\n match.round_length = (match.end_datetime - match.start_datetime).total_seconds()\n # TODO: Test this once PR merges\n elif x[0] == 'MASTERMODE':\n match.mastermode = x[1]\n elif x[0] == \"GAMEMODE\":\n prefix = len(\"GAMEMODE|\")\n match.modes_string = line[prefix:]\n match.modes_string = match.modes_string\n elif x[0] == \"TECH_TOTAL\":\n match.tech_total = x[1]\n elif x[0] == \"BLOOD_SPILLED\":\n match.blood_spilled = x[1]\n elif x[0] == \"CRATES_ORDERED\":\n match.crates_ordered = x[1]\n elif x[0] == \"ARTIFACTS_DISCOVERED\":\n match.artifacts_discovered = x[1]\n elif x[0] == \"CREWSCORE\":\n match.crewscore = x[1]\n elif x[0] == \"NUKED\":\n match.nuked = truefalse(x[1])\n elif x[0] == \"ESCAPEES\":\n match.escapees = x[1]\n elif x[0] == \"MOB_DEATH\":\n d = models.Death(match_id=match.id)\n d.mindname = nullparse(x[9])\n d.mindkey = nullparse(x[8])\n d.timeofdeath = x[3]\n d.typepath = x[1]\n d.special_role = x[2]\n d.last_assailant = x[4]\n d.death_x = x[5]\n d.death_y = x[6]\n d.death_z = x[7]\n\n db.session.add(d)\n elif x[0] == \"ANTAG_OBJ\":\n a = models.AntagObjective(match_id=match.id)\n a.mindname = nullparse(x[1])\n a.mindkey = nullparse(x[2])\n a.special_role = x[3]\n a.objective_type = x[4]\n a.objective_desc = x[6]\n # Check if this is a targeted objective or not.\n if x[5].isdigit():\n a.objective_succeeded = int(x[5])\n else:\n a.objective_succeeded = int(x[8])\n a.target_name = x[7]\n a.target_role = x[6]\n if a.objective_succeeded >= 2: # Mutiny gives 2 as an additional success value.\n a.objective_succeeded = 1\n db.session.add(a)\n elif x[0] == \"EXPLOSION\":\n e = models.Explosion(match_id=match.id)\n e.epicenter_x = x[1]\n e.epicenter_y = x[2]\n e.epicenter_z = x[3]\n e.devestation_range = x[4]\n e.heavy_impact_range = x[5]\n e.light_impact_range = x[6]\n e.max_range = x[7]\n\n db.session.add(e)\n elif x[0] == \"UPLINK_ITEM\":\n u = models.UplinkBuy(match_id=match.id)\n u.mindname = x[2]\n u.mindkey = x[1]\n u.traitor_buyer = truefalse(x[3])\n u.bundle_path = x[4]\n u.item_path = x[5]\n\n db.session.add(u)\n elif x[0] == \"BADASS_BUNDLE\":\n bb = models.BadassBundleBuy(match_id=match.id)\n bb.mindname = x[2]\n bb.mindkey = x[1]\n bb.traitor_buyer = truefalse(x[3])\n\n db.session.add(bb)\n items = x[4]\n for item in items:\n i = models.BadassBundleItem(badass_bundle_id=bb.id)\n i.item_path = item\n db.session.add(i)\n elif x[0] == \"CULTSTATS\":\n c = models.CultStats(match_id=match.id)\n c.runes_written = x[1]\n c.runes_fumbled = x[2]\n c.runes_nulled = x[3]\n c.converted = x[4]\n c.tomes_created = x[5]\n c.narsie_summoned = truefalse(x[6])\n c.narsie_corpses_fed = x[7]\n c.surviving_cultists = x[8]\n c.deconverted = x[9]\n\n db.session.add(c)\n elif x[0] == \"XENOSTATS\":\n xn = models.XenoStats(match_id=match.id)\n xn.eggs_laid = x[1]\n xn.faces_hugged = x[2]\n xn.faces_protected = x[3]\n\n db.session.add(xn)\n elif x[0] == 'BLOBSTATS':\n bs = models.BlobStats(match_id=match.id)\n bs.blob_wins = x[1]\n bs.spawned_blob_players = x[2]\n bs.spores_spawned = x[3]\n bs.res_generated = x[3]\n\n db.session.add(bs)\n elif x[0] == 'MALFSTATS':\n ms = models.MalfStats(match_id=match.id)\n ms.malf_won = x[1]\n ms.malf_shunted = x[2]\n ms.borgs_at_roundend = x[3]\n\n db.session.add(ms)\n elif x[0] == 'MALFMODULES':\n try:\n match.malfstat.malf_modules = '|'.join(x.pop(0))\n except:\n raise\n elif x[0] == 'REVSQUADSTATS':\n rss = models.RevsquadStats(match_id=match.id)\n rss.revsquad_won = x[1]\n rss.remaining_heads = x[2]\n\n db.session.add(rss)\n elif x[0] == 'POPCOUNT':\n pc = models.PopulationSnapshot(match_id=match.id)\n pc.popcount = x[2]\n timestamp_string = x[1]\n # yyyy-mm-dd hh:mm:ss\n timestamp_pattern = '(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})'\n timestamp_regex = re.search(timestamp_pattern, timestamp_string)\n\n year = int(timestamp_regex.group(1))\n month = int(timestamp_regex.group(2))\n day = int(timestamp_regex.group(3))\n hour = int(timestamp_regex.group(4))\n minute = int(timestamp_regex.group(5))\n second = int(timestamp_regex.group(6))\n\n timestamp_dt = datetime.datetime(year, month, day, hour, minute, second)\n pc.time = timestamp_dt\n\n db.session.add(pc)\n return True\n\n\ndef nullparse(s):\n \"\"\"Convert 'null' or empty entries in a statfile line to None.\"\"\"\n for sstring in s:\n if sstring == '' or sstring.lower() == 'null':\n sstring = None\n return s\n\n\ndef truefalse(s):\n \"\"\"Parse 1/0 to true/false.\"\"\"\n if s == '1':\n return True\n return False\n","sub_path":"app/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216795332","text":"from Classes.User import Users\n\nVishal = Users('Vishal', 'Kushwaha', 'Male', 9654656057)\nMansi = Users('Mansi', 'Goyal', 'Female')\nTestUser = Users('Test', 'User', 'Test')\n\n\ndef main():\n Vishal.describe_user()\n Vishal.greet_user()\n Mansi.describe_user()\n Mansi.greet_user()\n TestUser.describe_user()\n TestUser.greet_user()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Session_1/Sol_9_3.py","file_name":"Sol_9_3.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156962179","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None:\n return head\n\n current_ptr = head\n next_ptr = head.next\n\n while next_ptr is not None:\n if current_ptr.val == next_ptr.val:\n # delete\n current_ptr.next = next_ptr.next\n next_ptr = current_ptr.next\n else:\n current_ptr = next_ptr\n next_ptr = next_ptr.next\n return head\n\n\n\n\n","sub_path":"83.py","file_name":"83.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353107966","text":"import json\nimport os\nimport unittest\n\nfrom product_crawler.domain.entities.source import Source\nfrom product_crawler.service.extract_product_service import ExtractProductService\nfrom tests.utils_test import UtilsTest\n\n\nclass TestExtractProductService(unittest.TestCase):\n\n def setUp(self):\n self.source_dto_file_path1 = UtilsTest.get_resource(os.path.join(\"tests\", \"sources\", \"amazon_product_page.json\"))\n self.page_file_path1 = UtilsTest.get_resource(os.path.join(\"tests\", \"pages\", \"amazon_chromebook.html\"))\n\n self.source_dto_file_path2 = UtilsTest.get_resource(os.path.join(\"tests\", \"sources\", \"amazon_product_page.json\"))\n self.page_file_path2 = UtilsTest.get_resource(os.path.join(\"tests\", \"pages\", \"amazon_playstation5.html\"))\n\n def test_extract_product_with_price(self):\n source_dto_file1 = open(self.source_dto_file_path1, \"r\")\n source_dto = json.load(source_dto_file1)\n source_dto_file1.close()\n\n source = Source.instantiate_from_dto(source_dto)\n\n page_file1 = open(self.page_file_path1, \"r\")\n page1 = page_file1.read()\n page_file1.close()\n\n products = ExtractProductService.extract_product_from_html(page1, source.template)\n\n self.assertEqual(1, len(products))\n self.assertEqual(\"Chromebook Acer R721T-488H AMD A4-9120C 4GB 11,6" Chrome OS\", products[0].name)\n self.assertEqual(\"R$1.999,00\", products[0].price)\n\n def test_extract_product_without_price(self):\n source_dto_file2 = open(self.source_dto_file_path2, \"r\")\n source_dto = json.load(source_dto_file2)\n source_dto_file2.close()\n\n source = Source.instantiate_from_dto(source_dto)\n\n page_file2 = open(self.page_file_path2, \"r\")\n page2 = page_file2.read()\n page_file2.close()\n\n products = ExtractProductService.extract_product_from_html(page2, source.template)\n\n self.assertEqual(1, len(products))\n self.assertEqual(\"Console PlayStation 5 - Digital Edition\", products[0].name)\n self.assertIsNone(products[0].price)\n","sub_path":"tests/unittests/test_extract_product_service.py","file_name":"test_extract_product_service.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"591953689","text":"import os\nimport time\nfrom doctest import testmod\n\n\nclass TestServer:\n \"\"\"\n >>> t = TestServer(\"Vignesh\")\n >>> s = t.create_folder('Viggi')\n >>> s\n True\n >>> w = t.write_file(\"Viggi\",\"Vigi\",'Hi My name is Vignesh')\n >>> w\n True\n >>> r = t.read_file(\"viggi\",\"Vigi\")\n >>> r\n 'Hi My name is Vignesh'\n >>> c = t.change_folder_path(\"Viggi\")\n >>> c\n True\n \"\"\"\n def __init__(self, user_id):\n \"\"\"We create a user id for each person and save it\n into root file.\n\n input : user_id\n output : A file stored inside the root folder\n \"\"\"\n self.user_id = user_id\n self.bool = 0\n self.file_name = 0\n self.filename = 0\n self.inp = 0\n self.size = 0\n self.curr = 0\n self.data_info = 0\n self.path_mod = 0\n self.path = 0\n self.is_write = 0\n self.file = 0\n self.modified = 0\n self.old_name = 0\n self.folder = 0\n self.root_path = f\"C:\\\\Users\\\\ADMIN\\\\Downloads\\\\my assignment\\\\Assignment_3\\\\root\\\\{self.user_id}\\\\\"\n try:\n os.makedirs(self.root_path)\n except Exception:\n pass\n\n def create_folder(self, name):\n \"\"\"\n We create a folder where we store the files which are\n used to read and write using read_file and write_file\n functions.\n\n parameters:name\n Output: We create a folder name and the output will be\n printed if it satisfies the conditions.\n \"\"\"\n self.file_name = name\n self.bool = False\n self.file = os.path.join(self.root_path, self.file_name)\n try:\n os.makedirs(self.file)\n self.bool = True\n except FileExistsError:\n print(\"File already exists\")\n finally:\n return self.bool\n\n def write_file(self, file_name, new_name, input_id):\n \"\"\"\n The write operation is performed by giving the foldername\n as input and file to be created and also the data\n to be written to the file.\n\n parameters: file_name, new_name, input_id\n\n Output: For given folder name, the file is written to the file\n created inside the folder and the output will be printed\n stating that the write_file is executed.\n \"\"\"\n self.filename = new_name\n self.file_name = f\"{file_name}\\\\\"\n self.inp = input_id\n self.is_write = False\n try:\n self.path_mod = os.path.join(self.root_path, self.file_name)\n self.path = os.path.join(self.path_mod, self.filename)\n with open(self.path, 'w') as is_write:\n is_write.write(self.inp)\n self.is_write = True\n except Exception as exp:\n print(exp)\n finally:\n return self.is_write\n\n def read_file(self, file_name, new_name):\n \"\"\"\n We perform read operation by specifying the folder name where\n we want to read the file.\n The read_file takes two arguments.\n parameters: file_name, new_name\n Returns: To read a file we need the folder name and also the\n file name created\n \"\"\"\n self.filename = new_name\n self.file_name = f\"{file_name}\\\\\"\n self.data_info = ''\n try:\n self.path_mod = os.path.join(self.root_path, self.file_name)\n self.path = os.path.join(self.path_mod, self.filename)\n with open(self.path, 'r') as is_read:\n self.data_info = is_read.readlines()\n except Exception as exp:\n return print(exp)\n finally:\n return \" \".join(self.data_info)\n\n def list_of_directories(self):\n \"\"\"\n Here we print the existing list of directories present in the folder.\n The list of directories contain the name of file, creation, and also\n the size of file\n \"\"\"\n self.file = os.listdir(self.root_path)\n self.size = []\n self.curr = []\n self.modified = []\n total_size = 0\n for file in self.file:\n self.folder = os.path.join(self.root_path, file)\n self.modified.append(time.ctime(os.path.getmtime(f\"{self.folder}\")))\n self.curr.append(time.ctime(os.path.getctime(f\"{self.folder}\")))\n for path, dirs, files in os.walk(self.folder):\n for file in files:\n file_path = os.path.join(path, file)\n total_size += os.path.getsize(file_path)\n self.size.append(total_size)\n return self.file, self.size, self.curr, self.modified\n\n def change_folder_path(self, old_name):\n \"\"\"\n To change a folder path we specify which folder to be changed\n It takes one arguments i.e,; the folder name.\n \"\"\"\n self.old_name = old_name\n self.curr = False\n os.chdir(self.root_path)\n try:\n os.chdir(old_name)\n self.curr = True\n except Exception:\n pass\n finally:\n return self.curr\nif __name__ == \"__main__\":\n testmod(name='TestServer', verbose=True)\n","sub_path":"Testserver.py","file_name":"Testserver.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112804064","text":"__author__ = 'student'\nimport timeit\n\n'''\nComplexity\n\nThe cost of solving problems\n\nTypically measure:\nTime: How much time, or number of steps needed to solve a problem\nSpace: Amount of memory needed to solve a problem\n\nCan look at a particular program P and ask what is\n\nT(n) = amount of time to solve a problem of size n\nS(n) = amount of space to solve a problem of size n\n\nCan ask the question, of a particular problem (ie sorting),\nis there a best time/amount of space to solve that problem.\n\nLets look at programs first, focusing on time\n'''\n\n# In what follows we use the following notation:\ndef f(n):\n # COST OF FUNCTION BODY = sum of top level costs below\n\n for i in range(n): # COST OF FOR LOOP = (number of times through loop)*(cost of body of loop)\n # COST OF BODY = sum of top level costs below\n\n # O(a) top level cost in body\n # O(b) top level cost in body\n # O(c) top level cost in body\n\n pass\n\n# A catalog of worst case time costs. You can be more accurate than\n# this if you understand the code well\n# a = b # O(1)\n# z[5] # O(1), for lists and dictionaries (if dictionaries are implemented well)\n# i = i + 2 * j - k # O(1) for any mathematical expression\n# j = f(k) # O(cost to execute f(k))\n# for ... # O(# of times loop executed)*O(cost of body)\n# u = s + t # O(len(s)+len(t)) for strings s and t, think about why\n# Example:\n\ndef string_example(n):\n s = \"a\"\n for i in range(n): # n * O(1) = O(n)\n s = s + s # O(len(s)+len(t))\n return s\n\n# while ... # O(# of times loop executed)*O(cost of body)\n# if ... else ... # O(worst case of two bodies)\n\ndef f1(n):\n # COST OF FUNCTION = O(1)\n\n return 7 # O(1)\n\ndef f2(n):\n # COST OF FUNCTION = O(1)+O(n)+O(1) = O(n)\n j = 0 # O(1)\n\n for k in range(100): # COST OF FOR LOOP = 100*O(n) = O(n)\n # COST OF BODY = O(n)\n for i in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n\n j = j + 1 # O(1)\n\n return j # O(1)\n\n\n'''\nselection_sort\nT(n) = O(n^2) where n = len(list)\n\ninsertion_sort\nT(n) = O(n^2) (in the worst case) where n = len(list)\n\nNote: In CS we consider\n1) best case running time,\n2) worst case running time\n3) average case running time.\n\nUsually focus on worst case to start comparing algorithms\n'''\n\ndef f3(l):\n # here n = len(l)\n # COST OF FUNCTION = O(1)+O(n)+O(1) = O(n)\n\n s = 0 # O(1)\n for e in l: # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n s = s + e # O(1)\n return s # O(1)\n\ndef f4(n):\n # COST OF FUNCTION = O(1)+O(n^2)+O(1) = O(n^2)\n\n s = 0 # O(1)\n for i in range(n): # COST OF FOR LOOP = n*O(n) = O(n^2)\n # COST OF BODY = O(n) + O(1) = O(n)\n for j in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n s = s + i + j # O(1)\n t = 77 # O(1)\n return s # O(1)\n\ndef f5(n):\n # COST OF FUNCTION = O(1)+O(n^2)+O(1)+O(n)+O(1) = O(n^2)\n\n s = 0 # O(1)\n for i in range(n): # COST OF FOR LOOP = n*O(n) = O(n^2)\n for j in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n s = s + i + j # O(1)\n\n t = 0 # O(1)\n for k in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)+O(1) = O(1)\n\n s = s + k # O(1)\n t = t + 1 # O(1)\n\n return s # O(1)\n\n\ndef f6(n):\n # COST OF FUNCTION = O(1)+O(n)+O(n)+O(1) = O(n)\n\n s = 0 # O(1)\n\n for i in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n for j in range(n): # COST OF FOR LOOP = 6*O(1) = O(1)\n # COST OF BODY = O(1)\n if j == 5: #O(1)\n break\n\n for k in range(n): # COST OF FOR LOOP = n*O(1) = O(n)\n # COST OF BODY = O(1)\n s = s + k # O(1)\n\n return s # O(1)\n\ndef f7(n):\n # COST OF FUNCTION = O(1)+O(1)+O(1)+O(1) = O(1)\n s = 0 # O(1)\n\n for i in range(n): # COST OF FOR LOOP = 17*O(1) = O(1)\n # COST OF BODY = O(1) + O(1) = O(1)\n\n for j in range(n): # COST OF FOR LOOP = 5*O(1) = O(1)\n # COST OF BODY = O(1)\n if j == 5: # O(1)\n break\n\n # COST OF BODY = O(1)\n if i>17: # O(1)\n break\n\n for k in range(n): # COST OF FOR LOOP = 6*O(1) = O(1)\n # COST OF BODY = O(1) + O(1)\n if k >4: # O(1)\n break # O(1)\n s = s + k # O(1)\n\n return s # O(1)\n\ndef f8(n):\n # COST OF FUNCTION = O(1)+O(n)+O(1) = O(n)\n i = 0 # O(1)\n while i=n: # O(1)\n # COST OF BODY = O(1) + O(1) + O(1) = O(1)\n i = 0 # O(1)\n j = j + 1 # O(1)\n if j>=n: # O(1)\n break # O(1)\n return i # O(1)\n\nfor f in f1, f2, f4:\n print(f.__name__)\n file = open(f.__name__+\".csv\", \"w\")\n for n in range(0,4000,100):\n start_time = timeit.default_timer()\n f(n)\n elapsed = timeit.default_timer() - start_time\n print(n)\n file.write(\"{0},{1}\\n\".format(n, elapsed))\n file.close()\n\n# all in one file\n'''\nfile = open(\"all.csv\", \"w\")\n# for n in range(0,3000,100):\nfor n in range(0,300,1):\n\n times = []\n for f in f1, f2, f4:\n start_time = timeit.default_timer()\n f(n)\n elapsed = timeit.default_timer() - start_time\n times.append(elapsed)\n file.write(\",\".join(map(str,times))+\"\\n\")\nfile.close()\n\n'''","sub_path":"CSC108/Week 12/Monday.py","file_name":"Monday.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307998217","text":"'''\nRead Images and Video\n'''\nimport os \nimport cv2 as cv\nimport numpy as np \n\nblank = np.zeros((400,400),dtype='uint8')\n\nrectangle=cv.rectangle(blank.copy(),(30,30),(370,370),255,-1)\ncircle=cv.circle(blank.copy(),(200,200),180,255,-1)\n\ncv.imshow('Rectangle',rectangle)\ncv.imshow('Circle',circle)\n\n# Bitwise And\nbitwise_and=cv.bitwise_and(rectangle,circle)\ncv.imshow('And',bitwise_and)\n\n# Bitwise Or\nbitwise_or=cv.bitwise_or(rectangle,circle)\ncv.imshow('Or',bitwise_or)\n\n# Bitwise NOT\nbitwise_not=cv.bitwise_not(rectangle)\ncv.imshow('Not',bitwise_not)\n\ncv.waitKey(0)","sub_path":"10 Bitwise.py","file_name":"10 Bitwise.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426514868","text":"from django.db import models\n\n\nclass Card(models.Model):\n card_id = models.AutoField(primary_key=True)\n card_name = models.CharField(max_length=200)\n card_set = models.ForeignKey(\"Set\", on_delete=models.DO_NOTHING)\n card_number = models.IntegerField()\n card_price = models.FloatField()\n\n\nclass Set(models.Model):\n set_id = models.AutoField(primary_key=True)\n set_name = models.CharField(max_length=200)\n set_cards = models.ManyToManyField(Card)\n\n\nclass Wishlist(models.Model):\n wishlist_id = models.AutoField(primary_key=True)\n wishlist_cards = models.ManyToManyField(\"Card\")\n\n\nclass Quantity(models.Model):\n collection = models.ForeignKey(\"Collection\", on_delete=models.CASCADE)\n card = models.ForeignKey(Card, on_delete=models.CASCADE)\n card_quantity = models.IntegerField()\n\n\nclass Collection(models.Model):\n collection_id = models.AutoField(primary_key=True)\n collection_name = models.CharField(max_length=200)\n collection_cards = models.ManyToManyField(Card, through=Quantity)\n collection_user = models.ForeignKey(\"User\", on_delete=models.CASCADE)\n\n\nclass User(models.Model):\n user_id = models.AutoField(primary_key=True)\n username = models.CharField(unique=True, max_length=64)\n auth_token = models.CharField(unique=True, max_length=200)\n last_online = models.DateTimeField()\n wishlist = models.OneToOneField(\n \"Wishlist\", on_delete=models.CASCADE)\n","sub_path":"price_api/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"183948855","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os\nimport sys\nimport CGIHTTPServer\nimport BaseHTTPServer\n\nimport cgitb; cgitb.enable()\n\n##\n## Handler for requests\n##\nclass Handler(CGIHTTPServer.CGIHTTPRequestHandler):\n cgi_directories = '/cgi'\n\n ##\n def do_GET(self):\n print('GET')\n\n self.curr_directory = os.path.dirname(os.path.realpath(__file__))\n\n response = ''\n \n dir = os.path.dirname(self.path)\n\n try:\n if dir == self.cgi_directories:\n CGIHTTPServer.CGIHTTPRequestHandler.do_GET(self)\n\n else:\n new_path = self.curr_directory\n dirs = ['html', 'css', 'js', '']\n \n query_start = self.path.find('?')\n formatted = self.path\n\n if query_start != -1:\n formatted = self.path[:query_start]\n\n for dir in dirs:\n full_path = new_path + '/' + dir + formatted\n \n try:\n page_type = 'text/html'\n if full_path.find('.css') != -1:\n page_type = 'text/css'\n\n file = open(full_path, 'rb')\n response += file.read()\n self.send_page(response, page_type) \n\n break\n except Exception as e:\n print('')\n\n except Exception as e:\n print(('error : %s' % str(e)))\n\n ##\n def do_POST(self):\n self.curr_directory = os.path.dirname(os.path.realpath(__file__))\n\n response = ''\n \n dir = os.path.dirname(self.path)\n \n try:\n if dir == self.cgi_directories:\n CGIHTTPServer.CGIHTTPRequestHandler.do_POST(self)\n\n except Exception as e:\n print(('error : %s' % str(e)))\n\n ##\n def send_page(self, content, content_type):\n self.send_response(200)\n self.send_header('Content-type', content_type)\n self.send_header('Content-length', str(len(content)))\n self.end_headers()\n self.wfile.write(content)\n\n##\n## Server\n##\nclass FileServer(BaseHTTPServer.HTTPServer):\n \n ##\n def __init__(self, server_address, request_handler_class):\n BaseHTTPServer.HTTPServer.__init__(self, server_address, request_handler_class)\n self.running = False\n\n ##\n def serve_stuff(self):\n self.running = True\n while True:\n self.handle_request()\n\n if self.running == False:\n break\n\n##\ndef main():\n httpd = FileServer(('', 8888), Handler)\n httpd.serve_stuff()\n\n##\nif __name__ == '__main__':\n main()\n","sub_path":"sketchfab/load_server.py","file_name":"load_server.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"214907749","text":"import sys\n\n# reload(sys)\n# sys.setdefaultencoding(\"utf-8\")\n\nsys.path.extend(['/home/caikun/PycharmProjects/codeExecutor'])\nsys.path.extend(['/home/caikun/PycharmProjects/codeExecutor/venv/lib/python3.7/site-packages'])\n\nfrom src.util.db.DBExecutor import DbUtils\n\ndbut = DbUtils(\"192.168.1.145\", \"work\", \"5Zp5wph2Ol1P\", \"pack_center\", port=3306)\n# dbut = DbUtils(\"mysql-cps.duoku.com\", \"pack_user\", \"!KmmBWN2Q1e^\", \"pack_center\", port=4051)\n\nif __name__ == '__main__':\n mother_list = dbut.fetch_list('''\n select app_id,frs,count(id) from pack_cloud_req \n where finish_status = '1'\n group by app_id,frs having count(id) > 1\n ''')\n for im1 in mother_list:\n tar_app_id = im1[0]\n tar_frs = im1[1]\n # print(str(tar_app_id) + \"|\" + tar_frs)\n dep_pack_detail = dbut.fetch_list('''\n select c.req_id from (select req_id,finish_time from pack_cloud_req where app_id = %d \n and frs = '%s' and finish_status = '1' order by finish_time desc) c limit 1,99\n ''' % (tar_app_id, tar_frs))\n if dep_pack_detail:\n for im2 in dep_pack_detail:\n # print(\"reqId=\" + str(im2[0]))\n dep_urls = dbut.fetch_list('''\n select url from pack_cloud_monitor_flow where req_id = %d \n ''' % im2[0])\n if dep_urls:\n for im3 in dep_urls:\n # baidu-mgame.com/\n md = str(im3[0]).split(\"myqcloud.com/\")\n if len(md) >= 2:\n print(\"%s #20210127# %s\" % (md[1], im2[0]))\n else:\n print(\"Err req:%d\" % im2[0])\n","sub_path":"src/util/db/clearPack.py","file_name":"clearPack.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605648372","text":"#辗转相除法(循环版本)\ndef Euclidean(a, b):\n c = a % b\n while c != 0:\n a = b\n b = c\n c = a % b\n \n return b\n\n\nprint(Euclidean(123456, 7890))\n\n\n#辗转相除法(递归版本)\ndef Euclidean2(a, b):\n if a % b == 0:\n return b\n \n return Euclidean2(b, a%b)\n \n\nprint(Euclidean2(123456, 7890))\n\n\n#更相减损术(循环版本)\ndef reduction(a, b):\n if a <= b:\n a, b = b, a\n \n c = a - b\n while c != b:\n if b < c:\n b, c = c, b\n a = b\n b = c\n c = a - b\n \n return c\n\nprint(reduction(123456, 7890))\n\n\n#更相减损术(递归版本)\ndef reduction2(a, b):\n if a <= b:\n a, b = b, a\n \n if a - b == b:\n return b\n \n return reduction2(b, a-b)\n\n\nprint(reduction2(123456, 7890))","sub_path":"gcd.py","file_name":"gcd.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140883600","text":"# Python program to demonstrate\n# Conversion of JSON data to\n# dictionary\n\n\n# importing the module\nimport json\n\n# Opening JSON file\nwith open('menucard.json') as json_file:\n\tdata = json.load(json_file)\n\n\t# Print the type of data variable\n\tprint(\"Type:\", type(data))\nprint(data)\n\t# Print the data of dictionary\n\t#print(\"\\nPeople1:\", data['people1'])\n\t#print(\"\\nPeople2:\", data['people2'])\n","sub_path":"data/json_load.py","file_name":"json_load.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"469866500","text":"#!/usr/bin/env python\nimport random, time, operator, logging, math\nimport tornado.ioloop\n# custom classes\nfrom imud_globals import G\nfrom imud_constants import Constant, AState, CState\nfrom imud_utility import coms\nfrom imud_combat import Combat\nfrom imud_ai_maze import MazeSolver\nimport imud_ascii as Ascii\n\nclass AI:\n def __init__(self, cm):\n self.cm = cm\n self.brain = tornado.ioloop.PeriodicCallback(self.AIBrain, 5 * 1000, io_loop = G.main_loop)\n self.brain.start()\n self.awake = False\n \n def addAgro(self, char, value=0, surprised=False):\n # add us to the monster's agro list\n logging.debug(\"AI; monster %s (%s); add agro; %s; %s\", self.cm.m.name, self.cm.uid, char.name, value)\n self.cm.agro[char.name if char.__class__.__name__ == 'char' else char.uid] = (self.cm.agro[char.name if char.__class__.__name__ == 'char' else char.uid] if (char.name if char.__class__.__name__ == 'char' else char.uid) in self.cm.agro else 0) + (random.randint(1, 10) if value == 0 else value)\n # check to see if they are a member of a group\n if char.group_id:\n # add the agro to the groups score too\n self.cm.gagro[char.group_id] = (self.cm.gagro[char.group_id] if char.group_id in self.cm.gagro else 0) + (random.randint(1, 10) if value == 0 else value)\n else:\n self.cm.gagro[char.name] = (self.cm.gagro[char.name] if char.name in self.cm.gagro else 0) + (random.randint(1, 10) if value == 0 else value)\n \n if self.awake == False and not surprised:\n # Make sure we are pissed at everyone hostile in the room, and wake us up\n self.addAgroRoom()\n self.wake(True)\n \n def addAgroRoom(self):\n found = False\n if len(G.chars):\n mx, my, mz = self.cm.loc\n for name, char in G.chars.iteritems():\n px, py, pz = char.loc\n if not char.isdead and \\\n char not in self.cm.agro and \\\n char.state > CState.OFFLINE and \\\n (self.cm.loc == char.loc or \\\n (self.cm.m.reach and Combat.isShootable(self.cm.loc, char.loc)[0])):\n for e in char.effects:\n if \"SYSINVIS\" in e.adjust:\n char.hideDC = 666\n break\n if char.hideDC == 0 or (char.hideDC <= self.cm.rollSkill(\"perception\", 5)):\n # TODO: if ranged, do we want to \n # check to see if we want to agro on this person based on level\n if math.fabs(self.cm.m.cr - char.level) > 7:\n continue\n elif self.cm.m.aifaction[1] == None and self.cm.m.aifaction[2] == None and self.cm.m.aifaction[3] == None and self.cm.m.aifaction[4] == None and self.cm.m.aifaction[5] == None:\n # we are hostile by default\n # as we add people, we want to roll random hate generated\n self.cm.agro[char.name] = random.randint(1, 10)\n found = True\n continue\n else:\n # loop through faction and see if we trigger an attack\n for i in self.cm.m.aifaction:\n faction = self.cm.m.aifaction[i]\n if faction != None and faction in G.factions:\n # special case, forced friendly\n if G.factions[faction].min == G.factions[faction].max and G.factions[faction].initial > 0:\n #friendly\n continue\n # special case, forced hostile\n # check live factions\n # our faction level <= 50% of the faction \n elif (G.factions[faction].min == G.factions[faction].max and G.factions[faction].initial <= 0) or \\\n ((char.faction[faction] if faction in char.faction else 0) + G.factions[faction].initial) <= ((G.factions[faction].max - G.factions[faction].min) / 2):\n self.cm.agro[char.name] = random.randint(1, 10)\n found = True\n break\n else:\n # friendly, move on to the next\n continue\n \n if len(G.monster_live) and True == False:\n mx, my, mz = self.cm.loc\n for uid, cm in G.monster_live.iteritems():\n cmx, cmy, cmz = cm.loc\n if not cm.isdead and cm != self.cm and cm.uid not in self.cm.agro and \\\n (self.cm.loc == cm.loc or (self.cm.m.reach and Combat.isShootable(self.cm.loc, cm.loc)[0])):\n # TODO: check to see if we want to agro on this monster\n #self.cm.agro[cm.uid] = random.randint(1, 10)\n break\n \n if found:\n self.wake()\n return found\n \n def removeAgro(self, char, value=0):\n logging.debug(\"AI; remove agro; %s; %s\", char.name, value)\n if value == 0:\n if (char.name if char.name in G.chars else char.uid) in self.cm.agro:\n del self.cm.agro[char.name if char.name in G.chars else char.uid]\n if self.cm.target == (char.name if char.name in G.chars else char.uid):\n self.cm.target = None\n else:\n self.cm.agro[char.name if char.name in G.chars else char.uid] = (self.cm.agro[char.name if char.name in G.chars else char.uid] if (char.name if char.name in G.chars else char.uid) in self.cm.agro else 0) - value\n \n def wake(self, now=True):\n self.brain.stop()\n # set the thought speed based on ING and DEX average\n # TODO: eventually create a seperate brain speed db column\n old_max = 40\n old_min = -10\n new_max = 0.1\n new_min = 9\n val = (self.cm.m.stat[\"ING\"] + self.cm.m.stat[\"DEX\"]) / 2\n NewValue = (((val - old_min) * (new_max - new_min)) / (old_max - old_min)) + new_min\n logging.debug(\"AI; monster %s (%s); wake; poll speed %s\", self.cm.m.name, self.cm.uid, NewValue)\n self.brain = tornado.ioloop.PeriodicCallback(self.AIBrain, NewValue * 1000, io_loop = G.main_loop)\n self.brain.start() # think faster!\n self.awake = True\n if now:\n self.AIBrain() # call us right away\n \n def sleep(self):\n self.cm.srounds = 0\n self.cm.incombat = False\n self.cm.engaged = False\n self.cm.target = None\n self.cm.agro = {}\n #reset our brain\n self.awake = False\n self.brain.stop()\n self.brain = tornado.ioloop.PeriodicCallback(self.AIBrain, 5 * 1000, io_loop = G.main_loop)\n logging.debug(\"AI; monster %s (%s); sleeping\", self.cm.m.name, self.cm.uid)\n if not self.cm.isdead:\n self.brain.start() # think slower\n self.AIBrain() # call us right away\n \n def RoomMessage(self, data, loc, exclude=[], chat = False, DC = None):\n #coms.sendRoom(loc, data, exclude, False)\n for name, avatar in G.avatars.iteritems():\n if avatar not in exclude and avatar.char and avatar.char.loc == loc and (not DC or (avatar.char and avatar.char.rollSkill(\"perception\") >= DC)):\n avatar.protocol.sendLine(data, chat)\n \n def DirectMessage(self, data, char, crlf = True):\n char.avatar.protocol.sendLine(data)\n\n def DoMove(self, args, chase = False):\n dir, target = args\n cm = self.cm\n # clear any prelearned directions if we had a target\n if target and cm.dir:\n logging.debug(\"AI; monster %s (%s); found %s; clearing directions\", cm.m.name, cm.uid, target)\n cm.dir = None\n ax, ay, az = Constant.directions[dir.lower()]\n mx, my, mz = cm.loc\n if G.rooms[(mx + ax, my + ay, mz + az)].areaid != cm.area:\n logging.debug(\"AI; Out-Of-Bounds; %s; %s\", cm.area, G.rooms[(mx + ax, my + ay, mz + az)].areaid)\n return False\n self.RoomMessage(\"%s %s %s %s to the %s.\" % (cm.dsc, cm.pname, cm.m.name, (\"chases %s\" % (target.name,)) if target else \"left\", dir.lower()), cm.loc)\n # TODO: Send you hear movement message to users who make a perception roll\n for name, char in G.chars.iteritems():\n if (chase and target == char) or char.state < CState.ONLINE:\n continue\n # check to see if we notice them entering the room\n # TODO: check to see if we make a sound in the room first, if we do alert nearby rooms too\n sx, sy, sz = cm.loc\n ex, ey, ez = char.loc\n # loop through the directions and see if we are within ear shot\n for dir2, xloc in Constant.sdirections.iteritems():\n xx, xy, xz = xloc\n if (sx + xx == ex and sy + xy == ey and sz + xz == ez) and (G.rooms[(sx,sy,sz)].exit[dir2] > 0):\n char.avatar.protocol.sendLine(\"You sense movement %s.\" % (Constant.invert[Constant.tolong[dir2] if dir2 not in (\"u\", \"d\") else Constant.zdesc[dir2]].title(), ))\n break\n cm.loc = (mx + ax, my + ay, mz + az)\n if dir.lower() in Constant.invert:\n dir = Constant.invert[dir.lower()]\n self.RoomMessage(\"%s %s %s enters the room from %s%s%s.\" % (cm.dsc, cm.pname, cm.m.name, \"\" if dir == \"above\" or dir == \"below\" else \"the \", dir, (\", chasing %s\" % (target.name,)) if target else \"\"), cm.loc)\n logging.debug(\"AI; monster %s (%s); move; %s\", cm.name, cm.uid, Constant.invert[dir.lower()])\n return True\n \n def DoSpell(self, s, chance):\n cast = False\n roll = random.randint(1,100)\n if roll <= int(float(chance) * 100):\n sp = G.spells[int(s)]\n target = (G.chars[self.cm.target] if self.cm.target in G.chars else G.monster_live[self.cm.target])\n if sp.stype == \"heal\" and (self.cm.calcStatNow(\"LP\") / self.cm.calcStat(\"LP\")) * 100 <= random.randint(20, 40):\n cast = True\n target = self.cm\n if (sp.stype == \"attack\" or sp.stype == \"debuff\") and self.cm.target and target.loc == self.cm.loc:\n cast = True\n \n if cast:\n self.cm.action = True\n logging.debug(\"AI; monster %s (%s); casting; %s; targeting; %s\", self.cm.m.name, self.cm.uid, sp.name, target.name)\n Combat.doSpell(self.cm, target, sp, \"\")\n \n def AIBrain(self):\n startt = time.time()\n cm = self.cm\n # adjust our think time depending if we have agro until we no longer have agro\n # check if there are people in the room with us\n # if we are ranged check if there are people within range\n if self.cm.isdead: ##### Dead (5 second think time)\n # we are dead, put us to sleep\n self.sleep()\n else: ##### AGRO CHECK\n if not self.cm.agro:\n self.addAgroRoom()\n \n agro = {}\n # sort a list of targets, apply our modifier and choose the highest on my list\n for target, value in cm.agro.iteritems():\n # treat things in the room with us as 150% agro\n agro[target] = (value * 1.5) if (G.chars[target].loc if target in G.chars else G.monster_live[target].loc) == cm.loc else value\n \n agros = sorted(agro.iteritems(), key=operator.itemgetter(1))\n ##### Check to see if we want to move\n if not len(agros) and not self.cm.dir and (random.randint(1,100) <= int(self.cm.wander * 100)):\n # wander\n dirs = []\n for dir in G.rooms[self.cm.loc].exit:\n if G.rooms[self.cm.loc].exit[dir] == 1:\n dirs.append(dir)\n if dirs:\n random.shuffle(dirs)\n dir = dirs.pop()\n self.DoMove((Constant.tolong[dir], None))\n acted = False\n while not acted and len(agros):\n target, value = agros.pop()\n target = (G.chars[target] if target in G.chars else G.monster_live[target])\n if target.isdead or target.state == CState.OFFLINE:\n logging.debug(\"AI; monster %s (%s); target; %s; dead or offline\", cm.m.name, cm.uid, target.name)\n continue\n else:\n for e in target.effects:\n if \"SYSINVIS\" in e.adjust:\n char.hideDC = 666\n break\n if target.hideDC == 0 or (target.hideDC <= self.cm.rollSkill(\"perception\", 5)):\n logging.debug(\"AI; monster %s (%s); target; %s; in combat; %s\", cm.m.name, cm.uid, target.name, cm.incombat)\n else:\n logging.debug(\"AI; monster %s (%s); target; %s; in combat; %s; target hidden\", cm.m.name, cm.uid, target.name, cm.incombat)\n continue\n \n if target.name in G.chars or target.uid in G.monster_live:\n # check rooms\n mx, my, mz = cm.loc\n px, py, pz = target.loc\n \n for dir, add in Constant.sdirections.iteritems():\n if (cm.loc == target.loc):\n if cm.target != (target.name if target.__class__.__name__ == 'char' else target.uid) or not cm.incombat:\n ##### Target this player\n cm.target = (target.name if target.__class__.__name__ == 'char' else target.uid)\n cm.incombat = True\n cm.engaged = True\n cm.cround = G.round\n target.incombat = True\n target.avatar.protocol.sendStat.combat(target.avatar.protocol, True)\n if not target.target:\n target.target = cm.uid\n target.cround = G.round \n # send a moves to attack message to the room\n logging.debug(\"AI; monster %s (%s); attacking; %s\", cm.m.name, cm.uid, target.name)\n self.RoomMessage(\"%s %s %s moves to attack %s!\" % (cm.dsc, cm.pname, cm.m.name, target.name), cm.loc, (target.avatar,))\n self.DirectMessage(\"%s %s %s moves to attack you!\" % (cm.dsc, cm.pname, cm.m.name), target)\n # parse spells\n for chance, s in cm.m.spells:\n self.DoSpell(s, chance)\n acted = True\n break\n ax, ay, az = add\n if G.rooms[cm.loc].exit[dir] and ((mx+ax == px and my+ay == py and mz+az == pz)) and G.rooms[(mx+ax,my+ay,mz+az)].areaid == cm.area:\n # Don't move if you are ranged\n if not cm.m.reach:\n logging.debug(\"AI; monster %s (%s); found target; %s; adjacent room %s; moving\", cm.m.name, cm.uid, target.name, Constant.tolong[dir])\n acted = self.DoMove((Constant.tolong[dir], target))\n else:\n logging.debug(\"AI; monster %s (%s); found target; %s; adjacent room %s; reach; %s\", cm.m.name, cm.uid, target.name, Constant.tolong[dir], cm.m.reach)\n if (not cm.target or not cm.target == target.name or not cm.incombat):\n acted = True\n # target this player from a range\n cm.target = target.name\n cm.incombat = True\n cm.engaged = True\n cm.cround = G.round\n target.cround = G.round \n target.incombat = True\n target.avatar.protocol.sendStat.combat(target.avatar.protocol, True)\n if not target.target:\n target.target = cm.uid\n # send a moves to attack message to the room\n logging.debug(\"AI; monster %s (%s); attacking ranged; %s; %s\", cm.m.name, cm.uid, Constant.tolong[dir].title(), target.name)\n dsc = \"an\" if (cm.pname and cm.pname[0].lower() in Constant.vowels) else \"a\"\n self.RoomMessage(\"%s %s %s moves to attack %s, to the %s!\" % (dsc, cm.pname, cm.m.name, target.name, Constant.tolong[dir].title()), cm.loc, (target.avatar,))\n self.DirectMessage(\"%s %s %s moves to attack you, from the %s!\" % (dsc, cm.pname, cm.m.name, Constant.invert(Constant.tolong[dir])), target)\n # parse spells\n for s, chance in cm.m.spells:\n self.DoSpell(s, chance)\n break\n # try to follow their tracks (we need to be smart to track)\n else:\n if G.tracks.has_key(cm.loc):\n for name, dir, round in G.tracks[cm.loc]:\n if name == target.name:\n # DC is 5 * rounds old\n # basic track score is d10 + (ING * 2) so -2 is 6 (1 round) and +5 is 20 (3 rounds)\n if int(random.randint(1, 10) + (cm.m.stat[\"ING\"] * 2)) >= int((G.round - round) * 5):\n # found you bitch\n logging.debug(\"AI; monster %s (%s); following tracks; %s; %s\", cm.m.name, cm.uid, dir, target.name)\n acted = self.DoMove((dir, target))\n break\n else:\n logging.debug(\"AI; monster %s (%s); lost trail; %s\", cm.m.name, cm.uid, target.name)\n \n if acted:\n break\n\n if not acted and not cm.incombat and self.awake:\n if cm.srounds < 2:\n cm.srounds += 1\n logging.debug(\"AI; We didn't act, strike %s\", cm.srounds)\n else:\n # umm, I lost the trail\n # are we at home?\n if not cm.loc == cm.sloc:\n # start walking back home\n if not cm.dir:\n mstartt = time.time()\n maze = {}\n for key, r in G.rooms.iteritems():\n if r.areaid == G.rooms[cm.sloc].areaid:\n maze[key] = r\n ms = MazeSolver(maze)\n solved_maze = ms.Astar(cm.loc, cm.sloc)\n cm.dir = solved_maze\n mendt = time.time()\n logging.debug(\"AI; Calculated directions home in %.6f seconds; %s\", (mendt - mstartt), solved_maze)\n dir = cm.dir.pop(0)\n self.DoMove((dir, None))\n else:\n logging.debug(\"AI; Directions left; %s\", cm.dir)\n dir = cm.dir.pop(0)\n self.DoMove((dir, None))\n else:\n if self.awake == True:\n #reset us\n self.cm.reset()\n self.sleep()\n # we reset and we were forced spawned, destroy us\n if not self.cm.spawn_chance:\n self.cm.isdead = True\n coms.sendRoom(self.cm.loc, self.cm.m.message[\"death\"].text % (self.cm.name,))\n else:\n cm.srounds = 0 #reset our idle rounds","sub_path":"imud_ai.py","file_name":"imud_ai.py","file_ext":"py","file_size_in_byte":20958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"221733908","text":"# =============================================================================\n# @author: Shuo Zhou, The University of Sheffield\n# =============================================================================\n\nimport numpy as np\nfrom scipy.linalg import eig\nfrom numpy.linalg import multi_dot\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics.pairwise import pairwise_kernels\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.neighbors import kneighbors_graph\n# =============================================================================\n# Transfer Component Analysis: TCA\n# Ref: S. J. Pan, I. W. Tsang, J. T. Kwok and Q. Yang, \"Domain Adaptation via \n# Transfer Component Analysis,\" in IEEE Transactions on Neural Networks, \n# vol. 22, no. 2, pp. 199-210, Feb. 2011.\n# =============================================================================\n\ndef get_L(ns, nt):\n '''\n Get kernel weight matrix\n Parameters:\n ns: source domain sample size\n nt: target domain sample size\n Return: \n Kernel weight matrix L\n '''\n a = 1.0 / (ns * np.ones((ns, 1)))\n b = -1.0 / (nt * np.ones((nt, 1)))\n e = np.vstack((a, b))\n L = np.dot(e, e.T)\n return L\n\ndef get_kernel(X, Y=None, kernel = 'linear', **kwargs):\n '''\n Generate kernel matrix\n Parameters:\n X: X matrix (n1,d)\n Y: Y matrix (n2,d)\n Return: \n Kernel matrix\n '''\n\n return pairwise_kernels(X, Y=Y, metric = kernel, \n filter_params = True, **kwargs)\n \ndef get_lapmat(X, k = 5):\n n = X.shape[0]\n knn_graph = kneighbors_graph(X, n_neighbors = k).toarray()\n knn_mat = np.zeros((n, n))\n knn_mat[np.logical_or(knn_graph, knn_graph.T)] = 1\n D = np.diag(np.sum(knn_mat, axis = 1))\n return D - knn_mat\n\nclass TCA(BaseEstimator, TransformerMixin):\n def __init__(self, n_components, kernel='linear', lambda_=1, mu = 1, gamma = 0.5, k = 5, **kwargs):\n '''\n Init function\n Parameters\n n_components: n_componentss after tca (n_components <= d)\n kernel: 'rbf' | 'linear' | 'poly' (default is 'linear')\n lambda_: regulization param\n mu: KNN graph param\n k: number of nearest neighbour for KNN graph\n gamma: label dependence param\n '''\n self.n_components = n_components\n self.kwargs = kwargs\n self.kernel = kernel\n self.lambda_ = lambda_ \n self.mu = mu\n self.gamma = gamma\n self.k = k\n\n def fit(self, Xs, Xt, ys = None, yt = None, **kwargs):\n '''\n Parameters:\n Xs: Source domain data, array-like, shape (ns_samples, n_feautres)\n Xt: Target domain data, array-like, shape (nt_samples, n_feautres)\n ys: Source domain labels, array-like, shape (ns_samples,)\n yt: Target domain labels, array-like, shape (nt_samples,)\n Note:\n Unsupervised TCA is performed if ys and yt are not given.\n Semi-supervised TCA is performed is ys and yt are given.\n '''\n self.ns = Xs.shape[0]\n self.nt = Xt.shape[0]\n n = self.ns + self.nt\n X = np.vstack((Xs, Xt))\n L = get_L(self.ns, self.nt)\n L[np.isnan(L)] = 0\n K = get_kernel(X, kernel = self.kernel, **self.kwargs)\n K[np.isnan(K)] = 0\n \n I = np.eye(n)\n H = I - 1. / n * np.ones((n, n))\n\n if ys is not None and yt is not None:\n y = np.concatenate((ys, yt)) \n y = y.reshape((n,1))\n Kyy = self.gamma * np.dot(y, y.T) + (1-self.gamma) * I\n Lap_ = get_lapmat(K, k =self.k)\n obj = multi_dot([K, (L+ self.mu * Lap_), K.T]) + self.lambda_ * I\n st = multi_dot([K, H, Kyy, H, K.T])\n #obj = np.trace(np.dot(K,L)) \n else: \n obj = multi_dot([K, L, K.T]) + self.lambda_ * I\n st = multi_dot([K, H, K.T])\n eig_vals, eig_vecs = eig(obj, st)\n \n# ev_abs = np.array(list(map(lambda item: np.abs(item), eig_vals)))\n# idx_sorted = np.argsort(ev_abs)\n idx_sorted = eig_vals.argsort()\n\n \n self.eig_vals = eig_vals[idx_sorted]\n self.U = eig_vecs[:, idx_sorted]\n self.U = np.asarray(self.U, dtype = np.float)\n# self.components_ = np.dot(X.T, U)\n# self.components_ = self.components_.T\n\n self.Xs = Xs\n self.Xt = Xt\n return self\n\n def transform(self, X):\n '''\n Parameters:\n X: array-like, shape (n_samples, n_feautres)\n Return:\n tranformed data\n '''\n check_is_fitted(self, 'Xs')\n check_is_fitted(self, 'Xt')\n X_fit = np.vstack((self.Xs, self.Xt))\n K = get_kernel(X, X_fit, kernel = self.kernel, **self.kwargs)\n U_ = self.U[:,:self.n_components]\n X_transformed = np.dot(K, U_)\n return X_transformed\n\n\n def fit_transform(self, Xs, Xt, ys=None, yt=None):\n '''\n Parameters:\n Xs: Source domain data, array-like, shape (n_samples, n_feautres)\n Xt: Target domain data, array-like, shape (n_samples, n_feautres)\n Return:\n tranformed Xs_transformed, Xt_transformed\n '''\n self.fit(Xs, Xt, ys, yt)\n Xs_transformed = self.transform(Xs)\n Xt_transformed = self.transform(Xt)\n return Xs_transformed, Xt_transformed","sub_path":"feature_learning/tca.py","file_name":"tca.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"384409534","text":"\"\"\"\nSimulation of circating clock\n\"\"\"\n\ncompile_flags = '-Wall -O2 '\nlink_flags = ''\nif ARGUMENTS.get('profiling', 0):\n\tcompile_flags += '-pg'\n\tlink_flags += '-pg'\nelif ARGUMENTS.get('debug', 0):\n\tcompile_flags += '-g'\nelif ARGUMENTS.get('memtrack', 0):\n\tcompile_flags += '-D MEMTRACK'\n\nenv = Environment(CXX='g++')\nenv.Append(CXXFLAGS=compile_flags, LINKFLAGS=link_flags)\nenv.Program(target='simulation', source=['source/main.cpp','source/init.cpp','source/sim.cpp', 'source/io.cpp', 'source/memory.cpp', 'source/debug.cpp', 'source/kftest.cpp', 'source/calculation.cpp'])\n","sub_path":"simulation/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"79511465","text":"from django.views import View\nfrom users.models import User\nfrom users.model.list import Subscribe\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom logs.models import UserWorkerLog, UserManageCreatorLog\n\n\nclass UserBanCreate(View):\n def get(self,request,*args,**kwargs):\n self.user = User.objects.get(pk=self.kwargs[\"pk\"])\n request.user.block_user_with_pk(self.user.pk)\n return HttpResponse('')\n\n\nclass UserUnbanCreate(View):\n def get(self,request,*args,**kwargs):\n self.user = User.objects.get(pk=self.kwargs[\"pk\"])\n request.user.unblock_user_with_pk(self.user.pk)\n return HttpResponse('')\n\n\nclass UserAdView(View):\n def get(self,request,*args,**kwargs):\n from stst.models import AdNumbers\n\n if request.user.is_authenticated:\n pk = self.kwargs[\"pk\"]\n try:\n obj = AdNumbers.objects.get(user=request.user.pk, ad=pk)\n return HttpResponse('')\n except:\n obj = AdNumbers.objects.create(user=request.user.pk, ad=pk)\n return HttpResponse('')\n else:\n return HttpResponse('')\n\n\nclass PhoneVerify(View):\n def get(self,request,*args,**kwargs):\n from common.model.other import PhoneCodes\n from users.models import User\n\n code = self.kwargs[\"code\"]\n _phone = self.kwargs[\"phone\"]\n phone = request.user.get_last_location().phone + _phone\n try:\n obj = PhoneCodes.objects.get(code=code, phone=phone)\n except:\n obj = None\n if obj:\n user = User.objects.get(pk=request.user.pk)\n user.is_phone_verified=True\n user.phone=obj.phone\n user.save()\n obj.delete()\n data = 'ok'\n response = render(request,'generic/response/phone.html',{'response_text':data})\n return response\n else:\n data = 'Код подтверждения неверный. Проверьте, пожалуйста, номер, с которого мы Вам звонили. Последние 4 цифры этого номера и есть код подтверждения, который нужно ввести с поле \"Последние 4 цифры\". Если не можете найти номер, нажмите на кнопку \"Перезвонить повторно\".'\n response = render(request,'generic/response/phone.html',{'response_text':data})\n return response\n\n\nclass PhoneSend(View):\n def get(self,request,*args,**kwargs):\n import json, requests\n from common.model.other import PhoneCodes\n from users.models import User\n\n text = \"\"\n if request.user.is_phone_verified:\n return HttpResponse(\"\")\n else:\n _phone = self.kwargs[\"phone\"]\n if len(_phone) > 8:\n phone = request.user.get_last_location().phone + _phone\n try:\n user = User.objects.get(phone=phone)\n data = 'Пользователь с таким номером уже зарегистрирован. Используйте другой номер или напишите в службу поддержки, если этот номер Вы не использовали ранее.'\n response = render(request,'generic/response/phone.html',{'response_text':data})\n return response\n except:\n response = requests.get(url=\"https://api.ucaller.ru/v1.0/initCall?service_id=12203&key=GhfrKn0XKAmA1oVnyEzOnMI5uBnFN4ck&phone=\" + phone)\n data = response.json()\n PhoneCodes.objects.create(phone=phone, code=data['code'])\n data = 'Мы Вам звоним. Последние 4 цифры нашего номера - код подтверждения, который нужно ввести в поле \"Последние 4 цифры\" и нажать \"Подтвердить\"'\n response = render(request,'generic/response/code_send.html',{'response_text':data})\n return response\n else:\n data = 'Введите, пожалуйста, корректное количество цифр Вашего телефона'\n response = render(request,'generic/response/phone.html',{'response_text':data})\n return response\n\n\nclass AddSubscribe(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user != user and not request.user.is_blocked_with_user_with_id(user_id=user.pk):\n Subscribe.objects.create(adding_user=request.user, added_user=user)\n return HttpResponse('')\n else:\n return HttpResponse('')\n\n\nclass UnSubscribe(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n try:\n subscribe = Subscribe.objects.get(adding_user=request.user, added_user=user)\n subscribe.delete()\n return HttpResponse('')\n except:\n return HttpResponse('')\n\n\nclass UserAdminCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_administrator:\n user.add_user_administrator()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Добавлен админ пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserAdminDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_administrator:\n user.remove_user_administrator()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Удален админ пользователей')\n return HttpResponse(\"\")\n\n\nclass UserModerCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_moderator:\n user.add_user_moderator()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Добавлен модератор пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserModerDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_moderator:\n user.remove_user_moderator()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Удален модератор пользователей')\n return HttpResponse(\"\")\n\n\nclass UserEditorCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_editor:\n user.add_user_editor()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Добавлен редактор пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserEditorDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_editor:\n user.remove_user_editor()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Удален редактор пользователей')\n return HttpResponse(\"\")\n\n\nclass UserAdvertiserCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_advertiser:\n user.add_user_advertiser()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Добавлен рекламодатель пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserAdvertiserDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser and request.user.is_can_work_ad_advertiser:\n user.remove_user_advertiser()\n UserWorkerLog.objects.create(manager=request.user, user=user, action_type='Удален рекламодатель пользователей')\n return HttpResponse(\"\")\n\n\n\nclass UserWorkerAdminCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.add_user_administrator_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Добавлен создатель админов пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserWorkerAdminDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.remove_user_administrator_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Удален создатель админов пользователей')\n return HttpResponse(\"\")\n\n\nclass UserWorkerModerCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.add_user_moderator_worker()\n return HttpResponse(\"\")\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Добавлен создатель модераторов пользователей')\n else:\n return HttpResponse(\"\")\n\nclass UserWorkerModerDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.remove_user_moderator_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Удален создатель модераторов пользователей')\n return HttpResponse(\"\")\n\n\nclass UserWorkerEditorCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.add_user_editor_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Добавлен создатель редакторов пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserWorkerEditorDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.remove_user_editor_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Удален создатель редакторов пользователей')\n return HttpResponse(\"\")\n\n\nclass UserWorkerAdvertiserCreate(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.add_user_advertiser_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Добавлен создатель рекламодателей пользователей')\n return HttpResponse(\"\")\n else:\n return HttpResponse(\"\")\n\nclass UserWorkerAdvertiserDelete(View):\n def get(self,request,*args,**kwargs):\n user = User.objects.get(pk=self.kwargs[\"pk\"])\n if request.user.is_superuser:\n user.remove_user_advertiser_worker()\n UserManageCreatorLog.objects.create(manager=request.user, user=user, action_type='Удален создатель рекламодателей пользователей')\n return HttpResponse(\"\")\n","sub_path":"users/view/progs.py","file_name":"progs.py","file_ext":"py","file_size_in_byte":12605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575723183","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 10 12:20:59 2016\n\n@author: Jonathan\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\ndef linearFit(x, a, b):\n return a * x + b\n#%%\ndef autokorrFit(x, a, invw, x0):\n return a*((invw*(x-x0) - 1)*np.exp(4*invw*(x-x0)) + ( (x-x0)*invw+1)*np.exp(2*(x-x0)*invw) )/(np.exp(2*(x-x0)*invw-1)-1)**3\n\n\nautokorrFit(DL, *p0)\n#%%\nIL, PL = np.genfromtxt(\"./measurements/5_pi_qs_ml.csv\", delimiter=',',\n usecols=(0,1), skip_header=1, unpack=True)\nIL2, UO = np.genfromtxt(\"./measurements/6_freq_pulse_amplitude.csv\", delimiter=',',\n usecols=(0,1), skip_header=1, unpack=True)\nIL3, PL3 = np.genfromtxt(\"./measurements/5_pi_qs_ml.csv\", delimiter=',',\n usecols=(0,1), skip_header=1, skip_footer=18, unpack=True)\n\n\nfig = plt.figure()\nplt.title('Hauptlaser gepulster Betrieb')\nax = fig.add_subplot(111)\nax.plot(IL, PL, '.')\nax2 = ax.twinx()\nax2.plot(IL2, UO, '.')\nax.set_xlabel(\"Punpstrom in mA\")\nax.set_ylabel(\"Leistung in mW\")\nax2.set_ylabel(\"Spannung in mV\")\nax.errorbar(IL, PL, xerr=10, yerr=1, fmt='ro')\nax2.errorbar(IL2, UO, xerr=10, yerr=10, fmt='bs')\n\n#%%\nplt.figure()\n\nparameters = curve_fit(linearFit, IL3, PL3)\n[a, b] = parameters[0]\nx1 = np.arange(0, 3000, 500)\nplt.plot(IL, PL, '.')\nplt.title('Schwellenstrom')\nplt.xlabel(\"Punpstrom in mA\")\nplt.ylabel(\"Leistung in mW\")\nFit1 = plt.plot(x1, a*x1+b, label='Schwellenstrom=725.17 mA')\nplt.legend(loc='upper left')\n\n#%%\nplt.figure()\np0=[]\nDL, AM = np.genfromtxt(\"./measurements/11_auto_correlation.csv\", delimiter=',',\n usecols=(0,1), skip_header=1, skip_footer=2, unpack=True)\n#parameters2 = curve_fit(autokorrFit, DL, AM)\n#[a2, b2] = parameters2[0]\np0=[170, -1, 1.5]\nx2 = np.arange(0.2, 3.4, 0.2)\nplt.plot(DL, AM, '.')\nplt.plot(DL, autokorrFit(DL, *p0))\n#Fit2 = plt.plot(x2, 16*(a2*x2+b2-1)*np.exp(4*(a2*x2+b2)+(a2*x2+b2+1)*np.exp(2*(a2*x2+b2)))/((np.exp(2*(a2*x2+b2))-1)**3))\nplt.show()","sub_path":"Pythoncode_Jojo.py","file_name":"Pythoncode_Jojo.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"615302748","text":"# -*- coding: utf-8 -*-\n\n# logging\nLOGGING_JSON = 'logging.json'\nTARGET_HANDLERS = ['console', ]\n\n# flask config\nCONFIG_CFG = 'config.cfg'\nDEFAULT_ORION_ENDPOINT = 'DEFAULT_ORION_ENDPOINT'\nDEFAULT_PORT = 'DEFAULT_PORT'\nDEFAULT_BEARER_AUTH = 'DEFAULT_BEARER_AUTH'\n\n# environment variable name\nLOG_LEVEL = 'LOG_LEVEL'\nLISTEN_PORT = 'LISTEN_PORT'\nBEARER_AUTH = 'BEARER_AUTH'\nPREFIX = 'PREFIX'\nMONGODB_ENDPOINT = 'MONGODB_ENDPOINT'\nMONGODB_REPLICASET = 'MONGODB_REPLICASET'\nMONGODB_DATABASE = 'MONGODB_DATABASE'\nMONGODB_COLLECTION = 'MONGODB_COLLECTION'\nCYGNUS_MONGO_ATTR_PERSISTENCE = 'CYGNUS_MONGO_ATTR_PERSISTENCE'\n","sub_path":"app/src/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"36246194","text":"import os\nfrom time import sleep\n\nfrom client.arduino import Arduino\nfrom client.camera_stream import CameraStream\nfrom client.client import Client\n\nif __name__ == '__main__':\n # Read configuration details from environment\n host = os.getenv('HOST', 'localhost')\n port = int(os.getenv('PORT', '1234'))\n\n gst_port = int(os.getenv('GST_PORT', '5000'))\n arduino_port = os.getenv('ARDUINO_PORT')\n\n # Initialize Arduino connection and video stream\n arduino = Arduino(arduino_port)\n camera_stream = CameraStream(host, gst_port)\n arduino.connect()\n camera_stream.set_source(0)\n\n # Create and run client\n client = Client(host, port, arduino, camera_stream)\n while True:\n client.connect_and_run()\n sleep(client.reconnect_delay)\n","sub_path":"client/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"252147708","text":"# Copyright 2017, OpenCensus Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport mock\nfrom django.test import RequestFactory\nfrom django.test.utils import teardown_test_environment\n\nfrom opencensus.trace import execution_context\nfrom opencensus.trace import span as span_module\nfrom opencensus.trace.exporters import print_exporter\nfrom opencensus.trace.exporters import zipkin_exporter\nfrom opencensus.trace.exporters.ocagent import trace_exporter\nfrom opencensus.trace.exporters.transports import sync\nfrom opencensus.trace.ext import utils\nfrom opencensus.trace.propagation import google_cloud_format\nfrom opencensus.trace.samplers import always_on\nfrom opencensus.trace.samplers import probability\nfrom opencensus.trace.blank_span import BlankSpan\n\n\nclass TestOpencensusMiddleware(unittest.TestCase):\n\n def setUp(self):\n from django.conf import settings as django_settings\n from django.test.utils import setup_test_environment\n\n if not django_settings.configured:\n django_settings.configure()\n setup_test_environment()\n\n def tearDown(self):\n execution_context.clear()\n teardown_test_environment()\n\n def test_constructor_cloud(self):\n from opencensus.trace.ext.django import middleware\n\n class MockCloudExporter(object):\n def __init__(self, project_id, transport):\n self.project_id = project_id\n self.transport = transport\n\n MockCloudExporter.__name__ = 'GoogleCloudExporter'\n\n project_id = 'my_project'\n params = {\n 'GCP_EXPORTER_PROJECT': project_id,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params', params)\n patch_exporter = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n MockCloudExporter)\n\n with patch_params, patch_exporter:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertIs(middleware._sampler, always_on.AlwaysOnSampler)\n self.assertIs(\n middleware._exporter, MockCloudExporter)\n self.assertIs(\n middleware._propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n assert isinstance(middleware.sampler, always_on.AlwaysOnSampler)\n assert isinstance(\n middleware.exporter, MockCloudExporter)\n assert isinstance(\n middleware.propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n self.assertEqual(middleware.exporter.project_id, project_id)\n self.assertEqual(middleware.exporter.transport, sync.SyncTransport)\n\n def test_constructor_zipkin(self):\n from opencensus.trace.ext.django import middleware\n\n service_name = 'test_service'\n host_name = 'test_hostname'\n port = 2333\n protocol = 'http'\n params = {\n 'ZIPKIN_EXPORTER_SERVICE_NAME': service_name,\n 'ZIPKIN_EXPORTER_HOST_NAME': host_name,\n 'ZIPKIN_EXPORTER_PORT': port,\n 'ZIPKIN_EXPORTER_PROTOCOL': protocol,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_zipkin = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n zipkin_exporter.ZipkinExporter)\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params',\n params)\n\n with patch_zipkin, patch_params:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertIs(middleware._sampler, always_on.AlwaysOnSampler)\n self.assertIs(\n middleware._exporter, zipkin_exporter.ZipkinExporter)\n self.assertIs(\n middleware._propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n assert isinstance(middleware.sampler, always_on.AlwaysOnSampler)\n assert isinstance(\n middleware.exporter, zipkin_exporter.ZipkinExporter)\n assert isinstance(\n middleware.propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n self.assertEqual(middleware.exporter.service_name, service_name)\n self.assertEqual(middleware.exporter.host_name, host_name)\n self.assertEqual(middleware.exporter.port, port)\n\n def test_constructor_zipkin_service_name_param(self):\n from opencensus.trace.ext.django import middleware\n\n service_name = 'test_service'\n host_name = 'test_hostname'\n port = 2333\n protocol = 'http'\n params = {\n 'SERVICE_NAME': service_name,\n 'ZIPKIN_EXPORTER_HOST_NAME': host_name,\n 'ZIPKIN_EXPORTER_PORT': port,\n 'ZIPKIN_EXPORTER_PROTOCOL': protocol,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_zipkin = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n zipkin_exporter.ZipkinExporter)\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params',\n params)\n\n with patch_zipkin, patch_params:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertEqual(middleware.exporter.service_name, service_name)\n self.assertEqual(middleware.exporter.host_name, host_name)\n self.assertEqual(middleware.exporter.port, port)\n\n def test_constructor_ocagent_trace_exporter(self):\n from opencensus.trace.ext.django import middleware\n\n service_name = 'test_service'\n endpoint = 'localhost:50001'\n params = {\n 'SERVICE_NAME': service_name,\n 'OCAGENT_TRACE_EXPORTER_ENDPOINT': endpoint,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_ocagent_trace = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n trace_exporter.TraceExporter)\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params',\n params)\n\n with patch_ocagent_trace, patch_params:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertIs(middleware._sampler, always_on.AlwaysOnSampler)\n self.assertIs(\n middleware._exporter, trace_exporter.TraceExporter)\n self.assertIs(\n middleware._propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n assert isinstance(middleware.sampler, always_on.AlwaysOnSampler)\n assert isinstance(\n middleware.exporter, trace_exporter.TraceExporter)\n assert isinstance(\n middleware.propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n self.assertEqual(middleware.exporter.service_name, service_name)\n self.assertEqual(middleware.exporter.endpoint, endpoint)\n\n def test_constructor_ocagent_trace_exporter_default_endpoint(self):\n from opencensus.trace.ext.django import middleware\n\n service_name = 'test_service'\n params = {\n 'SERVICE_NAME': service_name,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_ocagent_trace = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n trace_exporter.TraceExporter)\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params',\n params)\n\n with patch_ocagent_trace, patch_params:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertEqual(middleware.exporter.service_name, service_name)\n self.assertEqual(middleware.exporter.endpoint,\n trace_exporter.DEFAULT_ENDPOINT)\n\n def test_constructor_probability_sampler(self):\n from opencensus.trace.ext.django import middleware\n\n rate = 0.8\n params = {\n 'SAMPLING_RATE': 0.8,\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport',\n }\n\n patch_sampler = mock.patch(\n 'opencensus.trace.ext.django.config.settings.SAMPLER',\n probability.ProbabilitySampler)\n patch_exporter = mock.patch(\n 'opencensus.trace.ext.django.config.settings.EXPORTER',\n print_exporter.PrintExporter)\n\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.config.settings.params',\n params)\n\n with patch_sampler, patch_exporter, patch_params:\n middleware = middleware.OpencensusMiddleware()\n\n self.assertIs(middleware._sampler, probability.ProbabilitySampler)\n self.assertIs(\n middleware._exporter, print_exporter.PrintExporter)\n self.assertIs(\n middleware._propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n assert isinstance(middleware.sampler, probability.ProbabilitySampler)\n assert isinstance(\n middleware.exporter, print_exporter.PrintExporter)\n assert isinstance(\n middleware.propagator,\n google_cloud_format.GoogleCloudFormatPropagator)\n\n self.assertEqual(middleware.sampler.rate, rate)\n\n def test_process_request(self):\n from opencensus.trace.ext.django import middleware\n\n trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'\n span_id = '6e0c63257de34c92'\n django_trace_id = '{}/{}'.format(trace_id, span_id)\n\n django_request = RequestFactory().get('/', **{\n 'HTTP_X_CLOUD_TRACE_CONTEXT': django_trace_id})\n\n middleware_obj = middleware.OpencensusMiddleware()\n\n # test process_request\n middleware_obj.process_request(django_request)\n\n tracer = middleware._get_current_tracer()\n\n span = tracer.current_span()\n\n expected_attributes = {\n 'http.url': u'/',\n 'http.method': 'GET',\n }\n self.assertEqual(span.span_kind, span_module.SpanKind.SERVER)\n self.assertEqual(span.attributes, expected_attributes)\n self.assertEqual(span.parent_span.span_id, span_id)\n\n span_context = tracer.span_context\n self.assertEqual(span_context.trace_id, trace_id)\n\n # test process_view\n view_func = mock.Mock()\n middleware_obj.process_view(django_request, view_func)\n\n self.assertEqual(span.name, 'mock.mock.Mock')\n\n def test_blacklist_path(self):\n from opencensus.trace.ext.django import middleware\n\n execution_context.clear()\n\n blacklist_paths = ['test_blacklist_path', ]\n params = {\n 'BLACKLIST_PATHS': ['test_blacklist_path', ],\n 'TRANSPORT':\n 'opencensus.trace.exporters.transports.sync.SyncTransport', }\n patch_params = mock.patch(\n 'opencensus.trace.ext.django.middleware.settings.params',\n params)\n\n with patch_params:\n middleware_obj = middleware.OpencensusMiddleware()\n\n django_request = RequestFactory().get('/test_blacklist_path')\n disabled = utils.disable_tracing_url(django_request.path,\n blacklist_paths)\n self.assertTrue(disabled)\n self.assertEqual(middleware_obj._blacklist_paths, blacklist_paths)\n\n # test process_request\n middleware_obj.process_request(django_request)\n\n tracer = middleware._get_current_tracer()\n span = tracer.current_span()\n\n # process view\n view_func = mock.Mock()\n middleware_obj.process_view(django_request, view_func)\n\n tracer = middleware._get_current_tracer()\n span = tracer.current_span()\n\n assert isinstance(span, BlankSpan)\n\n # process response\n django_response = mock.Mock()\n django_response.status_code = 200\n\n middleware_obj.process_response(django_request, django_response)\n\n tracer = middleware._get_current_tracer()\n span = tracer.current_span()\n assert isinstance(span, BlankSpan)\n\n def test_process_response(self):\n from opencensus.trace.ext.django import middleware\n\n trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'\n span_id = '6e0c63257de34c92'\n django_trace_id = '{}/{}'.format(trace_id, span_id)\n\n django_request = RequestFactory().get('/', **{\n google_cloud_format._TRACE_CONTEXT_HEADER_NAME: django_trace_id})\n\n middleware_obj = middleware.OpencensusMiddleware()\n\n middleware_obj.process_request(django_request)\n tracer = middleware._get_current_tracer()\n span = tracer.current_span()\n\n exporter_mock = mock.Mock()\n tracer.exporter = exporter_mock\n\n django_response = mock.Mock()\n django_response.status_code = 200\n\n expected_attributes = {\n 'http.url': u'/',\n 'http.method': 'GET',\n 'http.status_code': '200',\n 'django.user.id': '123',\n 'django.user.name': 'test_name'\n }\n\n mock_user = mock.Mock()\n mock_user.pk = 123\n mock_user.get_username.return_value = 'test_name'\n django_request.user = mock_user\n\n middleware_obj.process_response(django_request, django_response)\n\n self.assertEqual(span.attributes, expected_attributes)\n\n\nclass Test__set_django_attributes(unittest.TestCase):\n class Tracer(object):\n def __init__(self):\n self.attributes = {}\n\n def add_attribute_to_current_span(self, key, value):\n self.attributes[key] = value\n\n def test__set_django_attributes_no_user(self):\n from opencensus.trace.ext.django.middleware import \\\n _set_django_attributes\n tracer = self.Tracer()\n request = mock.Mock()\n\n request.user = None\n\n _set_django_attributes(tracer, request)\n\n expected_attributes = {}\n\n self.assertEqual(tracer.attributes, expected_attributes)\n\n def test__set_django_attributes_no_user_info(self):\n from opencensus.trace.ext.django.middleware import \\\n _set_django_attributes\n tracer = self.Tracer()\n request = mock.Mock()\n django_user = mock.Mock()\n\n request.user = django_user\n django_user.pk = None\n django_user.get_username.return_value = None\n\n _set_django_attributes(tracer, request)\n\n expected_attributes = {}\n\n self.assertEqual(tracer.attributes, expected_attributes)\n\n def test__set_django_attributes_with_user_info(self):\n from opencensus.trace.ext.django.middleware import \\\n _set_django_attributes\n tracer = self.Tracer()\n request = mock.Mock()\n django_user = mock.Mock()\n\n request.user = django_user\n test_id = 123\n test_name = 'test_name'\n django_user.pk = test_id\n django_user.get_username.return_value = test_name\n\n _set_django_attributes(tracer, request)\n\n expected_attributes = {\n 'django.user.id': '123',\n 'django.user.name': test_name}\n\n self.assertEqual(tracer.attributes, expected_attributes)\n","sub_path":"tests/unit/trace/ext/django/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":15860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"18453884","text":"# Copyright Notice:\n# Copyright 2019 Lenovo. All rights reserved.\n# License: Apache License. For full text see link: https://github.com/renxulei/Redfish-Mockup-Creator/blob/master/APACHE_LICENSE\n\n# -*- coding: utf-8 -*-\nimport argparse\nimport collections\nimport json\nimport logging\nimport os\nimport shutil\nimport sys\nimport redfishMockupCreate\nfrom datetime import datetime\n\ncurdir = os.path.dirname(__file__)\nlogdir = os.path.join(curdir, 'PerformanceGraphLogs' + os.sep)\nif not (os.path.exists(logdir)):\n os.mkdir(logdir)\n\nlog_file = os.path.join(logdir, \"output.log\")\n\n\ndef GenerateTimeDict(MockupPath, TimeDict):\n\n odataid = time = \"\"\n # recusive go through all directories under mockup folder\n MockupPathDirFile = os.listdir(MockupPath)\n for DirFileElem in MockupPathDirFile:\n DirFilePath = os.path.join(MockupPath, DirFileElem)\n logging.info(\"Processing directory :\" + DirFilePath)\n if(os.path.isdir(DirFilePath)):\n DirFilePathList = DirFilePath.split(os.sep)\n CurrentParentName = DirFilePathList[-1]\n # skip the first redfish v1/\n if(CurrentParentName == \"redfish\"):\n GenerateTimeDict(DirFilePath, TimeDict)\n logging.debug(\"Skip redfish directory without actual result\")\n else:\n if(os.path.exists(DirFilePath + os.sep + \"index.json\") and os.path.exists(DirFilePath + os.sep + \"time.json\")):\n try:\n with open(DirFilePath + os.sep + \"index.json\", \"r\") as f:\n try:\n fcontent = json.load(f)\n if \"@odata.id\" in fcontent.keys():\n odataid = fcontent[\"@odata.id\"]\n if (isinstance(odataid, dict)):\n logging.debug(\"Dict type odataid found\")\n odataid = fcontent[\"@odata.id\"][\"1\"][\"@odata.id\"][:-2]\n else:\n odataid = ''\n except Exception:\n logging.error(\"Fail to read odataid under \" + DirFilePath + \", Generate time dictionary failed\")\n sys.exit(-1)\n finally:\n f.close()\n with open(DirFilePath + os.sep + \"time.json\", \"r\") as f:\n try:\n fcontent = json.load(f)\n time = fcontent[\"GET_Time\"]\n except Exception:\n logging.error(\"Fail to read time under \" + DirFilePath + \", Generate time dictionary failed\")\n sys.exit(-1)\n finally:\n f.close()\n except Exception:\n logging.error(\"Fail to read file under \" + DirFilePath + \", Generate time dictionary failed\")\n sys.exit(-1)\n else:\n logging.warning(\"Index.json or time.json doesn't exist under \" + DirFilePath + \", Skip this directory\")\n \n if odataid != '':\n TimeDict[odataid] = time\n GenerateTimeDict(DirFilePath, TimeDict)\n\n else:\n continue\n\n return TimeDict\n\ndef GetReadmeData(MockupPath):\n\n rhost = averageResponseTime = totalResponseTime = \"\"\n\n if(os.path.exists(MockupPath + os.sep + \"README\")):\n try:\n with open(MockupPath + os.sep + \"README\", \"r\") as f:\n try:\n contents = f.readlines()\n for line in contents:\n line_val_list = line.split(\":\")\n if(\"rhost\" in line):\n rhost = line_val_list[1].strip()\n if(\"averageResponseTime\" in line):\n averageResponseTime = line_val_list[1].strip() + \" sec\"\n if(\"totalResponseTime\" in line):\n totalResponseTime = line_val_list[1].strip() + \" sec\"\n except ValueError:\n logging.error(\"Fail to read result info from README\")\n return False\n except IOError:\n logging.error(\"Fail to read README file under mockup directory\")\n return False\n finally:\n f.close()\n else:\n logging.error(\"README file under mockup directory doesn't exist\")\n \n return rhost, averageResponseTime, totalResponseTime\n\n\ndef GeneratePerformanceGraph(TimeDict, HostIP, AverageTime, TotalTime, ExpectAverage):\n\n chart_data = {\n\n \"legend\": [\"Time\"],\n \"xAxis\": [],\n \"rows\": [],\n \"series\": {\n \"Time\": [],\n },\n 'colors': {\n 'Time': '#99EEEE',\n 'realtime': '#9999EE',\n # 'variance': 'black'\n },\n 'types': {\n 'Time': 'bar',\n 'realtime': 'bar'\n # 'variance': 'line'\n },\n }\n xAxis = chart_data[\"xAxis\"]\n rows = chart_data[\"rows\"]\n se_Time = chart_data[\"series\"][\"Time\"]\n for url, arr in sorted(TimeDict.items(), key=lambda x: x[0]):\n if (url == \"\" or arr == \"\"):\n continue\n xAxis.append(url)\n Time_val = int(float(arr)*1000)\n se_Time.append(Time_val)\n rows.append({\"time\": Time_val, \"url\": url, \"rounds\": Time_val})\n\n try:\n template_path = os.path.join(curdir, \"template.html\")\n templateHtml = open(template_path, encoding= 'utf-8').read()\n timestamp = datetime.now().strftime('%Y%m%d%H%M%S')\n outfp = os.path.join(logdir, \"result\" + timestamp + \".html\")\n except IOError:\n logging.error(\"Fail to open template page\")\n return False\n\n templateHtml = templateHtml.replace(\"{{title}}\", \"Redfish Performance Test Result %s\" % timestamp\n ).replace('{{HostIP}}', HostIP).replace('{{AverageTime}}', AverageTime).replace('{{TotalTime}}', TotalTime)\n\n if (ExpectAverage[0] < (float(AverageTime[:-4]))):\n print(\"Performance test: *** FAIL ***, average time is beyond expect\")\n else:\n print(\"Performance test: *** PASS ***, average time is within expect\")\n print(\"Expect average time: %f\" %(ExpectAverage[0]))\n print(\"Actual average time: %f\" %(float(AverageTime[:-4])))\n\n try:\n with open(outfp, 'w') as outf:\n outf.write(templateHtml.replace(\"{{jsondata}}\", json.dumps(chart_data, sort_keys=True, indent=True)))\n outf.flush()\n except IOError:\n logging.error(\"Fail to write Json data into template page\")\n return False\n\n return outfp\n\n \ndef main():\n result= {}\n TimeDict= {}\n\n mkparser = argparse.ArgumentParser(description='Tool for generate performancegraph from mockup data.')\n\n mkparser.add_argument('--dir', type=str, required=True, help='directory of mockup creator data', dest=\"Dir\")\n mkparser.add_argument('--expect', type=float, required=True, nargs=1, help='expect average response time', dest=\"ExpectAverage\")\n\n mkparser.add_argument(\"use_mockup\", nargs='?', choices=[\"mockupargs\"], help=\"command name\")\n mkparser.add_argument(\"mockup_args\", nargs=argparse.REMAINDER, help=argparse.SUPPRESS) \n\n args = mkparser.parse_args()\n\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename=log_file,\n filemode='w',\n )\n \n console = logging.StreamHandler(stream=sys.stdout)\n console.setLevel(logging.ERROR)\n formatter = logging.Formatter('%(levelname)-8s: %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\n if not (\"-T\" in args.mockup_args):\n args.mockup_args.append(\"-T\")\n\n if not (\"-S\" in args.mockup_args):\n args.mockup_args.append(\"-S\")\n\n if(args.use_mockup is not None):\n try:\n mockup_args_list = [args.use_mockup] + args.mockup_args + [\"-D\", args.Dir]\n redfishMockupCreate.main(mockup_args_list)\n except SystemExit as e:\n if(e.code == 0):\n pass\n else:\n sys.exit(e)\n\n logging.info(\"Tool start at \" + datetime.now().strftime('%Y%m%d%H%M%S') + \" with Mockup data from \" + args.Dir)\n\n if (os.path.exists(args.Dir)):\n MockupPath = args.Dir\n else:\n logging.error(\"Mockup file directory doesn't exist\")\n result = {'ret': False, 'msg': \"Mockup file directory doesn't exist\"}\n return result\n \n print(\"Generating time dictionary from mockup data ...\")\n TimeDict = GenerateTimeDict(MockupPath, TimeDict)\n\n print(\"Reading data from README file ...\")\n HostIP, AverageTime, TotalTime, = GetReadmeData(MockupPath)\n if (HostIP == \"\" or AverageTime == \"\" or TotalTime ==\"\"):\n logging.error(\"Get data from README file failed\")\n result = {'ret': False, 'msg': \"Get data from README file failed\"}\n return result\n logdir = os.path.join(args.Dir, 'PerformanceGraphLogs'+os.sep)\n result = {'ret': True, 'HostIP': HostIP, 'AverageTime': float(AverageTime[:-4]), 'TotalTime': float(TotalTime[:-4]), 'logdir': logdir}\n if float(AverageTime[:-4]) > args.ExpectAverage[0]:\n result['ret'] = False\n\n print(\"Generating PerformanceGraph ...\")\n ret = GeneratePerformanceGraph(TimeDict, HostIP, AverageTime, TotalTime, args.ExpectAverage)\n if (ret != False):\n ret = os.path.join(args.Dir, 'PerformanceGraphLogs', os.path.split(ret)[-1])\n print(\"Please check detailed performance results under \" + ret + \" and running logs under \" + logdir + \"output.log\")\n else:\n print(\"Generating PerformanceGraph failed\")\n logging.error(\"Generating PerformanceGraph failed\")\n\n logging.info(\"Tool exit at \" + datetime.now().strftime('%Y%m%d%H%M%S'))\n logging.shutdown()\n return result\n\n \nif __name__ == \"__main__\":\n \n main()\n","sub_path":"PerformanceGraph.py","file_name":"PerformanceGraph.py","file_ext":"py","file_size_in_byte":10184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154142894","text":"#!python\n# ==========================================================#\n# project :sjdillon\n# title :test_data_reader.py\n# description :unit test qthena\n# author :sjdillon\n# date :08/26/2019\n# python_version :3.7\n# notes :\n# ==========================================================#\nimport logging\nimport os\nimport qthena.athena_data_reader as data_access\n\nlogging.basicConfig(format=\"%(asctime)s - %(thread)s - %(levelname)s - %(message)s\")\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef create_event():\n \"\"\"\n creates an event for unit tests\n :return: dict\n \"\"\"\n os.environ['region'] = 'us-west-2'\n os.environ['profile'] = 'default'\n os.environ['prefix1'] = 'sjd'\n os.environ['prefix2'] = 'illon'\n os.environ['env'] = 'dev'\n prefix1 = os.environ['prefix1']\n prefix2 = os.environ['prefix2']\n env = os.environ['env']\n region = os.environ['region']\n\n event = dict()\n event['region'] = os.environ['region']\n # 0 sleep for mocked unit tests\n event['sleep_seconds'] = 0\n bucket_format = \"s3-{prefix1}-{prefix2}-{env}-{region}-data\"\n event['bucket'] = bucket_format.format(prefix1=prefix1,\n prefix2=prefix2,\n env=env,\n region=region)\n event['s3_query_results_path'] = \"awsathenadata/queryresults\"\n return event\n\n\ngeneric_event = create_event()\n\n\ndef is_uuid(uuid):\n \"\"\"\n Check if value is a proper uuid\n :param uuid: string to check\n :return: bool\n \"\"\"\n import re\n UUID_PATTERN = re.compile(r'^[\\da-f]{8}-([\\da-f]{4}-){3}[\\da-f]{12}$', re.IGNORECASE)\n if UUID_PATTERN.match(uuid):\n return True\n return False\n\n\ndef run_data_access_run_query(event=generic_event, mode='playback'):\n \"\"\"\n Test running a query against athena\n :param event: generic event with aws env details\n :param mode: boto aws client or mocked client\n :return: assert\n \"\"\"\n # GIVEN an event\n if mode:\n event['mock_mode'] = mode\n event['mock_data_path'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mock_data')\n event['debug'] = False\n # WHEN we run a query using a CommandRunner\n runner = data_access.CommandRunner(event, bucket=event['bucket'],\n s3_query_results_path=event['s3_query_results_path'])\n results = runner.run_query('show databases')\n # THEN we get a uuid returned\n assert len(results) == 36\n assert is_uuid(results)\n\n\ndef run_data_access_select(event=generic_event, mode='playback'):\n \"\"\"\n Test running a select returning data\n :param event: generic event with aws env details\n :param mode: boto aws client or mocked client\n :return: assert\n \"\"\"\n # GIVEN an event\n if mode:\n event['mock_mode'] = mode\n event['mock_data_path'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mock_data')\n event['debug'] = False\n # WHEN we run a select using a CommandRunner\n runner = data_access.CommandRunner(event,\n bucket=event['bucket'],\n s3_query_results_path=event['s3_query_results_path'])\n results = runner.select('show databases', to_list=True)\n logger.info(results)\n # THEN we get a list of results\n assert results\n assert isinstance(results, list)\n\n\ndef run_data_access_select_w_bucket(event=generic_event, mode='playback'):\n \"\"\"\n Test running a select with a bucket specified\n :param event: generic event with aws env details\n :param mode: boto aws client or mocked client\n :return: assert\n \"\"\"\n # GIVEN an event that overrides the default bucket\n event['bucket'] = \"s3-sjd-illon-integ-us-west-2-data\"\n if mode:\n event['mock_mode'] = mode\n event['mock_data_path'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mock_data')\n event['debug'] = False\n # WHEN we run a select using a CommandRunner\n runner = data_access.CommandRunner(event, bucket=event['bucket'],\n s3_query_results_path=event['s3_query_results_path'])\n results = runner.select('show databases', to_list=True)\n logger.info(results)\n # THEN we get a list of results\n assert results\n assert isinstance(results, list)\n\n\ndef test_data_access_run_query(params=generic_event, mode='playback'):\n run_data_access_run_query(params, mode)\n\n\ndef test_data_access_select_w_bucket(params=generic_event, mode='playback'):\n run_data_access_select_w_bucket(params, mode)\n\n\ndef test_data_access_select(params=generic_event, mode='playback'):\n run_data_access_select(params, mode)\n\n\ndef test_results_to_list():\n \"\"\"\n Test results_to_list helper function\n :return:list\n \"\"\"\n # GIVEN a dictionary resultset from athena\n resultset = {'ResultSet': {'Rows': [{'Data': [{'VarCharValue': 'athena'}]}],\n 'ResultSetMetadata': {'ColumnInfo': [\n {'CatalogName': 'hive',\n 'SchemaName': '',\n 'TableName': '',\n 'Name': 'database_name',\n 'Label': 'database_name',\n 'Type': 'string', 'Precision': 0, 'Scale': 0, 'Nullable': 'UNKNOWN',\n 'CaseSensitive': False}]}}}\n # WHEN we convert to a list\n results = data_access.results_to_list(resultset)\n # THEN a list is returned\n assert isinstance(results, list)\n","sub_path":"qthena/tests/test_data_reader.py","file_name":"test_data_reader.py","file_ext":"py","file_size_in_byte":5692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642708312","text":"# Author: Bishal Sarang\n\"\"\"\nThis file contains implementation of AI agent that uses minimax algorithm to find the best possible move\n\"\"\"\nfrom collections import namedtuple\nfrom utilities import x_not_equals_y_operations, x_equals_y_operations, is_inside_board, is_game_over\nimport random\nfrom datetime import datetime\nfrom copy import deepcopy\n\nMove = namedtuple(\"Move\", \"type frm to inter\")\nINF = float(\"inf\")\n\nclass Agent(object):\n def __init__(self, board, turn,goats_in_hand, dead_goats, depth=5):\n self.board = board\n self.depth = depth\n self.best_move = None\n self.winner = None\n self.turn = turn\n self.goats_in_hand = goats_in_hand\n self.dead_goats = dead_goats\n\n def is_vacant(self, i, j):\n return self.board[i][j] == '_'\n\n def number_of_movable_tigers(self):\n cnt = 0\n for i in range(5):\n for j in range(5):\n operations = x_not_equals_y_operations\n if i % 2 == j % 2:\n operations = x_equals_y_operations\n if self.board[i][j] == 'T':\n for offset_x, offset_y in operations:\n next_i, next_j = i + offset_x, j + offset_y\n if is_inside_board(next_i, next_j) and self.is_vacant(next_i, next_j):\n cnt += 1\n break\n assert(cnt <= 4)\n return cnt\n\n\n\n def number_of_closed_spaces(self):\n cnt = 0\n for i in range(5):\n for j in range(5):\n if self.board[i][j] == '_':\n cnt += 1\n return cnt\n\n def evaluate(self, depth=0):\n winner = is_game_over(self.board, self.dead_goats)\n if not winner[0]:\n random.seed(datetime.now())\n return 5 * self.number_of_movable_tigers() + 50 * self.dead_goats + 15 * self.number_of_goats_that_can_be_captured() - random.random()\n # return depth\n\n if winner[1] == \"Goat\":\n return -INF\n elif winner[1] == \"Tiger\":\n return INF\n\n def place_goats(self):\n moves = []\n for i in range(5):\n for j in range(5):\n if self.is_vacant(i, j):\n moves.append(Move(\"p\", None, (i, j), None))\n return moves\n\n\n def number_of_goats_that_can_be_captured(self):\n cnt = 0\n board = deepcopy(self.board)\n for i in range(5):\n for j in range(5):\n if board[i][j] == 'T':\n operations = x_not_equals_y_operations\n if i % 2 == j % 2:\n operations = x_equals_y_operations\n\n for offset_x, offset_y in operations:\n next_i, next_j = i + offset_x, j + offset_y\n if is_inside_board(next_i, next_j) and board[next_i][next_j] == 'G':\n next_next_i, next_next_j = i + 2 * offset_x, j + 2 * offset_y\n if is_inside_board(next_next_i, next_next_j) and \\\n board[next_next_i][next_next_j] == '_':\n board[next_i][next_j] = '_'\n cnt += 1\n\n return cnt\n\n def move_goats(self):\n moves = []\n for i in range(5):\n for j in range(5):\n if self.board[i][j] == 'G':\n operations = x_not_equals_y_operations\n if i % 2 == j % 2:\n operations = x_equals_y_operations\n\n for offset_x, offset_y in operations:\n next_i, next_j = i + offset_x, j + offset_y\n if is_inside_board(next_i, next_j) and self.is_vacant(next_i, next_j):\n moves.append(Move(\"m\", (i, j), (next_i, next_j), None))\n return moves\n\n def move_tigers(self):\n moves = []\n for i in range(5):\n for j in range(5):\n if self.board[i][j] == 'T':\n operations = x_not_equals_y_operations\n if i % 2 == j % 2:\n operations = x_equals_y_operations\n\n for offset_x, offset_y in operations:\n next_i, next_j = i + offset_x, j + offset_y\n if is_inside_board(next_i, next_j) and self.is_vacant(next_i, next_j):\n moves.append(Move(\"m\", (i, j), (next_i, next_j), None))\n return moves\n\n def eat_goats(self):\n moves = []\n for i in range(5):\n for j in range(5):\n if self.board[i][j] == 'T':\n operations = x_not_equals_y_operations\n if i % 2 == j % 2:\n operations = x_equals_y_operations\n\n for offset_x, offset_y in operations:\n next_i, next_j = i + offset_x, j + offset_y\n if is_inside_board(next_i, next_j) and self.board[next_i][next_j] == 'G':\n next_next_i, next_next_j = i + 2 * offset_x, j + 2 * offset_y\n if is_inside_board(next_next_i, next_next_j) and self.board[next_next_i][next_next_j] == '_':\n moves.append(Move('e', (i, j), (next_next_i, next_next_j), (next_i, next_j)))\n return moves\n\n\n\n def generate_move_list(self, is_max):\n move_list = []\n\n # Goat is minimizing\n if not is_max:\n if self.goats_in_hand > 0:\n move_list.extend(self.place_goats())\n else:\n move_list.extend(self.move_goats())\n # Tiger is maximizing\n else:\n move_list.extend(self.eat_goats())\n move_list.extend(self.move_tigers())\n return move_list\n\n def make_move(self, move, is_max):\n object_to_be_placed = 'T' if is_max else 'G'\n _, frm, to, inter = move\n if move.type == \"p\":\n row, col = to\n self.board[row][col] = object_to_be_placed\n self.goats_in_hand -= 1\n elif move.type == \"m\":\n row1, col1 = frm\n row2, col2 = to\n\n self.board[row1][col1] = '_'\n self.board[row2][col2] = object_to_be_placed\n elif move.type == \"e\":\n row1, col1 = frm\n goat_x, goat_y = inter\n row2, col2 = to\n self.dead_goats += 1\n self.board[row1][col1] = '_'\n self.board[goat_x][goat_y] = '_'\n self.board[row2][col2] = object_to_be_placed\n\n\n\n def revert_move(self, move, is_max):\n object_to_be_placed = 'T' if is_max else 'G'\n _, frm, to, inter = move\n if move.type == \"p\":\n row, col = to\n self.board[row][col] = '_'\n self.goats_in_hand += 1\n elif move.type == \"m\":\n row1, col1 = frm\n row2, col2 = to\n\n self.board[row1][col1] = object_to_be_placed\n self.board[row2][col2] = '_'\n elif move.type == \"e\":\n row1, col1 = frm\n goat_x, goat_y = inter\n row2, col2 = to\n self.dead_goats -= 1\n self.board[row1][col1] = object_to_be_placed\n self.board[goat_x][goat_y] = 'G'\n self.board[row2][col2] = '_'\n\n def minimax(self, is_max=True, depth=0, alpha=-INF, beta=INF):\n score = self.evaluate(depth)\n\n if depth == self.depth or abs(score) == INF:\n return score\n\n\n if not is_max:\n value = INF\n\n for move in self.generate_move_list(is_max):\n self.make_move(move, is_max)\n current_value = self.minimax(True, depth + 1, alpha, beta)\n beta = min(beta, current_value)\n\n if current_value == value and depth == 0:\n self.best_move = move\n if current_value < value:\n\n value = current_value\n beta = min(beta, value)\n if depth == 0:\n self.best_move = move\n\n self.revert_move(move, is_max)\n if alpha >= beta:\n break\n return value\n\n else:\n value = -INF\n for move in self.generate_move_list(is_max):\n self.make_move(move, is_max)\n current_value = self.minimax(False, depth + 1, alpha, beta)\n alpha = max(alpha, value)\n if current_value == value and depth == 0:\n self.best_move = move\n if current_value > value:\n\n value = current_value\n alpha = max(alpha, value)\n if depth == 0:\n self.best_move = move\n self.revert_move(move, is_max)\n\n if alpha >= beta:\n break\n return value\n\n def best_tiger_move(self):\n self.minimax()\n return self.best_move\n\n def best_goat_move(self):\n self.minimax(is_max=False)\n return self.best_move\n\n def make_best_move(self):\n if self.turn == \"Goat\":\n move = self.best_goat_move()\n else:\n move = self.best_tiger_move()\n if self.turn == \"Goat\":\n is_max = False\n else:\n is_max = True\n self.make_move(move, is_max)\n\n\n def get_best_move(self):\n if self.turn == \"Goat\":\n move = self.best_goat_move()\n else:\n move = self.best_tiger_move()\n\n return move\n\n# The heuristic value for the tiger piece was calculated based on the number of goats in the board, mobility of the piece and number of possible captures.","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":9781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495179788","text":"import math\nfrom scipy import integrate\n\n# Linguistic variable class\nclass Variable:\n # New variable initialization\n def __init__(self, name, terms, universum):\n self.name = name\n self.terms = terms\n self.universum = universum\n # check if terms are in universum\n for term in self.terms:\n curr = self.terms[term]\n try:\n if not 2 <= len(curr) <= 4:\n print(\"Term error: term points quantity is not 2, 3 or 4\")\n raise SystemExit\n except:\n print(\"Term error: term points quantity is not 2, 3 or 4\")\n raise SystemExit\n if min(curr) < self.universum[0] or max(curr) > self.universum[1]:\n print(\"Term error: term points are not in variable's universum\")\n raise SystemExit\n if 3 <= len(curr) <= 4 and not list(curr) == sorted(list(curr)):\n print(\"Term error: term points are not in ascending order\")\n raise SystemExit\n\n # Member function calculation description\n def mf(self, value):\n out = []\n for term in self.terms:\n curr = self.terms[term]\n if len(curr) == 4:\n if curr[0] <= value <= curr[1]:\n out.append(1 - (curr[1] - value) / (curr[1] - curr[0]))\n elif curr[1] <= value <= curr[2]:\n out.append(1)\n elif curr[2] <= value <= curr[3]:\n out.append(1 - (value - curr[2]) / (curr[3] - curr[2]))\n else:\n out.append(0)\n elif len(curr) == 3:\n if curr[0] <= value <= curr[1]:\n out.append(1 - (curr[1] - value) / (curr[1] - curr[0]))\n elif curr[1] <= value <= curr[2]:\n out.append(1 - (value - curr[1]) / (curr[2] - curr[1]))\n else:\n out.append(0)\n elif len(curr) == 2:\n out.append(math.exp(-((value - curr[0]) / curr[1]) ** 2))\n return out\n\n\n# Rule base forming class\nclass Rule:\n # Empty rule base initialization\n def __init__(self):\n self.rules = {}\n\n # New rule addition method\n def add_rule(self, conditions, conclusions):\n self.rules[conditions] = conclusions\n\n\n# Fuzzy logics methods\nclass FuzzyMethods:\n # Initialization of empty sets needed for methods to work together\n def __init__(self):\n self.fuzz = {}\n self.aggr = {}\n self.accum_act = []\n\n # Input variables fuzzyfication\n def fuzzification(self, variables): # variables = {var_1: val_1, var_2: val_2...}\n self.fuzz = {}\n for var in variables:\n mem_func = var.mf(variables[var])\n for i in range(len(mem_func)):\n self.fuzz[list(var.terms.keys())[i]] = mem_func[i]\n return self.fuzz\n\n # Aggregating subconditions\n def aggregation(self, rules): # rules = {...}\n self.aggr = {}\n for rule in rules:\n self.aggr[rules[rule]] = (min(self.fuzz[rule[0]], self.fuzz[rule[2]]))\n return self.aggr\n\n # Activation with the multiplication operator + accumulation with max-union\n def accum_activation(self, x_value, var):\n self.accum_act = []\n for conclusion in self.aggr:\n self.accum_act.append(self.aggr[conclusion] * var.mf(x_value)[list(self.aggr.keys()).index(conclusion)])\n return max(self.accum_act) # Accumulation mode here\n\n # Дефаззифаикация методом центра тяжести\n def defuzzification(self, var):\n func1 = lambda x: x * self.accum_activation(x, var)\n func2 = lambda x: self.accum_activation(x, var)\n i1 = integrate.quad(func1, var.universum[0], var.universum[1], limit=1)\n i2 = integrate.quad(func2, var.universum[0], var.universum[1], limit=1)\n return i1[0] / i2[0]\n","sub_path":"Larsen.py","file_name":"Larsen.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"497668065","text":"import os\nimport fsspec\nimport json\nimport collections\nfrom pathlib import Path\nfrom typing import Optional\nfrom typing import Union\nfrom typing import Dict\n\nimport torch\nfrom torchvision.utils import save_image\nfrom pytorch_lightning.utilities import rank_zero_only\nfrom pytorch_lightning.loggers import LightningLoggerBase\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\n\npathlike = Union[Path, str]\n\n\ndef get_filesystem(path: pathlike):\n path = str(path)\n if \"://\" in path:\n # use the fileystem from the protocol specified\n return fsspec.filesystem(path.split(\":\", 1)[0])\n else:\n # use local filesystem\n return fsspec.filesystem(\"file\")\n\n\nclass ModelSaver(ModelCheckpoint):\n\n def __init__(self, limit_num, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.limit_num = limit_num\n\n def save_checkpoint(self, trainer, pl_module):\n \"\"\"\n Performs the main logic around saving a checkpoint.\n This method runs on all ranks, it is the responsibility of `self.save_function`\n to handle correct behaviour in distributed training, i.e., saving only on rank 0.\n \"\"\"\n epoch = trainer.current_epoch\n global_step = trainer.global_step\n\n if (\n self.save_top_k == 0 # no models are saved\n or self.period < 1 # no models are saved\n or (epoch + 1) % self.period # skip epoch\n or trainer.running_sanity_check # don't save anything during sanity check\n or self.last_global_step_saved == global_step # already saved at the last step\n ):\n return\n\n self._add_backward_monitor_support(trainer)\n self._validate_monitor_key(trainer)\n\n # track epoch when ckpt was last checked\n self.last_global_step_saved = global_step\n\n # what can be monitored\n monitor_candidates = self._monitor_candidates(trainer)\n\n # ie: path/val_loss=0.5.ckpt\n filepath = self._get_metric_interpolated_filepath_name(epoch, monitor_candidates)\n\n # callback supports multiple simultaneous modes\n # here we call each mode sequentially\n # Mode 1: save all checkpoints OR only the top k\n if self.save_top_k:\n self._save_top_k_checkpoints(monitor_candidates, trainer, pl_module, epoch, filepath)\n\n # Mode 2: save the last checkpoint\n self._save_last_checkpoint(trainer, pl_module, epoch, monitor_candidates, filepath)\n\n self._delete_old_checkpoint()\n\n def _delete_old_checkpoint(self):\n checkpoints = sorted([c for c in os.listdir(self.dirpath) if 'ckpt-epoch' in c])\n if len(checkpoints) > self.limit_num:\n margin = len(checkpoints) - self.limit_num\n checkpoints_for_delete = checkpoints[:margin]\n\n for ckpt in checkpoints_for_delete:\n ckpt_epoch = int(ckpt[len(\"ckpt-epoch=\"): len(\"ckpt-epoch=\") + 4])\n if (ckpt_epoch + 1) % 10 != 0:\n model_path = os.path.join(self.dirpath, ckpt)\n self._del_model(model_path)\n\n\nclass Logger(LightningLoggerBase):\n\n def __init__(self,\n save_dir: str,\n config: collections.defaultdict,\n seed: int,\n monitoring_metrics: list,\n name: Optional[str] = 'default',\n version: Optional[Union[int, str]] = None,\n **kwargs) -> None:\n super().__init__()\n self._save_dir = save_dir\n self._name = name\n self._config = config\n self._seed = seed\n self._version = version\n self._fs = get_filesystem(save_dir)\n self._experiment = None\n self._monitoring_metrics = monitoring_metrics\n self._kwargs = kwargs\n\n @property\n def root_dir(self) -> str:\n if self.name is None or len(self.name) == 0:\n return self.save_dir\n else:\n return os.path.join(self.save_dir, self.name)\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def log_dir(self) -> str:\n version = self.version if isinstance(self.version, str) else f\"version_{self.version}\"\n log_dir = os.path.join(self.root_dir, version)\n return log_dir\n\n @property\n def save_dir(self) -> Optional[str]:\n return self._save_dir\n\n @property\n def version(self) -> int:\n if self._version is None:\n self._version = self._get_next_version()\n return self._version\n\n def _get_next_version(self):\n root_dir = os.path.join(self.save_dir, self.name)\n\n if not self._fs.isdir(root_dir):\n print('Missing logger folder: %s', root_dir)\n return 0\n\n existing_versions = []\n for listing in self._fs.listdir(root_dir):\n d = listing[\"name\"]\n bn = os.path.basename(d)\n if self._fs.isdir(d) and bn.startswith(\"version_\"):\n dir_ver = bn.split(\"_\")[1].replace('/', '')\n existing_versions.append(int(dir_ver))\n if len(existing_versions) == 0:\n return 0\n\n return max(existing_versions) + 1\n\n @rank_zero_only\n def log_metrics(self, metrics: Dict[str, float], step: Optional[int] = None) -> None:\n assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n\n values = []\n for key in self._monitoring_metrics:\n if key in metrics.keys():\n v = metrics[key]\n if isinstance(v, torch.Tensor):\n v = str(v.sum().item())\n else:\n v = str(v)\n else:\n v = ''\n values.append(v)\n\n fname = os.path.join(self.log_dir, 'log.csv')\n with open(fname, 'a') as f:\n if f.tell() == 0:\n print(','.join(self._monitoring_metrics), file=f)\n print(','.join(values), file=f)\n\n @rank_zero_only\n def log_val_metrics(self, metrics: Dict[str, float]) -> None:\n assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n\n fname = os.path.join(self.log_dir, 'val_logs.csv')\n columns = metrics.keys()\n values = [str(value) for value in metrics.values()]\n\n with open(fname, 'a') as f:\n if f.tell() == 0:\n print(','.join(columns), file=f)\n print(','.join(values), file=f)\n\n @rank_zero_only\n def log_test_metrics(self, metrics: Dict[str, float]) -> None:\n assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n\n fname = os.path.join(self.log_dir, 'test_logs.csv')\n columns = metrics.keys()\n values = [str(value) for value in metrics.values()]\n\n with open(fname, 'a') as f:\n if f.tell() == 0:\n print(','.join(columns), file=f)\n print(','.join(values), file=f)\n\n print('Test results are saved: {}'.format(fname))\n\n @rank_zero_only\n def log_hyperparams(self, params):\n config_to_save = collections.defaultdict(dict)\n\n for key, child in self._config._asdict().items():\n for k, v in child._asdict().items():\n config_to_save[key][k] = v\n\n config_to_save['seed'] = self._seed\n config_to_save['save_dir_path'] = self.log_dir\n\n save_path = os.path.join(self.log_dir, 'config.json')\n os.makedirs(self.log_dir, exist_ok=True)\n with open(save_path, 'w') as f:\n json.dump(config_to_save,\n f,\n ensure_ascii=False,\n indent=2,\n sort_keys=False,\n separators=(',', ': '))\n\n @rank_zero_only\n def log_images(self, image_name: str, image: torch.Tensor, current_epoch: int, global_step: int, nrow: int) -> None:\n assert rank_zero_only.rank == 0, 'experiment tried to log from global_rank != 0'\n save_path = os.path.join(self.log_dir, f'{image_name}_{current_epoch:04d}_{global_step:06d}.png')\n save_image(image.data, save_path, nrow=nrow)\n\n def experiment(self):\n return self\n\n def save(self):\n super().save()\n\n @rank_zero_only\n def finalize(self, status: str) -> None:\n self.save()\n","sub_path":"utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":8305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140790067","text":"# This is true lossless compresssion. The\n# integer than defines the message on the\n# right after you hit run recreates that integer\n# using math. Using math we recreate lossless\n# compression, no tricks are used. This program\n# without the header is about 596 bytes, and\n# can recreate the integer of the actual\n# message you see on the left. The goal was to \n# compress a repeating message losselessly and\n# i obtained this goal by finding a repeating\n# pattern that climbs to the original integer.\n# This is a lossless self extracting compresser # of very small size\n\ndef n():\n global x\n global j\n temp = j^-x\n x=x<<1\n j = temp\n\ndef p():\n global x\n global j\n temp = j^x\n x=x<<1\n j = temp\n\n\nj=5\nx=8\npattern = \"+-+----+--+------++++--++-+-+---\"\nlengthpattern = len(pattern)\nfirsttime = 1\nfor c in range(0,2500):\n start=0\n if firsttime == 1:\n start= 3\n firsttime = 0\n for y in range (start, lengthpattern):\n if pattern[y]=='+':\n p()\n elif pattern[y]=='-':\n n()\nmessage = j \nprint(bytes.fromhex(hex(int(str((abs(message))),10))[2:])) \nprint(\"\")\nprint(\"This number, recreated with this small program is in the universe as {}\".format(abs(j)))\nprint(\"Scroll to the top to see the compressed message. This program is much smaller than the number it created and the message it compressed\")\n \n","sub_path":"uncompressmessage.py","file_name":"uncompressmessage.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"307568343","text":"msum = 0\nf = open('matrix sum.txt', 'r')\nlines = f.read()\nf.close()\nlines = lines.split('\\n')\nfor i in range(len(lines)):\n lines[i] = lines[i].split(' ')\nfor i in lines:\n gone = 0\n for x in range(len(i)):\n x -= gone\n if i[x] == '':\n del i[x]\n gone += 1\nfor i in lines:\n m = 0\n for x in i:\n if int(x) > m:\n m = int(x)\n msum += m\nprint(msum)\n","sub_path":"Python/Matrix sum.py","file_name":"Matrix sum.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"398414294","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any\n\nfrom schema.config import Guild, Table\nfrom utils.asyncqlio import to_dict\n\nif TYPE_CHECKING:\n from bot import BeattieBot\n\n\nclass Config:\n def __init__(self, bot: BeattieBot):\n self.db = bot.db\n self.bot = bot\n self.db.bind_tables(Table) # type: ignore\n bot.loop.create_task(self.__init())\n self._cache: dict[int, dict[str, Any]] = {}\n\n async def __init(self) -> None:\n await self.bot.wait_until_ready()\n await Guild.create(if_not_exists=True)\n\n async def get_guild(self, guild_id: int) -> dict[str, Any]:\n try:\n return self._cache[guild_id]\n except KeyError:\n async with self.db.get_session() as s:\n query = s.select(Guild).where(Guild.id == guild_id) # type: ignore\n guild = await query.first()\n if guild is None:\n res = {\"id\": guild_id}\n else:\n res = to_dict(guild)\n self._cache[guild_id] = res\n return res\n\n async def set_guild(self, guild_id: int, **kwargs: Any) -> None:\n guild = await self.get_guild(guild_id)\n self._cache[guild_id].update(kwargs)\n async with self.db.get_session() as s:\n row = Guild(**{**guild, **kwargs})\n query = s.insert.rows(row)\n query = query.on_conflict(Guild.id).update(\n getattr(Guild, name) for name in kwargs # type: ignore\n )\n await query.run()\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372005252","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 27 23:58:26 2019\n\n@author: 양지성\n\"\"\"\n\n#%% Word2Vec\nimport os\nos.chdir(r\"C:\\Users\\양지성\\Desktop\\git_projects\\My-Bachelor-Thesis\\BA_Thesis_git\")\nfrom preprocessing import lemmatized_text, keyword\nfrom gensim.models import Word2Vec\nimport multiprocessing\nimport pandas as pd\nimport numpy as np\nimport copy\n\n# Save the original dataset\ndata = []\nfor i in range(len(lemmatized_text)):\n data.append(lemmatized_text[i])\n\n# Get total word number to determine hyperparameters\ndef total_word_num(tokenized_docs):\n count = 0\n for i in range(len(tokenized_docs)):\n for j in range(len(tokenized_docs[i])):\n count += 1\n return count\n\n# Train the model (CBOW)\ndef model_w2v(corpus, size, window):\n model = Word2Vec(sentences=corpus, size=size, window=window, min_count=1, workers=multiprocessing.cpu_count(), sg=0)\n return model\n\n#%% Hyperparameter optimization\ntotal_word_num(data)\nnum_word_by_document = []\nfor i in range(len(data)):\n num_word_by_document.append(len(data[i]))\nfrom scipy import stats\nstats = stats.describe(num_word_by_document)\nstats.mean\nnp.sqrt(stats.variance)\nsize = [100, 200, 300, 400, 500]\nwindow = [5, 6, 7, 8, 9, 10]\n\n# Getting the closest word to the keyword\nprint(\"Word2Vec model training\")\nwords_by_window = []\nfor w in window:\n words_by_size = []\n for s in size:\n model = model_w2v(data, s, w)\n words_by_size.append(model.wv.most_similar(keyword, topn=10))\n print(\"Central words to the keyword (hidden layer: {}, window: {}):\\n{}\\n\".format(s, w, model.wv.most_similar(keyword)))\n words_by_window.append(words_by_size)\n\n# Central words\ncentral_words = []\nfor i in range(len(words_by_window)):\n for j in range(len(words_by_window[i])):\n for w, sim in words_by_window[i][j]:\n if sim >= 0.8:\n central_words.append(w)\n\ncentral_words\n# sim_matrix[0][0]\n\n\n\n\n\n#%%\n","sub_path":"BA_Thesis_git/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38412456","text":"class TreeNode:\n def __init__(self, number):\n self.num = number\n self.left = None\n self.right = None\n\n\ndef pre_order_traversal_recursive(head):\n if not head:\n return None\n print(head.num, end='')\n print(\" \", end='')\n pre_order_traversal_recursive(head.left)\n pre_order_traversal_recursive(head.right)\n\n\ndef pre_order_traversal_cycle(head):\n stack = [head]\n while len(stack) > 0:\n print(head.num, end='')\n print(\" \", end='')\n if head.right:\n stack.append(head.right)\n if head.left:\n stack.append(head.left)\n head = stack.pop()\n\n\ndef in_order_traverse_recursive(head):\n if not head:\n return None\n in_order_traverse_recursive(head.left)\n print(head.num, end='')\n print(\" \", end='')\n in_order_traverse_recursive(head.right)\n\n\ndef in_order_traverse_cycle(head):\n stack = []\n inner_node = head\n while inner_node or len(stack) > 0:\n if inner_node:\n stack.append(inner_node)\n inner_node = inner_node.left\n else:\n inner_node = stack.pop()\n print(inner_node.num, end='')\n print(\" \", end='')\n inner_node = inner_node.right\n\n\ndef post_order_traverse_recursive(head):\n if not head:\n return None\n post_order_traverse_recursive(head.left)\n post_order_traverse_recursive(head.right)\n print(head.num, end='')\n print(\" \", end='')\n\n\ndef post_order_traverse_cycle(head):\n stack_1 = [head]\n stack_2 = []\n while len(stack_1) > 0:\n inner_node = stack_1.pop()\n stack_2.append(inner_node)\n if inner_node.left is not None:\n stack_1.append(inner_node.left)\n if inner_node.right is not None:\n stack_1.append(inner_node.right)\n while len(stack_2) > 0:\n print(stack_2.pop().num, end=\"\")\n print(\" \", end=\"\")\n\n\ndef layer_traverse(head):\n if not head:\n return\n stack = [head]\n while len(stack) > 0:\n inner_node = stack.pop(0)\n print(inner_node.num, end=\"\")\n print(\" \", end=\"\")\n if inner_node.left:\n stack.append(inner_node.left)\n if inner_node.right:\n stack.append(inner_node.right)\n\n\ndef tree_builder():\n node1 = TreeNode(1)\n node2 = TreeNode(2)\n node3 = TreeNode(3)\n node4 = TreeNode(4)\n node5 = TreeNode(5)\n node6 = TreeNode(6)\n node7 = TreeNode(7)\n\n node1.left = node2\n node1.right = node3\n\n node2.left = node4\n node2.right = node5\n\n node3.left = node6\n node3.right = node7\n\n return node1\n\n\nif __name__ == \"__main__\":\n head_node = tree_builder()\n # pre order traversal\n print(\"pre order traversal*****************************\")\n print(\"recursive\")\n pre_order_traversal_recursive(head_node)\n print(\"\\n\")\n print(\"cycle\")\n pre_order_traversal_cycle(head_node)\n print(\"\\n\")\n # in order traversal\n print(\"in order traversal*****************************\")\n print(\"recursive\")\n in_order_traverse_recursive(head_node)\n print(\"\\n\")\n print(\"cycle\")\n in_order_traverse_cycle(head_node)\n print(\"\\n\")\n print(\"post order traversal*****************************\")\n print(\"recursive\")\n post_order_traverse_recursive(head_node)\n print(\"\\n\")\n print(\"cycle\")\n post_order_traverse_cycle(head_node)\n print(\"\\n\")\n print(\"layer traversal*****************************\")\n layer_traverse(head_node)","sub_path":"binaryTree/treeTraverse.py","file_name":"treeTraverse.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161514027","text":"\"\"\"The genome to be evolved.\"\"\"\n\nimport random\nimport logging\nimport hashlib\nimport copy\n\nfrom GA.evolve_cnn.train import train_and_score\n\n\nclass Genome():\n \"\"\"\n Represents one genome and all relevant utility functions (add, mutate, etc.).\n \"\"\"\n\n def __init__(self, all_possible_genes=None, geneparam={}, u_ID=0, mom_ID=0, dad_ID=0, gen=0):\n \"\"\"Initialize a genome.\n\n Args:\n all_possible_genes (dict): Parameters for the genome, includes:\n gene_nb_neurons (list): [64, 128, 256]\n gene_nb_layers (list): [1, 2, 3, 4]\n gene_activation (list): ['relu', 'elu']\n gene_optimizer (list): ['rmsprop', 'adam']\n gene_dropout (list): [ 0. , 0.075, 0.15 , 0.225, 0.3 ]\n gene_weight_decay (list): [ 0. , 0.075, 0.15 , 0.225, 0.3 ]\n gene_size: [2,3,5,10]\n gene_batch_norm: [True,False]\n gene_filters: [16, 32, 64, 128]\n gene_size: [2,3,5,10]\n gene_stride: [\"equal\",\"one\"]\n gene_nb_cnn_layers': [1, 2, 3]\n \"\"\"\n self.r = -1.0\n self.all_possible_genes = all_possible_genes\n self.geneparam = geneparam # (dict): represents actual genome parameters\n self.u_ID = u_ID\n self.parents = [mom_ID, dad_ID]\n self.generation = gen\n\n # hash only makes sense when we have specified the genes\n if not geneparam:\n self.hash = 0\n else:\n self.update_hash()\n\n def update_hash(self):\n \"\"\"\n Refesh each genome's unique hash - needs to run after any genome changes.\n all_possible_genes = {\n 'nb_neurons': [16, 32, 64, 128],\n 'nb_layers': [1, 2, 3],\n 'nb_cnn_layers': [1, 2, 3],\n 'batch_norm': [True,False],\n 'activation': ['relu', 'elu', 'softplus', 'linear'],\n 'optimizer': ['rmsprop', 'nadam'],\n 'dropout': [0., 0.075],\n 'filters': [16, 32, 64, 128],\n 'size_window': [2,3,5,10],\n 'stride' : [\"equal\",\"one\"],\n 'weight_decay': [0., 0.075]\n }\n \"\"\"\n genh = str(self.geneparam['nb_neurons']) + self.geneparam['activation'] \\\n + str(self.geneparam['nb_layers']) + self.geneparam['optimizer'] \\\n + str(self.geneparam['dropout']) + str(self.geneparam['weight_decay']) \\\n + str(self.geneparam['nb_cnn_layers']) + str(self.geneparam['batch_norm']) \\\n + str(self.geneparam['filters']) + str(self.geneparam['size_window']) + self.geneparam['stride']\n\n self.hash = hashlib.sha256(genh.encode(\"UTF-8\")).hexdigest()\n\n self.r = -1.0\n\n def set_genes_random(self):\n \"\"\"Create a random genome.\"\"\"\n # print(\"set_genes_random\")\n self.parents = [0, 0] # very sad - no parents :(\n\n for key in self.all_possible_genes:\n self.geneparam[key] = random.choice(self.all_possible_genes[key])\n\n self.update_hash()\n\n def mutate_one_gene(self):\n \"\"\"Randomly mutate one gene in the genome.\n\n Args:\n network (dict): The genome parameters to mutate\n\n Returns:\n (Genome): A randomly mutated genome object\n\n \"\"\"\n # Which gene shall we mutate? Choose one of N possible keys/genes.\n gene_to_mutate = random.choice(list(self.all_possible_genes.keys()))\n\n # And then let's mutate one of the genes.\n # Make sure that this actually creates mutation\n current_value = self.geneparam[gene_to_mutate]\n possible_choices = copy.deepcopy(self.all_possible_genes[gene_to_mutate])\n\n possible_choices.remove(current_value)\n\n self.geneparam[gene_to_mutate] = random.choice(possible_choices)\n\n self.update_hash()\n\n def set_generation(self, generation):\n \"\"\"needed when a genome is passed on from one generation to the next.\n the id stays the same, but the generation is increased\"\"\"\n\n self.generation = generation\n # logging.info(\"Setting Generation to %d\" % self.generation)\n\n def set_genes_to(self, geneparam, mom_ID, dad_ID):\n \"\"\"Set genome properties.\n this is used when breeding kids\n\n Args:\n genome (dict): The genome parameters\n IMPROVE\n \"\"\"\n self.parents = [mom_ID, dad_ID]\n\n self.geneparam = geneparam\n\n self.update_hash()\n\n def train(self, trainingset):\n \"\"\"Train the genome and record the accuracy.\n\n Args:\n trainingset (str): Name of dataset to use.\n\n \"\"\"\n if self.r == -1.0:\n self.r = train_and_score(self.geneparam, trainingset)\n\n def print_genome(self):\n \"\"\"Print out a genome.\"\"\"\n logging.info(self.geneparam)\n logging.info(\"R: %.2f%%\" % self.r)\n logging.info(\"UniID: %d\" % self.u_ID)\n logging.info(\"Mom and Dad: %d %d\" % (self.parents[0], self.parents[1]))\n logging.info(\"Gen: %d\" % self.generation)\n logging.info(\"Hash: %s\" % self.hash)\n\n def print_genome_ma(self):\n \"\"\"Print out a genome.\"\"\"\n logging.info(self.geneparam)\n logging.info(\"R: %.2f%% UniID: %d Mom and Dad: %d %d Gen: %d\" % (\n self.r, self.u_ID, self.parents[0], self.parents[1], self.generation))\n logging.info(\"Hash: %s\" % self.hash)\n","sub_path":"GA/evolve_cnn/genome.py","file_name":"genome.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"555474788","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 23 00:08:05 2017\n\nHistory:\n 2017-11-01 First version based on dlib\n 2017-12-08 Added TF based inference (using Keras model)\n 2017-12-11 Added face alignment\n\n\"\"\"\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom collections import OrderedDict\nimport cv2\nimport pandas as pd\nimport numpy as np\nimport os\n\nfrom scipy.misc import imresize\n\nfrom uploads.core.obj_detect_api.omni_utils import LoadLogger\nfrom uploads.core.obj_detect_api.omni_camera_utils import VideoCameraStream, np_rect, np_circle\n\nfrom uploads.core.obj_detect_api.omni_utils import FacialLandmarks\nfrom uploads.core.obj_detect_api.omni_utils import INNER_EYES_AND_BOTTOM_LIP, OUTER_EYES_AND_NOSE\nfrom uploads.core.obj_detect_api.omni_utils import TEMPLATE, INV_TEMPLATE, TPL_MIN, TPL_MAX, MINMAX_TEMPLATE\n\nimport tensorflow as tf\nfrom keras.models import load_model\nimport keras.backend as K\n\n__module__ = \"OmniFR\"\n__version__ = \"0.2.tf14\"\n__author__ = \"Andrei Ionut Damian\"\n__copyright__ = \"(C) Knowledge Investment Group\"\n__project__ = \"OmniDJ\"\n\n_METHODS_ = ['dlib', 'tf', 'keras']\n\ntry:\n import dlib\nexcept:\n print(\"Running without dlib\")\n\n\n\nFACIAL_LANDMARKS = OrderedDict([\n\t(FacialLandmarks.FL_MOUTH, (48, 68)),\n\t(FacialLandmarks.FL_REYEB, (17, 22)),\n\t(FacialLandmarks.FL_LEYEB, (22, 27)),\n\t(FacialLandmarks.FL_REYE, (36, 42)),\n\t(FacialLandmarks.FL_LEYE, (42, 48)),\n\t(FacialLandmarks.FL_NOSE, (27, 35)),\n\t(FacialLandmarks.FL_JAW, (0, 17))\n])\n \n\n\n\ndef is_shape(name, nr):\n assert name in FacialLandmarks.FL_SET\n return (nr>=FACIAL_LANDMARKS[name][0]) and (nr 0:\n dists = (embed_matrix - embed)**2\n dists = np.sum(dists, axis = 1)\n dists = np.sqrt(dists)\n result = dists\n return result\n\n\n def get_id_vs_all(self, pers_id):\n embed = self.df_faces[self.df_faces[self.ID_FIELD] == pers_id][self.feats_names].values.ravel()\n other_df = self.df_faces[self.df_faces[self.ID_FIELD] != pers_id]\n other_df_short = other_df[[self.ID_FIELD, self.NAME_FIELD]].copy()\n other_embeds = other_df[self.feats_names].values \n other_df_short.loc[:,'DIST'] = list(self._get_distances(embed, other_embeds))\n return other_df_short\n\n ##\n ## Face Align zone \n ##\n\n def FaceAlign(self, np_img, landmarks, inds = INNER_EYES_AND_BOTTOM_LIP,\n img_dim = 160, scale = 1.0, simple_crop=None):\n \"\"\"\n tries to align a face based on landmarks\n \"\"\"\n if self.DEBUG: \n self.logger.start_timer(\" FaceAlign\")\n if simple_crop is not None:\n left, top, right, bottom = simple_crop\n thumbnail = np_img[top:bottom,left:right,:].copy()\n else: \n np_landmarks = np.float32(landmarks)\n np_land_inds = np.array(inds)\n \n # pylint: disable=maybe-no-member\n p1 = np_landmarks[np_land_inds]\n p2 = img_dim * MINMAX_TEMPLATE[np_land_inds] * scale + img_dim * (1 - scale) / 2\n H = cv2.getAffineTransform(p1, p2)\n thumbnail = cv2.warpAffine(np_img, H, (img_dim, img_dim))\n\n if self.DEBUG: \n self.logger.end_timer(\" FaceAlign\")\n self.log(\" OmniFR: FaceAlign in: {} out:{}\".format(np_img.shape,\n thumbnail.shape))\n return thumbnail\n \n \n \n ##\n ## END Face Align zone \n ##\n \n def GetFaceInfo(self, np_image, get_shape = True, get_id_name = True,\n get_thumb = True):\n \"\"\"\n returns a tuple (BOX, SHAPE, EMBED, ID, NAME, IMG, DIST) containing \n facial info such as:\n BOX - LTRB tuple if face detected in frame or None otherwise\n SHAPE - facial landmarks if get_shape\n EMBED - embedding vector if get_embed\n ID - db user ID if get_id_name\n NAME - db user name if get_id_name\n IMG - resized/realigned image of the face \n DIST - distance from the re-identified person \n \"\"\"\n _found_box = None\n _shape = None\n _embed = None\n _id = None\n _name = \"???\"\n _np_resized = None\n _dist = 0\n self.logger.start_timer(\" FaceDetect\")\n fbox, _found_box = self.face_detect(np_image) \n self.logger.end_timer(\" FaceDetect\")\n if get_shape and (fbox != None):\n self.logger.start_timer(\" FaceLandmarks\")\n landmarks, _shape = self.face_landmarks(np_image, fbox)\n self.logger.start_timer(\" FaceLandmarks\")\n if landmarks != None:\n \n if get_thumb or self.method == 'keras':\n _np_resized = self.FaceAlign(np_img = np_image, \n landmarks = _shape, \n inds = INNER_EYES_AND_BOTTOM_LIP,\n img_dim = self._tf_input_HW[0], \n scale = 1.0)\n if get_id_name:\n fr_res = self.face_id_maybe_save(np_img = np_image, \n dlib_landmarks = landmarks,\n np_box = _found_box,\n np_img_resized = _np_resized)\n _id, _name, _embed, _dist = fr_res\n return (_found_box, _shape, _embed, _id, _name, _np_resized, _dist)\n \n \n def _get_current_matrix(self):\n np_matrix = self.df_faces[self.feats_names].values\n return np_matrix\n \n def _save_data(self):\n self.df_faces.to_csv(self.data_file, index = False)\n return\n \n def _find_closest_embedding(self, embed):\n \"\"\"\n given (NR_EMBEDDINGS,) vector finds closest embedding and returns ID\n \"\"\"\n result = -1\n min_dist = -1\n np_embeds = self._get_current_matrix()\n if np_embeds.shape[0] > 0:\n dists = (np_embeds - embed)**2\n dists = np.sum(dists, axis = 1)\n dists = np.sqrt(dists)\n min_dist = np.min(dists)\n if min_dist <= self.score_threshold:\n result = np.argmin(dists) \n if self.DEBUG:\n self.log(\" OmniFR: [Idx:{} Dist:{:3f}]\".format(\n result, min_dist))\n return result, min_dist\n \n \n def _create_identity(self, embed):\n \"\"\"\n receives embed and creates new identity in data store\n returns ID and Name\n \"\"\"\n pers_id = self.df_faces.shape[0] + 10\n pers_name = \"PERSOANA_#{}\".format(pers_id)\n rec = {}\n rec[self.ID_FIELD] = pers_id\n rec[self.NAME_FIELD] = pers_name\n for i, col in enumerate(self.feats_names):\n rec[col] = embed[i]\n \n self.last_rec = rec\n self.df_faces = self.df_faces.append(rec, ignore_index = True)\n self._save_data()\n if self.DEBUG:\n self.log(\" OmniFR: Created new identity {}\".format(\n pers_name))\n return pers_id, pers_name\n\n\n def _get_name_by_id(self, idpers, use_index = False):\n if use_index:\n sname = self.df_faces.loc[idpers,self.NAME_FIELD]\n else:\n sname = self.df_faces[self.df_faces[self.ID_FIELD]==idpers].loc[0,self.NAME_FIELD]\n return sname\n\n \n def _get_id_by_index(self, idx):\n return self.df_faces.loc[idx,self.ID_FIELD]\n \n \n def __dl_face_embed(self, np_img, dl_shape):\n return self._dlib_face_recog.compute_face_descriptor(np_img, dl_shape)\n \n def __tf_face_embed(self, np_img, np_ltrb = None):\n \"\"\"\n np_img MUST be HWC but will be converted to appropriate format\n np_ltrb is LTRB format box\n \"\"\"\n assert len(np_img.shape) == 3\n if np_ltrb is not None:\n L,T,R,B = np_ltrb\n np_img = np_img[T:B,L:R,:].copy()\n self.log(\" OmniFR: Running TF inference on {}\".format(np_img.shape))\n \n if np_img.shape[0:2] != self._tf_input_HW:\n np_img = imresize(np_img, self._tf_input_HW)\n \n if self._model_channels == 'channels_first':\n np_img = np_img.T\n \n np_img = np.expand_dims(np_img, axis = 0) / 255\n prev_ch = K.image_data_format()\n K.set_image_data_format(self._model_channels)\n \n if self.method == 'keras':\n lr_phase = K.learning_phase()\n else:\n lr_phase = self._tf_graph.get_tensor_by_name(self._tf_tensors_config[\"LEARNING_PHASE_TENSOR\"])\n embed = self.sess.run(self._tf_fr_output,\n feed_dict = {self._tf_fr_input : np_img,\n lr_phase : 0})\n K.set_image_data_format(prev_ch)\n embed = embed.ravel()\n return embed\n\n\n def get_face_embed(self, np_img, dl_shape = None, np_LTRB = None):\n \"\"\"\n np_img: either full picture or just cropped\n dl_shape: landmarks from dlib\n np_LTRB: left, top, right, bottom used in tf inference preprocessing\n \"\"\"\n if self.DEBUG:\n self.logger.start_timer(\" FaceEMBED\") \n self.log(\" OmniFR: {}.FR on {} image\".format(self.method, np_img.shape))\n _result = None\n if self.method == 'dlib':\n assert dl_shape != None\n self.logger.start_timer(\" FaceEMBED_DLIb\")\n _result = self.__dl_face_embed(np_img, dl_shape = dl_shape)\n self.logger.end_timer(\" FaceEMBED_DLIb\")\n elif self.method in ['tf', 'keras']:\n self.logger.start_timer(\" FaceEMBED_TF\")\n _result = self.__tf_face_embed(np_img) # np_ltrb = np_LTRB)\n _DEBUG_tf = self.logger.end_timer(\" FaceEMBED_TF\")\n if self.DEBUG:\n self.log(\" OmniFR: {}.FR Time: {:.4f}s\".format(self.method,_DEBUG_tf))\n self.logger.end_timer(\" FaceEMBED\") \n \n return _result\n \n \n def _get_info(self, embed):\n \"\"\"\n given generated embedding get ID, Name and L2 distance of proposed embed\n returns -1, \"\" if not found\n \"\"\"\n idx, dist = self._find_closest_embedding(embed)\n idpers = -1\n sname = \"\"\n if idx != -1:\n sname = self._get_name_by_id(idx, use_index = True)\n idpers = self._get_id_by_index(idx)\n return idpers, sname, dist\n \n def face_id_maybe_save(self, np_img, dlib_landmarks, np_box, np_img_resized):\n \"\"\"\n tries to ID face. Will return ID, Name, Embed if found or new info if NOT found\n also saves new IDs in own face datastore\n must pass np_img (H,W,C) and landmarks_shape (from face_landmarks)\n np_box is LTRB\n \"\"\"\n if self.DEBUG: self.logger.start_timer(\" FaceID\")\n result = (None, None, None)\n # get embed\n img = np_img\n if self.method in ['tf', 'keras']:\n img = np_img_resized\n embed = self.get_face_embed(img, \n dl_shape = dlib_landmarks,\n np_LTRB = np_box)\n if self.DEBUG: self.logger.start_timer(\" FaceInfo\")\n # try to find if avail\n pers_id, pers_name, dist = self._get_info(embed)\n if pers_id == -1:\n # now create new identity\n pers_id, pers_name = self._create_identity(embed)\n result = (pers_id, pers_name, embed, dist)\n if self.DEBUG: self.logger.end_timer(\" FaceInfo\")\n if self.DEBUG: self.logger.end_timer(\" FaceID\")\n return result\n \n \n def draw_facial_shape(self, np_img, np_facial_shape, left = 0, top = 0):\n self.logger.start_timer(\" DrawFacialShape\")\n for i in range(np_facial_shape.shape[0]):\n x = int(np_facial_shape[i,0]) + left\n y = int(np_facial_shape[i,1]) + top\n clr = (0,0,255)\n if is_shape(FacialLandmarks.FL_LEYE,i):\n clr = (255,255,255)\n if is_shape(FacialLandmarks.FL_REYE,i):\n clr = (0,255,255)\n np_img = np_circle(np_img, (x, y), 1, clr, -1)\n self.logger.end_timer(\" DrawFacialShape\")\n return np_img\n\n\n \n def face_detect(self, np_img, upsample_detector = 0):\n \"\"\"\n face detector - will return 1st bounding box both in dlib format and tuple format\n will return None if nothing found\n \"\"\"\n boxes = self._face_detector(np_img, upsample_detector)\n result = (None, None)\n if len(boxes)>0:\n box = boxes[0]\n LTRB = (box.left(),box.top(),box.right(),box.bottom())\n result = (box, LTRB)\n return result\n \n def multi_face_detect(self, np_img, upsample_detector = 0):\n \"\"\"\n returns Dlib boxes and LTRB tuples list\n will return None if nothing found\n \"\"\"\n if self.DEBUG: # half-redundant\n self.logger.start_timer(\" FaceDetector\")\n boxes = self._face_detector(np_img, upsample_detector)\n if self.DEBUG: # half-redundant\n self.logger.end_timer(\" FaceDetector\")\n result = (None, None)\n if len(boxes) > 0:\n LTRB_list = []\n for box in boxes:\n LTRB = (box.left(), box.top(), box.right(), box.bottom())\n LTRB_list.append(LTRB)\n result = (boxes, LTRB_list)\n \n return result\n\n\n def face_landmarks(self, np_img, dlib_box, large_landmarks = True):\n \"\"\"\n face landmarks generator - will return numpy array of [points,2] or None if\n nothing found\n \"\"\"\n result = (None,None)\n\n if large_landmarks:\n func = self._shape_large_model\n nr_land = 68\n else:\n func = self._shape_small_model\n nr_land = 5\n \n landmarks = func(np_img, dlib_box)\n np_landmarks = np.zeros((nr_land,2))\n for i in range(nr_land):\n np_landmarks[i] = (landmarks.part(i).x, landmarks.part(i).y)\n \n result = landmarks, np_landmarks\n \n return result\n \n def GetFaceCropFromLandmarks(self, np_landmarks):\n top = min(np_landmarks[:,1])\n left = min(np_landmarks[:,0])\n right = max(np_landmarks[:,0])\n bottom = max(np_landmarks[:,1])\n \n w = right - left\n h = bottom - top\n \n top -= h * 0.25\n bottom += h * 0.1\n left -= w * 0.15\n right += w * 0.15\n \n return int(left), int(top), int(right), int(bottom)\n \n \n \n def full_scene_process(self, np_img):\n \n SHOW_THUMB = True\n USE_DLIB_LTRB = True\n\n self.logger.start_timer(\" FullSceneProcess\")\n np_out_img = np_img.copy()\n \n #first stage detect all faces\n self.logger.start_timer(\" MultiFaceDetect\")\n boxes, ltrb_list = self.multi_face_detect(np_img)\n self.logger.end_timer(\" MultiFaceDetect\")\n \n #now process each face !\n if not (boxes is None):\n self.logger.start_timer(\" MultiFR\")\n self.log(\" OmniFR: Processing {} faces\".format(len(ltrb_list)))\n for i, LTRB in enumerate(ltrb_list):\n self.log(\" OmniFR: Face:{} LTRB:{}\".format(i,LTRB))\n box = boxes[i]\n self.logger.start_timer(\" MultiFaceLandmarks\")\n landmarks, np_shape = self.face_landmarks(np_img, box)\n simple_crop = self.GetFaceCropFromLandmarks(np_shape)\n self.log(\" OmniFR: Landmarks LTRB: {}\".format(simple_crop))\n \n if USE_DLIB_LTRB:\n simple_crop = LTRB\n \n if min(simple_crop) < 0:\n self.log(\" OmniFR: SKIP\")\n continue\n self.logger.end_timer(\" MultiFaceLandmarks\")\n self.logger.start_timer(\" MultiFaceID\")\n _np_resized = None\n if self.method in ['tf', 'keras']:\n _np_resized = self.FaceAlign(np_img = np_img, \n landmarks = np_shape, \n inds = INNER_EYES_AND_BOTTOM_LIP,\n img_dim = self._tf_input_HW[0], \n scale = 1.0,\n simple_crop=simple_crop)\n #endif\n _id, _name, _embed, _dist = self.face_id_maybe_save(np_img, \n landmarks, \n LTRB,\n _np_resized)\n _DEBUG_face_id = self.logger.end_timer(\" MultiFaceID\")\n self.log(\" OmniFR: Face [{}/{}/{:.2f}] identified in {:.3f}s\".format(\n _id, _name, _dist, _DEBUG_face_id))\n np_out_img = self.draw_facial_shape(np_out_img, np_shape)\n np_out_img = np_rect(LTRB[0], LTRB[1], LTRB[2], LTRB[3], np_out_img,\n color = (0,255,0), text = _name + ' D:{:.3f}'.format(_dist)) \n # end all faces\n if SHOW_THUMB:\n t_h = _np_resized.shape[0]\n t_w = _np_resized.shape[1]\n np_out_img[:t_h,-t_w:,:] = _np_resized\n \n self.logger.end_timer(\" MultiFR\")\n \n _DEBUG_full_scene = self.logger.end_timer(\" FullSceneProcess\")\n if self.DEBUG:\n self.log(\" OmniFR Full scene inference and draw time {:.3f}s\".format(\n _DEBUG_full_scene))\n return np_out_img\n \n\n \n \n \nif __name__ == '__main__':\n fr_method = 'tf'\n omnifr = FaceEngine(DEBUG = True, fr_method = fr_method)\n\n vstrm = VideoCameraStream(logger = omnifr.logger,\n process_func = omnifr.full_scene_process, \n info_func = None) \n if vstrm.video != None:\n video_frame_shape = (vstrm.H,vstrm.W) \n vstrm.play()\n vstrm.shutdown()\n\n omnifr.show_run_stats()\n\n ","sub_path":"00_libs/00_WebCfodDemo/uploads/core/obj_detect_api/omni_face_eng.py","file_name":"omni_face_eng.py","file_ext":"py","file_size_in_byte":25280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192440566","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# Front Matter {{{\n'''\nCopyright (c) 2016 The Broad Institute, Inc. All rights are reserved.\n\nThis file is part of GDCtools. See the /COPYRIGHT file for the\nSOFTWARE COPYRIGHT and WARRANTY NOTICE.\n\n@author: Michael S. Noble\n@date: 2016-05-18\n'''\n\n# }}}\n\nimport sys\nimport argparse\nfrom gdctools.GDCcore import *\n\n# Stop Python from complaining when I/O pipes are closed\nfrom signal import signal, SIGPIPE, SIG_DFL\nsignal(SIGPIPE, SIG_DFL)\n\nclass GDCcli(argparse.ArgumentParser):\n ''' Encapsulates interactions with the command line, making it easy for\n all gdctools to share a core set of common CLI self.args. '''\n\n ALL_REMAINING_ARGS = argparse.REMAINDER\n\n def __init__(self, descrip=None, version=\"\"):\n\n if not descrip:\n descrip = 'GDCtools: a suite of CLI tools plus Python bindings\\n'\n descrip += 'to simplify interaction with the Genomic Data Commons\\n'\n descrip += 'and perform useful data processing operations. The\\n'\n descrip += 'GDCtools suite was inspired by the data processing\\n'\n descrip += 'done by Firehose & FireBrowse in the Broad Institute\\n'\n descrip += 'GDAC, as part of the The Cancer Genome Atlast.\\n'\n\n version = version + \" (GDCtools: \" + GDCT_VERSION + \")\"\n self.version = version\n super(GDCcli, self).__init__(description=descrip,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n # Note that args with nargs=+ will be instantiated as lists\n self.add_argument('--verbose', dest='verbose', action='count', help=\\\n 'Each time specified, increment verbosity level [%(default)s]')\n self.add_argument('--version',action='version', version=version)\n self.add_argument('-c','--config', nargs='+', type=argparse.FileType('r'),\n help='One or more configuration files')\n\n self.add_argument('-l', '--log-dir',\n help='Directory where logfiles will be written')\n self.add_argument('-g', '--programs', nargs='+', metavar='program',\n help='Process data ONLY from these GDC programs')\n self.add_argument('-p', '--projects', nargs='+', metavar='project',\n help='Process data ONLY from these GDC projects')\n self.add_argument('--cases', nargs='+', metavar='case_id',\n help='Process data ONLY from these GDC cases')\n self.add_argument('datestamp', nargs='?', help='Use GDC data for a'\n ' specific date. If omitted, the latest available'\n ' data will be used.')\n\n def parse_args(self):\n return super(GDCcli,self).parse_args()\n\n def ok_to_continue(self, message=None):\n\n if message:\n gprint(message)\n\n gprint(\"If this is OK, shall I continue? (Y/N) [N]\",end=' ')\n sys.stdout.flush()\n answer = sys.stdin.readline().rstrip('\\n')\n gprint('')\n if answer not in [\"y\", \"yes\", \"Y\", \"Yes\", '1', 'true']:\n gprint(\"OK, exiting without doing anything further.\")\n sys.exit(0)\n\nif __name__ == \"__main__\":\n cli = GDCcli()\n options = cli.parse_args()\n gprint(str(options))\n","sub_path":"gdctools/GDCcli.py","file_name":"GDCcli.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397090351","text":"from __future__ import absolute_import, division, print_function\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nimport tensorflow_datasets as tfds\r\nimport tensorflow_hub as hub\r\nimport cv2\r\nimport time\r\nCLASSIFIER_URL = \"http://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4\"\r\nIMAGE_RES = 224\r\nmodel = tf.keras.Sequential([\r\n hub.KerasLayer(CLASSIFIER_URL, input_shape = (IMAGE_RES,IMAGE_RES, 3))\r\n])\r\n\r\nimport numpy as np\r\nimport PIL.Image as Image\r\n\r\nsplits = tfds.Split.ALL.subsplit(weighted=(80, 20))\r\nsplits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split= splits)\r\n(train_examples, validation_examples) = splits\r\nnum_examples = info.splits['train'].num_examples\r\nnum_classes = info.features['label'].num_classes\r\n\r\nlabels_path = tf.keras.utils.get_file('ImageNetLabels.txt','http://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')\r\nimagenet_labels = np.array(open(labels_path).read().splitlines())\r\n\r\nfor i, example_image in enumerate(train_examples.take(3)):\r\n print('Image {} shape: {}'.format(i+1, example_image[0].shape))\r\n\r\ndef format_image(image, label):\r\n image = tf.image.resize(image, (IMAGE_RES,IMAGE_RES))/255.0\r\n return image, label\r\nBATCH_SIZE = 32\r\ntrain_batches = train_examples.shuffle(num_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1)\r\nvalidation_batches = validation_examples.map(format_image).batch(BATCH_SIZE).prefetch(1)\r\n\r\nimage_batch, label_batch = next(iter(train_batches.take(1)))\r\nimage_batch = image_batch.numpy()\r\nlabel_batch = label_batch.numpy()\r\nresult_batch = model.predict(image_batch)\r\n\r\npredicted_class_names = imagenet_labels[np.argmax(result_batch, axis=-1)]\r\nplt.figure(figsize=(10,9))\r\nfor n in range(30):\r\n plt.subplot(6,5,n+1)\r\n plt.imshow(image_batch[n])\r\n plt.title(predicted_class_names[n])\r\n plt.axis('off')\r\n _ = plt.suptitle('Imagenet prediction')\r\nplt.show()\r\n\r\n# Tensorflow hub is used for calling partial model, this model will take input do all processings to extract feature of image except producing the probability of the output class\r\nURL = \"http://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4\"\r\nfeature_extractor = hub.KerasLayer(URL, input_shape = (IMAGE_RES, IMAGE_RES, 3))\r\n\r\nfeature_batch = feature_extractor(image_batch)\r\nprint(feature_batch.shape)\r\n\r\nfeature_extractor.trainable = False\r\n\r\nmodel = tf.keras.Sequential([\r\n feature_extractor,\r\n tf.keras.layers.Dense(2, activation = 'softmax')\r\n])\r\nmodel.summary()\r\n\r\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\r\nmodel.summary() #chk model summary\r\n\r\nepochs = 6\r\nhistory = model.fit(train_batches, epochs = epochs, validation_data = validation_batches)\r\n\r\nacc = history.history['acc']\r\nval_acc = history.history['val_acc']\r\n\r\nloss = history.history['loss']\r\nval_loss = history.history['val_loss']\r\n\r\nepochs_range = range(epochs)\r\nplt.figure(figsize=(0,0))\r\nplt.subplot(1,2,1)\r\nplt.plot(epochs_range, acc, label = 'Training Accuracy')\r\nplt.plot(epochs_range, val_acc, label = 'Validation Accuracy')\r\nplt.legend(loc = 'lower right')\r\nplt.title('Training and validation accuracy')\r\n\r\nplt.subplot(1,2,2)\r\nplt.plot(epochs_range, loss, label = 'Training Loss')\r\nplt.plot(epochs_range, val_loss, label = 'Validation Loss')\r\nplt.legend(loc = 'upper right')\r\nplt.title('Training and validation Loss')\r\nplt.show()\r\n\r\nclass_names = np.array(info.features['label'].names)\r\nprint(class_names)\r\n\r\npredicted_batch = model.predict(image_batch)\r\npredicted_batch = tf.squeeze(predicted_batch).numpy() #Removes dimensions of size 1 from the shape of a tensor\r\npredicted_ids = np.argmax(predicted_batch, axis = -1)\r\npredicted_class_names = class_names[predicted_ids]\r\nprint(predicted_class_names)\r\n\r\nprint(\"Labels:\", label_batch)\r\nprint(\"Predicted labels\", predicted_ids)\r\n\r\nplt.figure(figsize=(10,9))\r\nfor n in range(30):\r\n plt.subplot(6, 5, [n])\r\n color = 'blue' if predicted_ids[n]== label_batch[n] else\"red\"\r\n plt.title(predicted_class_names[n].title(), color = color)\r\n plt.axis('off')\r\n _ = plt.suptitle(\"Model prediction (blue: correct, red: incorrect)\")\r\n plt.imshow\r\n","sub_path":"TensorFlow_Tutorials/8.1.Transfer Learning with Cats and Dogs.py","file_name":"8.1.Transfer Learning with Cats and Dogs.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270855753","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\n\nurlpatterns = patterns('',\n url(r'^$', 'feedback.views.home', name='home'),\n url(r'^feedback/', include('feedback.urls', namespace=\"feedback\")),\n url(r'^getmail/', 'feedback.views.getmail', name='getmail'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^instructions/$', 'feedback.views.instruction', name='instruction'),\n url(r'^analytics/(?P
[A-Za-z]{2})/$', 'feedback.views.analytics'),\n url(r'^login/$', 'feedback.views.login_user', name='login_user'),\n url(r'^analytics/$', 'feedback.views.depart', name='department'),\n url(r'^logout/$', 'feedback.views.logout_user', name='logout_user'),\n url(r'^credits/$', 'feedback.views.credits', name='credits'),\n )\n\n","sub_path":"coursefeedback/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"1832828","text":"# Copyright 2017, Wenjia Bai. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport scipy.ndimage.interpolation\nimport skimage.transform\nimport nibabel as nib\n\n# import medpy.metric\n\n\ndef to_one_hot(array, depth):\n array_reshaped = np.reshape(array, -1).astype(np.uint8)\n array_one_hot = np.zeros((array_reshaped.shape[0], depth))\n array_one_hot[np.arange(array_reshaped.shape[0]), array_reshaped] = 1\n array_one_hot = np.reshape(array_one_hot, array.shape + (-1,))\n\n return array_one_hot\n\n\ndef tf_categorical_accuracy(pred, truth):\n \"\"\" Accuracy metric \"\"\"\n return tf.reduce_mean(tf.cast(tf.equal(pred, truth), dtype=tf.float32))\n\n\ndef tf_categorical_dice(pred, truth, k, axis, name):\n \"\"\" Dice overlap metric for label k \"\"\"\n A = tf.cast(tf.equal(pred, k), dtype=tf.float32)\n B = tf.cast(tf.equal(truth, k), dtype=tf.float32)\n\n numerator = 2 * tf.reduce_sum(tf.multiply(A, B), axis=axis)\n denominator = tf.reduce_sum(A, axis=axis) + tf.reduce_sum(B, axis=axis)\n\n return tf.divide(numerator, (denominator + 1e-7), name=name)\n\n\ndef get_dice_coef(prediction_probabilities, true_mask_one_hot, num_classes, name, axis, soft=False, smooth=0):\n if soft:\n prediction_mask_per_class = prediction_probabilities\n else:\n prediction_mask = tf.argmax(prediction_probabilities, axis=-1) # (batch_size, image_size_x, image_size_y)\n prediction_mask_per_class = tf.one_hot(prediction_mask, depth=num_classes, axis=-1,\n dtype=tf.float32) # (batch_size, image_size_x, image_size_y, num_classes)\n\n true_mask_one_hot = tf.to_float(true_mask_one_hot)\n\n numerator = 2 * tf.reduce_sum(tf.multiply(true_mask_one_hot, prediction_mask_per_class), axis=axis)\n denominator = tf.reduce_sum(true_mask_one_hot, axis=axis) + tf.reduce_sum(prediction_mask_per_class, axis=axis)\n\n return tf.divide(numerator + smooth, (denominator + smooth + 1e-7), name=name)\n\n\ndef get_accuracy(prediction_probabilities, true_mask_one_hot, name):\n prediction_mask = tf.argmax(prediction_probabilities, axis=-1)\n true_mask = tf.argmax(true_mask_one_hot, axis=-1)\n\n accuracy = tf.equal(prediction_mask, true_mask)\n\n return tf.reduce_mean(tf.cast(accuracy, tf.float32), name=name)\n\n\ndef crop_image(image, cx, cy, size, constant_values=0):\n \"\"\" Crop a 3D image using a bounding box centred at (cx, cy) with specified size \"\"\"\n X, Y = image.shape[:2]\n rX = int(size[0] / 2)\n rY = int(size[1] / 2)\n x1, x2 = cx - rX, cx + rX\n y1, y2 = cy - rY, cy + rY\n x1_, x2_ = max(x1, 0), min(x2, X)\n y1_, y2_ = max(y1, 0), min(y2, Y)\n # Crop the image\n crop = image[x1_: x2_, y1_: y2_]\n # Pad the image if the specified size is larger than the input image size\n if crop.ndim == 3:\n crop = np.pad(crop,\n ((x1_ - x1, x2 - x2_), (y1_ - y1, y2 - y2_), (0, 0)),\n 'constant', constant_values=constant_values)\n elif crop.ndim == 4:\n crop = np.pad(crop,\n ((x1_ - x1, x2 - x2_), (y1_ - y1, y2 - y2_), (0, 0), (0, 0)),\n 'constant', constant_values=constant_values)\n else:\n print('Error: unsupported dimension, crop.ndim = {0}.'.format(crop.ndim))\n exit(0)\n return crop\n\n\ndef crop_image_3d(image, cx, cy, cz, size, constant_values=0):\n \"\"\" Crop a 3D image using a bounding box centred at (cx, cy, cz) with specified size \"\"\"\n X, Y, Z = image.shape[:3]\n rX = int(size[0] / 2)\n rY = int(size[1] / 2)\n rZ = int(size[2] / 2)\n x1, x2 = cx - rX, cx + rX\n y1, y2 = cy - rY, cy + rY\n z1, z2 = cz - rZ, cz + rZ\n x1_, x2_ = max(x1, 0), min(x2, X)\n y1_, y2_ = max(y1, 0), min(y2, Y)\n z1_, z2_ = max(z1, 0), min(z2, Z)\n # Crop the image\n crop = image[x1_: x2_, y1_: y2_, z1_: z2_]\n # Pad the image if the specified size is larger than the input image size\n if crop.ndim == 3:\n crop = np.pad(crop,\n ((x1_ - x1, x2 - x2_), (y1_ - y1, y2 - y2_), (z1_ - z1, z2 - z2_)),\n 'constant', constant_values=constant_values)\n elif crop.ndim == 4:\n crop = np.pad(crop,\n ((x1_ - x1, x2 - x2_), (y1_ - y1, y2 - y2_), (z1_ - z1, z2 - z2_), (0, 0)),\n 'constant', constant_values=constant_values)\n else:\n print('Error: unsupported dimension, crop.ndim = {0}.'.format(crop.ndim))\n exit(0)\n return crop\n\n\ndef crop_based_on_label(image, label, pred, prob, crop_factor=1.0):\n crop_range = np.argwhere(label)\n y_size, x_size, _ = label.shape\n (ystart, xstart, _), (ystop, xstop, _) = crop_range.min(0), crop_range.max(0) + 1\n\n crop_factor = max(1.0, crop_factor)\n\n # Find the bounds of the crop with the same center point for all crop factors\n\n range_y = ystop - ystart\n ymid = ystart + range_y / 2.0\n ymin, ymax = ymid - crop_factor * (range_y / 2.0), ymid + crop_factor * (range_y / 2.0)\n\n range_x = xstop - xstart\n xmid = xstart + range_x / 2.0\n xmin, xmax = xmid - crop_factor * (range_x / 2.0), xmid + crop_factor * (range_x / 2.0)\n\n # Ensure the bounds are within the image\n ymin, ymax = max(0, ymin), min(y_size, ymax)\n xmin, xmax = max(0, xmin), min(x_size, xmax)\n\n ymin, ymax, xmin, xmax = int(ymin), int(ymax), int(xmin), int(xmax)\n\n image_crop, label_crop, pred_crop, prob_crop = None, None, None, None\n\n if image is not None:\n image_crop = image[ymin:ymax, xmin:xmax, :]\n\n label_crop = label[ymin:ymax, xmin:xmax, :]\n\n if pred is not None:\n pred_crop = pred[ymin:ymax, xmin:xmax, :]\n\n if prob is not None:\n prob_crop = prob[ymin:ymax, xmin:xmax, :, :]\n\n return image_crop, label_crop, pred_crop, prob_crop\n\n\ndef rescale_intensity(image, thres=(1.0, 99.0)):\n \"\"\" Rescale the image intensity to the range of [0, 1] \"\"\"\n val_l, val_h = np.percentile(image, thres)\n image2 = image\n image2[image < val_l] = val_l\n image2[image > val_h] = val_h\n image2 = (image2.astype(np.float32) - val_l) / (val_h - val_l)\n return image2\n\n\ndef zero_pad(image):\n (a, b, _) = image.shape\n front = int(np.ceil(np.abs(a - b) / 2.0))\n back = int(np.floor(np.abs(a - b) / 2.0))\n\n if a > b:\n padding = ((0, 0), (front, back), (0, 0))\n else:\n padding = ((front, back), (0, 0), (0, 0))\n\n return np.pad(image, padding, mode='constant', constant_values=0)\n\n\ndef resize_image(image, size, interpolation_order):\n return skimage.transform.resize(image, tuple(size), order=interpolation_order, mode='constant')\n\n\ndef augment_data_2d(whole_image, whole_label, preserve_across_slices, max_shift=10, max_rotate=10, max_scale=0.1):\n new_whole_image = np.zeros_like(whole_image)\n\n if whole_label is not None:\n new_whole_label = np.zeros_like(whole_label)\n else:\n new_whole_label = None\n\n for i in range(whole_image.shape[-1]):\n image = whole_image[:, :, i]\n new_image = image\n\n # For each image slice, generate random affine transformation parameters\n # using the Gaussian distribution\n if preserve_across_slices and i is not 0:\n pass\n else:\n shift_val = [np.clip(np.random.normal(), -3, 3) * max_shift,\n np.clip(np.random.normal(), -3, 3) * max_shift]\n rotate_val = np.clip(np.random.normal(), -3, 3) * max_rotate\n scale_val = 1 + np.clip(np.random.normal(), -3, 3) * max_scale\n\n new_whole_image[:, :, i] = transform_data_2d(new_image, shift_val, rotate_val, scale_val, interpolation_order=1)\n\n if whole_label is not None:\n label = whole_label[:, :, i]\n new_label = label\n new_whole_label[:, :, i] = transform_data_2d(new_label, shift_val, rotate_val, scale_val,\n interpolation_order=0)\n\n return new_whole_image, new_whole_label\n\n\ndef transform_data_2d(image, shift_value, rotate_value, scale_value, interpolation_order):\n # Apply the affine transformation (rotation + scale + shift) to the image\n row, col = image.shape\n M = cv2.getRotationMatrix2D((row / 2, col / 2), rotate_value, 1.0 / scale_value)\n M[:, 2] += shift_value\n\n return scipy.ndimage.interpolation.affine_transform(image, M[:, :2], M[:, 2], order=interpolation_order)\n\n\ndef save_nii(image, affine, header, filename):\n if header is not None:\n nii_image = nib.Nifti1Image(image, None, header=header)\n else:\n nii_image = nib.Nifti1Image(image, affine)\n\n nib.save(nii_image, filename)\n return\n\n\ndef load_nii(nii_image):\n image = nib.load(nii_image)\n affine = image.header.get_best_affine()\n image = image.get_data()\n\n return image, affine\n\n\ndef data_augmenter(image, label, shift, rotate, scale, intensity, flip):\n \"\"\"\n Online data augmentation\n Perform affine transformation on image and label,\n which are 4D tensor of shape (N, H, W, C) and 3D tensor of shape (N, H, W).\n \"\"\"\n image2 = np.zeros(image.shape, dtype=np.float32)\n label2 = np.zeros(label.shape, dtype=np.int32)\n for i in range(image.shape[0]):\n # For each image slice, generate random affine transformation parameters\n # using the Gaussian distribution\n shift_val = [np.clip(np.random.normal(), -3, 3) * shift,\n np.clip(np.random.normal(), -3, 3) * shift]\n rotate_val = np.clip(np.random.normal(), -3, 3) * rotate\n scale_val = 1 + np.clip(np.random.normal(), -3, 3) * scale\n intensity_val = 1 + np.clip(np.random.normal(), -3, 3) * intensity\n\n # Apply the affine transformation (rotation + scale + shift) to the image\n row, col = image.shape[1:3]\n M = cv2.getRotationMatrix2D((row / 2, col / 2), rotate_val, 1.0 / scale_val)\n M[:, 2] += shift_val\n for c in range(image.shape[3]):\n image2[i, :, :, c] = ndimage.interpolation.affine_transform(image[i, :, :, c],\n M[:, :2], M[:, 2], order=1)\n\n # Apply the affine transformation (rotation + scale + shift) to the label map\n label2[i, :, :] = ndimage.interpolation.affine_transform(label[i, :, :],\n M[:, :2], M[:, 2], order=0)\n\n # Apply intensity variation\n image2[i] *= intensity_val\n\n # Apply random horizontal or vertical flipping\n if flip:\n if np.random.uniform() >= 0.5:\n image2[i] = image2[i, ::-1, :, :]\n label2[i] = label2[i, ::-1, :]\n else:\n image2[i] = image2[i, :, ::-1, :]\n label2[i] = label2[i, :, ::-1]\n return image2, label2\n\n\ndef np_log_likelihood(prob, truth, num_classes):\n truth_one_hot = to_one_hot(truth, depth=num_classes)\n return np.mean(np.log(np.sum(prob * truth_one_hot, axis=-1) + 1e-7))\n\n\ndef np_categorical_dice_3d(pred, truth, num_classes):\n return np_categorical_dice(pred, truth, num_classes, axis=(0, 1, 2))\n\n\ndef np_categorical_dice(pred, truth, num_classes, axis, smooth_epsilon=None):\n pred_one_hot = to_one_hot(pred, depth=num_classes)\n truth_one_hot = to_one_hot(truth, depth=num_classes)\n\n numerator = 2 * np.sum(pred_one_hot * truth_one_hot, axis=axis)\n denominator = np.sum(pred_one_hot, axis=axis) + np.sum(truth_one_hot, axis=axis)\n\n if smooth_epsilon is None:\n return numerator / (denominator + 1e-7)\n else:\n return (numerator + smooth_epsilon) / (denominator + smooth_epsilon)\n\n\ndef np_foreground_dice(pred, truth):\n foreground_pred = np.zeros_like(pred)\n foreground_pred[pred != 0] = 1\n\n foreground_gt = np.zeros_like(truth)\n foreground_gt[truth != 0] = 1\n\n return np_categorical_dice_3d(foreground_pred, foreground_gt, num_classes=2)[1]\n\n\ndef np_categorical_volume(label, num_classes, pixel_spacing):\n volume = np.zeros(num_classes)\n\n for i in range(num_classes):\n A = (label == i).astype(np.float32)\n volume[i] = np.sum(A) * pixel_spacing[0] * pixel_spacing[1] * pixel_spacing[2]\n\n return volume\n\n\ndef np_categorical_areas(label, num_classes, pixel_spacing):\n areas = np.zeros([label.shape[-1], num_classes])\n\n for i in range(num_classes):\n A = (label == i).astype(np.float32)\n areas[:, i] = np.sum(A, axis=(0, 1)) * pixel_spacing[0] * pixel_spacing[1]\n\n return areas\n\n\ndef np_foreground_volume(label, pixel_spacing):\n foreground_label = np.zeros_like(label)\n foreground_label[label != 0] = 1\n\n return np_categorical_volume(foreground_label, num_classes=2, pixel_spacing=pixel_spacing)[1]\n\n\ndef medpy_categorical_dice(pred, truth, num_classes):\n \"\"\" Dice overlap metric for label k \"\"\"\n\n dice = np.zeros(num_classes)\n\n for i in range(num_classes):\n dice[i] = medpy.metric.dc(pred == i, truth == i)\n\n return dice\n\n\ndef np_categorical_assd_hd_per_slice(pred, truth, num_classes, pixel_spacing, fill_nan):\n num_slices = pred.shape[-1]\n assd = np.zeros([num_slices, num_classes])\n hd = np.zeros([num_slices, num_classes])\n\n for i in range(num_classes):\n assd_class_i, hd_class_i = distance_metric_2d(pred == i, truth == i, pixel_spacing, average_slices=False,\n fill_nan=fill_nan)\n assd[:, i] = np.array(assd_class_i)\n hd[:, i] = np.array(hd_class_i)\n\n return assd, hd\n\n\ndef np_categorical_assd_hd(pred, truth, num_classes, pixel_spacing):\n assd = np.zeros(num_classes)\n hd = np.zeros(num_classes)\n\n for i in range(num_classes):\n assd[i], hd[i] = distance_metric_2d(pred == i, truth == i, pixel_spacing, average_slices=True)\n\n return assd, hd\n\n\ndef np_foreground_assd_hd(pred, truth, pixel_spacing):\n foreground_pred = np.zeros_like(pred)\n foreground_pred[pred != 0] = 1\n\n foreground_gt = np.zeros_like(truth)\n foreground_gt[truth != 0] = 1\n\n return np_categorical_assd_hd(foreground_pred, foreground_gt, num_classes=2, pixel_spacing=pixel_spacing)[1]\n\n\ndef np_categorical_assd_hd_3d(pred, truth, num_classes, pixel_spacing):\n assd = np.zeros(num_classes)\n hd = np.zeros(num_classes)\n\n for i in range(num_classes):\n assd[i], hd[i] = distance_metric_3d(pred == i, truth == i, pixel_spacing)\n\n return assd, hd\n\n\ndef np_foreground_assd_hd_3d(pred, truth, pixel_spacing):\n foreground_pred = np.zeros_like(pred)\n foreground_pred[pred != 0] = 1\n\n foreground_gt = np.zeros_like(truth)\n foreground_gt[truth != 0] = 1\n\n return np_categorical_assd_hd_3d(foreground_pred, foreground_gt, num_classes=2, pixel_spacing=pixel_spacing)[1]\n\n\n# def medpy_categorical_assd_hd_3d(pred, truth, num_classes, pixel_spacing):\n# assd = np.zeros(num_classes)\n# hd = np.zeros(num_classes)\n#\n# for i in range(num_classes):\n# assd[i] = medpy.metric.assd(pred == i, truth == i, pixel_spacing)\n# hd[i] = medpy.metric.hd(pred == i, truth == i, pixel_spacing)\n#\n# return assd, hd\n#\n#\n# def medpy_categorical_assd_hd(pred, truth, num_classes, pixel_spacing):\n# assd = np.zeros(num_classes)\n# hd = np.zeros(num_classes)\n#\n# for i in range(num_classes):\n# assd_list = []\n# hd_list = []\n#\n# for z in range(pred.shape[-1]):\n# slice_A = (pred[:, :, z] == i).astype(np.uint8)\n# slice_B = (truth[:, :, z] == i).astype(np.uint8)\n#\n# # The distance is defined only when both contours exist on this slice\n# if np.sum(slice_A) > 0 and np.sum(slice_B) > 0:\n# assd_list.append(medpy.metric.assd(slice_A, slice_B, voxelspacing=pixel_spacing))\n# hd_list.append(medpy.metric.hd(slice_A, slice_B, voxelspacing=pixel_spacing))\n# else:\n# assd_list.append(np.nan)\n# hd_list.append(np.nan)\n#\n# assd[i] = np.nanmean(assd_list)\n# hd[i] = np.nanmean(hd_list)\n#\n# return assd, hd\n\n\ndef distance_metric_3d(seg_A, seg_B, pixel_spacing):\n X, Y, Z = seg_A.shape\n\n if np.sum(seg_A.astype(np.uint8)) == 0 or np.sum(seg_B.astype(np.uint8)) == 0:\n return np.nan, np.nan\n\n pts_A = []\n pts_B = []\n\n for z in range(Z):\n # Binary mask at this slice\n slice_A = seg_A[:, :, z].astype(np.uint8)\n slice_B = seg_B[:, :, z].astype(np.uint8)\n\n # Find contours and retrieve all the points\n # contours is a list with length num_contours. Each element is an array with shape (num_points, 1, 2)\n _, contours, _ = cv2.findContours(cv2.inRange(slice_A, 1, 1),\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_NONE)\n if len(contours) != 0:\n contours_array = np.concatenate(contours, axis=0)[:, 0, :]\n contours_array = np.pad(contours_array, ((0, 0), (0, 1)), 'constant', constant_values=z)\n\n pts_A.append(contours_array)\n\n _, contours, _ = cv2.findContours(cv2.inRange(slice_B, 1, 1),\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_NONE)\n if len(contours) != 0:\n contours_array = np.concatenate(contours, axis=0)[:, 0, :]\n contours_array = np.pad(contours_array, ((0, 0), (0, 1)), 'constant', constant_values=z)\n\n pts_B.append(contours_array)\n\n pts_A_array = np.concatenate(pts_A, axis=0) * pixel_spacing\n pts_B_array = np.concatenate(pts_B, axis=0) * pixel_spacing\n\n # Distance matrix between point sets\n N = np_pairwise_squared_euclidean_distance(pts_A_array, pts_B_array)\n N = np.sqrt(N)\n\n # Mean distance and hausdorff distance\n md = 0.5 * (np.mean(np.min(N, axis=0)) + np.mean(np.min(N, axis=1)))\n hd = np.max([np.max(np.min(N, axis=0)), np.max(np.min(N, axis=1))])\n\n return md, hd\n\n\ndef distance_metric_2d(seg_A, seg_B, pixel_spacing, average_slices, fill_nan=False):\n \"\"\"\n Measure the distance errors between the contours of two segmentations.\n The manual contours are drawn on 2D slices.\n We calculate contour to contour distance for each slice.\n \"\"\"\n table_md = []\n table_hd = []\n X, Y, Z = seg_A.shape\n for z in range(Z):\n # Binary mask at this slice\n slice_A = seg_A[:, :, z].astype(np.uint8)\n slice_B = seg_B[:, :, z].astype(np.uint8)\n\n # The distance is defined only when both contours exist on this slice\n if np.sum(slice_A) > 0 and np.sum(slice_B) > 0:\n # Find contours and retrieve all the points\n _, contours, _ = cv2.findContours(cv2.inRange(slice_A, 1, 1),\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_NONE)\n\n pts_A = np.concatenate(contours, axis=0)[:, 0, :] * pixel_spacing\n\n _, contours, _ = cv2.findContours(cv2.inRange(slice_B, 1, 1),\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_NONE)\n\n pts_B = np.concatenate(contours, axis=0)[:, 0, :] * pixel_spacing\n\n # Distance matrix between point sets\n N = np_pairwise_squared_euclidean_distance(pts_A, pts_B)\n N = np.sqrt(N)\n\n # Distance matrix between point sets\n # M = np.zeros((len(pts_A), len(pts_B)))\n # for i in range(len(pts_A)):\n # for j in range(len(pts_B)):\n # M[i, j] = np.linalg.norm(pts_A[i, 0] - pts_B[j, 0])\n\n # print(np.allclose(M, N, rtol=1e-5, atol=1e-5))\n\n # Mean distance and hausdorff distance\n md = 0.5 * (np.mean(np.min(N, axis=0)) + np.mean(np.min(N, axis=1)))\n hd = np.max([np.max(np.min(N, axis=0)), np.max(np.min(N, axis=1))])\n table_md += [md]\n table_hd += [hd]\n elif fill_nan:\n if np.sum(slice_A) == 0 and np.sum(slice_B) == 0:\n table_md += [0.]\n table_hd += [0.]\n elif np.sum(slice_A) == 0:\n mean_distance = find_average_distance_within_contour(slice_B, pixel_spacing)\n table_md += [mean_distance]\n table_hd += [mean_distance]\n else:\n mean_distance = find_average_distance_within_contour(slice_A, pixel_spacing)\n table_md += [mean_distance]\n table_hd += [mean_distance]\n else:\n table_md += [np.nan]\n table_hd += [np.nan]\n\n if average_slices:\n # Return the mean distance and Hausdorff distance across 2D slices\n mean_md = np.nanmean(table_md) if table_md else None\n mean_hd = np.nanmean(table_hd) if table_hd else None\n else:\n mean_md = table_md\n mean_hd = table_hd\n\n return mean_md, mean_hd\n\n\ndef find_average_distance_within_contour(slice, pixel_spacing):\n if np.sum(slice) == 0:\n return 0\n\n _, contours, _ = cv2.findContours(cv2.inRange(slice, 1, 1), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n pts = np.concatenate(contours, axis=0)[:, 0, :] * pixel_spacing\n\n N = np_pairwise_squared_euclidean_distance(pts, pts)\n N = np.sqrt(N)\n\n return np.mean(np.max(N, axis=0))\n\n\ndef np_pairwise_squared_euclidean_distance(x, z):\n '''\n This function calculates the pairwise euclidean distance\n matrix between input matrix x and input matrix z and\n return the distances matrix as result.\n\n x is a BxN matrix\n z is a CxN matrix\n result d is a BxC matrix that contains the Euclidean distances\n\n '''\n # Calculate the square of both\n x_square = np.expand_dims(np.sum(np.square(x), axis=1), axis=1)\n z_square = np.expand_dims(np.sum(np.square(z), axis=1), axis=0)\n\n # Calculate x*z\n x_z = np.matmul(x, np.transpose(z))\n\n # Calculate squared Euclidean distance\n d_matrix = x_square + z_square - 2 * x_z\n d_matrix[d_matrix < 0] = 0\n\n return d_matrix\n","sub_path":"misc/image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":22531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69591032","text":"#!/usr/bin/env python\n\n# pylint: disable=redefined-outer-name\n\n\"\"\"RegistryV2ImageSource tests.\"\"\"\n\nimport base64\nimport copy\nimport tempfile\n\nimport pytest\n\nfrom docker_sign_verify import (\n ImageConfig,\n ImageName,\n RegistryV2ImageSource,\n RegistryV2Manifest,\n)\nfrom docker_sign_verify.utils import FormattedSHA256\n\nfrom .stubs import FakeSigner\nfrom .testutils import get_test_data_path\n\nKNOWN_GOOD_IMAGE_LIST = [\"busybox:1.30.1\", \"library/python:3.7.2-slim-stretch\"]\n\n\n@pytest.fixture\ndef registry_v2_image_source() -> RegistryV2ImageSource:\n \"\"\"Provides a RegistryV2ImageSource instance.\"\"\"\n # Do not use caching; get a new instance for each test\n return RegistryV2ImageSource(dry_run=True)\n\n\ndef test_init(registry_v2_image_source: RegistryV2ImageSource):\n \"\"\"Test that the image source can be instantiated.\"\"\"\n assert registry_v2_image_source\n\n\n@pytest.mark.parametrize(\n \"endpoint,expected_username,expected_password\",\n [\n (\"endpoint:port\", \"username\", \"password\"),\n (\"endpoint2:port2\", \"username2\", \"password2\"),\n ],\n)\ndef test__get_credentials(\n request,\n registry_v2_image_source: RegistryV2ImageSource,\n endpoint: str,\n expected_username: str,\n expected_password: str,\n):\n \"\"\"Test credentials retrieval.\"\"\"\n registry_v2_image_source.credentials_store = get_test_data_path(\n request, \"credentials_store.json\"\n )\n # pylint: disable=protected-access\n credentials = registry_v2_image_source._get_credentials(endpoint)\n assert credentials\n\n decoded = base64.decodebytes(credentials.encode(\"utf-8\")).decode(\"utf-8\")\n assert decoded\n\n actual_username, actual_password = decoded.split(\":\")\n assert actual_username == expected_username\n assert actual_password == expected_password\n\n\n@pytest.mark.parametrize(\n \"image,expected_credentials\",\n [\n (\"endpoint:port/image\", \"dXNlcm5hbWU6cGFzc3dvcmQ=\"),\n (\"endpoint2:port2/image\", \"dXNlcm5hbWUyOnBhc3N3b3JkMg==\"),\n ],\n)\ndef test__get_request_headers(\n request,\n registry_v2_image_source: RegistryV2ImageSource,\n image: str,\n expected_credentials: str,\n):\n \"\"\"Test request headers retrieval.\"\"\"\n registry_v2_image_source.credentials_store = get_test_data_path(\n request, \"credentials_store.json\"\n )\n image_name = ImageName.parse(image)\n # pylint: disable=protected-access\n headers = registry_v2_image_source._get_request_headers(image_name)\n assert headers\n assert expected_credentials in headers[\"Authorization\"]\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_get_iamge_config(registry_v2_image_source: RegistryV2ImageSource, image: str):\n \"\"\"Test image configuration retrieval.\"\"\"\n image_name = ImageName.parse(image)\n config = registry_v2_image_source.get_image_config(image_name)\n\n assert config\n assert isinstance(config, ImageConfig)\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_get_image_layer_to_disk(\n registry_v2_image_source: RegistryV2ImageSource, image: str\n):\n \"\"\"Test layer retrieval to disk.\"\"\"\n image_name = ImageName.parse(image)\n config_digest = registry_v2_image_source.get_manifest(\n image_name\n ).get_config_digest()\n temp = tempfile.NamedTemporaryFile()\n result = registry_v2_image_source.get_image_layer_to_disk(\n image_name, config_digest, temp\n )\n assert result[\"digest\"] == config_digest\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_get_manifest(registry_v2_image_source: RegistryV2ImageSource, image: str):\n \"\"\"Test manifest retrieval.\"\"\"\n image_name = ImageName.parse(image)\n manifest = registry_v2_image_source.get_manifest(image_name)\n\n assert manifest\n assert isinstance(manifest, RegistryV2Manifest)\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_layer_exists(registry_v2_image_source: RegistryV2ImageSource, image: str):\n \"\"\"Test layer existence.\"\"\"\n image_name = ImageName.parse(image)\n layer = registry_v2_image_source.get_manifest(image_name).get_layers()[-1]\n assert registry_v2_image_source.layer_exists(image_name, layer)\n assert not registry_v2_image_source.layer_exists(\n image_name, FormattedSHA256(\"0\" * 64)\n )\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_sign_image_same_image_source(\n registry_v2_image_source: RegistryV2ImageSource, image: str\n):\n \"\"\"Test image signing.\"\"\"\n src_image_name = ImageName.parse(image)\n dest_image_name = copy.deepcopy(src_image_name)\n dest_image_name.tag = \"{0}_signed\".format(dest_image_name.tag)\n\n def assertions(result: dict):\n assert result\n\n image_config = result[\"image_config\"]\n assert image_config\n assert \"FAKE SIGNATURE\" in str(image_config)\n\n signature_value = result[\"signature_value\"]\n assert signature_value\n assert \"FAKE SIGNATURE\" in signature_value\n\n verify_image_data = result[\"verify_image_data\"]\n assert verify_image_data\n assert image_config == verify_image_data[\"image_config\"]\n\n manifest = verify_image_data[\"manifest\"]\n assert manifest\n\n manifest_signed = result[\"manifest_signed\"]\n assert manifest_signed\n assert manifest_signed.get_config_digest() == image_config.get_config_digest()\n assert len(manifest_signed.get_layers()) == len(image_config.get_image_layers())\n\n # 1. Single signature\n assertions(\n registry_v2_image_source.sign_image(\n FakeSigner(),\n src_image_name,\n registry_v2_image_source,\n dest_image_name,\n False,\n )\n )\n\n # TODO: Test signing image twice (with same key, with different keys ...)\n # Can we do this here (using dockerhub), or do we need to do this in test_imageconfig.py???\n\n\n# TODO: test_sign_image_different_image_source\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(\"image\", KNOWN_GOOD_IMAGE_LIST)\ndef test_verify_image_integrity(\n registry_v2_image_source: RegistryV2ImageSource, image: str\n):\n \"\"\"Test image integrity.\"\"\"\n image_name = ImageName.parse(image)\n\n def assertions(result: dict):\n assert result\n\n image_config = result[\"image_config\"]\n assert image_config\n\n manifest = result[\"manifest\"]\n assert manifest\n\n assert len(result[\"compressed_layer_files\"]) == len(\n result[\"uncompressed_layer_files\"]\n )\n\n assert len(result[\"uncompressed_layer_files\"]) == len(\n result[\"uncompressed_layer_files\"]\n )\n\n # 1. Unsigned\n assertions(registry_v2_image_source.verify_image_integrity(image_name))\n\n # TODO: Test integrity on a signed image ...\n # Can we do this here (using dockerhub), or do we need to do this in test_imageconfig.py???\n","sub_path":"tests/test_imagesources_registry.py","file_name":"test_imagesources_registry.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150085624","text":"from django.shortcuts import render, get_object_or_404, redirect\r\nfrom .models import Post, MyProjects\r\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\nfrom django.contrib.auth.models import User\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\n# To do for tomorrow:\r\n# On the DashBoard Page, Where turn the dashboard title into a dropdown menu of all the projects, then the progress bar/ pie chart / percent could just be for that project\r\n# Make a projects model where Posts are associated with a certain project\r\n\r\n\r\ndef Tracker(request):\r\n return redirect('/tracker/projects/1/')\r\n\r\n \r\n\r\nclass ProjectView(DetailView):\r\n model = MyProjects\r\n template_name = \"bugtracker/index.html\"\r\n\r\n def get_context_data(self, **kwargs):\r\n current_project = self.get_object()\r\n posts = current_project.post_set.all()\r\n completed = posts.filter(status='Completed', project= current_project)\r\n inProgress = posts.filter(status='InProgress', project= current_project)\r\n Features = posts.filter(ticket_type='Features', project= current_project)\r\n Bug = posts.filter(ticket_type='Bug/Error', project= current_project)\r\n Design = posts.filter(ticket_type='Design', project= current_project)\r\n projects = MyProjects.objects.all()\r\n\r\n if posts.count() == 0:\r\n percentCompleted = 0\r\n percentBug = 0\r\n percentDesign = 0\r\n percentFeatures = 0\r\n else:\r\n percentBug = int((Bug.count()/posts.count())* 100) \r\n percentDesign = int((Design.count()/posts.count())* 100) \r\n percentFeatures = int((Features.count()/posts.count())* 100) \r\n percentCompleted = int((completed.count()/posts.count())* 100) \r\n\r\n\r\n\r\n if posts.filter(ticket_type=\"Design\", project= current_project).count() == 0:\r\n completedDesign = 0\r\n else:\r\n completedDesign = int((completed.filter(ticket_type='Design', project= current_project).count() / posts.filter(ticket_type=\"Design\", project= current_project).count()) * 100)\r\n\r\n if posts.filter(ticket_type=\"Bug/Error\").count() == 0:\r\n completedBug = 0\r\n else: \r\n completedBug = int((completed.filter(ticket_type='Bug/Error', project= current_project).count() / posts.filter(ticket_type=\"Bug/Error\", project= current_project).count()) * 100)\r\n\r\n if posts.filter(ticket_type=\"Features\").count() == 0:\r\n completedFeature = 0\r\n else:\r\n completedFeature = int((completed.filter(ticket_type='Features', project= current_project).count() / posts.filter(ticket_type=\"Features\", project= current_project).count()) * 100)\r\n \r\n context = super().get_context_data(**kwargs)\r\n context['posts'] = posts\r\n context['completed'] = completed\r\n context['percentCompleted'] = percentCompleted\r\n context['inProgress'] = inProgress\r\n context['percentFeatures'] = percentFeatures\r\n context['percentBug'] = percentBug\r\n context['percentDesign'] = percentDesign\r\n context['completedBug'] = completedBug\r\n context['completedDesign'] = completedDesign\r\n context['completedFeature'] = completedFeature\r\n context['projects'] = projects\r\n context['project_title'] = current_project.title\r\n\r\n\r\n return context\r\n\r\n\r\n \r\n \r\n\r\n#def Tables(request):\r\n #ordering = [\"-priority\"]\r\n # context = {\r\n# 'posts': Post.objects.all()\r\n # }\r\n\r\n # return render(request, \"bugtracker/tables.html\", context)\r\n\r\ndef Tables(request):\r\n return redirect('/tracker/projects/1/tables')\r\n\r\n\r\nclass PostTableView(DetailView):\r\n model = MyProjects\r\n template_name ='bugtracker/tables.html'\r\n context_object_name = 'posts'\r\n ordering = ['priority']\r\n\r\n def get_context_data(self, **kwargs):\r\n current_project = self.get_object()\r\n posts = current_project.post_set.all()\r\n context = super().get_context_data(**kwargs)\r\n context['posts'] = posts\r\n context['project_title'] = current_project.title\r\n context['projects'] = MyProjects.objects.all()\r\n return context\r\n\r\nclass ProjectListView(ListView):\r\n model = MyProjects\r\n template_name = 'bugtracker/projects.html'\r\n context_object_name = 'projects'\r\n\r\n\r\n\r\n\r\n\r\nclass PostListView(ListView):\r\n model = Post\r\n template_name ='bugtracker/tasklist.html'\r\n context_object_name = 'posts'\r\n ordering = ['priority']\r\n\r\n\r\n\r\n\r\n\r\nclass PostDetailView(DetailView):\r\n model = Post\r\n\r\n\r\nclass PostCreateView(LoginRequiredMixin, CreateView):\r\n model = Post\r\n fields = ['title', 'content', 'priority', 'ticket_type', 'status', 'assigned_developer']\r\n\r\n def form_valid(self, form):\r\n form.instance.author = self.request.user\r\n form.instance.assigned_developer = self.request.user\r\n return super().form_valid(form)\r\n\r\n\r\nclass ProjectCreateView(LoginRequiredMixin, CreateView):\r\n model = MyProjects\r\n fields = ['title', 'description']\r\n\r\n\r\n\r\nclass PostUpdateView(LoginRequiredMixin, UpdateView):\r\n model = Post\r\n fields = ['title', 'content', 'priority', 'ticket_type', 'status', 'project']\r\n success_url = '/tracker/'\r\n\r\n def form_valid(self, form):\r\n form.instance.author = self.request.user\r\n return super().form_valid(form)\r\n\r\n\r\nclass PostDeleteView(LoginRequiredMixin, DeleteView):\r\n model = Post\r\n success_url = '/tracker/'\r\n","sub_path":"bugtracker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"359149312","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport time\nimport pytz\nfrom openerp import SUPERUSER_ID\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n\nfrom openerp.osv import fields, osv\nfrom openerp import netsvc\nfrom openerp import pooler\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom openerp.osv.orm import browse_record, browse_null\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP\n\n# Permite modificar el campo control de factura del pedido en status progress\n\n\nclass sale_order(osv.osv):\n _inherit = \"sale.order\"\n\n def _get_order(self, cr, uid, ids, context=None):\n result = {}\n for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context):\n result[line.order_id.id] = True\n return result.keys()\n\n _columns = {\n 'order_policy': fields.selection([\n ('manual', 'On Demand'),\n ('picking', 'On Delivery Order'),\n ('prepaid', 'Before Delivery'),\n ], 'Create Invoice', required=True, readonly=True,\n states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'progress': [('readonly', False)]},\n help=\"\"\"On demand: A draft invoice can be created from the\n sales order when needed. \\nOn delivery order:\n A draft invoice can be created from the delivery order\n when the products have been delivered. \\nBefore delivery:\n A draft invoice is created from the sales order and must be\n paid before the products can be delivered.\"\"\"),\n 'order_line': fields.one2many('sale.order.line', 'order_id', 'Order Lines', readonly=True,\n states={'draft': [('readonly', False)],\n 'sent': [('readonly', False)],\n 'progress': [('readonly', False)],\n 'shipping_except': [('readonly', False)]}),\n 'copies': fields.integer(string='# of Copies'),\n 'copiedfrom': fields.many2one('sale.order', string='Copiado desde')\n }\n\n _defaults = {\n 'copies': 0,\n }\n\n def write(self, cr, uid, ids, vals, context=None):\n if not isinstance(ids, list):\n ids = [ids]\n for order in self.browse(cr, uid, ids, context=context):\n services = sum([1 for line in order.order_line if line.product_id.type == 'service'])\n if services > 0:\n if vals.get('order_policy') == 'picking' or order.order_policy == 'picking':\n vals['order_policy'] = 'manual'\n if 'order_line' in vals:\n for l in vals['order_line']:\n if l[2] is not False and 'product_id' in l[2]:\n prod = self.pool.get('product.product').browse(cr, uid, l[2]['product_id']) if 'product_id' in l[2] else False\n if prod.type == 'service':\n if vals.get('order_policy') == 'picking' or order.order_policy == 'picking':\n vals['order_policy'] = 'manual'\n super(sale_order, self).write(cr, uid, [order.id], vals, context=context)\n return True\n\n def create(self, cr, uid, vals, context=None):\n if 'order_line' in vals:\n for l in vals['order_line']:\n if l[2] is False:\n continue\n if 'product_id' in l[2]:\n prod = self.pool.get('product.product').browse(cr, uid, l[2]['product_id'])\n if prod.type == 'service' and vals.get('order_policy') == 'picking':\n vals['order_policy'] = 'manual'\n return super(sale_order, self).create(cr, uid, vals, context=context)\n\n def copy(self, cr, uid, id, default=None, context=None):\n if not default:\n default = {}\n default.update({\n 'state': 'draft',\n 'invoice_ids': [],\n 'copies': 0,\n 'copiedfrom': False,\n 'quotation_origin_id': False,\n 'date_confirm': False,\n 'name': self.pool.get('ir.sequence').get(cr, uid, 'sale.order'),\n })\n return super(sale_order, self).copy(cr, uid, id, default, context=context)\n\n def copy_version(self, cr, uid, id, default=None, context=None):\n if isinstance(id, list):\n id = id[0]\n order = self.browse(cr, uid, id, context=context)\n root = self.browse(cr, uid, self.search(cr, uid, [('name', '=', order.name.split('/')[0])])[0])\n copies = root.copies+1\n newname = order.name.split('/')[0] + '/' + str(copies)\n if not default:\n default = {}\n default.update({\n 'state': 'draft',\n 'invoice_ids': [],\n 'date_confirm': False,\n 'date_order': date.today(),\n 'quotation_origin_id': order.id,\n 'copies': copies,\n })\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_validate(uid, 'sale.order', order.id, 'cancel', cr)\n while order:\n self.write(cr, uid, order.id, {'copies': copies})\n order = order.quotation_origin_id\n id = super(sale_order, self).copy(cr, uid, id, default, context=context)\n self.write(cr, uid, [id], {'name': newname, 'date_order': default['date_order']})\n view_ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'sale', 'view_order_form')\n view_id = view_ref and view_ref[1] or False,\n return {\n 'type': 'ir.actions.act_window',\n 'name': _('Sales Order'),\n 'res_model': 'sale.order',\n 'res_id': id,\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': view_id,\n 'target': 'current',\n 'nodestroy': True,\n }\n\n\nclass sale_order_line(osv.osv):\n _inherit = 'sale.order.line'\n\n def _get_line_qty(self, cr, uid, line, context=None):\n return line.product_uom_qty\n\n _columns = {\n 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)],\n change_default=True, readonly=True, states={'draft': [('readonly', False)]}),\n 'product_uom_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product UoS'), required=True,\n readonly=True,\n states={'draft': [('readonly', False)],\n 'confirmed': [('readonly', False)],\n 'exception': [('readonly', False)]}),\n 'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price'),\n readonly=True,\n states={'draft': [('readonly', False)],\n 'confirmed': [('readonly', False)],\n 'exception': [('readonly', False)]}),\n 'state': fields.selection(\n [('cancel', 'Cancelled'), ('draft', 'Draft'), ('confirmed', 'Confirmed'), ('exception', 'Exception'),\n ('done', 'Done')], 'Status', required=True, readonly=True,\n help='* The \\'Draft\\' status is set when the related sales order in draft status. \\\n \\n* The \\'Confirmed\\' status is set when the related sales order is confirmed. \\\n \\n* The \\'Exception\\' status is set when the related sales order is set as exception. \\\n \\n* The \\'Done\\' status is set when the sales order line has been picked. \\\n \\n* The \\'Cancelled\\' status is set when a user cancel the sales order related.'),\n }\n\n def button_cancel(self, cr, uid, ids, context=None):\n for line in self.browse(cr, uid, ids, context=context):\n if line.invoiced:\n raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sales order line that has already been invoiced.'))\n self.write(cr, uid, ids, {'state': 'cancel'})\n lines = self.browse(cr, uid, ids, context=context)\n\n for line in lines:\n exc = False\n conf = False\n order = line.order_id\n if order.state == 'shipping_except':\n for l in order.order_line:\n if l.state == 'exception':\n exc = True\n if l.state == 'confirmed':\n conf = True\n if exc == False and conf == True:\n order.write({'state': 'progress'})\n elif exc == False and conf == False and order.invoiced is True:\n order.write({'state': 'done'})\n self.pool.get('procurement.order').write(cr, uid, line.procurement_id.id, {'state': 'cancel'})\n return True\n","sub_path":"sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":10022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"271227724","text":"import asyncio\nfrom typing import Callable\nfrom collections import OrderedDict\n\nfrom .store import get_flow_stack, get_up_flow, get_top_flow\nfrom .channel import Channel, ChannelDict, END, check_list_of_channels\nfrom .task import BaseTask, default_execute, OUTPUT, initialize_inputs\nfrom .utils import INPUTS, OUTPUT\n\n\nclass Flow(object):\n def __init__(self, name=\"\"):\n self.name = name\n self.inputs: ChannelDict = None\n self.output: OUTPUT = None\n self.tasks = OrderedDict()\n self.task_futures = []\n self.execute: Callable = default_execute\n\n def __repr__(self):\n return self.__class__.__name__ + \"-\" + str(hash(self))\n\n def __enter__(self):\n get_flow_stack().append(self)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n get_flow_stack().pop(-1)\n\n def __call__(self, *args, **kwargs) -> Channel:\n check_list_of_channels(*args, **kwargs)\n flow = self.copy()\n # set up flows environments\n with flow:\n # set inputs within Task.__call\n self.inputs = ChannelDict(initialize_inputs(self, *args, **kwargs))\n flow.output = flow.run(*args, **kwargs)\n if not isinstance(flow.output, Channel):\n raise ValueError(\"Flow's run must return a Channel\")\n top_flow = get_top_flow()\n\n async def execute():\n for task, task_info in flow.tasks.items():\n if isinstance(task, BaseTask):\n task.future = asyncio.ensure_future(task.execute())\n top_flow.task_futures.append(task.future)\n loop = asyncio.get_running_loop()\n if not hasattr(loop, 'task_futures'):\n loop.task_futures = []\n loop.task_futures.append((task, task.future))\n elif isinstance(task, Flow):\n await task.execute()\n\n flow.execute = execute\n up_flow = get_up_flow()\n if up_flow:\n assert flow not in up_flow.tasks\n up_flow.tasks.setdefault(flow, {})\n if not isinstance(flow.output, Channel):\n raise ValueError(\"The output of flows must be a single Channel instead of list/tuple of Channel\")\n\n flow.output.flows.append(flow)\n return flow.output\n\n def run(self, *args, **kwargs) -> Channel:\n raise NotImplementedError\n\n def copy(self):\n from copy import deepcopy\n return deepcopy(self)\n\n def __str__(self):\n return type(self).__name__\n\n\nclass FlowRunner(object):\n def __init__(self, flow):\n self.flow = flow\n\n async def _run(self, *args):\n output = self.flow(*args)\n if not isinstance(output, Channel):\n raise ValueError(\"The return value of the outermost flows must be\"\n \" a single Channel, instead of a list of Channel.\")\n flow: Flow = output.flows[-1]\n await flow.execute()\n done, pending = await asyncio.wait(flow.task_futures, return_when=asyncio.FIRST_EXCEPTION)\n for task in done:\n if task.exception() is not None:\n raise task.exception()\n return flow\n\n def run(self, *args):\n flow = asyncio.run(self._run(*args))\n\n results = []\n while not flow.output.empty():\n item = flow.output.get_nowait()\n if item is END:\n break\n results.append(item)\n return results\n\n\n","sub_path":"pyflow/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524119985","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: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/app/test_.py\n# Compiled at: 2019-08-19 02:52:33\n# Size of source mod 2**32: 6062 bytes\n\"\"\"Launch unittests of the library\"\"\"\n__authors__ = [\n 'V. Valls']\n__license__ = 'MIT'\n__date__ = '12/01/2018'\nimport sys, argparse, logging, unittest, os\nfrom tomwer.test.utils import skip_gui_test\n\nclass StreamHandlerUnittestReady(logging.StreamHandler):\n __doc__ = 'The unittest class TestResult redefine sys.stdout/err to capture\\n stdout/err from tests and to display them only when a test fail.\\n\\n This class allow to use unittest stdout-capture by using the last sys.stdout\\n and not a cached one.\\n '\n\n def emit(self, record):\n self.stream = sys.stderr\n super(StreamHandlerUnittestReady, self).emit(record)\n\n def flush(self):\n pass\n\n\ndef createBasicHandler():\n \"\"\"Create the handler using the basic configuration\"\"\"\n hdlr = StreamHandlerUnittestReady()\n fs = logging.BASIC_FORMAT\n dfs = None\n fmt = logging.Formatter(fs, dfs)\n hdlr.setFormatter(fmt)\n return hdlr\n\n\nfor h in logging.root.handlers:\n logging.root.removeHandler(h)\n\nlogging.root.addHandler(createBasicHandler())\nlogging.captureWarnings(True)\n_logger = logging.getLogger(__name__)\n\nclass TextTestResultWithSkipList(unittest.TextTestResult):\n __doc__ = 'Override default TextTestResult to display list of skipped tests at the\\n end\\n '\n\n def printErrors(self):\n unittest.TextTestResult.printErrors(self)\n self.printErrorList('SKIPPED', self.skipped)\n\n\ndef main(argv):\n \"\"\"\n Main function to launch the unittests as an application\n\n :param argv: Command line arguments\n :returns: exit status\n \"\"\"\n from silx.test import utils\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-v', '--verbose', default=0, action='count',\n dest='verbose',\n help='Increase verbosity. Option -v prints additional INFO messages. Use -vv for full verbosity, including debug messages and test help strings.')\n parser.add_argument('--qt-binding', dest='qt_binding', default=None, help=\"Force using a Qt binding: 'PyQt5' or 'PySide2'\")\n parser.add_argument('--web', dest='web_log', default=False, help=\"Force unit test to export his log to graylog'\",\n action='store_true')\n utils.test_options.add_parser_argument(parser)\n options = parser.parse_args(argv[1:])\n test_verbosity = 1\n use_buffer = True\n if options.verbose == 1:\n logging.root.setLevel(logging.INFO)\n _logger.info('Set log level: INFO')\n test_verbosity = 2\n use_buffer = False\n else:\n if options.verbose > 1:\n logging.root.setLevel(logging.DEBUG)\n _logger.info('Set log level: DEBUG')\n test_verbosity = 2\n use_buffer = False\n else:\n os.environ['_TOMWER_NO_GUI_UNIT_TESTS'] = str(not options.gui)\n if options.qt_binding and options.gui is True:\n binding = options.qt_binding.lower()\n if binding == 'pyqt4':\n _logger.info('Force using PyQt4')\n import PyQt4.QtCore\n elif binding == 'pyqt5':\n _logger.info('Force using PyQt5')\n import PyQt5.QtCore\n else:\n if binding == 'pyside':\n _logger.info('Force using PySide')\n import PySide.QtCore\n else:\n if binding == 'pyside2':\n _logger.info('Force using PySide2')\n import PySide2.QtCore\n else:\n previous_web_log_value = os.environ.get('ORANGE_WEB_LOG')\n os.environ['ORANGE_WEB_LOG'] = str(options.web_log)\n utils.test_options.configure(options)\n runnerArgs = {}\n runnerArgs['verbosity'] = test_verbosity\n runnerArgs['buffer'] = use_buffer\n runner = (unittest.TextTestRunner)(**runnerArgs)\n runner.resultclass = TextTestResultWithSkipList\n unittest.installHandler()\n import tomwer.test\n test_suite = unittest.TestSuite()\n test_suite.addTest(tomwer.test.suite())\n if options.gui is True:\n import orangecontrib.tomwer.test\n test_suite.addTest(orangecontrib.tomwer.test.suite())\n result = runner.run(test_suite)\n if previous_web_log_value is None:\n del os.environ['ORANGE_WEB_LOG']\n else:\n os.environ['ORANGE_WEB_LOG'] = previous_web_log_value\n if result.wasSuccessful():\n exit_status = 0\n else:\n exit_status = 1\n return exit_status","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/test_.cpython-37.py","file_name":"test_.cpython-37.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"104171291","text":"from fabric.api import env, local, run, prefix\nfrom fabric.contrib.files import exists, sed\nimport fabtools\n\nREPO_URL = 'https://github.com/foonectar/obey-the-goat.git'\n\n\n# still need to set env vars manually\n# ex. \"fab deploy:host=just@staging-superlists.foo.sexy\" or \"fab deploy:host=just@superlists.foo.sexy\"\ndef deploy():\n site_folder = '/home/%s/sites/%s' % (env.user, env.host)\n source_folder = site_folder + '/source'\n # set db_name as host, potential for problems with . char\n db_name = '%s' % env.host\n _create_directory_structure_if_necessary(site_folder)\n _get_latest_source(source_folder)\n _set_postgres(db_name)\n _update_settings(source_folder, env.host)\n _update_virtualenv(source_folder)\n _update_static_files(source_folder)\n _update_database(source_folder)\n\n\ndef _create_directory_structure_if_necessary(site_folder):\n for subfolder in ('static', 'virtualenv', 'source'):\n run('mkdir -p %s/%s' % (site_folder, subfolder))\n\n\ndef _get_latest_source(source_folder):\n if exists(source_folder + '/.git'):\n run('cd %s && git fetch' % source_folder)\n else:\n run('git clone %s %s' % (REPO_URL, source_folder))\n current_commit = local(\"git log -n 1 --format=%H\", capture=True)\n run('cd %s && git reset --hard %s' % (source_folder, current_commit))\n\n\ndef _set_postgres(db_name):\n if not fabtools.postgres.user_exists('heis'):\n fabtools.postgres.create_user('heis', password='somesmartpassword', create_db=True)\n if not fabtools.postgres.database_exists(db_name):\n fabtools.postgres.create_database(db_name, owner='heis')\n\n\ndef _update_settings(source_folder, site_name):\n settings_path = source_folder + '/superlists/settings/production.py' # production and staging should always be same\n # 'sed' command for string substitution\n sed(settings_path, 'DOMAIN = \"localhost\"', 'DOMAIN = \"%s\"' % site_name)\n\n\ndef _update_virtualenv(source_folder):\n virtualenv_folder = source_folder + '/../virtualenv'\n if not exists(virtualenv_folder + '/bin/pip'):\n run('virtualenv --python=python3 %s' % virtualenv_folder)\n run('%s/bin/pip install -r %s/requirements.txt' % (\n virtualenv_folder, source_folder\n ))\n\n\n# Need way to set environment variables for virtual environment\n# fails on new deploy bc virtual env vars not fabricated by fabric\ndef _update_static_files(source_folder):\n run('cd %s && . ../virtualenv/bin/activate && python3 manage.py collectstatic --noinput' % source_folder)\n\n\n# fails on new deploy bc venv vars not set by fabric\ndef _update_database(source_folder):\n run('cd %s && . ../virtualenv/bin/activate && python3 manage.py migrate --noinput' % source_folder)","sub_path":"deploy_tools/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216294134","text":"from __future__ import print_function\nimport numpy as np\nimport sklearn.preprocessing as preprocessing\nfrom numpy.matlib import repmat\n\nfrom ifqi.algorithms.algorithm import Algorithm\nfrom ifqi.preprocessors.features import select_features\nfrom ifqi.models.actionregressor import ActionRegressor\n\n\"\"\"\nThis class implements the functions to run Fitted Q-Iteration algorithm.\n\"\"\"\n\n\nclass FQI(Algorithm):\n def __init__(self, estimator, state_dim, action_dim,\n discrete_actions, gamma, horizon,\n features=None, verbose=False):\n self.__name__ = 'FQI'\n super(FQI, self).__init__(estimator, state_dim, action_dim,\n discrete_actions, gamma, horizon,\n features, verbose)\n\n def partial_fit(self, sast=None, r=None, **kwargs):\n \"\"\"\n Perform a step of FQI using input data sast and r.\n Note that if the dataset does not change between iterations, you can\n provide None inputs after the first iteration.\n\n Args:\n sast (numpy.array, None): the input in the dataset\n r (numpy.array, None): the output in the dataset\n **kwargs: additional parameters to be provided to the fit function\n of the estimator\n\n Returns:\n sa, y: the preprocessed input and output\n \"\"\"\n if sast is not None:\n next_states_idx = self.state_dim + self.action_dim\n self._sa = sast[:, :next_states_idx]\n self._snext = sast[:, next_states_idx:-1]\n self._absorbing = sast[:, -1]\n if r is not None:\n self._r = r\n\n if self._iteration == 0:\n if self._verbose > 0:\n print('Iteration {}'.format(self._iteration + 1))\n\n y = self._r\n else:\n maxq, maxa = self.maxQA(self._snext, self._absorbing)\n\n if self._verbose > 0:\n print('Iteration {}'.format(self._iteration + 1))\n\n if hasattr(self._estimator, 'has_ensembles') \\\n and self._estimator.has_ensembles():\n # update estimator structure\n self._estimator.adapt(iteration=self._iteration)\n\n y = self._r + self.gamma * maxq\n\n self._estimator.fit(self._sa, y.ravel(), **kwargs)\n\n self._iteration += 1\n\n return self._sa, y\n\n def fit(self, sast, r, **kwargs):\n \"\"\"\n Perform steps of FQI using input data sast and r.\n\n Args:\n sast (numpy.array): the input in the dataset\n r (numpy.array): the output in the dataset\n **kwargs: additional parameters to be provided to the fit function\n of the estimator\n\n Returns:\n sa, y: the preprocessed input and output\n \"\"\"\n if self._verbose > 0:\n print(\"Starting complete run...\")\n\n # reset iteration count\n self.reset()\n\n # main loop\n self.partial_fit(sast, r, **kwargs)\n for t in range(1, self.horizon):\n self.partial_fit(sast=None, r=None, **kwargs)\n","sub_path":"ifqi/algorithms/fqi/FQI.py","file_name":"FQI.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"135178563","text":"# coding=utf-8\r\n\"\"\"\r\nКросс-валидация\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\n\r\nimport data_paths as dp\r\nimport titles as tl\r\nimport model as md\r\nimport datasets as dt\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn import preprocessing\r\n\r\n# Параметры обучения\r\nbatch_size = 16\r\nepochs = 200\r\n\r\n# Данные\r\nns, X, Y = dt.get_full_harding_data()\r\n\r\n\r\n# Обучение\r\nkfold = StratifiedKFold(n_splits=10, shuffle=True)\r\ncvscores = []\r\n# X = X.values\r\n# Y = Y.values\r\n\r\nit = 0\r\nfor train, test in kfold.split(X, Y):\r\n scaler = preprocessing.StandardScaler()\r\n # x_train = scaler.fit_transform(X.values[train])\r\n # x_test = scaler.transform(X.values[test])\r\n # y_train = Y[train].values\r\n # y_test = Y[test].values\r\n\r\n sc_data = X.loc[train, tl.full_hard_non_cat_title]\r\n sc_data = pd.DataFrame(scaler.fit_transform(sc_data), index=sc_data.index, columns=sc_data.columns)\r\n ct_data = X.loc[train, tl.full_hard_cat_title]\r\n x_train = pd.concat([sc_data, ct_data], axis=1)\r\n y_train = Y[train].values\r\n\r\n sc_data = X.loc[test, tl.full_hard_non_cat_title]\r\n sc_data = pd.DataFrame(scaler.transform(sc_data), index=sc_data.index, columns=sc_data.columns)\r\n ct_data = X.loc[test, tl.full_hard_cat_title]\r\n x_test = pd.concat([sc_data, ct_data], axis=1)\r\n y_test = Y[test].values\r\n\r\n # Модель\r\n model = md.get_simple_nn(X.shape[1])\r\n model.fit(x_train.values, y_train, epochs=epochs, batch_size=batch_size, verbose=0)\r\n\r\n scores = model.evaluate(x_test.values, y_test, verbose=0)\r\n print(\"%s: %.2f\" % (model.metrics_names[1], scores[1]))\r\n cvscores.append(scores[1])\r\n\r\n predicted = model.predict(x_test.values)\r\n print(\"corr: {:.2f}\".format(np.corrcoef(y_test, [i[0] for i in predicted])[0][1]))\r\n plt.hist([abs(i[0] - j) for i, j in zip(predicted, y_test)])\r\n plt.savefig(\"result/fig{}.jpg\".format(it))\r\n x_test_sc = pd.DataFrame(\r\n scaler.inverse_transform(x_test[tl.full_hard_non_cat_title]),\r\n columns=tl.full_hard_non_cat_title,\r\n index=x_test.index\r\n )\r\n x_test_ct = x_test[tl.full_hard_cat_title]\r\n x_test_ct[tl.full_hard_non_cat_title] = x_test_sc\r\n x_test_sc[u'прочность'] = y_test\r\n x_test_sc[u'прочность (сеть)'] = predicted\r\n x_test_sc.combine_first(pd.DataFrame(ns)).dropna().to_excel(\"result/res{}.xlsx\".format(it))\r\n it += 1\r\n\r\nprint(\"%.2f (+/- %.2f)\" % (np.mean(cvscores), np.std(cvscores)))\r\n\r\n# Тестирование\r\n","sub_path":"nn_learning.py","file_name":"nn_learning.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"602875884","text":"# coding: utf-8\n\n\"\"\"\n NiFi Rest API\n\n The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, definitions of the expected input and output, potential response codes, and the authorizations required to invoke each service.\n\n OpenAPI spec version: 1.19.0\n Contact: dev@nifi.apache.org\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass ControllerServiceStatusDTO(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'run_status': 'str',\n 'validation_status': 'str',\n 'active_thread_count': 'int'\n }\n\n attribute_map = {\n 'run_status': 'runStatus',\n 'validation_status': 'validationStatus',\n 'active_thread_count': 'activeThreadCount'\n }\n\n def __init__(self, run_status=None, validation_status=None, active_thread_count=None):\n \"\"\"\n ControllerServiceStatusDTO - a model defined in Swagger\n \"\"\"\n\n self._run_status = None\n self._validation_status = None\n self._active_thread_count = None\n\n if run_status is not None:\n self.run_status = run_status\n if validation_status is not None:\n self.validation_status = validation_status\n if active_thread_count is not None:\n self.active_thread_count = active_thread_count\n\n @property\n def run_status(self):\n \"\"\"\n Gets the run_status of this ControllerServiceStatusDTO.\n The run status of this ControllerService\n\n :return: The run_status of this ControllerServiceStatusDTO.\n :rtype: str\n \"\"\"\n return self._run_status\n\n @run_status.setter\n def run_status(self, run_status):\n \"\"\"\n Sets the run_status of this ControllerServiceStatusDTO.\n The run status of this ControllerService\n\n :param run_status: The run_status of this ControllerServiceStatusDTO.\n :type: str\n \"\"\"\n allowed_values = [\"ENABLED\", \"ENABLING\", \"DISABLED\", \"DISABLING\"]\n if run_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `run_status` ({0}), must be one of {1}\"\n .format(run_status, allowed_values)\n )\n\n self._run_status = run_status\n\n @property\n def validation_status(self):\n \"\"\"\n Gets the validation_status of this ControllerServiceStatusDTO.\n Indicates whether the component is valid, invalid, or still in the process of validating (i.e., it is unknown whether or not the component is valid)\n\n :return: The validation_status of this ControllerServiceStatusDTO.\n :rtype: str\n \"\"\"\n return self._validation_status\n\n @validation_status.setter\n def validation_status(self, validation_status):\n \"\"\"\n Sets the validation_status of this ControllerServiceStatusDTO.\n Indicates whether the component is valid, invalid, or still in the process of validating (i.e., it is unknown whether or not the component is valid)\n\n :param validation_status: The validation_status of this ControllerServiceStatusDTO.\n :type: str\n \"\"\"\n allowed_values = [\"VALID\", \"INVALID\", \"VALIDATING\"]\n if validation_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `validation_status` ({0}), must be one of {1}\"\n .format(validation_status, allowed_values)\n )\n\n self._validation_status = validation_status\n\n @property\n def active_thread_count(self):\n \"\"\"\n Gets the active_thread_count of this ControllerServiceStatusDTO.\n The number of active threads for the component.\n\n :return: The active_thread_count of this ControllerServiceStatusDTO.\n :rtype: int\n \"\"\"\n return self._active_thread_count\n\n @active_thread_count.setter\n def active_thread_count(self, active_thread_count):\n \"\"\"\n Sets the active_thread_count of this ControllerServiceStatusDTO.\n The number of active threads for the component.\n\n :param active_thread_count: The active_thread_count of this ControllerServiceStatusDTO.\n :type: int\n \"\"\"\n\n self._active_thread_count = active_thread_count\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, ControllerServiceStatusDTO):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","sub_path":"nipyapi/nifi/models/controller_service_status_dto.py","file_name":"controller_service_status_dto.py","file_ext":"py","file_size_in_byte":6408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468791676","text":"from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D\nimport numpy as np\nfrom keras.models import Model, load_model\nfrom keras import backend as K\n\ninput_img = Input(shape=(128, 128, 3)) # adapt this if using `channels_first` image data format\n\nx = Conv2D(16, (3, 3), activation='relu', name=\"firstone\", padding='same')(input_img)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\nencoded = MaxPooling2D((2, 2), padding='same')(x)\n# at this point the representation is (4, 4, 8) i.e. 128-dimensional\n\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(16, (3, 3), activation='relu', padding=\"same\")(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)\n\nautoencoder = Model(input_img, decoded)\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\nfrom keras.callbacks import TensorBoard\nimg_type = \"top\"\ndata = np.load(\"total_\"+img_type+\"_states.npy\")/255.0\nsplit = int(data.shape[0]*0.85)\nx_train = data[:split]\nx_test = data[split:]\n\nautoencoder.fit(x_train, x_train,\n validation_data =(x_test, x_test),\n epochs=200,\n batch_size=100,\n shuffle=True,\n callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])\n\nencoder = Model(input_img, encoded)\nencoder.save(\"models/encoder\"+img_type+\".h5\")\n\n\n#del encoder\n#encoder = load_model(\"models/encoder.h5\")\n#encoder(x_train)\n","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16596960","text":"class Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n\n result_list = [-1] * len(nums)\n result_list[0] = 0\n max_dist = 0\n max_dist_next = nums[0]\n for idx in range(1, len(nums)):\n if idx > max_dist:\n result_list[idx] = result_list[idx-1] + 1\n max_dist, max_dist_next = max_dist_next, max_dist\n else:\n result_list[idx] = result_list[idx-1]\n max_dist_next = max(max_dist_next, idx+nums[idx])\n\n return result_list[-1]\n \nif __name__ == '__main__':\n testcase1 = [2, 3, 1, 1, 4]\n testcase2 = [2, 0, 2, 0, 1]\n sol = Solution()\n # result = sol.jump(testcase1)\n result = sol.jump(testcase2)\n print(result)","sub_path":"python/45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441297323","text":"#!/usr/bin/env python\n\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ns.bind(('localhost', 1234))\n\nprint('Bound on localhost @ port 1234')\n\nwhile True:\n data, addr = s.recvfrom(512)\n print('[%s]: %s' % (addr, data))\n s.sendto(b'Acknowledged: [%d]' % len(data), addr)\n","sub_path":"Python/sockets_udp/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"224334148","text":"import time\nimport requests\n\nfrom config import levels, headers, cities\nfrom db_utils.job import Job\nfrom db_utils.db_methods import get_jobs_table, get_taken_ids\n\nclass TheMuseCrawler():\n def __init__(self):\n self.source = \"themuse\"\n\n def scrape(self, city, insert_jobs_into_db = True):\n jobs_table = get_jobs_table()\n taken_ids = get_taken_ids(city, self.source)\n\n for level in levels:\n total_pages = 9\n for page in range(1, total_pages):\n params = { 'page': str(page), 'location': city, \n 'level': level}\n j = self.get_query_results(params)\n total_pages = int(j['page_count'])\n\n for result in j[\"results\"]:\n if result[\"id\"] not in taken_ids \\\n and \"landing_page\" in result[\"refs\"] \\\n and len(result[\"locations\"]) > 0 \\\n and city == result[\"locations\"][0][\"name\"]:\n category = \"none\"\n if len(result[\"categories\"]) > 0:\n category = result[\"categories\"][0][\"name\"].lower()\n job = Job(\n name = result[\"name\"],\n category = category,\n city = city,\n source = self.source,\n contents = result[\"contents\"],\n company = result[\"company\"][\"name\"].lower(),\n date = result[\"publication_date\"],\n link = result[\"refs\"][\"landing_page\"],\n job_id = result[\"id\"])\n\n if insert_jobs_into_db:\n job.insert_into_table(jobs_table)\n else:\n return job\n\n\n def get_query_results(self, params):\n params['descending'] = 'true'\n params['api_key'] = 'e45578e2555dcc93550818c70d5df559a9b1efae3c2a6eb0cbb48a2e7db562aa'\n r = requests.get( 'https://www.themuse.com/api/public/jobs', params = params, headers = headers)\n time.sleep(0.7)\n j = r.json()\n\n return j","sub_path":"crawlers/the_muse_crawler.py","file_name":"the_muse_crawler.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"482307969","text":"from __future__ import print_function\nimport subprocess\nimport scipy\nimport scipy.stats\n\nsecurify_issues = {}\nsecurify_score = {}\nslither_issues = {}\nslither_score = {}\nloc = {}\nsmartcheck_issues = {}\nsmartcheck_score = {}\n\ndef mutno(mutant):\n return int(mutant.split(\".mutant.\")[1].split(\".\")[0])\n\nwith open(\"stats_424_securify.txt\", 'r') as securify_stats:\n for line in securify_stats:\n if \"analyzing 424contracts/\" in line:\n contract = line.split()[1]\n if \"ISSUES:\" in line:\n securify_issues[contract] = int(line.split()[-1])\n if \"MUTATION SCORE\" in line:\n securify_score[contract] = float(line.split()[-1])\n if \"NO VALID MUTANTS\" in line:\n securify_score[contract] = -1.0\n\nwith open(\"stats_424_slither.txt\", 'r') as slither_stats:\n for line in slither_stats:\n if \"analyzing 424contracts/\" in line:\n contract = line.split()[1]\n if \"ISSUES:\" in line:\n slither_issues[contract] = int(line.split()[-1])\n if \"LOC:\" in line:\n loc[contract] = int(line.split()[-1])\n if \"MUTATION SCORE\" in line:\n slither_score[contract] = float(line.split()[-1])\n if \"NO VALID MUTANTS\" in line:\n slither_score[contract] = -1.0\n\nwith open(\"stats_424_smartcheck.txt\", 'r') as smartcheck_stats:\n for line in smartcheck_stats:\n if \"analyzing 424contracts/\" in line:\n contract = line.split()[1]\n if \"ISSUES:\" in line:\n smartcheck_issues[contract] = int(line.split()[-1])\n if \"MUTATION SCORE\" in line:\n smartcheck_score[contract] = float(line.split()[-1])\n if \"NO VALID MUTANTS\" in line:\n smartcheck_score[contract] = -1.0\n\nallClean = []\n \nfor contract in slither_score:\n print(\"=\"*80)\n print(contract)\n print (\"ISSUE COUNTS: SLITHER\", slither_issues[contract],\n \"SECURIFY\", securify_issues[contract],\n \"SMARTCHECK\", smartcheck_issues[contract])\n if (securify_issues[contract] == 0) and (slither_issues[contract] == 0) and (smartcheck_issues[contract] == 0):\n print(\" -- ALL TOOLS FIND NO ISSUES --\")\n if slither_score[contract] != -1.0:\n allClean.append(contract)\n if slither_score[contract] == -1.0:\n print(\"NO VALID MUTANTS FOR THIS CONTRACT\")\n print()\n print()\n continue\n print(\"MUTATION SCORES: SLITHER\", slither_score[contract],\n \"SECURIFY\", securify_score[contract],\n \"SMARTCHECK\", smartcheck_score[contract])\n print(\"*\"*40)\n print()\n slither_kills = []\n with open(contract.replace(\".sol\",\".sol.slither.killed.txt\"), 'r') as slither_killf:\n for line in slither_killf:\n slither_kills.append(line[:-1])\n securify_kills = []\n with open(contract.replace(\".sol\",\".sol.securify.killed.txt\"), 'r') as securify_killf:\n for line in securify_killf:\n securify_kills.append(line[:-1])\n smartcheck_kills = []\n with open(contract.replace(\".sol\",\".sol.smartcheck.killed.txt\"), 'r') as smartcheck_killf:\n for line in smartcheck_killf:\n smartcheck_kills.append(line[:-1])\n shared_kills = []\n any_securify = False\n for m in sorted(securify_kills, key=mutno):\n if m not in slither_kills:\n print(\"securify detects\", m, \"not detected by slither\")\n print(\"DIFF:\")\n with open(\"diffout.txt\", 'w') as diff_f:\n subprocess.call([\"diff\", \"424mutants/\" + m, contract],\n stdout=diff_f, stderr=diff_f)\n with open(\"diffout.txt\", 'r') as diff_f:\n for line in diff_f:\n print(line, end=\"\")\n print()\n any_securify = True\n else:\n if m in smartcheck_kills:\n shared_kills.append(m)\n if any_securify:\n print()\n any_smartcheck = False\n for m in sorted(smartcheck_kills, key=mutno):\n if m not in slither_kills:\n print(\"smartcheck detects\", m, \"not detected by slither\")\n if m in securify_kills:\n print(\"** mutant detected by both non-slither tools **\")\n print(\"DIFF:\")\n with open(\"diffout.txt\", 'w') as diff_f:\n subprocess.call([\"diff\", \"424mutants/\" + m, contract],\n stdout=diff_f, stderr=diff_f)\n with open(\"diffout.txt\", 'r') as diff_f:\n for line in diff_f:\n print(line, end=\"\")\n print()\n any_smartcheck = True\n else:\n shared_kills.append(m)\n if any_smartcheck:\n print()\n any_slither = False\n for m in sorted(slither_kills, key=mutno):\n if m not in securify_kills:\n print(\"slither detects\", m, \"not detected by securify\")\n any_slither = True\n if m not in smartcheck_kills:\n print(\"slither detects\", m, \"not detected by smartcheck\")\n any_slither = True \n if any_slither:\n print()\n if len(shared_kills) > 0:\n print(len(shared_kills), \"MUTANTS WERE DETECTED BY ALL TOOLS:\")\n for m in shared_kills:\n print(\" \", m)\n print()\n\nprint()\nprint(\"+\"*80)\nprint(\"ISSUES SUMMARY:\")\nprint()\ntoolIssues = {}\nfor (tool, scores, issues) in [(\"slither\", slither_score, slither_issues),\n (\"smartcheck\", smartcheck_score, smartcheck_issues),\n (\"securify\", securify_score, securify_issues)]:\n cbasis = filter(lambda x: scores[x] >= 0.0, scores.keys())\n svals = map(lambda x: issues[x], cbasis)\n toolIssues[tool] = svals\n print(tool, \"MEAN:\", scipy.mean(svals), \"MEDIAN:\", scipy.median(svals),\n \"STD:\", scipy.std(svals))\n print()\nprint()\nprint(\"STATISTICAL COMPARISONS:\")\ndone = []\nfor tool1 in [\"slither\", \"smartcheck\", \"securify\"]:\n for tool2 in [\"slither\", \"smartcheck\", \"securify\"]:\n if tool1 == tool2:\n continue\n if sorted([tool1, tool2]) not in done:\n done.append(sorted([tool1, tool2]))\n else:\n continue\n print(tool1, \"VS.\", tool2 + \":\")\n print(scipy.stats.wilcoxon(toolIssues[tool1], toolIssues[tool2]))\n \n \nprint()\nprint(\"+\"*80)\nprint(\"MUTATION SCORE SUMMARY:\")\nprint()\nprint(len(allClean), \"CONTRACTS ARE CLEAN FOR ALL TOOLS\")\ntoolScores = {}\ntoolCleanScores = {}\nfor (tool, scores) in [(\"slither\", slither_score),\n (\"smartcheck\", smartcheck_score),\n (\"securify\", securify_score)]:\n svals = filter(lambda x: x >= 0.0, scores.values())\n toolScores[tool] = svals\n print(tool, \"MEAN:\", scipy.mean(svals), \"MEDIAN:\", scipy.median(svals),\n \"STD:\", scipy.std(svals))\n svals = map(lambda x: scores[x], allClean)\n toolCleanScores[tool] = svals\n print(tool, \"CLEAN MEAN:\", scipy.mean(svals), \"MEDIAN:\", scipy.median(svals),\n \"STD:\", scipy.std(svals))\n print()\nprint()\nprint(\"STATISTICAL COMPARISONS:\")\ndone = []\nfor tool1 in [\"slither\", \"smartcheck\", \"securify\"]:\n for tool2 in [\"slither\", \"smartcheck\", \"securify\"]:\n if tool1 == tool2:\n continue\n if sorted([tool1, tool2]) not in done:\n done.append(sorted([tool1, tool2]))\n else:\n continue\n print(tool1, \"VS.\", tool2 + \":\")\n print(scipy.stats.wilcoxon(toolScores[tool1], toolScores[tool2]))\n print(\"CLEAN:\", scipy.stats.wilcoxon(toolCleanScores[tool1], toolCleanScores[tool2]))\n","sub_path":"compare424.py","file_name":"compare424.py","file_ext":"py","file_size_in_byte":7567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"518724254","text":"import random\r\nimport os\r\nimport numpy as np\r\nimport argparse\r\nimport pickle\r\nimport itertools\r\nimport torch\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport joblib\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.model_selection import train_test_split\r\nfrom densray import *\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\ndef go(dim=10, cross=False):\r\n #first x dims\r\n model = LogisticRegression()\r\n model.fit(x_train[:,:dim], y_train)\r\n a = model.score(x_test[:,:dim], y_test)\r\n model.fit(x_train[:,dim:2*dim], y_train)\r\n b = model.score(x_test[:,dim:2*dim], y_test)\r\n #randomly choose x dims from [x:]\r\n if cross:\r\n idx = random.sample(range(dim,768-dim), 3)\r\n score = 0\r\n for i in range(3):\r\n model.fit(x_train[:,idx[i]:idx[i]+dim], y_train)\r\n score += model.score(x_test[:,idx[i]:idx[i]+dim], y_test)\r\n c = score/3\r\n else:\r\n idx = random.sample(range(dim, 768 - dim), 1)\r\n score = 0\r\n model.fit(x_train[:, idx[0]:idx[0] + dim], y_train)\r\n score += model.score(x_test[:, idx[0]:idx[0] + dim], y_test)\r\n c = score\r\n return a, b, c\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--seed', type=int, default=42)\r\n parser.add_argument('--mode', type=str, default='token')\r\n parser.add_argument('--lda', action=\"store_true\", default=False)\r\n parser.add_argument('--xlmr', action=\"store_true\", default=False)\r\n parser.add_argument('--svc', action=\"store_true\", default=False)\r\n args = parser.parse_args()\r\n\r\n all_langs = 'af,am,ar,as,az,be,bg,bn,bn_rom,br,bs,ca,cs,cy,da,de,el,en,eo,es,et,eu,fa,fi,fr,fy,ga,gd,gl,gu,ha,he,' \\\r\n 'hi,hi_rom,hr,hu,hy,id,is,it,ja,jv,ka,kk,km,kn,ko,ku,ky,la,lo,lt,lv,mg,mk,ml,mn,mr,ms,my,my_zaw,ne,' \\\r\n 'nl,no,om,or,pa,pl,ps,pt,ro,ru,sa,sd,si,sk,sl,so,sq,sr,su,sv,sw,ta,ta_rom,te,te_rom,th,tl,tr,ug,uk,' \\\r\n 'ur,ur_rom,uz,vi,xh,yi,zh,zh_classical'.split(',') if args.xlmr \\\r\n else 'af,sq,ar,an,hy,ast,az,ba,eu,bar,be,bn,bpy,bs,br,bg,my,ca,ceb,ce,zh,zh_classical,cv,hr,cs,da,nl,en,et,' \\\r\n 'fi,fr,gl,ka,de,el,gu,ht,he,hi,hu,is,io,id,ga,it,ja,jv,kn,kk,ky,ko,la,lv,lt,lmo,nds,lb,mk,mg,ms,ml,mr,' \\\r\n 'min,ne,new,no,nn,oc,fa,pms,pl,pt,pa,ro,ru,sco,sr,sh,scn,sk,sl,azb,es,su,sw,sv,tl,tg,ta,tt,te,tr,uk,ur,' \\\r\n 'uz,vi,vo,war,cy,fy,pnb,yo,th,mn'.split(',')\r\n random.seed(args.seed)\r\n n_langs = len(all_langs)\r\n n_samples = 5000\r\n ids = random.sample(range(0, 10000), n_samples)\r\n cls_model = LinearSVC(random_state=args.seed) if args.svc else LogisticRegression(random_state=args.seed)\r\n emb_path = 'cc-100_emb_2' if args.xlmr else 'mwiki_emb_2'\r\n\r\n for layer in range(13):\r\n if not args.lda:\r\n densray_path = '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/Q_' + str(\r\n n_langs) + '_new2.pt'\r\n if not os.path.exists(densray_path):\r\n embs = [torch.load(\r\n '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/' + all_langs[\r\n i] + '.pt')[ids, :] for i in range(len(all_langs))]\r\n dsr = DensRay(embs)\r\n dsr.fit()\r\n Q = dsr.eigvecs\r\n torch.save(Q, densray_path, _use_new_zipfile_serialization=False)\r\n torch.save(dsr.eigvals,\r\n '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/Eigvals_' + str(\r\n n_langs) + '_new2.pt',\r\n _use_new_zipfile_serialization=False)\r\n else:\r\n Q = torch.load(densray_path)\r\n else:\r\n lda_pth = '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/lda_104.model'\r\n if not os.path.exists(lda_pth):\r\n embs = torch.tensor(())\r\n labels = []\r\n for i in range(len(all_langs)):\r\n embs = torch.cat((embs, torch.load(\r\n '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/' + all_langs[\r\n i] + '.pt')[ids, :]))\r\n labels.extend([i] * n_samples)\r\n lda = LinearDiscriminantAnalysis()\r\n lda.fit(embs.numpy(), labels)\r\n joblib.dump(lda, lda_pth)\r\n else:\r\n lda = joblib.load(lda_pth)\r\n\r\n # CLS pairwise\r\n dims = [1]\r\n dims.extend(list(range(0, 200+1, 10))[1:])\r\n #dims.extend([104])\r\n #dims = list(range(50, 100 + 1, 10))\r\n acc_a, acc_b, acc_c = np.empty((0, len(dims))), np.empty((0, len(dims))), np.empty((0, len(dims)))\r\n for pair in random.sample(list(itertools.combinations(all_langs, 2)), 10):\r\n # X\r\n emb = torch.Tensor(()).cpu()\r\n for i in pair:\r\n e = torch.load(\r\n '/mounts/work/sliang/' + emb_path + '/' + args.mode + '/' + str(layer) + '/' + i + '.pt')[-10000:]\r\n eid = random.sample(list(range(len(e))), n_samples)\r\n emb = torch.cat((emb, e[eid]))\r\n if not args.lda:\r\n emb = torch.mm(emb, Q)\r\n emb = emb.cpu().detach().numpy()\r\n else:\r\n emb = emb.numpy()\r\n emb2 = lda.transform(emb)\r\n emb = np.hstack((emb2[:, :103], emb[:, :]))\r\n # Y\r\n y = []\r\n for i in range(2):\r\n y.extend([i] * n_samples)\r\n y = np.array(y)\r\n # split\r\n x_train, x_test, y_train, y_test = train_test_split(emb, y, random_state=args.seed, train_size=0.8)\r\n # train\r\n a, b, c = np.array([]), np.array([]), np.array([])\r\n #print(\"Y\")\r\n for dim in dims:\r\n aa, bb, cc = go(dim, cross=False)\r\n a = np.concatenate((a, [aa]))\r\n b = np.concatenate((b, [bb]))\r\n c = np.concatenate((c, [cc]))\r\n #print(pair, dim, aa, bb, cc)\r\n # pairwise summary\r\n acc_a = np.vstack((acc_a, a))\r\n acc_b = np.vstack((acc_b, b))\r\n acc_c = np.vstack((acc_c, c))\r\n for acc in [acc_a, acc_b, acc_c]:\r\n print(layer, \"mean\", ','.join(str(round(x, 4)) for x in acc.mean(axis=0)), sep=\",\")\r\n #print(layer, \"std\", ','.join(str(round(x, 4)) for x in acc.std(axis=0)), sep=\",\")\r\n #summary = [(acc.mean(axis=0),acc.std(axis=0)) for acc in [acc_a,acc_b,acc_c]]\r\n #for acc in [acc_a, acc_b, acc_c]:\r\n # print(n_langs, \"mean\", ','.join(str(round(x, 4)) for x in acc.mean(axis=0)), sep=\",\")\r\n","sub_path":"densray_lda.py","file_name":"densray_lda.py","file_ext":"py","file_size_in_byte":6991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"375486340","text":"import game\nimport time\nimport sys\nfrom random import randint\n\noriginalSet = game.values[:]\ndef play():\n \n numGames = int(sys.argv[1])\n while(numGames > 0):\n \n guessList = []\n\n allP = originalSet[:]\n workSet = originalSet[:]\n guess = \"1122\"\n \n startTime = time.time_ns()\n endTime = 0\n guesses = 0\n\n allstemp = []\n for i in range(5):\n for j in range(0, 4-i+1):\n allstemp.append((i, j))\n allScore = allstemp[:len(allstemp)-2]+allstemp[len(allstemp)-1:]\n\n while True:\n \n guessList.append(guess)\n\n temp = []\n cScore = []*len(allP)\n\n result = game.checkGuess(guess)\n guesses += 1\n #print(guess + \" | \" + result)\n\n if (result == \"BBBB\"):\n endTime = time.time_ns()\n print(guess + \" \" + str(guesses) + \" \" + str(endTime - startTime))\n break\n \n newSet = []\n\n for ans in workSet:\n if ans not in guessList:\n if (validateGuess(guess, ans) == result):\n newSet.append(ans)\n\n workSet = newSet\n\n for item in allP:\n if item not in guessList:\n hitCount = [0]*len(allScore)\n for s in workSet:\n evalResult = validateGuess(s, item)\n countProper = evalResult.count(\"B\")\n countTransposed = evalResult.count(\"W\")\n #print(str(countProper) + \" | \" + str(countTransposed))\n #print (str(allScore.index(countProper, countTransposed)))\n\n #if (hitCount.get(countProper, 0) > 0):\n #scoreCount[pegScore] += 1\n #else:\n #scoreCount[pegScore] = 1\n\n hitCount[allScore.index((countProper, countTransposed))] += 1\n cScore.append(len(workSet)-max(hitCount))\n else:\n cScore.append(0)\n\n maxScore = max(cScore)\n indices = [i for i, x in enumerate(cScore) if x == maxScore]\n\n change = False\n for i in range(len(indices)):\n if allP[indices[i]] in workSet:\n guess = allP[indices[i]]\n change = True\n break\n if change == False:\n guess = allP[indices[0]] \n \n if (len(workSet) < 1):\n endTime = time.time_ns()\n break\n\n numGames -= 1\n game.newAnswer()\n \n\n\n\n\ndef validateGuess(guessStr, supposed):\n result = \"\"\n tempAns = list(supposed[:])\n guess = list(guessStr)\n if (len(guess) > 4):\n return result\n\n for i in range(0, len(guess)):\n if(guess[i] == tempAns[i]):\n result += \"B\"\n tempAns[i] = \"X\"\n elif (guess[i] != tempAns[i] and guess[i] in tempAns):\n temp = tempAns.index(guess[i])\n if (guess[temp] == tempAns[temp]):\n result += \"B\"\n tempAns[temp] = \"X\"\n guess[temp] = \"Y\"\n else:\n result += \"W\"\n\n return result\n\nplay()\n","sub_path":"Knuth Right/fiveGuessMinimax2.py","file_name":"fiveGuessMinimax2.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"19012562","text":"class Compare:\n def __init__(self, c1, c2):\n self.company1 = c1\n self.company2 = c2\n\n def _greater(self, type, rationame):\n \"\"\"Return the company with the greater ratio.\"\"\"\n\n if self.company1.getallratios()[type][rationame] > \\\n self.company2.getallratios()[type][rationame]:\n return self.company1.getprofile['companyName']\n\n elif self.company2.getallratios()[type][rationame] > \\\n self.company1.getallratios()[type][rationame]:\n return self.company2.getallratios['companyName']\n\n else:\n return 'equal'\n\n def _less(self, type, rationame):\n if self.company1.getallratios()[type][rationame] < \\\n self.company2.getallratios()[type][rationame]:\n return self.company1.getprofile['companyName']\n\n elif self.company2.getallratios()[type][rationame] < \\\n self.company1.getallratios()[type][rationame]:\n return self.company2.getallratios['companyName']\n\n else:\n return 'equal'\n\n\n def compareliquidity(self):\n typer = 'liquidityMeasurementRatios'\n\n ratios = {'currentRatio':self._greater(typer, 'currentRatio'),\n 'quickRatio': self._greater(typer, 'quickRatio'),\n 'cashRatio': self._greater(typer,'cashRatio'),\n 'daysofSalesOutstanding':\n self._less(typer,\n 'daysofSalesOutstanding'),\n 'daysofInventoryOutstanding':\n self._less(typer, 'daysofInventoryOutstanding'),\n 'dayofPayablesOutstanding': 'equal',\n 'operatingCycle':self._less(typer, 'operatingCycle'),\n 'cashConversionCycle': self._less(typer, 'cashConversionCycle')}\n\n\n return ratios\n\n\n def compareprofit(self):\n typer = 'profitabilityIndicatorRatios'\n\n ratios = {'grossProfitMargin':\n self._greater(typer, 'grossProfitMargin'),\n 'operatingProfitMargin':\n self._greater(typer,\n 'operatingProfitMargin'),\n\n 'pretaxProfitMargin': self._greater(typer, 'pretaxProfitMargin'),\n 'netProfitMargin':\n self._greater(typer,\n 'netProfitMargin'),\n 'effectiveTaxRate':\n self._greater(typer, 'effectiveTaxRate'),\n 'returnOnAssets': self._greater(typer, 'returnOnAssets'),\n 'returnOnEquity': self._greater(typer, 'returnOnEquity'),\n 'returnOnCapitalEmployed':\n self._greater(typer, 'returnOnCapitalEmployed')}\n\n return ratios\n\n def compareall(self):\n all_ratios = {}\n\n\n for ratios in self.compareliquidity():\n all_ratios[ratios] = self.compareliquidity()[ratios]\n\n for ratios in self.compareprofit():\n all_ratios[ratios] = self.compareliquidity()[ratios]\n\n return all_ratios\n","sub_path":"easyfinancialstatements/Compare.py","file_name":"Compare.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"470344261","text":"import io\nimport math\nimport pynmea2\nimport threading\nfrom pymemcache.client import base\nimport socket\nfrom db import DB\nimport time\nimport utils\nfrom coordinates import Coordinate\nfrom datetime import date, datetime, timedelta\nfrom shapely.geometry import Point\nCoordinate.default_order = 'yx'\n\nclass TCPConnection:\n def __init__(self, sock=None):\n if sock is None:\n self.sock = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n else:\n self.sock = sock\n\n def connect(self, host, port):\n try:\n self.sock.connect((host, port))\n print('Successful Connection')\n except:\n print('Connection Failed')\n\n def close(self):\n self.sock.close()\n print(\"closed\")\n\n def readlines(self):\n try:\n data = self.sock.recv(1024).decode('utf-8')\n return data.split(\"\\r\\n\")\n except:\n self.sock.close()\n return None\n\n\nclass GPSData:\n def __init__(self):\n self.net= DB()\n self.listen = TCPConnection()\n self.client = base.Client(('localhost', 11211))\n self.nav=0\n self.spd=0\n self.lat=0\n self.lon=0\n self.rad=0\n self.ip=self.find_ip()\n self.last=datetime.now().timestamp()\n self.listen.connect(self.ip,8888)\n self.t1=None\n def find_ip(self):\n s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n myip=s.getsockname()[0].split(\".\")[0:3]\n ip=myip[0]+\".\"+myip[1]+\".\"+myip[2]+\".\"\n s.close()\n test=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n test.connect((self.net.get_ip(), 8888))\n test.close()\n print(\"OLD IP\")\n return self.net.get_ip()\n except:\n print(\"NEW IP LOOKING...\")\n for x in range(99,121):\n try:\n test.connect((ip+str(x), 8888))\n test.close()\n self.net.set_ip(ip+str(x))\n return ip+str(x)\n except Exception as e:\n print(x,repr(e))\n retry=self.find_ip()\n return retry\n\n def runner_child(self):\n err=0\n while True:\n try:\n lines = self.listen.readlines()\n for line in lines:\n if (line.startswith(\"$GNGGA\")):\n err=0\n data = pynmea2.parse(line)\n self.lat=data.latitude\n self.lon=data.longitude\n self.client.set('lat',str(data.latitude))\n self.client.set('lon', str(data.longitude))\n self.client.set('sat', str(data.num_sats))\n self.client.set('age', str(data.age_gps_data))\n\n elif (line.startswith(\"$GNRMC\")):\n err=0\n data = pynmea2.parse(line)\n self.spd=data.spd_over_grnd*0.5144\n tstamp=datetime.combine(data.datestamp, data.timestamp).timestamp()\n true_course=data.true_course or 0\n self.nav=true_course\n self.lat=data.latitude\n self.lon=data.longitude\n self.client.set('spd', str(data.spd_over_grnd*0.5144))\n self.client.set('nav', str(true_course))\n self.last=tstamp\n else:\n err+=1\n if err>200:\n err=0\n raise Exception('err', 'con')\n except Exception as e:\n print(\"GPS error\", repr(e))\n try:\n self.listen.close()\n time.sleep(10)\n self.listen = TCPConnection()\n time.sleep(2)\n self.listen.connect(self.ip,8888)\n time.sleep(5)\n except:\n print(\"reconnect error\")\n def pos(self):\n return Coordinate( self.lat , self.lon )\n def point(self):\n p=utils.to_utm(self.pos())\n return Point(p.x,p.y)\n def run(self):\n self.t1 = threading.Thread(target=self.runner_child)\n self.t1.start()\n def stop(self):\n self.t1.stop()\n","sub_path":"gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43051829","text":"import os\nimport pickle\nimport logging\nimport easydict\nimport os.path as p\nfrom typing import List\n\nimport pandas as pd\n\n\nlogger = logging.getLogger(\"feature\")\nlogger.setLevel(logging.INFO)\n\n\nclass FEBase:\n name: str = \"base_feature\" # Fature Engineering 이름\n fe_type: str = \"seq\"\n pre_fe: set = None # 선행되어야 하는 Feature Engineering\n no_fe: set = None # 같이 사용되면 안되는 Feature Engineering\n description = {\n \"userID\": \"사용자의 고유 번호입니다. 총 7,442명의 학생이 있습니다\",\n \"assessmentItemID\": \"사용자가 푼 문항의 일련 번호입니다.\",\n \"testID\": \"사용자가 푼 문항이 포함된 시험지의 일련 번호입니다.\",\n \"answerCode\": \"사용자가 푼 문항의 정답 여부를 담고 있는 이진 (0/1) 데이터입니다.\",\n \"Timestamp\": \"사용자가 문항을 푼 시간 정보입니다.\",\n \"KnowledgeTag\": \"사용자가 푼 문항의 고유 태그가 담겨져 있습니다.\",\n }\n\n @classmethod\n def get_save_path(cls, is_train):\n save_dir = p.join(os.environ[\"HOME\"], \"features\")\n prefix = \"train\" if is_train else \"test\"\n\n if not p.exists(save_dir):\n os.mkdir(save_dir)\n\n save_path = p.join(save_dir, f\"{prefix}_{cls.name}.pkl\")\n return save_path\n\n @classmethod\n def save_feature_df(cls, df: pd.DataFrame, save_path):\n with open(save_path, \"wb\") as f:\n pickle.dump(df, f)\n\n print(f\"save features dataframe to {save_path} ...\")\n\n @classmethod\n def load_feature_df(cls, load_path):\n with open(load_path, \"rb\") as f:\n right_df = pickle.load(f)\n\n print(f\"load features {load_path} to dataframe ... \")\n return right_df\n\n @classmethod\n def transform(cls, df):\n raise NotImplementedError\n\n\nclass FEPipeline:\n def __init__(self, args: easydict.EasyDict, fes: List[FEBase]):\n self.args = args\n self.fes = fes\n self.df = None\n\n assert \"root_dir\" in self.args, \"args.root_dir을 설정해주세요.\"\n\n log_file_handler = logging.FileHandler(p.join(self.args.root_dir, \"features.log\"))\n logger.addHandler(log_file_handler)\n logger.addHandler(logging.StreamHandler())\n\n def description(self):\n print(\"[Feature Descriptions]\")\n\n for fe in [FEBase] + self.fes:\n print(f\"\\nfeature name : {fe.name}\")\n print(f\"feature type : {fe.fe_type}\")\n for k, v in fe.description.items():\n print(f\" - {k:<20} : {v}\")\n\n def debug(self):\n pre_fe = set()\n\n for fe in self.fes:\n if fe.no_fe is not None:\n if len(fe.no_fe.intersection(pre_fe)) != 0:\n raise ValueError(f\"{fe.name}'s fe.no_fe: {fe.no_fe} in pre_fe({pre_fe})\")\n if fe.pre_fe is not None:\n if len(fe.pre_fe.difference(pre_fe)) != 0:\n raise ValueError(f\"{fe.name}'s fe.pre_fe: {fe.pre_fe} not in pre_fe({pre_fe})\")\n\n pre_fe.add(fe.name)\n\n def transform(self, df, is_train):\n logger.info(\"Feature Engineering Start ... \")\n original_columns = df.columns\n self.df = df\n\n for fe in self.fes:\n self.df = fe.transform(self.df, is_train)\n logger.info(f\"\\nFeature Engineering Name: {fe.name}\")\n\n for k, v in fe.description.items():\n logger.info(f\"\\n{k:<15} : {v}\")\n logger.info(f\"dtype: {self.df[k].dtype}\")\n logger.info(\"[Examples]\")\n\n for idx in range(0, min(1000, len(self.df)), 100):\n logger.info(f\"INDEX {idx:<04}: {self.df.iloc[idx][k]}\")\n\n logger.info(\"Feature Engineering End ... \")\n logger.info(f\"Original DataFrame Keywords: {original_columns}\")\n logger.info(f\"Feature Added DataFrame Keywords: {self.df.columns}\")\n \n self.df = self.df.sort_values(by=['userID','Timestamp']).reset_index(drop=True)\n \n return self.df\n\n def get_feature_df(self, df, keys):\n return df[keys]\n","sub_path":"dongwoo/LGBMwithRowData/fe/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149646260","text":"\"\"\"\nQuestion:\nWrite a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.\nThe numbers obtained should be printed in a comma-separated sequence on a single line.\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\"\"\"\n\n\ndef digit_even_numbers(numbers):\n numbers = numbers.split(\",\")\n numbers = [i for i in range(int(numbers[0]), int(numbers[1]) + 1)]\n b = [0, 2, 4, 6, 8]\n result = []\n for i in numbers:\n integers = (list(map(int, str(i))))\n if integers[0] % 2 == 0 and integers[1] % 2 == 0 and integers[2] % 2 == 0 and integers[3] % 2 == 0:\n result.append(i)\n return result\n","sub_path":"100+ Python challenging programming exercises/Level_2/Q12.py","file_name":"Q12.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"500874658","text":"# fileparse.py\nimport csv\n\n\ndef parse_csv(nombre_archivo, select=[], types=[], has_headers=True):\n '''\n Parsea un archivo CSV en una lista de registros\n '''\n if not(has_headers) and len(select):\n raise RuntimeError('select parameter invalid when has_headers is set to True')\n\n with open(nombre_archivo) as f:\n rows = csv.reader(f)\n\n if has_headers:\n # Lee los encabezados\n headers = next(rows)\n\n registros = []\n for row in rows:\n if not row: # Saltea filas sin datos\n continue\n \n if has_headers:\n registros.append(dict(zip(headers, row)))\n else: \n registros.append(list(row))\n\n remove_headers = []\n\n if len(select):\n remove_headers = [ header for header in headers if not(header in select)]\n for header_to_remove in remove_headers:\n for register in registros:\n register.pop(header_to_remove, None)\n\n if len(types):\n if has_headers:\n \n if len(types) != (len(headers)-len(remove_headers)):\n raise RuntimeError('TypesSizeUncompatible')\n \n for register in registros:\n keywords = dict(zip(register.keys(),types))\n for key,single_type in keywords.items():\n register[key] = single_type(register[key])\n else:\n typed_registers = []\n # breakpoint()\n for register in registros:\n typed_register = []\n for i,data in enumerate(register):\n typed_register.append(types[i](data))\n typed_registers.append(tuple(typed_register))\n return typed_registers\n return registros\n\n\nparse_csv('../Data/camion.csv',\n select=['cajones', 'precio'], types=[int, float])\n\nparse_csv('../Data/precios.csv', types=[str, float], has_headers=False)\n","sub_path":"class6/fileparse.py","file_name":"fileparse.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"573960256","text":"import pandas as pd\nimport plotly.graph_objs as go\nimport plotly as py\nimport config\n\n\nauction_days = pd.read_csv(r'app\\static\\tables\\dep_auc_days.csv')\n\ntrace_borrowed = go.Scatter(\n x=auction_days['Date'],\n y=auction_days['Borrowed'],\n showlegend=True,\n name='Привлеченные средства, трлн руб.',\n marker=dict(color='orange',\n opacity=0.1,),\n yaxis='y1')\n\ntrace_offered = go.Scatter(\n x=auction_days['Date'],\n y=auction_days['Offered'],\n showlegend=True,\n name='Предложение Банка России, трлн руб.',\n marker=dict(color='#000',\n opacity=0.1,),\n fill='tozeroy',\n yaxis='y1')\n\ntrace_cut = go.Scatter(\n x=auction_days['Date'],\n y=auction_days['Cut Rat'],\n showlegend=True,\n name='Ставка отсечения, %',\n marker=dict(color='red',\n line=dict(width=1)),\n yaxis='y3')\n\ntrace_avg = go.Scatter(\n x=auction_days['Date'],\n y=auction_days['Avg Rate'],\n showlegend=True,\n name='Средневзвешенная ставка, %',\n marker=dict(color='blue',\n line=dict(width=1)),\n yaxis='y3')\n\ndata = [trace_offered, trace_borrowed, trace_cut, trace_avg]\n\nlayout = go.Layout(title='Аукционы ЦБ РФ 1-6 дней',\n font=dict(size=config.LAYOUT_FONT_SIZE),\n legend=dict(\n orientation='h',\n font=dict(size=config.LEGEND_FONT_SIZE),\n ),\n yaxis1=dict(\n range=[0, auction_days['Offered'].max()*3]\n ),\n xaxis1=dict(\n dtick='M1',\n tickformat='%m.%y',\n ),\n yaxis3=dict(\n overlaying='y1',\n side='right'\n ),\n width=config.CURRENCY_2_WIDTH,\n height=config.CURRENCY_2_HEIGHT,\n margin=config.MARGINS\n )\n\nfig = go.Figure(data=data, layout=layout)\nconfig={'showLink': False}\npy.offline.plot(fig, filename=r'app\\templates\\auction_days.html', auto_open=False, config=config)","sub_path":"auction_days.py","file_name":"auction_days.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485176347","text":"''' \nleetcode - 62 - unique paths - https://leetcode.com/problems/unique-paths/\ntime complexity - O(2^N*2)\napproach - recursive approach\n\n'''\nclass Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n i=0\n j=0\n return self.helper(0,0,m,n)\n \n def helper(self,i,j,m,n):\n #base case\n if (i==m-1 and j==n-1): return 1\n if (i>=m or j>=n): return 0\n \n #logic\n right=self.helper(i,j+1,m,n)\n bottom=self.helper(i+1,j,m,n)\n return right+bottom\n \n'''\nApproach - DP - bottom-up\nTime complexity - O(M*N)\nspace complexity - O(M*N)\n'''\nclass Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n #dp =[[ for _ in range(n+1)] for _ in range(m+1)]\n dp = [[0]*(n+1) for _ in range(m+1)]\n dp[m-1][n-1]=1\n \n for i in range(m-1,-1,-1):\n for j in range(n-1,-1,-1):\n if (i==m-1 and j==n-1): continue\n dp[i][j]=dp[i+1][j]+dp[i][j+1]\n return dp[0][0]\n \n \n \n''''\nApproach - DP - Tom bottom\n'''\nclass Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n \n dp = [[1]*(n) for _ in range(m)]\n \n for i in range(1,m):\n for j in range(1,n):\n \n dp[i][j]=dp[i-1][j]+dp[i][j-1]\n return dp[m-1][n-1]\n \n ","sub_path":"Problem-109.py","file_name":"Problem-109.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"235159464","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2015-2021 BigML\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\n\"\"\" Creating datasets with missing values and errors counters\n\n\"\"\"\nfrom .world import world, setup_module, teardown_module, show_doc\nfrom . import create_source_steps as source_create\nfrom . import create_dataset_steps as dataset_create\nfrom . import read_dataset_steps as dataset_read\nfrom . import create_prediction_steps as prediction_create\nfrom . import compare_predictions_steps as prediction_compare\nfrom . import create_model_steps as model_create\n\nclass TestMissingsAndErrors(object):\n\n def setup(self):\n \"\"\"\n Debug information\n \"\"\"\n print(\"\\n-------------------\\nTests in: %s\\n\" % __name__)\n\n def teardown(self):\n \"\"\"\n Debug information\n \"\"\"\n print(\"\\nEnd of tests in: %s\\n-------------------\\n\" % __name__)\n\n def test_scenario1(self):\n \"\"\"\n Scenario: Successfully obtaining missing values counts:\n Given I create a data source uploading a \"\" file\n And I wait until the source is ready less than secs\n And I update the source with params \"\"\n And I create a dataset\n And I wait until the dataset is ready less than secs\n When I ask for the missing values counts in the fields\n Then the missing values counts dict is \"\"\n\n Examples:\n | data | time_1 | params | time_2 |missing_values |\n | ../data/iris_missing.csv | 30 | {\"fields\": {\"000000\": {\"optype\": \"numeric\"}}} |30 |{\"000000\": 1} |\n \"\"\"\n print(self.test_scenario1.__doc__)\n examples = [\n ['data/iris_missing.csv', '30', '{\"fields\": {\"000000\": {\"optype\": \"numeric\"}}}', '30', '{\"000000\": 1}']]\n for example in examples:\n print(\"\\nTesting with:\\n\", example)\n source_create.i_upload_a_file(self, example[0])\n source_create.the_source_is_finished(self, example[1])\n source_create.i_update_source_with(self, example[2])\n dataset_create.i_create_a_dataset(self)\n dataset_create.the_dataset_is_finished_in_less_than(self,\n example[3])\n dataset_read.i_get_the_missing_values(self)\n dataset_read.i_get_the_properties_values(\n self, 'missing values count', example[4])\n\n def test_scenario2(self):\n \"\"\"\n Scenario: Successfully obtaining parsing error counts:\n Given I create a data source uploading a \"\" file\n And I wait until the source is ready less than secs\n And I update the source with params \"\"\n And I create a dataset\n And I wait until the dataset is ready less than secs\n When I ask for the error counts in the fields\n Then the error counts dict is \"\"\n\n Examples:\n | data | time_1 | params | time_2 |error_values |\n | ../data/iris_missing.csv | 30 | {\"fields\": {\"000000\": {\"optype\": \"numeric\"}}} |30 |{\"000000\": 1} |\n \"\"\"\n print(self.test_scenario2.__doc__)\n examples = [\n ['data/iris_missing.csv', '30', '{\"fields\": {\"000000\": {\"optype\": \"numeric\"}}}', '30', '{\"000000\": 1}']]\n for example in examples:\n print(\"\\nTesting with:\\n\", example)\n source_create.i_upload_a_file(self, example[0])\n source_create.the_source_is_finished(self, example[1])\n source_create.i_update_source_with(self, example[2])\n dataset_create.i_create_a_dataset(self)\n dataset_create.the_dataset_is_finished_in_less_than(self,\n example[3])\n dataset_read.i_get_the_errors_values(self)\n dataset_read.i_get_the_properties_values(\n self, 'error counts', example[4])\n\n def test_scenario3(self):\n \"\"\"\n Scenario: Successfully comparing predictions:\n Given I create a data source uploading a \"\" file\n And I wait until the source is ready less than secs\n And I create a dataset\n And I wait until the dataset is ready less than secs\n And I create a model\n And I wait until the model is ready less than secs\n And I create a local model\n When I create a prediction for \"\"\n Then the prediction for \"\" is \"\"\n And I create a local prediction for \"\"\n Then the local prediction is \"\"\n\n Examples:\n | data | time_1 | time_2 | time_3 | data_input | objective | prediction |\n\n \"\"\"\n examples = [\n ['data/iris_missing.csv', '30', '{\"fields\": {\"000000\": {\"optype\": \"numeric\"}}, \"source_parser\": {\"missing_tokens\": [\"foo\"]}}', '30', '{\"sepal length\": \"foo\", \"petal length\": 3}', '000004', 'Iris-versicolor'],\n ['data/iris_missing.csv', '30', '{\"fields\": {\"000000\": {\"optype\": \"numeric\"}}, \"source_parser\": {\"missing_tokens\": [\"foo\"]}}', '30', '{\"sepal length\": \"foo\", \"petal length\": 5, \"petal width\": 1.5}', '000004', 'Iris-virginica']]\n\n show_doc(self.test_scenario3, examples)\n for example in examples:\n print(\"\\nTesting with:\\n\", example)\n source_create.i_upload_a_file(self, example[0])\n source_create.the_source_is_finished(self, example[1])\n source_create.i_update_source_with(self, example[2])\n dataset_create.i_create_a_dataset(self)\n dataset_create.the_dataset_is_finished_in_less_than(self, example[3])\n model_create.i_create_a_model(self)\n model_create.the_model_is_finished_in_less_than(self, example[3])\n prediction_compare.i_create_a_local_model(self)\n prediction_create.i_create_a_prediction(self, example[4])\n prediction_create.the_prediction_is(self, example[5], example[6])\n prediction_compare.i_create_a_local_prediction(self, example[4])\n prediction_compare.the_local_prediction_is(self, example[6])\n","sub_path":"bigml/tests/test_19_missing_and_errors.py","file_name":"test_19_missing_and_errors.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"60402875","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport imageio\nimport shutil\nimport os\n\ndef grid_animator(grid_filename=\"grid.npy\", moves_filename=\"moves_broad.npy\",\\\n\t\t\t\t shortest_path_filename=\"shortest_path.npy\", delete_img=True,\n\t\t\t\t savefile_filename=\"movie.gif\", reserved_numbers=[]):\n\t\"\"\"\n\tAnimating a path-finding algorithm on a square board. Reads numpy-arrays from file.\n\t{{grid.npy}} = (n,m) start board. -1 for unpassable, 0 for passable, 3 for start, 4 for target.\n\t{{moves.npy}} = (x,2) or (x,y,2). Former shows every tile-search seperately, in order.\n\t\t\t\t\tLatter shows searches of (y) moves at a time. (y) can vary through the search.\n\t{{shortest_path.npy}} = (z,2). Tiles included in shortest path. Displayed at the end.\n\t{{reserved_numbers}} = If given, these numbers are never overwritten.\n\t\"\"\"\n\n\tcurrent_path = os.path.dirname(os.path.realpath(__file__))\n\tfig_path = os.path.join(current_path, \"fig\")\n\tif not os.path.exists(fig_path):\n\t\tos.makedirs(fig_path)\n\n\tgrid = np.load(grid_filename)\n\tmoves_array = np.load(moves_filename)\n\tshortest_path = np.load(shortest_path_filename)\n\tgrid_size = np.shape(grid)\n\tnr_moves = len(moves_array)\n\tplt.matshow(grid)\n\tplt.savefig(\"fig/plot_00000.png\")\n\tplt.close()\n\n\tfor move_count, move in enumerate(moves_array):\n\t\tif np.shape(move) == (2,) and grid[move[0],move[1]] not in reserved_numbers:\n\t\t\tgrid[move[0],move[1]] = 2\n\t\telse:\n\t\t\tfor sub_move in move:\n\t\t\t\tif grid[sub_move[0],sub_move[1]] not in reserved_numbers:\n\t\t\t\t\tgrid[sub_move[0],sub_move[1]] = 2\n\t\tplt.matshow(grid)\n\t\tplt.savefig(\"fig/plot_%.5d.png\"%(move_count+1))\n\t\tplt.close()\n\t\tif np.shape(move) == (2,) and grid[move[0],move[1]] not in reserved_numbers:\n\t\t\tgrid[move[0],move[1]] = 1\n\t\telse:\n\t\t\tfor sub_move in move:\n\t\t\t\tif grid[sub_move[0],sub_move[1]] not in reserved_numbers:\n\t\t\t\t\tgrid[sub_move[0],sub_move[1]] = 1\n\n\tfor i in range(len(shortest_path)):\n\t\tif grid[shortest_path[i,0],shortest_path[i,1]] not in reserved_numbers:\n\t\t\tgrid[shortest_path[i,0],shortest_path[i,1]] = 2\n\tplt.matshow(grid)\n\tplt.savefig(\"fig/plot_%.5d.png\"%(nr_moves+1))\n\tplt.close()\n\n\timages = []\n\tfor i in range(nr_moves+1):\n\t\timages.append( imageio.imread(\"fig/plot_%.5d.png\"%i) )\n\tfor i in range(10): # Adding multiple of last img to make it stay longer.\n\t\timages.append( imageio.imread(\"fig/plot_%.5d.png\"%(nr_moves+1)))\n\timageio.mimsave(\"movie.gif\", images)\n\n\tif delete_img:\n\t\tshutil.rmtree(fig_path)\n\nif __name__ == \"__main__\":\n\tgrid_animator()","sub_path":"christmas_challenges/luke24/grid_animator.py","file_name":"grid_animator.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97519268","text":"# This file is part of the Reproducible and Reusable Data Analysis Workflow\n# Server (flowServ).\n#\n# Copyright (C) 2019-2020 NYU.\n#\n# flowServ is free software; you can redistribute it and/or modify it under the\n# terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Helper methods to initialize the database state via the service API.\"\"\"\n\nimport os\n\nfrom flowserv.service.run.argument import FILE\nfrom flowserv.tests.files import FakeStream\n\nimport flowserv.util as util\n\n\ndef create_group(api, workflow_id, users):\n \"\"\"Create a new group for the given workflow.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n workflow_id: string\n Unique workflow identifier.\n users: list(string)\n Identifier for group members.\n\n Returns\n -------\n string\n \"\"\"\n doc = api.groups().create_group(\n workflow_id=workflow_id,\n name=util.get_unique_identifier(),\n user_id=users[0],\n members=users\n )\n return doc['id']\n\n\ndef create_ranking(api, workflow_id, user_id, count):\n \"\"\"Create a ranking with n groups for the Hello World benchmark having a\n successful run each. Returns the group identifier in order of creation.\n The avg_len value is increased as groups are created and the max_len value\n is decreased.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n workflow_id: string\n Unique workflow identifier.\n user_id: string\n Identifier for the group owner.\n count: int\n Number of groups that are created for the workflow.\n\n Returns\n -------\n list(string)\n \"\"\"\n groups = list()\n for i in range(count):\n group_id = create_group(api, workflow_id=workflow_id, users=[user_id])\n # Start the new run. Then set it into SUCESS state.\n run_id, file_id = start_hello_world(api, group_id, user_id)\n data = {'avg_count': i, 'max_len': 100 - i, 'max_line': 'A'*i}\n write_results(\n api,\n run_id,\n [(data, None, 'results/analytics.json')]\n )\n api.runs().update_run(\n run_id=run_id,\n state=api.engine.success(\n run_id,\n files=['results/analytics.json']\n )\n )\n groups.append(group_id)\n return groups\n\n\ndef create_workflow(api, source, specfile=None):\n \"\"\"Start a new workflow for a given template.\"\"\"\n return api.workflows().create_workflow(\n name=util.get_unique_identifier(),\n source=source,\n specfile=specfile\n )['id']\n\n\ndef create_user(api):\n \"\"\"Register a new user with the API and return the unique user identifier.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n\n Returns\n -------\n string\n \"\"\"\n user_name = util.get_unique_identifier()\n doc = api.users().register_user(\n username=user_name,\n password=user_name,\n verify=False\n )\n return doc['id']\n\n\ndef start_hello_world(api, group_id, user_id):\n \"\"\"Start a new run for the Hello World template. Returns the run identifier\n and the identifier for the input file.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n group_id: string\n Unique group identifier.\n user_id: string\n Unique user identifier.\n\n Returns\n -------\n string, string\n \"\"\"\n file_id = api.uploads().upload_file(\n group_id=group_id,\n file=FakeStream(data=['Alice', 'Bob'], format='txt/plain'),\n name='n.txt',\n user_id=user_id\n )['id']\n run_id = api.runs().start_run(\n group_id=group_id,\n arguments=[{'id': 'names', 'value': FILE(file_id=file_id)}],\n user_id=user_id\n )['id']\n api.engine.start(run_id)\n return run_id, file_id\n\n\ndef start_run(api, group_id, user_id, arguments=list()):\n \"\"\"Start a new workflow run for a given group. Returns the identifier of\n the started run.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n group_id: string\n Unique group identifier.\n user_id: string\n Unique user identifier.\n arguments: list, default=None\n Optional arguments to run the workflow.\n\n Returns\n -------\n string\n \"\"\"\n return api.runs().start_run(\n group_id=group_id,\n arguments=arguments,\n user_id=user_id\n )['id']\n\n\ndef upload_file(api, group_id, user_id, file):\n \"\"\"Upload an input file for a workflow run. returns the file identifier.\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n group_id: string\n Unique group identifier.\n user_id: string\n Unique user identifier.\n file: FileObject\n Uploaded file.\n\n Returns\n -------\n string\n \"\"\"\n return api.uploads().upload_file(\n group_id=group_id,\n file=file,\n name=util.get_short_identifier(),\n user_id=user_id\n )['id']\n\n\ndef write_results(api, run_id, files):\n \"\"\"Create a reult file for a given workflow run.\n\n\n Parameters\n ----------\n api: flowserv.service.api.API\n Service API manager.\n run_id: string\n Unique run identifier.\n files: list\n List of 3-tuples containing the file data, format, and relative path.\n \"\"\"\n run = api.run_manager.get_run(run_id)\n for data, format, rel_path in files:\n filename = os.path.join(run.get_rundir(), rel_path)\n FakeStream(data=data, format=format).save(filename)\n","sub_path":"flowserv/tests/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"457041303","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\"\"\"karbor common internal object model\"\"\"\n\nimport contextlib\nimport datetime\n\nfrom oslo_log import log as logging\nfrom oslo_versionedobjects import base\nfrom oslo_versionedobjects import fields\n\nfrom karbor import db\nfrom karbor.db.sqlalchemy import models\nfrom karbor import exception\nfrom karbor.i18n import _\nfrom karbor import objects\n\n\nLOG = logging.getLogger('object')\nremotable = base.remotable\nremotable_classmethod = base.remotable_classmethod\nobj_make_list = base.obj_make_list\n\n\nclass KarborObjectRegistry(base.VersionedObjectRegistry):\n def registration_hook(self, cls, index):\n setattr(objects, cls.obj_name(), cls)\n # For Versioned Object Classes that have a model store the model in\n # a Class attribute named model\n try:\n model_name = cls.obj_name()\n cls.model = getattr(models, model_name)\n except (ImportError, AttributeError):\n pass\n\n\nclass KarborObject(base.VersionedObject):\n OBJ_SERIAL_NAMESPACE = 'karbor_object'\n OBJ_PROJECT_NAMESPACE = 'karbor'\n\n def karbor_obj_get_changes(self):\n \"\"\"Returns a dict of changed fields with tz unaware datetimes.\n\n Any timezone aware datetime field will be converted to UTC timezone\n and returned as timezone unaware datetime.\n\n This will allow us to pass these fields directly to a db update\n method as they can't have timezone information.\n \"\"\"\n # Get dirtied/changed fields\n changes = self.obj_get_changes()\n\n # Look for datetime objects that contain timezone information\n for k, v in changes.items():\n if isinstance(v, datetime.datetime) and v.tzinfo:\n # Remove timezone information and adjust the time according to\n # the timezone information's offset.\n changes[k] = v.replace(tzinfo=None) - v.utcoffset()\n\n # Return modified dict\n return changes\n\n @base.remotable_classmethod\n def get_by_id(cls, context, id, *args, **kwargs):\n # To get by id we need to have a model and for the model to\n # have an id field\n if 'id' not in cls.fields:\n msg = (_('VersionedObject %s cannot retrieve object by id.') %\n (cls.obj_name()))\n raise NotImplementedError(msg)\n\n model = getattr(models, cls.obj_name())\n orm_obj = db.get_by_id(context, model, id, *args, **kwargs)\n kargs = {}\n if hasattr(cls, 'DEFAULT_EXPECTED_ATTR'):\n kargs = {'expected_attrs': getattr(cls, 'DEFAULT_EXPECTED_ATTR')}\n return cls._from_db_object(context, cls(context), orm_obj, **kargs)\n\n def refresh(self):\n # To refresh we need to have a model and for the model to have an id\n # field\n if 'id' not in self.fields:\n msg = (_('VersionedObject %s cannot retrieve object by id.') %\n (self.obj_name()))\n raise NotImplementedError(msg)\n\n current = self.get_by_id(self._context, self.id)\n\n for field in self.fields:\n # Only update attributes that are already set. We do not want to\n # unexpectedly trigger a lazy-load.\n if self.obj_attr_is_set(field):\n if self[field] != current[field]:\n self[field] = current[field]\n self.obj_reset_changes()\n\n def __contains__(self, name):\n # We're using obj_extra_fields to provide aliases for some fields while\n # in transition period. This override is to make these aliases pass\n # \"'foo' in obj\" tests.\n return name in self.obj_extra_fields or super(KarborObject,\n self).__contains__(name)\n\n\nclass KarborObjectDictCompat(base.VersionedObjectDictCompat):\n \"\"\"Mix-in to provide dictionary key access compat.\n\n If an object needs to support attribute access using\n dictionary items instead of object attributes, inherit\n from this class. This should only be used as a temporary\n measure until all callers are converted to use modern\n attribute access.\n\n NOTE(berrange) This class will eventually be deleted.\n \"\"\"\n\n def get(self, key, value=base._NotSpecifiedSentinel):\n \"\"\"For backwards-compatibility with dict-based objects.\n\n NOTE(danms): May be removed in the future.\n \"\"\"\n if key not in self.obj_fields:\n # NOTE(jdg): There are a number of places where we rely on the\n # old dictionary version and do a get(xxx, None).\n # The following preserves that compatibility but in\n # the future we'll remove this shim altogether so don't\n # rely on it.\n LOG.debug('Karbor object %(object_name)s has no '\n 'attribute named: %(attribute_name)s',\n {'object_name': self.__class__.__name__,\n 'attribute_name': key})\n return None\n if (value != base._NotSpecifiedSentinel and\n not self.obj_attr_is_set(key)):\n return value\n else:\n try:\n return getattr(self, key)\n except (exception.ObjectActionError, NotImplementedError):\n # Exception when haven't set a value for non-lazy\n # loadable attribute, but to mimic typical dict 'get'\n # behavior we should still return None\n return None\n\n\ndef DateTimeField(**kwargs):\n return fields.DateTimeField(tzinfo_aware=False, **kwargs)\n\n\nclass KarborPersistentObject(object):\n \"\"\"Mixin class for Persistent objects.\n\n This adds the fields that we use in common for all persistent objects.\n \"\"\"\n fields = {\n 'created_at': DateTimeField(nullable=True),\n 'updated_at': DateTimeField(nullable=True),\n 'deleted_at': DateTimeField(nullable=True),\n 'deleted': fields.BooleanField(default=False),\n }\n\n @contextlib.contextmanager\n def obj_as_admin(self):\n \"\"\"Context manager to make an object call as an admin.\n\n This temporarily modifies the context embedded in an object to\n be elevated() and restores it after the call completes. Example\n usage:\n\n with obj.obj_as_admin():\n obj.save()\n \"\"\"\n if self._context is None:\n raise exception.OrphanedObjectError(method='obj_as_admin',\n objtype=self.obj_name())\n\n original_context = self._context\n self._context = self._context.elevated()\n try:\n yield\n finally:\n self._context = original_context\n\n\nclass KarborComparableObject(base.ComparableVersionedObject):\n def __eq__(self, obj):\n if hasattr(obj, 'obj_to_primitive'):\n return self.obj_to_primitive() == obj.obj_to_primitive()\n return False\n\n\nclass ObjectListBase(base.ObjectListBase):\n pass\n\n\nclass KarborObjectSerializer(base.VersionedObjectSerializer):\n OBJ_BASE_CLASS = KarborObject\n\n\nclass DictOfDictOfStringsField(fields.AutoTypedField):\n AUTO_TYPE = fields.Dict(fields.Dict(fields.String(), nullable=True))\n","sub_path":"karbor-1.3.0/karbor/objects/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"47538833","text":"from typing import Tuple, Optional, Union\n\nfrom mlagents.trainers.exception import UnityTrainerException\nfrom mlagents.trainers.torch.layers import linear_layer, Initialization, Swish\n\nimport torch\nfrom torch import nn\n\n\nclass Normalizer(nn.Module):\n def __init__(self, vec_obs_size: int):\n super().__init__()\n self.register_buffer(\"normalization_steps\", torch.tensor(1))\n self.register_buffer(\"running_mean\", torch.zeros(vec_obs_size))\n self.register_buffer(\"running_variance\", torch.ones(vec_obs_size))\n\n def forward(self, inputs: torch.Tensor) -> torch.Tensor:\n normalized_state = torch.clamp(\n (inputs - self.running_mean)\n / torch.sqrt(self.running_variance / self.normalization_steps),\n -5,\n 5,\n )\n return normalized_state\n\n def update(self, vector_input: torch.Tensor) -> None:\n steps_increment = vector_input.size()[0]\n total_new_steps = self.normalization_steps + steps_increment\n\n input_to_old_mean = vector_input - self.running_mean\n new_mean = self.running_mean + (input_to_old_mean / total_new_steps).sum(0)\n\n input_to_new_mean = vector_input - new_mean\n new_variance = self.running_variance + (\n input_to_new_mean * input_to_old_mean\n ).sum(0)\n # Update in-place\n self.running_mean.data.copy_(new_mean.data)\n self.running_variance.data.copy_(new_variance.data)\n self.normalization_steps.data.copy_(total_new_steps.data)\n\n def copy_from(self, other_normalizer: \"Normalizer\") -> None:\n self.normalization_steps.data.copy_(other_normalizer.normalization_steps.data)\n self.running_mean.data.copy_(other_normalizer.running_mean.data)\n self.running_variance.copy_(other_normalizer.running_variance.data)\n\n\ndef conv_output_shape(\n h_w: Tuple[int, int],\n kernel_size: Union[int, Tuple[int, int]] = 1,\n stride: int = 1,\n padding: int = 0,\n dilation: int = 1,\n) -> Tuple[int, int]:\n \"\"\"\n Calculates the output shape (height and width) of the output of a convolution layer.\n kernel_size, stride, padding and dilation correspond to the inputs of the\n torch.nn.Conv2d layer (https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html)\n :param h_w: The height and width of the input.\n :param kernel_size: The size of the kernel of the convolution (can be an int or a\n tuple [width, height])\n :param stride: The stride of the convolution\n :param padding: The padding of the convolution\n :param dilation: The dilation of the convolution\n \"\"\"\n from math import floor\n\n if not isinstance(kernel_size, tuple):\n kernel_size = (int(kernel_size), int(kernel_size))\n h = floor(\n ((h_w[0] + (2 * padding) - (dilation * (kernel_size[0] - 1)) - 1) / stride) + 1\n )\n w = floor(\n ((h_w[1] + (2 * padding) - (dilation * (kernel_size[1] - 1)) - 1) / stride) + 1\n )\n return h, w\n\n\ndef pool_out_shape(h_w: Tuple[int, int], kernel_size: int) -> Tuple[int, int]:\n \"\"\"\n Calculates the output shape (height and width) of the output of a max pooling layer.\n kernel_size corresponds to the inputs of the\n torch.nn.MaxPool2d layer (https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html)\n :param kernel_size: The size of the kernel of the convolution\n \"\"\"\n height = (h_w[0] - kernel_size) // 2 + 1\n width = (h_w[1] - kernel_size) // 2 + 1\n return height, width\n\n\nclass VectorEncoder(nn.Module):\n def __init__(\n self,\n input_size: int,\n hidden_size: int,\n num_layers: int,\n normalize: bool = False,\n ):\n self.normalizer: Optional[Normalizer] = None\n super().__init__()\n self.layers = [\n linear_layer(\n input_size,\n hidden_size,\n kernel_init=Initialization.KaimingHeNormal,\n kernel_gain=1.0,\n )\n ]\n self.layers.append(Swish())\n if normalize:\n self.normalizer = Normalizer(input_size)\n\n for _ in range(num_layers - 1):\n self.layers.append(\n linear_layer(\n hidden_size,\n hidden_size,\n kernel_init=Initialization.KaimingHeNormal,\n kernel_gain=1.0,\n )\n )\n self.layers.append(Swish())\n self.seq_layers = nn.Sequential(*self.layers)\n\n def forward(self, inputs: torch.Tensor) -> torch.Tensor:\n if self.normalizer is not None:\n inputs = self.normalizer(inputs)\n return self.seq_layers(inputs)\n\n def copy_normalization(self, other_encoder: \"VectorEncoder\") -> None:\n if self.normalizer is not None and other_encoder.normalizer is not None:\n self.normalizer.copy_from(other_encoder.normalizer)\n\n def update_normalization(self, inputs: torch.Tensor) -> None:\n if self.normalizer is not None:\n self.normalizer.update(inputs)\n\n\nclass VectorAndUnnormalizedInputEncoder(VectorEncoder):\n \"\"\"\n Encoder for concatenated vector input (can be normalized) and unnormalized vector input.\n This is used for passing inputs to the network that should not be normalized, such as\n actions in the case of a Q function or task parameterizations. It will result in an encoder with\n this structure:\n ____________ ____________ ____________\n | Vector | | Normalize | | Fully |\n | | --> | | --> | Connected | ___________\n |____________| |____________| | | | Output |\n ____________ | | --> | |\n |Unnormalized| | | |___________|\n | Input | ---------------------> | |\n |____________| |____________|\n \"\"\"\n\n def __init__(\n self,\n input_size: int,\n hidden_size: int,\n unnormalized_input_size: int,\n num_layers: int,\n normalize: bool = False,\n ):\n super().__init__(\n input_size + unnormalized_input_size,\n hidden_size,\n num_layers,\n normalize=False,\n )\n if normalize:\n self.normalizer = Normalizer(input_size)\n else:\n self.normalizer = None\n\n def forward( # pylint: disable=W0221\n self, inputs: torch.Tensor, unnormalized_inputs: Optional[torch.Tensor] = None\n ) -> None:\n if unnormalized_inputs is None:\n raise UnityTrainerException(\n \"Attempted to call an VectorAndUnnormalizedInputEncoder without an unnormalized input.\"\n ) # Fix mypy errors about method parameters.\n if self.normalizer is not None:\n inputs = self.normalizer(inputs)\n return self.seq_layers(torch.cat([inputs, unnormalized_inputs], dim=-1))\n\n\nclass SimpleVisualEncoder(nn.Module):\n def __init__(\n self, height: int, width: int, initial_channels: int, output_size: int\n ):\n super().__init__()\n self.h_size = output_size\n conv_1_hw = conv_output_shape((height, width), 8, 4)\n conv_2_hw = conv_output_shape(conv_1_hw, 4, 2)\n self.final_flat = conv_2_hw[0] * conv_2_hw[1] * 32\n\n self.conv_layers = nn.Sequential(\n nn.Conv2d(initial_channels, 16, [8, 8], [4, 4]),\n nn.LeakyReLU(),\n nn.Conv2d(16, 32, [4, 4], [2, 2]),\n nn.LeakyReLU(),\n )\n self.dense = nn.Sequential(\n linear_layer(\n self.final_flat,\n self.h_size,\n kernel_init=Initialization.KaimingHeNormal,\n kernel_gain=1.0,\n ),\n nn.LeakyReLU(),\n )\n\n def forward(self, visual_obs: torch.Tensor) -> None:\n hidden = self.conv_layers(visual_obs)\n hidden = torch.reshape(hidden, (-1, self.final_flat))\n hidden = self.dense(hidden)\n return hidden\n\n\nclass NatureVisualEncoder(nn.Module):\n def __init__(self, height, width, initial_channels, output_size):\n super().__init__()\n self.h_size = output_size\n conv_1_hw = conv_output_shape((height, width), 8, 4)\n conv_2_hw = conv_output_shape(conv_1_hw, 4, 2)\n conv_3_hw = conv_output_shape(conv_2_hw, 3, 1)\n self.final_flat = conv_3_hw[0] * conv_3_hw[1] * 64\n\n self.conv_layers = nn.Sequential(\n nn.Conv2d(initial_channels, 32, [8, 8], [4, 4]),\n nn.LeakyReLU(),\n nn.Conv2d(32, 64, [4, 4], [2, 2]),\n nn.LeakyReLU(),\n nn.Conv2d(64, 64, [3, 3], [1, 1]),\n nn.LeakyReLU(),\n )\n self.dense = nn.Sequential(\n linear_layer(\n self.final_flat,\n self.h_size,\n kernel_init=Initialization.KaimingHeNormal,\n kernel_gain=1.0,\n ),\n nn.LeakyReLU(),\n )\n\n def forward(self, visual_obs: torch.Tensor) -> None:\n hidden = self.conv_layers(visual_obs)\n hidden = hidden.view([-1, self.final_flat])\n hidden = self.dense(hidden)\n return hidden\n\n\nclass ResNetBlock(nn.Module):\n def __init__(self, channel: int):\n \"\"\"\n Creates a ResNet Block.\n :param channel: The number of channels in the input (and output) tensors of the\n convolutions\n \"\"\"\n super().__init__()\n self.layers = nn.Sequential(\n Swish(),\n nn.Conv2d(channel, channel, [3, 3], [1, 1], padding=1),\n Swish(),\n nn.Conv2d(channel, channel, [3, 3], [1, 1], padding=1),\n )\n\n def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:\n return input_tensor + self.layers(input_tensor)\n\n\nclass ResNetVisualEncoder(nn.Module):\n def __init__(self, height, width, initial_channels, final_hidden):\n super().__init__()\n n_channels = [16, 32, 32] # channel for each stack\n n_blocks = 2 # number of residual blocks\n self.layers = []\n last_channel = initial_channels\n for _, channel in enumerate(n_channels):\n self.layers.append(\n nn.Conv2d(last_channel, channel, [3, 3], [1, 1], padding=1)\n )\n self.layers.append(nn.MaxPool2d([3, 3], [2, 2]))\n height, width = pool_out_shape((height, width), 3)\n for _ in range(n_blocks):\n self.layers.append(ResNetBlock(channel))\n last_channel = channel\n self.layers.append(Swish())\n self.dense = linear_layer(\n n_channels[-1] * height * width,\n final_hidden,\n kernel_init=Initialization.KaimingHeNormal,\n kernel_gain=1.0,\n )\n\n def forward(self, visual_obs):\n batch_size = visual_obs.shape[0]\n hidden = visual_obs\n for layer in self.layers:\n hidden = layer(hidden)\n before_out = hidden.view(batch_size, -1)\n return torch.relu(self.dense(before_out))\n","sub_path":"ml-agents/mlagents/trainers/torch/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":11090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"306971684","text":"import sys\nimport os\nimport csv\nimport glob\nfrom PIL import Image\nimport xml.etree.ElementTree as ET\nimport numpy as np\nfrom pathlib import Path\nfrom tqdm import tqdm\n\n# Just try to open image and parse it using the xml\npath = sys.argv[1]\ncsvfile = open('metadata.csv', 'w', newline='')\nwriter = csv.writer(csvfile, delimiter=\",\", quotechar=\"|\",\n quoting=csv.QUOTE_MINIMAL)\nwriter.writerow(['filename', 'tags', 'description', 'permalink'])\n\nPath('./extracted_objects').mkdir(exist_ok=True)\n\nfor fileName in tqdm(glob.glob(path), 'extracting objects'):\n if fileName[-8:] != \"mask.png\":\n imFile = fileName\n im = Image.open(imFile)\n pix = np.asarray(im)\n # Have to parse the proper mask\n dataFile = Path(imFile[:-4] + \".xml\")\n if not dataFile.exists():\n dataFile = Path(imFile[:-4].replace('image', 'annotation') + '.xml')\n tree = ET.parse(dataFile)\n root = tree.getroot()\n\n for obj in root.iter('object'):\n boundingBox = obj.find('bndbox2D')\n tag = obj.find('category0').text\n xmin = int(boundingBox.find('xmin').text)\n xmax = int(boundingBox.find('xmax').text)\n ymin = int(boundingBox.find('ymin').text)\n ymax = int(boundingBox.find('ymax').text)\n subImageArray = pix[ymin:ymax, xmin:xmax]\n outfile = obj.attrib['id'] + \".png\"\n\n catCounter = 0\n tag = \"\"\n while not obj.find(\"category\"+str(catCounter)) is None:\n tag = obj.find('category'+str(catCounter)).text\n catCounter += 1\n persistentID = obj.attrib['persistent_id']\n\n # some images can be outside of screen, in which case, drop em:\n if subImageArray.shape[0] > 0 and subImageArray.shape[1] > 0:\n newim = Image.fromarray(subImageArray)\n newim.save(\"extracted_objects/\" + outfile, \"png\")\n writer.writerow([outfile, tag, persistentID, \"n/a\"])\n # might also want to potentially write metadata file. Will do this later\n","sub_path":"extract_objects_xml.py","file_name":"extract_objects_xml.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"390110634","text":"import kfp\r\nfrom kfp import dsl\r\nimport kfp.components as comp\r\n\r\n@kfp.dsl.component\r\ndef run_main_func1():\r\n component1 = kfp.dsl.ContainerOp(\r\n name=\"component11\",\r\n image = 'docker.io/kekunisarg/test-kubeflow-code',\r\n command=['python','main.py'],\r\n )\r\n return component1\r\n\r\n@kfp.dsl.component\r\ndef run_main_func2(username, level):\r\n component2 = kfp.dsl.ContainerOp(\r\n name=\"component22\",\r\n image = 'docker.io/kekunisarg/test-kubeflow-code',\r\n command=['python','main2.py'],\r\n arguments=[\r\n \"--username\", username,\r\n \"--level\", level,\r\n ]\r\n )\r\n return component2\r\n\r\n@kfp.dsl.pipeline(\r\n name = \"Test-kubeflow-pipeline\",\r\n description=\"run-Test-kubeflow-pipeline\"\r\n)\r\ndef run_pipeline(username: str, level:str):\r\n run_comp1 = run_main_func1()\r\n run_comp1.execution_options.caching_strategy.max_cache_stalness = \"P0D\"\r\n run_comp2 = run_main_func2(username,level).after(run_comp1)\r\n run_comp2.execution_options.caching_strategy.max_cache_stalness = \"P0D\"\r\n\r\nif __name__ == '__main__':\r\n from kfp.compiler import Compiler\r\n Compiler().compile(run_pipeline,\"test-kubeflow-pipeline.yaml\")\r\n # # create kfp client with using pipeline endpoint\r\n # client = kfp.Client(\"https://11b521f27cd0a187-dot-us-central1.pipelines.googleusercontent.com\")\r\n #\r\n # # create experiment\r\n # EXPERIMENT_NAME = 'test-kubeflow1'\r\n # experiment = client.create_experiment(name=EXPERIMENT_NAME)\r\n #\r\n # # deploy pipeline to kubeflow pipeline endpoint\r\n # run = client.run_pipeline(experiment.id, 'test-kubeflow1_run', 'test-kubeflow-pipeline.yaml')\r\n","sub_path":"kubeflow_pipeline.py","file_name":"kubeflow_pipeline.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23556150","text":"import Optimiser.pso as pso\nimport Optimiser.ga as ga\n\nfrom Entities.Enums.budget import Budget\nfrom Entities.place import Place\n\n\nclass Trip:\n \"\"\"\n From this trip object a user will be able to generate itineraries\n that are applicable to his constraints. Constraints include:\n budget, moderation, characteristics, travel date and accomodation.\n \"\"\"\n\n def __init__(\n self,\n budget: Budget,\n moderation,\n characteristics,\n number_of_days,\n accomodation: Place,\n is_personalised,\n ):\n super().__init__()\n\n self.budget = budget\n self.moderation = moderation\n self.characteristics = characteristics\n self.number_of_days = number_of_days\n self.accomodation = accomodation\n self.is_personalised = is_personalised\n\n def generate_itineraries(self):\n\n return ga.Optimise(self)\n # return pso.Optimse(self)\n\n","sub_path":"Entities/trip.py","file_name":"trip.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286793893","text":"import os\nimport glob\nimport random\nimport tempfile\nimport subprocess\nimport config\nimport numpy as np\nfrom scipy import misc\nfrom datetime import datetime\n\n\n### GLOBALS\ndataset_dir = config.DATA_DIR\n###\n\n\ndef resize_crop(img: np.ndarray) -> np.ndarray:\n '''\n resize the image frame to a random 224 by 224\n '''\n\n aspect_ratio = float(img.shape[1]) / float(img.shape[0])\n new_w = 0\n new_h = 0\n if aspect_ratio <= 1.0:\n new_w = 256\n new_h = int(256 / aspect_ratio)\n else:\n new_h = 256\n new_w = int(256 * aspect_ratio)\n\n random.seed(datetime.now())\n resize = misc.imresize(img, (new_h, new_w), 'bilinear')\n wrange = resize.shape[1] - 224\n hrange = resize.shape[0] - 224\n w_crop = random.randint(0, wrange)\n h_crop = random.randint(0, hrange)\n\n return resize[h_crop:h_crop+224, w_crop:w_crop+224]\n\n\ndef createJPGs(video, dest):\n '''\n creates the jpegs by calling the ffmpeg\n '''\n video = str(video).replace(' ', '\\ ')\n dest = str(dest).replace(' ', '\\ ')\n command = \"ffmpeg -i \" + video + \" -r 25.0 \" + dest\n proc = subprocess.Popen(\n command,\n shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n cwd='.'\n )\n out, err = proc.communicate()\n # print(out)\n # print(err)\n\n\ndef main():\n '''\n 1. move into the video directory\n 2. extract the frames and resize them using\n bilinear extrapolation\n 3. randomly select a 224 by 224 crop\n 4. change pixel values to be [-1, 1]\n '''\n os.chdir(dataset_dir)\n for label in os.listdir():\n if label.startswith(\".\"):\n continue\n\n print(\"===================== \" + label + \" ======================== \")\n label_path = os.path.join(dataset_dir, label)\n os.chdir(label_path)\n for video in glob.glob(\"*.mp4\"):\n print(\"\\tprocessing video: \" + video)\n # l = list()\n dest_name = os.path.splitext(video)[0]\n if dest_name not in os.listdir():\n os.mkdir(dest_name)\n video_path = os.path.join(label_path, video)\n dest_name = os.path.join(dest_name, \"img%4d.jpg\")\n createJPGs(video_path, dest_name)\n # with tempfile.TemporaryDirectory() as dirpath:\n # os.chdir(dirpath)\n # video_path = os.path.join(label_path, video)\n # createJPGs(video_path, \"img%4d.jpg\")\n # for img in glob.glob(\"*.jpg\"):\n # npimg = misc.imread(img)\n # cropped = resize_crop(npimg)\n # scaled = 2*(cropped/255) - 1\n # l.append(scaled)\n #\n # npy = np.array(l)\n # save_fn = os.path.join(dataset_dir, label, os.path.splitext(video)[0])\n # np.save(save_fn, npy)\n # print(\"\\tsaved video with shape: \" + str(npy.shape))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584022138","text":"\"\"\"Common init function for tests.\"\"\"\nimport importlib\nimport json\nimport logging\nimport sys\n\n\ndef fake_step_module():\n \"\"\"Fake the step module into the correct package.\"\"\"\n import graph_tool\n def load(what, where):\n module = importlib.import_module(what)\n sys.modules[where] = module\n\n load(\"graph_data\", \"ara.graph.graph_data\")\n load(\"py_logging\", \"ara.steps.py_logging\")\n load(\"step\", \"ara.steps.step\")\n\n\nfake_step_module()\n\n\n# this imports has to be _below_ the call to fake_step_module\nfrom ara.util import init_logging\nfrom ara.graph import Graph\nfrom ara.stepmanager import StepManager\n\n\ndef fail_with(*arg):\n \"\"\"Print an error message and exit.\"\"\"\n print(\"ERROR:\", *arg, file=sys.stderr)\n sys.exit(1)\n\n\ndef fail_if(condition, *arg, dry=False):\n \"\"\"Exit with error message, if condition is met.\n\n Keyword argument:\n dry -- Don't check and fail, only print message\n \"\"\"\n if condition or dry:\n print(\"ERROR:\", *arg, file=sys.stderr)\n if condition and not dry:\n sys.exit(1)\n\n\ndef get_config(i_file):\n \"\"\"Return the default common config.\"\"\"\n return {'log_level': 'debug',\n 'dump_prefix': 'dumps/{step_name}.',\n 'dump': False,\n 'runtime_stats': True,\n 'runtime_stats_file': 'logger',\n 'runtime_stats_format': 'human',\n 'entry_point': 'main',\n 'input_file': i_file}\n\n\ndef init_test(steps=None, extra_config=None):\n \"\"\"Common interface for test. Reads a JSON file and some ll-file from the\n command line and make them available.\n\n CLI usage when using init_test:\n your_program \n\n Return a graph reference, the JSON struct and the stepmanager instance.\n\n Arguments:\n steps: List of steps, see the `esteps` argument of\n Stepmanager.execute.\n extra_config: Dict with extra configuration, see the `extra_config`\n argument of Stepmanager.execute.\n \"\"\"\n init_logging(level=logging.DEBUG)\n if not extra_config:\n extra_config = {}\n g = Graph()\n assert len(sys.argv) == 3\n json_file = sys.argv[1]\n i_file = sys.argv[2]\n print(f\"Testing with JSON: '{json_file}'\"\n f\", and file: {i_file}\")\n if steps:\n print(f\"Executing steps: {steps}\")\n elif extra_config:\n print(f\"Executing with config: {extra_config}\")\n else:\n assert False\n with open(json_file) as f:\n data = json.load(f)\n\n s_manager = StepManager(g)\n\n s_manager.execute(get_config(i_file), extra_config, steps)\n\n return g, data, s_manager\n","sub_path":"test/init_test.py","file_name":"init_test.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213049859","text":"#!/usr/bin/env python\n\nfrom re import compile as regex\nfrom sys import stdin, stdout, argv\n\n_prologue = r'''\n\n\n\n\t\n\t\t\n\t\t\n\t\tt\n\t\n\t\n\t\t
\n'''[1:]\n\n_epilogue = r'''\n\t\t
\n\t\n\n'''[1:]\n\n_escape = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n}\n\n_escape_re = regex('(?:' + '|'.join(_escape.keys()) + ')')\n\ndef escape(m):\n return _escape[m.group()]\n\ndef main(args):\n stdout.write(_prologue)\n stream = stdin if len(args) == 0 else open(args[0])\n for line in stream:\n stdout.write(_escape_re.sub(escape, line))\n stdout.write(_epilogue)\n\nif __name__ == '__main__':\n main(argv[1:])\n","sub_path":"bin/htmlpre.py","file_name":"htmlpre.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"488602853","text":"from retractPolymer import fullyRetractPolymer\r\nfrom string import ascii_lowercase\r\n\r\nfile = open(\"input.txt\", \"r\")\r\ninput_polymer = file.read().strip()\r\nretracted_polymer = fullyRetractPolymer(input_polymer)\r\n\r\nbest = -1\r\nbest_letter = \"\"\r\n\r\nfor letter in ascii_lowercase:\r\n polymer = fullyRetractPolymer([ x for x in retracted_polymer if x.upper() != letter.upper()]) \r\n\r\n if best == -1 or len(polymer) < best:\r\n best = len(polymer)\r\n best_letter = letter\r\n\r\nprint(best)\r\n","sub_path":"2018/05/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"484039798","text":"# Find the longest word in a sentence\n# If two or more words have the same length, return the first longest word in the sentence\n# for example: \"I am Alive and my name is C\" -> Returns \"Alive\"\n\nimport re\n\ntest_word = \"I am Alive!!? and my name is C AlieA AlieB\"\n\n\ndef longest_word(sentence):\n # Create a list of strings\n sentence = re.findall(\"\\w+\", sentence)\n\n # Sort this list by length\n sentence.sort(key=len)\n\n # Group the words by length\n dct = {}\n for word in sentence:\n dct.setdefault(len(word), []).append(word)\n\n # Return the longest word and the first occurence of it in case of duplications\n return dct.get(max(dct.keys()))[0]\n\n\nprint(longest_word(test_word))\n","sub_path":"Python/Challenge 01 - Get the longest word out of a list/challenge_01.py","file_name":"challenge_01.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"475975098","text":"# %% [105. **Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)\n# 問題:preorderなリストとinorderなリストからTreeNodeを作成せよ\n# 解法:inorderが存在していれば、preorderから先頭を取り出し、その値でinorderを分割し再帰的に構築\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n if inorder:\n i = inorder.index(preorder.pop(0))\n res = TreeNode(inorder[i])\n res.left = self.buildTree(preorder, inorder[:i])\n res.right = self.buildTree(preorder, inorder[i + 1 :])\n return res\n","sub_path":"codes_/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py","file_name":"0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"90277907","text":"from functools import reduce\npzt = [ { \"isim\": 'Fonksiyonlara calis', \"sure\": 180 }, { \"isim\": 'ornek coz', \"sure\": 120 },\n { \"isim\": 'odev kontrol', \"sure\": 20 }, { \"isim\": 'bayramlasma', \"sure\": 200 } ]\nsali = [ { \"isim\": 'gelecek haftaya hazirlik', \"sure\": 240}, { \"isim\": 'ornek cozumlerine devam et', \"sure\": 180},\n { \"isim\": 'kahve molasi', \"sure\": 10}, { \"isim\": 'kitap oku', \"sure\": 200}, { \"isim\": 'spor yap', \"sure\": 40} ]\npzt_puan = reduce(lambda a,b:a+b, list(map(lambda a: round(a*20),filter(lambda a: a>=2,map(lambda a: a[\"sure\"]/60, pzt)))))\nsali_puan = reduce(lambda a,b:a+b, list(map(lambda a: round(a*20),filter(lambda a: a>=2,map(lambda a: a[\"sure\"]/60, sali)))))\n\nprint(pzt_puan + sali_puan)\n\n","sub_path":"odev 3.py","file_name":"odev 3.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273937363","text":"\n\n\n\n\n# class Button:\n \n# FontWeight = 'bold'\n# FontColor = 'red'\n \n# def __init__(self, color):\n# self.count = 0\n# self.color = color\n\n# @classmethod\n# def popUp(cls):\n# print('do you need some help?')\n \n# def click(self):\n# self.count += 1\n \n# if(self.count > 2):\n# Button.popUp()\n# self.count = 0\n \n \n\n\n# navButton = Button('green')\n# helpButton = Button('yellow')\n\n# print(navButton.FontWeight)\n# print(helpButton.FontWeight)\n\n# print(f\"nav {navButton.count}\")\n# print(f\"help {helpButton.count}\")\n\n\n# navButton.click()\n# navButton.click()\n\n# print(f\"nav {navButton.count}\")\n# print(f\"help {helpButton.count}\")\n\n# navButton.click()\n\n# helpButton.click()\n# print(f\"nav {navButton.count}\")\n# print(f\"help {helpButton.count}\")\n\n\n# class Test:\n# def __init__(self):\n# self.__a = 'a'\n# self._b = 'b' #semi private\n \n \n# def _privateMethod(self):\n \n# print(self.__a)\n \n \n\n# firstTest = Test()\n\n# print(firstTest._privateMethod())\n\n\n# class GoogleMapsAPI:\n \n# def __init__(self, address1, address2):\n\n# self.address1 = address1\n# self.address2 = address2\n \n# def Map(self):\n# pass \n \n# def determineLat(self):\n# pass \n \n# def determineLong(self):\n# pass\n \n# map = GoogleMapsAPI(\"123 my street\", 'some other streeet') \n\n# map.Map\n# map.determineLat \n\n# \"hello\"\n\n# # sample = \"hello\"\n# # sample.\nclass OurString(str):\n def __init__(self, word):\n self.word = word\n #super(OurString, self).__init__(word)\n \n def reverse(self):\n \n revString = ''\n \n for char in self.word:\n revString = char + revString #olleh\n \n return revString\n \nmyString = OurString('hello')\n\nprint(myString.capitalize())\n\nprint(myString.reverse())\n\n# class Car:\n# def __init__(self, make, model, color):\n# self.make = make \n# self.model = model \n# self.color = color\n \n# def carDetails(self):\n \n# print(\"Here are the details of this car\")\n \n\n# class Hybrid(Car):\n \n# def __init__(self, make, model, color):\n# super(Hybrid, self).__init__(make, model, color) \n \n# def carType(self):\n# print(\"I am a hybrid car\")\n \n# def carDetails(self):\n# print('this is a hybrid instance of carDetails')\n# super(Hybrid, self).carDetails()\n \n\n# class Electric(Car):\n \n# def carType(self):\n# print(\"I am an electric car\")\n\n# prius = Hybrid(\"toyota\", \"prius\", \"lime green\")\n\n# tesla = Electric(\"tesla\", \"model-s\", \"marble\")\n\n# print(prius.make)\n# prius.carType()\n# prius.carDetails()\n\n\n# print(tesla.make)\n# tesla.carType()\n# tesla.carDetails()\n\n","sub_path":"week02/3-Wednesday/veros-notes-dont-touch/class2.py","file_name":"class2.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"223968003","text":"# instiki_to_mediawiki.py\n\nfrom optparse import OptionParser\nimport os.path\nimport re\nimport cgi\nimport sys\nimport subprocess\n\ncategory_regex = re.compile(r\"(:)?category\\s*:(.*)\", re.IGNORECASE)\nredirect_regex = re.compile(r\"\\[\\[\\!redirects\\s+([^\\]\\s][^\\]]*?)\\s*\\]\\]\", re.IGNORECASE)\ntoc_regex = re.compile(r\"\\=\\s*Contents\\s*\\=\\s*\\n*\\s*\\*\\s*table of contents\", re.IGNORECASE)\n\ndef remove_tocs(contents):\n return toc_regex.sub(\"\", contents)\n\ndef title_to_wiki_style(s):\n s = s.strip()\n if len(s) == 0:\n return s\n return s[0].upper() + s[1:]\n\ndef category_to_wiki_style(c):\n return \"[[Category:%s]]\" % cgi.escape(title_to_wiki_style(c))\n\ndef replace_category(match):\n return \"\\n\".join(map(category_to_wiki_style, match.group(2).split(',')))\n\ndef replace_categories(input):\n return category_regex.sub(replace_category, input)\n\ndef get_redirects(contents):\n return map(lambda x: title_to_wiki_style(x.group(1)),\n redirect_regex.finditer(contents))\n\ndef remove_redirects(contents):\n return redirect_regex.sub(\"\", contents)\n\ndef register_redirect(s, t, register):\n if s and t and s != t:\n if s not in register.keys():\n register[s] = t\n\ndef get_page_list(dir):\n return map(lambda x: dir + \"/\" + x.replace(\".meta\", \"\"),\n filter(lambda x: x.endswith(\".meta\"), os.listdir(dir)))\n\ndef get_page_title(p):\n meta = open(p + \".meta\", 'r').read()\n r = re.compile(r\"name\\s*:(.*)\", re.IGNORECASE)\n ms = r.findall(meta)\n if not ms:\n return\n else:\n return title_to_wiki_style(ms[-1])\n\ndef write_redirects_register(register, path):\n open(path, 'w').write(\"\\n\".join(\n [\"%s -> %s\" % (s, t) for s, t in register.items()]))\n\ndef convert_markdown_to_wiki_syntax(path):\n subprocess.call(\"C:/Ruby193/bin/ruby.exe \"\n \"C:/Users/khan/Documents/GitHub/maruku/bin/maruku \"\n \"--wiki --math-engine none %s\" % path)\n\ndef main(input, output):\n redir_register = {}\n\n for p in get_page_list(input):\n x = open(p, 'r').read()\n\n x = remove_tocs(x)\n\n rs = get_redirects(x)\n x = remove_redirects(x)\n [register_redirect(r, get_page_title(p), redir_register) for r in rs]\n\n x = replace_categories(x)\n\n path = output + \"/\" + os.path.basename(p)\n open(path, 'w').write(x)\n\n convert_markdown_to_wiki_syntax(path)\n\n write_redirects_register(redir_register, \"redirects.txt\")\n\nif __name__ == \"__main__\":\n parser = OptionParser(\"usage: %prog -i INPUT -o OUTPUT\")\n parser.add_option(\"-i\", \"--input-dir\", dest=\"input\",\n help=\"A directory containing files exported from an Instiki installation, \"\n \"to be converted to MediaWiki format.\")\n parser.add_option(\"-o\", \"--output-dir\", dest=\"output\",\n help=\"A directory to be populated with MediaWiki format files.\")\n\n (options, args) = parser.parse_args()\n if not options.input:\n parser.error(\"missing input directory\")\n elif not os.path.isdir(options.input):\n parser.error(\"input directory is not a directory\")\n if not options.output:\n parser.error(\"missing output folder\")\n elif not os.path.isdir(options.output):\n parser.error(\"output directory is not a directory\")\n\n main(options.input, options.output)","sub_path":"dockerized-gists/9983048/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150354638","text":"# -*- coding: utf-8 -*-\n# Copyright 2021, CS GROUP - France, http://www.c-s.fr\n#\n# This file is part of EODAG project\n# https://www.github.com/CS-SI/EODAG\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 json\nimport unittest\n\nimport geojson\n\nfrom tests import mock\nfrom tests.context import (\n DEFAULT_ITEMS_PER_PAGE,\n SearchResult,\n ValidationError,\n eodag_http_server,\n get_date,\n)\n\n\nclass RequestTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.tested_product_type = \"S2_MSI_L1C\"\n\n def setUp(self):\n self.app = eodag_http_server.app.test_client()\n\n def test_route(self):\n response = self.app.get(\"/\", follow_redirects=True)\n self.assertEqual(200, response.status_code)\n\n self._request_valid(self.tested_product_type)\n\n @mock.patch(\n \"eodag.rest.utils.eodag_api.search\",\n autospec=True,\n return_value=(\n SearchResult.from_geojson(\n {\n \"features\": [\n {\n \"properties\": {\n \"snowCover\": None,\n \"resolution\": None,\n \"completionTimeFromAscendingNode\": \"2018-02-16T00:12:14\"\n \".035Z\",\n \"keyword\": {},\n \"productType\": \"OCN\",\n \"downloadLink\": (\n \"https://peps.cnes.fr/resto/collections/S1/\"\n \"578f1768-e66e-5b86-9363-b19f8931cc7b/download\"\n ),\n \"eodag_provider\": \"peps\",\n \"eodag_product_type\": \"S1_SAR_OCN\",\n \"platformSerialIdentifier\": \"S1A\",\n \"cloudCover\": 0,\n \"title\": \"S1A_WV_OCN__2SSV_20180215T235323_\"\n \"20180216T001213_020624_023501_0FD3\",\n \"orbitNumber\": 20624,\n \"instrument\": \"SAR-C SAR\",\n \"abstract\": None,\n \"eodag_search_intersection\": {\n \"coordinates\": [\n [\n [89.590721, 2.614019],\n [89.771805, 2.575546],\n [89.809341, 2.756323],\n [89.628258, 2.794767],\n [89.590721, 2.614019],\n ]\n ],\n \"type\": \"Polygon\",\n },\n \"organisationName\": None,\n \"startTimeFromAscendingNode\": \"2018-02-15T23:53:22\"\n \".871Z\",\n \"platform\": None,\n \"sensorType\": None,\n \"processingLevel\": None,\n \"orbitType\": None,\n \"topicCategory\": None,\n \"orbitDirection\": None,\n \"parentIdentifier\": None,\n \"sensorMode\": None,\n \"quicklook\": None,\n },\n \"id\": \"578f1768-e66e-5b86-9363-b19f8931cc7b\",\n \"type\": \"Feature\",\n \"geometry\": {\n \"coordinates\": [\n [\n [89.590721, 2.614019],\n [89.771805, 2.575546],\n [89.809341, 2.756323],\n [89.628258, 2.794767],\n [89.590721, 2.614019],\n ]\n ],\n \"type\": \"Polygon\",\n },\n }\n ],\n \"type\": \"FeatureCollection\",\n }\n ),\n 1,\n ),\n )\n def _request_valid(self, url, _):\n response = self.app.get(url, follow_redirects=True)\n self.assertEqual(200, response.status_code)\n # Assert response format is GeoJSON\n return geojson.loads(response.data.decode(\"utf-8\"))\n\n def _request_not_valid(self, url):\n response = self.app.get(url, follow_redirects=True)\n response_content = json.loads(response.data.decode(\"utf-8\"))\n\n self.assertEqual(400, response.status_code)\n self.assertIn(\"description\", response_content)\n self.assertIn(\"invalid\", response_content[\"description\"])\n\n def _request_not_found(self, url):\n response = self.app.get(url, follow_redirects=True)\n response_content = json.loads(response.data.decode(\"utf-8\"))\n\n self.assertEqual(404, response.status_code)\n self.assertIn(\"error\", response_content)\n self.assertIn(\"not found\", response_content[\"error\"])\n\n def test_request_params(self):\n self._request_not_valid(\n \"search?collections={}&bbox=1\".format(self.tested_product_type)\n )\n self._request_not_valid(\n \"search?collections={}&bbox=0,43,1\".format(self.tested_product_type)\n )\n self._request_not_valid(\n \"search?collections={}&bbox=0,,1\".format(self.tested_product_type)\n )\n self._request_not_valid(\n \"search?collections={}&bbox=a,43,1,44\".format(self.tested_product_type)\n )\n\n self._request_valid(\"search?collections={}\".format(self.tested_product_type))\n self._request_valid(\n \"search?collections={}&bbox=0,43,1,44\".format(self.tested_product_type)\n )\n\n def test_not_found(self):\n \"\"\"A request to eodag server with a not supported product type must return a 404 HTTP error code\"\"\" # noqa\n self._request_not_found(\"search?collections=ZZZ&bbox=0,43,1,44\")\n\n def test_filter(self):\n result1 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44\".format(self.tested_product_type)\n )\n result2 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44&filter=latestIntersect\".format(\n self.tested_product_type\n )\n )\n self.assertGreaterEqual(len(result1.features), len(result2.features))\n\n def test_get_date(self):\n \"\"\"Date validation function must correctly validate dates\"\"\"\n get_date(\"2018-01-01\")\n get_date(\"2018-01-01T\")\n get_date(\"2018-01-01T00:00\")\n get_date(\"2018-01-01T00:00:00\")\n get_date(\"2018-01-01T00:00:00Z\")\n get_date(\"20180101\")\n\n self.assertRaises(ValidationError, get_date, \"foo\")\n self.assertRaises(ValidationError, get_date, \"foo2018-01-01\")\n\n self.assertIsNone(get_date(None))\n\n def test_date_search(self):\n result1 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44\".format(self.tested_product_type)\n )\n result2 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\".format(\n self.tested_product_type\n )\n )\n self.assertGreaterEqual(len(result1.features), len(result2.features))\n\n def test_date_search_from_items(self):\n result1 = self._request_valid(\n \"collections/{}/items?bbox=0,43,1,44\".format(self.tested_product_type)\n )\n result2 = self._request_valid(\n \"collections/{}/items?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\".format(\n self.tested_product_type\n )\n )\n self.assertGreaterEqual(len(result1.features), len(result2.features))\n\n def test_date_search_from_catalog_items(self):\n result1 = self._request_valid(\n \"{}/year/2018/month/01/items?bbox=0,43,1,44\".format(\n self.tested_product_type\n )\n )\n result2 = self._request_valid(\n \"{}/year/2018/month/01/items?bbox=0,43,1,44&datetime=2018-01-20/2018-01-25\".format(\n self.tested_product_type\n )\n )\n self.assertGreaterEqual(len(result1.features), len(result2.features))\n\n def test_catalog_browse(self):\n result = self._request_valid(\n \"{}/year/2018/month/01/day\".format(self.tested_product_type)\n )\n self.assertListEqual(\n [str(i) for i in range(1, 32)],\n [it[\"title\"] for it in result.get(\"links\", []) if it[\"rel\"] == \"child\"],\n )\n\n def test_cloud_cover_search(self):\n result1 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44\".format(self.tested_product_type)\n )\n result2 = self._request_valid(\n \"search?collections={}&bbox=0,43,1,44&cloudCover=10\".format(\n self.tested_product_type\n )\n )\n self.assertGreaterEqual(len(result1.features), len(result2.features))\n\n def test_search_response_contains_pagination_info(self):\n \"\"\"Responses to valid search requests must return a geojson with pagination info in properties\"\"\" # noqa\n response = self._request_valid(\n \"search?collections={}\".format(self.tested_product_type)\n )\n self.assertIn(\"numberMatched\", response)\n self.assertIn(\"numberReturned\", response)\n self.assertIn(\"context\", response)\n self.assertEqual(1, response[\"context\"][\"page\"])\n self.assertEqual(DEFAULT_ITEMS_PER_PAGE, response[\"context\"][\"limit\"])\n self.assertIn(\"matched\", response[\"context\"])\n self.assertIn(\"returned\", response[\"context\"])\n\n @mock.patch(\n \"eodag.rest.utils.eodag_api.guess_product_type\", autospec=True, return_value=[]\n )\n @mock.patch(\n \"eodag.rest.utils.eodag_api.list_product_types\",\n autospec=True,\n return_value=[{\"ID\": \"S2_MSI_L1C\"}, {\"ID\": \"S2_MSI_L2A\"}],\n )\n def test_list_product_types_ok(self, list_pt, guess_pt):\n \"\"\"A simple request for product types with(out) a provider must succeed\"\"\"\n for url in (\"/collections\",):\n r = self.app.get(url)\n self.assertTrue(guess_pt.called)\n self.assertTrue(list_pt.called)\n self.assertEqual(200, r.status_code)\n self.assertListEqual(\n [\"S2_MSI_L1C\", \"S2_MSI_L2A\"],\n [\n it[\"title\"]\n for it in json.loads(r.data.decode(\"utf-8\")).get(\"links\", [])\n if it[\"rel\"] == \"child\"\n ],\n )\n\n guess_pt.return_value = [\"S2_MSI_L1C\"]\n url = \"/collections?instrument=MSI\"\n r = self.app.get(url)\n self.assertTrue(guess_pt.called)\n self.assertTrue(list_pt.called)\n self.assertEqual(200, r.status_code)\n self.assertListEqual(\n [\"S2_MSI_L1C\"],\n [\n it[\"title\"]\n for it in json.loads(r.data.decode(\"utf-8\")).get(\"links\", [])\n if it[\"rel\"] == \"child\"\n ],\n )\n\n @mock.patch(\n \"eodag.rest.utils.eodag_api.list_product_types\",\n autospec=True,\n return_value=[{\"ID\": \"S2_MSI_L1C\"}, {\"ID\": \"S2_MSI_L2A\"}],\n )\n def test_list_product_types_nok(self, list_pt):\n \"\"\"A request for product types with a not supported filter must return all product types\"\"\" # noqa\n url = \"/collections?platform=gibberish\"\n r = self.app.get(url)\n self.assertTrue(list_pt.called)\n self.assertEqual(200, r.status_code)\n self.assertListEqual(\n [\"S2_MSI_L1C\", \"S2_MSI_L2A\"],\n [\n it[\"title\"]\n for it in json.loads(r.data.decode(\"utf-8\")).get(\"links\", [])\n if it[\"rel\"] == \"child\"\n ],\n )\n\n def test_conformance(self):\n self._request_valid(\"conformance\")\n\n def test_service_desc(self):\n self._request_valid(\"api\")\n\n def test_service_doc(self):\n response = self.app.get(\"service-doc\", follow_redirects=True)\n self.assertEqual(200, response.status_code)\n","sub_path":"tests/units/test_http_server.py","file_name":"test_http_server.py","file_ext":"py","file_size_in_byte":13044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"616085538","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport os\nimport sys\nfrom PIL import Image\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\n\nnorm_size = 32\n\ndef predict(model_path, image_path):\n # load the trained convolutional neural network\n #print(\"[INFO] loading network...\")\n model = load_model(model_path)\n\n #load the image\n image = cv2.imread(image_path)\n #image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n #orig = image.copy()\n\n # pre-process the image for classification\n image = cv2.resize(image, (norm_size, norm_size))\n image = image.astype(\"float\") / 255.0\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n\n # classify the input image\n result = model.predict(image)[0]\n proba = np.max(result)\n label = int(np.where(result==proba)[0])\n #label = \"{}#{}#{:.2f}%\".format(image_path, label, proba * 100)\n return os.path.basename(image_path),label,proba * 100\n\n\n\ndef paste_img(image_dir, dst_dir, x):\n im_x = Image.open(os.path.join(image_dir, x + \".jpg\"))\n im_x = im_x.resize((37, 37))\n\n im = Image.open(os.path.join(image_dir, \"0.jpg\"))\n im = im.resize((74, 74))\n im.paste(im_x, (0, 0))\n im.save(os.path.join(dst_dir, x + \"1.jpg\"))\n\n im = Image.open(os.path.join(image_dir, \"0.jpg\"))\n im = im.resize((74, 74))\n im.paste(im_x, (37, 0))\n im.save(os.path.join(dst_dir, x + \"2.jpg\"))\n\n im = Image.open(os.path.join(image_dir, \"0.jpg\"))\n im = im.resize((74, 74))\n im.paste(im_x, (0, 37))\n im.save(os.path.join(dst_dir, x + \"3.jpg\"))\n\n im = Image.open(os.path.join(image_dir, \"0.jpg\"))\n im = im.resize((74, 74))\n im.paste(im_x, (37, 37))\n im.save(os.path.join(dst_dir, x + \"4.jpg\"))\n\n\n# python run.py ../images/source/2018223818/\ndef get_result(image_dir):\n dst_dir = \"../images/temp\"\n for i in (\"a\", \"b\", \"c\", \"d\"):\n paste_img(image_dir, dst_dir, i)\n\n model_path = \"./sw3.model\"\n results = []\n for image_name in os.listdir(dst_dir):\n image_path = os.path.join(dst_dir, image_name)\n name, label, proba = predict(model_path, image_path)\n result = dict()\n result['name'] = name\n result['label'] = label\n result['proba'] = proba\n results.append(result)\n\n results_0 = []\n results_1 = []\n for result in results:\n if result['label'] == 0:\n results_0.append(result)\n else:\n results_1.append(result)\n if len(results_0) == 0:\n ans = results_1[0]\n for result in results_1:\n if result['proba'] < ans['proba']:\n ans = result\n else:\n ans = results_0[0]\n for result in results_0:\n if result['proba'] > ans['proba']:\n ans = result\n return list(ans['name'])[0]\n\nif __name__ == \"__main__\":\n image_dir = sys.argv[1]\n result = get_result(image_dir)\n print(result)\n\n","sub_path":"sw3/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"132437202","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom xml.etree import ElementTree as etree\nfrom db_scripts import twits as twits_db\nimport asyncio\nimport aiohttp\nfrom urllib.error import HTTPError\n\n'genadiy_g'\nURL_MASK = \"http://twitrss.me/twitter_user_to_rss/?user={}&fetch=Fetch+RSS\"\n\n\nasync def get_twit(session, link, following_id):\n twit_id = link.split('/')[-1]\n\n async with session.get(link) as response:\n content = await response.content.read()\n soup = BeautifulSoup(content, \"html.parser\")\n twits_text = soup.find(class_='TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text').text\n twits_text = twits_text.split('pic.twitter.com')[0] if 'pic.twitter.com' in twits_text else twits_text\n twit = twits_db.Twit(twit_id, following_id, twits_text)\n # twit = twits_db.add_twit(twit_id, following_id, twits_text)\n return twit\n\n\nasync def get_followings_twits(following_id):\n # user_name = user.user_id\n loop = asyncio.get_event_loop()\n\n url = URL_MASK.format(following_id)\n with urlopen(url, timeout=10) as r:\n items = etree.parse(r).find('channel').findall('item')\n\n links = [item.find('link').text for item in items]\n\n async with aiohttp.ClientSession(loop=loop) as session:\n tasks = [get_twit(session, link, following_id) for link in links]\n return await asyncio.gather(*tasks)\n\n\ndef check_following_exists(following_id):\n url = URL_MASK.format(following_id)\n try:\n urlopen(url, timeout=10)\n return True\n except HTTPError:\n return False\n\n\n# loop = asyncio.get_event_loop()\n# twits = loop.run_until_complete(get_followings_twits('genadiy_g'))\n# print(twits)\n\n# print(check_following_exists('genadiy_g'))\n\n","sub_path":"scraper/twit_scraper.py","file_name":"twit_scraper.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"490781588","text":"\"\"\"\n This file contains the constants used \n throughout the program\n\"\"\"\n# Colors\nBG_COLOR = (250, 245, 245)\nPLAYER_COLOR = (0, 255, 0)\nQIX_COLOR = (255, 0, 0)\nBORDER_COLOR = (0, 0, 0)\nFONT_COLOR = (0, 20, 25)\nSPARX_COLOR = (100, 2, 245)\n\n# Constants for font\nFONT_SIZE = 25\n\n# Constants used in the Game\nPLAYER_RADIUS = QIX_DIM = SPARX_DIM = 10\nMARGIN = 20\nMAP_WIDTH = 420\nMAP_HEIGHT = 420\nMOVE_DIM = PLAYER_RADIUS\n\n# Constants related to life\nINIT_LIFE = 10\nINIT_COOR = (5, 2)\nQIX_DAMAGE = 1\nSPARX_DAMAAGE = 2\n\nFPS = 3","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198682228","text":"file = open('stores_old.csv', 'r', encoding='big5')\nfile2= open('stores_new.csv','w',encoding='big5')\n\nwhile True:\n line = file.readline()\n a=line.split(',')\n if not line:\n break\n a.pop(1)\n a.pop(1)\n a.pop(2)\n a.pop(4)\n b=str(a).strip('[')\n c=b.strip(']')\n d=c.replace(\"'\",' ')\n print(d)\n file2.write(d+'\\n')\n\nfile.close() \n\n\n","sub_path":"py267_羅駿朋_hw6.py.py","file_name":"py267_羅駿朋_hw6.py.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396122864","text":"#!/usr/bin/env python\n\n##\n# Copyright (c) 2009-2014 Apple Inc. All Rights Reserved.\n#\n# IMPORTANT NOTE: This file is licensed only for use on Apple-branded\n# computers and is subject to the terms and conditions of the Apple Software\n# License Agreement accompanying the package this file is a part of.\n# You may not port this file to another platform without Apple's written consent.\n#\n# IMPORTANT NOTE: This file is licensed only for use with the Wiki Server feature\n# of the Apple Software and is subject to the terms and conditions of the Apple\n# Software License Agreement accompanying the package this file is part of.\n##\n\nimport os\nfrom subprocess import Popen, PIPE\n\nserverInstallPathPrefix = \"/Applications/Server.app/Contents/ServerRoot\"\n\n# Kill all running _teamsserver processes.\n\nprocess = Popen('ps aux | grep -v grep | grep _teamsserver', stdout=PIPE, shell=True)\nlines = process.stdout.read().split('\\n')\nfor line in lines:\n\tcols = line.split()\n\tif (len(cols) > 1):\n\t\towner = cols[0]\n\t\tpid = cols[1]\n\t\tif owner == '_teamsserver':\n\t\t\tos.system('kill -TERM ' + pid)\n\n# Remove any files we installed outside /Library/Server.\nos.system(\"/bin/rm /private/etc/newsyslog.d/com.apple.collabd.conf\")\n","sub_path":"src/server/10.12/Payload/Applications/Server.app/Contents/ServerRoot/System/Library/ServerSetup/UninstallExtras/CoreCollaborationUninstallExtra.py","file_name":"CoreCollaborationUninstallExtra.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"564637904","text":"import json\nimport collections\n\nwith open('seattle.json') as json_file: \n airbnb = json.load(json_file)\n\nreviews = airbnb[0]['detailed_reviews']\n\nreview_dict = collections.defaultdict(dict)\ncount = 0\n\nfor review in reviews:\n review_dict[count]['reviewer_name'] = review.get('reviewer').get('first_name')\n review_dict[count]['review_rating'] = review.get('rating')\n count = count + 1\n \nprint(count)\n\n\ncalendar_yr = airbnb[0]['calendar']\n\ncalendar = []\n\nfor month in calendar_yr:\n day_count = 0\n \n for day in month.get('days'):\n if(day.get('available')):\n day_count = day_count + 1\n \n calendar.append(day_count)\n \nprint(calendar)","sub_path":"airbnb_scraper/.ipynb_checkpoints/review_cal-checkpoint.py","file_name":"review_cal-checkpoint.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133342152","text":"import json\r\nfrom demo.settings import BASE_DIR\r\n\r\n\r\ndef get_tips():\r\n jsonfile = BASE_DIR + '/data/junshi_data.json' # 生成的json地址\r\n with open(jsonfile,encoding='utf-8') as f:\r\n data=[]\r\n tmp_row=f.readline()\r\n while tmp_row:\r\n data.append(json.loads(tmp_row))\r\n tmp_row=f.readline()\r\n entity_array = []\r\n for row in data:\r\n entity_array.append(row['spo_list']['subject']) # 添加实体名\r\n entity_array = list(set(entity_array))\r\n return entity_array\r\n\r\n\r\ndef get_contact(data,key):\r\n kf_data=[]\r\n for row in data:\r\n row_data = row['spo_list']\r\n if row_data['subject'] == key:\r\n tmp_dict = {'source': row_data['subject'], 'target': row_data['object'], 'rela': row_data['predicate'],\r\n 'type': 'resolved'}\r\n kf_data.append(tmp_dict)\r\n if row_data['object']!=key:\r\n tmp_kf_data=get_contact(data,row_data['object'])\r\n kf_data.extend(tmp_kf_data)\r\n return kf_data\r\n\r\n\r\ndef get_data(key):\r\n jsonfile = BASE_DIR + '/data/junshi_data.json' # 生成的json地址\r\n with open(jsonfile,encoding='utf-8') as f:\r\n data = [] # 读取文件保存数据\r\n tmp_row = f.readline()\r\n while tmp_row:\r\n data.append(json.loads(tmp_row))\r\n tmp_row = f.readline()\r\n kf_data = []\r\n kf_data.extend(get_contact(data,key))\r\n return kf_data\r\n","sub_path":"demo/demo/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154233154","text":"\"\"\"\nWe can rotate digits by 180 degrees to form new digits.\nWhen 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively.\nWhen 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.\n\nA confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.\n(Note that the rotated number can be greater than the original number.)\n\ngo from 1 digit, 2 digit, 3 digit, 4 digit ....\n----\n\nGiven a positive integer N, return the number of confusing numbers between 1 and N inclusive.\nExample 1:\n\nInput: 20\nOutput: 6\nExplanation:\nThe confusing numbers are [6,9,10,16,18,19].\n6 converts to 9.\n9 converts to 6.\n10 converts to 01 which is just 1.\n16 converts to 91.\n18 converts to 81.\n19 converts to 61.\n\nExample 2:\n\nInput: 100\nOutput: 19\nExplanation:\nThe confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100].\n\"\"\"\nrotate_map = {\"6\": \"9\", \"1\": \"1\", \"0\": \"0\", \"8\": \"8\", \"9\": \"6\"}\n\n\ndef generate_confusing(n):\n def is_confusing_num(num):\n str_num = str(num)\n res = []\n for s in str_num:\n if s not in rotate_map:\n return False\n res.append(rotate_map[s])\n rotated = \"\".join(reversed(res))\n return str_num != rotated\n\n ones = [6, 9]\n if n < 10:\n result = []\n for o in ones:\n if o <= n:\n result += 1\n return result\n\n options = [0, 1, 6, 8, 9]\n prev = [1, 6, 8, 9]\n result = 2\n done = False\n while not done:\n new_prev = []\n for p in prev:\n for digit in options:\n new_num = p * 10 + digit\n if new_num > n:\n done = True\n break\n if is_confusing_num(new_num):\n result += 1\n new_prev.append(new_num)\n if done:\n break\n prev = new_prev\n return result\n\n\nif __name__ == \"__main__\":\n assert generate_confusing(100) == 19\n","sub_path":"lc_discuss/old/batch_3/confusing_number_ii.py","file_name":"confusing_number_ii.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"429005007","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Turing'\n\n\"\"\"\n\"\"\"\nimport Tkinter as tk\nimport sys\n\nmakemodal = (len(sys.argv) > 1)\n\n\ndef dialog():\n win = tk.Toplevel()\n tk.Label(master=win, text=\"Hard drive reformatted!\").pack()\n tk.Button(master=win, text=\"OK\", command=win.destroy).pack()\n if makemodal:\n win.focus_set()\n win.grab_set()\n win.wait_window()\n print(\"dialog exit\")\n\nif __name__ == '__main__':\n root = tk.Tk()\n tk.Button(master=root, text=\"popup\", command=dialog).pack()\n root.mainloop()\n","sub_path":"python/PP4E/Gui/Tour/dlg-custom.py","file_name":"dlg-custom.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"129590418","text":"import tkinter as tk\n\n\nclass InlogVenster(tk.Frame):\n \"\"\"Het venster waar de aanbieder kan inloggen.\"\"\"\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n\n self.controller = controller\n self.aanbieder = controller.aanbieder\n\n self.configure(bg=\"#007EA7\")\n\n frame_border = tk.Frame(self, pady=3, bg=\"#00A8E8\")\n frame_border.pack(side=tk.TOP, fill=tk.X)\n\n frame_balk = tk.Frame(frame_border, pady=20, bg=\"#003459\")\n frame_balk.pack(side=tk.TOP, fill=tk.X)\n\n titel = tk.Label(frame_balk, text=\"Aanbieders\", fg=\"#00A8E8\", bg=\"#003459\", font=(\"\", 32))\n titel.pack(side=tk.TOP)\n\n\n frame_login = tk.Frame(self, bg=\"#007EA7\")\n frame_login.place(relx=0.5, rely=0.5, anchor=tk.CENTER)\n\n label_naam = tk.Label(frame_login, bg=\"#007EA7\", text=\"Naam: \")\n label_email = tk.Label(frame_login, bg=\"#007EA7\", text=\"Wachtwoord: \")\n label_naam.grid(row=0, column=0, sticky=tk.W)\n label_email.grid(row=1, column=0, sticky=tk.W)\n\n self.entry_naam = tk.Entry(frame_login, bg=\"#95A3A4\")\n self.entry_wachtwoord = tk.Entry(frame_login, bg=\"#95A3A4\", show=\"*\")\n self.entry_naam.grid(row=0, column=1)\n self.entry_wachtwoord.grid(row=1, column=1)\n\n button_terug = tk.Button(frame_login, text=\"Terug\", bg=\"#00A8E8\", command=lambda: controller.show_frame(\"beginvenster\"))\n button_terug.grid(row=2, column=0, sticky=tk.W, pady=(5, 0))\n\n button_login = tk.Button(frame_login, text=\"Inloggen\", bg=\"#00A8E8\", command=self.volgende_venster)\n button_login.grid(row=2, column=1, sticky=tk.W, pady=(5, 0))\n\n self.label_waarschuwing = tk.Label(frame_login, bg=\"#007EA7\", text=\"\")\n self.label_waarschuwing.grid(row=3, column=0, columnspan=2)\n\n def volgende_venster(self):\n \"\"\"Deze functie laat het volgende scherm zien. Maar alleen als de inloggevens kloppen\"\"\"\n login_details = self.aanbieder.get_login()\n naam = self.entry_naam.get()\n wachtwoord = self.entry_wachtwoord.get()\n\n if [naam, wachtwoord] in login_details:\n self.aanbieder.naam = naam\n self.controller.refresh_frame(\"inlogvenster\")\n self.controller.show_frame(\"overzichtvenster\")\n else:\n self.label_waarschuwing.configure(text=\"Inloggevens kloppen niet\")\n","sub_path":"GUI/inlogvenster.py","file_name":"inlogvenster.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163955321","text":"# goto action\n\nimport time, math, sys, random\n\nimport rospy\nimport tf\n\nimport actionlib\n\nfrom actionlib_msgs.msg import *\nfrom geometry_msgs.msg import Quaternion, PoseWithCovarianceStamped\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\n\nfrom sensor_msgs.msg import *\nfrom std_msgs.msg import *\nfrom geometry_msgs.msg import PoseArray\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\nfrom geometry_msgs.msg import PoseWithCovariance\nfrom nav_msgs.msg import Odometry\n\nfrom actionproxy import ActionProxy\n\nACTION_NAME = 'gotopersondetected'\nACTION_move_base = 'move_base' # ROS action\nTOPIC_amcl_pose = 'amcl_pose' # localizer pose\nBASE_POSE_GROUND_TRUTH_TOPIC = '/base_pose_ground_truth'\nTARGET_RADIUS = 0.3\n\nLEG_FLUENT_TOPIC = '/human_positions'\n\n\n\nclass GotoPersonDetectedActionProxy(ActionProxy):\n\n def __init__(self, actionname):\n ActionProxy.__init__(self, actionname)\n\n self.map_robot_pose = [0,0,0]\n self.humans = {}\n\n self.leg_sub = rospy.Subscriber(LEG_FLUENT_TOPIC, PoseArray, self.humans_cb)\n rospy.sleep(0.5)\n\n #self.loc_sub = rospy.Subscriber(TOPIC_amcl_pose, PoseWithCovarianceStamped, self.localizer_cb)\n self.ac_movebase = None\n\n self.ac_movebase = actionlib.SimpleActionClient(ACTION_move_base, MoveBaseAction)\n self.ac_movebase.wait_for_server()\n\n def __del__(self):\n ActionProxy.__del__(self)\n\n def humans_cb(self,data):\n \"\"\"\n :param data: it is a PoseArray()\n\n :return: map that has\n - key: the id (not really an ID, but a fake id) of a person\n - values: the relatives position (w.r.t. marrtino).\n Note that the orientation is already in radians, and we do not need\n to convert it.\n \"\"\"\n\n for i,obj in enumerate(data.poses):\n self.humans[i] = [obj.position.x,obj.position.y,obj.orientation.z]\n rospy.loginfo(\"Humans position received: %r\" %self.humans)\n\n def distance(self, p1, p2):\n return math.sqrt(math.pow(p2[0] - p1[0], 2) + math.pow(p2[1] - p1[1], 2))\n\n def localizer_cb(self, data):\n self.map_robot_pose[0] = data.pose.pose.position.x\n self.map_robot_pose[1] = data.pose.pose.position.y\n o = data.pose.pose.orientation\n q = (o.x, o.y, o.z, o.w)\n euler = tf.transformations.euler_from_quaternion(q)\n self.map_robot_pose[2] = euler[2] # yaw\n\n def send_rotation_goal(self,angle):\n rospy.loginfo(\"Sending goal..\")\n\n goal = MoveBaseGoal()\n\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n\n yaw = angle + self.map_robot_pose[2]\n q = tf.transformations.quaternion_from_euler(0, 0, yaw)\n\n # AS ALTERNATIVE, JUST ROTATE MARRTINO TOWARDS EACH PEOPLE AND USE THE PERSON\n # DETECTION MODULE\n goal.target_pose.pose.position.x = self.map_robot_pose[0]\n goal.target_pose.pose.position.y = self.map_robot_pose[1]\n goal.target_pose.pose.orientation = Quaternion(q[0], q[1], q[2], q[3])\n\n rospy.loginfo(\"ANGLE OF PERSON RECEIVED (DEGREE): %f\\n\" %(angle * 180 / math.pi))\n rospy.loginfo(\"ANGLE OF PERSON RECEIVED (RADIANS): %f\\n\" %angle)\n rospy.loginfo(\"MARRTINO ANGLE (DEGREE): %f\\n\" % (self.map_robot_pose[2] * 180 / math.pi))\n rospy.loginfo(\"MARRTINO ANGLE (RADIANS): %f\\n\" %self.map_robot_pose[2])\n rospy.loginfo(\"ANGLE SENT AS GOAL (DEGREE): %f\\n\" % (yaw * 180 / math.pi))\n rospy.loginfo(\"ANGLE SENT AS GOAL (RADIANS): %f\\n\" %yaw)\n\n self.ac_movebase.send_goal(goal)\n\n rospy.loginfo(\"move_base: rotational goal %r sent!\" % (goal))\n\n def send_goal(self, target_pose):\n rospy.loginfo(\"Sending goal..\")\n\n goal = MoveBaseGoal()\n\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n\n # Consider a circle as origin the person and a radius of a TARGET_RADIUS m.\n # Marrtino does not want to go too close to the person.\n offset_x = TARGET_RADIUS if (target_pose[0] < 0) else - TARGET_RADIUS\n offset_y = TARGET_RADIUS if (target_pose[1] < 0) else - TARGET_RADIUS\n\n target_x = self.map_robot_pose[0] + target_pose[0] + offset_x\n target_y = self.map_robot_pose[1] + target_pose[1] + offset_y\n\n # Yaw of each person is already in degree\n yaw = target_pose[2] + self.map_robot_pose[2]\n q = tf.transformations.quaternion_from_euler(0, 0, yaw)\n\n # AS ALTERNATIVE, JUST ROTATE MARRTINO TOWARDS EACH PEOPLE AND USE THE PERSON\n # DETECTION MODULE\n goal.target_pose.pose.position.x = target_x\n goal.target_pose.pose.position.y = target_y\n goal.target_pose.pose.orientation = Quaternion(q[0], q[1], q[2], q[3])\n\n\n rospy.loginfo(\"Robot pose: %r\\n\" %([self.map_robot_pose[0],self.map_robot_pose[1]]))\n rospy.loginfo(\"Human pose (w.r.t MARRTINO): %r\\n\" %([target_pose[0],target_pose[1]]))\n rospy.loginfo(\"DISTANCE BETWEEN TARGET POSITION AND HUMAN: %r\\n\" % (\n self.distance([self.map_robot_pose[0] + target_pose[0], self.map_robot_pose[1] + target_pose[1]],\n [target_x, target_y])))\n rospy.loginfo(\"PERSON RECEIVED (w.r.t MARRTINO) ANGLE: %f\\n\" % (target_pose[2] * 180 / math.pi))\n rospy.loginfo(\"MARRTINO ANGLE (DEGREE): %f\\n\" % (self.map_robot_pose[2] * 180 / math.pi))\n rospy.loginfo(\"ANGLE (DEGREE) SENT AS GOAL: %f\\n\" % (yaw * 180 / math.pi))\n\n self.ac_movebase.send_goal(goal)\n\n rospy.loginfo(\"move_base: goal %r sent!\" % (goal))\n\n\n\n def action_thread(self, params):\n rospy.loginfo(\"Leg detection action thread started\")\n rospy.sleep(2)\n\n self.loc_sub = rospy.Subscriber(BASE_POSE_GROUND_TRUTH_TOPIC, Odometry, self.localizer_cb)\n rospy.sleep(0.5)\n\n #for index,key in self.humans.items():\n self.send_goal(self.humans[0])\n #self.send_rotation_goal(key[2])\n\n finished = False\n while self.do_run and not finished:\n self.ac_movebase.wait_for_result(rospy.Duration(1))\n status = self.ac_movebase.get_state() # 1 ACTIVE, 3 SUCCEEDED, 4 ABORTED\n finished = (status == GoalStatus.SUCCEEDED) or (status == GoalStatus.ABORTED)\n\n state = self.ac_movebase.get_state()\n if state == GoalStatus.SUCCEEDED:\n rospy.loginfo(\"move_base: goal succeeded!\")\n else:\n rospy.loginfo(\"move_base: goal failed!\")\n\n self.ac_movebase.get_result()\n self.ac_movebase.cancel_all_goals()\n self.loc_sub.unregister()\n\n\nif __name__ == \"__main__\":\n\n params = None\n if (len(sys.argv) > 1):\n params = sys.argv[1]\n\n a = GotoPersonDetectedActionProxy(ACTION_NAME)\n\n if params is not None:\n a.execute(params) # blocking, CTRL-C to interrupt\n else:\n a.run_server() # blocking, CTRL-C to interrupt","sub_path":"actions/gotopersondetected_actionproxy.py","file_name":"gotopersondetected_actionproxy.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22373032","text":"# Copyright 2016, 2017, 2020 California Institute of Technology\n# Users must agree to abide by the restrictions listed in the\n# file \"LegalStuff.txt\" in the PROPER library directory.\n#\n# PROPER developed at Jet Propulsion Laboratory/California Inst. Technology\n# Original IDL version by John Krist\n# Python translation by Navtej Saini, with Luis Marchen and Nikta Amiri\n\nimport proper\nimport numpy as np\n\ndef prop_ellipse(wf, xradius, yradius, xc = 0.0, yc = 0.0, **kwargs):\n \"\"\"Creates an image containing an antialiased filled ellipse\n\n Parameters\n ----------\n wf : obj\n Wavefront class object\n\n xradius : float\n Ellipse X radius (in meters unless NORM is set)\n\n yradius : float\n Ellipse Y radius (in meters unless NORM is set)\n\n Returns\n -------\n mask : numpy ndarray\n Image array containing antialiased, filled ellipse\n\n Other Parameters\n ----------------\n xc : float\n X center of ellipse relative to wavefront center (in meters unless norm\n is specified). Default is centered at wavefront center.\n\n yc : float\n Y center of ellipse relative to wavefront center (in meters unless norm\n is specified). Default is centered at wavefront center.\n\n DARK : bool\n Draw a dark ellipse (0 inside, 1 outside) (default is opposite way)\n\n NORM : bool\n Indicates radii and center coordinates are normalized to beam radius.\n\n ROTATION : float\n Angle in degrees to rotate ellipse.\n\n Modified by JEK - Jan 2020 - added rotation & subsample parameters.\n \"\"\"\n\n nsub = proper.antialias_subsampling\n \n if \"ROTATION\" in kwargs:\n rotation = kwargs[\"ROTATION\"]\n else:\n rotation = 0.0\n\n norm = proper.switch_set(\"NORM\",**kwargs)\n\n n = proper.prop_get_gridsize(wf)\n dx = proper.prop_get_sampling(wf)\n beamrad_pix = proper.prop_get_beamradius(wf) / dx\n\n xcenter_pix = n // 2\n ycenter_pix = n // 2\n\n if norm:\n xcenter_pix = xcenter_pix + xc * beamrad_pix \n ycenter_pix = ycenter_pix + yc * beamrad_pix\n xrad_pix = xradius * beamrad_pix\n yrad_pix = yradius * beamrad_pix\n else:\n xcenter_pix = xcenter_pix + xc / dx\n ycenter_pix = ycenter_pix + yc / dx\n xrad_pix = xradius / dx \n yrad_pix = yradius / dx\n\n t = rotation * np.pi / 180\n\n # rotate coordinates defining box containing unrotated ellipse\n\n sint = np.sin(t)\n cost = np.cos(t)\n xp = np.array( [-xrad_pix,xrad_pix,xrad_pix,-xrad_pix] )\n yp = np.array( [-yrad_pix,-yrad_pix,yrad_pix,yrad_pix] )\n xbox = xp * cost - yp * sint + xcenter_pix\n ybox = xp * sint + yp * cost + ycenter_pix\n\n minx_pix = int(np.clip( np.round(np.min(xbox))-1, 0, n-1))\n maxx_pix = int(np.clip( np.round(np.max(xbox))+1, 0, n-1))\n nx = maxx_pix - minx_pix + 1\n miny_pix = int(np.clip( np.round(np.min(ybox))-1, 0, n-1))\n maxy_pix = int(np.clip( np.round(np.max(ybox))+1, 0, n-1))\n ny = maxy_pix - miny_pix + 1\n\n # create & rotate coordinate arrays \n \n y_array, x_array = np.mgrid[ 0:ny, 0:nx ] \n x = x_array + (minx_pix - xcenter_pix)\n y = y_array + (miny_pix - ycenter_pix)\n\n xr = (x * cost - y * sint) / xrad_pix\n yr = (x * sint + y * cost) / yrad_pix\n r = np.sqrt(xr*xr + yr*yr)\n drx = np.abs(r[0,1] - r[0,0])\n dry = np.abs(r[1,0] - r[0,0])\n\n delx = 1.0 / xrad_pix\n dely = 1.0 / yrad_pix\n drx = delx * cost - dely * sint\n dry = delx * sint + dely * cost\n dr = max( abs(drx), abs(dry) )\n\n mask = np.full( (ny,nx), -1, dtype=np.float64 ) \n mask *= (1 - (r > (1+dr)))\n m = (r <= (1-dr))\n mask = mask * (1 - m) + m\n (y_edge, x_edge) = np.where(mask == -1) # find pixels along edge of ellipse to subpixellate\n npix = len(x_edge)\n\n # for each pixel along the edge, subpixellate it to compute fractional coverage (anti-aliasing)\n\n nsubpix = float(nsub * nsub)\n y_array, x_array = np.mgrid[ 0:nsub, 0:nsub ]\n subpix_x_array = (x_array - nsub//2) / float(nsub) + (minx_pix - xcenter_pix)\n subpix_y_array = (y_array - nsub//2) / float(nsub) + (miny_pix - ycenter_pix)\n\n xs = np.zeros( (nsub,nsub) )\n ys = np.zeros( (nsub,nsub) )\n x = np.zeros( (nsub,nsub) )\n y = np.zeros( (nsub,nsub) )\n\n limit = 1 + 1e-10\n\n for i in range(npix):\n xs[:,:] = subpix_x_array + x_edge[i]\n ys[:,:] = subpix_y_array + y_edge[i]\n x[:,:] = (xs * cost - ys * sint) / xrad_pix\n y[:,:] = (xs * sint + ys * cost) / yrad_pix\n mask[y_edge[i],x_edge[i]] = np.sum((x*x+y*y) <= limit) / nsubpix\n\n if proper.switch_set(\"DARK\",**kwargs):\n image = np.ones( (n,n), dtype=np.float64 )\n image[miny_pix:miny_pix+ny,minx_pix:minx_pix+nx] = 1 - mask\n else:\n image = np.zeros( (n,n), dtype=np.float64 )\n image[miny_pix:miny_pix+ny,minx_pix:minx_pix+nx] = mask\n \n return image \n\n","sub_path":"proper_v3.2.1_python_3.x_12feb20/proper/prop_ellipse.py","file_name":"prop_ellipse.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11952961","text":"#!/usr/bin/env python\n#\n# Good kraken and python resource:\n# https://github.com/zertrin/clikraken/tree/master/clikraken\nimport base64\nimport hashlib\nimport hmac\nimport logging\nimport time\nfrom typing import Any, Dict, List, Optional, Tuple, Union\nfrom urllib.parse import urlencode\n\nfrom requests import Response\n\nfrom rotkehlchen.assets.asset import Asset\nfrom rotkehlchen.assets.converters import asset_from_kraken\nfrom rotkehlchen.constants import KRAKEN_API_VERSION, KRAKEN_BASE_URL\nfrom rotkehlchen.constants.assets import A_BSV\nfrom rotkehlchen.errors import (\n DeserializationError,\n RecoverableRequestError,\n RemoteError,\n UnknownAsset,\n UnprocessableTradePair,\n)\nfrom rotkehlchen.exchange import Exchange\nfrom rotkehlchen.fval import FVal\nfrom rotkehlchen.inquirer import query_cryptocompare_for_fiat_price\nfrom rotkehlchen.logging import RotkehlchenLogsAdapter\nfrom rotkehlchen.order_formatting import (\n AssetMovement,\n Trade,\n get_pair_position_asset,\n pair_get_assets,\n trade_pair_from_assets,\n)\nfrom rotkehlchen.serializer import (\n deserialize_asset_amount,\n deserialize_fee,\n deserialize_price,\n deserialize_timestamp_from_kraken,\n deserialize_trade_type,\n)\nfrom rotkehlchen.typing import ApiKey, ApiSecret, Fee, FilePath, Timestamp, TradePair\nfrom rotkehlchen.user_messages import MessagesAggregator\nfrom rotkehlchen.utils.misc import cache_response_timewise, retry_calls\nfrom rotkehlchen.utils.serialization import rlk_jsonloads_dict\n\nlogger = logging.getLogger(__name__)\nlog = RotkehlchenLogsAdapter(logger)\n\n\nKRAKEN_ASSETS = (\n 'ATOM',\n 'XDAO',\n 'XETC',\n 'XETH',\n 'XLTC',\n 'XREP',\n 'XXBT',\n 'XXMR',\n 'XXRP',\n 'XZEC',\n 'ZEUR',\n 'ZUSD',\n 'ZGBP',\n 'ZCAD',\n 'ZJPY',\n 'ZKRW',\n 'XMLN',\n 'XICN',\n 'GNO',\n 'BCH',\n 'BSV',\n 'XXLM',\n 'DASH',\n 'EOS',\n 'USDT',\n 'KFEE',\n 'ADA',\n 'QTUM',\n 'XNMC',\n 'XXVN',\n 'XXDG',\n 'XTZ',\n)\n\nKRAKEN_DELISTED = ('XDAO', 'XXVN', 'ZKRW', 'XNMC', 'BSV', 'XICN')\n\n\ndef kraken_to_world_pair(pair: str) -> TradePair:\n \"\"\"Turns a pair from kraken to our pair type\n\n Can throw:\n - UknownAsset if one of the assets of the pair are not known\n - UnprocessableKrakenPair if the pair can't be processed and\n split into its base/quote assets\n\"\"\"\n # handle dark pool pairs\n if pair[-2:] == '.d':\n pair = pair[:-2]\n\n if pair[0:3] in KRAKEN_ASSETS:\n base_asset_str = pair[0:3]\n quote_asset_str = pair[3:]\n elif pair[0:4] in KRAKEN_ASSETS:\n base_asset_str = pair[0:4]\n quote_asset_str = pair[4:]\n else:\n raise UnprocessableTradePair(pair)\n\n base_asset = asset_from_kraken(base_asset_str)\n quote_asset = asset_from_kraken(quote_asset_str)\n\n return trade_pair_from_assets(base_asset, quote_asset)\n\n\ndef world_to_kraken_pair(tradeable_pairs: List[str], pair: TradePair) -> str:\n base_asset, quote_asset = pair_get_assets(pair)\n\n base_asset_str = base_asset.to_kraken()\n quote_asset_str = quote_asset.to_kraken()\n\n pair1 = base_asset_str + quote_asset_str\n pair2 = quote_asset_str + base_asset_str\n\n # In some pairs, XXBT is XBT and ZEUR is EUR ...\n pair3 = None\n if 'XXBT' in pair1:\n pair3 = pair1.replace('XXBT', 'XBT')\n pair4 = None\n if 'XXBT' in pair2:\n pair4 = pair2.replace('XXBT', 'XBT')\n if 'ZEUR' in pair1:\n pair3 = pair1.replace('ZEUR', 'EUR')\n pair4 = None\n if 'ZEUR' in pair2:\n pair4 = pair2.replace('ZEUR', 'EUR')\n\n if pair1 in tradeable_pairs:\n new_pair = pair1\n elif pair2 in tradeable_pairs:\n new_pair = pair2\n elif pair3 in tradeable_pairs:\n new_pair = pair3\n elif pair4 in tradeable_pairs:\n new_pair = pair4\n else:\n raise ValueError(\n f'Unknown pair \"{pair}\" provided. Couldnt find {base_asset_str + quote_asset_str}'\n f' or {quote_asset_str + base_asset_str} in tradeable pairs',\n )\n\n return new_pair\n\n\ndef trade_from_kraken(kraken_trade: Dict[str, Any]) -> Trade:\n \"\"\"Turn a kraken trade returned from kraken trade history to our common trade\n history format\n\n - Can raise UnknownAsset due to kraken_to_world_pair\n - Can raise UnprocessableTradePair due to kraken_to_world_pair\n - Can raise DeserializationError due to dict entries not being as expected\n - Can raise KeyError due to dict entries missing an expected entry\n \"\"\"\n currency_pair = kraken_to_world_pair(kraken_trade['pair'])\n quote_currency = get_pair_position_asset(currency_pair, 'second')\n timestamp = deserialize_timestamp_from_kraken(kraken_trade['time'])\n amount = deserialize_asset_amount(kraken_trade['vol'])\n cost = deserialize_price(kraken_trade['cost'])\n fee = deserialize_fee(kraken_trade['fee'])\n order_type = deserialize_trade_type(kraken_trade['type'])\n rate = deserialize_price(kraken_trade['price'])\n\n if cost != amount * rate:\n log.warning('cost ({cost}) != amount ({amount}) * rate ({rate}) for kraken trade')\n\n log.debug(\n 'Processing kraken Trade',\n sensitive_log=True,\n timestamp=timestamp,\n order_type=order_type,\n kraken_pair=kraken_trade['pair'],\n pair=currency_pair,\n quote_currency=quote_currency,\n amount=amount,\n cost=cost,\n fee=fee,\n rate=rate,\n )\n\n return Trade(\n timestamp=timestamp,\n location='kraken',\n pair=currency_pair,\n trade_type=order_type,\n amount=amount,\n rate=rate,\n fee=fee,\n fee_currency=quote_currency,\n )\n\n\ndef _check_and_get_response(response: Response, method: str) -> dict:\n \"\"\"Checks the kraken response and if it's succesfull returns the result. If there\n is an error an exception is raised\"\"\"\n if response.status_code in (520, 525, 504):\n raise RecoverableRequestError('kraken', 'Usual kraken 5xx shenanigans')\n elif response.status_code != 200:\n raise RemoteError(\n 'Kraken API request {} for {} failed with HTTP status '\n 'code: {}'.format(\n response.url,\n method,\n response.status_code,\n ))\n\n result = rlk_jsonloads_dict(response.text)\n if result['error']:\n if isinstance(result['error'], list):\n error = result['error'][0]\n else:\n error = result['error']\n\n if 'Rate limit exceeded' in error:\n raise RecoverableRequestError('kraken', 'Rate limited exceeded')\n else:\n raise RemoteError(error)\n\n return result['result']\n\n\nclass Kraken(Exchange):\n def __init__(\n self,\n api_key: ApiKey,\n secret: ApiSecret,\n user_directory: FilePath,\n msg_aggregator: MessagesAggregator,\n usd_eur_price: FVal,\n ):\n super(Kraken, self).__init__('kraken', api_key, secret, user_directory)\n self.msg_aggregator = msg_aggregator\n # typing TODO: Without a union of str and Asset we get lots of warning\n # How can this be avoided without too much pain?\n self.usdprice: Dict[Union[Asset, str], FVal] = {}\n self.eurprice: Dict[Union[Asset, str], FVal] = {}\n\n self.usdprice['EUR'] = usd_eur_price\n self.session.headers.update({ # type: ignore\n 'API-Key': self.api_key,\n })\n\n def first_connection(self):\n if self.first_connection_made:\n return\n\n with self.lock:\n self.tradeable_pairs = self.query_public('AssetPairs')\n # also make sure to get fiat prices from ticker before considering\n # kraken ready for external queries\n self.get_fiat_prices_from_ticker()\n self.first_connection_made = True\n\n def validate_api_key(self) -> Tuple[bool, str]:\n try:\n self.query_private('Balance', req={})\n except (RemoteError, ValueError) as e:\n error = str(e)\n if 'Error: Incorrect padding' in error:\n return False, 'Provided API Key or secret is in invalid Format'\n elif 'EAPI:Invalid key' in error:\n return False, 'Provided API Key is invalid'\n else:\n raise\n return True, ''\n\n def _query_public(self, method: str, req: Optional[dict] = None) -> dict:\n \"\"\"API queries that do not require a valid key/secret pair.\n\n Arguments:\n method -- API method name (string, no default)\n req -- additional API request parameters (default: {})\n \"\"\"\n if req is None:\n req = {}\n urlpath = f'{KRAKEN_BASE_URL}/{KRAKEN_API_VERSION}/public/{method}'\n log.debug('Kraken Public API query', request_url=urlpath, data=req)\n response = self.session.post(urlpath, data=req)\n return _check_and_get_response(response, method)\n\n def query_public(self, method: str, req: Optional[dict] = None) -> dict:\n return retry_calls(\n times=5, location='kraken',\n handle_429=False,\n backoff_in_seconds=0,\n method_name=method,\n function=self._query_public,\n # function's arguments\n method=method,\n req=req,\n )\n\n def query_private(self, method: str, req: Optional[dict] = None) -> dict:\n return retry_calls(\n times=5, location='kraken',\n handle_429=False,\n backoff_in_seconds=0,\n method_name=method,\n function=self._query_private,\n # function's arguments\n method=method,\n req=req,\n )\n\n def _query_private(self, method: str, req: Optional[dict] = None) -> dict:\n \"\"\"API queries that require a valid key/secret pair.\n\n Arguments:\n method -- API method name (string, no default)\n req -- additional API request parameters (default: {})\n\n \"\"\"\n if req is None:\n req = {}\n\n urlpath = '/' + KRAKEN_API_VERSION + '/private/' + method\n\n with self.lock:\n # Protect this section, or else\n req['nonce'] = int(1000 * time.time())\n post_data = urlencode(req)\n # any unicode strings must be turned to bytes\n hashable = (str(req['nonce']) + post_data).encode()\n message = urlpath.encode() + hashlib.sha256(hashable).digest()\n signature = hmac.new(\n base64.b64decode(self.secret),\n message,\n hashlib.sha512,\n )\n self.session.headers.update({ # type: ignore\n 'API-Sign': base64.b64encode(signature.digest()),\n })\n log.debug('Kraken Private API query', request_url=urlpath, data=post_data)\n response = self.session.post(\n KRAKEN_BASE_URL + urlpath,\n data=post_data.encode(),\n )\n\n return _check_and_get_response(response, method)\n\n def get_fiat_prices_from_ticker(self):\n self.ticker = self.query_public(\n 'Ticker',\n req={'pair': ','.join(self.tradeable_pairs.keys())},\n )\n self.eurprice['BTC'] = FVal(self.ticker['XXBTZEUR']['c'][0])\n self.usdprice['BTC'] = FVal(self.ticker['XXBTZUSD']['c'][0])\n self.eurprice['ETH'] = FVal(self.ticker['XETHZEUR']['c'][0])\n self.usdprice['ETH'] = FVal(self.ticker['XETHZUSD']['c'][0])\n self.eurprice['REP'] = FVal(self.ticker['XREPZEUR']['c'][0])\n self.eurprice['XMR'] = FVal(self.ticker['XXMRZEUR']['c'][0])\n self.usdprice['XMR'] = FVal(self.ticker['XXMRZUSD']['c'][0])\n self.eurprice['ETC'] = FVal(self.ticker['XETCZEUR']['c'][0])\n self.usdprice['ETC'] = FVal(self.ticker['XETCZUSD']['c'][0])\n\n # ---- General exchanges interface ----\n def main_logic(self):\n if not self.first_connection_made:\n return\n self.get_fiat_prices_from_ticker()\n\n def find_fiat_price(self, kraken_asset: str) -> FVal:\n \"\"\"Find USD/EUR price of asset. The asset should be in the kraken style.\n e.g.: XICN. Save both prices in the kraken object and then return the\n USD price.\n \"\"\"\n if kraken_asset == 'KFEE':\n # Kraken fees have no value\n return FVal(0)\n\n if kraken_asset == 'XXBT':\n return self.usdprice['BTC']\n\n if kraken_asset == 'USDT':\n price = FVal(self.ticker['USDTZUSD']['c'][0])\n self.usdprice['USDT'] = price\n return price\n\n if kraken_asset == 'BSV':\n # BSV has been delisted by kraken at 29/04/19\n # https://blog.kraken.com/post/2274/kraken-is-delisting-bsv/\n # Until May 31st there can be BSV in Kraken (even with 0 balance)\n # so keep this until then to get the price\n return query_cryptocompare_for_fiat_price(A_BSV)\n\n # TODO: This is pretty ugly. Find a better way to check out kraken pairs\n # without this ugliness.\n pair = kraken_asset + 'XXBT'\n pair2 = kraken_asset + 'XBT'\n pair3 = 'XXBT' + kraken_asset\n inverse = False\n if pair2 in self.tradeable_pairs:\n pair = pair2\n elif pair3 in self.tradeable_pairs:\n pair = pair3\n # here XXBT is the base asset so inverse\n inverse = True\n\n if pair not in self.tradeable_pairs:\n raise ValueError(\n 'Could not find a BTC tradeable pair in kraken for \"{}\"'.format(kraken_asset),\n )\n btc_price = FVal(self.ticker[pair]['c'][0])\n if inverse:\n btc_price = FVal('1.0') / btc_price\n our_asset = asset_from_kraken(kraken_asset)\n with self.lock:\n self.usdprice[our_asset] = btc_price * self.usdprice['BTC']\n self.eurprice[our_asset] = btc_price * self.eurprice['BTC']\n return self.usdprice[our_asset]\n\n @cache_response_timewise()\n def query_balances(self) -> Tuple[Optional[dict], str]:\n try:\n self.first_connection()\n old_balances = self.query_private('Balance', req={})\n\n except RemoteError as e:\n msg = (\n 'Kraken API request failed. Could not reach kraken due '\n 'to {}'.format(e)\n )\n log.error(msg)\n return None, msg\n\n balances = dict()\n for k, v in old_balances.items():\n v = FVal(v)\n if v == FVal(0):\n continue\n\n try:\n our_asset = asset_from_kraken(k)\n except UnknownAsset as e:\n self.msg_aggregator.add_warning(\n f'Found unsupported/unknown kraken asset {e.asset_name}. '\n f' Ignoring its balance query.',\n )\n continue\n\n entry = {}\n entry['amount'] = v\n if our_asset in self.usdprice:\n entry['usd_value'] = v * self.usdprice[our_asset]\n else:\n entry['usd_value'] = v * self.find_fiat_price(k)\n\n balances[our_asset] = entry\n log.debug(\n 'kraken balance query result',\n sensitive_log=True,\n currency=our_asset,\n amount=entry['amount'],\n usd_value=entry['usd_value'],\n )\n\n return balances, ''\n\n def query_until_finished(\n self,\n endpoint: str,\n keyname: str,\n start_ts: Timestamp,\n end_ts: Timestamp,\n extra_dict: Optional[dict] = None,\n ) -> List:\n \"\"\" Abstracting away the functionality of querying a kraken endpoint where\n you need to check the 'count' of the returned results and provide sufficient\n calls with enough offset to gather all the data of your query.\n \"\"\"\n result: List = list()\n\n log.debug(\n f'Querying Kraken {endpoint} from {start_ts} to '\n f'{end_ts} with extra_dict {extra_dict}',\n )\n response = self._query_endpoint_for_period(\n endpoint=endpoint,\n start_ts=start_ts,\n end_ts=end_ts,\n extra_dict=extra_dict,\n )\n count = response['count']\n offset = len(response[keyname])\n result.extend(response[keyname].values())\n\n log.debug(f'Kraken {endpoint} Query Response with count:{count}')\n\n while offset < count:\n log.debug(\n f'Querying Kraken {endpoint} from {start_ts} to {end_ts} '\n f'with offset {offset} and extra_dict {extra_dict}',\n )\n response = self._query_endpoint_for_period(\n endpoint=endpoint,\n start_ts=start_ts,\n end_ts=end_ts,\n offset=offset,\n extra_dict=extra_dict,\n )\n assert count == response['count']\n response_length = len(response[keyname])\n offset += response_length\n if response_length == 0 and offset != count:\n # If we have provided specific filtering then this is a known\n # issue documented below, so skip the warning logging\n # https://github.com/rotkehlchenio/rotkehlchen/issues/116\n if extra_dict:\n break\n # it is possible that kraken misbehaves and either does not\n # send us enough results or thinks it has more than it really does\n log.warning(\n 'Missing {} results when querying kraken endpoint {}'.format(\n count - offset, endpoint),\n )\n break\n\n result.extend(response[keyname].values())\n\n return result\n\n def query_trade_history(\n self,\n start_ts: Timestamp,\n end_ts: Timestamp,\n end_at_least_ts: Timestamp,\n ) -> List[Trade]:\n with self.lock:\n cache = self.check_trades_cache_list(start_ts, end_at_least_ts)\n\n if cache is not None:\n result = cache\n else:\n result = self.query_until_finished('TradesHistory', 'trades', start_ts, end_ts)\n with self.lock:\n # save it in the disk for future reference\n self.update_trades_cache(result, start_ts, end_ts)\n\n # And now turn it from kraken trade to our own trade format\n trades = []\n for raw_data in result:\n try:\n trades.append(trade_from_kraken(raw_data))\n except UnknownAsset as e:\n self.msg_aggregator.add_warning(\n f'Found kraken trade with unknown asset '\n f'{e.asset_name}. Ignoring it.',\n )\n continue\n except UnprocessableTradePair as e:\n self.msg_aggregator.add_error(\n f'Found kraken trade with unprocessable pair '\n f'{e.pair}. Ignoring it.',\n )\n continue\n except (DeserializationError, KeyError) as e:\n msg = str(e)\n if isinstance(e, KeyError):\n msg = f'Missing key entry for {msg}.'\n self.msg_aggregator.add_error(\n 'Error processing a kraken trade. Check logs '\n 'for details. Ignoring it.',\n )\n log.error(\n 'Error processing a kraken trade',\n trade=raw_data,\n error=msg,\n )\n continue\n\n return trades\n\n def _query_endpoint_for_period(\n self,\n endpoint: str,\n start_ts: Timestamp,\n end_ts: Timestamp,\n offset: Optional[int] = None,\n extra_dict: Optional[dict] = None,\n ) -> dict:\n request: Dict[str, Union[Timestamp, int]] = dict()\n request['start'] = start_ts\n request['end'] = end_ts\n if offset is not None:\n request['ofs'] = offset\n if extra_dict is not None:\n request.update(extra_dict)\n result = self.query_private(endpoint, request)\n return result\n\n def query_deposits_withdrawals(\n self,\n start_ts: Timestamp,\n end_ts: Timestamp,\n end_at_least_ts: Timestamp,\n ) -> List[AssetMovement]:\n with self.lock:\n cache = self.check_trades_cache_list(\n start_ts,\n end_at_least_ts,\n special_name='deposits_withdrawals',\n )\n result: List[Any]\n\n if cache is not None:\n result = cache\n else:\n result = self.query_until_finished(\n endpoint='Ledgers',\n keyname='ledger',\n start_ts=start_ts,\n end_ts=end_ts,\n extra_dict=dict(type='deposit'),\n )\n result.extend(self.query_until_finished(\n endpoint='Ledgers',\n keyname='ledger',\n start_ts=start_ts,\n end_ts=end_ts,\n extra_dict=dict(type='withdrawal'),\n ))\n\n with self.lock:\n self.update_trades_cache(\n result,\n start_ts,\n end_ts,\n special_name='deposits_withdrawals',\n )\n\n log.debug('Kraken deposit/withdrawals query result', num_results=len(result))\n\n movements = list()\n for movement in result:\n try:\n movements.append(AssetMovement(\n exchange='kraken',\n category=movement['type'],\n timestamp=deserialize_timestamp_from_kraken(movement['time']),\n asset=asset_from_kraken(movement['asset']),\n amount=FVal(movement['amount']),\n fee=Fee(FVal(movement['fee'])),\n ))\n except UnknownAsset as e:\n self.msg_aggregator.add_warning(\n f'Found unknown kraken asset {e.asset_name}. '\n f'Ignoring its deposit/withdrawals query.',\n )\n continue\n\n return movements\n","sub_path":"rotkehlchen/kraken.py","file_name":"kraken.py","file_ext":"py","file_size_in_byte":22395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"177418689","text":"__author__ = 'PyBeaner'\n\n# You want to make a dictionary that maps keys to more than one value (a so-called \"multidict\").\n\n# use list or set as the child value?\n# preserve order\nd = {\n 'a': [1, 2, 3],\n 'b': [4, 5]\n}\n# eliminate duplicates\ne = {\n 'a': {1, 2, 3},\n 'b': {4, 5}\n}\n\n# we can use the defaultdict\n\nfrom collections import defaultdict\nd = defaultdict(list)\nd['a'].append(1)\nd['a'].append(2)\nd['b'].append(4)\nprint(d)\n\nd = defaultdict(set)\nd['a'].add(1)\nd['a'].add(2)\nd['b'].add(4)\nprint(d)\n\n\npairs = [(1,\"I\"),(2,\"II\")]\nd = {}\nfor key, value in pairs:\n if key not in d:\n d[key] = []\n d[key].append(value)\nprint(d)\n\n# defaultdict(related to problems of grouping records)\nd = defaultdict(list)\nfor key,value in pairs:\n d[key].append(value)\nprint(d)\n","sub_path":"Chapter 1. Data Structures and Algorithms/Mapping Keys to Multiple Values in a Dictionary/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"265514911","text":"from django.conf.urls import patterns, include, url\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\n\nurlpatterns = patterns('django.contrib.staticfiles.views',\n url(r'^static/(?P.*)$', 'serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),\n)\n\nurlpatterns += patterns('',\n url('^$', lambda x: HttpResponseRedirect('/v1/')),\n url(r'v1/', include('charisma.charisma_urls', namespace='charisma')),\n)\n\n\n\n","sub_path":"charisma/charisma/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"40182758","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt('dow.csv',delimiter=',')\nOPEN,HIGH,LOW,CLOSE,VOLUME,ADJ_CLOSE = range(6)\n\nmask_ind = np.where(data > 5.5 * 10**9)[0]\nmask = data > 5.5 * 10**9\ncnt = sum(mask)\n\nprint(data.size)\n\nprint(data[:,ADJ_CLOSE][mask_ind],cnt)\n\nplt.plot(data[:,ADJ_CLOSE])\nplt.plot(mask_ind,data[mask_ind,ADJ_CLOSE],'rx')\nplt.show()\n\n","sub_path":"exercises/dow_selection/bp_solution.py","file_name":"bp_solution.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"453937104","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass ChessMan(Sprite):\n def __init__(self, chess_type, left, top, settings, screen):\n super().__init__()\n self.settings = settings\n self.screen = screen\n self.type = chess_type\n self.image = self.settings.white_img\n if self.type:\n self.image = self.settings.black_img\n self.rect = self.image.get_rect()\n self.size = self.settings.board_width // 15 // 2\n self.rect.x = left\n self.rect.y = top\n\n def draw(self):\n self.screen.blit(self.image, self.rect)\n\n\n\n\n","sub_path":"chessman.py","file_name":"chessman.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"124928776","text":"given_file = open(\"input.txt\", \"r\")\nans = 0\n\n# get list of integers from each line\nnums = list(map(int, given_file.readline().split()))\n\nwhile nums:\n\n # get result of all numbers that evenly divide\n mini_nums = [a // b for a in nums for b in nums if a != b and a % b == 0]\n\n # should only be one per line\n ans += mini_nums[0]\n\n # get next line\n nums = list(map(int, given_file.readline().split()))\n\n# print answer\nprint(\"Answer:\", ans)\n\n# close file\ngiven_file.close()\n","sub_path":"Day02/Part02/day02_02.py","file_name":"day02_02.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"165667256","text":"from mkdocs.plugins import BasePlugin\nimport os.path\nfrom nbconvert import MarkdownExporter\nimport nbformat\n\n\nclass NotebookConverter(BasePlugin):\n\n def __init__(self):\n self.exporter = MarkdownExporter()\n\n def can_load(self, path):\n return path.lower().endswith('.ipynb') and not 'ipynb_checkpoints' in path.lower()\n\n def on_config(self, config, **kwargs):\n config['extra_javascript'].append('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML')\n\n def on_page_read_source(self, something, **kwargs):\n page = kwargs['page']\n config = kwargs['config']\n input_path = page.file.src_path\n\n if not self.can_load(input_path):\n return\n\n ipynb_path = os.path.join(config['docs_dir'], input_path)\n nb = nbformat.read(ipynb_path, as_version=4)\n\n # we'll place the supporting files alongside the final HTML\n stem = os.path.splitext(os.path.basename(input_path))[0]\n exporter_resources = {'output_files_dir': stem} \n \n (body, resources) = self.exporter.from_notebook_node(nb,\n resources=exporter_resources)\n \n # folder in site may not have been created yet, create it so that we\n # can drop the support files in there\n target_in_site = os.path.join(\n config['site_dir'],\n page.abs_url[1:])\n os.makedirs(target_in_site, exist_ok=True)\n\n for output in resources['outputs'].keys():\n path = os.path.join(\n target_in_site,\n '..',\n output\n )\n\n with open(path, 'wb') as f:\n f.write(resources['outputs'][output])\n\n return body\n","sub_path":"mkdocs_nbconvert/nbconvert.py","file_name":"nbconvert.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"489262834","text":"from django import template\r\nfrom news.models import *\r\n\r\nregister = template.Library()\r\n@register.inclusion_tag('news_tag.html', takes_context=True)\r\ndef news_sidebar(context):\r\n request = context['request']\r\n news_list = News.objects.filter(publish=True) \r\n context_dict = {'news':news_list,}\r\n return context_dict\r\n\r\n \r\n@register.inclusion_tag('news_footer_tag.html', takes_context=True)\r\ndef news_footer(context):\r\n request = context['request']\r\n news_list = News.objects.filter(publish=True) \r\n context_dict = {'news':news_list,}\r\n return context_dict\r\n \r\n@register.inclusion_tag('news_category_tag.html', takes_context=True)\r\ndef news_category(context):\r\n request = context['request']\r\n category_list = NewsCategory.objects.all() \r\n context_dict = {'category_list':category_list,}\r\n return context_dict","sub_path":"news/templatetags/news_tags.py","file_name":"news_tags.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115954673","text":"import random\n\ndef initMatrix(size):\n \"\"\"Initialize matrix.\"\"\"\n matr = []\n for i in range(size):\n matr.append([])\n for j in range(size):\n matr[i].append(random.randint(10, 99))\n return matr\n\ndef printMatrix(matr,size):\n \"\"\"Print matrix ordinarily.\"\"\"\n for i in range(size):\n print(matr[i])\n\ndef spiralPrintMatrix(matr,size):\n \"\"\"Print matrix spiral\"\"\"\n center =int((size)/2)\n i = j = center\n l = 1\n matrStr = ''\n while l <= center:\n while j >= center - l: # left\n matrStr = matrStr + str(matr[i][j]) + ' '\n j -= 1\n j += 1\n i += 1\n while i <= center + l: # down\n matrStr = matrStr + str(matr[i][j]) + ' '\n i += 1\n i -= 1\n j += 1\n while j <= center + l: # right\n matrStr = matrStr + str(matr[i][j]) + ' '\n j += 1\n j -= 1\n i -= 1\n while i >= center - l: # up\n matrStr = matrStr + str(matr[i][j]) + ' '\n i -= 1\n i += 1\n j -= 1\n l += 1\n for item in reversed(matr[i][:j+1]):\n matrStr = matrStr + str(item) + ' '\n print(matrStr)\n\n\nn = int(input(\"Введите n:\"))\nmatrix=initMatrix(2*n-1)\nprintMatrix(matrix, 2*n-1)\nspiralPrintMatrix(matrix, 2*n-1)\n","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"451304578","text":"from constants import Constants\nfrom model.zone import Zone\n\n\nclass ConstraintManager(object):\n\n\n @staticmethod\n def c3_neighbors_sync(vi, vj):\n diff = abs(vi - vj)\n if 0 < diff <= Constants.T_SYNCHRO:\n return 1\n return 0\n\n @staticmethod\n def c1_no_devices(monitored_area, vi):\n if monitored_area.has_no_devices() and vi < Constants.INFINITY:\n return Constants.INFINITY\n return 0\n\n @staticmethod\n def c2_device_status(monitored_area, vi):\n\n if monitored_area.is_in_critical_state():\n if vi > 0:\n return Constants.INFINITY\n else:\n min_end_of_prog = monitored_area.get_min_end_of_prog()\n if min_end_of_prog <= Constants.URGT_TIME and vi > min_end_of_prog:\n return 1\n\n return 0\n\n @staticmethod\n def c4_last_intervention(monitored_area, vi):\n if monitored_area.is_tau_too_high() and vi > Constants.URGT_TIME:\n print(\"tau too high\")\n return Constants.INFINITY\n return 0\n\n @staticmethod\n def c5_nothing_to_report(monitored_area, vi):\n\n if not monitored_area.is_in_critical_state() \\\n and monitored_area.get_min_end_of_prog() > Constants.URGT_TIME \\\n and monitored_area.tau < Constants.THREE_HOURS \\\n and vi < Constants.INFINITY:\n return 1\n\n return 0\n\n def get_cost_of_private_constraints_for_value(self, monitored_area, value):\n if type(monitored_area) is Zone:\n return self.__get_cost_for_zone(monitored_area, value)\n\n return self.c1_no_devices(monitored_area, value) \\\n + self.c2_device_status(monitored_area, value) \\\n + self.c4_last_intervention(monitored_area, value) \\\n + self.c5_nothing_to_report(monitored_area, value)\n\n def __get_cost_for_zone(self, monitored_area, value):\n\n cost = 0\n\n for room in monitored_area.rooms:\n\n if room.is_in_critical_state():\n print(\"critic_state\")\n return 0 if value == 0 else Constants.INFINITY\n\n cost += self.c4_last_intervention(room, value)\n cost += self.c2_device_status(room, value)\n cost += self.c5_nothing_to_report(room, value)\n\n return cost if cost < Constants.INFINITY else Constants.INFINITY\n","sub_path":"dcop_engine/constraint_manager.py","file_name":"constraint_manager.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"283270921","text":"#!usr/bin/env python\n#-*- coding:utf-8 -*-\n#\nclass ProfilVertical:\n def __init__ (self,x): # x est une liste de tuples (nivAuDessusDuSol,valeur) pas forcément classée\n self.x=x\n def affiche(self):\n print (self.x)\n def getKey(self,item):\n return item[0]\n def rechercheNiveauDuValref(self,valref):\n # tri des tuples (niv,val) par niveaux croissants\n xtrie=sorted(self.x, key=self.getKey)\n print (xtrie)\n print (valref)\n # recherche, en partant du niveau le plus bas, du premier franchissement de \"valref\" en décroissant\n valprec=xtrie[0][1]\n nivprec=xtrie[0][0]\n for x in xtrie:\n #print x\n if ((x[1] 0:\n\t\ts = s / nv\n\t\ts = round(s,2)\n\telse:\n\t\ts = \"NA\"\n\n\tg.write(\"{},{}\\n\".format(ft[k].strip(\"\\n\"),s))\n\t\n\tk = k + 1\n\ng.close()\n","sub_path":"codes_for_crystal_structure/local_RMSD_avg.py","file_name":"local_RMSD_avg.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289976256","text":"import sys\r\nimport random\r\nimport numpy as np\r\nfrom NN import Layer\r\nimport pygame\r\n\r\nclass Bird:\r\n def __init__(self, x, y, num_birds):\r\n self.p = [Vector(x, y)] * num_birds\r\n self.v = [Vector(0.0, 0.0)] * num_birds\r\n \r\n def delete(self, i):\r\n self.p.pop(i)\r\n self.v.pop(i)\r\n \r\n def get(self, i):\r\n return (self.p[i], self.v[i])\r\n\r\n def update_v(self, i):\r\n self.v[i] = Vector(0.0, -.666)\r\n\r\nclass Vector:\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n \r\n def __add__(self, other):\r\n if type(self) == type(other) == Vector:\r\n return Vector(self.x + other.x, self.y+other.y)\r\n else:\r\n raise TypeError\r\n \r\n def __repr__(self):\r\n return \"Vector({}, {})\".format(self.x, self.y)\r\n\r\nclass Wall:\r\n def __init__(self, width, height):\r\n self.w1 = random.randint(.3*height//1, .9*height//1)\r\n self.w2 = random.randint(.3*height//1, .9*height//1)\r\n self.x1 = width\r\n self.x2 = None\r\n \r\n def step(self, velocity, width, height):\r\n self.x1 += velocity\r\n if self.x2 is None and self.x1 len(done):\r\n for lol in range(len(players)):\r\n if players[lol] is not None:\r\n #Plays game for each NN in players[], once it dies adds that player to done and sets its index to None in players[]\r\n if i % 10:\r\n cpu(players[lol], birds, walls, width, height, lol)\r\n if -95<(walls.x1-width/5)<20:\r\n if not (22<(walls.w1-birds.p[lol].y)<155):\r\n done.append(Strat(players[lol].l1.weights, players[lol].l2.weights, players[lol].l1.bias, players[lol].l2.bias, i))\r\n players[lol] = None\r\n elif walls.x2 is not None and -95<(walls.x2-width/5)<20:\r\n if not (22<(walls.w2-birds.p[lol].y)<155):\r\n done.append(Strat(players[lol].l1.weights, players[lol].l2.weights, players[lol].l1.bias, players[lol].l2.bias, i))\r\n players[lol] = None\r\n elif not (25 < birds.p[lol].y < height - 25):\r\n done.append(Strat(players[lol].l1.weights, players[lol].l2.weights, players[lol].l1.bias, players[lol].l2.bias, i))\r\n players[lol] = None\r\n birds.v[lol] += gravity\r\n birds.p[lol] += birds.v[lol]\r\n if i > 100000:#Goal, if reached print and save strategy and exit\r\n for strat in players:\r\n if strat is not None:\r\n print(\"{}\\n{}\\n{}\\n{}\\n\\n\".format(strat.l1.weights, strat.l2.weights, strat.l1.bias, strat.l2.bias))\r\n saved.write(\"{}\\n{}\\n{}\\n{}\\n\\n\".format(strat.l1.weights, strat.l2.weights, strat.l1.bias, strat.l2.bias))\r\n sys.exit()\r\n #Uncomment all below for graphics... Much slower\r\n #screen.fill(white) #fills screen black is actually white\r\n walls.step(-.333, width, height)\r\n #draw_wall(walls.w1, walls.x1, 75, red, screen, height)\r\n #if walls.x2 is not None:\r\n # draw_wall(walls.w2, walls.x2, 75, red, screen, height)\r\n #for lmk in range(len(players)):\r\n # if players[lmk] is not None:\r\n # pygame.draw.circle(screen, green, (birds.p[lmk].x, birds.p[lmk].y), size)\r\n i += 1 # counts number of loops\r\n #pygame.display.update()\r\n for strat in done:\r\n if strat.fit > 50000:\r\n print(strat.fit)\r\n if strat.fit > 80000:\r\n print(\"{}\\n{}\\n{}\\n{}\\n{}\\n\\n\".format(strat.w1, strat.w2, strat.b1, strat.b2, strat.fit))\r\n saved.write(\"{}\\n{}\\n{}\\n{}\\n{}\\n\\n\".format(strat.w1, strat.w2, strat.b1, strat.b2, strat.fit))\r\n for a in range(5):\r\n good = max(done)\r\n done.remove(good)\r\n best.append(good)\r\n # Mutates best strategies\r\n best.append(best[0]+best[1])\r\n best.append(best[0]+best[2])\r\n best.append(best[1]+best[2])\r\n best.append(best[0]+best[3])\r\n best.append(best[0]+best[4])\r\n best.append(best[1]+best[3])\r\n best.append(best[1]+best[4])\r\n best.append(best[2]+best[3])\r\n best.append(best[2]+best[4])\r\n best.append(best[3]+best[4])\r\n for a in range(5):\r\n for b in range(3):\r\n #Adds 15 New randoms\r\n d = NN()\r\n best.append(Strat(d.l1.weights, d.l2.weights, d.l1.bias, d.l2.bias))\r\n for c in range(0, 100, 5):\r\n # 2nd mutation strategy\r\n best.append(Strat(best[a].w1+.001*c*np.random.randn(4, 6), best[a].w2+.001*c*np.random.randn(6, 1), \r\n best[a].b1+.001*c*np.random.randn(1, 6), best[a].b2+.001*c*np.random.randn(1, 1)))\r\n\r\n saved.close()\r\n return best\r\n\r\n\r\n#calculates if individual bird should jump, pushes normalized inputs through corresponding NN\r\ndef cpu(cpu1, birds, walls, width, height, i):\r\n bird = birds.get(i)\r\n if walls.x2 is None or bird[0].x-100 < walls.x1 < walls.x2:\r\n wall = [(walls.x1-bird[0].x)/(width/2), (walls.w1)/height, (bird[0].y)/height, bird[1].y]\r\n else:\r\n wall = [(walls.x2-bird[0].x)/(width/2), (walls.w2)/height, (bird[0].y)/height, bird[1].y] \r\n cpu1.calc(wall)\r\n if cpu1.output < 0:\r\n birds.v[i] = Vector(0, -.666)\r\n\r\n\r\n# starts with 1000 in first batch and goes through 1000 generagtions or until goal is reached\r\nstrats = train(1000)\r\nfor i in range(1000):\r\n strats = train(i, strats)","sub_path":"flappy_training.py","file_name":"flappy_training.py","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"566528022","text":"def swap_col_gcode(base_gcode_path, col_gcode_path, recombinant_gcode_path, base_slice_thickness, col_slice_thickness, base_thickness, col_temp):\n\t\"\"\"\n\tGrafts G-code lines corresponding to experimental column layers onto a stub gcode file corresponding to a datum base printed using almost-default settings. \n\n\tInputs:\n\t- base_gcode_path: string containing path to gcode file from which base layers will be taken\n\t- col_gcode_path: string containing path to gcode file from which column layers will be taken\n\t- recombinant_gcode_path: string containing path to which recombinant gcode file will be written\n\t- base_slice_thickness: slice thickness (layer height) setting used in base gcode file\n\t- col_slice_thickness: slice thickness (layer height) setting used in column gcode file\n\t- base_thickness: nominal value of total base thickness. Must be an integral multiple of both base_slice_thickness and col_slice_thickness so that beginning of col layers line up\n\t- col_temp: hotend temperature used to print column layers, recombinant gcode adjusts temperature after printing base layers and before printing col layers\n\n\tOutputs:\n\t- recombinant_gcode_path: returns path to recombinant gcode file upon successful completion\n\t\"\"\"\n\n\t# Validate base thickness is integral multiple of slice thickness\n\t# if not base_thickness%base_slice_thickness < 0.0000001:\n\t# \traise ValueError('Base slice thickness is not integral multiple of slice thickness.')\n\t# elif not base_thickness%col_slice_thickness < 0.0000001:\n\t# \traise ValueError('Column slice thickness is not integral multiple of slice thickness.')\n\n\t# Determine location in base gcode file at which to insert graft\n\tinsert_after_layer = base_thickness/base_slice_thickness - 1 # add 1 because layers are zero-indexed\n\n\t# Determine location in col gcode file from which to take graft section\n\ttake_from_layer = base_thickness/col_slice_thickness # do not add 1 because inclusive\n\n\t# Open filestreams for input and output gcode files\n\tbase_fs = open(base_gcode_path)\n\tcol_fs = open(col_gcode_path)\n\toutput_fs = open(recombinant_gcode_path,'w')\n\n\t# Pass lines for base layers through to output file\n\tfor base_line in base_fs:\n\t\tif base_line.startswith(';$ layer ' + str(int(insert_after_layer + 1))):\n\t\t\t#print 'finished writing base layers'\n\t\t\tbreak # exit once the last base layer is passes through\n\t\toutput_fs.write(base_line) # pass lines straight through for base layers\n\tbase_fs.close() # close stream for the base gcode\n\n\t# Append lines for column layers on to the end of output file\n\tbase_layers_completed = 0 # toggle variable denoting if all base layers have been passed through\n\tfor col_line in col_fs:\n\t\tif col_line.startswith(';$ layer ' + str(int(take_from_layer))): # flip toggle once first layer reached\n\t\t\tbase_layers_completed = 1\n\t\t\t#print('start writing col layers')\n\t\t\toutput_fs.write('; BEGIN GRAFT\\n') #insert marker of graft start point\n\t\t\toutput_fs.write('G1 Z' + str(base_thickness+col_slice_thickness) + ' F12000.000\\n')\n\t\t\toutput_fs.write('; Begin move/purge/wipe gcode\\n')\n\t\t\toutput_fs.write('M38 Sjam\\n')\n\t\t\toutput_fs.write('; Start move to purge gcode\\n')\n\t\t\toutput_fs.write('G90 ; absolute\\n')\n\t\t\toutput_fs.write('G92 E0 ; reset e\\n')\n\t\t\toutput_fs.write('M107 ; turn part fan off\\n')\n\t\t\toutput_fs.write('G0 X189 F10800 \\n')\n\t\t\toutput_fs.write('G0 Y0\\n')\n\t\t\toutput_fs.write('; End move to purge gcode\\n')\n\t\t\toutput_fs.write('M104 S'+ str(col_temp) + '; set temperature\\n') #set hotend to column temp\n\t\t\toutput_fs.write('M109 T0 R' + str(col_temp) + '; wait for nozzle to heat or cool\\n') #wait for hotend to arrive at column temp\n\t\t\toutput_fs.write('; Start Purge Gcode\\n')\n\t\t\toutput_fs.write('M107\\n')\n\t\t\toutput_fs.write('G91\\n')\n\t\t\toutput_fs.write('G0 E6 F100\\n')\n\t\t\toutput_fs.write('G90\\n')\n\t\t\toutput_fs.write('G92 E0\\n')\n\t\t\toutput_fs.write('G10\\n')\n\t\t\toutput_fs.write('G0 X160 F5000\\n')\n\t\t\toutput_fs.write('G4 P1\\n')\n\t\t\toutput_fs.write('G0 X0 F10800\\n')\n\t\t\toutput_fs.write('G0 Y228\\n')\n\t\t\toutput_fs.write('G92 E0\\n')\n\t\t\toutput_fs.write('G11\\n')\n\t\t\toutput_fs.write('; End Purge Gcode\\n')\n\t\t\toutput_fs.write('M38 Sjam 0 T0; turn on jam detection for tool 0 with 0 millisecond timeout\\n')\n\t\t\toutput_fs.write('; End move/purge/wipe gcode\\n')\n\t\tif base_layers_completed:\n\t\t\toutput_fs.write(col_line)\n\tcol_fs.close()\n\n\toutput_fs.close()\n\n\treturn recombinant_gcode_path","sub_path":"swap_col_gcode.py","file_name":"swap_col_gcode.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424077284","text":"from django.conf.urls import url\nfrom . import views as post_views\n\nurlpatterns = [\n url(r'^$',post_views.post_list,name='post_list'),\n # url(r'^$',post_views.PostListView.as_view(),name='post_list'),\n url(r'^(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/(?P[-\\w]+)/$',\n post_views.post_detail,\n name='post_detail'),\n url(r'^(?P\\d+)/share/$',\n post_views.post_share,\n name='post_share'),\n url(r'^(?P\\d+)/comment/$',post_views.comment_reply,name='comment_reply'),\n url(r'tag/(?P[-\\w]+)/$',post_views.post_list,name='post_list_by_tag'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"644411335","text":"\"\"\"\n****************************************************************************************************\n:copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted\nprovided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions\nand the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions\nand the following disclaimer in the documentation and/or other materials provided with the\ndistribution.\n\nNeither the name of the copyright holder nor the names of its contributors may be used to endorse\nor promote products derived from this software without specific prior written permission.\n\nRedistribution of this software, without modification, must refer to the software by the same\ndesignation. Redistribution of a modified version of this software (i) may not refer to the\nmodified version by the same designation, or by any confusingly similar designation, and\n(ii) must refer to the underlying software originally provided by Alliance as “URBANopt”. Except\nto comply with the foregoing, the term “URBANopt”, or any confusingly similar designation may\nnot be used to refer to any modified version of this software or any modified version of the\nunderlying software originally provided by Alliance without the prior written consent of Alliance.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\nIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n****************************************************************************************************\n\"\"\"\n\nfrom pathlib import Path\n\nimport click\nfrom geojson_modelica_translator.geojson_modelica_translator import (\n GeoJsonModelicaTranslator\n)\nfrom geojson_modelica_translator.model_connectors.couplings import (\n Coupling,\n CouplingGraph\n)\nfrom geojson_modelica_translator.model_connectors.districts import District\nfrom geojson_modelica_translator.model_connectors.energy_transfer_systems import (\n CoolingIndirect,\n HeatingIndirect\n)\nfrom geojson_modelica_translator.model_connectors.load_connectors import (\n TimeSeries\n)\nfrom geojson_modelica_translator.model_connectors.networks import Network2Pipe\nfrom geojson_modelica_translator.model_connectors.plants import (\n CoolingPlant,\n HeatingPlant\n)\nfrom geojson_modelica_translator.modelica.modelica_runner import ModelicaRunner\nfrom geojson_modelica_translator.system_parameters.system_parameters import (\n SystemParameters\n)\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n \"\"\"URBANopt District Energy Systems\"\"\"\n pass\n\n\n@cli.command(short_help=\"Create sys-param file\")\n@click.argument(\n 'sys_param_filename',\n type=click.Path(file_okay=True, dir_okay=False),\n)\n@click.argument(\n \"scenario_file\",\n type=click.Path(exists=True, file_okay=True, dir_okay=False),\n)\n@click.argument(\n \"feature_file\",\n type=click.Path(exists=True, file_okay=True, dir_okay=False),\n)\n@click.argument(\n \"model_type\",\n default='time_series',\n)\n@click.option(\n '-o',\n '--overwrite',\n is_flag=True,\n help=\"Delete and replace any existing file of the same name & location\",\n default=False\n)\ndef build_sys_param(model_type, sys_param_filename, scenario_file, feature_file, overwrite):\n \"\"\"\n Create system parameters file using uo_sdk output\n\n SYS_PARAM_FILENAME: Path/name to sys-param file be created. Be sure to include the \".json\" suffix.\n\n SCENARIO_FILE: Path to sdk scenario folder with OpenStudio results.\n\n FEATURE_FILE: Path to sdk json feature file with data about the buildings.\n\n \\b\n MODEL_TYPE: selection for which kind of simulation this sys-param file will support.\n Valid choices for MODEL_TYPE: \"time_series\"\n\n \\f\n :param model_type: string, selection of which model type to use in the GMT\n :param sys_param_filename: Path, location & name of json output file to save\n :param scenario_file: Path, location of SDK scenario_file\n :param feature_file: Path, location of SDK feature_file\n :param overwrite: Boolean, flag to overwrite an existing file of the same name/location\n \"\"\"\n\n # Use scenario_file to be consistent with sdk\n scenario_name = Path(scenario_file).stem\n scenario_dir = Path(scenario_file).parent / 'run' / scenario_name\n\n SystemParameters.csv_to_sys_param(\n model_type=model_type,\n sys_param_filename=Path(sys_param_filename),\n scenario_dir=Path(scenario_dir),\n feature_file=Path(feature_file),\n overwrite=overwrite\n )\n\n if Path(sys_param_filename).exists():\n print(f\"\\nSystem parameters file {sys_param_filename} successfully created.\")\n else:\n raise Exception(f\"{sys_param_filename} failed. Please check your inputs and try again.\")\n\n\n@cli.command(short_help=\"Create Modelica model\")\n@click.argument(\n \"sys_param_file\",\n type=click.Path(exists=True, file_okay=True, dir_okay=False),\n)\n@click.argument(\n \"geojson_feature_file\",\n type=click.Path(exists=True, file_okay=True, dir_okay=False),\n)\n@click.argument(\n \"project_name\",\n default=\"model_from_sdk\",\n type=click.Path(exists=False, file_okay=False, dir_okay=True),\n)\n@click.argument(\n \"model_type\",\n default='time_series',\n)\ndef create_model(model_type, sys_param_file, geojson_feature_file, project_name):\n \"\"\"Build Modelica model from user data\n\n SYS_PARAM_FILE: Path/name to sys-param file, possibly created with this CLI.\n\n GEOJSON_FEATURE_FILE: Path to sdk json feature file with data about the buildings.\n\n PROJECT_NAME: Path for Modelica project directory created with this command\n\n \\b\n MODEL_TYPE: selection for which kind of simulation this model will support.\n Valid choices for MODEL_TYPE: \"time_series\"\n Default: \"time_series\"\n\n \\f\n :param model_type: String, type of model to create\n :param sys_param_file: Path, location and name of file created with this cli\n :param geojson_feature_file: Path, location and name of sdk feature_file\n \"\"\"\n\n gj = GeoJsonModelicaTranslator.from_geojson(geojson_feature_file)\n sys_params = SystemParameters(sys_param_file)\n modelica_project_name = Path(project_name).stem\n project_run_dir = Path(project_name).parent\n\n # create cooling network and plant\n # TODO: Enable selecting different plant models in sys-param file, kinda like this concept\n # if sys_params.get_param(\"$.district_system.default\"):\n # cooling_plant = CoolingPlant(sys_params)\n # elif sys_params.get_param(\"$.district_system.osu\"):\n # cooling_plant = CoolingPlantOSU(sys_params)\n # else:\n # raise SystemExit(f\"Cooling plant not defined\")\n cooling_network = Network2Pipe(sys_params)\n cooling_plant = CoolingPlant(sys_params)\n\n # create heating network and plant\n heating_network = Network2Pipe(sys_params)\n heating_plant = HeatingPlant(sys_params)\n\n # create our load/ets/stubs\n # store all couplings to construct the District system\n all_couplings = [\n Coupling(cooling_network, cooling_plant),\n Coupling(heating_network, heating_plant),\n ]\n\n # keep track of separate loads and etses\n loads = []\n heat_etses = []\n cool_etses = []\n # Simalar to load_base.py, only check buildings that are in the sys-param file\n for building in sys_params.get_default('$.buildings.custom[*].geojson_id', []):\n for geojson_load in gj.json_loads:\n # Read load & ets data from user-supplied files, build objects from them\n if geojson_load.feature.properties[\"id\"] == building:\n if model_type == \"time_series\":\n time_series_load = TimeSeries(sys_params, geojson_load)\n loads.append(time_series_load)\n else:\n raise Exception(f\"Model type: '{model_type}' is not supported at this time. \\\n'time_series' is the only valid model_type.\")\n geojson_load_id = geojson_load.feature.properties[\"id\"]\n\n cooling_indirect = CoolingIndirect(sys_params, geojson_load_id)\n cool_etses.append(cooling_indirect)\n all_couplings.append(Coupling(time_series_load, cooling_indirect))\n all_couplings.append(Coupling(cooling_indirect, cooling_network))\n\n heating_indirect = HeatingIndirect(sys_params, geojson_load_id)\n heat_etses.append(heating_indirect)\n all_couplings.append(Coupling(time_series_load, heating_indirect))\n all_couplings.append(Coupling(heating_indirect, heating_network))\n\n # create the couplings and graph\n graph = CouplingGraph(all_couplings)\n\n district = District(\n root_dir=project_run_dir,\n project_name=modelica_project_name,\n system_parameters=sys_params,\n coupling_graph=graph\n )\n district.to_modelica()\n\n if (Path(project_name) / 'Districts' / 'DistrictEnergySystem.mo').exists():\n print(f\"\\nModelica model {modelica_project_name} successfully created in {project_run_dir}.\")\n else:\n raise Exception(f\"{modelica_project_name} failed. Please check your inputs and try again.\")\n\n\n@cli.command(short_help=\"Run Modelica model\")\n@click.argument(\n \"modelica_project\",\n default=\"./model_from_sdk\",\n required=True,\n type=click.Path(exists=True, file_okay=False, dir_okay=True),\n)\ndef run_model(modelica_project):\n \"\"\"\n \\b\n Run the Modelica project in a docker-based environment.\n Results are saved at the same level as the project path that is passed.\n The model that runs is hard coded to be the Districts/DistrictEnergySystem.mo within the package.\n\n \\b\n MODELICA_PROJECT: Path to the Modelica project, possibly created by this cli\n default = ./model_from_sdk\n\n \\f\n :param modelica_project: Path, name & location of modelica project, possibly created with this cli\n \"\"\"\n run_path = Path(modelica_project).resolve()\n project_name = run_path.stem\n file_to_run = run_path / 'Districts' / 'DistrictEnergySystem.mo'\n\n # setup modelica runner\n mr = ModelicaRunner()\n mr.run_in_docker(file_to_run, run_path=run_path.parent, project_name=project_name)\n\n if (run_path.parent / f'{project_name}_results' / f'{project_name}_Districts_DistrictEnergySystem_result.mat').exists():\n print(f\"\\nModelica model {project_name} ran successfully\")\n else:\n raise Exception(f\"{project_name} failed. Please check your inputs and try again.\")\n","sub_path":"management/uo_des.py","file_name":"uo_des.py","file_ext":"py","file_size_in_byte":11377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"480944637","text":"#!/usr/bin/python3\r\n#\r\n# Copyright (c) 2021 Mark McCans\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\nimport logging, time, json, sys, os, argparse, re\r\nimport paho.mqtt.publish as publish\r\nfrom paho.mqtt import MQTTException\r\nfrom airthings import AirthingsWaveDetect\r\n\r\n_LOGGER = logging.getLogger(\"airthings-mqtt-ha\")\r\n\r\nCONFIG = {} # Variable to store configuration\r\nDEVICES = {} # Variable to store devices\r\n\r\n# Sensor detail deafults (for MQTT discovery)\r\nSENSORS = {\r\n \"radon_1day_avg\": {\"name\": \"Radon (1 day avg.)\", \"device_class\": None, \"unit_of_measurement\": \"Bq/m3\", \"icon\": \"mdi:radioactive\"},\r\n \"radon_longterm_avg\": {\"name\": \"Radon (longterm avg.)\", \"device_class\": None, \"unit_of_measurement\": \"Bq/m3\", \"icon\": \"mdi:radioactive\"},\r\n \"co2\": {\"name\": \"CO2\", \"device_class\": None, \"unit_of_measurement\": \"ppm\", \"icon\": \"mdi:molecule-co2\"},\r\n \"voc\": {\"name\": \"VOC\", \"device_class\": None, \"unit_of_measurement\": \"ppb\", \"icon\": \"mdi:cloud\"},\r\n \"temperature\": {\"name\": \"Temperature\", \"device_class\": \"temperature\", \"unit_of_measurement\": \"°C\", \"icon\": None},\r\n \"humidity\": {\"name\": \"Humidity\", \"device_class\": \"humidity\", \"unit_of_measurement\": \"%\", \"icon\": None},\r\n \"rel_atm_pressure\": {\"name\": \"Pressure\", \"device_class\": \"pressure\", \"unit_of_measurement\": \"mbar\", \"icon\": None}\r\n}\r\n\r\nclass ATSensors:\r\n\r\n sensors_list = []\r\n\r\n def __init__(self, scan_interval, devices=None):\r\n _LOGGER.info(\"Setting up Airthings sensors...\")\r\n self.airthingsdetect = AirthingsWaveDetect(scan_interval, None)\r\n\r\n # Note: Doing this so multiple mac addresses can be sent in instead of just one.\r\n if devices is not None and devices != {}:\r\n self.airthingsdetect.airthing_devices = list(devices)\r\n else:\r\n _LOGGER.info(\"No devices provided, so searching for Airthings sensors...\")\r\n self.find_devices()\r\n \r\n # Get info about the devices\r\n if not self.get_device_info():\r\n # Exit if setup fails\r\n _LOGGER.error(\"\\033[31mFailed to set up Airthings sensors. If the watchdog option is enabled, this addon will restart and try again.\\033[0m\")\r\n sys.exit(1)\r\n\r\n _LOGGER.info(\"Done Airthings setup.\")\r\n\r\n def find_devices(self):\r\n try:\r\n _LOGGER.info(\"Starting search for Airthings sensors...\")\r\n num_devices_found = self.airthingsdetect.find_devices()\r\n _LOGGER.info(\"Found {} airthings device(s).\".format(num_devices_found))\r\n if num_devices_found != 0:\r\n # Display suggested config file entry\r\n print(\"\")\r\n print(\"\\033[36m---------------------------------\")\r\n print(\"Suggested configuration is below:\")\r\n print(\" \")\r\n print(\"\\033[32mdevices:\")\r\n for d in self.airthingsdetect.airthing_devices:\r\n print(\" - mac: \"+d)\r\n print(\" name: Insert Device Name\")\r\n print(\"refresh_interval: 150\")\r\n print(\"retry_count: 10\")\r\n print(\"retry_wait: 3\")\r\n print(\"log_level: INFO\")\r\n print(\"mqtt_discovery: 'true'\")\r\n print(\" \")\r\n print(\"\\033[96m---------------------------------\\033[0m\")\r\n sys.exit(0)\r\n\r\n # # Put found devices into DEVICES variable\r\n # for d in self.airthingsdetect.airthing_devices:\r\n # DEVICES[d] = {}\r\n else:\r\n # Exit if no devices found\r\n _LOGGER.warning(\"\\033[31mNo airthings devices found. If the watchdog option is enabled, this addon will restart and try again.\\033[0m\")\r\n sys.exit(1)\r\n except SystemExit as e:\r\n sys.exit(e)\r\n except:\r\n _LOGGER.exception(\"\\033[31mFailed while searching for devices. Is a bluetooth adapter available? If the watchdog option is enabled, this addon will restart and try again.\\033[0m\")\r\n sys.exit(1)\r\n\r\n def get_device_info(self):\r\n _LOGGER.debug(\"Getting info about device(s)...\")\r\n for attempt in range(CONFIG[\"retry_count\"]):\r\n try:\r\n devices_info = self.airthingsdetect.get_info()\r\n except:\r\n _LOGGER.warning(\"Unexpected exception while getting device information on attempt {}. Retrying in {} seconds.\".format(attempt+1, CONFIG[\"retry_wait\"]))\r\n time.sleep(CONFIG[\"retry_wait\"])\r\n else:\r\n # Success!\r\n break\r\n else:\r\n # We failed all attempts\r\n _LOGGER.exception(\"Failed to get info from devices after {} attempts.\".format(CONFIG[\"retry_count\"]))\r\n return False\r\n\r\n # Collect device details\r\n for mac, dev in devices_info.items():\r\n _LOGGER.info(\"{}: {}\".format(mac, dev))\r\n DEVICES[mac][\"manufacturer\"] = dev.manufacturer\r\n DEVICES[mac][\"serial_nr\"] = dev.serial_nr\r\n DEVICES[mac][\"model_nr\"] = dev.model_nr\r\n DEVICES[mac][\"device_name\"] = dev.device_name\r\n\r\n _LOGGER.debug(\"Getting sensors...\")\r\n for attempt in range(CONFIG[\"retry_count\"]):\r\n try:\r\n devices_sensors = self.airthingsdetect.get_sensors()\r\n except:\r\n _LOGGER.warning(\"Unexpected exception while getting sensors information on attempt {}. Retrying in {} seconds.\".format(attempt+1, CONFIG[\"retry_wait\"]))\r\n time.sleep(CONFIG[\"retry_wait\"])\r\n else:\r\n # Success!\r\n break\r\n else:\r\n # We failed all attempts\r\n _LOGGER.exception(\"Failed to get info from sensors after {} attempts.\".format(CONFIG[\"retry_count\"]))\r\n return False\r\n\r\n # Collect sensor details\r\n for mac, sensors in devices_sensors.items():\r\n for sensor in sensors:\r\n self.sensors_list.append([mac, sensor.uuid, sensor.handle])\r\n _LOGGER.debug(\"{}: Found sensor UUID: {} Handle: {}\".format(mac, sensor.uuid, sensor.handle))\r\n \r\n return True\r\n \r\n def get_sensor_data(self):\r\n _LOGGER.debug(\"Getting sensor data...\")\r\n for attempt in range(CONFIG[\"retry_count\"]):\r\n try:\r\n sensordata = self.airthingsdetect.get_sensor_data()\r\n return sensordata\r\n except:\r\n _LOGGER.warning(\"Unexpected exception while getting sensor data on attempt {}. Retrying in {} seconds.\".format(attempt+1, CONFIG[\"retry_wait\"]))\r\n time.sleep(CONFIG[\"retry_wait\"])\r\n else:\r\n # Success!\r\n break\r\n else:\r\n # We failed all attempts\r\n _LOGGER.exception(\"Failed to get sensor data after {} attempts.\".format(CONFIG[\"retry_count\"]))\r\n return False\r\n \r\n return True\r\n\r\ndef mqtt_publish(msgs):\r\n # Publish the sensor data to mqtt broker\r\n try:\r\n _LOGGER.info(\"Sending messages to mqtt broker...\")\r\n if \"username\" in CONFIG[\"mqtt\"] and CONFIG[\"mqtt\"][\"username\"] != \"\" and \"password\" in CONFIG[\"mqtt\"] and CONFIG[\"mqtt\"][\"password\"] != \"\":\r\n auth = {'username':CONFIG[\"mqtt\"][\"username\"], 'password':CONFIG[\"mqtt\"][\"password\"]}\r\n _LOGGER.info(\"With authentification.\")\r\n else:\r\n auth = None\r\n _LOGGER.info(\"No authentification.\")\r\n publish.multiple(msgs, hostname=CONFIG[\"mqtt\"][\"host\"], port=CONFIG[\"mqtt\"][\"port\"], client_id=\"airthings-mqtt\", auth=auth)\r\n _LOGGER.info(\"Done sending messages to mqtt broker.\")\r\n except MQTTException as e:\r\n _LOGGER.error(\"Failed while sending messages to mqtt broker: {}\".format(e))\r\n except:\r\n _LOGGER.exception(\"Unexpected exception while sending messages to mqtt broker.\")\r\n\r\nif __name__ == \"__main__\":\r\n logging.basicConfig()\r\n _LOGGER.setLevel(logging.INFO)\r\n\r\n # Parse command line arguments\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--host', type=str, required=True, help='mqtt server host name or ip address')\r\n parser.add_argument('--port', type=int, default=1883, help='mqtt server host port')\r\n parser.add_argument('--username', type=str, required=True, help='mqtt server username')\r\n parser.add_argument('--password', type=str, required=True, help='mqtt server password')\r\n parser.add_argument('--config', type=str, required=True, help='location of options.json file')\r\n args = parser.parse_args()\r\n \r\n # Load configuration from file\r\n try:\r\n with open(vars(args)['config']) as f:\r\n CONFIG = json.load(f)\r\n except:\r\n # Exit if there is an error reading config file\r\n _LOGGER.exception(\"\\033[31mError reading options.json file. If the watchdog option is enabled, this addon will restart and try again.\\033[0m\")\r\n sys.exit(1)\r\n\r\n # Fill in the remainder of the config values\r\n CONFIG[\"mqtt\"] = {}\r\n CONFIG[\"mqtt\"][\"host\"] = vars(args)['host']\r\n CONFIG[\"mqtt\"][\"port\"] = vars(args)['port']\r\n CONFIG[\"mqtt\"][\"username\"] = vars(args)['username']\r\n CONFIG[\"mqtt\"][\"password\"] = vars(args)['password'] \r\n\r\n # Set logging level (defaults to INFO)\r\n if CONFIG[\"log_level\"] in [\"CRITICAL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\"]:\r\n _LOGGER.setLevel(CONFIG[\"log_level\"])\r\n\r\n # Pull out devices configured and insert them if a valid mac address has been provided\r\n if \"devices\" in CONFIG:\r\n for d in CONFIG[\"devices\"]:\r\n if \"mac\" in d:\r\n if re.match(\"[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\\\1[0-9a-f]{2}){4}$\", d[\"mac\"].lower()): \r\n # Ensure consistent formatting for the mac address\r\n d[\"mac\"] = d[\"mac\"].lower()\r\n DEVICES[d[\"mac\"].lower()] = {}\r\n else:\r\n _LOGGER.warning(\"Invalid mac address provided: {}\".format(d[\"mac\"]))\r\n\r\n a = ATSensors(180, DEVICES)\r\n\r\n # Update sensor values in accordance with the REFRESH_INTERVAL set.\r\n first = True\r\n while True:\r\n # Get sensor data\r\n sensors = a.get_sensor_data()\r\n # Only connect to mqtt broker if we have data \r\n if sensors is not None and sensors != {}:\r\n # Variable to store mqtt messages\r\n msgs = []\r\n \r\n # Send HA mqtt discovery messages to broker on first run\r\n if first and CONFIG[\"mqtt_discovery\"] != False:\r\n _LOGGER.info(\"Sending HA mqtt discovery configuration messages...\")\r\n for mac, data in sensors.items():\r\n # Consistent mac formatting\r\n mac = mac.lower()\r\n\r\n # Create device details for this device\r\n device = {}\r\n device[\"connections\"] = [[\"mac\", mac]]\r\n if \"serial_nr\" in DEVICES[mac]: device[\"identifiers\"] = [DEVICES[mac][\"serial_nr\"]]\r\n if \"manufacturer\" in DEVICES[mac]: device[\"manufacturer\"] = DEVICES[mac][\"manufacturer\"]\r\n if \"device_name\" in DEVICES[mac]: device[\"name\"] = DEVICES[mac][\"device_name\"]\r\n if \"model_nr\" in DEVICES[mac]: device[\"model\"] = DEVICES[mac][\"model_nr\"]\r\n\r\n for name, val in data.items():\r\n if name != \"date_time\": \r\n try:\r\n config = {}\r\n s = next((item for item in CONFIG[\"devices\"] if item[\"mac\"] == mac), None)\r\n if s != None:\r\n if name in SENSORS:\r\n config[\"name\"] = s[\"name\"]+\" \"+SENSORS[name][\"name\"]\r\n if SENSORS[name][\"device_class\"] != None: config[\"device_class\"] = SENSORS[name][\"device_class\"]\r\n if SENSORS[name][\"icon\"] != None: config[\"icon\"] = SENSORS[name][\"icon\"]\r\n config[\"unit_of_measurement\"] = SENSORS[name][\"unit_of_measurement\"]\r\n config[\"uniq_id\"] = mac+\"_\"+name\r\n config[\"state_topic\"] = \"airthings/\"+mac+\"/\"+name\r\n config[\"device\"] = device\r\n\r\n msgs.append({'topic': \"homeassistant/sensor/airthings_\"+mac.replace(\":\",\"\")+\"/\"+name+\"/config\", 'payload': json.dumps(config), 'retain': True})\r\n except:\r\n _LOGGER.exception(\"Failed while creating HA mqtt discovery messages.\")\r\n \r\n # Publish the HA mqtt discovery data to mqtt broker\r\n mqtt_publish(msgs)\r\n _LOGGER.info(\"Done sending HA mqtt discovery configuration messages.\")\r\n msgs = []\r\n time.sleep(5)\r\n first = False\r\n \r\n # Collect all of the sensor data\r\n _LOGGER.info(\"Collecting sensor value messages...\")\r\n for mac, data in sensors.items():\r\n for name, val in data.items():\r\n if name != \"date_time\":\r\n # Consistent mac formatting\r\n mac = mac.lower()\r\n if isinstance(val, str) == False:\r\n if name == \"temperature\":\r\n val = round(val,1)\r\n else:\r\n val = round(val)\r\n _LOGGER.info(\"{} = {}\".format(\"airthings/\"+mac+\"/\"+name, val))\r\n msgs.append({'topic': \"airthings/\"+mac+\"/\"+name, 'payload': val})\r\n \r\n # Publish the sensor data to mqtt broker\r\n mqtt_publish(msgs)\r\n else:\r\n _LOGGER.error(\"\\033[31mNo sensor values collected. Please check your configuration and make sure your bluetooth adapter is available. If the watchdog option is enabled, this addon will restart and try again.\\033[0m\")\r\n sys.exit(1)\r\n\r\n # Wait for next refresh cycle\r\n _LOGGER.info(\"Waiting {} seconds.\".format(CONFIG[\"refresh_interval\"]))\r\n time.sleep(CONFIG[\"refresh_interval\"])\r\n","sub_path":"src/airthings-mqtt.ha.py","file_name":"airthings-mqtt.ha.py","file_ext":"py","file_size_in_byte":15471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"417244267","text":"import numpy as np\nfrom .training.nmf import nmf\nfrom .data_handler import user_creator_matrix\n\nclass user_creator():\n\n\tdef __init__(self):\n\n\t\t\"\"\"\n\t\tuser_card_matrix is a torch tensor which contains the user_card preferences having shape - [number of cards, number of users]\n\t\tstats_user_card is a torch tensor which contains the cards seen by the user having shape - [number of cards, number of users]\n\t\t\"\"\"\n\n\t\t\"\"\"\n\t\tAll variables/functions starting with temp would be removed while actual program\n\t\t\"\"\"\n\t\tself.data_path = [\n\t\t\t\t\t\t\t'', \n\t\t\t\t\t\t\t['/home/mayank/Desktop/Balloon/Datasets/ml-latest-small/movies.csv', '/home/mayank/Desktop/Balloon/Datasets/ml-latest-small/ratings.csv'],\n\t\t\t\t\t\t\t['/home/mayank/Desktop/Balloon/Datasets/ml-latest-small/movies.csv', '/home/mayank/Desktop/Balloon/Datasets/ml-latest-small/ratings.csv'],\n\t\t\t\t\t\t\t['/home/mayank/Desktop/Balloon/Datasets/ml-latest-small/movies.csv']\n\t\t\t\t\t\t]\n\n\t\tself.data = user_card_matrix.get(self.data_path)\n\n\t\tself.rank = 20\n\n\t\tself.algorithm = nmf(rank=self.rank, shape = self.data.user_card_matrix.size())\n\n\t\tself.temp_num_card_retrieve = 20\n\t\t\n\tdef train(self, path):\n\n\t\tself.algorithm.training(iterations = 1e5, x = self.data.user_card_matrix, w = self.data.stats_user_card)\n\n\t\tself.algorithm.save(path)\n\n\tdef return_all_val_user(self, user_id):\n\n\t\treturn self.algorithm.reconstructed[:, self.data.user_id[user_id]].cpu().data.squeeze().numpy(), self.data.stats_user_card[:, self.data.user_id[user_id]].cpu().data.squeeze().numpy()\n\n\tdef temp_retrieve(self, user_id):\n\n\t\tprob = self.algorithm.reconstructed[:, self.data.user_id[user_id]].cpu().data.squeeze().numpy()*(1 - self.data.stats_user_card[:, self.data.user_id[user_id]].cpu().data.squeeze().numpy())\n\n\t\tprob = prob/np.sum(prob)\n\n\t\tid_predicted = np.random.choice(self.data.user_card_matrix.size()[0], self.temp_num_card_retrieve, p = prob, replace=False)\n\n\t\tname_predicted = ''\n\n\t\tname_predicted += self.data.get_user_movie_info(user_id)+'\\n\\n The movies recommended to him are : '\n\n\t\tfor i in id_predicted:\n\t\t\tname_predicted += self.data.card_id_to_name[self.data.index_to_movie_id[i]]+'\\n'\n\n\t\treturn name_predicted","sub_path":"user_creator/user_creator.py","file_name":"user_creator.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179399212","text":"\"\"\"\nArya has a string, S, of uppercase English letters. She writes down the string S on a paper K times.\nShe wants to calculate the occurence of a specific letter in the first N characters of the final string.\n\nInput:\n\nFirst line of input contains a single integer T denoting the number of test cases.\nThe first line of each test case contains a string S.\nThe second line contains 2 space-separated integers K and N, and an uppercase English letter C whose occurence needs to be counted.\n\nOutput:\n\nFor each test case, print the required answer in a new line.\n\n\nConstraints:\n\n1 <= T <= 150\n1 <= |S| <= 500\n1 <= K <= 10^5\n1 <= N <= |S|*K\n\n\nExample:\n\nInput :\n2\nABA\n3 7 B\nBHD\n4 6 E\nOutput :\n2\n0\n\nExplaination :\nCase 1 : Final string - ABAABAABA\nCase 2 : Final string - BHDBHDBHDBHD\n\nExample 2 :\nInput :\n1\nMMM\n2 4 M\nOutput :\n4\n\nExplaination :\nCase 1 : Final string - MMMMMM\n\"\"\"\n\n\ndef aryas_long_string(st, k, n, char):\n st = st * int(k)\n return st.count(char, 0, int(n))\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n st = input()\n k, n, char = [i for i in input().split()][0:3]\n print(aryas_long_string(st, k, n, char))\n","sub_path":"practice/Basic/aryass_long_string.py","file_name":"aryass_long_string.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"555023680","text":"# -*- coding: utf-8 -*\nfrom mininet.net import Mininet\nfrom mininet.node import Controller, RemoteController, OVSController\nfrom mininet.node import CPULimitedHost, Host, Node\nfrom mininet.node import OVSKernelSwitch, UserSwitch\nfrom mininet.node import IVSSwitch\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel, info\nfrom mininet.link import TCLink, Intf\nimport networkx as nx\nimport random\nimport os\nimport tarfile\nimport traceback\nimport numpy as np\nimport csv\nimport re\nimport threading\nimport time\nimport matplotlib.pyplot as plt\n# graph_path = 'gbnnet/gbn.txt'\ngraph_path = 'gbnnet/gbn_add_link_57.txt'\ntraffic_file = 'output_data.csv'\nG = nx.Graph()\n\ncat_mat = []\n\npath_set = []\ntraffic_list = []\nall_pairs_shortest_path = []\n\n\nclass DataNet:\n def generate_graphs_dic(self):\n global G\n\n graphs_dic = {}\n G = nx.read_gml(graph_path, destringizer=int)\n graphs_dic[graph_path] = G\n # nx.draw_networkx(G,node_color='green',with_label=1)\n # plt.show()\n return graphs_dic\n\n def create_Cap_Mat(self):\n global cap_mat\n\n cap_mat = np.full(\n (G.number_of_nodes()+1, G.number_of_nodes()+1), fill_value=None)\n for node in range(G.number_of_nodes()):\n for adj in G[node]:\n cap_mat[node, adj] = int(G[node][adj][0]['bandwidth'])\n info(cap_mat)\n # all_pairs_shortest_path = [p for p in nx.all_pairs_shortest_path(G)]\n\n def generate_traffic(self):\n global traffic_list\n for i in range(G.number_of_nodes()):\n for j in range(G.number_of_nodes()):\n if i != j:\n path_set.append(nx.shortest_path(G, i, j))\n\n with open(traffic_file) as csvfile:\n rows = csv.reader(csvfile)\n for row in rows:\n traffic_list.append(row[1])\n # print(path_set)\n # for x,y in zip(path_set,traffic_list):\n # print('path = ',x , 'bws = ', y)\n\n\ndef MyNetwork(net):\n global G\n\n info('*** Adding controller\\n')\n c0 = net.addController(name='c0',\n controller=RemoteController,\n protocol='tcp',\n port=6633, ip='127.0.0.1')\n\n for n in G.nodes():\n net.addSwitch(\"s%s\" % str(n+1))\n if int(n) in list(G.nodes()):\n net.addHost('h%s' % str(n+1), ip='10.0.0.' + str(n+1))\n net.addLink('s%s' % str(n+1), 'h%s' % str(n+1))\n existed_edge = []\n for (n1, n2) in G.edges():\n if (n1, n2) not in existed_edge:\n info((n1, n2))\n net.addLink('s%s' % str(n1+1), 's%s' % str(n2+1),\n cls=TCLink, bw=cap_mat[n1][n2]/10000*8)\n existed_edge.append((n1, n2))\n existed_edge.append((n2, n1))\n\n info('*** Starting network\\n')\n net.build()\n\n info('*** Starting controllers\\n')\n for controller in net.controllers:\n controller.start()\n\n info('*** Starting switches\\n')\n for n in range(0, G.number_of_nodes()):\n net.get('s%s' % str(n+1)).start([c0])\n\n info('*** Post configure switches and hosts\\n')\n while True:\n try:\n user_input = raw_input(\"GEN/CLI/QUIT : \")\n except EOFError as error:\n user_input = \"QUIT\"\n\n if user_input.upper() == \"GEN\":\n generate_flow(net, 50, G)\n\n elif user_input.upper() == \"CLI\":\n info(\"Running CLI...\\n\")\n CLI(net)\n elif user_input.upper() == \"QUIT\":\n info(\"Terminating...\\n\")\n net.stop()\n break\n else:\n print(\"Command not found\")\n\n\ndef swap(list, a, b):\n t = list[a]\n list[a] = list[b]\n list[b] = t\n return list\n\n\ndef generate_flow(net, n_files, G):\n hosts = net.hosts\n all_pairs_shortest_path = []\n flow_count = 0\n # Generate All Path\n for i in range(17):\n for j in range(17):\n if i != j:\n all_pairs_shortest_path.append(nx.shortest_path(G, i, j))\n\n\n while(n_files):\n if n_files == 200:\n break\n traffic_dir = 'traffic_dir/Result_Test_gbn/addlink57/'\n if not os.path.exists(traffic_dir + str(n_files)):\n os.makedirs(traffic_dir + str(n_files))\n traffic_dir += str(n_files)\n for i in range(272, 0, -1):\n time.sleep(0.001)\n # Random Select Path\n idx = random.randint(0, i-1)\n path = all_pairs_shortest_path[idx]\n src_h = \"h\" + str(path[0]+1)\n dst_h = \"h\" + str(path[1]+1)\n\n src = net.get(src_h)\n dst = net.get(dst_h)\n\n # create cmd ping\n server_cmd = \"START_TIME=$(date +%s%3N) && \" # get begin time\n pkt_size = 1000\n server_cmd += \"ping -c 350 -s \" + \\\n str(pkt_size) + \" -i 0.1 \" + dst.IP()\n server_cmd += \" > \" + traffic_dir + \"/\" + str(i) + \".log && \"\n server_cmd += \"echo path = \" + \\\n str(path) + \" >> \" + traffic_dir + \"/\" + str(i) + \".log && \"\n server_cmd += \"ELAPSED_TIME=$(($(date +%s%3N)-$START_TIME)) && \"\n server_cmd += \"echo duration=$ELAPSED_TIME >> \" + \\\n traffic_dir + \"/\" + str(i) + \".log &\"\n # print(server_cmd)\n # send the cmd\n src.cmdPrint(server_cmd)\n # src.popen(server_cmd,shell=True)\n all_pairs_shortest_path = swap(all_pairs_shortest_path, idx, i-1)\n time.sleep(1)\n n_files -= 1\n\n\nif __name__ == \"__main__\":\n setLogLevel('info')\n datanet = DataNet()\n datanet.generate_graphs_dic()\n datanet.create_Cap_Mat()\n\n\n net = Mininet(topo=None,\n build=False,\n ipBase='10.0.0.0/8')\n\n MyNetwork(net)\n","sub_path":"Topology and data_generation/mininet/gbnnet_topo.py","file_name":"gbnnet_topo.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52200850","text":"import numpy as np\nfrom numba import jit\n\n############################\n#CUSUM One-Way (Forward and Backwards):Count trips and return trip_changepoint_numtrips_direction matrix\ndef count_trips_and_return_matrix_oneway(trip_index_forward, trip_index_backwards, changepoint_index_forward, changepoint_index_backwards, num_photons_or_bins):\n# Forwards\n direction = 1\n trip_index_condensed_forward, changepoint_index_condensed_forward, number_of_trips_forward = find_number_of_trips_each_changepoint(trip_index_forward, changepoint_index_forward)\n matrix_forward = make_index_matrix_oneway(trip_index_condensed_forward, changepoint_index_condensed_forward, number_of_trips_forward, direction, num_photons_or_bins)\n\n# Backwards\n direction = -1\n trip_index_condensed_backwards, changepoint_index_condensed_backwards, number_of_trips_backwards = find_number_of_trips_each_changepoint(trip_index_backwards, changepoint_index_backwards)\n matrix_backwards = make_index_matrix_oneway(trip_index_condensed_backwards, changepoint_index_condensed_backwards, number_of_trips_backwards, direction, num_photons_or_bins)\n\n# Put Forward and Backwards Information Together into Single Matrix\n trip_changepoint_numtrips_direction = np.vstack((matrix_forward, matrix_backwards))\n\n# Sort Matrix by Changepoint (Ascending)\n trip_changepoint_numtrips_direction = sort(trip_changepoint_numtrips_direction)\n\n return trip_changepoint_numtrips_direction\n\n############################\n#CUSUM Two-Way: Count trips and return trip_changepoint_numtrips_direction matrix\ndef count_trips_and_return_matrix_twoway(trip_index, changepoint_index, direction_array):\n trip_changepoint_direction = np.stack((trip_index, changepoint_index, direction_array), axis = -1)\n\n#Increasing\n direction = 1\n trip_changepoint_direction_increasing = trip_changepoint_direction[np.where(trip_changepoint_direction[:, 2] == direction)]\n trip_index_condensed_increasing, changepoint_index_condensed_increasing, number_of_trips_increasing = find_number_of_trips_each_changepoint(trip_changepoint_direction_increasing[:, 0], trip_changepoint_direction_increasing[:, 1])\n matrix_increasing = make_index_matrix_twoway(trip_index_condensed_increasing, changepoint_index_condensed_increasing, number_of_trips_increasing, direction)\n\n#Decreasing\n direction = -1\n trip_changepoint_direction_decreasing = trip_changepoint_direction[np.where(trip_changepoint_direction[:, 2] == direction)]\n trip_index_condensed_decreasing, changepoint_index_condensed_decreasing, number_of_trips_decreasing = find_number_of_trips_each_changepoint(trip_changepoint_direction_decreasing[:, 0], trip_changepoint_direction_decreasing[:, 1])\n matrix_decreasing = make_index_matrix_twoway(trip_index_condensed_decreasing, changepoint_index_condensed_decreasing, number_of_trips_decreasing, direction)\n\n# Put Increasing and Decreasing Information Together into Single Matrix\n trip_changepoint_numtrips_direction = np.vstack((matrix_increasing, matrix_decreasing))\n\n# Sort Matrix by Changepoint (Ascending)\n trip_changepoint_numtrips_direction = sort(trip_changepoint_numtrips_direction)\n\n return trip_changepoint_numtrips_direction\n\n\n############################\n#Used by both one-way and two-way\ndef find_number_of_trips_each_changepoint(trip_index, changepoint_index):\n changepoint_index = changepoint_index[np.nonzero(changepoint_index)]\n trip_index = trip_index[np.nonzero(trip_index)]\n\n changepoint_index_condensed, indices_list, number_of_trips = np.unique(changepoint_index, return_index=True, return_counts=True)\n trip_index_condensed = np.take(trip_index, indices_list)\n\n return trip_index_condensed, changepoint_index_condensed, number_of_trips\n\n@jit(nopython=True)\ndef sort(trip_changepoint_numtrips_direction):\n trip_changepoint_numtrips_direction = trip_changepoint_numtrips_direction[np.argsort(trip_changepoint_numtrips_direction[:, 1])]\n\n return trip_changepoint_numtrips_direction\n\n############################\n#Used only by one-way\ndef make_index_matrix_oneway(trip_index, changepoint_index, number_of_trips, direction, num_photons_or_bins):\n direction_array = direction * np.ones(len(trip_index))\n if direction == 1:\n matrix = np.stack((trip_index, changepoint_index, number_of_trips, direction_array), axis=-1)\n else:\n backwards_flip = (num_photons_or_bins - 1)*np.ones(len(trip_index))\n trip_index = backwards_flip - trip_index\n changepoint_index = backwards_flip - changepoint_index\n matrix = np.stack((trip_index, changepoint_index, number_of_trips, direction_array), axis=-1)\n\n return matrix\n\n############################\n#Used only by two-way\ndef make_index_matrix_twoway(trip_index, changepoint_index, number_of_trips, direction):\n direction_array = direction * np.ones(len(trip_index))\n index_matrix = np.stack((trip_index, changepoint_index, number_of_trips, direction_array), axis = -1)\n\n return index_matrix\n\n","sub_path":"cusum_count_trips_module.py","file_name":"cusum_count_trips_module.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476459340","text":"import json\n\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy\n\n\nclass LedLightChile(Store):\n @classmethod\n def categories(cls):\n return [\n 'Lamp',\n 'LightTube',\n 'LightProjector',\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n category_paths = [\n # Ampolletas LED\n ['hogar/ampolletas', 'Lamp'],\n # Proyectores LED\n ['hogar/proyectores', 'LightProjector'],\n # Tubos LED\n ['hogar/equipos-y-tubos', 'LightTube'],\n ]\n\n discovery_urls = []\n session = session_with_proxy(extra_args)\n\n for category_path, local_category in category_paths:\n if local_category != category:\n continue\n\n category_url = 'http://ledlightchile.cl/categoria-producto/{}' \\\n ''.format(category_path)\n\n soup = BeautifulSoup(session.get(category_url).text, 'html.parser')\n\n product_containers = soup.findAll('div', 'wf-cell')\n\n for container in product_containers:\n subcategory_url = container.find('a')['href']\n discovery_urls.append(subcategory_url)\n\n return discovery_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n soup = BeautifulSoup(session.get(url).text, 'html.parser')\n\n products = []\n\n variations_container = soup.find('form', 'variations_form')\n\n variations = json.loads(variations_container[\n 'data-product_variations'])\n print(variations)\n\n for variation in variations:\n field_names = [\n 'attribute_pa_caracteristicas-tecnicas',\n 'attribute_pa_caracteristicas-tecnicas-2',\n 'attribute_pa_caracteristicas-tecnicas-3',\n None\n ]\n\n field_name = None\n\n for field_name in field_names:\n if field_name in variation['attributes']:\n break\n\n if field_name:\n name = variation['attributes'][field_name].replace(\n '%e2%80%a2', '')\n else:\n name = soup.find('meta', {'property': 'og:title'})['content']\n sku = str(variation['variation_id'])\n\n price = variation['display_price']\n if not price:\n continue\n price = Decimal(price)\n\n if variation['is_purchasable']:\n stock = -1\n else:\n stock = 0\n\n picture_urls = [variation['image']['url']]\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n price,\n price,\n 'CLP',\n sku=sku,\n picture_urls=picture_urls\n )\n\n products.append(p)\n\n return products\n","sub_path":"storescraper/stores/led_light_chile.py","file_name":"led_light_chile.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"428769392","text":"# -*- encoding:utf-8 -*-\nfrom card_models import CardDeckController\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass User(object):\n\n def __init__(self, name, money):\n self.name = name\n self.money = money\n\n def __repr__(self):\n return self.name\n\n\nclass Player(object):\n\n def __init__(self, username, money):\n self.username = username\n self.money = money\n self.host = False\n\n self.game = None\n self.game_pos = None\n self.first_hole = None\n self.second_hole = None\n self.cur_bet = 0\n self.best_hand_value = None\n self.status = 'init' # 'init', 'in game', 'all in', 'out game'\n\n def info(self):\n d = {}\n d['name'] = self.print_name()\n d['money'] = self.money\n d['host'] = self.host\n d['game_pos'] = self.game_pos\n d['first_hole'] = str(self.first_hole)\n d['second_hole'] = str(self.second_hole)\n d['cur_bet'] = self.cur_bet\n d['best_hand_value'] = str(self.best_hand_value)\n d['status'] = self.status\n return d\n\n def print_name(self):\n return \"Player%d-%s\" % (self.game_pos, self.username)\n\n def print_holes(self):\n return \" <%s> <%s> \" % (self.first_hole, self.second_hole)\n\n def update_best_hand_value(self):\n from hand_value import HandValue\n holes = [self.first_hole, self.second_hole]\n community_cards = self.game.community_cards\n self.best_hand_value = HandValue(holes + community_cards)\n\n def clear(self):\n self.first_hole = None\n self.second_hole = None\n self.cur_bet = 0\n self.best_hand_value = None\n self.status = 'in game'\n\n def bet(self, amount):\n amount = int(amount)\n if amount > self.money:\n raise Exception(\"Don't have enough money\")\n self.money -= amount\n self.game.pot += amount\n self.cur_bet += amount\n\n def bet_to(self, amount):\n self.bet(amount - self.cur_bet)\n\n def check(self):\n pass\n\n def call(self):\n self.bet_to(self.game.highest_bet)\n\n def raise_bet(self, amount):\n self.bet(amount)\n self.game.highest_bet = self.cur_bet\n\n def allin(self):\n self.status = 'all in'\n self.bet(self.money)\n\n def fold(self):\n self.status = 'out game'\n\n\nclass Game(object):\n\n def __init__(self):\n self.pot = 0\n self.community_cards = []\n self.highest_bet = 0\n self.players = []\n self.pos_button = 0\n self.pos_small_blind = 1\n self.pos_big_blind = 2\n self.active_player_pos = -1\n self.status = 'init' # 'init', 'new game', 'pre flop', 'flop', 'turn', 'river', 'showdown'\n self.log = ['Welcome to Texas Hold\\'em Poker Game v1.0-alpha']\n self.action_num = 0\n\n self.card_deck_controller = CardDeckController()\n self.card_deck_controller.add_card_deck()\n\n def info(self):\n d = {}\n d['pot'] = self.pot\n d['community_cards'] = map(str, self.community_cards)\n d['highest_bet'] = self.highest_bet\n d['players'] = [x.info() for x in self.players]\n d['pos_button'] = self.pos_button\n d['pos_small_blind'] = self.pos_small_blind\n d['pos_big_blind'] = self.pos_big_blind\n d['active_player_pos'] = self.active_player_pos\n d['status'] = self.status\n d['log'] = self.log\n return d\n\n def add_player(self, player):\n self.players.append(player)\n player.game_pos = len(self.players)\n player.game = self\n\n def print_community_cards(self):\n if len(self.community_cards) == 0:\n return \" \"\n s = \"> <\".join(map(str, self.community_cards))\n return \" <%s> \" % s\n\n def new_game(self):\n self.pot = 0\n self.community_cards = []\n self.card_deck_controller.initialize()\n for player in self.players:\n player.clear()\n\n self.pos_button = (self.pos_button + 1) % len(self.players)\n self.pos_small_blind = (self.pos_small_blind + 1) % len(self.players)\n self.pos_big_blind = (self.pos_big_blind + 1) % len(self.players)\n self.status = 'new game'\n\n def deal(self):\n n = len(self.players)\n\n # round-1\n for i in range(self.pos_button, self.pos_button + n):\n j = i % n\n if self.players[j].first_hole is not None or self.players[j].second_hole is not None:\n raise Exception(\"Didn't clear players' holes\")\n self.players[j].first_hole = self.card_deck_controller.deal()\n\n # round-2\n for i in range(self.pos_button, self.pos_button + n):\n j = i % n\n self.players[j].second_hole = self.card_deck_controller.deal()\n\n def pre_flop(self):\n self.status = 'pre flop'\n\n def flop(self):\n self.community_cards.append(self.card_deck_controller.deal())\n self.community_cards.append(self.card_deck_controller.deal())\n self.community_cards.append(self.card_deck_controller.deal())\n for player in self.players:\n player.update_best_hand_value()\n self.status = 'flop'\n\n def turn(self):\n self.community_cards.append(self.card_deck_controller.deal())\n for player in self.players:\n player.update_best_hand_value()\n self.status = 'turn'\n\n def river(self):\n self.community_cards.append(self.card_deck_controller.deal())\n for player in self.players:\n player.update_best_hand_value()\n self.status = 'river'\n\n def showdown(self):\n alive_players = filter(lambda x: x.status == 'in game' or x.status == 'all in', self.players)\n win_hand_value = max([x.best_hand_value for x in alive_players])\n winners = []\n for player in self.players:\n if player.status == 'in game' or player.status == 'all in':\n if player.best_hand_value == win_hand_value:\n winners.append(player)\n self.status = 'showdown'\n return winners\n\n def checkout(self, winners):\n num_winners = len(winners)\n prize = self.pot / num_winners\n for winner in winners:\n winner.money += prize\n self.pot = 0\n\n return prize\n","sub_path":"src/texas_game.py","file_name":"texas_game.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"299837305","text":"from __future__ import division\n\nimport gc\nimport os\nimport json\nimport copy\n\nimport numpy as np\nimport scipy.integrate as integrate\nfrom scipy.interpolate import interp1d\n\ntry:\n from scipy.special import logsumexp\nexcept ImportError:\n from scipy.misc import logsumexp\nfrom scipy.special import i0e\n\nfrom ..core.likelihood import Likelihood, MarginalizedLikelihoodReconstructionError\nfrom ..core.utils import BilbyJsonEncoder, decode_bilby_json\nfrom ..core.utils import (\n logger, UnsortedInterp2d, create_frequency_series, create_time_series,\n speed_of_light, radius_of_earth)\nfrom ..core.prior import Interped, Prior, Uniform\nfrom .detector import InterferometerList\nfrom .prior import BBHPriorDict, CBCPriorDict\nfrom .source import lal_binary_black_hole\nfrom .utils import noise_weighted_inner_product, build_roq_weights, blockwise_dot_product\nfrom .waveform_generator import WaveformGenerator\nfrom collections import namedtuple\n\n\nclass GravitationalWaveTransient(Likelihood):\n \"\"\" A gravitational-wave transient likelihood object\n\n This is the usual likelihood object to use for transient gravitational\n wave parameter estimation. It computes the log-likelihood in the frequency\n domain assuming a colored Gaussian noise model described by a power\n spectral density. See Thrane & Talbot (2019), arxiv.org/abs/1809.02293.\n\n\n Parameters\n ----------\n interferometers: list, bilby.gw.detector.InterferometerList\n A list of `bilby.detector.Interferometer` instances - contains the\n detector data and power spectral densities\n waveform_generator: `bilby.waveform_generator.WaveformGenerator`\n An object which computes the frequency-domain strain of the signal,\n given some set of parameters\n distance_marginalization: bool, optional\n If true, marginalize over distance in the likelihood.\n This uses a look up table calculated at run time.\n The distance prior is set to be a delta function at the minimum\n distance allowed in the prior being marginalised over.\n time_marginalization: bool, optional\n If true, marginalize over time in the likelihood.\n This uses a FFT to calculate the likelihood over a regularly spaced\n grid.\n In order to cover the whole space the prior is set to be uniform over\n the spacing of the array of times.\n If using time marginalisation and jitter_time is True a \"jitter\"\n parameter is added to the prior which modifies the position of the\n grid of times.\n phase_marginalization: bool, optional\n If true, marginalize over phase in the likelihood.\n This is done analytically using a Bessel function.\n The phase prior is set to be a delta function at phase=0.\n priors: dict, optional\n If given, used in the distance and phase marginalization.\n distance_marginalization_lookup_table: (dict, str), optional\n If a dict, dictionary containing the lookup_table, distance_array,\n (distance) prior_array, and reference_distance used to construct\n the table.\n If a string the name of a file containing these quantities.\n The lookup table is stored after construction in either the\n provided string or a default location:\n '.distance_marginalization_lookup_dmin{}_dmax{}_n{}.npz'\n jitter_time: bool, optional\n Whether to introduce a `time_jitter` parameter. This avoids either\n missing the likelihood peak, or introducing biases in the\n reconstructed time posterior due to an insufficient sampling frequency.\n Default is False, however using this parameter is strongly encouraged.\n\n Returns\n -------\n Likelihood: `bilby.core.likelihood.Likelihood`\n A likelihood object, able to compute the likelihood of the data given\n some model parameters\n\n \"\"\"\n\n _CalculatedSNRs = namedtuple('CalculatedSNRs',\n ['d_inner_h',\n 'optimal_snr_squared',\n 'complex_matched_filter_snr',\n 'd_inner_h_squared_tc_array'])\n\n def __init__(self, interferometers, waveform_generator,\n time_marginalization=False, distance_marginalization=False,\n phase_marginalization=False, priors=None,\n distance_marginalization_lookup_table=None,\n jitter_time=True):\n\n self.waveform_generator = waveform_generator\n super(GravitationalWaveTransient, self).__init__(dict())\n self.interferometers = InterferometerList(interferometers)\n self.time_marginalization = time_marginalization\n self.distance_marginalization = distance_marginalization\n self.phase_marginalization = phase_marginalization\n self.priors = priors\n self._check_set_duration_and_sampling_frequency_of_waveform_generator()\n self.jitter_time = jitter_time\n\n if self.time_marginalization:\n self._check_prior_is_set(key='geocent_time')\n self._setup_time_marginalization()\n priors['geocent_time'] = float(self.interferometers.start_time)\n if self.jitter_time:\n priors['time_jitter'] = Uniform(\n minimum=- self._delta_tc / 2, maximum=self._delta_tc / 2,\n boundary='periodic')\n self._marginalized_parameters.append('geocent_time')\n elif self.jitter_time:\n logger.debug(\n \"Time jittering requested with non-time-marginalised \"\n \"likelihood, ignoring.\")\n self.jitter_time = False\n\n if self.phase_marginalization:\n self._check_prior_is_set(key='phase')\n self._bessel_function_interped = None\n self._setup_phase_marginalization()\n priors['phase'] = float(0)\n self._marginalized_parameters.append('phase')\n\n if self.distance_marginalization:\n self._lookup_table_filename = None\n self._check_prior_is_set(key='luminosity_distance')\n self._distance_array = np.linspace(\n self.priors['luminosity_distance'].minimum,\n self.priors['luminosity_distance'].maximum, int(1e4))\n self.distance_prior_array = np.array(\n [self.priors['luminosity_distance'].prob(distance)\n for distance in self._distance_array])\n self._setup_distance_marginalization(\n distance_marginalization_lookup_table)\n priors['luminosity_distance'] = float(self._ref_dist)\n self._marginalized_parameters.append('luminosity_distance')\n\n def __repr__(self):\n return self.__class__.__name__ + '(interferometers={},\\n\\twaveform_generator={},\\n\\ttime_marginalization={}, ' \\\n 'distance_marginalization={}, phase_marginalization={}, priors={})'\\\n .format(self.interferometers, self.waveform_generator, self.time_marginalization,\n self.distance_marginalization, self.phase_marginalization, self.priors)\n\n def _check_set_duration_and_sampling_frequency_of_waveform_generator(self):\n \"\"\" Check the waveform_generator has the same duration and\n sampling_frequency as the interferometers. If they are unset, then\n set them, if they differ, raise an error\n \"\"\"\n\n attributes = ['duration', 'sampling_frequency', 'start_time']\n for attr in attributes:\n wfg_attr = getattr(self.waveform_generator, attr)\n ifo_attr = getattr(self.interferometers, attr)\n if wfg_attr is None:\n logger.debug(\n \"The waveform_generator {} is None. Setting from the \"\n \"provided interferometers.\".format(attr))\n elif wfg_attr != ifo_attr:\n logger.warning(\n \"The waveform_generator {} is not equal to that of the \"\n \"provided interferometers. Overwriting the \"\n \"waveform_generator.\".format(attr))\n setattr(self.waveform_generator, attr, ifo_attr)\n\n def calculate_snrs(self, waveform_polarizations, interferometer):\n \"\"\"\n Compute the snrs\n\n Parameters\n ----------\n waveform_polarizations: dict\n A dictionary of waveform polarizations and the corresponding array\n interferometer: bilby.gw.detector.Interferometer\n The bilby interferometer object\n\n \"\"\"\n signal = interferometer.get_detector_response(\n waveform_polarizations, self.parameters)\n d_inner_h = interferometer.inner_product(signal=signal)\n optimal_snr_squared = interferometer.optimal_snr_squared(signal=signal)\n complex_matched_filter_snr = d_inner_h / (optimal_snr_squared**0.5)\n\n if self.time_marginalization:\n d_inner_h_squared_tc_array =\\\n 4 / self.waveform_generator.duration * np.fft.fft(\n signal[0:-1] *\n interferometer.frequency_domain_strain.conjugate()[0:-1] /\n interferometer.power_spectral_density_array[0:-1])\n else:\n d_inner_h_squared_tc_array = None\n\n return self._CalculatedSNRs(\n d_inner_h=d_inner_h, optimal_snr_squared=optimal_snr_squared,\n complex_matched_filter_snr=complex_matched_filter_snr,\n d_inner_h_squared_tc_array=d_inner_h_squared_tc_array)\n\n def _check_prior_is_set(self, key):\n if key not in self.priors or not isinstance(\n self.priors[key], Prior):\n logger.warning(\n 'Prior not provided for {}, using the BBH default.'.format(key))\n if key == 'geocent_time':\n self.priors[key] = Uniform(\n self.interferometers.start_time,\n self.interferometers.start_time + self.interferometers.duration)\n else:\n self.priors[key] = BBHPriorDict()[key]\n\n @property\n def priors(self):\n return self._prior\n\n @priors.setter\n def priors(self, priors):\n if priors is not None:\n self._prior = priors.copy()\n elif any([self.time_marginalization, self.phase_marginalization,\n self.distance_marginalization]):\n raise ValueError(\"You can't use a marginalized likelihood without specifying a priors\")\n else:\n self._prior = None\n\n def noise_log_likelihood(self):\n log_l = 0\n for interferometer in self.interferometers:\n mask = interferometer.frequency_mask\n log_l -= noise_weighted_inner_product(\n interferometer.frequency_domain_strain[mask],\n interferometer.frequency_domain_strain[mask],\n interferometer.power_spectral_density_array[mask],\n self.waveform_generator.duration) / 2\n return float(np.real(log_l))\n\n def log_likelihood_ratio(self):\n waveform_polarizations =\\\n self.waveform_generator.frequency_domain_strain(self.parameters)\n\n if waveform_polarizations is None:\n return np.nan_to_num(-np.inf)\n\n d_inner_h = 0.\n optimal_snr_squared = 0.\n complex_matched_filter_snr = 0.\n if self.time_marginalization:\n if self.jitter_time:\n self.parameters['geocent_time'] += self.parameters['time_jitter']\n d_inner_h_tc_array = np.zeros(\n self.interferometers.frequency_array[0:-1].shape,\n dtype=np.complex128)\n\n for interferometer in self.interferometers:\n per_detector_snr = self.calculate_snrs(\n waveform_polarizations=waveform_polarizations,\n interferometer=interferometer)\n\n d_inner_h += per_detector_snr.d_inner_h\n optimal_snr_squared += np.real(per_detector_snr.optimal_snr_squared)\n complex_matched_filter_snr += per_detector_snr.complex_matched_filter_snr\n\n if self.time_marginalization:\n d_inner_h_tc_array += per_detector_snr.d_inner_h_squared_tc_array\n\n if self.time_marginalization:\n log_l = self.time_marginalized_likelihood(\n d_inner_h_tc_array=d_inner_h_tc_array,\n h_inner_h=optimal_snr_squared)\n if self.jitter_time:\n self.parameters['geocent_time'] -= self.parameters['time_jitter']\n\n elif self.distance_marginalization:\n log_l = self.distance_marginalized_likelihood(\n d_inner_h=d_inner_h, h_inner_h=optimal_snr_squared)\n\n elif self.phase_marginalization:\n log_l = self.phase_marginalized_likelihood(\n d_inner_h=d_inner_h, h_inner_h=optimal_snr_squared)\n\n else:\n log_l = np.real(d_inner_h) - optimal_snr_squared / 2\n\n return float(log_l.real)\n\n def generate_posterior_sample_from_marginalized_likelihood(self):\n \"\"\"\n Reconstruct the distance posterior from a run which used a likelihood\n which explicitly marginalised over time/distance/phase.\n\n See Eq. (C29-C32) of https://arxiv.org/abs/1809.02293\n\n Return\n ------\n sample: dict\n Returns the parameters with new samples.\n\n Notes\n -----\n This involves a deepcopy of the signal to avoid issues with waveform\n caching, as the signal is overwritten in place.\n \"\"\"\n if any([self.phase_marginalization, self.distance_marginalization,\n self.time_marginalization]):\n signal_polarizations = copy.deepcopy(\n self.waveform_generator.frequency_domain_strain(\n self.parameters))\n else:\n return self.parameters\n if self.time_marginalization:\n new_time = self.generate_time_sample_from_marginalized_likelihood(\n signal_polarizations=signal_polarizations)\n self.parameters['geocent_time'] = new_time\n if self.distance_marginalization:\n new_distance = self.generate_distance_sample_from_marginalized_likelihood(\n signal_polarizations=signal_polarizations)\n self.parameters['luminosity_distance'] = new_distance\n if self.phase_marginalization:\n new_phase = self.generate_phase_sample_from_marginalized_likelihood(\n signal_polarizations=signal_polarizations)\n self.parameters['phase'] = new_phase\n return self.parameters.copy()\n\n def generate_time_sample_from_marginalized_likelihood(\n self, signal_polarizations=None):\n \"\"\"\n Generate a single sample from the posterior distribution for coalescence\n time when using a likelihood which explicitly marginalises over time.\n\n In order to resolve the posterior we artifically upsample to 16kHz.\n\n See Eq. (C29-C32) of https://arxiv.org/abs/1809.02293\n\n Parameters\n ----------\n signal_polarizations: dict, optional\n Polarizations modes of the template.\n\n Returns\n -------\n new_time: float\n Sample from the time posterior.\n \"\"\"\n if self.jitter_time:\n self.parameters['geocent_time'] += self.parameters['time_jitter']\n if signal_polarizations is None:\n signal_polarizations = \\\n self.waveform_generator.frequency_domain_strain(self.parameters)\n\n n_time_steps = int(self.waveform_generator.duration * 16384)\n d_inner_h = np.zeros(n_time_steps, dtype=np.complex)\n psd = np.ones(n_time_steps)\n signal_long = np.zeros(n_time_steps, dtype=np.complex)\n data = np.zeros(n_time_steps, dtype=np.complex)\n h_inner_h = np.zeros(1)\n for ifo in self.interferometers:\n ifo_length = len(ifo.frequency_domain_strain)\n signal = ifo.get_detector_response(\n signal_polarizations, self.parameters)\n signal_long[:ifo_length] = signal\n data[:ifo_length] = np.conj(ifo.frequency_domain_strain)\n psd[:ifo_length] = ifo.power_spectral_density_array\n d_inner_h += np.fft.fft(signal_long * data / psd)\n h_inner_h += ifo.optimal_snr_squared(signal=signal).real\n\n if self.distance_marginalization:\n time_log_like = self.distance_marginalized_likelihood(\n d_inner_h, h_inner_h)\n elif self.phase_marginalization:\n time_log_like = (self._bessel_function_interped(abs(d_inner_h)) -\n h_inner_h.real / 2)\n else:\n time_log_like = (d_inner_h.real - h_inner_h.real / 2)\n\n times = create_time_series(\n sampling_frequency=16384,\n starting_time=self.parameters['geocent_time'] - self.waveform_generator.start_time,\n duration=self.waveform_generator.duration)\n times = times % self.waveform_generator.duration\n times += self.waveform_generator.start_time\n\n time_prior_array = self.priors['geocent_time'].prob(times)\n time_post = (\n np.exp(time_log_like - max(time_log_like)) * time_prior_array)\n\n keep = (time_post > max(time_post) / 1000)\n time_post = time_post[keep]\n times = times[keep]\n\n if len(times) > 1:\n new_time = Interped(times, time_post).sample()\n return new_time\n else:\n raise MarginalizedLikelihoodReconstructionError(\n \"Time posterior reconstruction failed, at least two samples \"\n \"are required.\"\n )\n\n def generate_distance_sample_from_marginalized_likelihood(\n self, signal_polarizations=None):\n \"\"\"\n Generate a single sample from the posterior distribution for luminosity\n distance when using a likelihood which explicitly marginalises over\n distance.\n\n See Eq. (C29-C32) of https://arxiv.org/abs/1809.02293\n\n Parameters\n ----------\n signal_polarizations: dict, optional\n Polarizations modes of the template.\n Note: These are rescaled in place after the distance sample is\n generated to allow further parameter reconstruction to occur.\n\n Returns\n -------\n new_distance: float\n Sample from the distance posterior.\n \"\"\"\n if signal_polarizations is None:\n signal_polarizations = \\\n self.waveform_generator.frequency_domain_strain(self.parameters)\n d_inner_h = 0\n h_inner_h = 0\n for interferometer in self.interferometers:\n per_detector_snr = self.calculate_snrs(\n signal_polarizations, interferometer)\n\n d_inner_h += per_detector_snr.d_inner_h\n h_inner_h += per_detector_snr.optimal_snr_squared\n\n d_inner_h_dist = (\n d_inner_h * self.parameters['luminosity_distance'] /\n self._distance_array)\n\n h_inner_h_dist = (\n h_inner_h * self.parameters['luminosity_distance']**2 /\n self._distance_array**2)\n\n if self.phase_marginalization:\n distance_log_like = (\n self._bessel_function_interped(abs(d_inner_h_dist)) -\n h_inner_h_dist.real / 2)\n else:\n distance_log_like = (d_inner_h_dist.real - h_inner_h_dist.real / 2)\n\n distance_post = (np.exp(distance_log_like - max(distance_log_like)) *\n self.distance_prior_array)\n\n new_distance = Interped(\n self._distance_array, distance_post).sample()\n\n self._rescale_signal(signal_polarizations, new_distance)\n return new_distance\n\n def generate_phase_sample_from_marginalized_likelihood(\n self, signal_polarizations=None):\n \"\"\"\n Generate a single sample from the posterior distribution for phase when\n using a likelihood which explicitly marginalises over phase.\n\n See Eq. (C29-C32) of https://arxiv.org/abs/1809.02293\n\n Parameters\n ----------\n signal_polarizations: dict, optional\n Polarizations modes of the template.\n\n Returns\n -------\n new_phase: float\n Sample from the phase posterior.\n\n Notes\n -----\n This is only valid when assumes that mu(phi) \\propto exp(-2i phi).\n \"\"\"\n if signal_polarizations is None:\n signal_polarizations = \\\n self.waveform_generator.frequency_domain_strain(self.parameters)\n d_inner_h = 0\n h_inner_h = 0\n for interferometer in self.interferometers:\n per_detector_snr = self.calculate_snrs(\n signal_polarizations, interferometer)\n\n d_inner_h += per_detector_snr.d_inner_h\n h_inner_h += per_detector_snr.optimal_snr_squared\n\n phases = np.linspace(0, 2 * np.pi, 101)\n phasor = np.exp(-2j * phases)\n phase_log_post = d_inner_h * phasor - h_inner_h / 2\n phase_post = np.exp(phase_log_post.real - max(phase_log_post.real))\n new_phase = Interped(phases, phase_post).sample()\n return new_phase\n\n def distance_marginalized_likelihood(self, d_inner_h, h_inner_h):\n d_inner_h_ref, h_inner_h_ref = self._setup_rho(\n d_inner_h, h_inner_h)\n if self.phase_marginalization:\n d_inner_h_ref = np.abs(d_inner_h_ref)\n else:\n d_inner_h_ref = np.real(d_inner_h_ref)\n return self._interp_dist_margd_loglikelihood(\n d_inner_h_ref, h_inner_h_ref)\n\n def phase_marginalized_likelihood(self, d_inner_h, h_inner_h):\n d_inner_h = self._bessel_function_interped(abs(d_inner_h))\n return d_inner_h - h_inner_h / 2\n\n def time_marginalized_likelihood(self, d_inner_h_tc_array, h_inner_h):\n if self.distance_marginalization:\n log_l_tc_array = self.distance_marginalized_likelihood(\n d_inner_h=d_inner_h_tc_array, h_inner_h=h_inner_h)\n elif self.phase_marginalization:\n log_l_tc_array = self.phase_marginalized_likelihood(\n d_inner_h=d_inner_h_tc_array,\n h_inner_h=h_inner_h)\n else:\n log_l_tc_array = np.real(d_inner_h_tc_array) - h_inner_h / 2\n times = self._times\n if self.jitter_time:\n times = self._times + self.parameters['time_jitter']\n time_prior_array = self.priors['geocent_time'].prob(times) * self._delta_tc\n return logsumexp(log_l_tc_array, b=time_prior_array)\n\n def _setup_rho(self, d_inner_h, optimal_snr_squared):\n optimal_snr_squared_ref = (optimal_snr_squared.real *\n self.parameters['luminosity_distance'] ** 2 /\n self._ref_dist ** 2.)\n d_inner_h_ref = (d_inner_h * self.parameters['luminosity_distance'] /\n self._ref_dist)\n return d_inner_h_ref, optimal_snr_squared_ref\n\n def log_likelihood(self):\n return self.log_likelihood_ratio() + self.noise_log_likelihood()\n\n @property\n def _delta_distance(self):\n return self._distance_array[1] - self._distance_array[0]\n\n @property\n def _ref_dist(self):\n \"\"\" Smallest distance contained in priors \"\"\"\n return self._distance_array[0]\n\n @property\n def _optimal_snr_squared_ref_array(self):\n \"\"\" Optimal filter snr at fiducial distance of ref_dist Mpc \"\"\"\n return np.logspace(-5, 10, self._dist_margd_loglikelihood_array.shape[0])\n\n @property\n def _d_inner_h_ref_array(self):\n \"\"\" Matched filter snr at fiducial distance of ref_dist Mpc \"\"\"\n if self.phase_marginalization:\n return np.logspace(-5, 10, self._dist_margd_loglikelihood_array.shape[1])\n else:\n return np.hstack((-np.logspace(3, -3, self._dist_margd_loglikelihood_array.shape[1] / 2),\n np.logspace(-3, 10, self._dist_margd_loglikelihood_array.shape[1] / 2)))\n\n def _setup_distance_marginalization(self, lookup_table=None):\n if isinstance(lookup_table, str) or lookup_table is None:\n self.cached_lookup_table_filename = lookup_table\n lookup_table = self.load_lookup_table(\n self.cached_lookup_table_filename)\n if isinstance(lookup_table, dict):\n if self._test_cached_lookup_table(lookup_table):\n self._dist_margd_loglikelihood_array = lookup_table[\n 'lookup_table']\n else:\n self._create_lookup_table()\n else:\n self._create_lookup_table()\n self._interp_dist_margd_loglikelihood = UnsortedInterp2d(\n self._d_inner_h_ref_array, self._optimal_snr_squared_ref_array,\n self._dist_margd_loglikelihood_array, kind='cubic')\n\n @property\n def cached_lookup_table_filename(self):\n if self._lookup_table_filename is None:\n self._lookup_table_filename = (\n '.distance_marginalization_lookup.npz')\n return self._lookup_table_filename\n\n @cached_lookup_table_filename.setter\n def cached_lookup_table_filename(self, filename):\n if isinstance(filename, str):\n if filename[-4:] != '.npz':\n filename += '.npz'\n self._lookup_table_filename = filename\n\n def load_lookup_table(self, filename):\n if os.path.exists(filename):\n try:\n loaded_file = dict(np.load(filename))\n except AttributeError as e:\n logger.warning(e)\n self._create_lookup_table()\n return None\n match, failure = self._test_cached_lookup_table(loaded_file)\n if match:\n logger.info('Loaded distance marginalisation lookup table from '\n '{}.'.format(filename))\n return loaded_file\n else:\n logger.info('Loaded distance marginalisation lookup table does '\n 'not match for {}.'.format(failure))\n elif isinstance(filename, str):\n logger.info('Distance marginalisation file {} does not '\n 'exist'.format(filename))\n return None\n\n def cache_lookup_table(self):\n np.savez(self.cached_lookup_table_filename,\n distance_array=self._distance_array,\n prior_array=self.distance_prior_array,\n lookup_table=self._dist_margd_loglikelihood_array,\n reference_distance=self._ref_dist,\n phase_marginalization=self.phase_marginalization)\n\n def _test_cached_lookup_table(self, loaded_file):\n pairs = dict(\n distance_array=self._distance_array,\n prior_array=self.distance_prior_array,\n reference_distance=self._ref_dist,\n phase_marginalization=self.phase_marginalization)\n for key in pairs:\n if key not in loaded_file:\n return False, key\n elif not np.array_equal(np.atleast_1d(loaded_file[key]),\n np.atleast_1d(pairs[key])):\n return False, key\n return True, None\n\n def _create_lookup_table(self):\n \"\"\" Make the lookup table \"\"\"\n logger.info('Building lookup table for distance marginalisation.')\n\n self._dist_margd_loglikelihood_array = np.zeros((400, 800))\n for ii, optimal_snr_squared_ref in enumerate(self._optimal_snr_squared_ref_array):\n optimal_snr_squared_array = (\n optimal_snr_squared_ref * self._ref_dist ** 2. /\n self._distance_array ** 2)\n for jj, d_inner_h_ref in enumerate(self._d_inner_h_ref_array):\n d_inner_h_array = (\n d_inner_h_ref * self._ref_dist / self._distance_array)\n if self.phase_marginalization:\n d_inner_h_array =\\\n self._bessel_function_interped(abs(d_inner_h_array))\n self._dist_margd_loglikelihood_array[ii][jj] = \\\n logsumexp(d_inner_h_array - optimal_snr_squared_array / 2,\n b=self.distance_prior_array * self._delta_distance)\n log_norm = logsumexp(0. / self._distance_array,\n b=self.distance_prior_array * self._delta_distance)\n self._dist_margd_loglikelihood_array -= log_norm\n self.cache_lookup_table()\n\n def _setup_phase_marginalization(self):\n self._bessel_function_interped = interp1d(\n np.logspace(-5, 10, int(1e6)), np.logspace(-5, 10, int(1e6)) +\n np.log([i0e(snr) for snr in np.logspace(-5, 10, int(1e6))]),\n bounds_error=False, fill_value=(0, np.nan))\n\n def _setup_time_marginalization(self):\n self._delta_tc = 2 / self.waveform_generator.sampling_frequency\n self._times =\\\n self.interferometers.start_time + np.linspace(\n 0, self.interferometers.duration,\n int(self.interferometers.duration / 2 *\n self.waveform_generator.sampling_frequency + 1))[1:]\n self.time_prior_array = \\\n self.priors['geocent_time'].prob(self._times) * self._delta_tc\n\n @property\n def interferometers(self):\n return self._interferometers\n\n @interferometers.setter\n def interferometers(self, interferometers):\n self._interferometers = InterferometerList(interferometers)\n\n def _rescale_signal(self, signal, new_distance):\n for mode in signal:\n signal[mode] *= self._ref_dist / new_distance\n\n @property\n def lal_version(self):\n try:\n from lal import git_version\n lal_version = str(git_version.verbose_msg).replace(\"\\n\", \";\")\n logger.info(\"Using LAL version {}\".format(lal_version))\n return lal_version\n except (ImportError, AttributeError):\n return \"N/A\"\n\n @property\n def meta_data(self):\n return dict(\n interferometers=self.interferometers.meta_data,\n time_marginalization=self.time_marginalization,\n phase_marginalization=self.phase_marginalization,\n distance_marginalization=self.distance_marginalization,\n waveform_generator_class=self.waveform_generator.__class__,\n waveform_arguments=self.waveform_generator.waveform_arguments,\n frequency_domain_source_model=self.waveform_generator.frequency_domain_source_model,\n parameter_conversion=self.waveform_generator.parameter_conversion,\n sampling_frequency=self.waveform_generator.sampling_frequency,\n duration=self.waveform_generator.duration,\n start_time=self.waveform_generator.start_time,\n lal_version=self.lal_version)\n\n\nclass BasicGravitationalWaveTransient(Likelihood):\n\n def __init__(self, interferometers, waveform_generator):\n \"\"\"\n\n A likelihood object, able to compute the likelihood of the data given\n some model parameters\n\n The simplest frequency-domain gravitational wave transient likelihood. Does\n not include distance/phase marginalization.\n\n\n Parameters\n ----------\n interferometers: list\n A list of `bilby.gw.detector.Interferometer` instances - contains the\n detector data and power spectral densities\n waveform_generator: bilby.gw.waveform_generator.WaveformGenerator\n An object which computes the frequency-domain strain of the signal,\n given some set of parameters\n\n \"\"\"\n super(BasicGravitationalWaveTransient, self).__init__(dict())\n self.interferometers = interferometers\n self.waveform_generator = waveform_generator\n\n def __repr__(self):\n return self.__class__.__name__ + '(interferometers={},\\n\\twaveform_generator={})'\\\n .format(self.interferometers, self.waveform_generator)\n\n def noise_log_likelihood(self):\n \"\"\" Calculates the real part of noise log-likelihood\n\n Returns\n -------\n float: The real part of the noise log likelihood\n\n \"\"\"\n log_l = 0\n for interferometer in self.interferometers:\n log_l -= 2. / self.waveform_generator.duration * np.sum(\n abs(interferometer.frequency_domain_strain) ** 2 /\n interferometer.power_spectral_density_array)\n return log_l.real\n\n def log_likelihood(self):\n \"\"\" Calculates the real part of log-likelihood value\n\n Returns\n -------\n float: The real part of the log likelihood\n\n \"\"\"\n log_l = 0\n waveform_polarizations =\\\n self.waveform_generator.frequency_domain_strain(\n self.parameters.copy())\n if waveform_polarizations is None:\n return np.nan_to_num(-np.inf)\n for interferometer in self.interferometers:\n log_l += self.log_likelihood_interferometer(\n waveform_polarizations, interferometer)\n return log_l.real\n\n def log_likelihood_interferometer(self, waveform_polarizations,\n interferometer):\n \"\"\"\n\n Parameters\n ----------\n waveform_polarizations: dict\n Dictionary containing the desired waveform polarization modes and the related strain\n interferometer: bilby.gw.detector.Interferometer\n The Interferometer object we want to have the log-likelihood for\n\n Returns\n -------\n float: The real part of the log-likelihood for this interferometer\n\n \"\"\"\n signal_ifo = interferometer.get_detector_response(\n waveform_polarizations, self.parameters)\n\n log_l = - 2. / self.waveform_generator.duration * np.vdot(\n interferometer.frequency_domain_strain - signal_ifo,\n (interferometer.frequency_domain_strain - signal_ifo) /\n interferometer.power_spectral_density_array)\n return log_l.real\n\n\nclass ROQGravitationalWaveTransient(GravitationalWaveTransient):\n \"\"\"A reduced order quadrature likelihood object\n\n This uses the method described in Smith et al., (2016) Phys. Rev. D 94,\n 044031. A public repository of the ROQ data is available from\n https://git.ligo.org/lscsoft/ROQ_data.\n\n Parameters\n ----------\n interferometers: list, bilby.gw.detector.InterferometerList\n A list of `bilby.detector.Interferometer` instances - contains the\n detector data and power spectral densities\n waveform_generator: `bilby.waveform_generator.WaveformGenerator`\n An object which computes the frequency-domain strain of the signal,\n given some set of parameters\n linear_matrix: str, array_like\n Either a string point to the file from which to load the linear_matrix\n array, or the array itself.\n quadratic_matrix: str, array_like\n Either a string point to the file from which to load the\n quadratic_matrix array, or the array itself.\n roq_params: str, array_like\n Parameters describing the domain of validity of the ROQ basis.\n roq_params_check: bool\n If true, run tests using the roq_params to check the prior and data are\n valid for the ROQ\n roq_scale_factor: float\n The ROQ scale factor used.\n priors: dict, bilby.prior.PriorDict\n A dictionary of priors containing at least the geocent_time prior\n distance_marginalization_lookup_table: (dict, str), optional\n If a dict, dictionary containing the lookup_table, distance_array,\n (distance) prior_array, and reference_distance used to construct\n the table.\n If a string the name of a file containing these quantities.\n The lookup table is stored after construction in either the\n provided string or a default location:\n '.distance_marginalization_lookup_dmin{}_dmax{}_n{}.npz'\n\n \"\"\"\n def __init__(self, interferometers, waveform_generator, priors,\n weights=None, linear_matrix=None, quadratic_matrix=None,\n roq_params=None, roq_params_check=True, roq_scale_factor=1,\n distance_marginalization=False, phase_marginalization=False,\n distance_marginalization_lookup_table=None):\n super(ROQGravitationalWaveTransient, self).__init__(\n interferometers=interferometers,\n waveform_generator=waveform_generator, priors=priors,\n distance_marginalization=distance_marginalization,\n phase_marginalization=phase_marginalization,\n time_marginalization=False,\n distance_marginalization_lookup_table=distance_marginalization_lookup_table,\n jitter_time=False)\n\n self.roq_params_check = roq_params_check\n self.roq_scale_factor = roq_scale_factor\n if isinstance(roq_params, np.ndarray) or roq_params is None:\n self.roq_params = roq_params\n elif isinstance(roq_params, str):\n self.roq_params_file = roq_params\n self.roq_params = np.genfromtxt(roq_params, names=True)\n else:\n raise TypeError(\"roq_params should be array or str\")\n if isinstance(weights, dict):\n self.weights = weights\n elif isinstance(weights, str):\n self.weights = self.load_weights(weights)\n else:\n self.weights = dict()\n if isinstance(linear_matrix, str):\n logger.info(\n \"Loading linear matrix from {}\".format(linear_matrix))\n linear_matrix = np.load(linear_matrix).T\n if isinstance(quadratic_matrix, str):\n logger.info(\n \"Loading quadratic_matrix from {}\".format(quadratic_matrix))\n quadratic_matrix = np.load(quadratic_matrix).T\n self._set_weights(linear_matrix=linear_matrix,\n quadratic_matrix=quadratic_matrix)\n self.frequency_nodes_linear =\\\n waveform_generator.waveform_arguments['frequency_nodes_linear']\n self.frequency_nodes_quadratic = \\\n waveform_generator.waveform_arguments['frequency_nodes_quadratic']\n\n def calculate_snrs(self, waveform_polarizations, interferometer):\n \"\"\"\n Compute the snrs for ROQ\n\n Parameters\n ----------\n waveform_polarizations: waveform\n interferometer: bilby.gw.detector.Interferometer\n\n \"\"\"\n\n f_plus = interferometer.antenna_response(\n self.parameters['ra'], self.parameters['dec'],\n self.parameters['geocent_time'], self.parameters['psi'], 'plus')\n f_cross = interferometer.antenna_response(\n self.parameters['ra'], self.parameters['dec'],\n self.parameters['geocent_time'], self.parameters['psi'], 'cross')\n\n dt = interferometer.time_delay_from_geocenter(\n self.parameters['ra'], self.parameters['dec'],\n self.parameters['geocent_time'])\n dt_geocent = self.parameters['geocent_time'] - interferometer.strain_data.start_time\n ifo_time = dt_geocent + dt\n\n calib_linear = interferometer.calibration_model.get_calibration_factor(\n self.frequency_nodes_linear,\n prefix='recalib_{}_'.format(interferometer.name), **self.parameters)\n calib_quadratic = interferometer.calibration_model.get_calibration_factor(\n self.frequency_nodes_quadratic,\n prefix='recalib_{}_'.format(interferometer.name), **self.parameters)\n\n h_plus_linear = f_plus * waveform_polarizations['linear']['plus'] * calib_linear\n h_cross_linear = f_cross * waveform_polarizations['linear']['cross'] * calib_linear\n h_plus_quadratic = (\n f_plus * waveform_polarizations['quadratic']['plus'] * calib_quadratic)\n h_cross_quadratic = (\n f_cross * waveform_polarizations['quadratic']['cross'] * calib_quadratic)\n\n indices, in_bounds = self._closest_time_indices(\n ifo_time, self.weights['time_samples'])\n if not in_bounds:\n logger.debug(\"SNR calculation error: requested time at edge of ROQ time samples\")\n return self._CalculatedSNRs(\n d_inner_h=np.nan_to_num(-np.inf), optimal_snr_squared=0,\n complex_matched_filter_snr=np.nan_to_num(-np.inf),\n d_inner_h_squared_tc_array=None)\n\n d_inner_h_tc_array = np.einsum(\n 'i,ji->j', np.conjugate(h_plus_linear + h_cross_linear),\n self.weights[interferometer.name + '_linear'][indices])\n\n d_inner_h = interp1d(\n self.weights['time_samples'][indices],\n d_inner_h_tc_array, kind='cubic', assume_sorted=True)(ifo_time)\n\n optimal_snr_squared = \\\n np.vdot(np.abs(h_plus_quadratic + h_cross_quadratic)**2,\n self.weights[interferometer.name + '_quadratic'])\n\n complex_matched_filter_snr = d_inner_h / (optimal_snr_squared**0.5)\n d_inner_h_squared_tc_array = None\n\n return self._CalculatedSNRs(\n d_inner_h=d_inner_h, optimal_snr_squared=optimal_snr_squared,\n complex_matched_filter_snr=complex_matched_filter_snr,\n d_inner_h_squared_tc_array=d_inner_h_squared_tc_array)\n\n @staticmethod\n def _closest_time_indices(time, samples):\n \"\"\"\n Get the closest five times\n\n Parameters\n ----------\n time: float\n Time to check\n samples: array-like\n Available times\n\n Returns\n -------\n indices: list\n Indices nearest to time\n in_bounds: bool\n Whether the indices are for valid times\n \"\"\"\n closest = np.argmin(abs(samples - time))\n indices = [closest + ii for ii in [-2, -1, 0, 1, 2]]\n in_bounds = (indices[0] >= 0) & (indices[-1] < samples.size)\n return indices, in_bounds\n\n def perform_roq_params_check(self, ifo=None):\n \"\"\" Perform checking that the prior and data are valid for the ROQ\n\n Parameters\n ----------\n ifo: bilby.gw.detector.Interferometer\n The interferometer\n \"\"\"\n if self.roq_params_check is False:\n logger.warning(\"No ROQ params checking performed\")\n return\n else:\n if getattr(self, \"roq_params_file\", None) is not None:\n msg = (\"Check ROQ params {} with roq_scale_factor={}\"\n .format(self.roq_params_file, self.roq_scale_factor))\n else:\n msg = (\"Check ROQ params with roq_scale_factor={}\"\n .format(self.roq_scale_factor))\n logger.info(msg)\n\n roq_params = self.roq_params\n roq_minimum_frequency = roq_params['flow'] * self.roq_scale_factor\n roq_maximum_frequency = roq_params['fhigh'] * self.roq_scale_factor\n roq_segment_length = roq_params['seglen'] / self.roq_scale_factor\n roq_minimum_chirp_mass = roq_params['chirpmassmin'] / self.roq_scale_factor\n roq_maximum_chirp_mass = roq_params['chirpmassmax'] / self.roq_scale_factor\n roq_minimum_component_mass = roq_params['compmin'] / self.roq_scale_factor\n\n if ifo.maximum_frequency > roq_maximum_frequency:\n raise BilbyROQParamsRangeError(\n \"Requested maximum frequency {} larger than ROQ basis fhigh {}\"\n .format(ifo.maximum_frequency, roq_maximum_frequency))\n if ifo.minimum_frequency < roq_minimum_frequency:\n raise BilbyROQParamsRangeError(\n \"Requested minimum frequency {} lower than ROQ basis flow {}\"\n .format(ifo.minimum_frequency, roq_minimum_frequency))\n if ifo.strain_data.duration != roq_segment_length:\n raise BilbyROQParamsRangeError(\n \"Requested duration differs from ROQ basis seglen\")\n\n priors = self.priors\n if isinstance(priors, CBCPriorDict) is False:\n logger.warning(\"Unable to check ROQ parameter bounds: priors not understood\")\n return\n\n if priors.minimum_chirp_mass is None:\n logger.warning(\"Unable to check minimum chirp mass ROQ bounds\")\n elif priors.minimum_chirp_mass < roq_minimum_chirp_mass:\n raise BilbyROQParamsRangeError(\n \"Prior minimum chirp mass {} less than ROQ basis bound {}\"\n .format(priors.minimum_chirp_mass,\n roq_minimum_chirp_mass))\n\n if priors.maximum_chirp_mass is None:\n logger.warning(\"Unable to check maximum_chirp mass ROQ bounds\")\n elif priors.maximum_chirp_mass > roq_maximum_chirp_mass:\n raise BilbyROQParamsRangeError(\n \"Prior maximum chirp mass {} greater than ROQ basis bound {}\"\n .format(priors.maximum_chirp_mass,\n roq_maximum_chirp_mass))\n\n if priors.minimum_component_mass is None:\n logger.warning(\"Unable to check minimum component mass ROQ bounds\")\n elif priors.minimum_component_mass < roq_minimum_component_mass:\n raise BilbyROQParamsRangeError(\n \"Prior minimum component mass {} less than ROQ basis bound {}\"\n .format(priors.minimum_component_mass,\n roq_minimum_component_mass))\n\n def _set_weights(self, linear_matrix, quadratic_matrix):\n \"\"\" Setup the time-dependent ROQ weights.\n\n Parameters\n ----------\n linear_matrix, quadratic_matrix: array_like\n Arrays of the linear and quadratic basis\n\n \"\"\"\n\n time_space = self._get_time_resolution()\n # Maximum delay time to geocentre + 5 steps\n earth_light_crossing_time = radius_of_earth / speed_of_light + 5 * time_space\n delta_times = np.arange(\n self.priors['geocent_time'].minimum - earth_light_crossing_time,\n self.priors['geocent_time'].maximum + earth_light_crossing_time,\n time_space)\n time_samples = delta_times - self.interferometers.start_time\n self.weights['time_samples'] = time_samples\n logger.info(\"Using {} ROQ time samples\".format(len(time_samples)))\n\n for ifo in self.interferometers:\n if self.roq_params is not None:\n self.perform_roq_params_check(ifo)\n # Get scaled ROQ quantities\n roq_scaled_minimum_frequency = self.roq_params['flow'] * self.roq_scale_factor\n roq_scaled_maximum_frequency = self.roq_params['fhigh'] * self.roq_scale_factor\n roq_scaled_segment_length = self.roq_params['seglen'] / self.roq_scale_factor\n # Generate frequencies for the ROQ\n roq_frequencies = create_frequency_series(\n sampling_frequency=roq_scaled_maximum_frequency * 2,\n duration=roq_scaled_segment_length)\n roq_mask = roq_frequencies >= roq_scaled_minimum_frequency\n roq_frequencies = roq_frequencies[roq_mask]\n overlap_frequencies, ifo_idxs, roq_idxs = np.intersect1d(\n ifo.frequency_array[ifo.frequency_mask], roq_frequencies,\n return_indices=True)\n else:\n overlap_frequencies = ifo.frequency_array[ifo.frequency_mask]\n roq_idxs = np.arange(linear_matrix.shape[0], dtype=int)\n ifo_idxs = [True] * sum(ifo.frequency_mask)\n if sum(ifo_idxs) != len(roq_idxs):\n raise ValueError(\n \"Mismatch between ROQ basis and frequency array for \"\n \"{}\".format(ifo.name))\n logger.info(\n \"Building ROQ weights for {} with {} frequencies between {} \"\n \"and {}.\".format(\n ifo.name, len(overlap_frequencies),\n min(overlap_frequencies), max(overlap_frequencies)))\n\n logger.debug(\"Preallocate array\")\n tc_shifted_data = np.zeros((\n len(self.weights['time_samples']), len(overlap_frequencies)),\n dtype=complex)\n\n logger.debug(\"Calculate shifted data\")\n data = ifo.frequency_domain_strain[ifo.frequency_mask][ifo_idxs]\n prefactor = (\n data /\n ifo.power_spectral_density_array[ifo.frequency_mask][ifo_idxs]\n )\n for j in range(len(self.weights['time_samples'])):\n tc_shifted_data[j] = prefactor * np.exp(\n 2j * np.pi * overlap_frequencies * time_samples[j])\n\n # to not kill all computers this minimises the memory usage of the\n # required inner products\n max_block_gigabytes = 4\n max_elements = int((max_block_gigabytes * 2 ** 30) / 8)\n\n logger.debug(\"Apply dot product\")\n self.weights[ifo.name + '_linear'] = blockwise_dot_product(\n tc_shifted_data,\n linear_matrix[roq_idxs],\n max_elements) * 4 / ifo.strain_data.duration\n\n del tc_shifted_data, overlap_frequencies\n gc.collect()\n\n self.weights[ifo.name + '_quadratic'] = build_roq_weights(\n 1 /\n ifo.power_spectral_density_array[ifo.frequency_mask][ifo_idxs],\n quadratic_matrix[roq_idxs].real,\n 1 / ifo.strain_data.duration)\n\n logger.info(\"Finished building weights for {}\".format(ifo.name))\n\n def save_weights(self, filename, format='npz'):\n if format not in filename:\n filename += \".\" + format\n logger.info(\"Saving ROQ weights to {}\".format(filename))\n if format == 'json':\n with open(filename, 'w') as file:\n json.dump(self.weights, file, indent=2, cls=BilbyJsonEncoder)\n elif format == 'npz':\n np.savez(filename, **self.weights)\n\n @staticmethod\n def load_weights(filename, format=None):\n if format is None:\n format = filename.split(\".\")[-1]\n if format not in [\"json\", \"npz\"]:\n raise IOError(\"Format {} not recongized.\".format(format))\n logger.info(\"Loading ROQ weights from {}\".format(filename))\n if format == \"json\":\n with open(filename, 'r') as file:\n weights = json.load(file, object_hook=decode_bilby_json)\n elif format == \"npz\":\n # Wrap in dict to load data into memory\n weights = dict(np.load(filename))\n return weights\n\n def _get_time_resolution(self):\n \"\"\"\n This method estimates the time resolution given the optimal SNR of the\n signal in the detector. This is then used when constructing the weights\n for the ROQ.\n\n A minimum resolution is set by assuming the SNR in each detector is at\n least 10. When the SNR is not available the SNR is assumed to be 30 in\n each detector.\n\n Returns\n -------\n delta_t: float\n Time resolution\n \"\"\"\n\n def calc_fhigh(freq, psd, scaling=20.):\n \"\"\"\n\n Parameters\n ----------\n freq: array-like\n Frequency array\n psd: array-like\n Power spectral density\n scaling: float\n SNR dependent scaling factor\n\n Returns\n -------\n f_high: float\n The maximum frequency which must be considered\n \"\"\"\n integrand1 = np.power(freq, -7. / 3) / psd\n integral1 = integrate.simps(integrand1, freq)\n integrand3 = np.power(freq, 2. / 3.) / (psd * integral1)\n f_3_bar = integrate.simps(integrand3, freq)\n\n f_high = scaling * f_3_bar**(1 / 3)\n\n return f_high\n\n def c_f_scaling(snr):\n return (np.pi**2 * snr**2 / 6)**(1 / 3)\n\n inj_snr_sq = 0\n for ifo in self.interferometers:\n inj_snr_sq += min(10, getattr(ifo.meta_data, 'optimal_SNR', 30))**2\n\n psd = ifo.power_spectral_density_array[ifo.frequency_mask]\n freq = ifo.frequency_array[ifo.frequency_mask]\n fhigh = calc_fhigh(freq, psd, scaling=c_f_scaling(inj_snr_sq**0.5))\n\n delta_t = fhigh**-1\n\n # Apply a safety factor to ensure the time step is short enough\n delta_t = delta_t / 5\n\n logger.info(\"ROQ time-step = {}\".format(delta_t))\n return delta_t\n\n def _rescale_signal(self, signal, new_distance):\n for kind in ['linear', 'quadratic']:\n for mode in signal[kind]:\n signal[kind][mode] *= self._ref_dist / new_distance\n\n\ndef get_binary_black_hole_likelihood(interferometers):\n \"\"\" A rapper to quickly set up a likelihood for BBH parameter estimation\n\n Parameters\n ----------\n interferometers: {bilby.gw.detector.InterferometerList, list}\n A list of `bilby.detector.Interferometer` instances, typically the\n output of either `bilby.detector.get_interferometer_with_open_data`\n or `bilby.detector.get_interferometer_with_fake_noise_and_injection`\n\n Returns\n -------\n bilby.GravitationalWaveTransient: The likelihood to pass to `run_sampler`\n\n \"\"\"\n waveform_generator = WaveformGenerator(\n duration=interferometers.duration,\n sampling_frequency=interferometers.sampling_frequency,\n frequency_domain_source_model=lal_binary_black_hole,\n waveform_arguments={'waveform_approximant': 'IMRPhenomPv2',\n 'reference_frequency': 50})\n return GravitationalWaveTransient(interferometers, waveform_generator)\n\n\nclass BilbyROQParamsRangeError(Exception):\n pass\n","sub_path":"bilby/gw/likelihood.py","file_name":"likelihood.py","file_ext":"py","file_size_in_byte":53782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"451436192","text":"def main():\n import sys\n input = sys.stdin.readline\n\n N, M = map(int, input().split())\n pS = [list(input().split()) for i in range(M)]\n\n was = [0]*N\n acs = [0]*N\n\n for p, s in pS:\n q_ind = int(p)-1\n if acs[q_ind] == 0:\n if s == 'AC':\n acs[q_ind] = 1\n else:\n was[q_ind] += 1\n ans_wa = 0\n for i in range(N):\n if acs[i] != 0:\n ans_wa += was[i]\n\n print(sum(acs), ans_wa)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"legacy/abc151/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"134872912","text":"\"\"\"\nThe script detects faces in images.\n\nTakes a folder with images as input and returns a list of jsons:\n\n.json\n\n[\n {\n \"file_name\": ,\n \"bbox\": [x_min, y_min, x_max, y_max],\n \"confidence\": float,\n \"landmarks\": [[x0, y0], [x1, y1] ... [x4, y4]]\n \"embedding\": List[float]\n }\n]\n\n\"\"\"\n\nimport argparse\nimport json\nfrom pathlib import Path\nfrom typing import List, Any, Dict, Union\n\nimport albumentations as albu\nimport cv2\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn.functional as F\nimport yaml\nfrom albumentations.core.serialization import from_dict\nfrom iglovikov_helper_functions.config_parsing.utils import object_from_dict\nfrom iglovikov_helper_functions.utils.image_utils import load_rgb\nfrom pytorch_toolbelt.utils.torch_utils import tensor_from_rgb_image\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision.ops import nms\n\nfrom retinaface.box_utils import decode, decode_landm\nfrom retinaface.utils import load_checkpoint\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n arg = parser.add_argument\n arg(\"-i\", \"--input_path\", type=Path, help=\"Path with images.\", required=True)\n arg(\"-c\", \"--config_path\", type=Path, help=\"Path with images.\", required=True)\n arg(\"-o\", \"--output_path\", type=Path, help=\"Path to save jsons.\", required=True)\n arg(\"-v\", \"--visualize\", action=\"store_true\", help=\"Visualize predictions\")\n arg(\"-g\", \"--num_gpus\", type=int, help=\"The number of GPUs to use.\")\n\n arg(\"-t\", \"--target_size\", type=int, help=\"Target size\", default=1600)\n arg(\"-m\", \"--max_size\", type=int, help=\"Target size\", default=2150)\n arg(\"--origin_size\", action=\"store_true\", help=\"Whether use origin image size to evaluate\")\n arg(\"--confidence_threshold\", default=0.7, type=float, help=\"confidence_threshold\")\n arg(\"--nms_threshold\", default=0.4, type=float, help=\"nms_threshold\")\n arg(\"-w\", \"--weight_path\", type=str, help=\"Path to weights.\")\n arg(\"--keep_top_k\", default=750, type=int, help=\"keep_top_k\")\n return parser.parse_args()\n\n\nclass InferenceDataset(Dataset):\n def __init__(\n self, file_paths: List[Path], origin_size: int, target_size: int, max_size: int, transform: albu.Compose\n ) -> None:\n self.file_paths = file_paths\n self.transform = transform\n self.origin_size = origin_size\n self.target_size = target_size\n self.max_size = max_size\n\n def __len__(self) -> int:\n return len(self.file_paths)\n\n def __getitem__(self, idx):\n image_path = self.file_paths[idx]\n raw_image = load_rgb(image_path, lib=\"cv2\")\n image = raw_image.astype(np.float32)\n\n if self.origin_size:\n resize = 1\n else:\n # testing scale\n im_shape = image.shape\n image_size_min = np.min(im_shape[:2])\n image_size_max = np.max(im_shape[:2])\n resize = float(self.target_size) / float(image_size_min)\n # prevent bigger axis from being more than max_size:\n if np.round(resize * image_size_max) > self.max_size:\n resize = float(self.max_size) / float(image_size_max)\n\n image = cv2.resize(image, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR)\n\n image = self.transform(image=image)[\"image\"]\n\n return {\n \"torched_image\": tensor_from_rgb_image(image),\n \"resize\": resize,\n \"raw_image\": raw_image,\n \"image_path\": str(image_path),\n }\n\n\nclass InferenceModel(pl.LightningModule):\n def __init__(self, hparams: Dict[str, Any], weight_path: Union[Path, str]) -> None:\n super().__init__()\n self.hparams = hparams\n self.model = object_from_dict(self.hparams[\"model\"])\n\n corrections: Dict[str, str] = {\"model.\": \"\"}\n checkpoint = load_checkpoint(file_path=weight_path, rename_in_layers=corrections)\n self.model.load_state_dict(checkpoint[\"state_dict\"])\n\n def setup(self, stage: int = 0) -> None:\n print(self.hparams.keys())\n print(\"output_path\" in self.hparams)\n self.output_vis_path = Path(self.hparams[\"output_path\"]) / \"viz\"\n\n if self.hparams[\"visualize\"]:\n self.output_vis_path.mkdir(exist_ok=True, parents=True)\n\n self.output_label_path = Path(self.hparams[\"output_path\"]) / \"labels\"\n self.output_label_path.mkdir(exist_ok=True, parents=True)\n\n def forward(self, batch: Dict) -> torch.Tensor:\n return self.model(batch)\n\n def test_dataloader(self) -> DataLoader:\n return DataLoader(\n InferenceDataset(\n self.hparams[\"file_paths\"],\n origin_size=self.hparams[\"origin_size\"],\n target_size=self.hparams[\"target_size\"],\n max_size=self.hparams[\"max_size\"],\n transform=from_dict(self.hparams[\"test_aug\"]),\n ),\n batch_size=1,\n num_workers=self.hparams[\"num_workers\"],\n shuffle=False,\n pin_memory=True,\n drop_last=False,\n )\n\n def test_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> None:\n torched_images = batch[\"torched_image\"]\n resizes = batch[\"resize\"]\n image_paths = batch[\"image_path\"]\n raw_images = batch[\"raw_image\"]\n\n labels: List[Dict[str, Any]] = []\n\n loc, conf, land = self.model(torched_images)\n conf = F.softmax(conf, dim=-1)\n\n batch_size = torched_images.shape[0]\n\n image_height, image_width = torched_images.shape[2:]\n\n scale1 = torch.from_numpy(np.tile([image_width, image_height], 5)).to(self.device)\n scale = torch.from_numpy(np.tile([image_width, image_height], 2)).to(self.device)\n\n priors = object_from_dict(hparams[\"prior_box\"], image_size=(image_height, image_width)).to(loc.device)\n\n for batch_id in range(batch_size):\n image_path = image_paths[batch_id]\n file_id = Path(str(image_path)).stem\n raw_image = raw_images[batch_id]\n\n resize = resizes[batch_id].float()\n\n boxes = decode(loc.data[batch_id], priors, hparams[\"test_parameters\"][\"variance\"])\n\n boxes *= scale / resize\n scores = conf[batch_id][:, 1]\n\n landmarks = decode_landm(land.data[batch_id], priors, hparams[\"test_parameters\"][\"variance\"])\n landmarks *= scale1 / resize\n\n # ignore low scores\n valid_index = torch.where(scores > self.hparams[\"confidence_threshold\"])[0]\n boxes = boxes[valid_index]\n landmarks = landmarks[valid_index]\n scores = scores[valid_index]\n\n order = scores.argsort(descending=True)\n\n boxes = boxes[order]\n landmarks = landmarks[order]\n scores = scores[order]\n\n # do NMS\n keep = nms(boxes, scores, self.hparams[\"nms_threshold\"])\n boxes = boxes[keep, :].int()\n\n if boxes.shape[0] == 0:\n continue\n\n landmarks = landmarks[keep].int()\n scores = scores[keep].cpu().numpy().astype(np.float64)\n\n boxes = boxes[: self.hparams[\"keep_top_k\"]]\n landmarks = landmarks[: self.hparams[\"keep_top_k\"]]\n scores = scores[: self.hparams[\"keep_top_k\"]]\n\n if self.hparams[\"visualize\"]:\n vis_image = raw_image.cpu().numpy().copy()\n\n for crop_id, bbox in enumerate(boxes):\n landms = landmarks[crop_id].cpu().numpy().reshape([5, 2])\n\n colors = [(255, 0, 0), (128, 255, 0), (255, 178, 102), (102, 128, 255), (0, 255, 255)]\n for i, (x, y) in enumerate(landms):\n vis_image = cv2.circle(vis_image, (x, y), radius=3, color=colors[i], thickness=3)\n\n x_min, y_min, x_max, y_max = bbox.cpu().numpy()\n\n x_min = np.clip(x_min, 0, x_max - 1)\n y_min = np.clip(y_min, 0, y_max - 1)\n\n vis_image = cv2.rectangle(\n vis_image, (x_min, y_min), (x_max, y_max), color=(0, 255, 0), thickness=2\n )\n\n cv2.imwrite(\n str(self.output_vis_path / f\"{file_id}.jpg\"), cv2.cvtColor(vis_image, cv2.COLOR_BGR2RGB)\n )\n\n for crop_id, bbox in enumerate(boxes):\n bbox = bbox.cpu().numpy()\n\n labels += [\n {\n \"crop_id\": crop_id,\n \"bbox\": bbox.tolist(),\n \"score\": scores[crop_id],\n \"landmarks\": landmarks[crop_id].tolist(),\n }\n ]\n\n result = {\"file_path\": image_path, \"file_id\": file_id, \"bboxes\": labels}\n\n with open(self.output_label_path / f\"{file_id}.json\", \"w\") as f:\n json.dump(result, f, indent=2)\n\n\nif __name__ == \"__main__\":\n args = get_args()\n\n with open(args.config_path) as f:\n hparams = yaml.load(f, Loader=yaml.SafeLoader)\n\n hparams.update(\n {\n \"file_paths\": sorted([x for x in args.input_path.rglob(\"*\") if x.is_file()]),\n \"json_path\": args.output_path,\n \"output_path\": args.output_path,\n \"visualize\": args.visualize,\n \"origin_size\": args.origin_size,\n \"max_size\": args.max_size,\n \"target_size\": args.target_size,\n \"confidence_threshold\": args.confidence_threshold,\n \"nms_threshold\": args.nms_threshold,\n \"keep_top_k\": args.keep_top_k,\n }\n )\n hparams[\"trainer\"][\"gpus\"] = 1 # Right now we work only with one GPU\n\n model = InferenceModel(hparams, weight_path=args.weight_path)\n trainer = object_from_dict(\n hparams[\"trainer\"], checkpoint_callback=object_from_dict(hparams[\"checkpoint_callback\"]),\n )\n\n trainer.test(model)\n","sub_path":"retinaface/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":9979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"88458532","text":"import cv2\nimport numpy as np\nfrom playsound import playsound\nimport serial\n\n#Open serial port on COM4\nser_port = serial.Serial('COM4')\n\n#Webcam capture\nvideo = cv2.VideoCapture(0)\n\n#history, Threshold, Detect Shadows\nfgbg = cv2.createBackgroundSubtractorMOG2(300, 400, True)\n\n#Current frame number\ncurrentFrameNumber = 0\n\n#Number of frames since last activation\nframeCount = 0\n\n#Current frame state: motion = true, no motion = false\ncurrentFrameState = False\n#Last frame state: motion = true, no motion = false\nlastFrameState = False\n\nwhile True:\n\t#return value and current frame\n\tret, frame = video.read()\n\n\t#check if a current frame actually exists\n\tif not ret:\n\t\tbreak\n\t\n\t#update frames since last activation\n\tframeCount += 1\n\n\tcurrentFrameNumber += 1\n\n\t#get the foreground mask\n\tfmask = fgbg.apply(frame)\n\n\t#count all nonzero pixels within mask\n\tcount = np.count_nonzero(fmask)\n\n\t#print(\"Frame: %d, Pixel Count: %d\" % (frameCount, count))\n\n\tcv2.imshow(\"Frame\", frame)\n\t#cv2.imshow(\"Mask\", fmask)\n\n\tif (currentFrameNumber > 1 and count > 5000):\n\t\tcurrentFrameState = True\n\telse:\n\t\tcurrentFrameState = False\n\n\t#if it's been 45 frames since the last activation\n\tif frameCount > 45:\n\t\t#if the current frame has motion but the last frame didn't, say it\n\t\tif currentFrameState == True and lastFrameState == False:\n\t\t\t#turn on LED\n\t\t\tser_port.write(b'1')\n\t\t\tplaysound(\"motion_trigger.mp3\")\n\t\t\t#reset frame count since last activation\n\t\t\tframeCount = 0\n\t\t\t\n\t#update last frame\n\tlastFrameState = currentFrameState\n\t#turn off LED\n\tser_port.write(b'0')\n\n\tk = cv2.waitKey(40) & 0xff\n\tif k == 27: #if escape key is pressed\n\t\tbreak\n\nvideo.release()\ncv2.destroyAllWindows()\n","sub_path":"motion_detection_and_device_control.py","file_name":"motion_detection_and_device_control.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"198841979","text":"#!/usr/bin/env python3\n\nimport re\nimport sys\nimport bs4\nimport itertools\nimport urllib.request\n\nUSER_AGENT = \" \".join([\n \"Mozilla/5.0 (Windows NT 6.1; WOW64)\",\n \"AppleWebKit/537.36 (KHTML, like Gecko)\",\n \"Chrome/38.0.2125.104\",\n \"Safari/537.36\",\n])\n\ndef wget (url):\n headers = {\n \"User-Agent\": USER_AGENT,\n \"Accept\": \"*/*\",\n }\n q = urllib.request.Request(url=url, headers=headers)\n with urllib.request.urlopen(q) as fp:\n return fp.read()\n\ndef _do_tvshow (url):\n content = wget(url)\n soup = bs4.BeautifulSoup(content, \"html5lib\")\n\n for elem in soup.find(class_=\"list\").children:\n if elem.name == \"h3\":\n group_title = list(elem.strings)[0]\n print(group_title)\n elif elem.name == \"a\" and elem.has_attr(\"href\"):\n episode = elem.text\n url = elem[\"href\"]\n print(\"{} ({})\".format(episode, url))\n\ndef main (arg0, argv):\n if len(argv) != 1:\n return \"usage: {} TVID\".format(arg0)\n tvid = argv[0]\n m = re.search(r\"\\A(\\d+)/(\\d+)\\Z\", tvid)\n if not m:\n return \"invalid tvid: {!a}\".format(tvid)\n ida, idb = m.groups()\n url = \"https://www.icefilms.info/tv/series/{}/{}\".format(ida, idb)\n print(url)\n _do_tvshow(url)\n\nif __name__ == \"__main__\":\n try:\n c = main(sys.argv[0], sys.argv[1:])\n except KeyboardInterrupt:\n c = 1\n if c:\n sys.exit(c)\n","sub_path":"projects/apis/icefilms/tv.py","file_name":"tv.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"326228272","text":"import json\nimport pathlib\nimport asyncio\nimport aiohttp\nimport aiofiles\nimport timeit\nimport datetime\n\n# For download statistic checking\ntotal_num_downloads = 0\nsuccessful_posts, failed_posts = 0, 0\nsuccessful_downloads, failed_downloads = 0, 0\n\n# For keeping files and dates paired correctly\nprocessed_urls = {\"url\": [], \"path\": []}\n\n# For use in file path formatting\nmonths = {'01': 'Jan', '02': 'Feb', '03': 'Mar',\n '04': 'Apr', '05': 'May', '06': 'Jun',\n '07': 'Jul', '08': 'Aug', '09': 'Sep',\n '10': 'Oct', '11': 'Nov', '12': 'Dec'}\ntypes = {'PHOTO': 'Photos', 'VIDEO': 'Videos'}\n\n\ndef get_formatted_urls():\n \"\"\"\n Gets properly formatted urls and dates from the memories json\n\n The urls gotten here will later be used for POST requests.\n The dates gotten here will later be used for file pathing.\n Each url and its date are returned as a key-pair in a dict,\n which is done to ensure they stay together throughout the process.\n \"\"\"\n global total_num_downloads\n\n json_location = \"./memories_history.json\" # Default is current directory\n\n with open(json_location, \"r\") as memories_json:\n memories = json.load(memories_json)\n\n json_urls = []\n paths = []\n # The range in this for loop controls how many memories are downloaded\n for memory in range(len(memories[\"Saved Media\"])): \n json_urls.append(memories[\"Saved Media\"][memory][\"Download Link\"])\n year = (memories[\"Saved Media\"][memory][\"Date\"]).split('-')[0]\n month = months[(memories[\"Saved Media\"][memory][\"Date\"]).split('-')[1]]\n media_type = types[(memories[\"Saved Media\"][memory][\"Media Type\"])]\n path = 'media/{0}/{1}/{2}'.format(year, month, media_type)\n paths.append(path)\n\n total_num_downloads = len(json_urls)\n\n return dict(zip(json_urls, paths))\n\n\nasync def get_s3_url(session, formatted_url, formatted_urls):\n \"\"\"\n Get AWS S3 download link from a link in the memories json.\n\n Each url from the memories json needs to be used to make POST requests.\n The response from these requests will be a AWS S3 bucket item link. \n The link is then added to a dictionary that will contain both \n the download link, and the path (which was gotten from the memory's date).\n \"\"\"\n global successful_posts\n global failed_posts\n\n async with session.post(formatted_url) as response:\n text_response = await response.text()\n if response.status == 200:\n processed_urls['url'].append(text_response)\n processed_urls['path'].append(formatted_urls[formatted_url])\n successful_posts += 1\n else:\n failed_posts += 1\n\n\nasync def download_file(session, processed_url, dir):\n \"\"\"\n Downloads a file, given a valid download link and a path to download it to\n \n The dictionary containing each AWS S3 bucket item link and corresponding\n is used to download each memory and store it relative to the date the\n memory was originally created/saved.\n \"\"\"\n global total_num_downloads\n global successful_downloads\n global failed_downloads\n\n success = False\n\n async with session.get(processed_url) as resp:\n if resp.status == 200:\n success = True\n filename = processed_url.split('/')[5].split('?')[0]\n path = '{}/{}'.format(dir, filename)\n pathlib.Path(dir).mkdir(parents=True, exist_ok=True)\n f = await aiofiles.open(path, mode='wb')\n await f.write(await resp.read())\n await f.close()\n\n if(success):\n successful_downloads += 1\n print(\"--> Downloaded memory {} out of {}\"\n .format(successful_downloads, total_num_downloads))\n else:\n failed_downloads += 1\n\n\nasync def retrieve_memories():\n \"\"\"Puts everything together and retrieves the snapchat memories\n\n The order of operations will go as follows:\n 1. Data from the memories json will be formatted so that it is more usable\n 2. A list of download links will be created using this data\n 3. Memories will then be downloaded accordignly based off of this list\n \"\"\"\n try:\n formatted_urls = get_formatted_urls()\n except FileNotFoundError:\n print(\"\\nCannot proceed without json file. Stopping...\\n\")\n loop = asyncio.get_running_loop()\n loop.stop()\n exit(0)\n except ValueError:\n print(\"\\nBad json file. Stopping...\\n\")\n loop = asyncio.get_running_loop()\n loop.stop()\n exit(0)\n\n print('Getting download links...')\n async with aiohttp.ClientSession() as session:\n tasks = [get_s3_url(session, formatted_url, formatted_urls)\n for formatted_url in formatted_urls]\n await asyncio.gather(*tasks)\n print('DONE!\\n')\n\n print('Downloading memories...')\n async with aiohttp.ClientSession() as session:\n tasks = [download_file(session, processed_urls['url'][memory],\n processed_urls['path'][memory])\n for memory in range(len(processed_urls['url']))]\n await asyncio.gather(*tasks)\n print('DONE!\\n')\n\n\ndef run():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(retrieve_memories())\n\n\nif __name__ == '__main__':\n # Run and time the program\n starttime = timeit.default_timer()\n run()\n stoptime = timeit.default_timer() - starttime\n time = str(datetime.timedelta(seconds=stoptime))\n hours = time.split(':')[0]\n minutes = time.split(':')[1]\n seconds = time.split(':')[2]\n\n # Printing out download statistics\n print(\"Downloaded {} memories in: \".format(successful_downloads))\n print(\"{} hours {} minutes {} seconds\".format(hours, minutes, seconds))\n print(\"\\n# of POST successes : {}\".format(successful_posts))\n print(\"# of POST failures : {}\".format(failed_posts))\n print(\"# of download successes : {}\".format(successful_downloads))\n print(\"# of download failures : {}\".format(failed_downloads))\n\n exit(0)\n","sub_path":"snapchat_memory_retrieval_tool.py","file_name":"snapchat_memory_retrieval_tool.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"591056592","text":"from componentes.campoTexto import *\nfrom PPlay.gameimage import *\nfrom PPlay.sprite import *\nfrom componentes.botao import *\nfrom componentes.campoSenha import *\nimport pygame\n\n'''\nClasse para definir o componente de popup de senha para entrar e saguao\n'''\nclass SenhaPopUp:\n # Inicia o objeto com seus respectivos sprites, fundo e inputs nas posicoes corretas\n def __init__(self, janela):\n \n self.janela = janela\n \n self.fundo = GameImage(\"assets/imagem/busca_saguao/sombra.png\")\n\n self.popup_box = GameImage(\"assets/imagem/busca_saguao/popup.png\")\n self.popup_box.set_position(\n janela.width/2 - self.popup_box.width/2,\n self.janela.height/2 - self.popup_box.height/2 \n )\n\n self.input = CampoSenha(\n janela,\n GameImage(\"assets/imagem/busca_saguao/senha_da_sala.png\"), \n self.popup_box.x + 40, \n self.popup_box.y + 52,\n 250,\n 40, \n 22\n )\n\n self.entrar_botao = Botao(\n Sprite(\"assets/imagem/busca_saguao/botao_entrar.png\"),\n Sprite(\"assets/imagem/busca_saguao/botao_entrar_select.png\"),\n 1\n )\n self.entrar_botao.setposition(\n self.popup_box.x + self.popup_box.width/2 - self.entrar_botao.width/2,\n self.popup_box.y + self.popup_box.height - 45\n )\n \n self.fechar_botao = Botao(\n Sprite(\"assets/imagem/busca_saguao/x_popup.png\"),\n Sprite(\"assets/imagem/busca_saguao/x_popup.png\"),\n 2\n )\n self.fechar_botao.setposition(\n self.popup_box.x + self.popup_box.width - self.fechar_botao.width - 5,\n self.popup_box.y + 5\n )\n\n #Atualiza os componentes do popup a cada frame\n def update(self):\n self.trataEventos()\n update_botao = self.entrar_botao.update()\n if(update_botao):\n return self.entrar_botao.code\n update_fechar = self.fechar_botao.update()\n if(update_fechar):\n return self.fechar_botao.code\n #Codigo padrao de que nao houve eventos\n return 0\n\n #Renderiza os objetos do popup\n def render(self):\n self.fundo.draw()\n self.popup_box.draw()\n self.input.draw()\n self.entrar_botao.render()\n self.fechar_botao.render()\n \n def trataEventos(self):\n for evento in pygame.event.get():\n self.input.evento(evento)\n if evento.type == pygame.QUIT:\n exit()\n\n \n \n ","sub_path":"componentes/SenhaSalaPopUp.py","file_name":"SenhaSalaPopUp.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33174719","text":"\ndef take_multiple_args(*params):\n for param in params:\n print(param)\n\ntake_multiple_args(1, 2)\ntake_multiple_args(1, 2, \"hello\", False)\n\nprint(50 * '-')\n\ndef return_multiple_args(a, b):\n return a + b, a - b, a * b, a / b\n\na , b = 2, 5\n\nprint(\"a = %d, b = %d\" % (a , b))\nprint(\"a + b = %s\\n\"\n \"a - b = %s\\n\"\n \"a * b = %s\\n\"\n \"a / b = %s\" % return_multiple_args(a, b))\n\nprint(50 * '-')\n\ndef text_contains_aA(text):\n if \"a\" in text or \"A\" in text:\n return \"Text %r contains a or A\" % text\n else:\n return \"Text %r does not contain a or A\" % text\n\nprint(text_contains_aA(\"qwerty\"))\nprint(text_contains_aA(\"qwertya\"))\nprint(text_contains_aA(\"qwAerty\"))\n\nprint(50 * '-')\n\n# inline if\ndef contains_aA(text):\n return True if \"a\" in text or \"A\" in text else False\n\nprint(contains_aA(\"qwerty\"))\nprint(contains_aA(\"qwertya\"))\n","sub_path":"basics/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"122230642","text":"from inventory.models import Material, MaterialStock\n\n\ndef get_restock_total_price(materials):\n total_price = 0\n for material in materials:\n if isinstance(material, dict):\n price = Material.objects.get(pk=material.get('material')).price\n total_price += price * material.get('quantity')\n elif isinstance(material, MaterialStock):\n price = Material.objects.get(pk=material.material.pk).price\n total_price += price * \\\n (material.max_capacity - material.current_capacity)\n\n return float(round(total_price, 2))\n\n\ndef get_model_obj_property(model, instance, exclude=(\"pk\")):\n field_names = [f.name for f in model._meta.fields]\n property_names = [\n name for name in dir(model)\n if isinstance(getattr(model, name), property) and name not in exclude\n ]\n return dict((name, getattr(instance, name)) for name in field_names + property_names)\n","sub_path":"inventory/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111580253","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom backbone.resnet import resnet\n\n\nclass Kernel_Calculate(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0):\n super(Kernel_Calculate, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels,\n kernel_size=kernel_size, stride=stride, padding=padding)\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n\n self.init_weight()\n\n def init_weight(self):\n for ly in self.children():\n if isinstance(ly, nn.Conv2d):\n nn.init.kaiming_normal_(ly.weight, a=1)\n if not ly.bias is None: nn.init.constant_(ly.bias, 0)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\nclass ConvBNReLU(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1):\n super(ConvBNReLU, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels,\n kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=True)\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.init_weight()\n\n\n def init_weight(self):\n for ly in self.children():\n if isinstance(ly, nn.Conv2d):\n nn.init.kaiming_normal_(ly.weight, a=1)\n if not ly.bias is None: nn.init.constant_(ly.bias, 0)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\n\n\n\n\nclass Feature_Fusion(nn.Module):\n def __init__(self):\n super(Feature_Fusion, self).__init__()\n\n self.featurefusion1 = ConvBNReLU(2048, 256, padding=18, dilation=18)\n self.featurefusion2 = ConvBNReLU(2048, 256, padding=12, dilation=12)\n self.featurefusion3 = ConvBNReLU(2048, 256, padding=6, dilation=6)\n self.featurefusion4 = ConvBNReLU(2048, 256, padding=1, dilation=1)\n\n self.avg = nn.AdaptiveAvgPool2d((1, 1))\n self.featurefusion5 = ConvBNReLU(2048, 256, kernel_size=1, stride=1, padding=0)\n\n self.conv_out = ConvBNReLU(256 * 5, 256, kernel_size=1, stride=1, padding=0)\n\n self.init_weight()\n\n def init_weight(self):\n for ly in self.children():\n if isinstance(ly, nn.Conv2d):\n nn.init.kaiming_normal_(ly.weight, a=1)\n if not ly.bias is None: nn.init.constant_(ly.bias, 0)\n #\n\n def forward(self, x4):\n H, W = x4.size()[2:]\n\n feat1 = self.featurefusion1(x4)\n feat2 = self.featurefusion2(x4)\n feat3 = self.featurefusion3(x4)\n feat4 = self.featurefusion4(x4)\n\n feat5 = self.avg(x4)\n feat5 = self.featurefusion5(feat5)\n feat5 = F.interpolate(feat5, size=(H, W), mode='bilinear', align_corners=True)\n\n feat = torch.cat((feat1, feat2, feat3, feat4, feat5), dim=1)\n\n out = self.conv_out(feat)\n\n return out\n\n\nclass HighOrder(nn.Module):\n def __init__(self, n_classes):\n super(HighOrder, self).__init__()\n\n self.backbone = resnet(101, 16)\n self.featurefusion = Feature_Fusion()\n\n self.conv_low = nn.Conv2d(256, 48, kernel_size=1, stride=1, padding=0)\n self.bn1 = nn.BatchNorm2d(48)\n\n self.conv_cat = nn.Sequential(\n ConvBNReLU(304, 256),\n ConvBNReLU(256, 256)\n )\n\n self.conv_out = nn.Conv2d(256, n_classes, kernel_size=1, bias=False)\n\n self.relu = nn.ReLU(inplace=True)\n\n self.init_weight()\n\n def init_weight(self):\n for ly in self.children():\n if isinstance(ly, nn.Conv2d):\n nn.init.kaiming_normal_(ly.weight, a=1)\n if not ly.bias is None: nn.init.constant_(ly.bias, 0)\n #\n #\n def forward(self, x):\n x1, x2, x3, x4 = self.backbone(x)\n feat = self.featurefusion(x4)\n\n H, W = x1.size()[2:]\n low = self.bn1(self.conv_low(x1))\n feat = F.interpolate(feat, (H, W), mode='bilinear', align_corners=True)\n cat = torch.cat((feat, low), dim=1)\n final = self.conv_cat(cat)\n final = self.conv_out(final)\n\n H, W = x.size()[2:]\n final = F.interpolate(final, (H, W), mode='bilinear', align_corners=True)\n\n return final\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"model/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286358136","text":"print(\"Project Euler-Problem 2\")\r\nprint(\"Fibonacci hesaplama\")\r\na=1\r\nb=1\r\nfibonacci=[a,b]\r\nfor i in range(50):\r\n if a+b<=4000000 :\r\n a,b=b,a+b\r\n fibonacci.append(b) \r\ntoplam=0 \r\nfor i in fibonacci: \r\n if i%2==0:\r\n toplam +=i\r\nprint(toplam)","sub_path":"ProjectEulerProblem_2.py","file_name":"ProjectEulerProblem_2.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553695300","text":"'''\nTema 1 ASC\nDascalu Laurentiu 335CA\n'''\n\nfrom asc_t1_defs import GenericRouter\nfrom asc_t1_defs import GenericConnection\nfrom asc_t1_defs import GenericConnectionManager\nfrom asc_t1_test import SimpleConnectionManager\nfrom asc_t1_defs import DIR_EST, DIR_NORD, DIR_SUD, DIR_VEST \nfrom threading import Lock, Semaphore\nfrom asc_t1_util import barrier\n\n## Variabile globale :\n\n# Lista de routere\nrouters = []\n\n# Lista de conexiuni\nconnections = []\n\n# Lista de manageri\nmanagers = []\n\n# Lista de directii\nDIRS = [DIR_EST, DIR_VEST, DIR_NORD, DIR_SUD]\n\nlock = Lock()\n\n# Numarul de conexiuni\nnConn = 0\n\n# Numarul de routere\nnRtr = 0\n\n# Numarul de conexiuni si routere active pe perioada de timp curenta\nnConnActive = 0\nnRtrActive = 0\n\n# Semafoare pentru sincronizarea routerelor si a conexiunilor\nsemConn = Semaphore(value=0)\nsemRtr = Semaphore(value=0)\n\n# Bariere pentru asigurarea evolutiei procesolor in concordanta cu timpul\nconnBarrier = None\nrtrBarrier = None\n\n\ndef getRouters(numRouters):\n global routers\n routers = [None for i in range(numRouters)]\n for i in range(numRouters):\n routers[i] = MyRouter();\n return routers\n \ndef getConnections(numConnections):\n global connections\n connections = [None for i in range(numConnections)]\n for i in range(numConnections):\n connections[i] = MyConnection();\n return connections\n\ndef getConnManagers(numManagers):\n global managers\n managers = [None for i in range(numManagers)]\n for i in range(numManagers):\n managers[i] = MyConnectionManager();\n return managers\n\ndef nextTimeMoment():\n global semConn, nConn, nConnActive, nRtrActive\n\n nConnActive = nConn\n nRtrActive = nRtr\n \n for i in range(nConn):\n semConn.release()\n \ndef initStuff(NUM_ROUTERS, NUM_CONNECTIONS, NUM_CONN_MANAGERS):\n global nConn, nRtr, nConnActive, nRtrActive, semConn, semRtr, connBarrier, rtrBarrier\n \n nConn = NUM_CONNECTIONS\n nConnActive = NUM_CONNECTIONS\n \n nRtr = NUM_ROUTERS\n nRtrActive = NUM_ROUTERS\n \n for i in range(NUM_CONN_MANAGERS):\n managers[i].init(2 * NUM_ROUTERS)\n for i in range(nConn):\n semConn.release()\n connBarrier = barrier(NUM_CONNECTIONS)\n rtrBarrier = barrier(NUM_ROUTERS)\n\nclass MyRouter(GenericRouter):\n def __init__(self):\n GenericRouter.__init__(self)\n \n # Contine perechi de tipul (directie, referinta la conexiune)\n self.m_conn = dict()\n \n # Contine prechi de tipul (directie, result - indica sensul transferului de mesaje)\n self.m_dir = dict()\n \n # Initialiez conexiunile si sensurile de transfer\n for i in DIRS:\n self.m_conn[i] = None\n self.m_dir[i] = 0\n \n # Liste de mesaje catre Sud-Est, respectiv Nord-Vest\n self.msgListSE = []\n self.msgListNV = []\n \n self.finished = False\n \n # Semafor binar pentru restrictionarea accesului la functia waitUntilEndOfTimeMoment\n # Un mutex era suficient, dar in python nu exista implementarea directa ( din ce stiu eu )\n self.sem = Semaphore(value=0)\n \n def setConnection(self, dir, conn, connManager):\n self.m_conn[dir] = conn\n connManager.manageConnection(conn)\n conn.setManager(connManager)\n \n def waitUntilEndOfTimeMoment(self, stopRunning):\n self.sem.acquire()\n self.finished = stopRunning\n \n # Adaug intr-o lista toate mesajele stocate intern si intorc lista astfel formata\n msgList = []\n \n for msg in self.msgListNV:\n msgList.append(msg)\n \n for msg in self.msgListSE:\n msgList.append(msg)\n \n return msgList\n \n def sendMessage(self, msg):\n if self.m_conn[DIR_NORD] == None and self.m_conn[DIR_VEST] == None:\n self.msgListSE.append(msg)\n if self.m_conn[DIR_SUD] == None and self.m_conn[DIR_EST] == None:\n self.msgListNV.append(msg)\n \n def communicateResult(self, result, connection):\n for i in DIRS:\n if self.m_conn[i] != None:\n if self.m_conn[i].connID == connection.connID:\n self.m_dir[i] = result\n \n def send(self, msgList, dir, DIR):\n for i in range(min([dir, len(msgList)])):\n self.m_conn[DIR].msgList.append(msgList.pop())\n if (self.m_conn[DIR].router[DIR_NORD].routerID == self.routerID):\n self.m_conn[DIR].dir = DIR_EST\n if (self.m_conn[DIR].router[DIR_EST].routerID == self.routerID):\n self.m_conn[DIR].dir = DIR_SUD\n \n def sendMessages(self, msgList, DIR1, DIR2):\n if (len(msgList) == 0):\n return\n else:\n if (self.application != None and self.m_conn[DIR1] == None and self.m_conn[DIR2] == None):\n # Router special\n for i in range(len(msgList)):\n self.application.receivedMessage(msgList.pop())\n else:\n # Se transmit mesajele altor rutere\n if (self.m_dir[DIR1] == 1 and self.m_dir[DIR2] == 1):\n dir1 = self.m_conn[DIR1].maxMessagesPerTimeUnit\n dir2 = self.m_conn[DIR2].maxMessagesPerTimeUnit\n if (dir1 > dir2):\n self.send(msgList, dir1, DIR1)\n self.send(msgList, dir2, DIR2)\n else:\n self.send(msgList, dir2, DIR2)\n self.send(msgList, dir1, DIR1)\n else:\n if (self.m_dir[DIR1] == 1):\n dir1 = self.m_conn[DIR1].maxMessagesPerTimeUnit\n self.send(msgList, dir1, DIR1)\n else:\n if (self.m_dir[DIR2] == 1):\n dir2 = self.m_conn[DIR2].maxMessagesPerTimeUnit\n self.send(msgList, dir2, DIR2)\n \n def run(self):\n while 1:\n global rtrBarrier, semRtr\n \n semRtr.acquire()\n\n # Stabilesc sensurile pe conexiuni\n for i in DIRS:\n if self.m_conn[i] != None:\n if i in [DIR_NORD, DIR_VEST]:\n self.m_conn[i].manager.submitPreference(len(self.msgListNV), self, self.m_conn[i]);\n if i in [DIR_SUD, DIR_EST]:\n self.m_conn[i].manager.submitPreference(len(self.msgListSE), self, self.m_conn[i]);\n \n # Astept ca toate routerele sa termine stabilirea sensurilor\n rtrBarrier.barrier()\n\n # Incep transferul datelor pe conexiuni, in limitele capacitatilor conexiunilor :\n # a) Sud - Est - am date de transmis in sud si/sau in est\n # b) Nord - Vest - am date de transmis in nord si/sau in vest\n \n # Codul este in oglinda, Sud <-> Nord si Est <-> Vest \n self.sendMessages(self.msgListSE, DIR_SUD, DIR_EST)\n self.sendMessages(self.msgListNV, DIR_NORD, DIR_VEST)\n \n # Astept ca toate routerele sa termine de pus pe conexiuni mesaje\n rtrBarrier.barrier()\n \n # Se poate apela waitUntilEndOfTimeMoment\n self.sem.release()\n \n if self.finished:\n break\n #print \"Am terminat \" + self.routerID\n return 0\n\n \nclass MyConnection(GenericConnection):\n def __init__(self):\n GenericConnection.__init__(self)\n self.sem = Semaphore(value=0)\n self.finished = False;\n \n # Lista de mesaje de pe conexiune\n self.msgList = []\n self.manager = None\n \n #Directia in care se trimit mesaje\n self.dir = 0\n \n def setManager(self, manager):\n self.manager = manager\n \n def waitUntilEndOfTimeMoment(self, stopRunning):\n self.sem.acquire()\n self.finished = stopRunning \n return self.msgList\n \n def sendMessage(self, conn, router, msg):\n # Trimit mesajul msg : \n # a) catre routerul din Sud-Est daca acesta a provenit din Nord-Vest\n # b) catre routerul din Nord-Vest daca acesta a provenit din Sud-Est\n for dir in DIRS:\n if (router.m_conn[dir] != None and router.m_conn[dir].connID == conn.connID):\n if dir in [DIR_SUD, DIR_EST]:\n router.msgListNV.append(msg)\n break\n if dir in [DIR_NORD, DIR_VEST]:\n router.msgListSE.append(msg)\n break\n\n def run(self):\n while 1:\n global semConn, semRtr, lock, nConnActive, nRtr\n \n semConn.acquire()\n \n __dir = 0\n if self.dir == 1:\n __dir = 1\n\n # Calculez directia de trimitere a mesajului si forwardez mesajele in directia corespunzatoare\n while(len(self.msgList) > 0):\n self.sendMessage(self, self.router[__dir], self.msgList.pop())\n \n lock.acquire()\n # Conexiunea curenta si-a terminat activitatea\n nConnActive -= 1\n lock.release()\n \n # Astept toate conexiunile sa termine de transmis mesajele din coada\n connBarrier.barrier()\n \n # Daca conexiunile au terminat treaba atunci prima conexiune da drumul routerelor sa lucreze\n if nConnActive == 0 and self.connID == \"conn-1\":\n for i in range(nRtr):\n semRtr.release()\n \n # Se poate apela waitUntilEndOfTimeMoment\n self.sem.release()\n \n if self.finished:\n break\n return 0\n\n# Clasa care manageriaza conexiunile; structura este inspirata din SimpleConnectionManager\nclass MyConnectionManager(GenericConnectionManager):\n def __init__(self):\n GenericConnectionManager.__init__(self)\n self.managedConnections = []\n \n # Liste de rutere si preferinte de la primul capat al conexiunilor\n self.routers1 = None\n self.prefs1 = None\n \n # Liste de rutere si preferinte de la al doilea capat al conexiunilor\n self.routers2 = None\n self.prefs2 = None\n \n self.dataLock = Lock()\n \n def init(self, routersNumber):\n # Primul capat al conexiunii\n self.routers1 = [None for i in range(routersNumber)]\n self.prefs1 = [0 for i in range(routersNumber)]\n \n # Al doilea capat al conexiunii\n self.routers2 = [None for i in range(routersNumber)]\n self.prefs2 = [0 for i in range(routersNumber)]\n \n def manageConnection(self, conn):\n self.managedConnections.append(conn)\n \n def submitPreference(self, preferenceValue, router, connection):\n # se verifica apartenta conexiunii la lista de conexiuni gestionate\n valid = False\n for conn in self.managedConnections:\n if conn.connID == connection.connID:\n valid = True\n break\n \n # Conexiunea nu este manageriata de aceasta instanta\n if (valid == False):\n return\n \n # Incep zona critica\n self.dataLock.acquire()\n \n # Calculez id-ul conexiunii ( dupa numele thread-ului )\n id = int(conn.connID[5:])\n \n if (self.routers1[id] != None):\n # Ambele routere si-au trimis preferinta; aleg preferinta maxima\n self.routers2[id] = router\n self.prefs2[id] = preferenceValue\n result = 1\n \n if (self.prefs1[id] < self.prefs2[id]):\n result = - 1\n \n # Comunic rezultatul routerelor\n self.routers1[id].communicateResult(result, connection)\n self.routers2[id].communicateResult(-result, connection)\n \n # Resetez punctele de extrem ale conexiunii\n self.routers1[id] = None\n self.prefs1[id] = 0\n self.routers2[id] = None\n self.prefs2[id] = 0\n else:\n self.routers1[id] = router\n self.prefs1[id] = preferenceValue\n \n self.dataLock.release()\n","sub_path":"ComputingSystemsArchitecture/Tema1/Cod/src/asc_t1.py","file_name":"asc_t1.py","file_ext":"py","file_size_in_byte":12455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"481253746","text":"####################\n# ES-DOC CIM Questionnaire\n# Copyright (c) 2016 ES-DOC. All rights reserved.\n#\n# University of Colorado, Boulder\n# http://cires.colorado.edu/\n#\n# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].\n####################\n\n__author__ = \"allyn.treshansky\"\n\n\"\"\"\n.. module:: test_api_projects\n\n\"\"\"\n\nfrom rest_framework.test import APIRequestFactory, APIClient\nimport json\n\nfrom Q.questionnaire.tests.test_base import TestQBase, create_project\nfrom Q.questionnaire.q_constants import *\n\n\nclass Test(TestQBase):\n\n def setUp(self):\n\n # override some parent attributes w/ API-specific factory...\n self.factory = APIRequestFactory()\n self.client = APIClient()\n\n # no need to call the parent stuff\n # super(Test, self).setUp()\n\n def tearDown(self):\n pass\n\n # no need to call the parent stuff...\n # super(Test, self).tearDown()\n\n #########\n # tests #\n #########\n\n def test_api_get(self):\n\n self.test_project = create_project(\n name=\"test_project\",\n title=\"Test Project\",\n email=\"allyn.treshansky@noaa.gov\",\n )\n\n response = self.client.get(\n \"/api/projects/?is_active=true&is_displayed=true&ordering=title\"\n )\n self.assertEqual(response.status_code, 200)\n\n content = json.loads(response.content)\n self.assertDictEqual(\n content,\n {\n \"count\": 1,\n \"next\": None,\n \"previous\": None,\n \"results\": [\n {\n \"id\": 1,\n \"name\": \"test_project\",\n \"title\": \"Test Project\",\n \"description\": \"\",\n \"email\": \"allyn.treshansky@noaa.gov\",\n \"url\": \"\",\n \"is_active\": True,\n \"is_displayed\": True,\n \"authenticated\": True,\n \"ontologies\": []\n }\n ]\n }\n )\n\n\n","sub_path":"Q/questionnaire/tests/tests_api/test_api_projects.py","file_name":"test_api_projects.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96309974","text":"count = 0\r\ntotal = 0\r\narr = []\r\n\r\nwhile True:\r\n try:\r\n item = input(\"\\nEnter a number > \")\r\n if item == 'done':\r\n break\r\n arr.append(int(item))\r\n\r\n except ValueError:\r\n print('Invalid Input')\r\n\t\t\r\nfor itervar in arr:\r\n count = count + 1\r\n total = total + itervar\r\nprint('Total: ', total)\r\nprint('Count: ', count)\r\nprint('Average: ', total/count)\r\n\r\n \r\n\r\n\r\n","sub_path":"ch4_exc_1_LIST_VERSION.py","file_name":"ch4_exc_1_LIST_VERSION.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"609149921","text":"# from google.colab import drive\r\n# drive.mount('/content/gdrive')\r\n\r\n# root_path = 'gdrive/My Drive/week.02'\r\nroot_path = '.'\r\n\r\nimport time\r\n#from BaseLine\r\nimport os\r\nimport json\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport sklearn.svm as svm\r\nimport sklearn.tree as tree\r\nimport sklearn.ensemble as ensemble\r\nimport sklearn.neighbors as neighbors\r\nimport sklearn.naive_bayes as naive_bayes\r\nimport sklearn.linear_model as linear_model\r\n\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn import preprocessing as preproc\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.feature_selection import SelectKBest, f_classif\r\nfrom sklearn.metrics import accuracy_score, log_loss, mean_squared_error, mean_absolute_error\r\n\r\n#from Wan\r\nimport shutil\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nimport random\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.feature_selection import VarianceThreshold\r\nfrom sklearn.exceptions import DataConversionWarning\r\nimport warnings\r\nfrom traitlets.config.configurable import Configurable\r\nwarnings.filterwarnings(action='ignore', category=DataConversionWarning)\r\n# sol 3\r\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\r\n\r\n#from Valerie\r\n#sol 2\r\nimport xgboost as xgb\r\nfrom xgboost import XGBClassifier\r\n#sol 4\r\nfrom sklearn.ensemble import GradientBoostingClassifier,GradientBoostingRegressor \r\nfrom sklearn.model_selection import cross_validate\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.metrics import mean_squared_log_error,r2_score \r\n#sol 6\r\nimport sklearn\r\nfrom sklearn.ensemble import ExtraTreesClassifier\r\nfrom sklearn.feature_selection import SelectFromModel\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom keras import Sequential\r\nfrom keras.layers import Dense\r\n#sol 8\r\nfrom sklearn.feature_selection import SelectKBest \r\nfrom sklearn.feature_selection import chi2 \r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.metrics import roc_auc_score\r\n###########################################################\r\ndef ObjColConvertToDigit(train_df, numericColList):\r\n delRowList = []\r\n\r\n for col in numericColList:\r\n if(train_df[col].dtype == \"object\"):\r\n for i, cell in enumerate(train_df[col]):\r\n if(cell.replace('.', '').isdigit() == False):\r\n delRowList.append(i)\r\n\r\n train_df = train_df.drop(train_df.index[delRowList])\r\n\r\n return train_df\r\n###############\r\ndef columnToList(columns):\r\n columns = columns.tolist()[0].replace(\"[\", \"\").replace(\"]\", \"\").split(\";\")\r\n tempList = []\r\n columnList = []\r\n for i, cell in enumerate(columns): \r\n tempList.append(cell)\r\n if i % 3 == 2:\r\n columnList.append(tempList)\r\n tempList = newListClass.newList()\r\n\r\n numeric_columns = [x[1] for x in columnList if x[2]=='numeric' or x[2]=='real' or x[2]=='integer' or x[2] =='numerical' in x ]\r\n categorical_columns = [x[1] for x in columnList if x[2] == 'categorical' in x ]\r\n datetime_columns = [x[1] for x in columnList if x[2] == 'datetime' or x[2] == 'dateTime' in x ]\r\n unwanted_columns = [x[1] for x in columnList if x[2] == 'unwanted' or x[2] == 'string' in x ]\r\n columNameTarget = [x[1] for x in columnList if x[2] == 'target' in x ] \r\n\r\n return columnList, columns, numeric_columns, categorical_columns , datetime_columns, unwanted_columns, columNameTarget\r\n###############\r\ndef parseMetaData(rowFilePath):\r\n # print(rowFilePath)\r\n data = pd.read_csv(rowFilePath, header = 0, delimiter = ',')\r\n pd.set_option(\"display.max_colwidth\", 10000)\r\n\r\n # print(rowFilePath + \"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\r\n\r\n #check data\r\n # for i, col in enumerate(data.columns.values):\r\n # print(i+1, \" \", col, \"-> \", data[col].to_string().replace('0 ', '')) \r\n\r\n # #Assign strings to metadata\r\n tab = '0 '\r\n competition_name = data['name'].to_string().replace(tab,'')\r\n columnList, columns, numeric_columns, categorical_columns, datetime_columns, unwanted_columns, columNameTarget = columnToList(data['columns'])\r\n metric = data['performanceMetric'].to_string().replace(tab,'')\r\n prepro_function_call = data['preprocessing function call'].to_string().replace(tab,'')\r\n feature_selector_type = data['featureSelector'].to_string().replace(tab,'')\r\n feature_selector = data['featureSelector function call'].to_string().replace(tab,'')\r\n estimator_type = data['estimator1'].to_string().replace(tab,'')\r\n estimator = data['estimator1 function call'].to_string().replace(tab,'')\r\n estimator2 = data['estimator2 function call'].to_string().replace(tab,'')\r\n target_column = data['targetName'].to_string().replace(tab,'')\r\n output_type = data['outputType'].to_string().replace(tab,'')\r\n output_type = output_type.split(',')\r\n\r\n if len(columNameTarget ) == 0:\r\n target_column = data['targetName'].to_string().replace(tab,'')\r\n else:\r\n target_column = columNameTarget[0]\r\n\r\n ##check if unwanted column has target_column\r\n removeStr = \"\"\r\n for i, ele in enumerate(unwanted_columns):\r\n ele = ele.replace(' ', '')\r\n if ele == target_column.replace(' ', ''):\r\n removeStr = ele\r\n if(removeStr != \"\"):\r\n unwanted_columns.remove(removeStr)\r\n\r\n my_dict = {'competition_name': competition_name, 'columns':columns, 'metric':metric,\r\n 'prepro_function_call':prepro_function_call, 'feature_selector':feature_selector,\r\n 'feature_selector_type':feature_selector_type, 'estimator_type':estimator_type,\r\n 'estimator':estimator, 'estimator2':estimator2, 'target_column':target_column, 'output_type':output_type,\r\n 'numeric_columns':numeric_columns, 'categorical_columns':categorical_columns,\r\n 'datetime_columns':datetime_columns, 'unwanted_columns':unwanted_columns} \r\n\r\n\r\n return my_dict \r\n####################\r\nclass newListClass():\r\n def newList():\r\n newList = []\r\n return newList\r\n#####################\r\ndef dataAugmentation(X, y):\r\n tempX = pd.DataFrame()\r\n tempX = tempX.append(X, ignore_index = True)\r\n\r\n newYList = y.tolist()\r\n\r\n for i, col in enumerate(X.columns.values):\r\n qNumeric = col in metaDic['numeric_columns'] \r\n qCate = col in metaDic['categorical_columns']\r\n if qNumeric == True and qCate == False:\r\n for j in range(X[col].shape[0]):\r\n tempX.loc[j, col] = X[col][j]*(1+random.randint(-50, 50)*0.001)\r\n\r\n\r\n X = X.append(tempX, ignore_index=True)\r\n # X = X.concat([X, tempX], axis=0, ignore_index=True)\r\n y = y.append(y, ignore_index=True)\r\n\r\n return X, y\r\n########################\r\ndef auxillaryDataAugmentation(X, y):\r\n # # read Data\r\n # auxDataPath = \"./\" + \"house-prices-advanced-regression-techniques\" + \"/data/train.csv\"\r\n auxDataPath =\"./\" + metaDic['competition_name'] + \"/data/auxTrain.csv\"\r\n auxData = pd.read_csv(auxDataPath, parse_dates = [1])\r\n # print(auxData.head())\r\n\r\n #X column selection for auxillary data\r\n newColList = [\"LotArea\"]\r\n auxDataX = auxData.loc[:, newColList]\r\n auxDataX.rename(columns={'LotArea':'area_m'}, inplace=True)\r\n\r\n #y column selection for auxillary data\r\n auxYList = auxData.loc[:, ['SalePrice']]\r\n auxYList.rename(columns={'SalePrice': 'price_doc'}, inplace=True)\r\n\r\n #column selection for X\r\n selectedX = X.loc[:, ['area_m']]\r\n\r\n # combine original X with auxillary data\r\n combinedX = selectedX.append(auxDataX, ignore_index=True)\r\n # print(combinedX.shape) \r\n \r\n # #join original Y with auxillary y\r\n joinedY = pd.concat([y, auxYList['price_doc']])\r\n\r\n return X, y\r\n#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\ndef preprocess(train_df):\r\n # drop rows which has string in numeric column \r\n train_df = ObjColConvertToDigit(train_df, metaDic['numeric_columns'])\r\n\r\n # drop unwanted columns\r\n if len(metaDic['unwanted_columns']) > 0:\r\n train_df.drop(metaDic['unwanted_columns'], axis=1, inplace=True)\r\n\r\n X = train_df.drop(metaDic['target_column'], 1)\r\n y = train_df[metaDic['target_column']]\r\n\r\n #auxillary Data augmentation\r\n if dataRootStr.find(\"russian-housing-\") >= 0:\r\n X, y = auxillaryDataAugmentation(X, y)\r\n\r\n X, y = feature_extraction(X, y, train_df)\r\n\r\n if dataRootStr.find(\"restaurant-revenue-prediction\") >= 0 or dataRootStr.find(\"bike\") >= 0:\r\n X, y = dataAugmentation(X, y)\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(X, y)\r\n\r\n return X_train, X_test, y_train, y_test\r\n\r\n######################################################################################\r\ndef feature_extraction(X, y, train_df): \r\n # treat missing values\r\n pd.set_option('mode.chained_assignment', None) # used to subside the panda's chain assignment warning\r\n imp = SimpleImputer(missing_values=np.nan, strategy='mean')\r\n X_numeric_colums = metaDic['numeric_columns']\r\n if metaDic['target_column'] in X_numeric_colums:\r\n X_numeric_colums.remove(metaDic['target_column']) \r\n for col in X_numeric_colums:\r\n X [[col]]= imp.fit_transform(X[[col]])\r\n\r\n #handle categorical target \r\n if metaDic['target_column'] in metaDic['categorical_columns']:\r\n col_dummies = pd.get_dummies(train_df[metaDic['target_column']], prefix=col)\r\n y = pd.concat([y, col_dummies], axis=1)\r\n y.drop(metaDic['target_column'], axis=1, inplace=True) \r\n\r\n # Categorial transform \r\n X_categorical_columns = metaDic['categorical_columns']\r\n if metaDic['target_column'] in X_categorical_columns:\r\n X_categorical_columns.remove(metaDic['target_column'])\r\n for col in X_categorical_columns:\r\n col_dummies = pd.get_dummies(X[col], dummy_na=True)\r\n X = pd.concat([X, col_dummies], axis=1)\r\n \r\n # drop float column in Categorical Column\r\n floatColInCat = \"\" \r\n for col in X_categorical_columns:\r\n Xcol = X[col]\r\n if(Xcol.dtype == 'float64' ):\r\n floatColInCat = col\r\n\r\n if floatColInCat != \"\":\r\n X.drop(floatColInCat, axis=1, inplace=True)\r\n\r\n dropThresh = int(X.shape[0]*0.01)\r\n X.dropna(axis=1, how='any')\r\n\r\n le = preprocessing.LabelEncoder()\r\n X = X.apply(le.fit_transform)\r\n\r\n #Transform datetime\r\n X_datetime_columns = metaDic['datetime_columns']\r\n for col in X_datetime_columns:\r\n X[\"hour\"] = [t.hour for t in pd.DatetimeIndex(X[col])] \r\n X[\"day\"] = [t.dayofweek for t in pd.DatetimeIndex(X[col])]\r\n X[\"month\"] = [t.month for t in pd.DatetimeIndex(X[col])]\r\n X['year'] = [t.year for t in pd.DatetimeIndex(X[col])]\r\n X.drop(col, axis=1, inplace=True)\r\n\r\n # Feature normalization\r\n if len(metaDic['numeric_columns']) > 0:\r\n X[X_numeric_colums] = preproc.scale(X[X_numeric_colums])\r\n\r\n # print to screen\r\n print(\"************************************************************\")\r\n print(metaDic['competition_name'])\r\n print(X_numeric_colums)\r\n # print(metaDic['string_columns'])\r\n print(metaDic['datetime_columns'])\r\n print(metaDic['categorical_columns'])\r\n print(metaDic['target_column'])\r\n print(metaDic['metric'])\r\n print(metaDic['feature_selector'])\r\n print(metaDic['estimator'])\r\n\r\n return X, y\r\n\r\n#######################################################################################\r\ndef feature_selection(X_train, X_test, y_train, y_test):\r\n\r\n metaDic['feature_selector'] = metaDic['feature_selector'].replace(' ',',')\r\n function = metaDic['feature_selector']\r\n selector = metaDic['feature_selector_type']\r\n\r\n model = eval(function)\r\n model.fit(X_train, y_train)\r\n\r\n if selector == \"selectkbest\": #CODE 8\r\n X_train = model.transform(X_train)\r\n X_test = model.transform(X_test)\r\n else:\r\n pass\r\n \r\n return X_train, X_test, y_train, y_test \r\n##############################################################################################\r\ndef estimation(X_train, X_test, y_train, y_test):\r\n estimator = metaDic['estimator'].replace(' ', ', ' )\r\n estimator2 = metaDic['estimator2'].replace(' ', ', ' )\r\n\r\n if(estimator == \"NONE\") :\r\n estimator = estimator2\r\n \r\n print(\"estimator====\", estimator)\r\n model = eval(estimator)\r\n\r\n if (metaDic['estimator_type'] == 'nn'):\r\n model.compile(optimizer ='adam',loss='binary_crossentropy', metrics =['accuracy'])\r\n\r\n model.fit(X_train, y_train)\r\n predict = model.predict(X_test)\r\n\r\n error = \"Nothing\"\r\n print(metaDic['metric'])\r\n print(metaDic['estimator_type'])\r\n\r\n # print(y_test)\r\n if metaDic['metric'] == \"rmse\":\r\n error = np.sqrt(mean_squared_error(y_test, predict))\r\n elif metaDic['metric'] == 'mse':\r\n error = mean_squared_error(y_test, predict)\r\n elif metaDic['metric'] == \"accuracy\":\r\n if (metaDic['estimator_type'] == 'nn'):\r\n predict = (predict > 0.5) \r\n elif (metaDic['estimator_type'] == 'RandomForestRegressor'):\r\n predict = (predict > 0.5) \r\n error = accuracy_score(y_test, predict)\r\n elif metaDic['metric'] == \"auc\":\r\n fpr, tpr, _ = roc_curve(y_test, predict)\r\n error = auc(fpr, tpr)\r\n #elif metaDic['metric'] == 'cross_val_score':\r\n #error = cross_val_score(model, X_test, predict, cv=2)\r\n elif metaDic['metric'] == 'gini':\r\n error = Gini(y_test, predict)\r\n elif metaDic['metric'] == 'logloss':\r\n probs = model.predict_proba(X_test)\r\n error = log_loss(y_test, probs)\r\n elif metaDic['metric'] == 'rmsle':\r\n error = np.sqrt(np.mean((np.log(predict) - np.log(1+y_test))**2))\r\n else:\r\n pass\r\n\r\n print(metaDic['metric'] + \" --------------> \", error)\r\n\r\n####################################################################\r\ndef postprocessing(y_estimation, postProcessNum):\r\n pass\r\n##########################################################\r\ndef Gini(y_true, y_pred):\r\n # print(y_true)\r\n # check and get number of samples\r\n assert y_true.shape == y_pred.shape\r\n n_samples = y_true.shape[0]\r\n\r\n # sort rows on prediction column \r\n # (from largest to smallest)\r\n arr = np.array([y_true, y_pred]).transpose()\r\n true_order = arr[arr[:,0].argsort()][::-1,0]\r\n pred_order = arr[arr[:,1].argsort()][::-1,0]\r\n\r\n # print(type(true_order))\r\n true_order = true_order.astype(np.float)\r\n pred_order = pred_order.astype(np.float)\r\n\r\n # get Lorenz curves\r\n L_true = np.cumsum(true_order) / np.sum(true_order)\r\n L_pred = np.cumsum(pred_order) / np.sum(pred_order)\r\n L_ones = np.linspace(1/n_samples, 1, n_samples)\r\n\r\n # get Gini coefficients (area between curves)\r\n G_true = np.sum(L_ones - L_true)\r\n G_pred = np.sum(L_ones - L_pred)\r\n\r\n # normalize to true Gini coefficient\r\n return G_pred/G_true\r\n#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\nstartTime1 = time.time()\r\n\r\n# read row.csv file\r\nrowFilePaths =[]\r\nfor root, dirs, files in os.walk(\".\", topdown=False):\r\n for FileName in files:\r\n dirFileName = os.path.join(root, FileName)\r\n if(dirFileName.find(\"submission\") > 0 and dirFileName.find(\"row\") > 0):\r\n # print(dirFileName)\r\n rowFilePaths.append(dirFileName)\r\n\r\n# rowFilePaths = [rowFilePaths[0]] #Russ\r\n# print(\"======>\",rowFilePaths) \r\n\r\ndataRootStr = \"\"\r\nfor rowFilePath in rowFilePaths:\r\n startTime = time.time()\r\n # print(\"======>\",rowFilePath)\r\n metaDic = parseMetaData(rowFilePath)\r\n # print(metaDic['metric'])\r\n dataRootStr = \"./\" + metaDic['competition_name'] + \"/data/\"\r\n # print(dataRootStr)\r\n trainData = pd.read_csv(dataRootStr + \"train.csv\", parse_dates = [1])\r\n # print(trainData)\r\n\r\n X_train, X_test, y_train, y_test = preprocess(trainData)\r\n\r\n if metaDic['feature_selector'] != \"NONE\" :\r\n X_train, X_test, y_train, y_test = feature_selection(X_train, X_test, y_train, y_test)\r\n # X_train, X_test, y_train, y_test = feature_selection(X_train, X_test, y_train, y_test)\r\n\r\n estimation(X_train, X_test, y_train, y_test)\r\n \r\n endTime = time.time()\r\n print(\"execution duration->\", endTime - startTime)\r\n\r\nendTime1 = time.time()\r\nprint(\"Total execution duration->\", endTime1 - startTime1)\r\n \r\n","sub_path":"val_Wan/code/pipeline.05.08.py","file_name":"pipeline.05.08.py","file_ext":"py","file_size_in_byte":16252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"464875600","text":"import sys\nimport numpy as np\n\n\ndef main():\n a = int(sys.argv[1])\n # 底に並ぶ個数を計算\n aa = 2*a-1\n\n result = []\n\n for i in range(1, a+1):\n # アスタリスクの個数を計算\n an = 2*i-1\n # 片側のスペースの個数を計算\n bn = int((aa-an)/2)\n\n # 片側のスペースを個数分並べる\n base1 = [' ']*bn\n # アスタリスクを個数分並べる\n base2 = ['*']*an\n\n # アスタリスクをスペースで挟む\n line = base1+base2+base1\n result.append([line])\n\n # 表示を整える\n for results in result:\n for resultss in results:\n print(*resultss)\n\n\nif __name__ == '__main__':\n main()","sub_path":"3-3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"19865630","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, api, _\nfrom openerp.exceptions import ValidationError\n\n\nclass ResInvestAsset(models.Model):\n _inherit = 'res.invest.asset'\n\n @api.model\n def create(self, vals):\n # For asset code on create\n if not vals.get('fiscalyear_id', False):\n raise ValidationError(_('No fiscalyear for this invest asset!'))\n ctx = {'fiscalyear_id': vals['fiscalyear_id']}\n Seq = self.env['ir.sequence']\n vals['code'] = Seq.with_context(ctx).next_by_code('invest.asset')\n return super(ResInvestAsset, self).create(vals)\n","sub_path":"pabi_budget_plan/models/res_invest_asset.py","file_name":"res_invest_asset.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"574706238","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\nimport math\nimport torch\nfrom torch import nn\nfrom .base import MIN_SCORE, PositionwiseFeedForward\n\n\nclass GlobalAttention(nn.Module):\n def __init__(self, dropout=0.3):\n super(GlobalAttention, self).__init__()\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, query, key, value, mask=None):\n \"Compute 'Scaled Dot Product Attention'\"\n head_dim = query.size(-1)\n attention_scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(head_dim)\n if mask is not None:\n mask = mask.unsqueeze(-2)\n attention_scores = attention_scores.masked_fill(mask == 0, MIN_SCORE)\n attention_probs = self.dropout(attention_scores.softmax(-1))\n return torch.matmul(attention_probs, value), attention_probs\n\n\nclass LocalAttention(nn.Module):\n def __init__(self, window_size, dropout=0.3):\n super(LocalAttention, self).__init__()\n assert window_size % 2 == 1\n self.window_size = window_size\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, query, key, value, mask):\n '''\n :param query: FloatTensor(*, seq_len, dim)\n :param key: FloatTensor(*, seq_len, dim)\n :param value: FloatTensor(*, seq_len, dim)\n :param mask: ByteTensor(*, seq_len)\n :return:\n '''\n value_size = value.size()\n seq_len, dim = value_size[-2:]\n query = query.contiguous().view(-1, seq_len, dim)\n key = key.contiguous().view(-1, seq_len, dim)\n value = value.contiguous().view(-1, seq_len, dim)\n mask = mask.contiguous().view(-1, seq_len)\n\n half = min(self.window_size//2, seq_len//2)\n\n scores = []\n for offset in range(-half, half+1, 1):\n if offset < 0:\n w = (query[:, -offset:] * key[:, :offset]).sum(-1).masked_fill(mask[:, :offset], MIN_SCORE)\n w = torch.cat([w.new_full((w.size(0), -offset), MIN_SCORE), w], dim=-1)\n elif offset == 0:\n w = (query * key).sum(-1).masked_fill(mask, MIN_SCORE)\n else:\n w = (query[:, :-offset] * key[:, offset:]).sum(-1).masked_fill(mask[:, offset:], MIN_SCORE)\n w = torch.cat([w, w.new_full((w.size(0), offset), MIN_SCORE)], dim=-1)\n scores.append(w)\n\n probs = self.dropout(torch.stack(scores, dim=-1).softmax(-1))\n\n new_value = value.new_zeros(value.size())\n\n for offset in range(-half, half+1, 1):\n if offset < 0:\n new_value[:, -offset:] += probs[:, -offset:, offset+half:offset+half+1] * value[:, :offset]\n elif offset == 0:\n new_value += probs[:, :, half:half+1] * value\n else:\n new_value[:, :-offset] += probs[:, :-offset, offset+half:offset+half+1] * value[:, offset:]\n\n return new_value, probs\n\n\nclass MultiHeadedAttention(nn.Module):\n def __init__(self, num_head, hidden_dim, atten_window_size=None, dropout=0.3):\n \"Take in model size and number of heads.\"\n super(MultiHeadedAttention, self).__init__()\n assert hidden_dim % num_head == 0\n # We assume d_v always equals d_k\n self.head_dim = hidden_dim // num_head\n self.num_head = num_head\n self.query_layer = nn.Linear(hidden_dim, hidden_dim)\n self.key_value = nn.Linear(hidden_dim, hidden_dim)\n self.value_layer = nn.Linear(hidden_dim, hidden_dim)\n self.attention = GlobalAttention(dropout) if atten_window_size is None or atten_window_size < 0 \\\n else LocalAttention(atten_window_size, dropout)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n for child in self.children():\n if isinstance(child, nn.Linear):\n nn.init.xavier_normal_(child.weight)\n\n def forward(self, query, key, value, mask=None, batch_first=True):\n if batch_first is False:\n query = query.transpose(0, 1)\n key = key.transpose(0, 1)\n value = value.transpose(0, 1)\n mask = mask.transpose(0, 1) if mask is not None else None\n\n if mask is not None:\n # Same mask applied to all h heads.\n mask = mask.unsqueeze(1).expand(mask.size(0), self.num_head, mask.size(1))\n\n # 1) Do all the linear projections in batch from hidden_dim => num_head x head_dim\n query = self._split_head(self.query_layer(query))\n key = self._split_head(self.key_value(key))\n value = self._split_head(self.value_layer(value))\n\n # 2) Apply attention on all the projected vectors in batch.\n value, attention_weights = self.attention(query, key, value, mask=mask)\n\n # 3) \"Concat\" using a view and apply a final linear.\n value = self._concat_head(value)\n\n if batch_first is False:\n value = value.transpose(0, 1)\n\n return value\n\n def _split_head(self, input):\n batch_size, seq_len, dim = input.size()\n return input.view(batch_size, seq_len, self.num_head, self.head_dim).transpose(1, 2)\n\n def _concat_head(self, input):\n batch_size, head_size, seq_len, head_dim = input.size()\n assert head_size == self.num_head\n assert head_dim == self.head_dim\n return input.transpose(1, 2).contiguous().view(batch_size, seq_len, self.num_head * self.head_dim)\n\n\nclass TransformerLayer(nn.Module):\n \"\"\"\n attention -> add & norm -> PositionwiseFeedForward\n Note for code simplicity the norm is first as opposed to last.\n \"\"\"\n def __init__(self, size, num_heads, dropout=0.3):\n super(TransformerLayer, self).__init__()\n self.output_linear = nn.Linear(size, size)\n self.norm = nn.LayerNorm(size)\n self.dropout = nn.Dropout(dropout)\n\n self.atten = MultiHeadedAttention(num_heads, size, dropout=dropout)\n\n self.ffn = PositionwiseFeedForward(size, dropout=dropout)\n\n def forward(self, input, mask=None, batch_first=False):\n atten_output = self.atten(input, input, input, mask, batch_first)\n atten_output = self.output_linear(atten_output)\n return self.ffn(self.norm(input + self.dropout(atten_output)))","sub_path":"task/pretrained/transformer/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236610711","text":"import unittest\nfrom deco import *\n\n@concurrent\ndef kwarg_func(kwarg = None):\n kwarg[0] = \"kwarged\"\n return kwarg\n\nclass TestAST(unittest.TestCase):\n\n def test_kwargs(self):\n list_ = [0]\n kwarg_func(kwarg = list_)\n kwarg_func.wait()\n self.assertEqual(list_[0], \"kwarged\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/testconc.py","file_name":"testconc.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444000106","text":"from zds_client.schema import get_operation_url\nfrom zgw_consumers.client import ZGWClient\n\nfrom bptl.tasks.base import BaseTask, check_variable\nfrom bptl.tasks.models import TaskMapping\nfrom bptl.tasks.registry import register\n\n\ndef get_client(task: BaseTask, alias: str = \"kownsl\") -> ZGWClient:\n default_services = TaskMapping.objects.get(\n topic_name=task.topic_name\n ).defaultservice_set.select_related(\"service\")\n services_by_alias = {svc.alias: svc.service for svc in default_services}\n if alias not in services_by_alias:\n raise RuntimeError(f\"Service alias '{alias}' not found.\")\n\n client = services_by_alias[alias].build_client()\n client._log.task = task\n\n return client\n\n\n@register\ndef finalize_review_request(task: BaseTask) -> dict:\n \"\"\"\n Update a review request in Kownsl.\n\n Review requests can be requests for advice or approval. This tasks registers the\n case used for the actual review with the review request, and derives the frontend\n URL for end-users where they can submit their review.\n\n In the task binding, the service with alias ``kownsl`` must be connected, so that\n this task knows which endpoints to contact.\n\n **Required process variables**\n\n * ``reviewRequestId``: the identifier of the Kowns review request, used to update\n the object in the API.\n * ``zaakUrl``: URL reference to the zaak used for the review itself.\n\n **Sets the process variables**\n\n * ``doReviewUrl``: the frontend URL that reviewers visit to submit the review\n\n \"\"\"\n variables = task.get_variables()\n\n request_id = check_variable(variables, \"reviewRequestId\")\n zaak_url = check_variable(variables, \"zaakUrl\")\n\n client = get_client(task)\n\n resp_data = client.partial_update(\n \"reviewrequest\", data={\"review_zaak\": zaak_url}, uuid=request_id,\n )\n\n return {\n \"doReviewUrl\": resp_data[\"frontend_url\"],\n }\n\n\n@register\ndef get_approval_status(task: BaseTask) -> dict:\n \"\"\"\n Get the result of an approval review request.\n\n Once all reviewers have submitted their approval or rejection, derive the end-result\n from the review session. If all reviewers approve, the result is positive. If any\n rejections are present, the result is negative.\n\n In the task binding, the service with alias ``kownsl`` must be connected, so that\n this task knows which endpoints to contact.\n\n **Required process variables**\n\n * ``reviewRequestId``: the identifier of the Kowns review request, used to update\n the object in the API.\n * ``zaakUrl``: URL reference to the zaak used for the review itself.\n\n **Sets the process variables**\n\n * ``approvalResult``: a JSON-object containing meta-data about the result:\n\n .. code-block:: json\n\n {\n \"approved\": true,\n \"num_approved\": 3,\n \"num_rejected\": 0\n }\n \"\"\"\n client = get_client(task)\n variables = task.get_variables()\n\n # TODO: switch from zaak-based retrieval to review-request based\n zaak_url = check_variable(variables, \"zaakUrl\")\n check_variable(variables, \"reviewRequestId\")\n\n operation_id = \"approvalcollection_retrieve\"\n url = get_operation_url(client.schema, operation_id, base_url=client.base_url)\n\n params = {\"objectUrl\": zaak_url}\n approval_collection = client.request(\n url, operation_id, request_kwargs={\"params\": params},\n )\n\n num_approved = 0\n num_rejected = 0\n for approval in approval_collection[\"approvals\"]:\n if approval[\"approved\"]:\n num_approved += 1\n else:\n num_rejected += 1\n\n return {\n \"approvalResult\": {\n \"approved\": num_approved > 0 and num_rejected == 0,\n \"num_approved\": num_approved,\n \"num_rejected\": num_rejected,\n },\n }\n","sub_path":"src/bptl/work_units/kownsl/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"630447575","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[ ]:\n\n\ndf=pd.read_csv(\"C:\\\\Users\\\\preetham\\\\Desktop\\\\SIH_Datasets\\\\WFT_SUV_City1_R1_.csv\")\n\n\n# In[ ]:\n\n\ndf.shape\n\n\n# In[ ]:\n\n\ndf.head()\n\n\n# In[ ]:\n\n\nfrom sklearn.preprocessing import StandardScaler\n\n\n# In[ ]:\n\n\nnormalizedata=df\n\n\n# In[ ]:\n\n\nX=df[[ 'Veh_Speed', 'CS_RR', 'CS_RL', 'ARB_R', 'AXLE_RR_Z',\n 'AXLE_RL_Z', 'RR_Mz', 'RR_Mx', 'RR_Fz', 'RR_Fy', 'RL_Mz', 'RL_Fz',\n 'RRA_Z', 'RLA_Z', 'CG_X', 'CG_Y', 'CG_Z', 'pca1', 'pca2',\n 'pca3']]\nY=df['cluster']\n\n\n# In[ ]:\n\n\ndef Normalization(num):\n normalizedata[X.columns[i]]=StandardScaler().fit_transform(df[X.columns[i]].values.reshape(-1,1))\nfor i in range(0,20):\n Normalization(i)\n\n\n# In[ ]:\n\n\nfrom sklearn.cluster import KMeans\n\n\n# In[ ]:\n\n\nkmeans =KMeans(n_clusters=2)\n\n\n# In[ ]:\n\n\nkmeans.fit(normalizedata)\n\n\n# In[ ]:\n\n\ncount1=0\ncount2=0\nfor i in kmeans.labels_:\n if i==1:\n count1=count1+1\n else:\n count2=count2+1\n \n\n\n# In[ ]:\n\n\nimport seaborn as sn\nk=list()\nfor i in kmeans.labels_:\n k.append(i)\nk=pd.DataFrame(k,columns=[\"clusters\"])\n\n\n# In[ ]:\n\n\nsn.distplot(k[\"clusters\"],kde=False,color=\"red\")\n\n\n# In[ ]:\n\n\ncount1\n\n\n# In[ ]:\n\n\ncount2\n\n\n# In[ ]:\n\n\ncount1+count2\n\n\n# In[ ]:\n\n\nimport numpy as np\nclusters=kmeans.fit_predict(df)\n\n\n# In[ ]:\n\n\ncluster_0=np.where(clusters==0 )\ncluster_1=np.where(clusters==1)\n\n\n# In[ ]:\n\n\nfrom nltk.cluster import KMeansClusterer, euclidean_distance\n\n\n# In[ ]:\n\n\ndf=df.values\n\n\n# In[ ]:\n\n\nx_cluster_0=df[cluster_0]\nx_cluster_1=df[cluster_1]\n\n\n# In[ ]:\n\n\nls=list()\nls1=list()\n\n\n# In[ ]:\n\n\nfor i in range(0,328496):\n \n distance=euclidean_distance(x_cluster_0[i],kmeans.cluster_centers_[0])\n ls.append(distance)\n\n\n# In[ ]:\n\n\nfor i in range(0,328497):\n distance=euclidean_distance(x_cluster_1[i],kmeans.cluster_centers_[1])\n ls1.append(distance)\n\n\n# In[ ]:\n\n\nmin(ls)\n\n\n# In[ ]:\n\n\nmax(ls)\n\n\n# In[ ]:\n\n\nmn=1.521201652284063\nmx=320.9014005287401\n\n\n# In[ ]:\n\n\nl1=list()\nfor i in ls:\n print('score :{}'.format((i-mn)/(mx-mn)))\n l1.append((i-mn)/(mx-mn)*10)\n\n\n# In[ ]:\n\n\nmin(ls1)\n\n\n# In[ ]:\n\n\nmax(ls1)\n\n\n# In[ ]:\n\n\nmn1=1.8334033408659618\n\n\n# In[ ]:\n\n\nmx1=320.90277590372847\n\n\n# In[ ]:\n\n\nl2=list()\nfor i in ls1:\n print('score :{}'.format((i-mn1)/(mx1-mn1)))\n l2.append((i-mn1)/(mx1-mn1)*10)\n\n\n# In[ ]:\n\n\nl1=pd.DataFrame(l1,columns=[\"cluster_0\"])\n\n\n# In[ ]:\n\n\nsn.distplot(l1[\"cluster_0\"],kde=False,color=\"red\")\n\n\n# In[ ]:\n\n\nl2=pd.DataFrame(l2,columns=[\"cluster_1\"])\n\n\n# In[ ]:\n\n\nsn.distplot(l2[\"cluster_1\"],kde=False,color=\"red\")\n\n","sub_path":"ride and comfort_city.py","file_name":"ride and comfort_city.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"604104258","text":"# 개인용 데이터 베이스 SQLite3 : python에 기본 설치 되어있음\r\n\r\nimport sqlite3\r\nprint(sqlite3.sqlite_version_info)\r\n\r\n# conn = sqlite3.connect('example.db') \r\nconn = sqlite3.connect(':memory:') # ram에 DB 생성 - 테스트용으로 연습할 때\r\n\r\ntry:\r\n cur = conn.cursor()\r\n \r\n cur.execute('create table if not exists friends(name text, phone text)')\r\n \r\n cur.execute(\"insert into friends values('홍길동','111-1111')\")\r\n cur.execute(\"insert into friends values(?,?)\",('tom', '222-2222'))\r\n conn.commit()\r\n \r\n cur.execute(\"select * from friends\")\r\n \r\n for f in cur:\r\n print(f[0] + \" \" + f[1])\r\n \r\nexcept Exception as e:\r\n print(e)\r\n conn.rollback()\r\nfinally:\r\n conn.close()","sub_path":"python_basic/pack5db/test33sqlite.py","file_name":"test33sqlite.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"427891863","text":"import numpy as np\nimport pandas as pd\n\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef read_data(filename: str):\n dataset = pd.read_csv(filename)\n xs = dataset.iloc[:, 0:2].to_numpy()\n\n xs = MinMaxScaler().fit_transform(xs)\n ys = dataset.iloc[:, 2:3].to_numpy()\n ys = np.concatenate(ys).ravel()\n ys = np.array(list(map(lambda x: 1 if x == 'P' else -1, ys)))\n\n indices = np.arange(ys.shape[0])\n np.random.shuffle(indices)\n return xs[indices], ys[indices]\n","sub_path":"Machine Learning/Labs/SVM/utils/support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"41730824","text":"'''A module containing views pertinent to the manipulation of reaction objects'''\n\nfrom django.views.generic import CreateView, ListView, UpdateView\nfrom DRP.models import PerformedReaction, OrdRxnDescriptorValue, CompoundQuantity\nfrom DRP.models import NumRxnDescriptorValue, BoolRxnDescriptorValue, CatRxnDescriptorValue\nfrom DRP.forms import PerformedRxnForm, PerformedRxnDeleteForm\nfrom DRP.forms import NumRxnDescValForm, OrdRxnDescValForm, BoolRxnDescValForm, CatRxnDescValForm \nfrom django.utils.decorators import method_decorator\nfrom decorators import userHasLabGroup, hasSignedLicense, labGroupSelected\nfrom django.contrib.auth.decorators import login_required\nfrom django.forms.models import modelformset_factory\nfrom DRP.forms import ModelFormSet, FormSet\nfrom django.forms.formsets import TOTAL_FORM_COUNT\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, Http404, HttpResponseForbidden\nfrom django.views.decorators.http import require_POST\nfrom django.core.exceptions import PermissionDenied\n\nclass ListPerformedReactions(ListView):\n '''Standard list view of performed reactions, adjusted to deal with a few DRP idiosyncrasies'''\n\n template_name='reactions_list.html'\n context_object_name='reactions'\n model=PerformedReaction \n paginate_by=20\n \n @labGroupSelected #sets self.labGroup\n def dispatch(self, request, filetype=None, *args, **kwargs):\n\n if self.labGroup is not None:\n self.queryset = PerformedReaction.objects.filter(reaction_ptr__in=self.labGroup.reaction_set.all()) | PerformedReaction.objects.filter(public=True)\n else:\n self.queryset = PerformedReaction.objects.filter(public=True)\n\n if filetype is None:\n response = super(ListPerformedReactions, self).dispatch(request, *args, **kwargs)\n elif filetype == '.html':\n if 'page' not in request.GET:\n self.paginate_by = None\n if 'reactions_only' in request.GET:\n self.template_name='reactions_divs.html'\n response = super(ListPerformedReactions, self).dispatch(request, *args, **kwargs)\n elif filetype == '.csv':\n self.paginate_by = None\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition']='attachment; filename=\"reactions.csv\"'\n if 'expanded' in request.GET and request.user.is_authenticated():\n self.queryset.toCsv(response, True)\n else:\n self.queryset.toCsv(response)\n elif filetype == '.arff':\n self.paginate_by = None\n response = HttpResponse(content_type='text/vnd.weka.arff')\n response['Content-Disposition']='attachment; filename=\"reactions.arff\"'\n if 'expanded' in request.GET and request.user.is_authenticated():\n self.queryset.toArff(response, True)\n else:\n self.queryset.toArff(response)\n return response\n\n def get_context_data(self, **kwargs):\n context = super(ListPerformedReactions, self).get_context_data(**kwargs)\n context['lab_form'] = self.labForm\n# context['filter_formset'] = self.filterFormSet\n return context\n\n@login_required\n@hasSignedLicense\n@userHasLabGroup\ndef reactionForm(request, pk=None):\n '''A view designed to create performed reaction instances'''\n descFields = ('descriptor', 'value')\n if pk == None:\n reaction = None\n else:\n try:\n reaction=PerformedReaction.objects.get(pk=pk)\n except PerformedReaction.DoesNotExist:\n raise Http404(\"This reaction cannot be found\")\n if reaction is not None:\n reactants = CompoundQuantity.objects.filter(reaction=reaction.reaction_ptr)\n numRxnDescriptorValues = NumRxnDescriptorValue.objects.filter(reaction=reaction, descriptor__calculatorSoftware='manual')\n ordRxnDescriptorValues = OrdRxnDescriptorValue.objects.filter(reaction=reaction, descriptor__calculatorSoftware='manual')\n boolRxnDescriptorValues = BoolRxnDescriptorValue.objects.filter(reaction=reaction, descriptor__calculatorSoftware='manual')\n catRxnDescriptorValues = CatRxnDescriptorValue.objects.filter(reaction=reaction, descriptor__calculatorSoftware='manual') \n else:\n reactants=None\n numRxnDescriptorValues = None \n ordRxnDescriptorValues = None\n boolRxnDescriptorValues = None\n catRxnDescriptorValues = None\n \n if request.method=='POST':\n reactantsFormSetInst = ModelFormSet(CompoundQuantity, fields=('compound', 'role', 'amount'), data=request.POST, canAdd=True, canDelete=True, instances=reactants)\n reactionForm = PerformedRxnForm(request.user, data=request.POST, instance=reaction) \n\n descriptorFormSets = (\n ModelFormSet(NumRxnDescriptorValue, formClass=NumRxnDescValForm, data=request.POST, prefix='num', canDelete=True, instances=numRxnDescriptorValues),\n ModelFormSet(OrdRxnDescriptorValue, formClass=OrdRxnDescValForm, data=request.POST, prefix='ord', canDelete=True, instances=ordRxnDescriptorValues),\n ModelFormSet(BoolRxnDescriptorValue, formClass=BoolRxnDescValForm, data=request.POST, prefix='bool', canDelete=True, instances=boolRxnDescriptorValues),\n ModelFormSet(CatRxnDescriptorValue, formClass=CatRxnDescValForm, data=request.POST, prefix='cat', canDelete=True, instances=catRxnDescriptorValues)\n )\n\n if 'save' in request.POST: \n if reactionForm.is_valid() and reactantsFormSetInst.is_valid() and all(d.is_valid() for d in descriptorFormSets):\n rxn = reactionForm.save()\n reactants = reactantsFormSetInst.save(commit=False)\n for reactant in reactants:\n reactant.reaction=rxn.reaction_ptr\n reactant.save()\n CompoundQuantity.objects.filter(reaction=rxn.reaction_ptr).exclude(pk__in=(reactant.pk for reactant in reactants)).delete()\n cdvs = [] #collated descriptor values\n for formSet in descriptorFormSets:\n descriptorValues = formSet.save(commit=False)\n cdvs.append(descriptorValues)\n for descriptorValue in descriptorValues:\n descriptorValue.reaction=rxn.reaction_ptr\n descriptorValue.save()\n NumRxnDescriptorValue.objects.filter(reaction=rxn.reaction_ptr).exclude(pk__in=(dv.pk for dv in cdvs[0]))\n OrdRxnDescriptorValue.objects.filter(reaction=rxn.reaction_ptr).exclude(pk__in=(dv.pk for dv in cdvs[1]))\n BoolRxnDescriptorValue.objects.filter(reaction=rxn.reaction_ptr).exclude(pk__in=(dv.pk for dv in cdvs[2]))\n CatRxnDescriptorValue.objects.filter(reaction=rxn.reaction_ptr).exclude(pk__in=(dv.pk for dv in cdvs[3]))\n return redirect('reactionlist')\n else:\n reactionForm = PerformedRxnForm(request.user, instance=reaction)\n reactantsFormSetInst = ModelFormSet(CompoundQuantity, fields=('compound', 'role', 'amount'), canAdd=True, instances=reactants, canDelete=True)\n descriptorFormSets = (\n ModelFormSet(NumRxnDescriptorValue, formClass=NumRxnDescValForm, prefix='num', instances=numRxnDescriptorValues, canDelete=True),\n ModelFormSet(OrdRxnDescriptorValue, formClass=OrdRxnDescValForm, prefix='ord', instances=ordRxnDescriptorValues, canDelete=True),\n ModelFormSet(BoolRxnDescriptorValue, formClass=BoolRxnDescValForm, prefix='bool', instances=boolRxnDescriptorValues, canDelete=True),\n ModelFormSet(CatRxnDescriptorValue, formClass=CatRxnDescValForm, prefix='cat', instances=catRxnDescriptorValues, canDelete=True)\n )\n return render(request, 'reaction_form.html', {'reaction_form':reactionForm, 'reactants_formset':reactantsFormSetInst, 'descriptor_formsets':descriptorFormSets}) \n\n@require_POST\n@login_required\n@hasSignedLicense\n@userHasLabGroup\ndef deleteReaction(request, *args, **kwargs):\n '''A view managing the deletion of reaction objects'''\n form =PerformedRxnDeleteForm(data=request.POST, user=request.user) \n if form.is_valid():\n form.save()\n else:\n raise RuntimeError(str(form.errors))\n return redirect('reactionlist')\n\n@require_POST\n@login_required\n@hasSignedLicense\n@userHasLabGroup\ndef invalidateReaction(request, *args, **kwargs):\n '''A view managing the deletion of reaction objects'''\n form =PerformedRxnInvalidateForm(data=request.POST, user=request.user) \n if form.is_valid():\n form.save()\n else:\n raise RuntimeError(str(form.errors))\n return redirect('reactionlist')\n","sub_path":"DRP/views/reaction.py","file_name":"reaction.py","file_ext":"py","file_size_in_byte":8741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"479210198","text":"from django.shortcuts import render,redirect\nfrom .forms import addlighting, enquiryform\nfrom .models import orderl, lighting, lighting, user_enquiry1\nfrom django.contrib.auth.models import User\nfrom random import randint\n# Create your views here.\n\n\ndef productdetail(request,id):\n od=id\n displaymore=lighting.objects.get(pk=id) \n n=randint(1,2)\n rand=lighting.objects.get(pk=n)\n\n\n n1=randint(1,2)\n rand1=lighting.objects.get(pk=n1)\n \n n2=randint(1,2)\n rand2=lighting.objects.get(pk=n2)\n\n n3=randint(1,2)\n rand3=lighting.objects.get(pk=n3)\n\n brand=displaymore.brand_name\n price=displaymore.price\n\n if request.method=='POST':\n enfm=enquiryform(request.POST)\n if enfm.is_valid():\n pc=brand\n sc=price\n br=enfm.cleaned_data['full_name']\n pr=enfm.cleaned_data['phone_no']\n orp=enfm.cleaned_data['district']\n rm=enfm.cleaned_data['address']\n ro=enfm.cleaned_data['message']\n \n print('helloooo')\n \n reg=user_enquiry1(full_name=br,phone_no=pr,district=orp,address=rm,message=ro,brand_name=pc,price=sc)\n reg.save()\n order=lighting.objects.get(pk=id) \n todos=orderl.objects.filter(user=request.user)\n for i in todos:\n\n ap=i.user\n\n \n us=ap\n bn=order.brand_name\n pr=order.price\n cp=order.coverphoto\n reg=orderl(brand=bn,priceo=pr,coverphotoo=cp,user=us)\n reg.save()\n \n \n else:\n enfm=enquiryform()\n return render(request,'main/productdetail.html',{'dsm':displaymore,'enqform':enfm,'dsm1':od,'randm':rand,'randm1':rand1,'randm2':rand2,'randm3':rand3})\n\ndef additem(request):\n return render(request,'main/additem.html')\n\ndef lightinggallery(request):\n mg=lighting.objects.all()\n return render(request,'main/lightinggallery.html',{'mg1':mg})\n\ndef update(request):\n upd=lighting.objects.all()\n return render(request,'main/update.html',{'up':upd})\n\ndef updatepage(request,id):\n if request.method=='POST':\n pi=lighting.objects.get(pk=id)\n fm=addlighting(request.POST,instance=pi)\n if fm.is_valid():\n fm.save()\n\n else:\n pi=lighting.objects.get(pk=id)\n fm=addlighting(instance=pi)\n return render(request,'main/updatepage.html',{'up':fm,'pi':pi})\n\n\ndef lightingpage(request):\n \n if request.method=='POST':\n fm=addlighting(request.POST,request.FILES)\n if fm.is_valid():\n br=fm.cleaned_data['brand_name']\n pr=fm.cleaned_data['price']\n orp=fm.cleaned_data['original_price']\n \n ds=fm.cleaned_data['description']\n cimg=fm.cleaned_data['coverphoto']\n pho=fm.cleaned_data['photo']\n \n reg=lighting(brand_name=br,price=pr,original_price=orp,description=ds,coverphoto=cimg,photo=pho)\n reg.save()\n \n \n \n \n \n else:\n fm=addlighting()\n \n return render(request,'main/addlighting.html',{'lightingform':fm})\n\n\ndef userordervi(request,id):\n order=lighting.objects.get(pk=id) \n todos=orderl.objects.filter(user=request.user)\n for i in todos:\n\n ap=i.user\n\n \n us=ap\n bn=order.brand_name\n pr=order.price\n cp=order.coverphoto\n reg=orderl(brand=bn,priceo=pr,coverphotoo=cp,user=us)\n reg.save()\n \n return redirect('home')\n\ndef lightingcart(request):\n if request.user.is_authenticated:\n todos=orderl.objects.filter(user=request.user)\n return render(request,'main/lightingcart.html',{'todo':todos})\n else:\n return render(request,'emptycart.html')\n \n # if User:\n # user=User.objects.get()\n # return render(request,'lightingcart.html',{'cart':user})\n # else:\n # return redirect('home')","sub_path":"lighting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"401237511","text":"List2 = [12,14,-95,3]\r\nfor i in range(0):\r\n value = int(input())\r\n List2.append(value)\r\n\r\n# finding all positive number from the list\r\nposNoList = list(filter(lambda i: (i >= 0), List2))\r\n\r\n# printing all positive values of the list\r\nprint(posNoList)\r\n","sub_path":"list2.py","file_name":"list2.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"28769375","text":"import numpy as np\nimport qctoolkit as qtk\nimport os\nimport pkgutil\n\nif pkgutil.find_loader('pyscf') is not None:\n from rdkit import Chem\n from rdkit.Chem import AllChem, rdMolTransforms, rdMolDescriptors\n import rdkit.Chem.rdForceFieldHelpers as rcr\n from rdkit.Geometry.rdGeometry import Point3D\n\ndef mol2rdk(mol, **kwargs):\n if 'removeHs' not in kwargs:\n kwargs['removeHs'] = False\n if type(mol) is not Chem.rdchem.Mol:\n mol.write('.tmp.xyz')\n try:\n os.system(\"obabel -ixyz -opdb .tmp.xyz > .tmp.pdb\")\n except Exception as err:\n qtk.exit(\"obabel failed with error: \" + str(err))\n mol = Chem.MolFromPDBFile('.tmp.pdb', **kwargs)\n os.remove('.tmp.xyz')\n os.remove('.tmp.pdb')\n return mol\n\ndef rdk2mol(rdmol):\n conf = rdmol.GetConformer()\n ZR = []\n atoms = rdmol.GetAtoms()\n for i in range(rdmol.GetNumAtoms()):\n R = conf.GetAtomPosition(i)\n Z = atoms[i].GetAtomicNum()\n coord = [Z, R.x, R.y, R.z]\n ZR.append(coord)\n ZR = np.asarray(ZR)\n mol = qtk.Molecule()\n mol.build(ZR)\n return mol\n\ndef geopt(mol, forcefield='uff', max_iter=500, **kwargs):\n\n if type(mol) is not Chem.rdchem.Mol:\n rdmol = mol2rdk(mol)\n else:\n rdmol = mol\n \n ff_dict = {\n 'uff': AllChem.UFFOptimizeMolecule,\n 'mmff94': AllChem.MMFFOptimizeMolecule\n }\n\n ff = ff_dict[forcefield]\n\n AllChem.EmbedMolecule(\n rdmol, \n useExpTorsionAnglePrefs=True,\n useBasicKnowledge=True)\n ff(rdmol, maxIters=max_iter)\n return rdk2mol(rdmol)\n\ndef mol2svg(mol,\n molSize=(200,200),\n kekulize=False, \n index=True,\n atom_label=False,\n highlight=[],\n colors={},\n sizes={},\n ):\n\n mol = mol2rdk(mol, removeHs=True)\n \n drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])\n opts = drawer.drawOptions()\n kw_drawing = {}\n \n ##################\n # bare bone plot #\n ##################\n m = Chem.Mol(mol.ToBinary())\n if kekulize:\n try:\n Chem.Kekulize(m)\n except:\n m = Chem.Mol(mol.ToBinary())\n if not m.GetNumConformers():\n rdDepictor.Compute2DCoords(m)\n \n ############\n # indexing #\n ############\n if index:\n for i in range(m.GetNumAtoms()):\n opts.atomLabels[i] = m.GetAtomWithIdx(i).GetSymbol()+str(i)\n \n ##############\n # atom label #\n ##############\n if atom_label:\n for i in range(m.GetNumAtoms()):\n opts.atomLabels[i] = m.GetAtomWithIdx(i).GetSymbol()\n \n #################\n # high lighting #\n #################\n kw_hl = {\n 'highlightAtoms': highlight,\n 'highlightAtomColors': colors,\n 'highlightAtomRadii': sizes,\n 'highlightBonds': None,\n }\n kw_drawing.update(kw_hl)\n \n drawer.DrawMolecule(m, **kw_drawing)\n drawer.FinishDrawing()\n svg = drawer.GetDrawingText()\n return svg.replace('svg:','')\n","sub_path":"qctoolkit/utilities/rdkit_tools.py","file_name":"rdkit_tools.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"17921304","text":"import os, re, glob, hashlib\r\n\r\nclass CfgHash:\r\n def __init__(self):\r\n self.bfname = ''\r\n self.logname = ''\r\n self.bfdate = ''\r\n self.floc = ''\r\n self.fhash = ''\r\n\r\ndef dofilehash(newestfilelist, hashlist):\r\n cmtssource = '/usr/local/airflow/incoming/hfc/dataminer/CMTS_CFG_BAK/inservice'\r\n os.chdir(cmtssource)\r\n paths = str(cmtssource)\r\n for newlist in newestfilelist:\r\n for filelist in newlist:\r\n bfname = filelist\r\n logname = filelist[:12]\r\n bfdate = filelist[13:28]\r\n hashobject = CfgHash()\r\n hashobject.bfname = bfname\r\n hashobject.logname = logname\r\n hashobject.bfdate = bfdate\r\n hashobject.floc = paths\r\n with open(filelist, 'rb') as text:\r\n hasher = hashlib.sha1()\r\n blocksize = 65536\r\n data = text.readline()\r\n buf = text.readline(blocksize)\r\n while len(buf) > 1:\r\n hasher.update(buf)\r\n buf = text.read(blocksize)\r\n lhash = hasher.hexdigest()\r\n hashobject.fhash = lhash\r\n hashlist.append(hashobject)","sub_path":"pyrob/loads/hfc/cfg/cmts_dm_cfg_bu_hash.py","file_name":"cmts_dm_cfg_bu_hash.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322304965","text":"from classes import character\n\ndef main():\n \n #Character constructed here with my name, a current DnD character's name, his race, and his class\n #class is a special keyword in python so I've used clas in its place;\n newCharacter = character.character('Kindon', 'Clouse Reddington', 'human', 'sorcerer')\n #print('Character created: {0}', vars(newCharacter))\n '''\n newCharacter.update('characterName', 'Requiem', 'none')\n #print(vars(newCharacter))\n newCharacter.update('stats', {'Intellect' : 18, 'Strength' : 13, 'Wisdom' : 8, 'Charisma' : 20, 'Dexterity' : 12, 'Constitution' : 14}, 'none')\n #print(newCharacter.stats.list)\n print(newCharacter.inv.dictItems)\n newCharacter.update('inv', {'Ring of Featherfalling' : 'User falls at 60ft per second', 'Wand of Webbing' : 'blah blah blah'}, 'add')\n print(newCharacter.inv.dictItems)\n newCharacter.update('inv', {'Wand of Webbing' : 'blah blah blah'}, 'remove')\n print(newCharacter.inv.dictItems)\n newCharacter.update('inv', {'asdf' : 'blah blah blah'}, 'remove')\n print(newCharacter.inv.dictItems)\n '''\n\n\n newCharacter.update('skills', {'Athletics' : '+2', 'Performance' : '+3'}, 'none')\n #print(newCharacter.skills.list)\n\n\nmain()","sub_path":"DnD Character Generator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"646107972","text":"def solution(s):\n s=list(s.lower())\n tmp = ' '\n for i in range(len(s)):\n if tmp == ' ':\n s[i] = s[i].upper()\n tmp = s[i]\n return ''.join(s)\n\nprint(solution('TEST'))","sub_path":"algo_py/programmers/jadencase문자열만들기.py","file_name":"jadencase문자열만들기.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"66408047","text":"import math\nimport collections\nfrom threading import Thread\nfrom robot_library.robot import *\nimport time as tm\nfrom scripts.artag_detector import *\n\n\nDEBUG = True\n\n\nclass RobotConst: # константы\n cell_size = 0.304\n exact_cell_size = 0.3\n wheel_d = 0.17999999999999999\n track = 0.29999999999999999\n cpr = 2 * math.pi\n\n forward_laser_delta = 0.154 # на столько м вынесен дальномер вперед центра оси\n min_lasers_on_edge = 15 # столько лазеров должно попасть на ребро, чтобы считать его препятствием\n laser_node_collision_dist = 0.10 # расстояние от точки на ребре до узла должно быть не меньше этого (в клетках)\n laser_collision_dist = 0.05 # точка на ребре, если расхождение ее координаты и настоящей координаты ребра не больше этого (в клетках)\n lasers_on_one_node = 4 # столько лазеров проверяет один узел на пустоту; будет взято x2+1\n min_length_delta = 0.2 # каждый лазер должен проходить дальше пустого узла хотя бы на столько м\n\n v = 0.35\n vslow = 0.04\n acceleration = 0.2 # points per second\n pid_window_size = 10\n decel_start_offset = 1 # расстояние до начала замедления\n rotate_decel_start_offset = 29000 # расстояние до начала замедления\n maze_size = 15\n\n hamming_length = 12\n directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n colors = {\n 2: 'green',\n 4: 'blue',\n 0: 'red',\n 1: 'yellow'\n }\n\n\nclass Data: # одометрия\n cur_angle = 0\n pid_error_deque = [0.0 for i in range(RobotConst.pid_window_size)]\n pid_deque_index = -1\n field = np.full((RobotConst.maze_size * 2 + 1, RobotConst.maze_size * 2 + 1), -1)\n field_cells = [[-1 for _ in range((RobotConst.maze_size + 1) * 2 + 1)]\n for _ in range((RobotConst.maze_size + 1) * 2 + 1)]\n robot_pos = (RobotConst.maze_size, RobotConst.maze_size)\n borders = [1, 1, field.shape[0] - 2, field.shape[1] - 2]\n enc = {\"left\": 0, \"right\": 0}\n sensors = {'time_stamp': 0, 'angle': 0.0, 'angle_increment': 0.0, 'values': tuple([0.0 for _ in range(683)])}\n encL = 0\n encR = 0\n min_robot_pos = (RobotConst.maze_size, RobotConst.maze_size)\n max_robot_pos = (RobotConst.maze_size, RobotConst.maze_size)\n finish = False\n threads = []\n\n\n# -1 - неизвестная клетка\n# 0 - пустота\n# 1 - препятствие\n# 2 - граница поля\n\n\n# Shortcut methods\nrobot = Robot()\ndetector = ARTagDetector(debug=DEBUG)\nhamming = Hamming(RobotConst.hamming_length, debug=DEBUG)\neL = lambda: Data.enc['right']\neR = lambda: Data.enc['left']\nsF = lambda: min(Data.sensors[\"values\"][(683 // 2) - 40:(683 // 2) + 41])\nsR = lambda: Data.sensors['values'][31]\nsR90 = lambda: Data.sensors['values'][84]\nsL = lambda: Data.sensors['values'][-32]\nsL90 = lambda: Data.sensors['values'][-85]\n# sA = lambda x: robot.getLaser()['values'][x]\nnode_value = lambda cell_dist: (cell_dist % 1 <= RobotConst.laser_node_collision_dist or\n cell_dist % 1 >= (1 - RobotConst.laser_node_collision_dist))\nedge_value = lambda cell_dist: (cell_dist % 1 <= RobotConst.laser_collision_dist or\n cell_dist % 1 >= (1 - RobotConst.laser_collision_dist))\npi = math.pi\nsleep = lambda x: tm.sleep(x / 1000)\ninf = float('inf')\neps = 0.00000001\n\n# getLasers() output:\n# {'time_stamp': int,\n# 'angle': float,\n# 'angle_increment': float,\n# 'values': tuple(683 floats)\n# }\n#\n\n# Base methods\nsign = lambda x: -1 if x < 0 else 1\ntime = lambda: tm.time() * 1000\ngetYaw = lambda: math.degrees(robot.getDirection()) * -1000\nlog = lambda *args, sep=' ', end='\\n', file=None: print(*args, sep=sep, end=end, file=file) if DEBUG else None\n\n\ndef encoder_polling(delay=200):\n while True:\n if Data.finish:\n break\n\n try:\n sleep(delay)\n x = robot.getEncoders()\n if x is not None:\n Data.enc = x\n except rospy.exceptions.ROSInterruptException:\n break\n\n\ndef laser_polling(delay=200):\n while True:\n if Data.finish:\n break\n\n try:\n sleep(delay)\n x = robot.getLaser()\n if x is not None:\n Data.sensors = x\n except rospy.exceptions.ROSInterruptException:\n break\n\n\nclass SpiralGenerator:\n def __init__(self, size):\n self.dir = 1\n self.size = size\n self.iter_lim = size * size\n self.iteration = 0\n self.start_dir = (0, 0)\n self.cur = (0, -1)\n\n def __next__(self):\n if self.iter_lim == self.iteration:\n raise StopIteration\n if self.dir == 1:\n if self.cur[1] == self.start_dir[1] + self.size - 1:\n self.dir = 2\n self.cur = (self.cur[0] + 1, self.cur[1])\n self.start_dir = self.cur\n self.size -= 1\n else:\n self.cur = (self.cur[0], self.cur[1] + 1)\n elif self.dir == 2:\n if self.cur[0] == self.start_dir[0] + self.size - 1:\n self.dir = 3\n self.cur = (self.cur[0], self.cur[1] - 1)\n self.start_dir = self.cur\n else:\n self.cur = (self.cur[0] + 1, self.cur[1])\n elif self.dir == 3:\n if self.cur[1] == self.start_dir[1] - self.size + 1:\n self.dir = 4\n self.cur = (self.cur[0] - 1, self.cur[1])\n self.start_dir = self.cur\n self.size -= 1\n else:\n self.cur = (self.cur[0], self.cur[1] - 1)\n elif self.dir == 4:\n if self.cur[0] == self.start_dir[0] - self.size + 1:\n self.dir = 1\n self.cur = (self.cur[0], self.cur[1] + 1)\n self.start_dir = self.cur\n else:\n self.cur = (self.cur[0] - 1, self.cur[1])\n self.iteration += 1\n return self.cur\n\n def __iter__(self):\n return self\n\n\ndef print_field():\n for i in Data.field:\n for j in i:\n log(('-' if j == -1 else j), end=' ')\n log()\n log('=' * len(Data.field_cells) * 2)\n for i in Data.field_cells:\n for j in i:\n log(('-' if j == -1 else j), end=' ')\n log()\n\n\ndef motors(vL=None, vR=None):\n vL = RobotConst.v if vL is None else vL\n vR = vL if vR is None else vR\n\n delta = vL - vR\n linear = vR + delta / 2\n angular = (2 * pi) / (pi * RobotConst.track / (delta / 2)) if abs(delta) > eps else 0 # градусы в секунду.\n # Подразумевается, что скорость вращения\n # колёс в gazebo считается как сумма скоростей колёс при linear_speed+angular_speed. Плюс, считается, что все\n # линейные величины считаются в метрах, linear_speed в м/с, angular_speed в рад/с\n # log(linear, angular)\n robot.setVelosities(linear, angular)\n\n\ndef _drive_enc_(power=RobotConst.v):\n sgnL = sign(Data.encL - eL())\n sgnR = sign(Data.encR - eR())\n flagL = 0 if eL() < Data.encL else 1\n flagR = 0 if eR() < Data.encR else 1\n while [eL(), Data.encL][flagL] < [Data.encL, eL()][flagL] or [eR(), Data.encR][flagR] < [Data.encR, eR()][flagR]:\n if abs(Data.encL - eL()) < RobotConst.decel_start_offset:\n powerL = RobotConst.vslow * sgnL if [eL(), Data.encL][flagL] < [Data.encL, eL()][\n flagL] else 0\n else:\n powerL = max(0, min(power, RobotConst.v * 2)) * sgnL if [eL(), Data.encL][flagL] < [Data.encL, eL()][\n flagL] else 0\n if abs(Data.encR - eR()) < RobotConst.decel_start_offset:\n powerR = RobotConst.vslow * sgnR if [eR(), Data.encR][flagR] < [Data.encR, eR()][\n flagR] else 0\n else:\n powerR = max(0, min(power, RobotConst.v * 2)) * sgnR if [eR(), Data.encR][flagR] < [Data.encR, eR()][\n flagR] else 0\n # log(eL(), Data.encL, eR(), Data.encR)\n motors(powerL, powerR)\n if Data.finish:\n exit(1)\n sleep(10)\n motors(0)\n\n\ndef forward_enc_simplified(cm=RobotConst.cell_size):\n path = (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.encL += path # Add start encoder value\n Data.encR += path # Difference correction\n _drive_enc_()\n\n\ndef rotate_enc_simplified_relative(angle):\n if abs(angle) < 200:\n angle *= 1000\n if abs(angle) >= 180000:\n angle -= 360000\n cm = RobotConst.track * pi * (angle / 360000)\n Data.encL += (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.encR -= (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.cur_angle += angle\n _drive_enc_()\n\n\ndef rotate_enc_simplified_absolute(angle):\n if abs(angle) < 200:\n angle *= 1000\n rotate_enc_simplified_relative(angle - Data.cur_angle)\n\n\ndef forward_enc_simplified_while(check_func, dir=1, power=RobotConst.v):\n \"\"\"\n Едет по гироскому пока check_func возвращает True\n :param check_func: функция, по которой надо останавливать цикл (возвращает bool)\n :param dir: 1 - вперёд, -1 - назад\n :param power: скорость\n :return:\n \"\"\"\n sgn = sign(dir)\n while check_func():\n motors(max(0, min(power, 100)) * sgn, max(0, min(power, 100)) * sgn)\n if Data.finish:\n exit(1)\n sleep(1)\n Data.encL = eL()\n Data.encR = eR()\n motors(0)\n\n\ndef forward_gyro(cm=float(RobotConst.cell_size), additional_corrections=lambda: 0.0):\n gyro_kp = 0.000005 # П коэффиент для езды по гироскопу\n path = (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.encL += path # Add start encoder value\n Data.encR += path # Add start encoder value\n\n # start_time = time()\n sgn = sign(cm)\n # decel_offset = (Robot.decel_start_offset / (pi * Robot.wheelD)) * Robot.cpr\n # decel_start = None\n flag = 0 if eL() < Data.encL else 1\n while [eL(), Data.encL][flag] < [Data.encL, eL()][flag]:\n # power_delta = Robot.acceleration * ((time() - start_time) / 1000)\n # power_accel = min(Robot.vstart + power_delta, Robot.v)\n # power_decel = Robot.v\n # if decel_start is not None:\n # power_delta_decel = Robot.acceleration * ((time() - decel_start) / 1000)\n # power_decel = max(Robot.vstart, Robot.v - power_delta_decel)\n # power = min(power_accel, power_decel)\n extra_correction = additional_corrections()\n if abs(Data.encL - eL()) < RobotConst.decel_start_offset:\n power = RobotConst.vslow\n else:\n power = RobotConst.v\n error = Data.cur_angle - getYaw() # Proportional steering\n if error > 180000:\n error -= 360000\n if error < -180000:\n error += 360000\n correction = error * gyro_kp\n motors(max(0, min(power + correction * sgn + extra_correction, RobotConst.v * 2)) * sgn,\n max(0, min(power - correction * sgn - extra_correction, RobotConst.v * 2)) * sgn)\n if Data.finish:\n exit(1)\n sleep(10)\n motors(0)\n # log(time() - decel_start) # print the deceleration actual time after simulation\n\n\ndef forward_gyro_while(check_func, dir=1, power=RobotConst.v):\n \"\"\"\n Едет по гироскому пока check_func возвращает True\n :param check_func: функция, по которой надо останавливать цикл (возвращает bool)\n :param dir: 1 - вперёд, -1 - назад\n :param power: скорость\n :return:\n \"\"\"\n gyro_kp = 0.00002 # П коэффиент для езды по гироскопу\n sgn = sign(dir)\n while check_func():\n # log(Data.sensors[\"values\"][(683 // 2) - 5:(683 // 2) + 6])\n error = Data.cur_angle - getYaw() # Proportional steering\n if error > 180000:\n error -= 360000\n if error < -180000:\n error += 360000\n correction = error * gyro_kp\n motors(max(0, min(power + correction * sgn, 100)) * sgn, max(0, min(power - correction * sgn, 100)) * sgn)\n if Data.finish:\n exit(1)\n sleep(1)\n Data.encL = eL()\n Data.encR = eR()\n motors(0)\n\n\ndef rotate_gyro_absolute(angle):\n \"\"\"\n Rotates robot to a given value (NOTE: accepts values from -180 to 180 degrees!!!)\n \"\"\"\n if abs(angle) < 200:\n angle *= 1000\n delta = angle - Data.cur_angle\n if delta > 180000:\n delta -= 360000\n if delta < -180000:\n delta += 360000\n cm = RobotConst.track * pi * (delta / 360000)\n Data.encL += (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.encR -= (cm / (pi * RobotConst.wheel_d)) * RobotConst.cpr\n Data.cur_angle = angle\n sgn = sign(angle - getYaw())\n if abs(angle - getYaw()) >= 180000:\n sgn *= -1\n if Data.finish:\n exit(1)\n while abs(angle - getYaw()) > 3000 and (angle > -180000 + 3000 or abs(-angle - getYaw()) > 3000):\n if abs(angle - getYaw()) < RobotConst.rotate_decel_start_offset or \\\n (angle <= -180000 + RobotConst.rotate_decel_start_offset and\n abs(-angle - getYaw()) < RobotConst.rotate_decel_start_offset):\n motors(RobotConst.vslow * 1.3 * sgn, RobotConst.vslow * 1.3 * -sgn)\n else:\n motors((RobotConst.v / 3 * 2) * sgn, (RobotConst.v / 3 * 2) * -sgn)\n sleep(1)\n if Data.finish:\n exit(1)\n motors(0)\n if abs(eL() - Data.encL) > 2 * math.pi or abs(eL() - Data.encL) > 2 * math.pi:\n Data.encL = eL()\n Data.encR = eR()\n log('Rotate', angle, 'done!')\n\n\ndef rotate_gyro_relative(angle):\n angle *= 1000\n rotate_gyro_absolute(((Data.cur_angle + angle + 180000) % 360000) - 180000)\n log('Rotate', angle, '(relative) done!')\n\n\ndef pid_controller(value: float, setpoint: float) -> float:\n \"\"\"\n Calculates PID correction\n :param value: current sensor value\n :param setpoint: target sensor value\n :return: correction value\n \"\"\"\n kp = 0.05 # П/ПИД регулятор коэффициент\n ki = 0.04 # И/ПИД регулятор коэффициент\n kd = 0.03 # Д/ПИД регулятор коэффициент\n err = value - setpoint\n Data.pid_deque_index = (Data.pid_deque_index + 1) % RobotConst.pid_window_size\n Data.pid_error_deque[Data.pid_deque_index] = err\n P = err * kp\n I = sum(Data.pid_error_deque) / 10 * ki\n D = (Data.pid_error_deque[Data.pid_deque_index] - Data.pid_error_deque[\n (Data.pid_deque_index + RobotConst.pid_window_size + 1) % RobotConst.pid_window_size]) * kd\n return P + I + D\n\n\ndef pid_correction_to_motors(base_speed: int, correction: float) -> None:\n \"\"\"\n Runs motor based on calculated PID correction\n :param base_speed: default speed\n :param correction: PID correction value\n :return:\n \"\"\"\n motors(min(max(base_speed * (1 - correction), 10), 100), min(max(base_speed * (1 + correction), 10), 100))\n if Data.finish:\n exit(1)\n\n\ndef get_neighbors(pos: tuple) -> list:\n \"\"\"\n Получает смежные вершины графа (в лабиринте).\n Всё происходит в 3D\n :param pos: текущее положение (x, y, z)\n :return: [(x, y, z) * len(neighbors)]\n \"\"\"\n ans = [((pos[0] + 1) % len(RobotConst.directions), pos[1], pos[2]),\n ((pos[0] - 1) % len(RobotConst.directions), pos[1], pos[2])] # мы всегда можем повернуть в этой же клетке\n i = RobotConst.directions[pos[0]]\n if 0 <= pos[1] + i[0] < Data.field.shape[0] and 0 <= pos[2] + i[1] < Data.field.shape[1] \\\n and Data.field[pos[1] + i[0], pos[2] + i[1]] < 1:\n ans.append((pos[0], pos[1] + i[0], pos[2] + i[1]))\n return ans\n\n\ndef get_orientation() -> int:\n return ((Data.cur_angle + 180000 - 45000) // 90000) % 4\n\n\ndef get_orientation_exact() -> int:\n return ((round(getYaw()) + 180000 - 45000) // 90000) % 4\n\n\ndef BFS3D(target: list) -> list:\n \"\"\"\n По списку смежностей (трёхмерному)\n :param target: list(tuple(x,y,z)) - все целевые вершины\n :return: list(tuple) если найдено инчае пустой list\n \"\"\"\n target_cp = target.copy()\n target = []\n for i in target_cp:\n target += [(j, i[0], i[1]) for j in range(len(RobotConst.directions))] if len(i) == 2 else [i]\n start = get_orientation(), Data.robot_pos[0], Data.robot_pos[1]\n log('START', start)\n log('TARGET', target)\n queue = [start]\n done = np.full((len(RobotConst.directions), *Data.field.shape), False) # посмотрели ли вершину\n marked = np.full((len(RobotConst.directions), *Data.field.shape), -1, dtype=\"i,i,i\") # прошлая вершина\n while len(queue) > 0:\n if Data.finish:\n exit(1)\n cur = queue[0]\n queue.pop(0)\n if not done[cur]:\n done[cur] = True\n for i in get_neighbors(cur):\n if not done[i]:\n queue.append(i)\n marked[i] = cur\n if i in target: # если нашли\n ans = []\n j = i\n ans.append(i)\n while j != start: # восстановление ответа\n j = tuple(marked[j])\n ans.append(j)\n if Data.finish:\n exit(1)\n ans.reverse()\n log(\"PATH:\", ans)\n return ans\n return []\n\n\ndef update_node(x, y, value):\n if Data.borders[0] <= x <= Data.borders[2] and Data.borders[1] <= y <= Data.borders[3]:\n Data.field[x, y] = value\n\n\ndef update_cell(ax, ay, bx, by, value):\n if ax > bx:\n ax, ay, bx, by = bx, by, ax, ay\n if ay > by:\n ay, by = ay - 1, by + 1\n if Data.borders[0] <= bx <= Data.borders[2] + 1 and Data.borders[1] <= by <= Data.borders[3] + 1:\n Data.field_cells[bx][by] = value\n\n\ndef update_cell_relative(ax, ay, bx, by, value):\n ax, ay = convert_relative_to_absolute(ax, ay)\n bx, by = convert_relative_to_absolute(bx, by)\n update_cell(ax, ay, bx, by, value)\n\n\ndef convert_relative_to_absolute(dx, dy):\n rx, ry = Data.robot_pos[0], Data.robot_pos[1]\n cur_dir = get_orientation()\n if cur_dir == 0:\n x, y = rx - dx, ry - dy\n elif cur_dir == 2:\n x, y = rx + dx, ry + dy\n elif cur_dir == 1:\n x, y = rx - dy, ry + dx\n else:\n x, y = rx + dy, ry - dx\n return x, y\n\n\ndef convert_absolute_to_relative(x, y):\n rx, ry = Data.robot_pos[0], Data.robot_pos[1]\n cur_dir = get_orientation()\n if cur_dir == 0:\n dx = rx - x\n dy = ry - y\n elif cur_dir == 2:\n dx = x - rx\n dy = y - ry\n elif cur_dir == 1:\n dx = y - ry\n dy = rx - x\n else:\n dx = ry - y\n dy = x - rx\n return dx, dy\n\n\ndef update_node_relative(dx, dy, value):\n # dx - клеток вперед относительно робота\n # dy - клеток влево относительно робота\n x, y = convert_relative_to_absolute(dx, dy)\n update_node(x, y, value)\n\n\ndef update_obstacles():\n # -90 = #598 (~0.3)\n # -45 = #469 (~0.423 on left-forward, ~0.205 on forward)\n # 0 = #341 (не рекомендуется использовать для obstacles)\n # 45 = #213 (~0.423 on right-forward, ~0.205 on forward)\n # 90 = #85 (~0.3)\n\n start_time = time()\n\n # Важно: теперь лазеры слева направо\n data = robot.getLaser()\n lasers_delta_angle = data['angle_increment']\n distances = list(data['values'])[::-1]\n\n cell_rx, cell_ry = Data.robot_pos[0], Data.robot_pos[1]\n update_node(cell_rx, cell_ry, 0)\n update_cell(cell_rx, cell_ry, cell_rx - 1, cell_ry - 1, 0)\n update_cell(cell_rx, cell_ry, cell_rx - 1, cell_ry + 1, 0)\n update_cell(cell_rx, cell_ry, cell_rx + 1, cell_ry - 1, 0)\n update_cell(cell_rx, cell_ry, cell_rx + 1, cell_ry + 1, 0)\n\n edges = collections.defaultdict(int)\n for num, dist in enumerate(distances):\n if dist < 0.25:\n continue\n if dist == float('inf'):\n continue\n angle = lasers_delta_angle * (num - 85)\n # dx и dy - относительно робота (!) вперед и влево\n dx = math.sin(angle) * dist + RobotConst.forward_laser_delta\n dy = math.cos(angle) * dist\n\n cell_dx = dx / RobotConst.exact_cell_size\n cell_dy = dy / RobotConst.exact_cell_size\n if node_value(cell_dx) and node_value(cell_dy):\n # Laser endpoint is close to node\n continue\n\n if edge_value(cell_dx):\n cell_dx = round(cell_dx)\n ay = math.floor(cell_dy)\n by = math.ceil(cell_dy)\n edges[((cell_dx, ay), (cell_dx, by))] += 1\n elif edge_value(cell_dy):\n cell_dy = round(cell_dy)\n ax = math.floor(cell_dx)\n bx = math.ceil(cell_dx)\n edges[((ax, cell_dy), (bx, cell_dy))] += 1\n\n for points, cnt in edges.items():\n if cnt < RobotConst.min_lasers_on_edge:\n # Untrusted laser\n continue\n a, b = points\n ax, ay = a\n bx, by = b\n edges_now = [(a, b)]\n if ax == bx:\n if ax > 0:\n edges_now += [((ax + 1, ay), (bx + 1, by)),\n ((ax + 2, ay), (bx + 2, by))]\n update_cell_relative(ax, ay, ax + 1, by, 1)\n update_cell_relative(ax + 1, ay, ax + 2, by, 1)\n update_cell_relative(ax - 1, ay, ax, by, 0)\n else:\n edges_now += [((ax - 1, ay), (bx - 1, by)),\n ((ax - 2, ay), (bx - 2, by))]\n update_cell_relative(ax, ay, ax - 1, by, 1)\n update_cell_relative(ax - 1, ay, ax - 2, by, 1)\n update_cell_relative(ax + 1, ay, ax, by, 0)\n elif ay == by:\n if ay > 0:\n edges_now += [((ax, ay + 1), (bx, by + 1)),\n ((ax, ay + 2), (bx, by + 2))]\n update_cell_relative(ax, ay, bx, by + 1, 1)\n update_cell_relative(ax, ay + 1, bx, by + 2, 1)\n update_cell_relative(ax, ay - 1, bx, by, 0)\n else:\n edges_now += [((ax, ay - 1), (bx, by - 1)),\n ((ax, ay - 2), (bx, by - 2))]\n update_cell_relative(ax, ay, bx, by - 1, 1)\n update_cell_relative(ax, ay - 1, bx, by - 2, 1)\n update_cell_relative(ax, ay + 1, bx, by, 0)\n for a, b in edges_now:\n update_node_relative(*a, 1)\n update_node_relative(*b, 1)\n\n for x in range(Data.borders[0], Data.borders[2] + 1):\n for y in range(Data.borders[1], Data.borders[3] + 1):\n if Data.field[x, y] != -1:\n continue\n if x == cell_rx and y == cell_ry:\n continue\n\n dx, dy = convert_absolute_to_relative(x, y)\n distance = (((dx - RobotConst.exact_cell_size) ** 2 + dy ** 2) ** 0.5) * RobotConst.exact_cell_size\n angle = math.atan2((dx - RobotConst.exact_cell_size), dy)\n central_laser = 85 + round(angle / lasers_delta_angle)\n start, end = central_laser - RobotConst.lasers_on_one_node, central_laser + RobotConst.lasers_on_one_node\n if start < 0 or end >= len(distances) or distances[start] < 0.25 or distances[end] < 0.25:\n continue\n\n minimal, maximal = min(distances[start:end + 1]), max(distances[start:end + 1])\n if minimal >= distance + RobotConst.min_length_delta and maximal != float('inf'):\n update_node_relative(dx, dy, 0)\n update_cell_relative(dx, dy, dx + 1, dy + 1, 0)\n update_cell_relative(dx, dy, dx + 1, dy - 1, 0)\n update_cell_relative(dx, dy, dx - 1, dy + 1, 0)\n update_cell_relative(dx, dy, dx - 1, dy - 1, 0)\n\n print_field()\n log('CALC TIME:', time() - start_time)\n\n\ndef ride_path(path, need_to_exit=lambda: False):\n for i in range(1, len(path)):\n for j in range(i, len(path)):\n if Data.field[path[j][1:]] > 0:\n return\n if need_to_exit():\n return\n log(path[i - 1], '--->', path[i])\n if path[i][0] != path[i - 1][0]:\n if (path[i][0] - 1) % 4 == path[i - 1][0]:\n precise_90_degree_turn(1)\n elif (path[i][0] + 1) % 4 == path[i - 1][0]:\n precise_90_degree_turn(-1)\n else:\n raise AssertionError()\n else:\n forward_gyro((abs(path[i - 1][1] - path[i][1]) + abs(path[i - 1][2] - path[i][2])) * RobotConst.cell_size,\n distance_corrector_proportional)\n\n sleep(250)\n\n Data.robot_pos = (path[i][1], path[i][2])\n Data.min_robot_pos = (min(path[i][1], Data.min_robot_pos[0]), min(path[i][2], Data.min_robot_pos[1]))\n Data.max_robot_pos = (max(path[i][1], Data.max_robot_pos[0]), max(path[i][2], Data.max_robot_pos[1]))\n update_obstacles()\n update_borders()\n log('POSITION:', Data.robot_pos)\n\n\ndef update_borders() -> None:\n \"\"\"\n Обновляет массив поля согласно заданным границам (заполняет всё, что за пределами границ стенами)\n :return:\n \"\"\"\n Data.borders[0] = max(Data.borders[0], Data.robot_pos[0] - (RobotConst.maze_size - 1))\n Data.borders[1] = max(Data.borders[1], Data.robot_pos[1] - (RobotConst.maze_size - 1))\n Data.borders[2] = min(Data.borders[2], Data.robot_pos[0] + (RobotConst.maze_size - 1))\n Data.borders[3] = min(Data.borders[3], Data.robot_pos[1] + (RobotConst.maze_size - 1))\n\n for i in range(Data.borders[0]):\n for j in range(Data.field.shape[1]):\n Data.field[i, j] = 2\n for j in range(Data.borders[1]):\n for i in range(Data.field.shape[0]):\n Data.field[i, j] = 2\n for i in range(Data.field.shape[0] - 1, Data.borders[2], -1):\n for j in range(Data.field.shape[1]):\n Data.field[i, j] = 2\n for j in range(Data.field.shape[1] - 1, Data.borders[3], -1):\n for i in range(Data.field.shape[0]):\n Data.field[i, j] = 2\n # ==============================\n for i in range(Data.borders[0]):\n for j in range(len(Data.field_cells[i])):\n Data.field_cells[i][j] = 2\n for j in range(Data.borders[1]):\n for i in range(len(Data.field_cells)):\n Data.field_cells[i][j] = 2\n for i in range(len(Data.field_cells) - 1, Data.borders[2] + 1, -1):\n for j in range(len(Data.field_cells[i])):\n Data.field_cells[i][j] = 2\n for j in range(len(Data.field_cells[0]) - 1, Data.borders[3] + 1, -1):\n for i in range(len(Data.field_cells)):\n Data.field_cells[i][j] = 2\n\n\ndef proximity_corrector():\n \"\"\"\n Corrects the robot position according to the walls position\n :return:\n \"\"\"\n if sF() <= 0.142:\n log(\"CORRECT TOO CLOSE FRONT\")\n forward_gyro_while(lambda: sF() < 0.146, -1, RobotConst.vslow)\n sleep(250)\n if 0.152 <= sF() <= 0.3:\n log(\"CORRECT TOO FAR FRONT\")\n forward_gyro_while(lambda: sF() > 0.148, 1, RobotConst.vslow)\n sleep(250)\n\n\ndef precise_90_degree_turn(dir):\n \"\"\"\n Turns robot in a maze by 90 degrees precisely\n :param dir: 1 - clockwise, -1 - counterclockwise\n :return:\n \"\"\"\n proximity_corrector()\n\n if sign(dir) > 0 and sL() < 0.437 and abs(0.317 - sL()) > 0.05:\n rotate_gyro_relative(-90)\n proximity_corrector()\n rotate_gyro_relative(90)\n elif sign(dir) < 0 and sR() < 0.437 and abs(0.317 - sR()) > 0.05:\n rotate_gyro_relative(90)\n proximity_corrector()\n rotate_gyro_relative(-90)\n rotate_gyro_relative(sign(dir) * 90)\n proximity_corrector()\n\n\ndef watchdog(time_limit):\n \"\"\"\n Watches the encoders value. If their value doesn't change much for more than\n time_limit ms - it kills the program\n :param time_limit:\n :return:\n \"\"\"\n last_val1 = eL()\n last_val2 = eR()\n watch_timestamp = time()\n while True:\n if abs(eL() - last_val1) > 0.001 and abs(eR() - last_val2) > 0.001:\n last_val1 = eL()\n last_val2 = eR()\n watch_timestamp = time()\n if time() - watch_timestamp > time_limit:\n Data.finish = True\n break\n sleep(100)\n\n\ndef distance_corrector_proportional():\n \"\"\"\n For maintaining the good distance to the wall while riding through the maze cells\n :return: correction value\n \"\"\"\n kp = 0.5\n correction = 0\n if sL90() < 0.38 and sL() < 0.437:\n correction = 0.317 - sL()\n elif sR90() < 0.38 and sR() < 0.437:\n correction = sR() - 0.317\n # log(sL(), sR())\n return correction * kp\n\n\n# Main code\ndef main():\n log('Start')\n start_time = time()\n\n Data.cur_angle = (get_orientation_exact() - 1) * 90000\n rotate_gyro_relative(0)\n\n log('Localize') # Локализация\n update_obstacles()\n update_borders()\n\n while Data.borders[2] - Data.borders[0] >= RobotConst.maze_size:\n if Data.finish:\n exit(1)\n target = Data.max_robot_pos[0] + 1, -1\n for i in range(Data.field.shape[1]):\n if Data.field[Data.max_robot_pos[0] + 1, i] < 1:\n if target[1] == -1 or abs(target[1] - Data.robot_pos[1]) > abs(i - Data.robot_pos[1]):\n target = (Data.max_robot_pos[0] + 1, i)\n path = BFS3D([target])\n if len(path) == 0 or target == (Data.max_robot_pos[0] + 1, -1):\n Data.borders[2] = Data.max_robot_pos[0]\n update_borders()\n ride_path(path)\n while Data.borders[3] - Data.borders[1] >= RobotConst.maze_size:\n if Data.finish:\n exit(1)\n target = -1, Data.min_robot_pos[1] - 1\n for i in range(Data.field.shape[0]):\n if Data.field[i, Data.min_robot_pos[1] - 1] < 1:\n if target[0] == -1 or abs(target[0] - Data.robot_pos[0]) > abs(i - Data.robot_pos[0]):\n target = (i, Data.min_robot_pos[1] - 1)\n path = BFS3D([target])\n if len(path) == 0 or target == (-1, Data.min_robot_pos[1] - 1):\n Data.borders[1] = Data.min_robot_pos[1]\n update_borders()\n ride_path(path)\n\n log('Location succeed!')\n print_field()\n exit(1)\n\n log('Search start') # Поиск близжайшей тумбы к стене\n status = False\n pos = (-1, -1) # Координаты близжайшей тумбы к стене\n while not status:\n if Data.finish:\n exit(1)\n log('Searching again...')\n status, pos = spiral_obstacle_search()\n\n status = False # Определение цвета близжайшей тумбы\n color = -1\n center = (-1, -1)\n first_run = False\n while (not status) or (color not in RobotConst.colors):\n log(\"Try ride_close\")\n status, area, center = ride_close(pos, first_run)\n first_run = True\n if not status:\n continue\n log(\"Color detect\")\n status, color = detect_color(robot.getImage(), area)\n print('color', RobotConst.colors[color])\n\n if color != 1:\n full_localize()\n scan_boxes(1, center)\n\n targets = find_way_outs() # Поиск артага на тумбе, куда подъехали\n\n if Data.robot_pos[0] % 2 != 1 or Data.robot_pos[1] % 2 != 1:\n log(\"DRIVE TO INT NODE\")\n int_nodes = get_int_nodes() # едем до близжайшей целой позиции\n path = BFS3D(int_nodes)\n if len(path) == 0:\n log(\"NO WAY FOUND INT NODE\")\n ride_path(path)\n\n robot_pos = robot_abs_pos(color)\n print('coordinates', robot_pos[0] // 2, robot_pos[1] // 2)\n robot.sleep(10)\n\n status = -1\n code = \"\"\n while status < 0:\n while (get_orientation(), Data.robot_pos[0], Data.robot_pos[1]) not in targets:\n path = BFS3D(targets)\n if len(path) == 0:\n log(\"NO WAY FOUND\")\n exit(0)\n ride_path(path)\n status, code = detector.detect(robot.getImage())\n targets.remove((get_orientation(), Data.robot_pos[0], Data.robot_pos[1]))\n\n print('found marker')\n robot.sleep(10)\n\n while status > 0: # считывание артага\n if status == 1:\n rotate_gyro_relative(-10)\n elif status == 2:\n rotate_gyro_relative(10)\n sleep(100)\n status, code = detector.detect(robot.getImage())\n x, y = -1, -1\n if status == 0:\n status, parsed_code = hamming.decode(code)\n if not status:\n log(\"ERROR PARSING\", code)\n exit(0)\n x, y = parse_artag_coordinates(parsed_code)\n print('marker', x, y)\n else:\n log(\"Error, detector returned code\", status)\n exit(0)\n rotate_gyro_absolute(0)\n if x == -1 or y == -1:\n log(\"Error, coordinates not valid\")\n\n target = robot_abs_pos_to_relative(color, (x*2, y*2))\n target = target[0], target[1]\n log(\"Finish coords:\", target)\n\n while (Data.robot_pos[0], Data.robot_pos[1]) != target:\n path = BFS3D([target])\n if len(path) == 0:\n log(\"NO WAY FOUND\")\n exit(0)\n ride_path(path)\n\n print('finish')\n\n log('Success!!!')\n log('Exec time:', (time() - start_time) / 1000)\n\n\ndef scan_boxes(target_color, closest_center):\n center_nodes = centers_of_boxes()\n if closest_center in center_nodes:\n center_nodes.remove(closest_center)\n target_list = get_near_points_from_centers(center_nodes)\n while len(target_list) > 0:\n path = BFS3D(target_list)\n if len(path) == 0:\n break\n ride_path(path)\n if (get_orientation(), Data.robot_pos[0], Data.robot_pos[1]) in target_list:\n status, color = detect_color(robot.getImage(), 0)\n if status and (color == target_color):\n log(\"SCAN SUCCESS\")\n return\n elif status:\n box_nodes = find_way_outs()\n for i in box_nodes:\n if i in target_list:\n target_list.remove(i)\n log(\"SCAN FAIL\")\n\n\ndef get_int_nodes():\n ans = []\n for i in range(Data.borders[0], Data.borders[2] + 1):\n for j in range(Data.borders[1], Data.borders[3] + 1):\n if i % 2 == 1 and j % 2 == 1:\n ans.append((i, j))\n return ans\n\n\ndef full_localize():\n log(\"START FULL LOCALIZE\")\n while True:\n unknown_nodes = []\n for i in range(Data.borders[0], Data.borders[2] + 1):\n for j in range(Data.borders[1], Data.borders[3] + 1):\n if Data.field[i, j] < 0:\n unknown_nodes.append((i, j))\n if len(unknown_nodes) == 0:\n break\n path = BFS3D(unknown_nodes)\n if len(path) == 0:\n break\n ride_path(path, lambda: True if Data.field[path[-1][1], path[-1][2]] > -1 else False)\n log(\"FULL LOCALIZE DONE\")\n\n\ndef robot_abs_pos(color):\n if Data.borders[0] < RobotConst.maze_size // 2:\n if Data.borders[1] < RobotConst.maze_size // 2:\n green = RobotConst.maze_size - Data.robot_pos[0], RobotConst.maze_size - Data.robot_pos[1]\n else:\n green = Data.robot_pos[1] - RobotConst.maze_size, RobotConst.maze_size - Data.robot_pos[0]\n elif Data.borders[1] < RobotConst.maze_size // 2:\n green = RobotConst.maze_size - Data.robot_pos[1], Data.robot_pos[0] - RobotConst.maze_size\n else:\n green = Data.robot_pos[0] - RobotConst.maze_size, Data.robot_pos[1] - RobotConst.maze_size\n\n if color == 2: # green\n return green\n elif color == 4: # blue\n return green[1], (RobotConst.maze_size - 1) - green[0]\n elif color == 0: # red\n return (RobotConst.maze_size - 1) - green[0], (RobotConst.maze_size - 1) - green[1]\n elif color == 1: # yellow\n return (RobotConst.maze_size - 1) - green[1], green[0]\n return green\n\n\ndef robot_abs_pos_to_relative(color, coords):\n green = (-1, -1)\n if color == 2: # green\n green = coords\n elif color == 4: # blue\n green = (RobotConst.maze_size - 1) - coords[1], coords[0]\n elif color == 0: # red\n green = (RobotConst.maze_size - 1) - coords[0], (RobotConst.maze_size - 1) - coords[1]\n elif color == 1: # yellow\n green = coords[1], (RobotConst.maze_size - 1) - coords[0]\n else:\n return green\n\n if Data.borders[0] < RobotConst.maze_size // 2:\n if Data.borders[1] < RobotConst.maze_size // 2: # вверх влево\n return RobotConst.maze_size - green[0], RobotConst.maze_size - green[1]\n else: # вверх вправо\n return RobotConst.maze_size - green[1], RobotConst.maze_size + green[0]\n elif Data.borders[1] < RobotConst.maze_size // 2: # вниз влево\n return RobotConst.maze_size + green[1], RobotConst.maze_size - green[0]\n else: # вниз вправо\n return RobotConst.maze_size + green[0], RobotConst.maze_size + green[1]\n\n\ndef centers_of_boxes():\n res = []\n for x in range(Data.borders[0], Data.borders[2] + 1):\n for y in range(Data.borders[1], Data.borders[3] + 1):\n if Data.field_cells[x][y] == Data.field_cells[x][y + 1] == \\\n Data.field_cells[x + 1][y] == Data.field_cells[x + 1][y + 1] == 1:\n res.append((x, y))\n return res\n\n\ndef detect_color(image: np.ndarray, search_area):\n status, code = detector.detect(image)\n if search_area == 0 and status > -1:\n return True, 1\n\n src = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n left = src[720 // 2 - 2: 720 // 2 + 3, (1280 // 2 - 160) - 2:(1280 // 2 - 160) + 3]\n right = src[720 // 2 - 2: 720 // 2 + 3, (1280 // 2 + 160) - 2:(1280 // 2 + 160) + 3]\n left_hsv = cv2.cvtColor(left, cv2.COLOR_BGR2HSV)\n right_hsv = cv2.cvtColor(right, cv2.COLOR_BGR2HSV)\n mean_left = left_hsv.mean(axis=0).mean(axis=0)\n mean_right = right_hsv.mean(axis=0).mean(axis=0)\n if (search_area == 1 and mean_left[1] < 127) or (search_area == 2 and mean_right[1] < 127) \\\n or (search_area == 0 and (mean_left[1] < 127 or mean_right[1] < 127)):\n return False, -1\n left_type = round(mean_left[0] / 30)\n right_type = round(mean_right[0] / 30)\n if search_area == 0 and right_type != left_type:\n return False, -1\n if search_area == 0:\n return True, left_type\n if search_area == 1:\n return True, left_type\n if search_area == 2:\n return True, right_type\n\n\ndef get_near_points_from_centers(centers: list) -> list:\n res = set()\n for c in centers:\n centerX, centerY = c\n\n res.add((0, centerX + 2, centerY))\n res.add((1, centerX, centerY - 2))\n res.add((2, centerX - 2, centerY))\n res.add((3, centerX, centerY + 2))\n return list(res)\n\n\ndef find_way_outs():\n posX, posY = Data.robot_pos\n direction = get_orientation()\n centerX = centerY = -1\n if direction == 0:\n centerX = posX - 2\n centerY = posY\n elif direction == 1:\n centerY = posY + 2\n centerX = posX\n elif direction == 2:\n centerX = posX + 2\n centerY = posY\n elif direction == 3:\n centerY = posY - 2\n centerX = posX\n\n coords = [\n (0, centerX + 2, centerY),\n (1, centerX, centerY - 2),\n (2, centerX - 2, centerY),\n (3, centerX, centerY + 2)\n ]\n return coords\n\n\ndef get_cell(cell: tuple) -> int:\n px, py = cell\n if px < 0 or py < 0:\n return 2\n if len(Data.field_cells) <= px or len(Data.field_cells) <= py:\n return 2\n return Data.field_cells[px][py]\n\n\ndef find_lost_cells(cells: list):\n if len(cells) == 0:\n return True\n for i in cells:\n nodes = [i, (i[0] - 1, i[1]), (i[0], i[1] - 1), (i[0] - 1, i[1] - 1)]\n while Data.robot_pos not in nodes:\n path = BFS3D(nodes)\n if len(path) == 0:\n return False\n ride_path(path, lambda: True if Data.field_cells[i[0]][i[1]] > -1 else False)\n return True\n\n\ndef ride_close(pos: tuple, is_first_run: bool):\n \"\"\"\n Подъехать максимально близко к тумбе на pos\n \"\"\"\n # Посчитать все координаты тумбы\n cell_borders = [Data.borders[0], Data.borders[1], Data.borders[2] + 1, Data.borders[3] + 1]\n\n res_box = list()\n res_box.append(pos)\n px, py = pos\n minX = maxX = minY = maxY = False\n toWall = min(px - cell_borders[0],\n cell_borders[2] - px,\n py - cell_borders[1],\n cell_borders[3] - py)\n if toWall == px - cell_borders[0]:\n minX = True\n elif toWall == cell_borders[2] - px:\n maxX = True\n elif toWall == py - cell_borders[1]:\n minY = True\n elif toWall == cell_borders[3] - py:\n maxY = True\n print_field()\n Xmove = Ymove = 0\n if minX:\n Xmove = 1\n res_box.append((px + 1, py))\n if minY:\n Ymove = 1\n res_box.append((px, py + 1))\n if maxX:\n Xmove = -1\n res_box.append((px - 1, py))\n if maxY:\n Ymove = -1\n res_box.append((px, py - 1))\n while len(res_box) != 4:\n lost_cells = []\n if minX or maxX:\n if get_cell((px, py + 1)) == 0\\\n or get_cell((px + Xmove, py + 1)) == 0 or get_cell((px, py - 1)) == 1:\n res_box.append((px, py - 1))\n res_box.append((px + Xmove, py - 1))\n\n elif get_cell((px, py - 1)) == 0\\\n or get_cell((px + Xmove, py - 1)) == 0 or get_cell((px, py + 1)) == 1:\n res_box.append((px, py + 1))\n res_box.append((px + Xmove, py + 1))\n else:\n lost_cells.append((px, py + 1))\n lost_cells.append((px, py - 1))\n\n if minY or maxY:\n if get_cell((px + 1, py)) == 0 or\\\n get_cell((px + 1, py + Ymove)) == 0 or get_cell((px - 1, py)) == 1:\n res_box.append((px - 1, py))\n res_box.append((px - 1, py + Ymove))\n\n elif get_cell((px - 1, py)) == 0 \\\n or get_cell((px - 1, py + Ymove)) == 0 or get_cell((px + 1, py)):\n res_box.append((px + 1, py))\n res_box.append((px + 1, py + Ymove))\n else:\n lost_cells.append((px + 1, py))\n lost_cells.append((px - 1, py))\n status = find_lost_cells(lost_cells)\n if not status:\n return False, -1, (-1, -1)\n target_list = []\n\n target_dict = {}\n\n p1, p2, p3, p4 = res_box\n centerX = min((p1[0], p2[0], p3[0], p4[0]))\n centerY = min((p1[1], p2[1], p3[1], p4[1]))\n\n\n path = []\n for i in range(1, 3):\n # ЦЕНТРАЛЬНЫЕ\n target_list.append((3, centerX, centerY + 1 + i)) # -Y\n target_dict[(3, centerX, centerY + 1 + i)] = 0\n\n target_list.append((0, centerX + 1 + i, centerY)) # -X\n target_dict[(0, centerX + 1 + i, centerY)] = 0\n\n target_list.append((1, centerX, centerY - 1 - i)) # +Y\n target_dict[(1, centerX, centerY - 1 - i)] = 0\n\n target_list.append((2, centerX - 1 - i, centerY)) # +X\n target_dict[(2, centerX - 1 - i, centerY)] = 0\n\n if i == 1:\n if not is_first_run and (get_orientation(), Data.robot_pos[0], Data.robot_pos[1]) in target_dict:\n target_dict.pop((get_orientation(), Data.robot_pos[0], Data.robot_pos[1]))\n target_list.remove((get_orientation(), Data.robot_pos[0], Data.robot_pos[1]))\n path = BFS3D(target_list)\n if len(path) > 0:\n break\n\n # Низ БОКОВЫЕ (+y)\n target_list.append((1, centerX - 1, centerY - i - 1))\n target_dict[(1, centerX - 1, centerY - i - 1)] = 2\n\n target_list.append((1, centerX + 1, centerY - i - 1))\n target_dict[(1, centerX + 1, centerY - i - 1)] = 1\n\n # ЛЕВО БОКОВЫЕ (+x)\n target_list.append((2, centerX - 1 - i, centerY - 1))\n target_dict[(2, centerX - 1 - i, centerY - 1)] = 1\n\n target_list.append((2, centerX - 1 - i, centerY + 1))\n target_dict[(2, centerX - 1 - i, centerY + 1)] = 2\n\n # Верх БОКОВЫЕ (-y)\n target_list.append((3, centerX + 1, centerY + 1 + i))\n target_dict[(3, centerX + 1, centerY + 1 + i)] = 2\n\n target_list.append((3, centerX - 1, centerY + i + 1))\n target_dict[(3, centerX - 1, centerY + 1 + i)] = 1\n\n # ПРАВО БОКОВЫЕ (-x)\n target_list.append((0, centerX + 1 + i, centerY + 1))\n target_dict[(0, centerX + 1 + i, centerY + 1)] = 1\n\n target_list.append((0, centerX + 1 + i, centerY - 1))\n target_dict[(0, centerX + 1 + i, centerY - 1)] = 2\n\n if not is_first_run and (get_orientation(), Data.robot_pos[0], Data.robot_pos[1]) in target_dict:\n target_dict.pop((get_orientation(), Data.robot_pos[0], Data.robot_pos[1]))\n target_list.remove((get_orientation(), Data.robot_pos[0], Data.robot_pos[1]))\n path = BFS3D(target_list)\n if len(path) > 0:\n break\n\n if len(path) == 0:\n return False, -1, (centerX, centerY)\n ride_path(path)\n\n if (get_orientation(), Data.robot_pos[0], Data.robot_pos[1]) not in target_dict:\n return False, -1, (centerX, centerY)\n\n return True, target_dict[(get_orientation(), Data.robot_pos[0], Data.robot_pos[1])], (centerX, centerY)\n\n\ndef parse_artag_coordinates(code: str):\n return int(code[2::-1], 2), int(code[5:2:-1], 2)\n\n\ndef spiral_obstacle_search():\n \"\"\"\n Проходит по спирали от границы поля. (Выполняет одну итерацию поиска!)\n Если находит неизвестную клетку - пытается построить до неё путь.\n Находит препятствие - выводит ответ\n :return: True если успешно найден ответ, False если нет\n \"\"\"\n cell_borders = [Data.borders[0], Data.borders[1], Data.borders[2] + 1, Data.borders[3] + 1]\n for i in SpiralGenerator(cell_borders[2] - cell_borders[0] + 1):\n position = cell_borders[0] + i[0], cell_borders[1] + i[1]\n cell_type = Data.field_cells[position[0]][position[1]]\n if cell_type == -1:\n path = BFS3D([position, (position[0] - 1, position[1]),\n (position[0], position[1] - 1), (position[0] - 1, position[1] - 1)])\n if len(path) == 0:\n continue\n ride_path(path, lambda: True if Data.field_cells[position[0]][position[1]] > -1 else False)\n return False, (-1, -1)\n elif cell_type == 1:\n ans = min(position[0] - cell_borders[0],\n cell_borders[2] - position[0],\n position[1] - cell_borders[1],\n cell_borders[3] - position[1]) * RobotConst.exact_cell_size\n log('FOUND:', i, 'ANSWER:', ans)\n print('distance', round(ans, 1))\n return True, position\n\n\nif __name__ == '__main__':\n # Thread(target=watchdog, args=(10000,), daemon=True).start()\n Data.threads.append(Thread(target=encoder_polling, args=(1,)))\n Data.threads.append(Thread(target=laser_polling, args=(100,)))\n for i in Data.threads:\n i.start()\n sleep(100)\n try:\n main()\n finally:\n robot.setVelosities(0, 0)\n Data.finish = True\n for i in Data.threads:\n i.join()\n\n log(\"Done\")\n","sub_path":"FinalSolution/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":48650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459042497","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nx=\"2017-8-23\".split(\"-\")\nprint(\"西元\",x[0],\"年\",x[1],\"月\",x[2],\"日\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[6]:\n\n\nimport random\n\n\n# In[12]:\n\n\nx=random.sample(range(1,50),7)\nxx=x.pop()\nx.sort()\nprint(\"本期大樂透中獎號碼:\",x)\nprint(\"本期大樂透特別號:\",xx)\n\n\n# In[ ]:\n\n\n\n\n\n# In[13]:\n\n\nimport time\n\n\n# In[27]:\n\n\ndef numeric_month(x):\n if x==\"Jen\":\n return \"1\"\n elif x==\"Feb\":\n return \"2\"\n elif x==\"Mar\":\n return \"3\"\n elif x==\"Apr\":\n return \"4\"\n elif x==\"May\":\n return \"5\"\n elif x==\"Jun\":\n return \"6\"\n elif x==\"Jul\":\n return \"7\"\n elif x==\"Aug\":\n return \"8\"\n elif x==\"Sep\":\n return \"9\"\n elif x==\"Oct\":\n return \"10\"\n elif x==\"Nov\":\n return \"11\"\n elif x==\"Dec\":\n return \"12\"\n \ndef chinese_week(x):\n if x==\"Sun\":\n return \"星期日\"\n elif x==\"Mon\":\n return \"星期一\"\n elif x==\"Tue\":\n return \"星期二\"\n elif x==\"Wed\":\n return \"星期三\"\n elif x==\"Tru\":\n return \"星期四\"\n elif x==\"Fri\":\n return \"星期五\"\n elif x==\"Sat\":\n return \"星期六\"\n\n\n# In[36]:\n\n\nnow=time.ctime().split(\" \")\nnow2=time.localtime()\nb=lambda x: \"有\" if x==0 else \"沒有\"\nprint(\"中華民國\",now[4],\"年\",numeric_month(now[1]),\"月\",now[2],\"日\",now[3].split(\":\")[0],\"點\",now[3].split(\":\")[1],\"分\",now[3].split(\":\")[2],\"秒\",chinese_week(now[0]))\nprint(\"今天是今年的第\",now2.tm_yday,\"天,此地\"+b(now2.tm_isdst)+\"日光節約時間\")\n\n","sub_path":"W8_a2.py","file_name":"W8_a2.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"551765049","text":"\n# set_up\ndef set_up_alumno():\n alumno_list=[\n {'nombreAlumno':'martin','apellidoAlumno': 'perez'\n ,'dniAlumno':'12121212','direccionAlumno': 'lima norte'},\n {'nombreAlumno':'braulio','apellidoAlumno': 'pachaqtec'\n ,'dniAlumno':'34343434','direccionAlumno': 'lima sur'},\n {'nombreAlumno':'hipolito','apellidoAlumno': 'pachaqtec'\n ,'dniAlumno':'56565656','direccionAlumno': 'lima centro'},\n {'nombreAlumno':'sergio','apellidoAlumno': 'perez'\n ,'dniAlumno':'78787878','direccionAlumno': 'lima sur'} \n ]\n return alumno_list\n\n# create one\ndef insert_alumno(nombreAlumno,apellidoAlumno,dniAlumno,direccionAlumno):\n mydict={\"nombreAlumno\":nombreAlumno,\"apellidoAlumno\":apellidoAlumno\n ,\"dniAlumno\":dniAlumno,\"direccionAlumno\":direccionAlumno}\n return mydict\n \n# find\ndef find_alumno(nombreAlumno,apellidoAlumno,dniAlumno,direccionAlumno):\n query={\"nombreAlumno\":nombreAlumno,\"apellidoAlumno\":apellidoAlumno\n ,\"dniAlumno\":dniAlumno,\"direccionAlumno\":direccionAlumno}\n return query\n\n# delete\ndef delete_alumno(nombre,apellido):\n query={\"nombreAlumno\":nombre,\"apellidoAlumno\":apellido}\n return query\n\n# update\n# update\ndef update_input(nombre,apellido,dni,direccion):\n query={\"nombreAlumno\":nombre,\"apellidoAlumno\":apellido\n ,\"dniAlumno\":dni,\"direccionAlumno\":direccion}\n return query\n\ndef update_alumno(new_value,field): \n my_dict={'$set':{field:new_value}}\n return my_dict\n\n","sub_path":"Grupo6/a_alumno/funcion.py","file_name":"funcion.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472593079","text":"#!/usr/bin/python\n\nimport pandas as pd\nfrom patsy import dmatrices\nimport numpy as np\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nimport matplotlib.pyplot as plt\n\n#create a pandas DataFrame for the counts data set\ndf = pd.read_csv('nyc_bb_bicyclist_counts.csv', header=0, infer_datetime_format=True, parse_dates=[0], index_col=[0])\n\n#add a few derived regression variables to the X matrix\ndf['Date'] = pd.to_datetime(df['Date'])\ndf['MONTH'] = df['Date'].dt.month\ndf['DAY_OF_WEEK'] = df['Date'].dt.dayofweek\ndf['DAY'] = df['Date'].dt.day\n\n#create the training and testing data sets\nmask = np.random.rand(len(df)) < 0.8\n\ndf_train = df[mask]\nprint (\"\\r\\n============================== training data ================================\")\nprint (df_train)\n\n\ndf_test = df[~mask]\nprint (\"\\r\\n============================== test data ================================\")\nprint (df_test)\nprint('\\r\\nTraining data set length='+str(len(df_train)))\nprint('Testing data set length='+str(len(df_test)))\n\n#Setup the regression expression in patsy notation. We are telling patsy that BB_COUNT is our dependent variable and it depends on the regression variables: DAY, DAY_OF_WEEK, MONTH, HIGH_T, LOW_T and PRECIP\nexpr = \"\"\"BB_COUNT ~ DAY + DAY_OF_WEEK + MONTH + HIGH_T + LOW_T + PRECIP\"\"\"\n\n#Set up the X and y matrices for the training and testing data sets\ny_train, X_train = dmatrices(expr, df_train, return_type='dataframe')\ny_test, X_test = dmatrices(expr, df_test, return_type='dataframe')\n\n#Using the statsmodels GLM class, train the Poisson regression model on the training data set\npoisson_training_results = sm.GLM(y_train, X_train, family=sm.families.Poisson()).fit()\n\n#print out the training summary\nprint (\"\\r\\n============================== Poisson result ================================\")\nprint(poisson_training_results.summary())\n\n#print out the fitted rate vector\nprint(poisson_training_results.mu)\n\n#Add the λ vector as a new column called 'BB_LAMBDA' to the Data Frame of the training data set\ndf_train['BB_LAMBDA'] = poisson_training_results.mu\n\n#add a derived column called 'AUX_OLS_DEP' to the pandas Data Frame. This new column will store the values of the dependent variable of the OLS regression\ndf_train['AUX_OLS_DEP'] = df_train.apply(lambda x: ((x['BB_COUNT'] - x['BB_LAMBDA'])**2 - x['BB_COUNT']) / x['BB_LAMBDA'], axis=1)\n\n#use patsy to form the model specification for the OLSR\nols_expr = \"\"\"AUX_OLS_DEP ~ BB_LAMBDA - 1\"\"\"\n\n#Configure and fit the OLSR model\naux_olsr_results = smf.ols(ols_expr, df_train).fit()\n\n#Print the regression params\nprint(aux_olsr_results.params)\n\n#train the NB2 model on the training data set\nnb2_training_results = sm.GLM(y_train, X_train,family=sm.families.NegativeBinomial(alpha=aux_olsr_results.params[0])).fit()\n\n#print the training summary\nprint (\"\\r\\n============================== NB2 result ================================\")\nprint(nb2_training_results.summary())\n\n#make some predictions using our trained NB2 model\nnb2_predictions = nb2_training_results.get_prediction(X_test)\n\n#print out the predictions\npredictions_summary_frame = nb2_predictions.summary_frame()\nprint (\"\\r\\n============================== predictions_summary_frame ================================\")\nprint(predictions_summary_frame)\n\n#plot the predicted counts versus the actual counts for the test data\npredicted_counts=predictions_summary_frame['mean']\nactual_counts = y_test['BB_COUNT']\nfig = plt.figure()\nfig.suptitle('Predicted versus actual bicyclist counts on the Brooklyn bridge')\npredicted, = plt.plot(X_test.index, predicted_counts, 'go-', label='Predicted counts')\nactual, = plt.plot(X_test.index, actual_counts, 'ro-', label='Actual counts')\nplt.legend(handles=[predicted, actual])\nplt.show()\n","sub_path":"NBR/Nbr.py","file_name":"Nbr.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164075357","text":"\"\"\"Some common parsers\nSo you don't always have to start from scratch.\n\"\"\"\nfrom .combinator import All\nfrom .combinator import Any\nfrom .combinator import FLOAT\nfrom .combinator import Forward\nfrom .combinator import ID\nfrom .combinator import INT\nfrom .combinator import Middle\nfrom .combinator import Parser\nfrom .combinator import S\nfrom .combinator import STR\nfrom .combinator import Struct\nfrom .combinator import Token\nfrom .combinator import Triple\nfrom .results import Success\nfrom mtots import test\nfrom mtots.util.dataclasses import dataclass\nfrom mtots.util.lexer.common import lexer\nfrom mtots.util.source import Error\nfrom mtots.util.source import Mark\nfrom mtots.util.source import MARK\nfrom typing import Callable\nfrom typing import Generic\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import TypeVar\n\n\nE = TypeVar('E')\n\n\ndef _fail(mark: Mark, *args: object) -> E:\n raise Error([mark], f'Syntax not implemented')\n\n\ndef expression(\n exprtype: Type[E],\n *,\n inttype: Callable[[Mark, int], E],\n floattype: Callable[[Mark, float], E],\n idtype: Callable[[Mark, str], E],\n strtype: Callable[[Mark, str], E],\n subscripttype: Callable[[Mark, E, E], E],\n calltype: Callable[[Mark, E, Tuple[E, ...]], E],\n attrtype: Callable[[Mark, E, str], E],\n binoptype: Callable[[Mark, E, str, E], E],\n unoptype: Callable[[Mark, str, E], E],\n condtype: Callable[[Mark, E, E, E], E],\n and_token_type: str='and',\n or_token_type: str='or',\n atom: Parser[E]=Any[E]()) -> Parser[E]:\n return expression_and_postfix(\n exprtype=exprtype,\n inttype=inttype,\n floattype=floattype,\n idtype=idtype,\n strtype=strtype,\n subscripttype=subscripttype,\n calltype=calltype,\n attrtype=attrtype,\n binoptype=binoptype,\n unoptype=unoptype,\n condtype=condtype,\n and_token_type=and_token_type,\n or_token_type=or_token_type,\n atom=atom,\n )[0]\n\n\ndef expression_and_postfix(\n exprtype: Type[E],\n *,\n inttype: Callable[[Mark, int], E],\n floattype: Callable[[Mark, float], E],\n idtype: Callable[[Mark, str], E],\n strtype: Callable[[Mark, str], E],\n subscripttype: Callable[[Mark, E, E], E],\n calltype: Callable[[Mark, E, Tuple[E, ...]], E],\n attrtype: Callable[[Mark, E, str], E],\n binoptype: Callable[[Mark, E, str, E], E],\n unoptype: Callable[[Mark, str, E], E],\n condtype: Callable[[Mark, E, E, E], E],\n and_token_type: str='and',\n or_token_type: str='or',\n atom: Parser[E]=Any[E]()) -> Tuple[Parser[E], Parser[E]]:\n \"\"\"\n Constructs an expression parser and returns the\n expression and postfix parsers.\n The postfix parser is also useful because if the user wants\n to add additional patterns that involve assignment or\n type expresisons, often postfix tends to provide a good middle\n ground.\n \"\"\"\n expr = Forward(exprtype, lambda: assign)\n\n atom = Any(\n atom,\n ID.markmap(idtype),\n INT.markmap(inttype),\n FLOAT.markmap(floattype),\n STR.markmap(strtype),\n Middle('(', expr, ')'),\n )\n\n args = expr.join(S(',')).map(lambda args: tuple(args))\n\n postfix: Parser[E] = Forward(exprtype, lambda: Any(\n Struct(_Call, [\n ('owner', postfix),\n '(',\n ('args', args),\n S(')').required(),\n ]).map(lambda c: calltype(c.mark, c.owner, c.args)),\n Struct(_Subscript, [\n ('owner', postfix),\n '[',\n ('i', expr),\n S(']').required(),\n ]).map(lambda s: subscripttype(s.mark, s.owner, s.i)),\n Struct(_Attr, [\n ('owner', postfix),\n '.',\n ('name', ID.required()),\n ]).map(lambda a: attrtype(a.mark, a.owner, a.name)),\n atom,\n ))\n\n exponential: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(atom, '**', exponential, binoptype),\n postfix,\n ))\n\n unary: Parser[E] = Forward(exprtype, lambda: Any(\n _unop('-', unary, unoptype),\n _unop('~', unary, unoptype),\n exponential,\n ))\n\n multiplicative: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(multiplicative, '*', unary, binoptype),\n _binop(multiplicative, '/', unary, binoptype),\n _binop(multiplicative, '//', unary, binoptype),\n _binop(multiplicative, '%', unary, binoptype),\n unary,\n ))\n\n additive: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(additive, '+', multiplicative, binoptype),\n _binop(additive, '-', multiplicative, binoptype),\n multiplicative,\n ))\n\n comparison = Forward(exprtype, lambda: Any(\n _binop(additive, '==', additive, binoptype),\n _binop(additive, '!=', additive, binoptype),\n _binop(additive, '<', additive, binoptype),\n _binop(additive, '<=', additive, binoptype),\n _binop(additive, '>', additive, binoptype),\n _binop(additive, '>=', additive, binoptype),\n additive,\n ))\n\n and_: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(and_, and_token_type, comparison, binoptype),\n comparison,\n ))\n\n or_: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(or_, or_token_type, comparison, binoptype),\n and_,\n ))\n\n conditional: Parser[E] = Forward(exprtype, lambda: Any(\n Triple(\n or_,\n Middle('?', expr, All()),\n Middle(':', expr, All()),\n ).markmap(lambda m, t: condtype(m, t[0], t[1], t[2])),\n or_,\n ))\n\n assign: Parser[E] = Forward(exprtype, lambda: Any(\n _binop(postfix, '=', assign, binoptype),\n _binop(postfix, '+=', assign, binoptype),\n _binop(postfix, '-=', assign, binoptype),\n _binop(postfix, '*=', assign, binoptype),\n _binop(postfix, '/=', assign, binoptype),\n _binop(postfix, '//=', assign, binoptype),\n _binop(postfix, '%=', assign, binoptype),\n or_,\n ))\n\n return expr, postfix\n\n\ndef _binop(\n lhs: Parser[E],\n op: str,\n rhs: Parser[E],\n binoptype: Callable[[Mark, E, str, E], E]) -> Parser[E]:\n return Struct(_Binop, [\n ('left', lhs),\n op,\n ('right', rhs),\n ]).map(lambda b: binoptype(b.mark, b.left, op, b.right))\n\n\ndef _unop(\n op: str,\n expr: Parser[E],\n unoptype: Callable[[Mark, str, E], E]) -> Parser[E]:\n return Struct(_Unop, [\n op,\n ('expr', expr),\n ]).map(lambda u: unoptype(u.mark, op, u.expr))\n\n\n@dataclass(frozen=True)\nclass _Call(Generic[E]):\n mark: Mark\n owner: E\n args: Tuple[E, ...]\n\n\n@dataclass(frozen=True)\nclass _Subscript(Generic[E]):\n mark: Mark\n owner: E\n i: E\n\n\n@dataclass(frozen=True)\nclass _Attr(Generic[E]):\n mark: Mark\n owner: E\n name: str\n\n\n@dataclass(frozen=True)\nclass _Binop(Generic[E]):\n mark: Mark\n left: E\n right: E\n\n\n@dataclass(frozen=True)\nclass _Unop(Generic[E]):\n mark: Mark\n expr: E\n\n\ndef _handle(mark: Mark, *args: object) -> object:\n if len(args) == 1:\n return args[0]\n else:\n return list(args)\n\n_expr = expression(\n object,\n inttype=_handle,\n floattype=_handle,\n idtype=_handle,\n strtype=_handle,\n subscripttype=_handle,\n calltype=_handle,\n attrtype=_handle,\n binoptype=_handle,\n unoptype=_handle,\n condtype=_handle,\n)\n\n\ndef _parse(s: str) -> object:\n return _expr.match_string(s, lexer=lexer)\n\n\n@test.case\ndef basic_usage_test() -> None:\n test.equal(_parse('10'), Success(MARK, 10))\n test.equal(_parse('10 + 5'), Success(MARK, [10, '+', 5]))\n test.equal(_parse('(10) + 5'), Success(MARK, [10, '+', 5]))\n\n\n@test.case\ndef atoms_test() -> None:\n test.equal(_parse('a'), Success(MARK, 'a'))\n test.equal(_parse('abc'), Success(MARK, 'abc'))\n test.equal(_parse('15'), Success(MARK, 15))\n test.equal(_parse('14.24'), Success(MARK, 14.24))\n\n\n@test.case\ndef operator_precedence_test() -> None:\n test.equal(\n _parse('1 + 2 * 3'),\n Success(MARK, [1, '+', [2, '*', 3]]),\n )\n test.equal(\n _parse('(1 + 2) * 3'),\n Success(MARK, [[1, '+', 2], '*', 3]),\n )\n\n\n@test.case\ndef assignment_test() -> None:\n test.equal(\n _parse('x = 15'),\n Success(MARK, ['x', '=', 15]),\n )\n\n\n@test.case\ndef postfix_test() -> None:\n test.equal(\n _parse('f(x, \"hello world\")'),\n Success(MARK, ['f', ('x', 'hello world')]),\n )\n","sub_path":"mtots/util/parser/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":8574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410591080","text":"from functools import partial\n\nimport pytest\n\nfrom plenum.test.view_change.helper import provoke_and_wait_for_view_change\nfrom stp_core.loop.eventually import eventually\nfrom stp_core.common.log import getlogger\nfrom plenum.common.util import getMaxFailures\nfrom plenum.test import waits\nfrom plenum.test.delayers import ppDelay, icDelay\nfrom plenum.test.helper import sendRandomRequest, \\\n sendReqsToNodesAndVerifySuffReplies\nfrom plenum.test.test_node import TestReplica, getNonPrimaryReplicas, \\\n checkViewChangeInitiatedForNode\n\nnodeCount = 7\n\nlogger = getlogger()\n\n\n# TODO: This test needs to be implemented\n# noinspection PyIncorrectDocstring\n@pytest.mark.skip(reason='INDY-84. Complete implementation')\ndef testQueueingReqFromFutureView(delayed_perf_chk, looper, nodeSet, up,\n wallet1, client1):\n \"\"\"\n Test if every node queues 3 Phase requests(PRE-PREPARE, PREPARE and COMMIT)\n that come from a view which is greater than the current view. Slow down\n the primary node of master protocol instance, delay reception and\n processing of view change message by a non primary for master instance so\n that it starts receiving 3 phase commit messages for next view\n \"\"\"\n\n nprs = getNonPrimaryReplicas(nodeSet, 0)\n lagging_node = nprs[0].node\n old_view_no = lagging_node.viewNo\n\n # Delay processing of instance change on a node\n delay_ic = 60\n lagging_node.nodeIbStasher.delay(icDelay(delay_ic))\n logger.debug('{} will delay its view change'.format(lagging_node))\n\n # Delay processing of PRE-PREPARE from all non primary replicas of master\n # so master's throughput falls and view changes\n delay_pp = 5\n pp_delayer = ppDelay(delay_pp, 0)\n for r in nprs:\n r.node.nodeIbStasher.delay(pp_delayer)\n\n timeout = waits.expectedTransactionExecutionTime(len(nodeSet)) + delay_pp\n sendReqsToNodesAndVerifySuffReplies(looper, wallet1, client1, 5,\n customTimeoutPerReq=timeout)\n\n def chk_fut_view(view_no, is_empty):\n length = len(lagging_node.msgsForFutureViews.get(view_no, ()))\n if is_empty:\n assert length == 0\n else:\n assert length > 0\n return length\n\n # No messages queued for future view\n chk_fut_view(old_view_no+1, is_empty=True)\n logger.debug('{} does not have any messages for future views'\n .format(lagging_node))\n\n # Every node except Node A should do a view change\n provoke_and_wait_for_view_change(looper,\n [n for n in nodeSet if n != lagging_node],\n old_view_no + 1,\n wallet1, client1)\n\n for node in nodeSet:\n node.nodeIbStasher.nodelay(pp_delayer)\n\n sendReqsToNodesAndVerifySuffReplies(looper, wallet1, client1, 3,\n customTimeoutPerReq=timeout)\n\n # Messages queued for future view\n l = chk_fut_view(old_view_no + 1, is_empty=False)\n logger.debug('{} has {} messages for future views'\n .format(lagging_node, l))\n\n # Eventually no messages queued for future view\n looper.run(eventually(chk_fut_view, old_view_no + 1, True,\n retryWait=1, timeout=delay_ic+10))\n logger.debug('{} exhausted pending messages for future views'\n .format(lagging_node))\n\n # timeout = waits.expectedPoolViewChangeStartedTimeout(len(nodeSet)-1)\n # # for node in nodeSet:\n # # if node.name == nodeA.name:\n # # # Node A's view should not have changed yet\n # # with pytest.raises(AssertionError):\n # # looper.run(eventually(partial(\n # # checkViewChangeInitiatedForNode, node, 1),\n # # retryWait=1,\n # # timeout=timeout))\n # # else:\n # # looper.run(eventually(\n # # partial(checkViewChangeInitiatedForNode, node, 1),\n # # retryWait=1,\n # # timeout=timeout))\n #\n #\n # # NodeA should not have any pending 3 phase request for a later view\n # for r in nodeA.replicas: # type: TestReplica\n # assert len(r.threePhaseMsgsForLaterView) == 0\n #\n # # Reset delays on incoming messages from all nodes\n # for node in nodeSet:\n # node.nodeIbStasher.nodelay(pp_delayer)\n #\n # # Send one more request\n # sendRandomRequest(wallet1, client1)\n #\n # def checkPending3PhaseReqs():\n # # Get all replicas that have their primary status decided\n # reps = [rep for rep in nodeA.replicas if rep.isPrimary is not None]\n # # At least one replica should have its primary status decided\n # assert len(reps) > 0\n # for r in reps: # type: TestReplica\n # logger.debug(\"primary status for replica {} is {}\"\n # .format(r, r.primaryNames))\n # assert len(r.threePhaseMsgsForLaterView) > 0\n #\n # # NodeA should now have pending 3 phase request for a later view\n # timeout = waits.expectedPoolViewChangeStartedTimeout(len(nodeSet)) + delayIcA\n # looper.run(eventually(checkPending3PhaseReqs, retryWait=1, timeout=timeout))\n","sub_path":"plenum/test/view_change/test_queueing_req_from_future_view.py","file_name":"test_queueing_req_from_future_view.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472680925","text":"#\n# LSST Data Management System\n#\n# Copyright 2008-2017 AURA/LSST.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\"\"\"Select sources that are useful for astrometry.\n\nSuch sources have good signal-to-noise, are well centroided, not blended,\nand not flagged with a handful of \"bad\" flags.\n\"\"\"\n\nimport numpy as np\n\nimport lsst.pex.config as pexConfig\nfrom .sourceSelector import BaseSourceSelectorConfig, BaseSourceSelectorTask, sourceSelectorRegistry\nfrom lsst.pipe.base import Struct\nfrom functools import reduce\n\n\nclass AstrometrySourceSelectorConfig(BaseSourceSelectorConfig):\n badFlags = pexConfig.ListField(\n doc=\"List of flags which cause a source to be rejected as bad\",\n dtype=str,\n default=[\n \"base_PixelFlags_flag_edge\",\n \"base_PixelFlags_flag_interpolatedCenter\",\n \"base_PixelFlags_flag_saturatedCenter\",\n \"base_PixelFlags_flag_crCenter\",\n \"base_PixelFlags_flag_bad\",\n ],\n )\n sourceFluxType = pexConfig.Field(\n doc=\"Type of source flux; typically one of Ap or Psf\",\n dtype=str,\n default=\"Ap\",\n )\n minSnr = pexConfig.Field(\n dtype=float,\n doc=\"Minimum allowed signal-to-noise ratio for sources used for matching \"\n \"(in the flux specified by sourceFluxType); <= 0 for no limit\",\n default=10,\n )\n\n\n@pexConfig.registerConfigurable(\"astrometry\", sourceSelectorRegistry)\nclass AstrometrySourceSelectorTask(BaseSourceSelectorTask):\n \"\"\"Select sources that are useful for astrometry.\n\n Good astrometry sources have high signal/noise, are non-blended, and\n did not have certain \"bad\" flags set during source extraction. They need not\n be PSF sources, just have reliable centroids.\n \"\"\"\n ConfigClass = AstrometrySourceSelectorConfig\n\n def __init__(self, *args, **kwargs):\n BaseSourceSelectorTask.__init__(self, *args, **kwargs)\n\n def selectSources(self, sourceCat, matches=None, exposure=None):\n \"\"\"Return a selection of sources that are useful for astrometry.\n\n Parameters:\n -----------\n sourceCat : `lsst.afw.table.SourceCatalog`\n Catalog of sources to select from.\n This catalog must be contiguous in memory.\n matches : `list` of `lsst.afw.table.ReferenceMatch` or None\n Ignored in this SourceSelector.\n exposure : `lsst.afw.image.Exposure` or None\n The exposure the catalog was built from; used for debug display.\n\n Return\n ------\n struct : `lsst.pipe.base.Struct`\n The struct contains the following data:\n\n - selected : `array` of `bool``\n Boolean array of sources that were selected, same length as\n sourceCat.\n \"\"\"\n self._getSchemaKeys(sourceCat.schema)\n\n bad = reduce(lambda x, y: np.logical_or(x, sourceCat.get(y)), self.config.badFlags, False)\n good = self._isGood(sourceCat)\n return Struct(selected=good & ~bad)\n\n def _getSchemaKeys(self, schema):\n \"\"\"Extract and save the necessary keys from schema with asKey.\"\"\"\n self.parentKey = schema[\"parent\"].asKey()\n self.nChildKey = schema[\"deblend_nChild\"].asKey()\n self.centroidXKey = schema[\"slot_Centroid_x\"].asKey()\n self.centroidYKey = schema[\"slot_Centroid_y\"].asKey()\n self.centroidXSigmaKey = schema[\"slot_Centroid_xSigma\"].asKey()\n self.centroidYSigmaKey = schema[\"slot_Centroid_ySigma\"].asKey()\n self.centroidFlagKey = schema[\"slot_Centroid_flag\"].asKey()\n\n self.edgeKey = schema[\"base_PixelFlags_flag_edge\"].asKey()\n self.interpolatedCenterKey = schema[\"base_PixelFlags_flag_interpolatedCenter\"].asKey()\n self.saturatedKey = schema[\"base_PixelFlags_flag_saturated\"].asKey()\n\n fluxPrefix = \"slot_%sFlux_\" % (self.config.sourceFluxType,)\n self.fluxKey = schema[fluxPrefix + \"flux\"].asKey()\n self.fluxFlagKey = schema[fluxPrefix + \"flag\"].asKey()\n self.fluxSigmaKey = schema[fluxPrefix + \"fluxSigma\"].asKey()\n\n def _isMultiple(self, sourceCat):\n \"\"\"Return True for each source that is likely multiple sources.\"\"\"\n test = (sourceCat.get(self.parentKey) != 0) | (sourceCat.get(self.nChildKey) != 0)\n # have to currently manage footprints on a source-by-source basis.\n for i, cat in enumerate(sourceCat):\n footprint = cat.getFootprint()\n test[i] |= (footprint is not None) and (len(footprint.getPeaks()) > 1)\n return test\n\n def _hasCentroid(self, sourceCat):\n \"\"\"Return True for each source that has a valid centroid\"\"\"\n def checkNonfiniteCentroid():\n \"\"\"Return True for sources with non-finite centroids.\"\"\"\n return ~np.isfinite(sourceCat.get(self.centroidXKey)) | \\\n ~np.isfinite(sourceCat.get(self.centroidYKey))\n assert ~checkNonfiniteCentroid().any(), \\\n \"Centroids not finite for %d unflagged sources.\" % (checkNonfiniteCentroid().sum())\n return np.isfinite(sourceCat.get(self.centroidXSigmaKey)) \\\n & np.isfinite(sourceCat.get(self.centroidYSigmaKey)) \\\n & ~sourceCat.get(self.centroidFlagKey)\n\n def _goodSN(self, sourceCat):\n \"\"\"Return True for each source that has Signal/Noise > config.minSnr.\"\"\"\n if self.config.minSnr <= 0:\n return True\n else:\n with np.errstate(invalid=\"ignore\"): # suppress NAN warnings\n return sourceCat.get(self.fluxKey)/sourceCat.get(self.fluxSigmaKey) > self.config.minSnr\n\n def _isUsable(self, sourceCat):\n \"\"\"\n Return True for each source that is usable for matching, even if it may\n have a poor centroid.\n\n For a source to be usable it must:\n - have a valid centroid\n - not be deblended\n - have a valid flux (of the type specified in this object's constructor)\n - have adequate signal-to-noise\n \"\"\"\n\n return self._hasCentroid(sourceCat) \\\n & ~self._isMultiple(sourceCat) \\\n & self._goodSN(sourceCat) \\\n & ~sourceCat.get(self.fluxFlagKey)\n\n def _isGood(self, sourceCat):\n \"\"\"\n Return True for each source that is usable for matching and likely has a\n good centroid.\n\n The additional tests for a good centroid, beyond isUsable, are:\n - not interpolated in the center\n - not saturated\n - not near the edge\n \"\"\"\n\n return self._isUsable(sourceCat) \\\n & ~sourceCat.get(self.saturatedKey) \\\n & ~sourceCat.get(self.interpolatedCenterKey) \\\n & ~sourceCat.get(self.edgeKey)\n\n def _isBadFlagged(self, source):\n \"\"\"Return True if any of config.badFlags are set for this source.\"\"\"\n return any(source.get(flag) for flag in self.config.badFlags)\n","sub_path":"python/lsst/meas/algorithms/astrometrySourceSelector.py","file_name":"astrometrySourceSelector.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387462909","text":"#!/usr/bin/env python3\n\n\"\"\"\nSaltyBet scraper and betting bot. \n\"\"\"\n\n# Import\nimport requests\nimport datetime\nimport json\nimport time\n\ndef getUpdate():\n # Get the current state\n state = requests.get('http://www.saltybet.com/zdata.json').json()\n\n # Calculate bet counts\n counts = [0, 0]\n avgBet = [0, 0]\n for key in state:\n try:\n int(key)\n playerData = state[key]\n if state['status'] == 'locked':\n counts[int(playerData['p'])-1] += 1\n avgBet[int(playerData['p'])-1] += int(playerData['w'])\n except ValueError as e:\n print(\"ValueError: \", e)\n continue\n if state['status'] == 'locked':\n for i in range(0,2):\n avgBet[i] = round(avgBet[i]/counts[i],2)\n\n # Calculate SaltyBet's odds\n state['p1total'] = int(state['p1total'].replace(',',''))\n state['p2total'] = int(state['p2total'].replace(',',''))\n \n # Store values to reduce dict-access overhead when calculating odds.\n p1 = state['p1total']\n p2 = state['p2total']\n \n odds1 = round(p1 / p2 if p1 > p2 else 1, 1)\n odds2 = round(p2 / p1 if p2 > p1 else 1, 1)\n # cleanup temporary variables\n del p1\n del p2\n odds = (odds1, odds2)\n \n d = datetime.datetime.today()\n date = (d.month, d.day, d.year)\n \n # Put everything in a dictionary\n data = {\n 'status' : (state['status'],'ended')[state['status'] in ['1','2']],\n 'odds' : odds,\n 'date' : date,\n 'player1': {\n 'name' : state['p1name'],\n 'bettingCount' : counts[0],\n 'bettingAmount': state['p1total'], \n 'avgBet' : avgBet[0],\n 'winner' : True if state['status'] == '1' else False\n },\n 'player2': {\n 'name' : state['p2name'],\n 'bettingCount' : counts[1],\n 'bettingAmount': state['p2total'],\n 'avgBet' : avgBet[1],\n 'winner' : True if state['status'] == '2' else False\n }\n }\n return data\n\ndef loop(heldState):\n # Check the state\n updatedState = getUpdate()\n # This will contain the betting data for the match; fight in progress\n if updatedState['status'] == 'locked':\n print('Fight in progress')\n heldState = updatedState\n\n # Don't have the bet numbers for the previous match, currently betting\n elif updatedState['status'] == 'ended' and not bool(heldState): \n print('Currently betting, no previous match data.')\n\n # This will contain the winner; save the full data from this round\n # and then bet on the new fighters\n elif updatedState['status'] == 'ended' and bool(heldState): \n print('Currently betting, saving previous match data.')\n heldState['player1']['winner'] = updatedState['player1']['winner']\n heldState['player2']['winner'] = updatedState['player2']['winner']\n\n return heldState\n\nif __name__ == '__main__':\n interval = 30.0 # Time interval in seconds\n startTime = time.time()\n heldState = {}\n while True: \n heldState = loop(heldState)\n print(heldState)\n time.sleep(interval - ((time.time()-startTime) % interval))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"616700344","text":"T_INT = 'अंकम्'\nT_FLOAT = 'चरः'\nT_STRING = 'सूत्र'\nT_PLUS = 'योजनम्'\nT_MINUS = 'ऊन'\nT_MUL = 'गुणता'\nT_DIV = 'भेद'\nT_MOD = 'प्रतिशत'\nT_EOF = 'समन्त'\nT_KEYWORD = \"आरक्षितपद\"\nT_IDENTIFIER = \"नामन्\"\nT_NL = 'नवीन् पङ्क्ति'\nT_THEN = '~'\nT_POW = '^'\nT_LCURL = '{'\nT_RCURL = '}'\nT_LPAREN = '('\nT_RPAREN = ')'\nT_LSQUARE = '['\nT_RSQUARE = ']'\nT_EQU = \"=\"\nT_ISNEQ = '!='\nT_ISEQ = '=='\nT_BIT_AND= \"&\"\nT_BIT_OR=\"|\"\nT_BIT_NOT=\"$\"\nT_ISG = '>'\nT_RSHIFT = '>>'\nT_ISL = '<'\nT_LSHIFT = '<<'\nT_XOR = \"^^\"\nT_ISGEQ = '>='\nT_ISLEQ = '<='\nT_NOT = '!'\nT_COMMA = ','\nT_SEP = ';'\nT_FACT = 'T_FACT'\n\nKEYWORDS = ['च', 'वा', 'न', 'असत्यम्', 'सत्यम्', 'यावद्', 'प्रति', 'कार्य', 'यदि', 'नोचेत्', 'चेत्',\n 'अनुवर्तते', 'विघ्नः', 'यच्छ']\n\n\nclass Token:\n def __init__(self, type_, value=None, pos_start=None, pos_end=None):\n self.type = type_\n self.value = value\n\n if pos_start:\n self.pos_start = pos_start.copy()\n self.pos_end = pos_start.copy()\n self.pos_end.advance()\n\n if pos_end:\n self.pos_end = pos_end.copy()\n\n def matches(self, type_, value):\n return self.type == type_ and self.value == value\n\n def __repr__(self):\n if self.value:\n return f'{self.type}->{self.value}'\n return f'{self.type}'\n","sub_path":"Sansam/Lexer/Token.py","file_name":"Token.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"544468270","text":"# 导入必要的模块\nimport csv\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfrom matplotlib import dates as mdates\n\n# 从文件中获取日期、最高气温和最低气温\nfilename = '/home/yyh/Documents/VSCode_work/chapter16/sitka_weather_2014.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n\n dates, highs, lows = [], [], []\n for row in reader:\n try:\n current_date = datetime.strptime(row[0], \"%Y-%m-%d\")\n high = int(row[1])\n low = int(row[3])\n except ValueError:\n print(current_date, 'missing data')\n else:\n dates.append(current_date)\n highs.append(high)\n lows.append(low)\n\n# Plot data.\nfig = plt.figure(dpi=128, figsize=(10, 6))\nplt.plot(dates, highs, c='red', alpha=0.5)\nplt.plot(dates, lows, c='blue', alpha=0.5)\nplt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)\n\n# Format plot.\ntitle = \"Daily high and low temperatures - 2014\\nSitka, AK\"\nplt.title(title, fontsize=20)\nplt.xlabel('', fontsize=16)\nfig.autofmt_xdate()\nplt.ylabel(\"Temperature (F)\", fontsize=16)\nplt.tick_params(axis='both', top=True, right=True, which='both', labelsize=16)\nplt.ylim(10, 120)\nplt.xlim(dates[0], dates[-1]) # 这样也可以的\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # 日期格式,%B为月份名,%b为月份名缩写\n\n# plt.show()\nplt.savefig(\"/home/yyh/Documents/VSCode_work/chapter16/chapter16_16_2_0\", bbox_inches='tight')\n","sub_path":"VSCode_work/chapter16/chapter16_16_2_0.py","file_name":"chapter16_16_2_0.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543285007","text":"# -*- coding:utf-8 -*-\n\nimport json\nimport sys\nimport os\n\n__author__ = 'Midas'\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nTMP_DIR = \"tmp\"\nJSON_DIR = \"json\"\n\n\ndef prepare_directory(sql_path):\n head, tail = os.path.split(sql_path)\n if not os.access(head, os.F_OK):\n os.makedirs(head)\n\n\ndef process_json(json_path):\n with open(json_path, \"r\") as f:\n json_list = json.load(f)\n\n sql_commands = map(lambda json_object: process_command(json_object) + \"\\n\", json_list)\n\n sql_path = os.path.join(TMP_DIR, json_path.replace(\"json\", \"sql\"))\n prepare_directory(sql_path)\n with open(sql_path, \"w\") as f:\n f.writelines(sql_commands)\n\n\ndef process_command(json_object):\n table_name = json_object[\"$table_name\"]\n name_field = filter(lambda name: name not in [\"$table_name\"], json_object.iterkeys())\n name_field = map(lambda name: name.strip(\"'\"), name_field)\n value_field = map(lambda name: json_object[name], name_field)\n\n sql_command = \"INSERT INTO %s (%s) VALUES\\n (%s);\" % (table_name, \", \".join(name_field), \", \".join(value_field))\n\n return sql_command\n\n\ndef get_json_list():\n json_path_list = list()\n\n for root, dirs, files in os.walk(JSON_DIR):\n for filename in files:\n if filename.endswith(\".json\"):\n json_path_list.append(os.path.join(root, filename))\n\n return json_path_list\n\njson_path_list = get_json_list()\nfor json_path in json_path_list:\n process_json(json_path)\n","sub_path":"src/json2sql.py","file_name":"json2sql.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226261440","text":"# geometry.py\n# ---------------\n# Licensing Information: You are free to use or extend this projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to the University of Illinois at Urbana-Champaign\n#\n# Created by Jongdeog Lee (jlee700@illinois.edu) on 09/12/2018\n\n\"\"\"\nThis file contains geometry functions that relate with Part1 in MP2.\n\"\"\"\n\nimport math\nimport numpy as np\nfrom const import *\n\ndef computeCoordinate(start, length, angle):\n \"\"\"Compute the end cooridinate based on the given start position, length and angle.\n\n Args:\n start (tuple): base of the arm link. (x-coordinate, y-coordinate)\n length (int): length of the arm link\n angle (int): degree of the arm link from x-axis to couter-clockwise\n\n Return:\n End position (int,int):of the arm link, (x-coordinate, y-coordinate)\n \"\"\"\n return (start[0]+(length*math.cos(math.radians(angle))), start[1]-(length*math.sin(math.radians(angle))))\n\ndef doesArmTouchObjects(armPosDist, objects, isGoal=False):\n \"\"\"Determine whether the given arm links touch any obstacle or goal\n\n Args:\n armPosDist (list): start and end position and padding distance of all arm links [(start, end, distance)]\n objects (list): x-, y- coordinate and radius of object (obstacles or goals) [(x, y, r)]\n isGoal (bool): True if the object is a goal and False if the object is an obstacle.\n When the object is an obstacle, consider padding distance.\n When the object is a goal, no need to consider padding distance.\n Return:\n True if touched. False if not.\n \"\"\"\n for arm in armPosDist:\n arm_start = np.array(arm[0]) \n arm_end = np.array(arm[1]) \n pad = 0 if isGoal else arm[2] # if obstacle, add padding\n \n armdist = arm_end - arm_start \n arml = np.dot(armdist, armdist) \n armp = np.dot(arm_start, arm_start) \n \n for obj in objects:\n obj_loc = np.array([obj[0], obj[1]])\n r = obj[2] + pad # don't forget to add padding \n perp_loc = np.dot(armdist, arm_start - obj_loc) * 2\n inct = armp + np.dot(obj_loc, obj_loc) - 2 * np.dot(arm_start, obj_loc) - r ** 2\n disc = perp_loc ** 2 - 4 * arml * inct\n if disc < 0: continue\n \n # cases where the arm is touching obj\n sqrt = math.sqrt(disc)\n target_d1 = (-perp_loc + sqrt) / (2 * arml)\n if 0 <= target_d1 <= 1: return True\n\n target_d2 = (-perp_loc - sqrt) / (2 * arml)\n if 0 <= target_d2 <= 1: return True\n \n return False\n\ndef doesArmTipTouchGoals(armEnd, goals):\n \"\"\"Determine whether the given arm tip touch goals\n\n Args:\n armEnd (tuple): the arm tip position, (x-coordinate, y-coordinate)\n goals (list): x-, y- coordinate and radius of goals [(x, y, r)]. There can be more than one goal.\n Return:\n True if arm tick touches any goal. False if not.\n \"\"\"\n for goal in goals:\n distance = math.hypot(armEnd[0] - goal[0], armEnd[1] - goal[1])\n if distance <= goal[2]: \n return True\n \n return False\n\ndef isArmWithinWindow(armPos, window):\n \"\"\"Determine whether the given arm stays in the window\n\n Args:\n armPos (list): start and end positions of all arm links [(start, end)]\n window (tuple): (width, height) of the window\n\n Return:\n True if all parts are in the window. False if not.\n \"\"\"\n width, height = window \n for arm in armPos:\n for p in arm:\n if width < p[0] or p[0] < 0: return False\n if height < p[1] or p[1] < 0: return False\n\n return True\n\n\nif __name__ == '__main__':\n computeCoordinateParameters = [((150, 190),100,20), ((150, 190),100,40), ((150, 190),100,60), ((150, 190),100,160)]\n resultComputeCoordinate = [(243, 156), (226, 126), (200, 104), (57, 156)]\n testRestuls = [computeCoordinate(start, length, angle) for start, length, angle in computeCoordinateParameters]\n assert testRestuls == resultComputeCoordinate\n\n testArmPosDists = [((100,100), (135, 110), 4), ((135, 110), (150, 150), 5)]\n testObstacles = [[(120, 100, 5)], [(110, 110, 20)], [(160, 160, 5)], [(130, 105, 10)]]\n resultDoesArmTouchObjects = [\n True, True, False, True, False, True, False, True,\n False, True, False, True, False, False, False, True\n ]\n\n testResults = []\n for testArmPosDist in testArmPosDists:\n for testObstacle in testObstacles:\n testResults.append(doesArmTouchObjects([testArmPosDist], testObstacle))\n # print(testArmPosDist)\n # print(doesArmTouchObjects([testArmPosDist], testObstacle))\n\n print(\"\\n\")\n for testArmPosDist in testArmPosDists:\n for testObstacle in testObstacles:\n testResults.append(doesArmTouchObjects([testArmPosDist], testObstacle, isGoal=True))\n # print(testArmPosDist)\n # print(doesArmTouchObjects([testArmPosDist], testObstacle, isGoal=True))\n\n assert resultDoesArmTouchObjects == testResults\n\n testArmEnds = [(100, 100), (95, 95), (90, 90)]\n testGoal = [(100, 100, 10)]\n resultDoesArmTouchGoals = [True, True, False]\n\n testResults = [doesArmTipTouchGoals(testArmEnd, testGoal) for testArmEnd in testArmEnds]\n assert resultDoesArmTouchGoals == testResults\n\n testArmPoss = [((100,100), (135, 110)), ((135, 110), (150, 150))]\n testWindows = [(160, 130), (130, 170), (200, 200)]\n resultIsArmWithinWindow = [True, False, True, False, False, True]\n testResults = []\n for testArmPos in testArmPoss:\n for testWindow in testWindows:\n testResults.append(isArmWithinWindow([testArmPos], testWindow))\n assert resultIsArmWithinWindow == testResults\n\n print(\"Test passed\\n\")\n","sub_path":"mp2/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"339879798","text":"import rospy as ros\nimport baxter_interface as baxter\nimport json\nimport positionControl as pos\nimport taskFunctions as tasks\nimport time\nfrom threading import *\nfrom baxter_pykdl import baxter_kinematics\nimport ctypes\n\n\ndef terminate_thread(thread):\n \"\"\"Terminates a python thread from another thread.\n\n :param thread: a threading.Thread instance\n \"\"\"\n if not thread.isAlive():\n return\n\n exc = ctypes.py_object(KeyboardInterrupt)\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(\n ctypes.c_long(thread.ident), exc)\n if res == 0:\n raise ValueError(\"nonexistent thread id\")\n elif res > 1:\n # \"\"\"if it returns a number greater than one, you're in trouble,\n # and you should call it again with exc=NULL to revert the effect\"\"\"\n ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)\n raise SystemError(\"PyThreadState_SetAsyncExc failed\")\n\n\nros.init_node('cartRecorder')\n\nbaxter_enabler = baxter.RobotEnable(versioned=True)\nbaxter_enabler.enable()\n\nlLimb = baxter.Limb('left')\nrLimb = baxter.Limb('right')\nlGripper = baxter.Gripper('left')\nrGripper = baxter.Gripper('right')\n\n# calibrating gripper\nif not lGripper.calibrate():\n print(\"left gripper did not calibrate\")\n sys.exit()\n\nlGripper.set_holding_force(100)\nlGripper.set_moving_force(100)\n\nrGripper.set_holding_force(100)\nrGripper.set_moving_force(100)\n\nhead = baxter.Head()\nhead.set_pan(1.5707)\n","sub_path":"ros_ws/Archive/ProductFiles20180511/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"272030708","text":"import pprint\n\nfrom collections import defaultdict\nfrom typing import List, Tuple, Dict\n\npp = pprint.PrettyPrinter(indent=4)\n\nfile = 'a.txt'\n\n\nclass Cart:\n def __init__(self, pos: complex, di: complex):\n self.position = pos\n self.direction = di\n self.cross_mod = 0\n self.dead = False\n\n\ndef parse(data: List[str]):\n tracks = defaultdict(lambda: \"\")\n carts = []\n\n for y, line in enumerate(data):\n for x, char in enumerate(line):\n if char == \"\\n\":\n continue\n if char in \"^\":\n direction = {\n \"<\": -1,\n \"v\": +1j,\n \">\": +1,\n \"^\": -1j,\n }[char]\n carts.append(Cart(x + y * 1j, direction)) # location, direction, crossings\n part = {\n \"<\": \"-\",\n \"v\": \"|\",\n \">\": \"-\",\n \"^\": \"|\",\n }[char]\n else:\n part = char\n if part in \"\\\\/+\":\n tracks[(x + y * 1j)] = part\n return tracks, carts\n\n\ndef turn_cart(cart: Cart, part: str):\n \"\"\"This space uses a downwards-facing Y axis, which means all calculations\n must flip their imaginary part. For example, rotation to the left\n (counterclockwise) would be multiplying by -1j instead of by +1j.\"\"\"\n if not part: # empty track is impossible, and | or - don't matter\n return\n if part == \"\\\\\":\n if cart.direction.real == 0:\n cart.direction *= -1j # ⮡ ⮢\n else:\n cart.direction *= +1j # ⮧ ⮤\n if part == \"/\":\n if cart.direction.real == 0:\n cart.direction *= +1j # ⮣ ⮠\n else:\n cart.direction *= -1j # ⮥ ⮦\n if part == \"+\":\n cart.direction *= -1j * 1j ** cart.cross_mod # rotate left, forward, or right\n cart.cross_mod = (cart.cross_mod + 1) % 3\n\ndef solve_a(data: List[str]) -> str:\n tracks, carts = parse(data)\n while True:\n carts.sort(key=lambda c: (c.position.imag, c.position.real))\n for ci, cart in enumerate(carts):\n cart.position += cart.direction\n if any(c2.position == cart.position for c2i, c2 in enumerate(carts) if c2i != ci):\n return str(int(cart.position.real)) + \",\" + str(int(cart.position.imag))\n part = tracks[cart.position]\n turn_cart(cart, part)\n\ndef solve_b(data: List[str]) -> str:\n tracks, carts = parse(data)\n while len(carts) > 1:\n carts.sort(key=lambda c: (c.position.imag, c.position.real))\n for ci, cart in enumerate(carts):\n if cart.dead:\n continue\n cart.position += cart.direction\n for ci2, cart2 in enumerate(carts):\n if ci != ci2 and cart.position == cart2.position and not cart2.dead:\n cart.dead = True\n cart2.dead = True\n break\n if cart.dead:\n continue\n part = tracks[cart.position]\n turn_cart(cart, part)\n carts = [c for c in carts if not c.dead]\n if not carts:\n return \"ERROR: there's an even number of carts, there's isn't 1 cart left at the end!\"\n cart = carts[0]\n return str(int(cart.position.real)) + \",\" + str(int(cart.position.imag))\n\n\ndef main():\n data = [_.strip('\\n') for _ in open(file).readlines()]\n print(solve_a(data))\n print(solve_b(data))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"13/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"428306030","text":"#!/usr/bin/env python\n# Filename: raster_io \n\"\"\"\nintroduction: Based on rasterio, to read and write raster data\n\nauthors: Huang Lingcao\nemail:huanglingcao@gmail.com\nadd time: 03 January, 2021\n\"\"\"\n\nimport os, sys\nfrom optparse import OptionParser\nimport rasterio\nimport numpy as np\n\ndef open_raster_read(raster_path):\n src = rasterio.open(raster_path)\n return src\n\ndef get_width_heigth_bandnum(opened_src):\n return opened_src.height, opened_src.width, opened_src.count\n\ndef read_oneband_image_to_1dArray(image_path,nodata=None, ignore_small=None):\n\n if os.path.isfile(image_path) is False:\n raise IOError(\"error, file not exist: \" + image_path)\n\n with rasterio.open(image_path) as img_obj:\n # read the all bands (only have one band)\n indexes = img_obj.indexes\n if len(indexes) != 1:\n raise IOError('error, only support one band')\n\n data = img_obj.read(indexes)\n data_1d = data.flatten() # convert to one 1d, row first.\n\n # input nodata\n if nodata is not None:\n data_1d = data_1d[data_1d != nodata]\n # the nodata in the image meta.\n if img_obj.nodata is not None:\n data_1d = data_1d[data_1d != img_obj.nodata]\n\n if ignore_small is not None:\n data_1d = data_1d[data_1d >= ignore_small ]\n\n return data_1d\n\ndef read_raster_all_bands_np(raster_path):\n\n with rasterio.open(raster_path) as src:\n indexes = src.indexes\n\n data = src.read(indexes) # output (1, 8249, 13524), (band_count, height, width)\n\n # print(data.shape)\n # print(src.nodata)\n if src.nodata is not None and src.dtypes[0] == 'float32':\n data[ data == src.nodata ] = np.nan\n\n return data, src.nodata\n\ndef read_raster_one_band_np(raster_path):\n with rasterio.open(raster_path) as src:\n indexes = src.indexes\n if len(indexes) != 1:\n raise IOError('error, only support one band')\n\n # data = src.read(indexes) # output (1, 8249, 13524)\n data = src.read(1) # output (8249, 13524)\n print(data.shape)\n # print(src.nodata)\n if src.nodata is not None:\n data[ data == src.nodata ] = np.nan\n return data\n\ndef save_numpy_array_to_rasterfile(numpy_array, save_path, ref_raster, format='GTiff', nodata=None,\n compress=None, tiled=None, bigtiff=None):\n '''\n save a numpy to file, the numpy has the same projection and extent with ref_raster\n Args:\n numpy_array:\n save_path:\n ref_raster:\n format:\n\n Returns:\n\n '''\n if numpy_array.ndim == 2:\n band_count = 1\n height,width = numpy_array.shape\n # reshape to 3 dim, to write the disk\n numpy_array = numpy_array.reshape(band_count, height, width)\n elif numpy_array.ndim == 3:\n band_count, height,width = numpy_array.shape\n else:\n raise ValueError('only accept ndim is 2 or 3')\n\n dt = np.dtype(numpy_array.dtype)\n\n print('dtype:', dt.name)\n print(numpy_array.dtype)\n print('band_count,height,width',band_count,height,width)\n # print('saved numpy_array.shape',numpy_array.shape)\n\n with rasterio.open(ref_raster) as src:\n # test: save it to disk\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": format,\n \"height\": height,\n \"width\": width,\n \"count\":band_count,\n \"dtype\": dt.name\n })\n if nodata is not None:\n out_meta.update({\"nodata\": nodata})\n\n if compress is not None:\n out_meta.update(compress=compress)\n if tiled is not None:\n out_meta.update(tiled=tiled)\n if bigtiff is not None:\n out_meta.update(bigtiff=bigtiff)\n\n with rasterio.open(save_path, \"w\", **out_meta) as dest:\n dest.write(numpy_array)\n\n print('save to %s'%save_path)\n\n return True\n\ndef image_numpy_to_8bit(img_np, max_value, min_value, src_nodata=None, dst_nodata=None):\n '''\n convert float or 16 bit to 8bit,\n Args:\n img_np: numpy array\n max_value:\n min_value:\n src_nodata:\n dst_nodata: if output nodata is 0, then covert data to 1-255, if it's 255, then to 0-254\n\n Returns: new numpy array\n\n '''\n print('Convert to 8bit, old max, min: %.4f, %.4f'%(max_value, min_value))\n nan_loc = np.where(np.isnan(img_np))\n if nan_loc[0].size > 0:\n img_np = np.nan_to_num(img_np)\n\n img_np[img_np > max_value] = max_value\n img_np[img_np < min_value] = min_value\n\n if dst_nodata == 0:\n n_max, n_min = 255, 1\n elif dst_nodata == 255:\n n_max, n_min = 254, 0\n else:\n n_max, n_min = 255, 0\n\n # scale the grey values to 0 - 255 for better display\n k = (n_max - n_min)*1.0/(max_value - min_value)\n new_img_np = (img_np - min_value) * k + n_min\n new_img_np = new_img_np.astype(np.uint8)\n\n # replace nan data as nodata\n if nan_loc[0].size > 0:\n if dst_nodata is not None:\n new_img_np[nan_loc] = dst_nodata\n else:\n new_img_np[nan_loc] = n_min\n\n return new_img_np\n\ndef main():\n pass\n\n\nif __name__=='__main__':\n main()\n","sub_path":"raster_io.py","file_name":"raster_io.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"617110435","text":"# -------------------------------------------------------------------------------\n# Copyright IBM Corp. 2017\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 pixiedust.display.app import *\nimport sys\nimport os\nimport requests\nimport json\nimport nbformat\nfrom pixiedust.utils.userPreferences import getUserPreference, setUserPreference\nfrom pixiedust.utils import Logger\nimport warnings\nimport pkg_resources\nfrom jupyter_client.manager import KernelManager\n\nimport ast\nclass ImportsLookup(ast.NodeVisitor):\n def __init__(self):\n self.imports = set()\n\n #pylint: disable=E0213,E1102\n def onvisit(func):\n def wrap(self, node):\n ret_node = func(self, node)\n super(ImportsLookup, self).generic_visit(node)\n return ret_node\n return wrap\n\n def add_import(self, module_name):\n if not module_name in sys.builtin_module_names:\n try:\n module = __import__(module_name)\n ok_to_add = module.__package__ != \"\"\n if not ok_to_add and \"site-packages\" in module.__file__:\n ok_to_add = True\n #check if egg-link (aka editable mode)\n if not ok_to_add:\n for p in sys.path:\n if os.path.isfile(os.path.join(p,module_name+\".egg-link\")):\n ok_to_add = True\n\n if ok_to_add:\n try:\n pkg = pkg_resources.get_distribution(module_name)\n version = pkg.parsed_version._version.release\n self.imports.add( (module_name, version, self.get_egg_url(pkg, module_name)) )\n except pkg_resources.DistributionNotFound:\n pass\n except:\n print(\"Unknown import found {}\".format(module_name))\n\n def get_egg_url(self, pkg, module_name):\n if requests.get(\"https://pypi.python.org/pypi/{}/json\".format(module_name)).status_code == 200:\n return None\n def try_location(base, name):\n ret = os.path.join(base,name)\n if not os.path.exists(ret):\n ret = os.path.join(base, name.replace(\"-\", \"_\"))\n if not os.path.exists(ret):\n ret = os.path.join(base, name.replace(\"_\", \"-\"))\n return ret\n \n location = pkg.location\n if not os.path.exists(os.path.join(location, \"setup.py\")):\n location = try_location(location, module_name)\n if not os.path.exists(os.path.join(location, \"setup.py\")):\n #try the github page\n pkg_info = os.path.join(pkg.location, \"{}.egg-info\".format(pkg.egg_name()), \"PKG-INFO\")\n if os.path.isfile(pkg_info):\n with open(pkg_info) as fp:\n for line in fp.readlines():\n index = line.find(':')\n if index>0:\n key = line[0:index].strip()\n if key.lower()==\"home-page\":\n return \"git+{}#egg={}\".format(line[index+1:].strip(), module_name)\n \n @onvisit\n def visit_ImportFrom(self, node):\n self.add_import(node.module.split(\".\")[0])\n \n @onvisit\n def visit_Import(self, node):\n for name in node.names:\n self.add_import(name.name)\n \n @onvisit\n def generic_visit(self, node):\n pass\n\n@PixieApp\n@Logger()\nclass PublishApp():\n \"\"\"\n Publish a PixieApp as a web app\n \"\"\"\n \n def setup(self):\n self.server = getUserPreference(\"pixie_gateway_server\", \"http://localhost:8899\")\n self.kernel_spec = None\n self.lookup = None\n \n def set_contents(self, contents):\n self.contents = json.loads(contents)\n self.contents['notebook']['metadata']['pixiedust'] = {}\n kernel_spec = self.contents['notebook']['metadata']['kernelspec']\n km = KernelManager(kernel_name=kernel_spec['name'])\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.kernel_spec = json.dumps(km.kernel_spec.to_dict(), indent=4, sort_keys=True)\n \n @route(publish_server=\"*\")\n def publish(self, publish_server, publish_title, publish_icon):\n self.server = publish_server\n self.contents['notebook']['metadata']['pixiedust'].update({\"title\":publish_title, \"icon\":publish_icon})\n self.compute_imports()\n setUserPreference(\"pixie_gateway_server\", publish_server)\n response = requests.post(\n \"{}/publish/{}\".format(self.server, self.contents['name']), \n json = self.contents['notebook']\n )\n if response.status_code == requests.codes.ok:\n self.pixieapp_model = response.json()\n return \"\"\"\n\n
\n
\n {%for message in this.pixieapp_model['log']%}\n
\n {{message}}\n
\n {%endfor%}\n
\n
\n
Notebook Successfully published
\n \n
\n
\n \"\"\"\n \n return \"
An Error occured while publishing this notebook: {}\".format(response.text)\n\n \n def ast_parse(self, code):\n try:\n #Do we even need to sanitize\n return ast.parse(code)\n except SyntaxError:\n pass\n\n def translateMagicLine(line):\n index = line.find('%')\n if index >= 0:\n try:\n ast.parse(line)\n except SyntaxError:\n magic_line = line[index+1:].split()\n line= \"\"\"{} get_ipython().run_line_magic(\"{}\", \"{}\")\"\"\".format(\n line[:index], magic_line[0], ' '.join(magic_line[1:])\n ).strip()\n return line\n return ast.parse('\\n'.join([translateMagicLine(p) for p in code.split('\\n') if not p.strip().startswith('!')]))\n\n def compute_imports(self):\n if self.lookup is None:\n notebook = nbformat.from_dict(self.contents['notebook'])\n code = \"\"\n for cell in notebook.cells:\n if cell.cell_type == \"code\":\n code += \"\\n\" + cell.source \n self.lookup = ImportsLookup()\n self.lookup.visit(ast.parse(self.ast_parse(code)))\n self.contents['notebook']['metadata']['pixiedust'].update({\n \"imports\": {p[0]:{\"version\":p[1],\"install\":p[2]} for p in self.lookup.imports}\n })\n \n @route(importTable=\"*\")\n def imports(self):\n self.compute_imports()\n return \"\"\"\n\n \n \n \n \n \n \n \n \n {% for import in this.lookup.imports%}\n \n \n \n \n \n {%endfor%}\n \n
PackageVersionInstall
{{import[0]}}{{import[1]}}{{import[2] or \"PyPi\"}}
\n \"\"\"\n \n @route(showKernelSpec=\"*\")\n def show_kernel_spec(self):\n return \"
{{this.kernel_spec}}
\"\n \n @route()\n def main(self):\n return \"\"\"\n\n\n\n
\n

Publish Notebook as a web application

\n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n
\n \nself.set_contents('''$val(getNotebookJSON)''')\n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n\n
\n \n
\n
\n \"\"\"\n","sub_path":"pixiedust/apps/gateway/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":12332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"381681600","text":"import re\nimport os\nimport sys\n\nfrom handle_role_file import convert_to_speciesnames\n\ndef extract_modules(modfile,moduledict,seednum):\n if moduledict=={}:\n moduledict[seednum]={}\n\n f=open(modfile,'r')\n minidict={}\n for line in f:\n modulenum=line.split()[0] # Irrelevant module label\n nodes_in_module=line.split()[1]\n links_in_module=line.split()[2]\n within_module_links=line.split()[3]\n links_to_other_modules=line.split()[4]\n nodelist=line.split('---')[1].split('\\n')[0].split()\n\n\n minidict[modulenum]={'nodes':sorted(nodelist),'numlinks':links_in_module}\n duplicate='no'\n\n for seed in moduledict:\n if seed!=seednum: # Not this seed\n for module in moduledict[seed]:\n if moduledict[seed][module]==minidict[modulenum]:\n duplicate='yes'\n if duplicate=='yes':\n pass\n else:\n try:\n moduledict[seednum][modulenum]={'nodes':sorted(nodelist),'numlinks':links_in_module}\n except KeyError:\n moduledict[seednum]={}\n moduledict[seednum][modulenum]={'nodes':sorted(nodelist),'numlinks':links_in_module}\n\n f.close()\n\n return moduledict\n\ndef extract_modules_by_species(modfile,moduledict,seednum):\n f=open(modfile,'r')\n for line in f:\n modulenum=line.split()[0] # Irrelevant module label\n nodes_in_module=line.split()[1]\n links_in_module=line.split()[2]\n within_module_links=line.split()[3]\n links_to_other_modules=line.split()[4]\n nodelist=line.split('---')[1].split('\\n')[0].split()\n for node in nodelist:\n if node not in moduledict:\n moduledict[node]={} \n moduledict[node][seednum]={modulenum:(nodes_in_module,links_in_module)}\n\n f.close()\n\n return moduledict\n\n\ndef extract_modularity(clusfile):\n f=open(clusfile,'r')\n for line in f:\n modularity=line.split()[1]\n f.close()\n \n return modularity\n\ndef read_module_files(moduledir):\n for web in os.listdir(moduledir):\n bestseed=select_best_modules(moduledir)\n moduledict={}\n speciesdict={}\n for seednum in bestseed:\n moduledict=extract_modules(moduledir+'/'+seednum+'/modules_bipart_w.dat',moduledict,seednum)\n\n if len(moduledict.keys())==1:\n seed=moduledict.keys()[0]\n modfile=moduledir+'/'+moduledict.keys()[0]+'/modules_bipart_w.dat'\n speciesmods=extract_modules_by_species(modfile,speciesdict,seed)\n else: \n for seed in moduledict.keys():\n # seed=moduledict.keys()[0]\n modfile=moduledir+'/'+moduledict.keys()[0]+'/modules_bipart_w.dat'\n speciesmods=extract_modules_by_species(modfile,speciesdict,seed)\n # print 'Multiple best modules: ', len(moduledict.keys())\n\n return moduledict, speciesmods\n\ndef select_best_modules(moduledir):\n bestmod=[0]\n bestseed=['1']\n for seednum in os.listdir(moduledir):\n clusfile=moduledir+seednum+'/clustering.txt'\n modularity=extract_modularity(clusfile) \n if modularity>bestmod[0]:\n bestmod=[modularity]\n bestseed=[seednum]\n elif modularity==bestmod[0]:\n bestmod.append(modularity)\n bestseed.append(seednum)\n else:\n pass\n\n return bestseed\n\n\n# What to do about multiple best modules? \n\ndef main():\n for subdir in os.listdir('../../data/raw/'):\n\n rolefile='../../data/roles/'+subdir+'.roles'\n moduledir='../../data/modules/rgraph_output/'+subdir+'_projection/'\n\n read_module_files(moduledir)\n translate_dict=convert_to_speciesnames(rolefile)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"datafile_management/handle_module_files.py","file_name":"handle_module_files.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"39538436","text":"import os\nimport glob\nimport sys\nimport re\n\n\nroot_dir = sys.argv[1]\n\nlist_selective = ['noselective', 'selective']\n\ntarget_file = open(os.path.join(root_dir, 'merged_rouge_results.csv'), 'w')\n\nlist_str_metric = ['precision', 'recall', 'f_score']\nlist_ngram = ['1', '2', 'l']\n\nheader = ['\\\\']\nitem2id = dict()\ncounter = 0\n\nfor ngram in list_ngram:\n for str_metric in list_str_metric:\n header.append('ROUGE-%s-%s' % (ngram, str_metric))\n item2id[ngram + str_metric] = counter\n counter += 1\n\ntarget_file.write(','.join(header))\n\npattern = r'rouge_(\\w)_(.*?): (\\d+\\.\\d+)'\n\npossible_dir = ['rnn_baseline', 'no_query', 'query_in_encoder', 'query_in_decoder', 'query_in_both']\n\nfor dir_ in possible_dir:\n if not os.path.exists(os.path.join(root_dir, dir_)):\n continue\n for selective in list_selective:\n list_files = glob.glob(root_dir + '/%s' % dir_ + '/%s/log/mei/decode_test*/ROUGE_results.txt' % selective)\n results = ['-'] * (len(list_str_metric) * len(list_ngram))\n if len(list_files) == 0:\n pass\n else:\n try:\n assert len(list_files) == 1\n except AssertionError:\n print(list_files)\n exit(0)\n single_line = ' '.join([line.strip() for line in open(list_files[0], 'r').readlines()])\n for ngram, str_metric, str_value in re.findall(pattern, single_line):\n results[item2id[ngram + str_metric]] = str_value\n\n results.insert(0, '%s_%s' % (dir_, selective))\n target_file.write('\\n' + ','.join(results))\n","sub_path":"fetch_rouge.py","file_name":"fetch_rouge.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503362959","text":"# -*- coding: utf-8 -*-\nimport logging\nimport time\nimport numpy as np\nfrom hyperopt import STATUS_OK\nfrom imblearn.over_sampling import SMOTE, ADASYN, RandomOverSampler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_fscore_support, \\\n confusion_matrix, accuracy_score\n\n# Static variables\nSEED = 666\nbest_f1 = 0\nbest_rf = None\nbest_feature_importance = None\nconfig_counter = 0\n\n\nclass RandomForest:\n def __init__(self, hyperparameters, data, output_dir):\n \"\"\"\n RandomForest model constructor. Responsible for splitting up data and\n setting hyperparamters.\n\n Args:\n hyperparameters (dict): Contains relevant hyperparameters\n data (list): List of Bag objects\n output_dir (str): Path to output directory for model files.\n \"\"\"\n super().__init__()\n\n # Set up log file to record general information about program operation\n logging.basicConfig(filename='%s/training.log' % output_dir,\n level=logging.DEBUG,\n filemode='a',\n format='%(asctime)s - %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\n # Extract bags and reshape to 2D array\n bags = np.asarray([x.instances for x in data])\n bags = np.reshape(bags, newshape=(len(bags), -1))\n labels = np.asarray([x.label for x in data])\n labels[labels < 0] = 0\n\n # Split data into train and dev sets\n self.X_train, self.X_dev, self.y_train, self.y_dev = \\\n train_test_split(bags, labels, test_size=0.15, random_state=SEED)\n\n # Resample data set to alleviate class imbalance\n if hyperparameters[\"resampling\"] == \"SMOTE\":\n self.X_train, self.y_train = SMOTE(random_state=SEED)\\\n .fit_resample(self.X_train, self.y_train)\n elif hyperparameters[\"resampling\"] == \"ADASYN\":\n self.X_train, self.y_train = ADASYN(random_state=SEED)\\\n .fit_resample(self.X_train, self.y_train)\n elif hyperparameters[\"resampling\"] == \"RandomOverSampler\":\n self.X_train, self.y_train = RandomOverSampler(random_state=SEED)\\\n .fit_resample(self.X_train, self.y_train)\n self.hyperparameters = hyperparameters\n\n # Convert params to appropriate types for scikit learn\n params = {\n \"n_estimators\": int(self.hyperparameters[\"n_estimators\"]),\n \"max_depth\": int(self.hyperparameters[\"max_depth\"]),\n \"min_samples_split\": int(\n self.hyperparameters[\"min_samples_split\"]),\n \"min_samples_leaf\": int(\n self.hyperparameters[\"min_samples_leaf\"])\n }\n\n self.model = RandomForestClassifier(**params, random_state=SEED,\n n_jobs=-1)\n\n def fit(self):\n global best_f1, best_rf, best_feature_importance, config_counter\n\n # Train model\n self.model.fit(self.X_train, self.y_train)\n\n # Obtain out-of-bag predictions\n dev_preds = self.model.predict(self.X_dev)\n\n accuracy = accuracy_score(self.y_dev, dev_preds)\n my_precision, my_recall, my_f1_score, my_support = \\\n precision_recall_fscore_support(self.y_dev, dev_preds,\n pos_label=1, average=\"binary\")\n conf_matrix = confusion_matrix(self.y_dev, dev_preds)\n\n logging.info(\"CONFIG %d: precision=%.5f, recall=%.5f, f1_score=%.5f, \"\n \"accuracy=%.5f\" %\n (config_counter, my_precision, my_recall, my_f1_score, accuracy))\n print(\"CONFIG %d: precision=%.5f, recall=%.5f, f1_score=%.5f \"\n \"accuracy=%.5f\" %\n (config_counter, my_precision, my_recall, my_f1_score, accuracy))\n print(\"Confusion Matrix\\n%s\" % conf_matrix.__str__())\n\n if my_f1_score > best_f1:\n best_f1 = my_f1_score\n best_rf = self.model\n best_feature_importance = self.model.feature_importances_\n config_counter += 1\n\n return {\n 'loss': (1 - my_f1_score),\n 'status': STATUS_OK,\n 'eval_time': time.time()\n }\n","sub_path":"python/Models/hyperopt_pipeline/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161425858","text":"import json\nfrom flask import Flask \nfrom flask import (render_template,url_for,redirect,\n\tmake_response,request)\n\nfrom options import DEFAULTS\n\napp = Flask(__name__)\n\ndef get_saved_data():\n\ttry:\n\t\tdata = json.loads(request.cookies.get('character'))\n\texcept TypeError:\n\t\tdata = {}\n\treturn data\n\n@app.route('/')\ndef index():\n\tdata = get_saved_data()\n\treturn render_template('index.html',saves=data)\n\n@app.route('/builder')\ndef builder():\n\tdata = get_saved_data()\n\treturn render_template('builder.html',saves=data,options=DEFAULTS)\n\n@app.route('/save',methods=['POST'])\ndef save():\n\tresponse = make_response(redirect(url_for('builder')))\n\tdata = get_saved_data()\n\tdata.update(dict(request.form.items()))\n\tresponse.set_cookie('character',json.dumps(data))\n\treturn response\n\napp.run(debug=True,port=8000)","sub_path":"Python3/Flask/Project files/Stage 3 Start/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"466047531","text":"lista = [1, 8, 4, 99, 34, 129]\nprint(type(lista))\nprint(max(lista))\n\ntupla = (1, 8, 4, 99, 34, 129)\nprint(type(tupla))\nprint(max(tupla))\n\nconjunto = {1, 8, 4, 99, 34, 129}\nprint(type(conjunto))\nprint(max(conjunto))\n\ndicionario = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129}\nprint(type(dicionario))\nprint(max(dicionario.values()))\n\nprint(max('Geek University'))\n\nnomes = ['Arya', 'Sanson', 'Dora', 'Tim', 'Ollivander']\nprint(max(nomes))\nprint(min(nomes))\nprint(max(nomes, key=lambda nome: len(nome)))\nprint(min(nomes, key=lambda nome: len(nome)))\n\nmusicas = [\n {\"titulo\": \"tunderstruck\", \"Tocou\": 3},\n {\"titulo\": \"dead skin mask\", \"Tocou\": 200},\n {\"titulo\": \"back in black\", \"Tocou\": 4},\n {\"titulo\": \"too old to rock in roll, too ynoung to die\", \"Tocou\": 32}\n]\n\nprint(max(musicas, key=lambda musica: musica[\"Tocou\"]))\nprint(min(musicas, key=lambda musica: musica[\"Tocou\"]))\n\nprint(max(musicas, key=lambda musica: musica[\"Tocou\"])['titulo'])\nprint(min(musicas, key=lambda musica: musica[\"Tocou\"])['titulo'])\n\nmaior = 0\nfor musica in musicas:\n if musica[\"Tocou\"] > maior:\n maior = musica[\"Tocou\"]\nfor musica in musicas:\n if musica['Tocou'] == maior:\n print(musica['titulo'])\n\nmaior = 10\nfor musica in musicas:\n if musica[\"Tocou\"] < maior:\n maior = musica[\"Tocou\"]\nfor musica in musicas:\n if musica['Tocou'] == maior:\n print(musica['titulo'])\n\n#criar um sistema de nomes e organizar conforme letra\n#Sistema de exememplo no uso das funcoes min e max\n\n\ndef funcaominmax(numero):\n from time import sleep\n if numero == 1:\n quantidade = int(input('Digite a quantidade de numeros: '))\n valor = [input('Digite um valor: ') for numero in range(quantidade)]\n print(f'Menor valor digitado é: {min(valor)}')\n elif numero == 2:\n quantidade = int(input('Digite a quantidade de numeros: '))\n valor = [input('Digite um valor: ') for numero in range(quantidade)]\n print(f'Maior valor digitado é: {max(valor)}')\n elif numero == 3:\n print('Saindo', end='')\n for c in range(3):\n print('.', end='')\n sleep(1)\n\n\nwhile True:\n print('-' * 20)\n print('1: Minimo\\n2: Maximo\\n3: EXIT')\n print('-' * 20)\n opc = int(input('Escolha um item: '))\n funcaominmax(opc)\n if opc == 3:\n break\n","sub_path":"Aula 9/min max.py","file_name":"min max.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653449390","text":"from random import randint, shuffle, choice\nfrom time import sleep, time\nfrom colorama import Fore, Back, Style, init\ninit(autoreset = True)\n\n#version\nprint(Fore.GREEN+Back.BLACK+ \"Canuto's Trivia version 3.1.2\")\nprint(Fore.CYAN+\"∆ \"*35 +Fore.RESET)\n\n#LISTAS\npreguntas = [1,2,3,4,5,\"BONUS\"]\nA =[1,2,3,4,5,6]\npuntajes = []\ntextos=[[\"Pregunta 1:\",\"Pregunta 2:\",\"Pregunta 3:\", \"Pregunta 4:\", \"Pregunta 5:\",\"¡BONUS!\"], ['¿Quién es el autor de \"Don Quijote de la Mancha\"?',\"¿Cuál es el río más largo del mundo?\",\"¿Dónde se originaron los juegos olímpicos?\",\"¿Cuándo acabó la II Guerra Mundial?\", \"¿Quién es el padre del psicoanálisis?\",\"¿Cuál de los siguientes números es HEXADECIMAL?\"]]\nletras = [\"a)\",\"b)\",\"c)\",\"d)\"]\nalternativas =[[\"Miguel de Cervantes Saavedra\",\"Inca Garcilaso de la Vega\", \"Ricardo Palma\",\"Adolfo Béquer\"], [\"Nilo\", \"Amazonas\",\"Éufrates\",\"Misisipi\"], [\"Roma\",\"Arabia\",\"China\",\"Grecia\"],[\"1935\",\"1945\",\"1928\",\"1937\"],[\"Isaac Netwon\",\"Iván Pávlov\",\"Sigmund Freud\",\"Wilhelm Wundt\"],[\"145.789\", \"12FF01G\", \"01010101\", \"10BC13F\"]]\n\nW = Fore.WHITE+ Back.BLACK \nR = Fore.RESET+Back.RESET\n\n#colores\nBLACK = '\\033[30m'\nRED = '\\033[31m'\nGREEN = '\\033[32m'\nYELLOW = '\\033[33m'\nBLUE = '\\033[34m'\nMAGENTA = '\\033[35m'\nCYAN = '\\033[36m'\nWHITE = '\\033[37m'\nRESET = '\\033[39m'\n\n\n#---FUNCIONES:\n#para las respuestas de cada pregunta\ndef respuesta():\n r = input(\"\\n-->\"+W+\" Tu respuesta: \"+R).lower()\n while r not in (\"a\",\"b\",\"c\",\"d\"):\n r = input(GREEN+\"--> Debes responder a, b, c o d. Ingresa nuevamente tu respuesta: \").lower()\n return r\n\n#para la ejecucion automática y aleatoria de las preguntas\ndef preg(k):\n global t\n print(\"\\n\\n\",textos[0][t]+\"\\n-->\"+YELLOW+textos[1][k-1]+\"\\n\")\n sleep(2)\n for i in range(0,4):\n print(letras[i], alternativas[k-1][i])\n sleep(.7)\n t=t+1\n#para instrucciones\ndef instrucciones():\n print(Fore.LIGHTBLUE_EX+'''\\n\\nDeberás responder las siguientes preguntas escribiendo la letra de la alternativa que consideres correcta y luego presionando 'Enter' para enviarla. \n Dependiendo de si la letra es la correcta o no, recibirás una cantidad aleatoria de puntos, que pueden ser negativos o positivos. \n \n Además, en algunas preguntas podrías obtener puntos 'extras' si eliges la letra oculta. ¡Deberás probar!\n ¿Entendido?\\n''')\n \n ok = input(YELLOW+\"(Responde entendido) \"+RESET).lower()\n while ok not in (\"entendido\"):\n ok = input(\"Quiero que estés seguro. Responde de nuevo: \").lower()\n \n print(\"¡Está bien!\\n\")\n\n#para el final 1 del modo 2: \ndef f_12():\n print(\"¡Bien hecho!\")\n print(\"¡Has respondido todo a tiempo!\")\n#para el final 1 del modo 3\ndef f_13():\n print(\"¡Bien hecho!\")\n print(\"¡Has completado esta trivia satisfactoriamente! Wow, 6 respuestas correctas seguidas, ¡impresionante!\")\n#--- FUNCIONES\n\n# variables\npuntaje = 10\nt =0\niniciar_trivia = True\n\nnormal= False\ncontra=False\nmyf = False #valor del modo \"mala y fuera\"\ncron=False\nintentos = int(0)\n\n#INTRO\nprint(CYAN+'''\\n\\n--> Soy Mr. Canuto'''+RESET+ '''\n __\n o-''|\\_____/)\n \\_/|_) )\n \\ __ /\n (_/ (_/ \n ''')\n\ninput(YELLOW+ Style.NORMAL+'(Di \"Hola Mr. Canuto\") '+RESET)\n\nprint('''\\n ,-.___,-.\n--> ¡Hola, \\_/_ _\\_/\n hola! )O_O(\n { (_) }\n `-^-' ''')\n \nsleep(0.5)\nnombre = CYAN+ input(CYAN+'''\n Dime, ¿cómo te llamas? '''+RESET)+RESET\n\nwhile iniciar_trivia == True:\n intentos += 1\n print('''\\n--> Bien\n ███▓▒░░''',nombre,'''░░▒▓███ \\n''')\n\n # texto de bienvenida\n print('''\n --> ╔═══╗ ♪ ¡Bienvenid@\n ║███║ ♫ a mi trivia\n ║(●) ♫ sobre\n ╚═══╝ ♪♪ Cultura General!\n ''')\n sleep(1.5) \n print('''Ahora pondré a prueba tus conocimientos :D.''')\n print(\"--> ¿Está bien?\\n\")\n a_ = input(YELLOW+\"(Responde sí o no) \"+RESET).lower()\n\n if a_ in (\"si\", \"sí\"):\n print(\"¡Correcto! Este es tu intento n°\",intentos,\"y tienes 10 puntos.\\n\\n\")\n sleep(1)\n else:\n print(\"¡Ehh! ¿Y esos ánimos?\")\n sleep(1.5)\n print(\"Bueno, este es tu intento n°\",intentos,\" ahora mismo tienes 10 puntos.\\n\\n\")\n sleep(1)\n \n print(\"\\n\\n¿Deseas comenzar o primero leer las instrucciones?\\n\")\n sleep(1)\n\n print(\"1) Deseo comenzar\")\n sleep(0.5)\n answer = input(\"2) Deseo leer las instrucciones \")\n \n if answer == \"1\":\n print(\"\")\n elif answer == \"2\":\n instrucciones()\n else:\n b_ = input(\"\\nSi eliges 1 el juego comenzará inmediatamente, si eliges 2, mostraré las instrucciones. \")\n while b_ not in (\"1\",\"2\"):\n b_ = input(GREEN+\"Escribe 1 o 2 para continuar: \"+RESET)\n if b_ == \"2\":\n instrucciones()\n \n print(\"Existen 4 modos de juegos.\")\n sleep(.7)\n print(YELLOW+\"1) Normal:\"+RESET+\" 5 preguntas, tiempo ilimitado.\")\n sleep(1.3)\n print(Fore.LIGHTGREEN_EX+\"2) Contrarreloj:\"+RESET+\" Tendrás 5 minutos para responder la mayor cantidad de preguntas posibles.\")\n sleep(1.3)\n print(Fore.LIGHTBLUE_EX+\"3) Incorrecta y fuera:\"+RESET+\" Logra la mayor cantidad de preguntas correctas. Tiempo ilimitado, el juego acabará cuando cometas un error.\")\n sleep(1.3)\n print(Fore.LIGHTMAGENTA_EX+\"4) Cronómetro:\"+RESET+\" Te daré 5 preguntas, trata de reponderlas en el menor tiempo posible\")\n \n modo = input(\"¿Con cuál quieres comenzar? \")\n str_m = modo.isnumeric()\n\n while str_m == False:\n str_m = input(\"Ingresa un número. \")\n \n while modo not in (\"1\",\"2\",\"3\",\"4\"):\n modo = input(\"Elige un número válido: \")\n\n print(\"¡Comencemos...!\") \n sleep(2)\n \n print(\"Cargando trivia...\")\n sleep(0.7)\n print(\" 10% █▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒\")\n sleep(0.7) \n print(\" 30% ███▒▒▒▒▒▒▒▒▒▒▒▒▒▒\")\n sleep(.7)\n print(\" 50% █████▒▒▒▒▒▒▒▒▒▒\")\n sleep(.7)\n print(\" 70% ███████▒▒▒▒▒▒\")\n sleep(.7)\n print(\" 90% █████████▒▒\")\n sleep(.7)\n print(\"100% ██████████\")\n sleep(0.5) \n\n if modo ==\"1\":\n normal=True\n elif modo==\"2\":\n contra=True\n elif modo==\"3\":\n myf=True\n elif modo==\"4\":\n cron=True\n\n def p_1():\n a=randint(0,21)\n global r, puntaje,modo\n if r == \"a\":\n puntaje += 10\n puntajes.append(10)\n print(\"¡Geniaal! Ganaste 10 puntos\", nombre)\n elif modo==\"3\":\n if r!=\"a\":\n myf == False\n else:\n puntaje -= a\n puntajes.append(-a)\n print(\"¡Incorrecto! Has perdido\",a,\"puntos\",nombre)\n def p_2():\n a=randint(0,21)\n global r, puntaje, modo\n if r == \"b\":\n puntaje +=a\n puntajes.append(a)\n print(\"¡ Muy bien\",nombre,\"! Ganaste\",a,\"puntos\")\n elif r == \"a\":\n puntaje -= a\n puntajes.append(-a)\n print(\"Ehhh, incorrecto. Sé que puede causar confusión, pero la respuesta es la b. Has perdido\",a,\"puntos\",nombre)\n elif r == \"x\":\n puntaje *=2\n puntajes.append(\"Desconocido xd\")\n print(\"¿Hola? Wiii. Esto es divertido. Ahora tienes\",puntaje, nombre,)\n elif modo==\"3\":\n if r!=\"b\":\n myf == False\n else:\n puntaje -=a\n puntajes.append(-a)\n print(\"¡Incorrecto! La respuesta correcta es la b. Has perdido\",a,\"puntos\",nombre)\n def p_3():\n ndint(0,21)\n global r, puntaje,modo\n if r == \"d\":\n puntaje += a\n puntajes.append(a)\n print(\"¡Muy bien! Ganaste\", a, \"puntos\", nombre) \n elif modo==\"3\":\n if r!=\"a\":\n myf == False\n else:\n puntaje -=a\n puntajes.append(-a)\n print(\"¡Incorrecto! La respuesta correcta es la d. Has perdido\",a,\"puntos\",nombre) \n print(\"Se llaman así porque se celebraban en la ciudad de Olimpia. ¿Lo sabías?\")\n def p_4():\n global r, puntaje,modo,a\n if r == \"b\":\n punje +=a\n puntajes.append(a)\n print(\"¡Muy bien! Ganaste\", a, \"puntos\", nombre)\n elif r == \"l\":\n d = randint(0,5001)\n puntaje += d\n puntajes.append(d, \"Era un 'extra' uwu\")\n print(\"¡GENIAAL! Ganaste\", d, \"puntos\", nombre)\n print(\"Ahora tienes\",puntaje,\"puntos\")\n elif modo==\"3\":\n if r!=\"b\":\n myf == False\n else:\n puntaje -= a\n puntajes.append(-a)\n print(\"¡Incorrecto! Has perdido\", a, \"puntos\", nombre,\". La respuesta correcta es la b.\")\n def p_5():\n global r, puntaje,modo,a\n a=randint(0,21)\n if r == \"c\":\n punjes.append(puntaje)\n puntaje *=2\n print(\"¡ Muy bien\",nombre,\"! Tu puntaje ha sido duplicado. Ahora tienes \",puntaje,\"puntos.\")\n elif r == \"a\":\n puntaje /=2\n puntajes.append(-puntaje)\n print(\"Ehhh, ¡totalmente incorrecto! La respuesta es la c. Isaac Netwon es el Padre de la Física Moderna, ¡deberías saberlo! Pierdes\"+YELLOW+\" la mitad \"+RESET+\"de tus puntos.\")\n elif r == \"b\":\n puntaje += 1\n puntajes.append(1)\n print(\"¡Incorrecto! La respuesta correcta es la c. Iván Pavlov es un psicoanalista pero no el padre de esta. Solo ganas\"+YELLOW+ \" 1 \"+RESET+ \"punto.\")\n elif modo==\"3\":\n if r!=\"c\":\n myf == False\n else:\n puntaje -= 15\n puntajes.append(-15)\n print(\"¡Incorrecto! La respuesta correcta es la c. Wilhelm Wundt es el Padre de la Psicología; no del Psicoanálisis. Pierdes \"+YELLOW+ \"15 \"+RESET+ \"puntos\",nombre,\".\")\n sleep(2)\n def bon():\n global r, puntaje,modo,a\n a=randint(0,21)\n if r == \"a\":\n pri(\"¡Totalmente incorrecto!\", nombre, \"Este es un número DECIMAL... ¡Deberías saberlo! Pierdes \"+YELLOW+\"la mitad\"+YELLOW+\" de tu puntaje\")\n puntaje /= 2\n puntajes.append(-puntaje)\n elif r == \"b\":\n print(\"¡Incorrecto!\", nombre, \"Te confundiste por una letra... Los números hexadecimales llegan hasta la F, la G no corresponde. Te damos\"+YELLOW+\" + 5\"+RESET+\" puntos por casi acertar\")\n puntaje += 5\n puntajes.append(5)\n elif r == \"c\":\n print(\"¡Incorrecto!\", nombre, \"¡este es número binario! Lo siento, pierdes\"+YELLOW+\" 5\"+RESET+\" puntos.\")\n puntaje -= 5\n puntajes.append(-5)\n elif modo==\"3\":\n if r!=\"d\":\n myf == False\n else:\n print(\"¡Correcto!\", nombre, \"Este es el único número hexadecimal de la lista, ¡ganaste puntos \"+YELLOW+\"x 2!!\"+RESET)\n puntajes.append(puntaje)\n puntaje = puntaje * 2\n \n def sec_p():\n global r, puntaje,modo,t\n while len(A) != 0:\n a = randint(0,21)\n j = choice(A)\n preg(j)\n r=respuesta()\n return a\n if j ==1:\n p_1()\n elif j ==2:\n p_2()\n elif j ==3:\n p_3()\n elif j ==4:\n p_4()\n elif j ==5:\n p_5()\n elif j==6:\n bon()\n A.remove(j)\n \n if modo == \"2\":\n contra== True\n f_12()\n elif modo == \"3\":\n f_13()\n\n print()\n \n #definiendo los game loops de los modos de juego\n if modo == \"1\":\n sec_p()\n elif modo == \"2\":\n start = input(\"\\n¡Escribe 'start' para comenzar a tomar el tiempo y correr el temporrizador! \").lower()\n while start != \"start\":\n start= input(\"Escribe 'start' para continuar: \").lower()\n time_start=time()\n \n while ((time()-time_start)<300):\n contra=False\n sec_p()\n if contra == False:\n print(\"¡Oh no! No lo lograste\")\n sleep(.5)\n print(\"¡Tal vez quieras jugar de nuevo!\\n\\n\")\n sleep(.5)\n print(\"De cualquier modo...\")\n sleep(1)\n elif modo == \"3\":\n while myf == True:\n sec_p()\n elif modo == \"4\":\n start = input(\"\\n¡Escribe 'start' iniciar el cronómetro! \").lower()\n while start != \"start\":\n start= input(\"Escribe 'start' para continuar: \").lower()\n ts =time()\n sec_p()\n te = time()\n timec = te - ts\n\n sleep(2)\n print('''\n __^__ __^__\n ( ___ )------------------------------------( ___ )\n | / | | \\ |\n | / | '''+YELLOW+''' ¡Felicidades!'''+RESET+''' | \\ |\n | / | | \\ |\n | / | ¡Terminaste esta trivia! | \\ |\n |___| |___|\n (_____)------------------------------------(_____) \n ''')\n \n if modo == \"3\":\n print(\"¡Completaste esta trivia en\",int(timec/60),\"minutos y\",int(timec%60),\"segundos!\")\n \n \n s = input(YELLOW+'''\\n¿Deseas ver tu Historial de juego?'''+RESET+''' \n Escribe s para mostrar el historial de esta partida: ''').lower()\n if s == \"s\" :\n print(Fore.BLACK + Back.WHITE+Style.BRIGHT+'''Historial de juego:'''+R+'''\\n''')\n \n for number in range(0, 6):\n print(CYAN+\"El puntaje de la pregunta\", preguntas[number], \"es\", puntajes[number])\n \n print(\"Puntaje total: \",puntaje)\n \n sleep(1.3)\n print(\"\\n¿Deseas intentar la trivia nuevamente?\")\n repetir_trivia = input(\"Ingresa 'R' para repetir, o cualquier tecla para finalizar: \").lower()\n \n A = [1,2,3,4,5,6]\n puntajes = []\n\n if repetir_trivia != (\"r\"): \n print('''\\n\n __\n .' '.\n _.-'/ | \\\n , _.-\" ,| / 0 `-.\n |\\ .-\" `--\"\"-.__.'=====================-,\n \\ '-'` .___.--._)=========================|\n \\ .' | |\n | /,_.-' | ¡GRACIAS,''',nombre,''' |\n _ / _.'( | POR JUGAR |\n / ,-' \\ \\ | MI TRIVIA! |\n \\ \\ `-' | |\n `-' '--------------------------'\n '''+YELLOW+'''Alcanzaste''', puntaje,'''puntos.\n '''+RESET)\n \n print(CYAN+\"∆ \"*35 +RESET)\n iniciar_trivia = False \n\n \n\n\n ","sub_path":"main(2).py","file_name":"main(2).py","file_ext":"py","file_size_in_byte":13747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"184200788","text":"import numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# queryImage\nimg1 = cv.imread('./data/src_1.jpg',0) \nimg2 = cv.imread('./data/dst_1.jpg',0) # trainImage\n\n# Initiate SIFT detector\nsift = cv.xfeatures2d.SIFT_create()\n\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1,None)\nkp2, des2 = sift.detectAndCompute(img2,None)\n\n# get number of features of these two images\nprint('source image features:' + str(len(kp1)))\nprint('target image features:' + str(len(kp2)))\n\n# show the detected features overlaid on the images\nimg4 = cv.imread('./data/src_1.jpg',0)\nimg5 = cv.imread('./data/dst_1.jpg',0)\nimg4 = cv.drawKeypoints(img1,kp1,img4, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\nimg5 = cv.drawKeypoints(img2,kp2,img5, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv.imshow('detected features overlaid on source images',img4)\ncv.imshow('detected features overlaid on images',img5)\n\n# create BFMatcher object\nbf = cv.BFMatcher()\n\n# Match descriptors which returns k of the best matches.\nmatches = bf.knnMatch(des1,des2,k=2)\n\nmatches_withoutlist = [] # for the question 2\n\n# Apply ratio test\ntmp = []\nfor m,n in matches:\n if m.distance < 0.75*n.distance:\n tmp.append([m])\n matches_withoutlist.append(m)\n\nmatches = tmp\n\n# get number of matches\nprint(\"number of matches:\" + str(len(matches)))\n\n# Sort them in the order of their distance.\nmatches = sorted(matches, key = lambda x:x[0].distance)\nmatches_withoutlist = sorted(matches_withoutlist, key = lambda x:x.distance)\n\n# Draw the top 20 scoring matches.\nimg3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,matches[:20], None, flags=2)\nplt.imshow(img3),plt.show()\n\n\n\n# get keypoints of matches in both image\nsrc_kp = []\ntar_kp = [] \nfor m in matches:\n src_kp.append(kp1[m[0].queryIdx].pt)\n tar_kp.append(kp2[m[0].trainIdx].pt)\n#change the type tp np array\nsrc_kp = np.asarray(src_kp)\ntar_kp = np.asarray(tar_kp)\n#find the homography\nmatrix, mask = cv.findHomography(src_kp, tar_kp, cv.RANSAC, 5.0)\n\nprint('the total numbers consistent:' + str(np.sum(mask)))\n\nprint('the computed homography matrix:')\nprint(matrix)\n\n#find the boundary of the img1\nh,w = img1.shape\npts = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)\n\n#do the transform to get the boundary for the src1 in img2.\ndst = cv.perspectiveTransform(pts,matrix)\n\n#set how to draw img2 with boundary dst\nimg2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)\nmatchesMask = mask.ravel().tolist()\n\n\ndraw_params = dict(matchColor = (0,255,0), # draw matches in green color\n matchesMask = matchesMask,\n flags = 2)\n\n#Show the top 10 (or more) matches that are found after homography has been computed\nimg3 = cv.drawMatches(img1, kp1, img2, kp2, matches_withoutlist, None, **draw_params) # show top 20 mathches\nplt.imshow(img3, 'gray'),plt.show()\n","sub_path":"HW3_Data/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"587977336","text":"def flip(panstack):\r\n\tfstack=\"\"\r\n\tfor cake in list(panstack):\r\n\t\tif cake==\"+\":\r\n\t\t\tfstack=\"-\"+fstack\r\n\t\telif cake==\"-\":\r\n\t\t\tfstack=\"+\"+fstack\r\n\treturn fstack\r\n\r\ndef flipnumber(panstack):\r\n\tif panstack==\"+\":\r\n\t\treturn 0\r\n\telif panstack==\"-\":\r\n\t\treturn 1\r\n\telif panstack.endswith(\"+\"):\r\n\t\treturn flipnumber(panstack[:-1])\r\n\telif panstack.endswith(\"-\") and panstack.startswith(\"-\"):\r\n\t\treturn 1+flipnumber(flip(panstack))\r\n\telif panstack.endswith(\"-\") and panstack.startswith(\"+\"):\r\n\t\tnumplus=panstack.find(\"-\");\r\n\t\treturn 1+flipnumber(flip(panstack[0:numplus])+panstack[+numplus:])\r\n\t\r\n\r\n\r\nt = int(input()) \r\nfor i in range(1, t + 1):\r\n\tprint(\"Case #{}: {}\".format(i,flipnumber(input())))","sub_path":"codes/CodeJamCrawler/16_0_2/richard27182/pancake.py","file_name":"pancake.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115738054","text":"# coding: utf-8\n\nfrom supervisely_lib.io.json import load_json_file\nfrom supervisely_lib import TaskPaths\nimport supervisely_lib as sly\nfrom supervisely_lib.video.video import _check_video_requires_processing, _SUPPORTED_CODECS, _SUPPORTED_CONTAINERS, \\\n get_video_streams, warn_video_requires_processing, gen_video_stream_name\nfrom supervisely_lib.video.import_utils import get_dataset_name\n\n\nDEFAULT_DATASET_NAME = 'ds0'\nroot_ds_name = DEFAULT_DATASET_NAME\n\n\ndef add_videos_to_project():\n task_config = load_json_file(TaskPaths.TASK_CONFIG_PATH)\n\n task_id = task_config['task_id']\n append_to_existing_project = task_config['append_to_existing_project']\n\n server_address = task_config['server_address']\n token = task_config['api_token']\n\n instance_type = task_config.get(\"instance_type\", sly.ENTERPRISE)\n\n api = sly.Api(server_address, token)\n\n task_info = api.task.get_info_by_id(task_id)\n api.add_additional_field('taskId', task_id)\n api.add_header('x-task-id', str(task_id))\n\n workspace_id = task_info[\"workspaceId\"]\n project_name = task_config.get('project_name')\n if project_name is None:\n project_name = task_config[\"res_names\"][\"project\"]\n\n project_info = None\n if append_to_existing_project is True:\n project_info = api.project.get_info_by_name(workspace_id, project_name, expected_type=sly.ProjectType.VIDEOS, raise_error=True)\n\n files_list = api.task.get_import_files_list(task_id)\n for file_info in files_list:\n original_path = file_info[\"filename\"]\n try:\n file_name = sly.fs.get_file_name_with_ext(original_path)\n all_streams = file_info[\"meta\"][\"streams\"]\n hash = file_info[\"hash\"]\n ds_info = None\n\n video_streams = get_video_streams(all_streams)\n for stream_info in video_streams:\n stream_index = stream_info[\"index\"]\n\n if instance_type == sly.COMMUNITY:\n if _check_video_requires_processing(file_info, stream_info) is True:\n warn_video_requires_processing(file_name)\n continue\n\n if project_info is None:\n project_info = api.project.create(workspace_id, project_name, type=sly.ProjectType.VIDEOS, change_name_if_conflict=True)\n\n if ds_info is None:\n ds_name = get_dataset_name(original_path)\n ds_info = api.dataset.get_or_create(project_info.id, ds_name)\n\n item_name = file_name\n info = api.video.get_info_by_name(ds_info.id, item_name)\n if info is not None:\n item_name = gen_video_stream_name(file_name, stream_index)\n sly.logger.warning(\"Name {!r} already exists in dataset {!r}: renamed to {!r}\"\n .format(file_name, ds_info.name, item_name))\n\n _ = api.video.upload_hash(ds_info.id, item_name, hash, stream_index)\n except Exception as e:\n sly.logger.warning(\"File skipped {!r}: error occurred during processing {!r}\".format(original_path, str(e)))\n\n if project_info is not None:\n sly.logger.info('PROJECT_CREATED', extra={'event_type': sly.EventType.PROJECT_CREATED, 'project_id': project_info.id})\n else:\n temp_str = \"Project\"\n if append_to_existing_project is True:\n temp_str = \"Dataset\"\n raise RuntimeError(\"{} wasn't created: 0 files with supported codecs ({}) and containers ({}). It is a limitation for Community Edition (CE).\"\n .format(temp_str, _SUPPORTED_CODECS, _SUPPORTED_CONTAINERS))\n pass\n\n\ndef main():\n add_videos_to_project()\n sly.report_import_finished()\n\n\nif __name__ == '__main__':\n sly.main_wrapper('VIDEO_ONLY_IMPORT', main)","sub_path":"plugins/import/videos-raw/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"109834181","text":"import time\nfrom copy import deepcopy\nfrom functools import total_ordering\nfrom queue import PriorityQueue\n\nimport numpy as np\nfrom scipy.linalg import cho_solve, cholesky, solve_triangular\nfrom scipy.optimize import linear_sum_assignment\n\nfrom autotl.distance import (bourgain_embedding_matrix, edit_distance,\n edit_distance_matrix)\n\n\nclass IncrementalGaussianProcess(object):\n def __init__(self, kernel_lambda):\n self.alpha = 1e-10\n self.alpha = 1e-10\n self._k_matrix = None\n self._distance_matrix = None\n self._x = None\n self._y = None\n self._first_fitted = False\n self._l_matrix = None\n self._alpha_vector = None\n self.edit_distance_matrix = edit_distance_matrix\n self.kernel_lambda = kernel_lambda\n\n @property\n def kernel_matrix(self):\n return self._distance_matrix\n\n def fit(self, train_x, train_y):\n if self._first_fitted:\n self.incremental_fit(train_x, train_y)\n else:\n self.first_fit(train_x, train_y)\n\n @property\n def first_fitted(self):\n return self._first_fitted\n\n def first_fit(self, train_x, train_y):\n train_x, train_y = np.array(train_x), np.array(train_y)\n self._x = np.copy(train_x)\n self._y = np.copy(train_y)\n self._distance_matrix = self.edit_distance_matrix(\n self.kernel_lambda, self._x)\n self._distance_matrix = bourgain_embedding_matrix(\n self._distance_matrix)\n self._k_matrix = 1.0 / np.exp(self._distance_matrix)\n self._k_matrix[np.diag_indices_from(self._k_matrix)] += self.alpha\n self._l_matrix = cholesky(self._k_matrix, lower=True)\n self._alpha_vector = cho_solve((self._l_matrix, True), self._y)\n self._first_fitted = True\n return self\n\n def incremental_fit(self, train_x, train_y):\n if not self._first_fitted:\n raise ValueError(\"The first_fit function needs to be called first\")\n\n train_x, train_y = np.array(train_x), np.array(train_y)\n up_right_k = self.edit_distance_matrix(self.kernel_lambda, self._x,\n train_x)\n down_left_k = np.transpose(up_right_k)\n down_right_k = self.edit_distance_matrix(self.kernel_lambda, train_x)\n up_k = np.concatenate((self._distance_matrix, up_right_k), axis=1)\n down_k = np.concatenate((down_left_k, down_right_k), axis=1)\n self._distance_matrix = np.concatenate((up_k, down_k), axis=0)\n self._distance_matrix = bourgain_embedding_matrix(\n self._distance_matrix)\n self._k_matrix = 1.0 / np.exp(self._distance_matrix)\n diagonal = np.diag_indices_from(self._k_matrix)\n diagonal = (diagonal[0][-len(train_x):], diagonal[1][-len(train_x):])\n self._k_matrix[diagonal] += self.alpha\n self._x = np.concatenate((self._x, train_x), axis=0)\n self._y = np.concatenate((self._y, train_y), axis=0)\n\n self._l_matrix = cholesky(self._k_matrix, lower=True) # Line 2\n\n self._alpha_vector = cho_solve((self._l_matrix, True),\n self._y) # Line 3\n\n return self\n\n\nclass BayesianOptimizer(object):\n def __init__(self, searcher, t_min, metric, kernel_lambda, beta):\n self.searcher = searcher\n self.t_min = t_min\n self.metric = metric\n self.kernel_lambda = kernel_lambda\n self.beta = beta\n self.gpr = IncrementalGaussianProcess(kernel_lambda)\n\n def fit(self, x_queue, y_queue):\n self.gpr.fit(x_queue, y_queue)\n\n def optimize_acq(self, model_ids, descriptors, timeout):\n start_time = time.time()\n target_graph = None\n father_id = None\n descriptors = deepcopy(descriptors)\n elem_class = Elem\n if self.metric.higher_better():\n elem_class = ReverseElem\n pq = PriorityQueue()\n temp_list = []\n for model_id in model_ids:\n metric_value = self.searcher.get_metric_value_by_id(model_id)\n temp_list.append((metric_value, model_id))\n temp_list = sorted(temp_list)\n for metric_value, model_id in temp_list:\n graph = self.searcher.load_model_by_id(model_id)\n graph.clear_operation_history()\n graph.clear_weights()\n\n\n@total_ordering\nclass Elem:\n def __init__(self, metric_value, father_id, graph):\n self.father_id = father_id\n self.graph = graph\n self.metric_value = metric_value\n\n def __eq__(self, other):\n return self.metric_value == other.metric_value\n\n def __lt__(self, other):\n return self.metric_value < other.metric_value\n\n\nclass ReverseElem(Elem):\n def __lt__(self, other):\n return self.metric_value > other.metric_value\n\n\ndef contain(descriptors, target_descriptor):\n for descriptor in descriptors:\n if edit_distance(descriptor, target_descriptor, 1) < 1e-5:\n return True\n return False\n","sub_path":"autotl/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397259355","text":"#!/usr/bin/env python3\n\nimport argparse\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport types\nfrom pathlib import Path\nfrom typing import List\n\n\ndef parse_args(argv: List[str]) -> types.SimpleNamespace:\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-s\",\n \"--source\",\n help=\"GTK install prefix to copy\",\n type=Path,\n default=Path.home() / \"gtk\" / \"inst\",\n )\n parser.add_argument(\n \"-o\", \"--output\", help=\"Write tar file to this path\", type=Path, required=True\n )\n parser.add_argument(\"--zstd\", action=\"store_true\", help=\"Use zstd compression\")\n parser.add_argument(\n \"--split\",\n action=\"store_true\",\n help=\"Split archive into 50 MB chunks (e.g., for CI)\",\n )\n return parser.parse_args(argv)\n\n\ndef main(argv: List[str]):\n args = parse_args(argv[1:])\n # Validate arguments\n if not args.source.exists():\n exit(f\"GTK install prefix '{args.source}' doesn't exist!\")\n if not args.output.parent.exists():\n exit(f\"Output directory '{args.output.parent}' doesn't exist!\")\n\n zstd_bin = shutil.which(\"zstd\")\n if args.zstd and zstd_bin is None:\n exit(\"--zstd specified, but zstd command not found\")\n\n print(\"Packaging GTK installation for pipeline usage. This may take a while...\")\n stage_tmpfile = tempfile.TemporaryDirectory()\n output_dir = Path(stage_tmpfile.name)\n stage_dir = output_dir / \"gtk\" / \"inst\"\n stage_dir.mkdir(parents=True)\n\n def copy2_custom(src, dst):\n \"\"\"copy2 that does not follow symlinks\"\"\"\n return shutil.copy2(src, dst, follow_symlinks=False)\n\n def copytree_custom(*args, **kwargs):\n return shutil.copytree(\n *args, **kwargs, copy_function=copy2_custom, symlinks=True\n )\n\n def copy_to_stage(src_relpath: Path):\n srcp = args.source / src_relpath\n dstp = stage_dir / src_relpath\n assert srcp != dstp\n dstp.parent.mkdir(parents=True, exist_ok=True)\n copy2_custom(srcp, dstp)\n\n def copytree_to_stage(src_relpath: Path):\n srcp = args.source / src_relpath\n dstp = stage_dir / src_relpath\n assert srcp != dstp\n dstp.parent.mkdir(parents=True, exist_ok=True)\n copytree_custom(srcp, dstp)\n\n # Copy CMake\n copy_to_stage(Path(\"bin\") / \"cmake\")\n cmake_data = list(args.source.glob(\"share/cmake-*\"))\n assert cmake_data, \"share/cmake-* dir not found\"\n assert len(cmake_data) == 1, \"more than one share/cmake-* dir unexpectedly found\"\n copytree_custom(cmake_data[0], stage_dir / \"share\" / cmake_data[0].name)\n\n # Copy CTest\n copy_to_stage(Path(\"bin\") / \"ctest\")\n\n # Copy pkgconfig\n copy_to_stage(Path(\"bin\") / \"pkg-config\")\n copytree_to_stage(Path(\"share\") / \"pkgconfig\")\n\n # Copy gettext\n gettext_bins = [\n Path(\"bin\") / \"gettext\",\n Path(\"bin\") / \"gettext.sh\",\n Path(\"bin\") / \"xgettext\",\n Path(\"bin\") / \"msgmerge\",\n Path(\"bin\") / \"msgfmt\",\n Path(\"bin\") / \"msgcat\",\n ]\n for p in gettext_bins:\n copy_to_stage(p)\n for p in args.source.glob(\"share/gettext*\"):\n copytree_custom(p, stage_dir / \"share\" / p.name)\n\n # Copy libraries\n copytree_to_stage(\"lib\")\n copytree_to_stage(\"include\")\n # Remove python3 as it takes a lot of space\n for p in (stage_dir / \"lib\").glob(\"python3.*\"):\n shutil.rmtree(p)\n\n # Copy files required by bundler\n for p in [\n Path(\"glib-2.0\") / \"schemas\",\n \"locale\",\n \"themes\",\n \"icons\",\n \"gtksourceview-4\",\n ]:\n copytree_to_stage(Path(\"share\") / p)\n copy_to_stage(Path(\"bin\") / \"gdk-pixbuf-query-loaders\")\n copy_to_stage(Path(\"bin\") / \"gtk-query-immodules-3.0\")\n\n subprocess.run([\"find\", stage_dir])\n\n output_arg: str\n if args.split:\n output_arg = \"-\"\n print(f\"Generating split archive {args.output}.*\")\n else:\n output_arg = args.output\n if args.output.exists():\n args.output.unlink()\n print(f\"Generating archive {args.output}\")\n\n compress_args = [\"--use-compress-program\", zstd_bin] if args.zstd else [\"-z\"]\n tar_cmd = [\"tar\", *compress_args, \"-cf\", output_arg, \"-C\", output_dir, \"gtk\"]\n\n if args.split:\n tar_proc = subprocess.Popen(tar_cmd, stdout=subprocess.PIPE)\n split_proc = subprocess.run(\n [\"split\", \"-b\", \"50m\", \"-\", str(args.output) + \".\"],\n stdin=tar_proc.stdout,\n check=True,\n )\n tar_proc.communicate()\n tar_proc.wait()\n else:\n subprocess.run(tar_cmd, check=True)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"gtk/package-gtk-bin.py","file_name":"package-gtk-bin.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"152236426","text":"from Weapon import Weapon\r\n\r\nclass NerdBombs(Weapon):\r\n\r\n #Creates Constructor for NerdBombs\r\n #@Param self\r\n # Current Instance\r\n def __init__(self):\r\n super(Weapon, self).__init__()\r\n self.usesLeft = 1\r\n self.lowerMod = 4\r\n self.upperMod = 5\r\n self.name = \"NerdBombs\"\r\n","sub_path":"NerdBombs.py","file_name":"NerdBombs.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157850161","text":"import mysql.connector\nfrom os import path\nimport pysam\n\n__author__ = 'Sabina Turkusic'\n\n##\n## Concept:\n## TODO\n##\n\n\nclass Assignment1:\n\n #Constructor\n def __init__(self, gene, genome_reference, file_name, bam_file):\n self.gene = gene\n self.genome_reference = genome_reference\n self.file_name = file_name #ucsc_name\n self.bam_file = bam_file\n self.alignment_file = pysam.AlignmentFile(self.bam_file, \"rb\")\n\n\n def download_gene_coordinates(self):\n print(\"Connecting to UCSC to fetch data\")\n \n ## Open connection\n cnx = mysql.connector.connect(host='genome-mysql.cse.ucsc.edu', user='genomep', passwd='password', db=self.genome_reference)\n \n ## Get cursor\n cursor = cnx.cursor()\n \n ## Build query fields\n query_fields = [\"refGene.name2\",\n \"refGene.name\",\n \"refGene.chrom\",\n \"refGene.txStart\",\n \"refGene.txEnd\",\n \"refGene.strand\",\n \"refGene.exonCount\",\n \"refGene.exonStarts\",\n \"refGene.exonEnds\"]\n \n ## Build query\n query = \"SELECT DISTINCT %s from refGene\" % \",\".join(query_fields)\n \n ## Execute query\n cursor.execute(query)\n \n ## Write to file\n ## TODO this may need some work\n with open(self.file_name, \"w\") as fh:\n for row in cursor:\n fh.write(str(row) + \"\\n\")\n \n \n ## Close cursor & connection\n cursor.close()\n cnx.close()\n \n print(\"Done fetching data\")\n\n \n def get_coordinates_of_gene(self):\n ## Use UCSC file\n count = 0\n with open(self.file_name, \"r\") as UCSC_file:\n for line in UCSC_file:\n if self.gene in line:\n count+=1\n print(line.rstrip(\"\\n\"))\n print(\"There are\", count, \"entries for\", self.gene, \"and only first entry will be used.\")\n\n #use only first entry to get gene coordinates\n with open(self.file_name, \"r\") as UCSC_file:\n for line in UCSC_file:\n if self.gene in line:\n line_split = line.replace(\")\", \"\").replace(\"(\", \"\").replace(\"'\", \"\")\n line_split = line_split.split(\", \")\n break\n\n gene_symbol = line_split[0:2]\n chromosome = line_split[2]\n start = int(line_split[3])\n end = int(line_split[4])\n exons = line_split[6]\n\n print(\"GENE COORDINATES OF FIRST ENTRY: Chromosome:\", chromosome, \", Start-position:\", start, \", Stop-position:\", end)\n\n #Gene Symbol\n\n print(\"The gene symbol is: \", gene_symbol)\n\n #Exons\n\n print(\"The number of exons is: \", exons)\n\n #Reads\n\n reads = self.alignment_file.fetch(chromosome, start, end)\n\n #Prpperly Paired\n\n count_pair = 0\n count_reads = 0\n for read in reads:\n count_reads += 1\n if read.is_proper_pair:\n count_pair += 1\n print(\"In total there are\", count_reads, \"reads and\", count_pair, \"are properly paired\")\n\n\n #Reads with Indels\n reads = self.alignment_file.fetch(chromosome, start, end)\n indel_list = []\n for read in reads:\n if not read.is_unmapped:\n cig = read.cigartuples\n for (operation, length) in cig:\n if (operation == 1) or (operation == 2):\n indel_list.append(read)\n print(\"There are \", len(indel_list), \"reads with indels.\")\n\n\n #Number of mapped Reads\n reads = self.alignment_file.fetch(chromosome, start, end)\n count_mapped = 0\n for read in reads:\n if not read.is_unmapped:\n count_mapped += 1\n print(\"Number of mapped reads:\", count_mapped)\n\n\n #Total Coverage - läuft länger\n #total_cov = []\n #for pileup in self.alignment_file.pileup(chromosome):\n # total_cov.append(pileup.n)\n\n #average_total_coverage = sum(total_cov) / float(len(total_cov))\n #print(\"The average total coverage is: \", average_total_coverage)\n\n #Average Gene Coverage\n gene_cov = []\n for pileup in self.alignment_file.pileup(chromosome, start, end):\n gene_cov.append(pileup.n)\n\n average_gene_coverage = sum(gene_cov) / float(len(gene_cov))\n print(\"The average gene coverage is: \", average_gene_coverage)\n\n\n def get_sam_header(self):\n header_dict = self.alignment_file.header\n #print(header_dict)\n #print(samfile.header.keys())\n\n\ndef main():\n print(\"Assignment 1\")\n assignment1 = Assignment1(\"NRIP1\", \"hg38\", \"UCSC_file.txt\", \"chr21.bam\" )\n\n #check if file exists\n if (path.exists(\"UCSC_file.txt\")):\n print(\"Processing gene coordinates...\")\n else:\n assignment1.download_gene_coordinates() #download gene coordinates\n\n assignment1.get_coordinates_of_gene()\n assignment1.get_sam_header()\n\n print(\"Done with assignment 1\")\n \n \nif __name__ == '__main__':\n main()\n","sub_path":"assignment1_sabinaturkusic.py","file_name":"assignment1_sabinaturkusic.py","file_ext":"py","file_size_in_byte":5238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593162863","text":"from sys import stdin\nfrom Others.Disjoint import Disjoint\nfrom collections import defaultdict\n\n\ndef accounts_merge(accounts):\n ds = Disjoint()\n mail_nm = {}\n mail_id = {}\n cont = 0\n for i in accounts:\n name = i[0]\n for j in i[1:]:\n ds.make_set(j)\n mail_nm[j] = name\n if j not in mail_id:\n mail_id[j] = i\n cont += 1\n ds.union(i[1], j)\n #Tansformar diccionario a listas\n\n\n\nif __name__ == '__main__':\n n = int(stdin.readline())\n accounts = []\n for i in range(n):\n a = stdin.readline().strip().split(\",\")\n accounts.append(a)\n print(accounts_merge(accounts))\n","sub_path":"Laboratorios 12/Accounts merge.py","file_name":"Accounts merge.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"618889779","text":"import nltk\nimport csv\nimport pandas as pd\nimport stanza\nimport Preprocessing\n\nfrom nltk.tokenize.treebank import TreebankWordDetokenizer\nfrom nltk.tokenize.treebank import TreebankWordTokenizer\n\n# download necessary packages\nstanza.download('es', package='ancora', processors='tokenize,pos,lemma', verbose=True) \nnltk.download('stopwords')\nnltk.download('punkt')\n\n# main function\ndef main():\n test()\n # read_csv()\n # read_tsv()\n\n# function for testing\ndef test():\n stNLP, abbreviations, emojis, emoticons, stopwords, d_es = Preprocessing.initialize()\n text = \"\\\"Si ya he pasado el coronavirus, ¿para qué me vacuno? https://t.co/oZo4ZjSruk a través de @Conversation_E\\\"\"\n text = text_preprocessing_debug(text, stNLP, abbreviations, emojis, emoticons, stopwords, d_es)\n print(text)\n\n# function to process tweets in a tsv format\ndef read_tsv():\n stNLP, abbreviations, emojis, emoticons, stopwords, d_es = Preprocessing.initialize()\n \n with open('data/tweets/emoevales_test.tsv', 'r', encoding='utf-8') as infile, open('data/tweets/test-processed_v3.tsv', 'w', newline = '', encoding = 'utf-8') as outfile:\n reader = csv.reader(infile, delimiter='\\t', quoting=csv.QUOTE_NONE)\n writer = csv.writer(outfile, delimiter='\\t')\n \n line_count = 1\n print('START PROCESSING ...')\n writer.writerow(['id', 'event', 'tweet', 'offensive', 'processed_tweet'])\n\n\n for row in reader:\n print('\\tProcessing line ', line_count)\n new_row = row\n print(f'TEXT: {row[2]}')\n text = text_preprocessing(row[2], stNLP, abbreviations, emojis, emoticons, stopwords, d_es)\n new_row.append(text)\n writer.writerow(new_row)\n print(f'TEXT: {text}')\n line_count += 1\n\n outfile.flush() \n\n# function to process tweets in a csv format\ndef read_csv():\n stNLP, abbreviations, emojis, emoticons, stopwords, d_es = Preprocessing.initialize()\n\n with open('data/tweets/covid19-india-dataset-translated.csv', 'r', encoding='utf-8-sig') as infile, open('data/tweets/covid19-india-dataset-training.csv', 'w', newline = '', encoding = 'utf-8') as outfile:\n reader = csv.reader(infile)\n writer = csv.writer(outfile)\n writer.writerow(['id', 'tweet', 'processed_tweet', 'emotion'])\n\n print('START PROCESSING ...')\n line_num = 0\n\n for row in reader:\n new_row = [line_num, row[2], '', row[3]]\n text = text_preprocessing(row[2], stNLP, abbreviations, emojis, emoticons, stopwords, d_es)\n new_row[2] = text\n writer.writerow(new_row)\n \n print(f'\\tProcessing line {line_num}: {new_row}')\n line_num = line_num + 1\n\n outfile.flush() \n\n# function for testing\ndef text_preprocessing_debug(text, stNLP, abbreviations, emojis, emoticons, stopwords, d_es):\n print(\"ORIGINAL TEXT: \", text, \"\\n\")\n text = text.lower()\n print(\"LOWER TEXT: \", text, \"\\n\")\n\n text = Preprocessing.remove_url(text)\n print(\"REMOVE URL TEXT: \", text, \"\\n\")\n text = Preprocessing.remove_mention(text)\n print(\"REMOVE MENTION TEXT: \", text, \"\\n\")\n text = Preprocessing.remove_numbers(text)\n print(\"REMOVE NUMBERS TEXT: \", text, \"\\n\")\n\n text = Preprocessing.replace_emoticons_label(text, emoticons)\n print(\"REPLACE EMOTICONS TEXT: \", text, \"\\n\")\n text = Preprocessing.replace_emojis_label(text, emojis)\n print(\"REPLACE EMOJIS TEXT: \", text, \"\\n\")\n text = Preprocessing.replace_abbreviations(text, abbreviations)\n print(\"REPLACE ABBREV TEXT: \", text, \"\\n\")\n\n text = Preprocessing.remove_punctuation(text)\n print(\"REMOVE PUNCT TEXT: \", text, \"\\n\")\n text = Preprocessing.check_dictionary(text, d_es)\n print(\"DICTIONARY, REPLACE LAUGH, REMOVE REP CHARS: \", text, \"\\n\") \n\n # lemmas = Preprocessing.lemmatize_stanza(text, stNLP)\n lemmas = Preprocessing.lemmatize_spacy(text)\n print(lemmas)\n text = TreebankWordDetokenizer().detokenize(lemmas)\n print(\"LEMMATIZE TEXT: \", text, \"\\n\")\n\n text = Preprocessing.remove_stopwords(text, stopwords)\n print(\"REMOVE STOPWORDS TEXT: \", text, \"\\n\")\n \n text = Preprocessing.remove_extra_spaces(text) \n print(\"PROCESSED TEXT: \", text, \"\\n\")\n\n return text\n\n# function for preprocessing\ndef text_preprocessing(text, stNLP, abbreviations, emojis, emoticons, stopwords, d_es):\n text = text.lower()\n\n text = Preprocessing.remove_url(text)\n text = Preprocessing.remove_mention(text)\n text = Preprocessing.remove_numbers(text)\n\n text = Preprocessing.replace_emoticons_label(text, emoticons)\n text = Preprocessing.replace_emojis_label(text, emojis)\n text = Preprocessing.replace_abbreviations(text, abbreviations)\n\n text = Preprocessing.remove_punctuation(text)\n text = Preprocessing.check_dictionary(text, d_es) \n\n # lemmas = Preprocessing.lemmatize_stanza(text, stNLP)\n lemmas = Preprocessing.lemmatize_spacy(text)\n text = TreebankWordDetokenizer().detokenize(lemmas)\n\n text = Preprocessing.remove_stopwords(text, stopwords)\n text = Preprocessing.remove_extra_spaces(text) \n\n return text\n\n\nif __name__ == '__main__':\n main()\n ","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"78406658","text":"def main():\r\n shape = [[], [], [], [], []]\r\n shape = FillList(shape)\r\n ##printList(shape)\r\n\r\n\r\n\r\ndef FillList(list1):\r\n count = 1\r\n for row in range(0, 5):\r\n for col in range(0, count):\r\n list1[row].append(\"$\")\r\n print(list1)\r\n count+=1\r\n return list1\r\n\r\ndef printList(list1):\r\n count = 1\r\n for row in range(0, 5):\r\n for col in range(0, count):\r\n print(list1[row][col], end=\" \")\r\n print(\"\\n\")\r\n count+=1\r\n\r\n\r\nmain()\r\n","sub_path":"shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"204274722","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function, absolute_import\n\nimport os\nimport subprocess\n\nimport click\n\nfrom click_project.decorators import group, option, argument, flag, table_format,\\\n table_fields\nfrom click_project.lib import which, check_output, call, createfile, ParameterType,\\\n TablePrinter\nfrom click_project.completion import startswith\nfrom click_project.log import get_logger\n\nLOGGER = get_logger(__name__)\n\n\ndef git():\n git = which(\"git\")\n if not git:\n raise click.UsageError(\"Git is needed to use the git-store command\")\n return git\n\n\ndef get_refs(remote=None):\n ref_command = [\"ls-remote\", remote] if remote else [\"show-ref\"]\n\n def split(ref):\n res = ref.split(\" \")\n res[1] = res[1][len(\"refs/git-store/\"):]\n return res\n\n return [\n split(line)\n for line in check_output(\n [git()] + ref_command,\n internal=True,\n nostderr=True,\n ).strip().replace(\"\\t\", \" \").splitlines()\n if line.split(\" \")[1].startswith(\"refs/git-store/\")\n ]\n\n\ndef get_refs_names(remote=None):\n return [\n ref[1]\n for ref in get_refs(remote)\n ]\n\n\ndef get_refs_dict(remote=None):\n return {\n ref[1]: ref[0]\n for ref in get_refs(remote)\n }\n\n\ndef notes_command():\n return [git(), \"notes\", \"--ref\", \"git-store\"]\n\n\n_note_ref = None\n\n\ndef note_ref():\n global _note_ref\n if _note_ref is None:\n _note_ref = check_output(notes_command() + [\"get-ref\"]).strip()\n return _note_ref\n\n\n_current_remote = None\n\n\ndef current_remote():\n global _current_remote\n if _current_remote is None:\n try:\n _current_remote = check_output(\n [\n git(), \"rev-parse\", \"--abbrev-ref\", \"--symbolic-full-name\", \"@{u}\"\n ],\n internal=True,\n nostderr=True,\n ).strip().split(\"/\")[0]\n except subprocess.CalledProcessError:\n pass\n return _current_remote\n\n\n@group(default_command=\"show\")\ndef git_store():\n \"\"\"Store data in a git repository\n\n This is a low level command. If you want to manage data files of a project,\n consider using the higher level command gt-record.\n\n Guess your model depends on client data. You generally want those data to\n hang around your code to take advantage of them. But you you don't want to\n mix those data with your code because:\n\n 1. data and code don't belong to the same intellectual property\n\n 2. data will irreversibly increase the repository size even when you don't need the data anymore\n\n Generally, you put your data in some NAS but:\n\n 1. it is not practical to have to fetch them every time\n\n 2. you may be out of sync easily\n\n 3. you need two credentials: one for git, one for the NAS\n\n 4. people being able to change the data in the NAS, you cannot make sure of the reproducibility of your simulations\n\n Guess what? Git was designed as a file system. There is better: when you put\n a file or directory in git, it returns a so called hash value (remember the\n git sha1?) that identifies the file by its content. You can retrieve this\n file/directory later with its hash value. You will be sure to have the exact\n same content. This is particularly important in reproducible research when\n you want to make sure you always run the same simulation with the same\n input. Of course, to ease file retrieval, you can also provide fancy names\n to files stored in git.\n\n Technicaly, you save a file/directory foo by calling 'git-store save\n foo' will indicate in return the name of the object to retrieve it\n later. The name is composed of the original file name along with the first 8\n characters of its hash value. This name is more than enough to prevent name\n clashes even when saving other files with the same name. You can still\n provide your prefered name with 'git-store save --name \"foo/v1\" foo'.\n\n To see what files are saved in git, use 'git-store show'\n\n To restore the file content somewhere, use 'git-store restore foo/v1\n --file foo'\n\n To send the file to a git remote so that everyone can get access to it:\n 'git-store push foo/v1'\n\n To see what files are saved in a git remote bar, use 'git-store show\n --remote bar'\n\n To fetch the file from the remote bar 'git-store fetch --from bar\n --name foo/v2'. Then you will be able to run 'git-store restore foo/v2\n --file foo'\n\n To add notes to files, try 'git-store notes --help'\n \"\"\"\n if toplevel() is None:\n raise click.UsageError(\n \"Using git store commands only makes sense in a git repository\"\n )\n\n\n_git_remotes = None\n\n\ndef git_remotes():\n global _git_remotes\n if _git_remotes is None:\n _git_remotes = check_output([git(), \"remote\"]).splitlines()\n return _git_remotes\n\n\nclass GitRemoteType(ParameterType):\n def complete(self, ctx, incomplete):\n return [\n clr\n for clr in git_remotes()\n if startswith(clr, incomplete)\n ]\n\n\nclass LocalReferenceType(ParameterType):\n def __init__(self, notinremote=False):\n self.notinremote = notinremote\n\n @property\n def refs(self):\n if self.notinremote and _remote is not None:\n return list(set(get_refs_names()) - set(get_refs_names(_remote)))\n else:\n return get_refs_names()\n\n def complete(self, ctx, incomplete):\n return [\n clr\n for clr in self.refs\n if startswith(clr, incomplete)\n ]\n\n def convert(self, value, param, ctx):\n choices = self.refs + [\"*\"]\n if value not in choices:\n self.fail('invalid choice: %s. (choose from %s)' %\n (value, ', '.join(choices)), param, ctx)\n return \"refs/git-store/{}\".format(value)\n\n\nclass RemoteReferenceType(ParameterType):\n def __init__(self, notinlocal=False):\n super(RemoteReferenceType, self).__init__()\n self.notinlocal = notinlocal\n\n @property\n def refs(self):\n if self.notinlocal:\n return list(set(get_refs_names(_remote)) - set(get_refs_names()))\n else:\n return get_refs_names(_remote)\n\n def complete(self, ctx, incomplete):\n if _remote:\n return [\n clr\n for clr in self.refs\n if startswith(clr, incomplete)\n ]\n else:\n return []\n\n def convert(self, value, param, ctx):\n choices = self.refs + [\"*\"]\n if value not in choices:\n self.fail('invalid choice: %s. (choose from %s)' %\n (value, ', '.join(choices)), param, ctx)\n return \"refs/git-store/{}\".format(value)\n\n\n@git_store.command()\n@argument('file', required=True)\n@option('--name', help=(\n \"Name of the saved file.\"\n \" Its default value is generally a good choice,\"\n \" thus use this option only if you know what you are doing\"))\n@flag(\"--force\", help=(\n \"Force the insertion of the file in git,\"\n \" even though a file with the same name already exists.\"\n \" Use this only if you understand what it does.\"\n))\n@flag(\"--create-hash-file/--dont-create-hash-file\",\n help=\"Create a hash file, to be consumed by generated hash scripts\")\ndef save(name, file, force, create_hash_file):\n \"\"\"Save the file or directory into git\n\n If a different file associated to the same name already exists, it means you\n are probably trying to shoot yourself in the foot: the command will fail.\n You can bypass this security with --force.\n\n \"\"\"\n name = _save(name, file, force, create_hash_file=create_hash_file)\n click.echo(\"Saved {} with the git name {}\".format(file, name))\n\n\n_toplevel = None\n\n\ndef toplevel():\n global _toplevel\n if _toplevel is None:\n try:\n _toplevel = check_output(\n [git(), \"rev-parse\", \"--show-toplevel\"],\n nostderr=True,\n internal=True,\n ).strip()\n except subprocess.CalledProcessError:\n pass\n return _toplevel\n\n\ndef _save(name, file, force, create_hash_file=False):\n full = os.path.abspath(file)\n hash_file = full + \".hash\"\n dir = os.path.dirname(full)\n file = os.path.basename(full)\n tl = toplevel()\n prefixfile = os.path.relpath(full, tl)\n if os.path.isdir(full):\n call([git(), \"add\", \"-f\", \"--\", file], cwd=dir)\n blob = check_output([git(), \"write-tree\", \"--prefix\", prefixfile]).strip()\n check_output([git(), \"reset\", \"--\", file], nostderr=True)\n else:\n blob = check_output([git(), \"hash-object\", \"-w\", \"--\", full]).strip()\n name = name or (file + \"-\" + blob[:8])\n name = name.replace(\".\", \"_\").replace(\" \", \"_\")\n if create_hash_file:\n createfile(hash_file, name)\n refs_dict = get_refs_dict()\n if not force and name in refs_dict:\n other_blob = refs_dict[name]\n if blob == other_blob:\n LOGGER.warning(\"The git name {} already exists\"\n \" and is associated to the same content\".format(\n name,\n blob,\n ))\n return name\n else:\n raise click.UsageError(\n \"The git name {} already exists with hash {}.\"\n \" You are willing to associate it with the hash {}.\"\n \" Either choose another name or use --force\"\n \" if you know what you are doing\".format(\n name,\n other_blob,\n blob,\n ))\n ref = \"refs/git-store/{}\".format(name)\n check_output([git(), \"update-ref\", ref, blob])\n return name\n\n\n@git_store.command()\n@option(\"-r\", \"--remote\", type=GitRemoteType(),\n help=(\n \"Instead of showing the file available locally,\"\n \" list those available to be fetched from the remote\"\n ))\n@table_fields(choices=['ref', 'details'])\n@table_format(default='key_value')\n@flag(\"--with-notes\", help=(\n \"Show the first line of notes on the file.\"\n \" See git-store notes --help for more info\"\n))\n@argument(\"name\", type=LocalReferenceType(), nargs=-1)\ndef show(remote, format, fields, with_notes, name):\n \"\"\"Show the available files\n\n It also show some low level information about the file, like its hash value.\n\n If you want to list the files of a remote, use the --remote option.\n \"\"\"\n refs = [\n r\n for r in get_refs(remote)\n if not name or \"refs/git-store/\" + r[1] in name\n ]\n\n def get(blob_ref):\n ref = \"refs/git-store/\" + blob_ref[1]\n res = \"Hash: {}\".format(blob_ref[0][:8])\n try:\n typ = check_output(\n [git(), \"cat-file\", \"-t\", ref],\n nostderr=True,\n internal=True,\n ).strip()\n except subprocess.CalledProcessError:\n typ = \"unknown\"\n res += \" , Type: {}\".format(typ)\n if with_notes:\n try:\n note = check_output(notes_command() + [\"show\", ref], nostderr=True).strip()\n except subprocess.CalledProcessError:\n note = None\n if note:\n res += \" , Note: {}\".format(note.splitlines()[0])\n return res\n\n with TablePrinter(fields, format) as tp:\n for ref in refs:\n tp.echo(ref[1], get(ref))\n\n\n@git_store.command()\n@argument(\"name\", type=LocalReferenceType())\ndef cat(name):\n \"\"\"Display the file content\n\n If it is a file, show its content. If it is a directory, show its files\nlisting.\n\n \"\"\"\n call([git(), \"cat-file\", \"-p\", name])\n\n\n@git_store.command()\n@option(\"-f\", \"--from\", \"remote\", type=GitRemoteType(),\n help=\"Remove from this remote\")\n@argument(\"name\", type=LocalReferenceType())\ndef remove(remote, name):\n \"\"\"Remove the file\n\n The file is removed locally. If --from is used, the file is removed\n from this remote instead (i.e. without removing locally)\n\n \"\"\"\n call([git()] +\n ([\"push\", \"-d\", remote] if remote else [\"update-ref\", \"-d\"]) +\n [name])\n LOGGER.status(\"Removed {}\".format(name))\n\n\n_remote = None\n\n\ndef remote_callback(ctx, attr, value):\n global _remote\n if value:\n _remote = value\n return value\n\n\n@git_store.command(handle_dry_run=True)\n@option(\"-f\", \"--from\", \"remote\", required=True, default=current_remote, is_eager=True,\n type=GitRemoteType(), callback=remote_callback,\n help=\"The remote to fetch from\")\n@option(\"--name\", default=\"*\", type=RemoteReferenceType(notinlocal=True), multiple=True)\ndef fetch(remote, name):\n \"\"\"Fetch those files from the remote\n\n Once fetched, you can cat or restore them\n\n \"\"\"\n for ref_ in name:\n call([git(), \"fetch\", remote, \"{}:{}\".format(ref_, ref_)])\n\n\n@git_store.command()\n@option(\"-t\", \"--to\", \"remote\", default=current_remote, type=GitRemoteType(),\n help=\"The remote to push to\", callback=remote_callback)\n@option(\"--name\", default=\"*\", type=LocalReferenceType(notinremote=True),\n multiple=True)\n@flag(\"--force/--no-force\",\n help=\"Force the push (you probably won't want to do that)\")\ndef push(remote, name, force):\n \"\"\"Send the file to the given remote\"\"\"\n args = [git(), \"push\", remote]\n if force:\n args.append(\"--force\")\n for ref_ in name:\n call(args + [ref_])\n\n\n@git_store.command()\n@argument(\"name\", type=LocalReferenceType())\n@option(\"--file\", help=\"Location where to put the content\")\ndef restore(file, name):\n \"\"\"Put the content of name into file\n\n By default, put the content of name on a file/directory with the same\n name. You can provide a different location with --file\n\n \"\"\"\n file = file or name[len(\"refs/git-store/\"):]\n file = os.path.abspath(file)\n tl = toplevel()\n prefixfile = os.path.relpath(file, tl)\n if check_output([git(), \"cat-file\", \"-t\", name]).strip() == \"tree\":\n call([git(), \"read-tree\", name, \"--prefix\", prefixfile])\n call([git(), \"checkout\", \"--\", file])\n check_output([git(), \"reset\", \"--\", file])\n else:\n call([git(), \"cat-file\", \"blob\", name], stdout=open(file, \"w\"))\n LOGGER.info(\n \"Restored git name {} in location {}\".format(\n name[len(\"refs/git-store/\"):],\n prefixfile\n ))\n\n\n@git_store.group()\ndef notes():\n \"\"\"Manipulate notes on files\n\n Sometimes, one wants to store some information to explain what the file is\n and why it is important. Git allows to store notes associated to file for\n exactly this purpose.\n\n Generally, you just need to call 'git-store notes set -m \"some\n information\" foo/v1' to set the note.\n\n To send the note for everyone to see it, just run 'git-store notes\n push'.\n\n To fetch the notes written by someone else, run 'git-store notes fetch'\n\"\"\"\n pass\n\n\n@notes.command()\n@option(\"-m\", \"--message\", required=True, help=\"The message to set as note\")\n@argument(\"name\", type=LocalReferenceType())\ndef _set(message, name):\n \"\"\"Set a message as note of the file\"\"\"\n call(\n notes_command() + [\n \"add\", \"-f\",\n \"-m\", message,\n name\n ]\n )\n\n\n@notes.command()\n@option(\"-m\", \"--message\", required=True, help=\"The message to append as note\")\n@argument(\"name\", type=LocalReferenceType())\ndef append(message, name):\n \"\"\"Append the message to the note associated to the file\"\"\"\n call(\n notes_command() + [\n \"append\",\n \"-m\", message,\n name\n ]\n )\n\n\n@notes.command()\n@argument(\"name\", type=LocalReferenceType())\ndef edit(name):\n \"\"\"Edit the note of the file\"\"\"\n call(\n notes_command() + [\n \"edit\",\n name\n ]\n )\n\n\n@notes.command()\n@argument(\"name\", type=LocalReferenceType())\ndef _remove(name):\n \"\"\"Remove the note associated to the file\"\"\"\n call(\n notes_command() + [\n \"remove\",\n name\n ]\n )\n\n\n@notes.command()\n@argument(\"name\", type=LocalReferenceType())\ndef _show(name):\n \"\"\"Show the note associated to the file\"\"\"\n call(\n notes_command() + [\n \"show\",\n name\n ]\n )\n\n\n@notes.command()\n@argument(\"remote\", type=GitRemoteType())\ndef _push(remote):\n \"\"\"Send all the notes to the git remote\"\"\"\n call(\n [\n \"git\", \"push\",\n remote, \"{}:{}\".format(note_ref(), note_ref())\n ]\n )\n\n\n@notes.command()\n@argument(\"remote\", type=GitRemoteType())\ndef _fetch(remote):\n \"\"\"Fetch all the notes from the git remote\"\"\"\n call(\n [\n \"git\", \"fetch\",\n remote, \"{}:{}\".format(note_ref(), note_ref())\n ]\n )\n","sub_path":"click_project/commands/git_store.py","file_name":"git_store.py","file_ext":"py","file_size_in_byte":16800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"242501796","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport datetime\nimport random\nimport string\nfrom xml.etree import cElementTree as ElementTree\n\nfrom django.test import TestCase\n\nfrom casexml.apps.phone.models import SyncLogSQL, properly_wrap_sync_log\nfrom casexml.apps.phone.tests.utils import (\n call_fixture_generator,\n create_restore_user,\n deprecated_generate_restore_payload,\n)\nfrom corehq.apps.app_manager.tests.util import TestXmlMixin\nfrom corehq.apps.programs.fixtures import program_fixture_generator\nfrom corehq.apps.products.fixtures import product_fixture_generator\nfrom corehq.apps.products.models import Product\nfrom corehq.apps.programs.models import Program\nfrom corehq.apps.commtrack.tests import util\nfrom six.moves import range\n\n\nclass FixtureTest(TestCase, TestXmlMixin):\n domain = \"fixture-test\"\n\n @classmethod\n def setUpClass(cls):\n super(FixtureTest, cls).setUpClass()\n cls.domain_obj = util.bootstrap_domain(cls.domain)\n util.bootstrap_location_types(cls.domain)\n util.bootstrap_products(cls.domain)\n cls.user = create_restore_user(cls.domain)\n\n @classmethod\n def tearDownClass(cls):\n cls.domain_obj.delete()\n super(FixtureTest, cls).tearDownClass()\n\n def _random_string(self, length):\n return ''.join(random.choice(string.ascii_lowercase)\n for _ in range(length))\n\n def _initialize_product_names(self, count):\n product_names = sorted([self._random_string(20) for _ in range(count)])\n\n def get_product_name():\n for name in product_names:\n yield name\n self.product_names = get_product_name()\n\n def generate_product_xml(self, user, randomize_data=True):\n products = []\n product_list = Product.by_domain(user.domain)\n self._initialize_product_names(len(product_list))\n for i, product in enumerate(product_list):\n product_id = product._id\n product_name = next(self.product_names)\n product_unit = self._random_string(20)\n product_code = self._random_string(20)\n product_description = self._random_string(20)\n product_category = self._random_string(20)\n product_program_id = self._random_string(20)\n product_cost = 0 if i == 0 else float('%g' % random.uniform(1, 100))\n\n # only set this on one product, so we can also test that\n # this node doesn't get sent down on every product\n if i == 0:\n product_data = {\n 'special_number': '555111'\n }\n\n custom_data_xml = '''\n \n 555111\n \n '''\n else:\n product_data = {}\n custom_data_xml = ''\n\n product_xml = '''\n \n {name}\n {unit}\n {code}\n {description}\n {category}\n {program_id}\n {cost}\n {custom_data}\n \n '''.format(\n id=product_id,\n name=product_name,\n unit=product_unit,\n code=product_code,\n description=product_description,\n category=product_category,\n program_id=product_program_id,\n cost=product_cost,\n custom_data=custom_data_xml\n )\n\n product.name = product_name\n product.unit = product_unit\n product.code = product_code\n product.description = product_description\n product.category = product_category\n product.program_id = product_program_id\n product.cost = product_cost\n product.product_data = product_data\n product.save()\n\n products.append((product, product_xml))\n\n products.sort(key=lambda p: p[0].code)\n return ''.join(product_xml for product, product_xml in products)\n\n def generate_product_fixture_xml(self, user, randomize_data=True):\n return \"\"\"\n \n \n {products}\n \n \n \"\"\".format(\n user_id=user.user_id,\n products=self.generate_product_xml(user, randomize_data)\n )\n\n def test_product_fixture(self):\n user = self.user\n fixture_xml = self.generate_product_fixture_xml(user)\n index_schema, fixture = call_fixture_generator(product_fixture_generator, user)\n\n self.assertXmlEqual(fixture_xml, fixture)\n\n schema_xml = \"\"\"\n \n \n @id\n category\n code\n program_id\n \n \n \"\"\"\n self.assertXmlEqual(schema_xml, ElementTree.tostring(index_schema))\n\n # test restore with different user\n user2 = create_restore_user(self.domain, username='user2')\n self.addCleanup(user2._couch_user.delete)\n fixture_xml = self.generate_product_fixture_xml(user2)\n index_schema, fixture = call_fixture_generator(product_fixture_generator, user2)\n\n self.assertXmlEqual(fixture_xml, fixture)\n\n def test_product_fixture_cache(self):\n user = self.user\n\n expected_xml = self.generate_product_fixture_xml(user)\n\n fixture_original = call_fixture_generator(product_fixture_generator, user)[1]\n self.assertXmlEqual(\n expected_xml,\n fixture_original\n )\n\n product = Product.by_domain(user.domain)[0]\n product.name = 'new_name'\n super(Product, product).save() # save but skip clearing the cache\n\n fixture_cached = call_fixture_generator(product_fixture_generator, user)[1]\n self.assertXmlEqual(\n expected_xml,\n fixture_cached\n )\n\n # This will update all the products and re-save them.\n expected_xml_new = self.generate_product_fixture_xml(user)\n\n fixture_cached = call_fixture_generator(product_fixture_generator, user)[1]\n self.assertXmlEqual(\n expected_xml_new,\n fixture_cached\n )\n self.assertXMLNotEqual(expected_xml_new, expected_xml)\n\n def generate_program_xml(self, program_list, user):\n program_xml = ''\n for program in program_list:\n program_xml += '''\n \n {name}\n {code}\n \n '''.format(\n id=program.get_id,\n name=program.name,\n code=program.code\n )\n\n return \"\"\"\n \n \n {programs}\n \n \n \"\"\".format(\n user_id=user.user_id,\n programs=program_xml\n )\n\n def _get_latest_synclog(self):\n return properly_wrap_sync_log(SyncLogSQL.objects.order_by('date').last().doc)\n\n def test_program_fixture(self):\n user = self.user\n Program(\n domain=user.domain,\n name=\"test1\",\n code=\"t1\"\n ).save()\n\n program_list = Program.by_domain(user.domain)\n program_xml = self.generate_program_xml(program_list, user)\n\n fixture = call_fixture_generator(program_fixture_generator, user)\n\n self.assertXmlEqual(\n program_xml,\n fixture[0]\n )\n\n # test restore with different user\n user2 = create_restore_user(self.domain, username='user2')\n self.addCleanup(user2._couch_user.delete)\n program_xml = self.generate_program_xml(program_list, user2)\n fixture = call_fixture_generator(program_fixture_generator, user2)\n\n self.assertXmlEqual(\n program_xml,\n fixture[0]\n )\n\n def test_program_fixture_cache(self):\n user = self.user\n Program(\n domain=user.domain,\n name=\"test1\",\n code=\"t1\"\n ).save()\n\n program_list = list(Program.by_domain(user.domain))\n program_xml = self.generate_program_xml(program_list, user)\n\n fixture = call_fixture_generator(program_fixture_generator, user)\n\n self.assertXmlEqual(\n program_xml,\n fixture[0]\n )\n\n program = program_list[0]\n program.name = 'new_name'\n super(Program, program).save() # save but skip clearing the cache\n\n fixture_cached = call_fixture_generator(program_fixture_generator, user)\n self.assertXmlEqual(\n program_xml,\n fixture_cached[0]\n )\n\n program.save()\n program_xml_new = self.generate_program_xml(program_list, user)\n\n fixture_regen = call_fixture_generator(program_fixture_generator, user)\n self.assertXmlEqual(\n program_xml_new,\n fixture_regen[0]\n )\n self.assertXMLNotEqual(program_xml_new, program_xml)\n","sub_path":"corehq/apps/commtrack/tests/test_fixture.py","file_name":"test_fixture.py","file_ext":"py","file_size_in_byte":9647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"332232402","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom forecaster import Forecaster\nfrom calibration import EWACalibratedForecaster\n\nclass EWARecalibratedForecaster(Forecaster):\n \"\"\"Recalibrates online probability estimates\"\"\"\n def __init__(self, N, eta=None):\n super(EWARecalibratedForecaster, self).__init__(N+1)\n self.last_i = None\n # F_cal[i] is responsible for iterval [i/N, (i+1)/N]\n if (isinstance(eta, np.ndarray) or isinstance(eta, list)) and len(eta) == N:\n self.F_cal = [EWACalibratedForecaster(N, eta[i]) for i in range(N)]\n else:\n self.F_cal = [EWACalibratedForecaster(N, eta) for i in range(N)]\n\n def predict(self, p_raw):\n if p_raw == 1.0:\n i = self.N-2\n else:\n i = int(np.floor(p_raw*(self.N-1)))\n self.last_i = i\n return self.F_cal[i].predict()\n\n def expected_prediction(self, p_raw):\n if p_raw == 1.0:\n i = self.N-2\n else:\n i = int(np.floor(p_raw*(self.N-1)))\n self.last_i = i\n return self.F_cal[i].expected_prediction()\n\n def observe(self, y_t):\n if self.last_i is None:\n raise ValueError(\"Need to observe an uncalibrated p first\")\n\n i = self.last_i\n self.F_cal[i].observe(y_t)\n self.last_i = None\n\n @property\n def examples_seen(self):\n return [F.examples_seen for F in self.F_cal]\n \n \n","sub_path":"forecasters/recalibration.py","file_name":"recalibration.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"473647383","text":"import os\nimport json\nfrom math import log\nfrom geojson import GeoJSON\nfrom progress import Progress\n\nif __name__ == '__main__':\n\n print(\"threshold 1: \", end=\"\")\n threshold_1 = int( input() )\n print(\"input data 1: \", end=\"\")\n input_file_1 = input()\n print(\"max 1: \", end=\"\")\n max_1 = int( input() )\n print(\"threshold 2: \", end=\"\")\n threshold_2 = int( input() )\n print(\"input data 2: \", end=\"\")\n input_file_2 = input()\n print(\"max 2: \", end=\"\")\n max_2 = int( input() )\n\n input_text = \"\"\n input_path = \"json/\" + input_file_1 + \".json\"\n\n file_size = os.path.getsize(input_path)\n progress = Progress(file_size)\n progress.progressBar(\"File1 Loading\")\n with open(input_path, 'r') as f:\n line = f.readline()\n while line:\n progress.tick( len(line) )\n input_text += line\n line = f.readline()\n\n dataset_1 = json.loads(input_text)\n\n input_text = \"\"\n input_path = \"json/\" + input_file_2 + \".json\"\n file_size = os.path.getsize(input_path)\n progress = Progress(file_size)\n progress.progressBar(\"File2 Loading\")\n with open(input_path, 'r') as f:\n line = f.readline()\n while line:\n progress.tick( len(line) )\n input_text += line\n line = f.readline()\n\n dataset_2 = json.loads(input_text)\n\n geojson = GeoJSON()\n output = geojson.getFormat()\n\n progress = Progress( len(dataset_1) )\n progress.progressBar(\"Conversioning\")\n for i in range( len(dataset_1) ):\n if dataset_1[i][5] > threshold_1 and dataset_2[i][5] > threshold_2:\n red = int( ( log(dataset_1[i][5]) / log(max_1) ) * 255 )\n blue = int( ( log(dataset_2[i][5]) / log(max_2) ) * 255 )\n color = \"rgba(\" + str(red) + \", 0, \" + str(blue) + \", 0.5)\"\n output[\"features\"].append( geojson.getFeature(\"Polygon\",\n [[ [dataset_1[i][2], dataset_1[i][1]],\n [dataset_1[i][2], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][1]] ]],\n { \"color\": color,\n \"twitter\": {\"population\": dataset_1[i][5]},\n \"flickr\": {\"population\": dataset_2[i][5]}\n }) )\n elif dataset_1[i][5] > threshold_1:\n red = int( ( log(dataset_1[i][5]) / log(max_1) ) * 255 )\n color = \"rgba(\" + str(red) + \", 0, 0, 0.5)\"\n output[\"features\"].append( geojson.getFeature(\"Polygon\",\n [[ [dataset_1[i][2], dataset_1[i][1]],\n [dataset_1[i][2], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][1]] ]],\n { \"color\": color,\n \"twitter\": {\"population\": dataset_1[i][5]},\n \"flickr\": {\"population\": 0}\n }) )\n elif dataset_2[i][5] > threshold_2:\n blue = int( ( log(dataset_2[i][5]) / log(max_2) ) * 255 )\n color = \"rgba(0, 0, \" + str(blue) + \", 0.5)\"\n output[\"features\"].append( geojson.getFeature(\"Polygon\",\n [[ [dataset_1[i][2], dataset_1[i][1]],\n [dataset_1[i][2], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][3]],\n [dataset_1[i][4], dataset_1[i][1]] ]],\n { \"color\": color,\n \"twitter\": {\"population\": 0},\n \"flickr\": {\"population\": dataset_2[i][5]}\n }) )\n\n progress.tick(1)\n\n output_text = json.dumps(output, indent=4)\n\n output_path = 'json/mixture_geo.json'\n with open(output_path, 'w') as f:\n f.write(output_text)\n\n print(\"[\" + str( len(output[\"features\"]) ) + \"]\")\n","sub_path":"conversion/conversion_mix.py","file_name":"conversion_mix.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"253916761","text":"#!/usr/local/bin/python\r\n\r\nimport pandas as pd\r\nimport argparse\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--transcriptomics', dest='rnafile',\r\n help='Deconvoluted matrix of transcriptomics data')\r\n parser.add_argument('--proteomics', dest='profile',\r\n help='Deconvoluted matrix of proteomics data')\r\n parser.add_argument('--spearOrPears', dest='sop', help='Use spearman or pearson correlation',\r\n default='pearson')\r\n # parser.add_argument('--output', dest='output',\r\n # help='Output file for the correlation values')\r\n opts = parser.parse_args()\r\n\r\n rna = pd.read_csv(opts.rnafile, sep='\\t', index_col=0)\r\n pro = pd.read_csv(opts.profile, sep='\\t', index_col=0)\r\n\r\n rnaCols = list(rna.columns)\r\n proCols = list(pro.columns)\r\n rnaRows = list(rna.index)\r\n proRows = list(pro.index)\r\n intersectCols = list(set(rnaCols) & set(proCols))\r\n intersectRows = list(set(rnaRows) & set(proRows))\r\n\r\n pro = pro.loc[intersectRows, intersectCols]\r\n rna = rna.loc[intersectRows, intersectCols]\r\n\r\n rna = rna.transpose()\r\n pro = pro.transpose()\r\n\r\n if opts.sop == 'pearson':\r\n corrList = [pro[sample].corr(rna[sample]) for sample in intersectRows]\r\n else:\r\n corrList = [pro[sample].corr(rna[sample], method='spearman')\r\n for sample in intersectRows]\r\n\r\n correlations = pd.Series(corrList)\r\n correlations.index = intersectRows\r\n correlations.to_csv(\"corrXcelltypes.tsv\", sep='\\t', header=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"metrics/correlations/correlationXcelltypes.py","file_name":"correlationXcelltypes.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"560314336","text":"import os\nimport sys\nfrom collections import defaultdict\n# Add the parent directory to the path\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\n\nfrom Intcode.Intcode import Intcode\n\nclass Graph():\n def __init__(self, height):\n self.__height = height\n self.nodes = defaultdict(list)\n self.alignment = 0\n\n\n def calibrate(self):\n for node, adjacents in self.nodes.items():\n if len(adjacents) == 4:\n x, y = node\n self.alignment += (self.__height - y) * x\n\n\n def listAdjacents(self, node):\n x, y = node\n adjacents = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n for a in adjacents:\n if a in self.nodes.keys():\n self.nodes[node].append(a)\n\n\nif __name__ == \"__main__\":\n intcode = Intcode(\"input.txt\")\n intcode.run()\n out = intcode.getOutput()\n\n\n length = 1\n with open(os.path.join(sys.path[0], \"output.txt\"), \"w\") as w:\n for n in out:\n if n == 10:\n length += 1\n w.write(chr(n))\n \n graph = Graph(length)\n with open(os.path.join(sys.path[0], \"output.txt\"), \"r\") as r:\n x, y = (0, length)\n for line in r.readlines():\n y -= 1\n x = 0\n for c in line:\n x += 1\n if c == \"#\":\n graph.nodes[(x, y)] = []\n\n for node in graph.nodes.keys():\n graph.listAdjacents(node)\n\n graph.calibrate()\n print(graph.alignment)\n\n A = [ord(c) for c in \"L,12,L,10,R,8,L,12\\n\"]\n B = [ord(c) for c in\"R,8,R,10,R,12\\n\"]\n C = [ord(c) for c in \"L,10,R,12,R,8\\n\"]\n mainRoutine = [ord(c) for c in \"A,B,A,B,C,C,B,A,B,C\\n\"]\n\n intcode = Intcode(\"input_part2.txt\")\n intcode.run()\n out = intcode.getOutput(ascii=True)[-6:-1]\n print(\"\".join(out), mainRoutine)\n\n for i in mainRoutine:\n intcode.run(i)\n \n out = intcode.getOutput(ascii=True)\n print(\"\".join(out), A)\n for i in A:\n intcode.run(i)\n\n out = intcode.getOutput(ascii=True)\n print(\"\".join(out), B)\n for i in B:\n intcode.run(i)\n \n out = intcode.getOutput(ascii=True)\n print(\"\".join(out), C)\n for i in C:\n intcode.run(i)\n \n\n out = intcode.getOutput(ascii=True)\n print(\"\".join(out), \"n\")\n intcode.run(ord(\"n\"))\n intcode.run(10)\n out = intcode.getOutput(ascii=True)\n print(\"\".join(out))\n \n\n\n\n\n\n","sub_path":"Day17/day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"316166038","text":"\"\"\"\r\nw konsli\r\nwejść do folderu z bazą\r\nsqlite3 student.db\r\n.schema student\r\n# wyswietla schemat utworzenia tabeli\r\n\r\n#dodawanie daty aktualnej\r\nINSERT INTO test VALUES (date('now'), 1, NULL);\r\n\r\n\"\"\"\r\n\r\nimport random\r\nf_names = [\"Michael\", \"Christopher\", \"Joshua\", \"Matthew\", \"David\",\r\n \"Daniel\", \"Andrew\", \"Joseph\", \"Justin\", \"James\",\r\n \"Jessica\", \"Ashley\", \"Brittany\", \"Amanda\", \"Melissa\",\r\n \"Stephanie\", \"Jennifer\", \"Samantha\", \"Sarah\", \"Megan\", \"Lauren\"]\r\nl_names = [\"Smith\", \"Johnson\", \"Williams\", \"Jones\", \"Brown\",\r\n \"Davis\", \"Miller\", \"Wilson\", \"Moore\", \"Taylor\",\r\n \"Anderson\", \"Thomas\", \"Jackson\", \"White\", \"Harris\",\r\n \"Martin\", \"Thompson\", \"Garcia\", \"Martinez\", \"Robinson\"]\r\n\r\n\r\ndef create_students(how_many):\r\n for i in range(how_many):\r\n f_name = f_names[random.randint(0, len(f_names) - 1)]\r\n l_name = l_names[random.randint(0, len(l_names) - 1)]\r\n\r\n sex = random.choice([\"M\", \"F\"])\r\n print(f\"INSERT INTO student (f_name, l_name, sex) VALUES('{l_name}', '{l_name}', '{sex}');\")\r\n\r\n\r\n#create_students(10)\r\n\r\n\r\ndef create_test_scores(num_tests, num_studs):\r\n \"\"\"\r\n sqlite> .schema test_score\r\n CREATE TABLE test_score(\r\n student_id INTEGER NOT NULL,\r\n test_id INTEGER NOT NULL,\r\n score INTEGER NOT NULL,\r\n FOREIGN KEY (test_id) REFERENCES test(id),\r\n FOREIGN KEY (student_id) REFERENCES student(id),\r\n PRIMARY KEY (test_id, student_id));\r\n \"\"\"\r\n for i in range(1, num_tests + 1):\r\n for j in range(1, num_studs + 1):\r\n score = random.randrange(1, 25)\r\n print(f\"INSERT INTO test_score VALUES ({j}, {i}, {score});\")\r\n\r\n\r\ncreate_test_scores(4, 10)\r\n# sqlite> .mode column\r\n# sqlite> .header on\r\n# sqlite> SELECT * FROM test_score;\r\n# student_id test_id score\r\n\r\n\"\"\"\r\nsqlite> .schema test_score\r\nCREATE TABLE test_score(\r\nstudent_id INTEGER NOT NULL,\r\ntest_id INTEGER NOT NULL,\r\nscore INTEGER NOT NULL,\r\nFOREIGN KEY (test_id) REFERENCES test(id),\r\nFOREIGN KEY (student_id) REFERENCES student(id),\r\nPRIMARY KEY (test_id, student_id));\r\n\"\"\"\r\n\r\n# UPDATE test_score\r\n# SET score = -1\r\n# WHERE student_id = 1 AND test_id = 1;\r\n#\r\n# UPDATE test_score\r\n# SET score = -1\r\n# WHERE student_id = 2 AND test_id = 1;\r\n#\r\n# UPDATE test_score\r\n# SET score = -1\r\n# WHERE student_id = 3 AND test_id = 1;\r\n\r\n\r\n\r\n# .schema absence\r\n# INSERT INTO absence\r\n# VALUES(1, '2018-10-1');\r\n#\r\n# INSERT INTO absence\r\n# VALUES(2, '2018-10-1');\r\n#\r\n# INSERT INTO absence\r\n# VALUES(3, '2018-10-1');\r\n#\r\n# SELECT * FROM absence;","sub_path":"bootcam_banas/py_sqlite3/pythontut32.py","file_name":"pythontut32.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284767624","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# pylint: disable= no-member, invalid-name\n\"\"\"Definition of grads of mxnet core functions\"\"\"\nfrom __future__ import absolute_import\n\nimport operator\nimport mxnet\nfrom mxnet import ndarray\nfrom mxnet.ndarray import NDArray\nfrom . import mxnet_wrapper\n\n\ndef _unbroadcast(ans, x, gradfun):\n \"\"\" Append the gradient function with an unbroadcast function \"\"\"\n #pylint: disable= missing-docstring\n if isinstance(ans, NDArray) and isinstance(x, NDArray):\n padded_shape = (1,) * (len(ans.shape) - len(x.shape)) + x.shape\n def newgradfun(g):\n gg = gradfun(g)\n for axis, (i, j) in enumerate(zip(g.shape, padded_shape)):\n if i != j:\n gg = ndarray.sum(gg, axis=axis, keepdims=True)\n if gg.shape != x.shape:\n gg = gg.reshape(x.shape)\n return gg\n return newgradfun\n elif isinstance(ans, NDArray): # x is numerical value\n def newgradfun(g):\n gg = gradfun(g)\n return ndarray.sum(gg)\n else: # both ans and x are numerical value\n return gradfun\n #pylint: enable= missing-docstring\n\ndef _sum_grad(ans, x, axis=None, keepdims=False):\n \"\"\" Generate gradient function of sum \"\"\"\n if axis is None:\n def grad(g):\n if isinstance(g, float) or isinstance(g, int):\n return ndarray.full(x.shape, g, x.context)\n else:\n return ndarray.full(x.shape, g.asscalar(), x.context)\n return grad\n if isinstance(axis, int):\n axis = [axis]\n elif isinstance(axis, tuple):\n axis = list(axis)\n ans_shape_expanded = list(x.shape)\n for a in axis:\n ans_shape_expanded[a] = 1\n xshape = x.shape # Only shape is needed, hope array `x` could be GC'ed.\n return lambda g: ndarray.zeros(xshape, ctx=g.context) + g.reshape(tuple(ans_shape_expanded))\n\n################################################################\n# Functions exposed for primitive & gradient registry\ndef register_primitives(reg, prim_wrapper):\n \"\"\" Register primitives in mxnet package \"\"\"\n mxnet_wrapper.wrap_namespace(mxnet.ndarray.__dict__, reg, prim_wrapper)\n # Additional primitives due to naming issues in MXNet.\n reg.register('reshape', prim_wrapper(NDArray.reshape))\n\ndef def_grads(reg, prims):\n \"\"\" Define gradient function for primitives \"\"\"\n identity = lambda x: x\n # dot\n prims('dot').def_grad(lambda ans, a, b: lambda g: ndarray.dot(g, b.T))\n prims('dot').def_grad(lambda ans, a, b: lambda g: ndarray.dot(a.T, g),\n argnum=1)\n # non-linear\n #prims.tanh.def_grad(lambda ans, x: lambda g: g / np.cosh(x) ** 2)\n prims('exp').def_grad(lambda ans, x: lambda g: g * ans)\n prims('log').def_grad(lambda ans, x: lambda g: g / x)\n # reduce\n prims('sum').def_grad(_sum_grad)\n # + - * /\n prims('multiply').def_grad(\n lambda ans, x, y: _unbroadcast(ans, x, lambda g: g * y))\n prims('multiply').def_grad(\n lambda ans, x, y: _unbroadcast(ans, y, lambda g: x * g),\n argnum=1)\n prims('add').def_grad(lambda ans, x, y: _unbroadcast(ans, x, identity))\n prims('add').def_grad(lambda ans, x, y: _unbroadcast(ans, y, identity),\n argnum=1)\n prims('subtract').def_grad(lambda ans, x, y: _unbroadcast(ans, x, identity))\n prims('subtract').def_grad(\n lambda ans, x, y: _unbroadcast(ans, y, operator.neg),\n argnum=1)\n prims('divide').def_grad(\n lambda ans, x, y: _unbroadcast(ans, x, lambda g: g / y))\n prims('divide').def_grad(\n lambda ans, x, y: _unbroadcast(ans, y, lambda g: -g * x / (y * y)),\n argnum=1)\n prims('true_divide').def_grad(\n lambda ans, x, y: _unbroadcast(ans, x, lambda g: g / y))\n prims('true_divide').def_grad(\n lambda ans, x, y: _unbroadcast(ans, y, lambda g: -g * x / (y * y)),\n argnum=1)\n # mod\n #prims.mod.def_grad(lambda ans, x, y : _unbroadcast(ans, x, identity))\n #prims.mod.def_grad(\n #lambda ans, x, y : _unbroadcast(ans, y, lambda g : - g * ndarray.floor(x/y)), argnum=1)\n # negate\n prims('negative').def_grad(lambda ans, x: operator.neg)\n prims('transpose').def_grad(lambda ans, x: mxnet.nd.transpose)\n prims('abs').def_grad(lambda ans, x: lambda g: mxnet.nd.sign(x) * g)\n prims('sign').def_grad_zero()\n prims('round').def_grad_zero()\n prims('ceil').def_grad_zero()\n prims('floor').def_grad_zero()\n prims('sqrt').def_grad(lambda ans, x: lambda g: g * 0.5 / mxnet.nd.sqrt(x))\n prims('sin').def_grad(lambda ans, x: lambda g: g * mxnet.nd.cos(x))\n prims('cos').def_grad(lambda ans, x: lambda g: -g * mxnet.nd.sin(x))\n prims('power').def_grad(\n lambda ans, x, y: _unbroadcast(ans, x, lambda g: g * y * mxnet.nd.power(x, y - 1)))\n prims('power').def_grad(\n lambda ans, x, y: _unbroadcast(ans, y, lambda g: g * mxnet.nd.log(x) * ans),\n argnum=1)\n prims('reshape').def_grad(\n lambda _0, x, _1: lambda g: NDArray.reshape(g, x.shape))\n prims('expand_dims').def_grad(\n lambda ans, x, axis: lambda g: NDArray.reshape(g, x.shape)\n )\n","sub_path":"minpy/array_variants/mxnet/mxnet_core.py","file_name":"mxnet_core.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"26885983","text":"# !python3\n# -*- coding:utf-8 -*-\n\nimport webbrowser as wbr\nimport requests as rq\nimport re\n\n# 下载基金页面代码,并保存为txt。xq-兴全轻资产,hs-华商优势行业\nres_xq = rq.get('http://fund.eastmoney.com/163412.html')\nplayFile_xq = open('fund_xq.txt', 'wb')\nfor chunk_xq in res_xq.iter_content(100000):\n playFile_xq.write(chunk_xq)\n\nplayFile_xq.close\n\n## 华商代码,同上\nres_hs = rq.get('http://fund.eastmoney.com/000390.html')\nplayFile_hs = open('fund_hs.txt', 'wb')\nfor chunk_hs in res_hs.iter_content(100000):\n playFile_hs.write(chunk_hs)\n\nplayFile_hs.close \n\n\n# 在txt中用正则表达式查找html代码中的相关语句\nhtmlCode_xq = open('fund_xq.txt', 'r')\ncontent_xq = htmlCode_xq.read(int(200000))\n\nfundValueRegex = re.compile(r'id=\"gz_gsz\">\\d\\.\\d\\d\\d\\d')\nmatchList_xq = fundValueRegex.findall(content_xq)\n\n## 华商代码,同上\nhtmlCode_hs = open('fund_hs.txt', 'r')\ncontent_hs = htmlCode_hs.read(int(200000))\n\nfundValueRegex = re.compile(r'id=\"gz_gsz\">\\d\\.\\d\\d\\d\\d')\nmatchList_hs = fundValueRegex.findall(content_hs)\n\n# 将匹配到的List,转换成String\nmatchString_xq = ''.join(matchList_xq)\n\n## 华商代码,同上\nmatchString_hs = ''.join(matchList_hs)\n\n# 对匹配结果进行二次处理,从中提取数字\nnumRegex = re.compile(r'\\d\\.\\d\\d\\d\\d')\nfundValueList_xq = numRegex.findall(matchString_xq)\nfundValue_xq = ''.join(fundValueList_xq)\n\n## 华商代码,同上\nfundValueList_hs = numRegex.findall(matchString_hs)\nfundValue_hs = ''.join(fundValueList_hs)\n\nprint('兴全轻资产 每份额净值 :' + fundValue_xq)\nprint('华商优势行业 每份额净值 :' + fundValue_hs)\n\ntotal = float(fundValue_xq) * 100940.38 + float(fundValue_hs) * 220322.65\n\nprint('持仓总额 : ' + str(round(total, 2)))\n\nif total < 500000:\n print('亏损:' + str(round(total - 500000, 2)))\nelse:\n print('盈利:' + str(round(total - 500000, 2)))\n","sub_path":"fund/fund.py","file_name":"fund.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415827672","text":"# opticalmodel_protons\n# Functions for proton optical models\n# =============================================================================================== #\n# Patrick MacGregor\n# Nuclear Physics Research Group\n# School of Physics and Astronomy\n# The University of Manchester\n# =============================================================================================== #\nfrom opticalmodel_globals import *\nimport numpy as np\n\n# Define optical model dictionary\nproton_dct = {\n\t\"BG\": [0,1],\n\t\"KD\": [1,2],\n\t\"M\": [2,3],\n\t\"P\": [3,4],\n\t\"V\": [4,5],\n\t\"len\": 5,\n\t\"ALL-P\": [0,5]\n}\n\n# Return the names of the proton potentials alphabetically\ndef ProtonModelNumber():\n\treturn [ \"BecchettiGreenlees\", \"KoningDelaroche\", \"Menet\", \"Perey\", \"Varner\" ]\n\n# =============================================================================================== #\n# Koning-Delaroche set\ndef KoningDelaroche(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H):\n\t# CHECK VALUE OF H\n\tCheckP(H)\n\n\t# CALCULATE TRIVIAL PARAMETERS\n\t[N, Q, E] = CalcTrivials(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H)\n\t\n\t\t\n\t# Calculate more involved parameters\n\tvp1 = 59.3 + 21*float((N-Z))/float(A) - 0.024*A\n\tvp2 = 0.007067 + (4.23e-6)*A\n\tvp3 = (1.729e-5) + (1.136e-8)*A\n\tvp4 = 7e-9\n\t\n\twp1 = 14.667 + 0.009629*A\n\twp2 = 73.55 + 0.0795*A\n\t\n\tdp1 = 16*(1 + float(N-Z)/float(A))\n\tdp2 = 0.018 + 0.003802/( 1 + np.exp( (A - 156)/8 ) )\n\tdp3 = 11.5\n\t\n\tvpso1 = 5.922 + 0.0030*A\n\tvpso2 = 0.0040\n\t\n\twpso1 = -3.1\n\twpso2 = 160\n\t\n\tepf = -8.4075 + 0.01378*A\n\trc = 1.198 + 0.697*(A**(-2.0/3.0)) + 12.994*(A**(-5.0/3.0))\n\t\n\tvc = 1.73*Z*(A**(-1.0/3.0))/rc\n\t\n\t# Calculate final parameters\n\tv = vp1*( 1 - (vp2*(E - epf)) + (vp3*((E-epf)**2)) - (vp4*((E-epf)**3)) ) + ( vc*vp1*( vp2 - (2*vp3*(E-epf)) + (3*vp4*((E-epf)**2)) ) )\n\tvi = wp1*((E-epf)**2)/(((E-epf)**2) + (wp2**2))\n\tvsi = dp1*((E-epf)**2)/(((E-epf)**2) + (dp3**2))*np.exp( -dp2*(E-epf) )\n\tvso = vpso1*np.exp( -vpso2*(E-epf) )\n\tvsoi = wpso1*((E-epf)**2)/(((E-epf)**2) + (wpso2**2))\n\t\n\tr0 = 1.3039 - 0.4054*(A**(-1.0/3.0))\n\tri0 = r0\n\trsi0 = 1.3424 - 0.01585*(A**(1.0/3.0))\n\trso0 = 1.1854 - 0.647*(A**(-1.0/3.0))\n\trsoi0 = rso0\n\t\n\ta = 0.6778 - 0.0001487*A\n\tai = a\n\tasi = 0.5187 + 0.0005205*A\n\taso = 0.59\n\tasoi = aso\n\t\n\trc0 = rc\n\t\n\t# Format final paramaters into a list of strings\n\tv_list = [v, vi, vsi, vso, vsoi]\n\tr_list = [r0, ri0, rsi0, rso0, rsoi0]\n\ta_list = [a, ai, asi, aso, asoi]\n\tstring_list = MakeStringList(v_list,r_list,a_list,rc0)\n\t\n\tif PRINT == 1:\n\t\tPrintOpticalModel(string_list, \"Koning and Delaroche \")\n\t\tPrintCalculatedQuantities(A,Z,E,Q)\n\t\tprint(DIV)\n\t\tprint(\"vp1\" + sep + str(vp1))\n\t\tprint(\"vp2\" + sep+ str(vp2))\n\t\tprint(\"vp3\" + sep + str(vp3))\n\t\tprint(\"vp4\" + sep + str(vp4))\n\t\tprint(div)\n\t\tprint(\"wp1\" + sep + str(wp1))\n\t\tprint(\"wp2\" + sep + str(wp2))\n\t\tprint(\"dp1\" + sep + str(dp1))\n\t\tprint(\"dp2\" + sep + str(dp2))\n\t\tprint(\"dp3\" + sep + str(dp3))\n\t\tprint(div)\n\t\tprint(\"vpso1\" + sep + str(vpso1))\n\t\tprint(\"vpso2\" + sep + str(vpso2))\n\t\tprint(\"wpso1\" + sep + str(wpso1))\n\t\tprint(\"wpso2\" + sep + str(wpso2))\n\t\tprint(div)\n\t\tprint(\"epf\" + sep + str(epf))\n\t\tprint(\"rc\" + sep + str(rc))\n\t\tprint(\"vc\" + sep + str(vc))\n\t\tprint(DIV)\n\n\treturn string_list\n\n# =============================================================================================== #\n# Perey (protons)\ndef Perey(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H):\n\t# CHECK VALUE OF H\n\tCheckP(H)\n\n\t# CALCULATE TRIVIAL PARAMETERS\n\t[N, Q, E] = CalcTrivials(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H)\n\t\n\t# Calculate final parameters\n\tv = 53.3 - 0.55*Ebeam + 27.0*(N - Z)/A + 0.4*Z*(A**(-1.0/3.0))\n\tvi = 0.0\n\tvsi = 13.5\n\tvso = 7.5\n\tvsoi = 0.0\n\t\n\tr0 = 1.25\n\tri0 = 0.0\n\trsi0 = 1.25\n\trso0 = 1.25\n\trsoi0 = 0.0\n\t\n\ta = 0.65\n\tai = 0.0\n\tasi = 0.47\n\taso = 0.47\n\tasoi = 0.0\n\t\n\trc0 = 1.25\n\t\n\t# Format final paramaters into a list of strings\n\tv_list = [v, vi, vsi, vso, vsoi]\n\tr_list = [r0, ri0, rsi0, rso0, rsoi0]\n\ta_list = [a, ai, asi, aso, asoi]\n\tstring_list = MakeStringList(v_list,r_list,a_list,rc0)\n\t\n\tif PRINT == 1:\n\t\tPrintOpticalModel(string_list, \"Perey proton\")\n\t\tPrintCalculatedQuantities(A,Z,E,Q)\n\treturn string_list\n\n# =============================================================================================== #\n# Menet (protons)\ndef Menet(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H):\n\t# CHECK VALUE OF H\n\tCheckP(H)\n\n\t# CALCULATE TRIVIAL PARAMETERS\n\t[N, Q, E] = CalcTrivials(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H)\n\t\n\t# Calculate final parameters\n\tv = 49.9 - 0.22*E + 26.4*( N - Z )/A + 0.4*Z*( A**(-1.0/3.0) )\n\tvi = 1.2 + 0.09*E\n\tvsi = 4.2 - 0.05*E + 15.5*( N - Z )/A\n\tvso = 6.04\n\tvsoi = 0.0\n\t\n\tr0 = 1.16\n\tri0 = 1.37\n\trsi0 = 1.37\n\trso0 = 1.064\n\trsoi0 = 0.0\n\t\n\ta = 0.75\n\tai = 0.74 - 0.008*E + float( N - Z )/float(A)\n\tasi = 0.74 - 0.008*E + float( N - Z )/float(A)\n\taso = 0.78\n\tasoi = 00\n\t\n\trc0 = 1.25\n\t\n\t# Format final paramaters into a list of strings\n\tv_list = [v, vi, vsi, vso, vsoi]\n\tr_list = [r0, ri0, rsi0, rso0, rsoi0]\n\ta_list = [a, ai, asi, aso, asoi]\n\tstring_list = MakeStringList(v_list,r_list,a_list,rc0)\n\t\n\tif PRINT == 1:\n\t\tPrintOpticalModel(string_list, \"Menet proton\")\n\t\tPrintCalculatedQuantities(A,Z,E,Q)\n\treturn string_list\n\n # =============================================================================================== #\n# Varner (protons)\ndef Varner(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H):\n\t# CHECK VALUE OF H\n\tCheckP(H)\n\n\t# CALCULATE TRIVIAL PARAMETERS\n\t[N, Q, E] = CalcTrivials(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H)\n\n\t# Calculate final parameters\n\trc1 = 1.24*(A**(1.0/3.0) ) + 0.12\n\tec = 1.73*Z/rc1\n\teta = float(N - Z)/float(A) \n\n\tv = 52.9 + (13.1*float(N - Z)/float(A) ) + ( -0.299*( E - ec) )\n\tvi = 7.8/( 1 + np.exp( ( 35 - ( E - ec ) )/16.0 ) )\n\tvsi = ( 10 + ( 18.0*float(N - Z)/float(A) ) )/( 1 + np.exp( ( E - ec - 36.0 )/37.0 ) )\n\tvso = 5.9\n\tvsoi = 0.0\n\t\n\tr0 = ( ( 1.25*( A**(1.0/3.0) ) ) - 0.225 )*( A**(-1.0/3.0) )\n\tri0 = ( ( 1.33*( A**(1.0/3.0) ) ) - 0.42 )*( A**(-1.0/3.0) )\n\trsi0 = ( ( 1.33*( A**(1.0/3.0) ) ) - 0.42 )*( A**(-1.0/3.0) )\n\trso0 = ( ( 1.34*( A**(1.0/3.0) ) ) - 1.2 )*( A**(-1.0/3.0) )\n\trsoi0 = 0.0\n\t\n\ta = 0.69\n\tai = 0.69\n\tasi = 0.69\n\taso = 0.63\n\tasoi = 0.0\n\n\trc0 = rc1*( A**(-1.0/3.0) )\n\t\n\t\n\t\n\t# Format final paramaters into a list of strings\n\tv_list = [v, vi, vsi, vso, vsoi]\n\tr_list = [r0, ri0, rsi0, rso0, rsoi0]\n\ta_list = [a, ai, asi, aso, asoi]\n\tstring_list = MakeStringList(v_list,r_list,a_list,rc0)\n\t\n\tif PRINT == 1:\n\t\tPrintOpticalModel(string_list, \"Varner proton\")\n\t\tPrintCalculatedQuantities(A,Z,E,Q)\n\t\tprint( \"ec\\t\" + str(ec) )\n\t\tprint( \"eta\\t\" + str(eta) )\n\treturn string_list\n\n# =============================================================================================== #\n# Becchetti and Greenlees (protons)\ndef BecchettiGreenlees(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H):\n\t# CHECK VALUE OF H\n\tCheckP(H)\n\n\t# CALCULATE TRIVIAL PARAMETERS\n\t[N, Q, E] = CalcTrivials(A, Z, Ebeam, Ex, M_Target, M_Projectile, M_Ejectile, M_Product, H)\n\t\n\t# Calculate final parameters\n\tv = 54.0 - 0.32*E + 0.4*Z*( A**(-1.0/3.0) ) + 24.0*( N - Z )/A\n\tvi = 0.22*E - 2.7 if 0.22*E - 2.7 > 0.0 else 0.0\n\tvsi = 11.8 - 0.25*E + 12.0*( N - Z )/A if 11.8 - 0.25*E + 12.0*( N - Z )/A > 0.0 else 0.0\n\tvso = 6.2\n\tvsoi = 0.0\n\t\n\tr0 = 1.17\n\tri0 = 1.32\n\trsi0 = 1.32\n\trso0 = 1.01\n\trsoi0 = 0.0\n\t\n\ta = 0.75\n\tai = 0.51 + 0.7*( N - Z )/A\n\tasi = 0.51 + 0.7*( N - Z )/A\n\taso = 0.75\n\tasoi = 0.0\n\t\n\trc0 = 1.3\n\t\n\t# Format final paramaters into a list of strings\n\tv_list = [v, vi, vsi, vso, vsoi]\n\tr_list = [r0, ri0, rsi0, rso0, rsoi0]\n\ta_list = [a, ai, asi, aso, asoi]\n\tstring_list = MakeStringList(v_list,r_list,a_list,rc0)\n\t\n\tif PRINT == 1:\n\t\tPrintOpticalModel(string_list, \"Becchetti and Greenlees proton\")\n\t\tPrintCalculatedQuantities(A,Z,E,Q)\n\treturn string_list\n\n# 124Te(p,d), Ebeam=15MeV, Ex=0MeV\n#PRINT = 1\n#BecchettiGreenlees(124, 52, 15, 0, 123.9028179, 1.00782503224, 2.01410177811, 122.9042698, 0)\n\n","sub_path":"ptolemy_energy_comparison/ptolemy/opticalmodel_protons.py","file_name":"opticalmodel_protons.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"579449033","text":"__version__=\"0.1.0.1\"\n__usage__=\"\"\"\n _______ __ __ __ _ _______ __ __ ______ __ _ __ __ \n| || | | || | | || || | | || | | | | || |_| |\n| _____|| |_| || |_| ||_ _|| |_| || _ || |_| || |\n| |_____ | || | | | | || | | || || |\n|_____ ||_ _|| _ | | | | || |_| || _ || |\n _____| | | | | | | | | | | _ || || | | || ||_|| |\n|_______| |___| |_| |__| |___| |__| |__||______| |_| |__||_| |_|\n\n\nVersion {} Authors: Danny Antaki, Aojie Lian, James Guevara \n Contact: j3guevar@ucsd.health.edu\n---------------------------------------------------------------------------------\n synthdnm -f -v [-oLgkVh]\n \nnecessary arguments:\n \n -v, -vcf PATH VCF file\n -f, -fam PATH PLINK pedigree (.fam/.ped) file\n \noptional arguments:\n\n -g --gen STR human reference genome version [default: hg38]\n \n -h, --help show this message and exit\n \n\"\"\".format(__version__)\n\ndef run():\n import argparse\n \n parser = argparse.ArgumentParser(usage=__usage__)\n \n # Necessary arguments\n parser.add_argument(\"-v\",\"--vcf\",required=True)\n parser.add_argument(\"-f\",\"--fam\",required=True)\n # Optional arguments\n parser.add_argument(\"-g\",\"--gen\",required=False,default=\"hg38\",choices=[\"hg19\",\"hg38\"])\n parser.add_argument(\"-i\",\"--info\",required=False)\n args = parser.parse_args()\n \n vcf_filepath = args.vcf\n fam_filepath = args.fam\n gen = args.gen\n \n info_keys = []\n if args.info: \n f = open(args.info,\"r\")\n for line in f:\n info_keys.append(line.rstrip()) \n else: info_keys = [\"VQSLOD\",\"ClippingRankSum\",\"BaseQRankSum\",\"FS\",\"SOR\",\"MQ\",\"MQRankSum\",\"QD\",\"ReadPosRankSum\"]\n \n from vcf import parse\n parse(vcf_filepath, fam_filepath, info_keys=info_keys)\n\nif __name__==\"__main__\":\n run()\n\n\n","sub_path":"tests/build/lib/synthdnm/synthdnm.py","file_name":"synthdnm.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101211060","text":"from constants import *\n\n\nclass Wall:\n \"\"\"\n A class to define a wall or an obstacle and manage collisions\n \"\"\"\n\n def __init__(self, x, y, width, height):\n self.pos = (x, y)\n self.height = height\n self.width = width\n\n def get_constraint(self, entity, direction):\n \"\"\"\n Method to check if the player is touching a wall or not\n \"\"\"\n px, py = entity.pos\n pw, ph = entity.size\n wx, wy = self.pos\n ww = self.width\n wh = self.height\n\n if direction == DOWN:\n if px + pw <= wx or px >= wx + ww: # no collision\n return None\n if py + ph >= wy > py:\n return wy - ph\n\n if direction == RIGHT:\n if py + ph <= wy or py >= wy + wh: # no collision\n return None\n if px + pw >= wx > px:\n return wx - pw\n\n if direction == UP:\n if px + pw <= wx or px >= wx + ww: # no collision\n return None\n if py <= wy + wh < py + ph:\n return wy + wh\n\n if direction == LEFT:\n if py + ph <= wy or py >= wy + wh: # no collision\n return None\n if px <= wx + ww < px + pw:\n return wx + ww\n\n return None\n","sub_path":"core/Wall.py","file_name":"Wall.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"128651723","text":"import os\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\n\n\ndef calculate_cluster_centers(feature_dir, feature, nb_centers, nb_feat, output_dir=None, nb_jobs=8):\n feates = os.listdir(feature_dir)\n # feat_idxes = []\n ffs = set()\n for f in feates:\n f_dir = f.split('_')[0] + '_' + feature + '_resnet.npy'\n if os.path.exists(feature_dir + '/' + f_dir):\n ffs.add(f_dir)\n if len(ffs) == nb_feat:\n break\n\n feat_sum = []\n for f in ffs:\n cur_feat = np.load(feature_dir + '/' + f)\n cur_feat = cur_feat.reshape((-1, cur_feat.shape[-1]))\n feat_sum.append(cur_feat)\n feat_sum = np.concatenate(feat_sum)\n print(feat_sum.shape)\n\n print('start kmeans')\n kmeans = KMeans(nb_centers, n_jobs=nb_jobs)\n kmeans.fit(feat_sum)\n print('kmeans finishes')\n\n if output_dir is not None:\n path = output_dir\n else:\n path = feature_dir + '/kmeans_' + str(nb_centers) + '.npy'\n np.save(path, kmeans.cluster_centers_)\n","sub_path":"util/Kmeans.py","file_name":"Kmeans.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"433317554","text":"# PROPRIETARY AND CONFIDENTIAL\r\n# Property of Blackbird Logical Applications, LLC\r\n# Copyright Blackbird Logical Applications, LLC 2016\r\n# NOT TO BE CIRCULATED OR REPRODUCED WITHOUT PRIOR WRITTEN APPROVAL\r\n\r\n#Blackbird Engine\r\n#Module: tools.for_tag_operations\r\n\r\n\"\"\"\r\n\r\nModule includes convenience functions for identifying objects based on the tags\r\nthey carry.\r\n==================== ==========================================================\r\nAttribute Description\r\n==================== ==========================================================\r\n\r\nDATA:\r\nn/a\r\n\r\nFUNCTIONS:\r\nbuild_basic_profile() return a set of target tags, used as simple criteria\r\nbuild_combo_profile() return a set of tags from target and model\r\nget_tagged() return objects from container that have specified tags\r\n\r\nCLASSES:\r\nn/a\r\n==================== ==========================================================\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n# imports\r\n# n/a\r\n\r\n\r\n\r\n\r\n# globals\r\n# n/a\r\n\r\n# functions\r\ndef build_basic_profile(target):\r\n \"\"\"\r\n\r\n\r\n build_basic_profile(target) -> set()\r\n\r\n\r\n Return set of all tags on target, with None stripped out.\r\n \"\"\"\r\n try:\r\n criteria = target.tags.all | {target.tags.name}\r\n except AttributeError:\r\n raise\r\n\r\n criteria = set(c.casefold() for c in criteria if c)\r\n\r\n return criteria\r\n\r\n\r\ndef build_combo_profile(target, model):\r\n \"\"\"\r\n\r\n\r\n build_combo_criteria(target, model) -> set()\r\n\r\n\r\n Return the set of all tags found on target, target's parent, target's\r\n grandparent, and the model.\r\n\r\n When target is a LineItem, target's parent will usually be a line or a\r\n Financials object and its grandparent will usually be a line, Financials\r\n object, or a BusinessUnit.\r\n \"\"\"\r\n\r\n parent_rels = getattr(target, \"relationships\", None)\r\n parent = getattr(parent_rels, \"parent\", None)\r\n\r\n grandpa_rels = getattr(parent, \"relationships\", None)\r\n grandpa = getattr(grandpa_rels, \"parent\", None)\r\n\r\n parent_tags = getattr(parent, \"tags\", None)\r\n parent_name = getattr(parent_tags, \"name\", None)\r\n tags_up_one = getattr(parent_tags, \"all\", set())\r\n if parent_name:\r\n tags_up_one.add(parent_name)\r\n\r\n grandpa_tags = getattr(grandpa, \"tags\", None)\r\n grandpa_name = getattr(grandpa_tags, \"name\", None)\r\n tags_up_two = getattr(grandpa_tags, \"all\", set())\r\n if grandpa_name:\r\n tags_up_two.add(grandpa_name)\r\n\r\n criteria = target.tags.all | {target.tags.name}\r\n\r\n try:\r\n path_tags = model.target.stage.path.tags.all\r\n except AttributeError:\r\n path_tags = set()\r\n\r\n criteria = criteria | tags_up_one | tags_up_two | path_tags\r\n criteria = criteria | set(model.tags.all) | {model.tags.name}\r\n criteria = set(c.casefold() for c in criteria if c)\r\n\r\n return criteria\r\n\r\n\r\ndef get_tagged(container, *tags, catch_blank_ids=True):\r\n \"\"\"\r\n\r\n\r\n get_tagged(container, *tags) -> dict()\r\n\r\n\r\n Return an {bbid:obj} dict of objects that have each of the specified tags.\r\n\r\n Container must be an iterable. If ``catch_blank_ids`` is True, function will\r\n store all matching objects that are missing a bbid in a set at the None key.\r\n\r\n NOTE: Function evaluates ``tags`` as a set, so it will not differentiate\r\n between objects that carry that tag once and those that do so more than\r\n once.\r\n \"\"\"\r\n criterion = set(tags)\r\n result = dict()\r\n for obj in container:\r\n obj_profile = build_basic_profile(obj)\r\n missing = criterion - obj_profile\r\n if missing:\r\n continue\r\n else:\r\n try:\r\n k = obj.id.bbid\r\n result[k] = obj\r\n except AttributeError:\r\n # easier to catch missing error than two layers of getattr\r\n # or use some inspect function.\r\n if catch_blank_ids:\r\n blanks = result.setdefault(None, set())\r\n # if None is already a key, pull its set, otherwise add\r\n # None as a key with an empty set\r\n blanks.add(obj)\r\n\r\n return result\r\n\r\n\r\ndef get_product_names(model, question):\r\n pass\r\n # should be in interview tools\r\n # return a list of product names, top to bottom by size, that fits\r\n # the input_element array; only runs when model is tagged \"real names\"\r\n","sub_path":"tools/for_tag_operations.py","file_name":"for_tag_operations.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22748317","text":"#coding=utf-8\nfrom django.conf.urls.defaults import *\nfrom django.conf import settings\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^site_media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_SITE}),\n (r'^theme_media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.THEME_SITE}),\n (r'^upload_media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n)\n#首页\nurlpatterns += patterns('myblog.views',\n (r'^$', 'index'), \n)\n\n#注册、登录\nurlpatterns += patterns('account.views',\n (r'^account/register/$', 'register'), #注册\n (r'^account/register_check/$','register_check'), #检测 \n (r'^account/login/$', 'login'), #登录\n (r'^account/loginout/$','loginout_view'), #注销 \n)\n\n#网站后台\nurlpatterns += patterns('',\n (r'^admin/',include('admin.urls')), #后台管理\n (r'^article/',include('myblog.urls')),#博客 \n)\n","sub_path":"ldj17/golden_urls.py","file_name":"golden_urls.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137598788","text":"import math\nimport time\nfrom collections import deque\nfrom random import randint\n\nimport cv2\nimport numpy as np\n\n\nclass GameObject(object):\n def __init__(self, image_path, name='??', resize=1.0):\n self.name = name\n self.image = self.load_image(image_path=image_path, resize=resize)\n self.center = (0.0, 0.0) # x, y\n self.dx = 0.0\n self.dy = 0.0\n self.direction = dict.fromkeys(['up', 'down', 'left', 'right'], False)\n self.following_green = True\n self.legacy_dx = 0.0\n self.legacy_dy = 0.0\n\n def load_image(self, image_path, resize):\n image = cv2.imread(image_path)\n image = cv2.resize(image, (int(resize * image.shape[0]), int(resize * image.shape[1])))\n return image\n\n def collide(self, point):\n if point[0] - 50 < self.center[0] < point[0] + 50 and point[1] - 50 < self.center[1] < point[1] + 50:\n return True\n return False\n\n\nclass Game(object):\n def __init__(self):\n self.frame = None\n self.start_time = time.time()\n self.cur_time = time.time()\n self.game_state = 'select_object'\n self.game_object = None\n self.hand_region = None\n self.num_fingers = []\n self.time_with_object = 0.0\n self.time_end_phase = 0.0\n self.points = deque(maxlen=32)\n self.target_spawned = False\n self.target_img = None\n self.target_x = 0.0\n self.target_y = 0.0\n self.player_points = 0\n self.has_written_to_high = False\n self.red_box_width = 80\n\n def play(self, camera):\n faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n noseCascade = cv2.CascadeClassifier('haarcascade_mcs_nose.xml')\n imgMustache = cv2.imread('mustache_temp/mustache.png', -1)\n orig_mask, orig_mask_inv, imgMustache, origMustacheHeight, origMustacheWidth = self.mustache_setup(imgMustache)\n\n while camera.isOpened():\n _, self.frame = camera.read()\n\n # to show game timer in top-right corner\n self.cur_time = time.time()\n time_elapsed = self.cur_time - self.start_time\n\n # resize and flip the self.frame, blur it, and convert it to the HSV color space\n # self.frame = imutils.resize(self.frame, width=1000)\n self.frame = cv2.flip(self.frame, 1)\n # cv2.putText(self.frame, str(int(time_elapsed)), (950, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))\n cv2.putText(self.frame, \"Points: \" + str(int(self.player_points)), (900, 700), cv2.FONT_HERSHEY_SIMPLEX, 2,\n (71, 247, 226))\n self.hand_region = self.frame[100:400, 100:400]\n\n if self.player_points == 5:\n imgMustache = cv2.imread('mustache_temp/mustache2.png', -1)\n orig_mask, orig_mask_inv, imgMustache, origMustacheHeight, origMustacheWidth = self.mustache_setup(\n imgMustache)\n elif self.player_points == 3:\n imgMustache = cv2.imread('mustache_temp/mustache1.png', -1)\n orig_mask, orig_mask_inv, imgMustache, origMustacheHeight, origMustacheWidth = self.mustache_setup(\n imgMustache)\n\n self.frame = self.mustache_overlay(self.frame, orig_mask, orig_mask_inv, imgMustache, origMustacheHeight,\n origMustacheWidth, faceCascade, noseCascade)\n\n if self.game_state == 'select_object':\n cv2.rectangle(self.frame, (400, 400), (100, 100), (0, 255, 0), 0) # draws rectangle for gesture area\n self.object_selection_mode()\n if self.game_state == 'transition_after_object_selection' and self.game_object:\n self.transition_after_object_selection(game_object=self.game_object)\n if self.game_state == 'object_selected' and self.game_object:\n self.object_selected_mode(game_object=self.game_object)\n if self.game_state == 'game_over':\n with open(\"high.txt\", \"r+\") as f:\n content = f.readlines()\n f.close()\n\n content = [x.strip() for x in content]\n content = [int(x) for x in content]\n high_score = max(content)\n # print(\"high score: \", high_score)\n if len(content) == 0:\n content.append(0)\n else:\n content.append(self.player_points)\n\n s_to_write = ''\n # use Insertion Sort to sort the mostly sorted txt file and write to txt\n for i in range(1, len(content)):\n currentvalue = content[i]\n pos = i\n while pos > 0 and content[pos - 1] < currentvalue:\n content[pos] = content[pos - 1]\n pos = pos - 1\n content[pos] = currentvalue\n\n for i in range(len(content)):\n s_to_write += str(content[i - 1]) + '\\n'\n end_string = \"\"\n\n if self.player_points > high_score:\n end_string = \"Congrats! You Got The New High Score\"\n elif self.player_points == high_score:\n end_string = \"Congrats! You Tied The High Score\"\n else:\n end_string = \"Well done! High Score was \" + str(high_score)\n\n if not self.has_written_to_high:\n with open(\"high.txt\", \"w\") as myfile:\n myfile.write(s_to_write)\n self.has_written_to_high = True\n self.game_over_mode(end_string)\n self.render()\n k = cv2.waitKey(10)\n if k == 27:\n break\n\n def overlay_image(self, image, center):\n # image = game_object.image\n # performs bound checking before overlaying image\n height = image.shape[0]\n width = image.shape[1]\n temp_y, temp_x = center[1], center[0]\n\n y1 = temp_y - int(height / 2) - (height % 2)\n y2 = temp_y + int(height / 2)\n if y1 < 0:\n y1, y2 = 0, height\n return 'edge'\n elif y2 >= self.frame.shape[0]:\n y1, y2 = self.frame.shape[0] - height, self.frame.shape[0]\n return 'edge'\n x1 = temp_x - int(width / 2) - (width % 2)\n x2 = temp_x + int(width / 2)\n if x1 < 0:\n x1, x2 = 0, width\n return 'edge'\n\n elif x2 >= self.frame.shape[1]:\n x1, x2 = self.frame.shape[1] - width, self.frame.shape[1]\n return 'edge'\n\n self.frame[y1:y2, x1:x2] = image\n\n def select_object(self): # TODO: pass num_defects as parameter for recent_val, don' have to append to list, slow\n num_frames = 30 # number of self.frames that must have detected same gesture (num of fingers) for selection\n if len(self.num_fingers) > num_frames:\n recent = self.num_fingers[-num_frames:]\n recent_val = recent[0]\n # print(recent_val)\n if recent.count(recent_val) == num_frames: # if all recent elements are same\n if 1 <= recent_val <= 4:\n self.game_object = GAME_OBJECTS[recent_val - 1]\n self.target_img = TARGET_IMAGES[recent_val - 1]\n\n def object_selection_mode(self):\n self.game_object = None\n grey = cv2.cvtColor(self.hand_region, cv2.COLOR_BGR2GRAY)\n g_val = int(self.red_box_width / 4)\n if g_val % 2 == 0:\n g_val += 1\n value = (g_val, g_val)\n print(g_val)\n blurred = cv2.GaussianBlur(grey, value, 0)\n _, thresh1 = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n contours = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2]\n\n cnt = max(contours, key=lambda x: cv2.contourArea(x))\n x, y, w, h = cv2.boundingRect(cnt)\n self.red_box_width = w\n cv2.rectangle(self.hand_region, (x, y), (x + w, y + h), (0, 0, 255), 0)\n hull = cv2.convexHull(cnt)\n drawing = np.zeros(self.hand_region.shape, np.uint8)\n cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 0)\n cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 0)\n hull = cv2.convexHull(cnt, returnPoints=False)\n defects = cv2.convexityDefects(cnt, hull)\n count_defects = 0\n cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)\n for i in range(defects.shape[0]):\n s, e, f, d = defects[i, 0]\n start = tuple(cnt[s][0])\n end = tuple(cnt[e][0])\n far = tuple(cnt[f][0])\n a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)\n b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)\n c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)\n angle = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 57\n if angle <= 90:\n count_defects += 1\n cv2.circle(self.hand_region, far, 1, [0, 0, 255], -1)\n cv2.line(self.hand_region, start, end, [0, 255, 0], 2)\n if count_defects == 1:\n cv2.putText(self.frame, '1 finger', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n elif count_defects == 2:\n cv2.putText(self.frame, '2 fingers', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n elif count_defects == 3:\n cv2.putText(self.frame, '3 fingers', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n elif count_defects == 4:\n cv2.putText(self.frame, '4 fingers', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n else:\n cv2.putText(self.frame, 'Unrecognized', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n self.num_fingers.append(count_defects)\n self.select_object()\n if self.game_object:\n self.game_state = 'transition_after_object_selection'\n print(\"switching to \", self.game_state)\n self.time_with_object = time.time()\n self.num_fingers.clear()\n else:\n cv2.putText(self.frame, \"Please hold gesture still\", (200, 500), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 250),\n thickness=2)\n\n # @staticmethod\n # def apply_gravity(point):\n #\n\n def move_object(self, game_object):\n # resize and flip the self.frame, blur it, and convert it to the HSV color space\n # self.frame = imutils.resize(self.frame, width=1200)\n blurred = cv2.GaussianBlur(self.frame, (11, 11), 0) # already blurred in play()\n hsv = cv2.cvtColor(self.frame, cv2.COLOR_BGR2HSV)\n\n # construct a mask for the color 'green', then perform a series of\n # dilations and erosions to remove any small blobs left in the mask\n frame_thresh = cv2.inRange(hsv, GREEN_MIN, GREEN_MAX)\n frame_thresh = cv2.erode(frame_thresh, None, iterations=2)\n frame_thresh = cv2.dilate(frame_thresh, None, iterations=2)\n if game_object.following_green:\n # find contours in the mask and initialize the current\n # (x, y) center of the object\n contours = cv2.findContours(frame_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n if contours:\n # only proceed if at least one contour was found, find the largest\n # contour in the mask and compute the minimum\n contour = max(contours, key=cv2.contourArea)\n ((_, _), radius) = cv2.minEnclosingCircle(contour)\n M = cv2.moments(contour)\n game_object.center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))\n # print(radius)\n if radius > 15:\n # draw cirlce?\n self.points.append(game_object.center)\n # print(self.points)\n # print(len(self.points))\n else:\n # game_object.center += (game_object.legacy_dx/10, game_object.legacy_dy/10)\n old_x = game_object.center[0]\n old_y = game_object.center[1]\n game_object.center = (old_x + int(game_object.legacy_dx / 5), old_y + int(game_object.legacy_dy / 5))\n game_object.legacy_dy += 20\n # print(game_object.center)\n self.points.append(game_object.center)\n for i in range(1, len(self.points)):\n # ignore if either tracked point is None\n if not self.points[i - 1] or not self.points[i]:\n continue\n # check if enough points have been in deque\n num = 2\n if len(self.points) >= num and i == 1 and game_object.following_green:\n if self.points[-num]:\n # compute the difference between the x and y coordinates\n # initialize direction variables\n game_object.dx = self.points[-num][0] - self.points[i][0]\n game_object.dy = self.points[-num][1] - self.points[i][1]\n detect_speed = 170\n velocity = math.sqrt(math.pow(game_object.dx, 2) + math.pow(game_object.dy, 2))\n if velocity > detect_speed:\n game_object.following_green = False\n game_object.legacy_dx = game_object.dx\n game_object.legacy_dy = game_object.dy\n if np.abs(game_object.dx) > detect_speed:\n if np.sign(game_object.dx) == 1:\n game_object.direction['right'] = True\n game_object.direction['left'] = False\n else:\n game_object.direction['left'] = True\n game_object.direction['right'] = False\n if np.abs(game_object.dy) > detect_speed:\n if np.sign(game_object.dy) == 1:\n game_object.direction['down'] = True\n game_object.direction['up'] = False\n else:\n game_object.direction['up'] = True\n game_object.direction['down'] = False\n cv2.putText(self.frame, 'dx: {}, dy: {}'.format(game_object.dx, game_object.dy),\n (10, self.frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX,\n 0.35, (0, 0, 255), 1)\n if len(self.points) > 1:\n possible_edge_hit = self.overlay_image(image=game_object.image, center=self.points[len(self.points) - 1])\n if possible_edge_hit == 'edge':\n game_object.following_green = True\n self.points.clear()\n if game_object.collide((self.target_x, self.target_y)):\n self.player_points += 1\n self.target_spawned = False\n game_object.following_green = True\n self.points.clear()\n # thickness = int(np.sqrt(32 / float(i + 1)) * 2.5)\n # cv2.line(self.frame, self.points[len(self.points) - 1], self.points[len(self.points) - 2], (0, 0, 255), thickness)\n\n def object_selected_mode(self, game_object):\n if self.time_with_object:\n time_allowed_with_object = 60.0\n elapsed_time_with_object = self.cur_time - self.time_with_object\n time_left = int(time_allowed_with_object - elapsed_time_with_object)\n cv2.putText(self.frame, str(int(time_left)), (1200, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255))\n if not self.target_spawned:\n self.target_x, self.target_y = self.spawn_target(self.target_img) # spawn target img\n self.target_spawned = True\n else:\n self.overlay_image(self.target_img, (self.target_x, self.target_y)) # keep target img\n self.move_object(game_object=game_object)\n # print(self.game_object.dx)\n if elapsed_time_with_object > time_allowed_with_object:\n self.time_with_object = 0.0\n self.game_state = 'game_over'\n self.game_object = None\n print(\"switching to \", self.game_state)\n self.time_end_phase = time.time()\n else:\n raise ValueError\n\n def transition_after_object_selection(self, game_object):\n if self.time_with_object:\n cv2.putText(self.frame, 'You have chosen: ' + game_object.name, (150, 500), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 0, 0), thickness=4)\n # self.overlay_image(image=game_object.image, center=game_object.center)\n elapsed_time_with_object = self.cur_time - self.time_with_object\n if elapsed_time_with_object > 2:\n self.game_state = 'object_selected'\n print(\"switching to \", self.game_state)\n else:\n raise ValueError\n\n def game_over_mode(self, end_string):\n time_in_end_phase = time.time() - self.time_end_phase\n if time_in_end_phase > 5:\n exit()\n cv2.putText(self.frame, 'Thanks for Playing!', (300, 300), cv2.FONT_HERSHEY_SIMPLEX, 2,\n (255, 0, 0), thickness=3)\n cv2.putText(self.frame, 'Your score was: ' + str(self.player_points), (300, 500), cv2.FONT_HERSHEY_SIMPLEX, 2,\n (0, 0, 255), thickness=3)\n cv2.putText(self.frame, end_string, (250, 650), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (0, 0, 255), thickness=3)\n\n def render(self):\n cv2.imshow('Game Console', self.frame)\n\n def spawn_target(self, target):\n s_x = target.shape[1]\n s_y = target.shape[0]\n max_x = self.frame.shape[1]\n max_y = self.frame.shape[0]\n max_x -= 1.5 * s_x\n max_y -= 1.5 * s_y\n x = randint(int(1.5 * s_x), int(max_x))\n y = randint(int(1.5 * s_x), int(max_y))\n return x, y\n\n # def overlay_img2(self, main_img, s_img, x_offset, y_offset):\n # main_img[y_offset:y_offset + s_img.shape[0], x_offset:x_offset + s_img.shape[1]] = s_img\n\n def mustache_setup(self, imgMustache):\n # Create the mask for the mustache\n orig_mask = imgMustache[:, :, 3]\n\n # Create the inverted mask for the mustache\n orig_mask_inv = cv2.bitwise_not(orig_mask)\n\n # Convert mustache image to BGR\n # and save the original image size (used later when re-sizing the image)\n imgMustache = imgMustache[:, :, 0:3]\n origMustacheHeight, origMustacheWidth = imgMustache.shape[:2]\n\n return orig_mask, orig_mask_inv, imgMustache, origMustacheHeight, origMustacheWidth\n\n def mustache_overlay(self, frame, orig_mask, orig_mask_inv, imgMustache, origMustacheHeight, origMustacheWidth,\n faceCascade, noseCascade):\n\n # Create greyscale image from the video feed\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in input video stream\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE\n )\n\n # Iterate over each face found\n for (x, y, w, h) in faces:\n # Un-comment the next line for debug (draw box around all faces)\n # face = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n\n roi_gray = gray[y:y + h, x:x + w]\n roi_color = frame[y:y + h, x:x + w]\n\n # Detect a nose within the region bounded by each face (the ROI)\n nose = noseCascade.detectMultiScale(roi_gray)\n\n for (nx, ny, nw, nh) in nose:\n # Un-comment the next line for debug (draw box around the nose)\n # cv2.rectangle(roi_color,(nx,ny),(nx+nw,ny+nh),(255,0,0),2)\n\n # The mustache should be three times the width of the nose\n mustacheWidth = 3 * nw\n mustacheHeight = mustacheWidth * origMustacheHeight / origMustacheWidth\n\n # Center the mustache on the bottom of the nose\n x1 = int(nx - (mustacheWidth / 4))\n x2 = int(nx + nw + (mustacheWidth / 4))\n y1 = int(ny + nh - (mustacheHeight / 2))\n y2 = int(ny + nh + (mustacheHeight / 2))\n\n # Check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # Re-calculate the width and height of the mustache image\n mustacheWidth = x2 - x1\n mustacheHeight = y2 - y1\n\n # Re-size the original image and the masks to the mustache sizes\n # calcualted above\n mustache = cv2.resize(imgMustache, (int(mustacheWidth), int(mustacheHeight)),\n interpolation=cv2.INTER_AREA)\n mask = cv2.resize(orig_mask, (int(mustacheWidth), int(mustacheHeight)), interpolation=cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv, (int(mustacheWidth), int(mustacheHeight)),\n interpolation=cv2.INTER_AREA)\n\n # take ROI for mustache from background equal to size of mustache image\n roi = roi_color[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the mustache is not\n # in the region that is the size of the mustache.\n roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n # roi_fg contains the image of the mustache only where the mustache is\n roi_fg = cv2.bitwise_and(mustache, mustache, mask=mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg, roi_fg)\n\n # place the joined image, saved to dst back over the original image\n roi_color[y1:y2, x1:x2] = dst\n\n break\n\n # Display the resulting frame\n return frame\n\n\n# define the lower and upper boundaries of the green object in HSV color space\n# BLACK_MIN = np.array([0, 0, 0], np.uint8)\n# BLACK_MAX = np.array([180, 255, 30], np.uint8)\nGREEN_MIN = np.array([29, 86, 6], np.uint8)\nGREEN_MAX = np.array([64, 255, 255], np.uint8)\nglobal GAME_OBJECTS\nglobal TARGET_IMAGES\n\nif __name__ == '__main__':\n camera = cv2.VideoCapture(0)\n camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1366)\n camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)\n\n basketball = GameObject(image_path='pics/bball.png', name='basketball', resize=0.333)\n cash = GameObject(image_path='pics/cash.png', name='cash', resize=0.125)\n baseball = GameObject(image_path='pics/baseball.png', name='baseball', resize=0.045)\n trash = GameObject(image_path='pics/trash.jpg', name='trash', resize=0.333)\n\n GAME_OBJECTS = [basketball, cash, baseball, trash]\n\n hoop = cv2.imread(\"pics/hoop.jpeg\")\n hoop = cv2.resize(hoop, (int(hoop.shape[0] / 5), int(hoop.shape[1] / 5)))\n barnes = cv2.imread(\"pics/barnes.jpg\")\n barnes = cv2.resize(barnes, (int(barnes.shape[0] / 7), int(barnes.shape[1] / 7)))\n mitt = cv2.imread(\"pics/mitt.jpg\")\n mitt = cv2.resize(mitt, (int(mitt.shape[0] / 2), int(mitt.shape[1] / 2)))\n trash_can = cv2.imread(\"pics/trash_can.jpeg\")\n trash_can = cv2.resize(trash_can, (int(trash_can.shape[0] / 8), int(trash_can.shape[1] / 7)))\n\n TARGET_IMAGES = [hoop, barnes, mitt, trash_can]\n\n game = Game()\n game.play(camera=camera)\n camera.release()\n cv2.destroyAllWindows()\n","sub_path":"hand_motion/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":23749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430750780","text":"from pathlib import Path\n\nimport pytest\n\n\n@pytest.mark.workflow(\"test_chimeric_sam_specific\")\ndef test_dedup_merged_dedup_match(workflow_dir, bam_md5):\n bam_path = workflow_dir / Path(\"test-output/chimeric_sam_specific.bam\")\n bam_md5sum = bam_md5(bam_path)\n assert bam_md5sum == \"7f524c704e9fc1077423fdc09a813e26\"\n","sub_path":"tests/integration/test_chimeric_sam_specific.py","file_name":"test_chimeric_sam_specific.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"89502356","text":"import logging\n\nimport discord\nfrom discord.ext import commands\n\nimport helpers\n\nlogger = logging.getLogger(\"main.onlyphans\")\n\n\nclass OnlyPhans(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n async def cog_check(self, ctx):\n \"\"\"Global check to see if the guild utilizing the commands is the OnlyPhans guild.\"\"\"\n return ctx.guild.id == 733944519640350771\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def eversong(self, ctx):\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/HijmLV8.jpg\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def bagu4k(self, ctx):\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/Wp9aJ4q.png\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def enter(self, ctx):\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/tNSoLk5.png\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def marshiie(self, ctx):\n marshiieID = 142809966749679616\n marshiie = await self.bot.fetch_user(marshiieID)\n\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/UgiwdJV.png\")\n await ctx.send(\n f\"Introducing: the <:ayaya:745792801215610930> Ayaya\"\n f\"{marshiie.mention} Collection™ <:ayaya:745792801215610930>\",\n embed=embed,\n )\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def maniicc(self, ctx):\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/k94JJVU.png\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def kat(self, ctx):\n await ctx.send(content='<:why:745691113939009638>')\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def pusher(self, ctx):\n embed = helpers.makeSimpleImageEmbed(\"https://i.imgur.com/0mHp2wx.png\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def neph(self, ctx):\n embed = helpers.makeSimpleTextEmbed(\" Loading...\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def crab(self, ctx):\n oldNick = ctx.author.nick\n if oldNick is None:\n oldNick = str(ctx.author.name)\n\n crab = \"🦀\"\n newNick = f\"{crab}{oldNick}{crab}\"\n\n try:\n await ctx.author.edit(nick=newNick)\n except Exception as err:\n logger.error(f\"Unknown error occurred when editing nickname! \\n Error: {err}\")\n\n await ctx.send(\"https://media.giphy.com/media/2dK0W3oUksQk0Xz8OK/giphy.gif\")\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def auto(self, ctx):\n def autoMessageCheck(message: discord.Message) -> bool:\n \"\"\"A message check for the auto command.\"\"\"\n validResponses = [\"y\", \"n\", \"yes\", \"no\"]\n return message.author == ctx.author and message.content.lower() in validResponses\n\n counter = 0\n while True:\n if counter == 0:\n textModifier = \"\"\n else:\n textModifier = \"REALLY \" * counter\n\n embed = helpers.makeSimpleTextEmbed(\n f\"Are you {textModifier}sure you want to kick auto? y/n\"\n )\n await ctx.send(embed=embed)\n\n try:\n response = await self.bot.wait_for(\"message\", check=autoMessageCheck, timeout=30)\n except Exception as err:\n print(err)\n embed = helpers.makeSimpleTextEmbed(\n \"Too late. Guess you don't really want to kick auto.\"\n )\n await ctx.send(embed=embed)\n return\n\n if response.content.lower() in [\"no\", \"n\"]:\n embed = helpers.makeSimpleTextEmbed(\"Okay... :(\")\n await ctx.send(embed=embed)\n break\n\n counter += 1\n\n @commands.command()\n @helpers.logCommand(logger=logger)\n async def heck(self, ctx, member: discord.Member):\n if member != self.bot.user:\n embed = helpers.makeSimpleTextEmbed(\n f\"Yeah! Heck {member.mention}! \"\n )\n else:\n embed = helpers.makeSimpleTextEmbed(\n f\"Nah! Heck you instead, {ctx.author.name}! \"\n )\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(OnlyPhans(bot))\n","sub_path":"cogs/guilds/onlyphans.py","file_name":"onlyphans.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191455531","text":"#This algorithm is written to process the heauristics data\n#in Option Object:\n# v = values\n# eq=equal\n# plaus = plausible\n# all statements of similarity are translated into 3 integers:\n# 1 = same\n# 2 = similar\n# 3 = different\n\nfrom collections import defaultdict\nimport weightedstats as ws\n\nclass Data:\n def __init__(self):\n self.value_options = defaultdict(list)\n self.measured_v = []\n self.weights = []\n self.v_eq_plaus = False\n\n def reset(self):\n self.value_options = defaultdict(list)\n self.measured_v = []\n self.weights = []\n self.v_eq_plaus = False\n\n\nclass Options:\n def __init__ (self):\n self.method = \"\"\n self.organism = \"\"\n self.enzyme = \"\"\n self.species = \"\"\n self.condition = \"\"\n def reset(self):\n self.method = \"\"\n self.organism = \"\"\n self.enzyme = \"\"\n self.species = \"\"\n self.condition = \"\"\n\nclass Weighting :\n def __init__(self):\n self.method = 0\n self.organism = 0\n self.enzyme = 0\n self.conditions = 0\n self.total = 0\n def reset (self):\n self.method = 0\n self.organism = 0\n self.enzyme = 0\n self.conditions = 0\n self.total = 0\n\noptions = Options()\ndata = Data()\nweight = Weighting()\n\ndef weightMethod(method):\n\n def in_vivo():\n #if same as modelling system???\n weight.method += 2\n def in_vitro():\n weight.method -= 1\n\n weight_options = {\n 1 : in_vivo,\n 2 : in_vitro\n }\n\n weight_options[method]()\n\n\ndef weightOrganism (organism):\n\n def same_organism():\n weight.organism = 4\n def phylo_related():\n weight.organism = 2\n def unrelated():\n weight.organism = 1\n\n organism_options = {\n 1 : same_organism,\n 2 : phylo_related,\n 3 : unrelated\n }\n\n organism_options[organism]()\n\n#it can be anything, not only enzyme, do I need to deal with more than one case or is this a single value?\n\ndef weightEnzyme(enzyme):\n def same():\n weight.enzyme = 4\n def related():\n weight.enzyme = 2\n def unrelated():\n weight.enzyme = 1\n\n enzyme_options = {\n 1 : same,\n 2 : related,\n 3 : unrelated\n }\n\n enzyme_options[enzyme]()\n\ndef weightConditions(conditions):\n def same_pH_temp():\n weight.conditions = 4\n def similar_pH_temp():\n weight.conditions = 2\n def unrelated():\n weight.conditions = 1\n\n cond_options ={\n 1 : same_pH_temp,\n 2 : similar_pH_temp,\n 3 : unrelated\n }\n cond_options[conditions]()\n\ndef multiplyWeights():\n\n weight.total = weight.conditions*weight.enzyme*weight.organism*weight.method\n\ndef weightValues(value, method, condition, enzyme, organism):\n\n weightMethod(method)\n weightConditions(condition)\n weightEnzyme(enzyme)\n weightOrganism(organism)\n\n multiplyWeights()\n\ndef main():\n\n #this is an array with possible parameter values and weight used as example\n\n data.value_options = {\n 2 : [1,2,3,1],\n 10 : [1,3,1,2],\n 3 : [2,3,1,2],\n 5 : [2,3,2,1],\n 11 : [1,2,3,2]\n }\n\n for value in data.value_options:\n\n data.measured_v.append(value)\n\n method = data.value_options[value][0]\n condition = data.value_options[value][1]\n enzyme = data.value_options[value][2]\n organism = data.value_options[value][3]\n\n\n weightValues(value , method , condition , enzyme , organism)\n\n data.weights.append(weight.total)\n\n print(data.weights)\n print(data.measured_v)\n\n print(ws.median(data.measured_v))\n\n\n print(ws.weighted_median(data.measured_v, data.weights))\n\nmain()\n\n#most weights can be divided in 3 statements: same, similar, different\n#why are we looking for the weighted median? to define the distribution? why not mean?\n#species mean chem species, of which enzyme are made of\n#make one general specie opriton","sub_path":"Heuristics.py","file_name":"Heuristics.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605451642","text":"import pandas as pd\n\nfrom task_geo.common.country_codes import fips_to_name\nfrom task_geo.data_sources.noaa.api_connector import DEFAULT_METRICS\n\n\ndef noaa_api_formatter(raw, metrics=None):\n data = raw.copy()\n data.columns = [column.lower() for column in data.columns]\n\n if metrics is None:\n metrics = [metric.lower() for metric in DEFAULT_METRICS if metric in raw.columns]\n\n column_order = [\n 'latitude', 'longitude', 'elevation', 'country', 'name',\n 'date', 'station']\n column_order.extend(metrics)\n\n data.date = pd.to_datetime(data.date)\n\n for column in ['tmax', 'tavg', 'tmin']:\n if column in raw.columns:\n data.loc[:, column] = data[column].astype(float) / 10\n\n if 'snwd' in raw.columns:\n data.loc[:, 'snwd'] = data['snwd'].astype(float) / 1000\n data.snwd.fillna(0, inplace=True)\n\n if 'prcp' in raw.columns:\n data.loc[:, 'prcp'] = data['prcp'].astype(float) / 10000\n\n data['country'] = data.station.str.slice(0, 2).apply(fips_to_name)\n\n return data[column_order]\n","sub_path":"task_geo/data_sources/noaa/api_formatter.py","file_name":"api_formatter.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"10760808","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2021 OpenROAD 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\nimport json\nimport os\nimport pathlib\nimport pprint\nimport sys\n\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent.parent))\n\n\nfrom github_api import send_github_json\n\n\ndef update_pr():\n\n event_json_path = os.environ.get('GITHUB_EVENT_PATH', None)\n if not event_json_path:\n print(\"Did not find GITHUB_EVENT_PATH environment value.\")\n return -1\n\n event_json_path = pathlib.Path(event_json_path)\n if not event_json_path.exists():\n print(f\"Path {event_json_path} was not found.\")\n return -2\n\n with open(event_json_path) as f:\n event_json = json.load(f)\n\n # /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\n api_url = f\"https://api.github.com/repos/{event_json['repository']['full_name']}/issues/{event_json['pull_request']['number']}/labels/{event_json['label']['name']}\"\n print()\n r = send_github_json(api_url, \"DELETE\")\n if isinstance(r, dict):\n print(f\"Failed to removed {event_json['label']['name']}.\")\n pprint.pprint(r)\n return -1\n else:\n print(f\"Removed {event_json['label']['name']}.\")\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(update_pr())\n","sub_path":"remove_label/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101945614","text":"# -*- coding: utf-8 -*-\n\"\"\"Module providing content page type\"\"\"\nfrom five import grok\nfrom plone.app.textfield import RichText\nfrom plone.dexterity.content import Container\nfrom plone.namedfile.field import NamedBlobImage\nfrom plone.namedfile.interfaces import IImageScaleTraversable\nfrom plone.supermodel import model\nfrom plone.supermodel.directives import fieldset\nfrom zope import schema\nfrom zope.interface import implementer\n\nfrom hph.sitecontent import MessageFactory as _\n\n\nclass IContentPage(model.Schema, IImageScaleTraversable):\n \"\"\"\n A content page type including fulltext and preview image\n \"\"\"\n headline = schema.TextLine(\n title=_(u\"Content Headline\"),\n description=_(u\"Optional custom headline to seperate navigation and \"\n u\"content title\"),\n required=False,\n )\n text = RichText(\n title=_(u\"Text\"),\n required=False\n )\n\n fieldset(\n 'media',\n label=_(u\"Media\"),\n fields=['image', 'image_caption']\n )\n\n image = NamedBlobImage(\n title=_(u\"Preview Image\"),\n description=_(u\"Upload preview image that can be used in search \"\n u\"results and listings.\"),\n required=False\n )\n\n image_caption = schema.TextLine(\n title=_(u\"Cover Image Caption\"),\n required=False\n )\n\n\n@implementer(IContentPage)\nclass ContentPage(Container):\n pass\n","sub_path":"src/hph.sitecontent/hph/sitecontent/contentpage.py","file_name":"contentpage.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101594096","text":"# fuaq ler 5 valores x. se somatório entre 1 e x for maior que 100,\n# ler valor pra Y e trocar valores entre X e y. se não maior que 100, mostrar\n# a tabuada de 1 até 10 de x.\nsom=0\ntab=0\nfor i in range(1,6):\n print(f'{i} Execução')\n x=int(input('Insira o Numero X: '))\n som=0\n for j in range(2,x): #pois o 1 e o 8 não entram no somatório.\n som+=x\n if (som>100):\n y=int(input('Insira o Numero Y: '))\n temp=x\n x=y\n y=temp\n print(f'A Variável X é {x} e a Y é {y}')\n else:\n for l in range(1,11):\n tab=x*l\n print(f'Numero {x} Multiplicado por {l} é {tab}')","sub_path":"5 - 17.04.20/ler5xde sommaior5lerYsenaoTABdeX.py","file_name":"ler5xde sommaior5lerYsenaoTABdeX.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"167198774","text":"# -*- coding: utf-8 -*-\nmatriz = []\nm = int(input('Digite a quantidade de linhas: '))\nn = int(input('Digite a quantidade de colunas: '))\nfor i in range(0,m,1):\n linha = []\n for j in range(0,n,1):\n linha.append(int(input('Digite um binário [m ,n]: ')))\n matriz.append(linha)\n \n \n \n \n \n \n \n \n \n \n \n \n\nmatriz_recorte = []\n\nindice_superior = m-1\nindice_inferior = 0\nindice_esquerdo = 0\nindice_direito = n-1\n\nfor i in range(0,m,1):\n encontrou_na_linha = False\n for j in range(0,n,1):\n if matriz[i][j] == 1:\n encontrou_na_linha = True\n if j > indice_esquerdo == j:\n indice_esquerdo = j\n if j < indice_direito:\n indice_direito = j\n if encontrou_na_linha:\n if i>indice_superior == i:\n indice_superior = i\n if i`_ .\n\n .. code-block:: yaml\n\n roles:\n grains.list_present:\n - value: web\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': ''}\n grain = __grains__.get(name)\n\n if grain:\n # check whether grain is a list\n if not isinstance(grain, list):\n ret['result'] = False\n ret['comment'] = 'Grain {0} is not a valid list'.format(name)\n return ret\n\n if value in grain:\n ret['comment'] = 'Value {1} is already in grain {0}'.format(name, value)\n return ret\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Value {1} is set to be appended to grain {0}'.format(name, value)\n return ret\n\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Grain {0} is set to be added'.format(name)\n return ret\n\n __salt__['grains.append'](name, value)\n if value not in __grains__.get(name):\n ret['result'] = False\n ret['comment'] = 'Failed append value {1} to grain {0}'.format(name, value)\n return ret\n ret['comment'] = 'Append value {1} to grain {0}'.format(name, value)\n return ret\n\n\ndef list_absent(name, value):\n '''\n Ensure the value is absent in the list type grain\n\n name\n The grain name\n\n value\n The value is absent in the list type grain\n\n The grain should be `list type `_ .\n\n .. code-block:: yaml\n\n roles:\n grains.list_absent:\n - value: db\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': ''}\n grain = __grains__.get(name)\n\n if grain:\n # check whether grain is a list\n if not isinstance(grain, list):\n ret['result'] = False\n ret['coment'] = 'Grain {0} is not a valid list'\n return ret\n\n if value not in grain:\n ret['comment'] = 'Value {1} is absent in grain {0}'.format(name, value)\n return ret\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Value {1} is set to be remove from grain {0}'.format(name, value)\n return ret\n __salt__['grains.remove'](name, value)\n\n if value in __grains__.get(name):\n ret['result'] = False\n ret['comment'] = 'Failed remove value {1} from grain {0}'.format(name, value)\n return ret\n ret['comment'] = 'Remove value {1} from grain {0}'.format(name, value)\n else:\n ret['comment'] = 'Grain {0} is not exist or empty'.format(name)\n return ret\n","sub_path":"sources/salt/states/grains.py","file_name":"grains.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"609003169","text":"#!/usr/bin/python\n\"\"\"\nTime series analysis of data\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pylab as ppl\n\nppl.close('all')\n\n# Load paramters\nimport ConfigDetailSingle\nreload(ConfigDetailSingle)\nfrom ConfigDetailSingle import *\n\nnT = 2 #Thermistor number\n\nChunk1 = np.array([388, 404.5])\nChunk2 = np.array([408.5, 422.2])\n\nprint ('Load data...')\n\nfrom netCDF4 import Dataset as ncdf\nfile = ncdf(DetailDir+'Output_data.nc', mode='r', format='NETCDF4')\ntime = file.variables['Time'][:]\nT = file.variables['Temp'][nT-1,np.nonzero((time>=Start)&(time<=End))[0]]\nZ = file.variables['Depth'][nT-1]\nDataSkipping = file.SkipData\nfile.close()\ntime = time[np.nonzero((time>=Start)&(time<=End))]\n\nprint ('Data loaded')\n\nfrom sys import path\n\npath.append('/home/cimatori/installed')\n#function to perform block averaging\nfrom MyLib import BlockAverage\n\n# Make block average of data if subsampling is requested\nT = BlockAverage(T, DataSkipping, SubSamp)\ntime = BlockAverage(time, DataSkipping, SubSamp)\n\n# Interpolate to regular time step\nintTime = np.arange(time[0], time[-1], SubSamp/86400.)\nData = np.interp(intTime, time, T, left=np.nan, right=np.nan)\ntime = intTime\n\nfrom scipy.signal import detrend\nT1 = T[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\nT1 = detrend(T1)\nT2 = T[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\nT2 = detrend(T2)\ntime1 = time[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\ntime2 = time[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\n\n# Use Hanning window (see pag.445 Data Analysis Methods in Phys. Oc)\nfrom scipy.signal import hann\nT1w = T1*hann(T1.size)\nT2w = T2*hann(T2.size)\n# Use Kaiser window\n#from scipy.signal import kaiser\n#T1 *= kaiser(T1.size, 2)\n#T2 *= kaiser(T1.size, 2)\n\nprint ('Compute FFT')\n# Use matplotlib psd\n\nN1 = 2**int(np.log2(T1w.size)+1); N2 = 2**int(np.log2(T2w.size)+1)\n#N1 = T1.size; N2 = T2.size\n#N1 = 2**22; N2=2**22\n\n# 8/3 for hanning\n# N1/T1.size for compensate zero padding\nfft_pw1 = (N1/np.float(T1.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T1w,N1)) ** 2 # FFT power spectrum\nfft_pw2 = (N2/np.float(T2.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T2w,N2)) ** 2\nfreqs1 = np.fft.fftfreq(len(fft_pw1), SubSamp) # frequencies of FFT\nfreqs2 = np.fft.fftfreq(len(fft_pw2), SubSamp)\n\n# Normalization: Dt*abs(FFT)**2/N\n# this way Df*sum(power)/N = variance\nfft_power1 = SubSamp*fft_pw1[:fft_pw1.size/2]/N1\nfft_power1[1:] += SubSamp*fft_pw1[fft_pw1.size/2+1:]/N1\nfft_power2 = SubSamp*fft_pw2[:fft_pw2.size/2]/N2\nfft_power2[1:] += SubSamp*fft_pw2[fft_pw2.size/2+1:]/N2\nfreqs1 = freqs1[:freqs1.size/2]\nfreqs2 = freqs2[:freqs2.size/2]\n\nwin = 19 #width of smoothing window\nsm_fft_power1 = np.convolve(fft_power1,np.ones(win))\nsm_fft_power1 = sm_fft_power1[(win/2):-(win/2)]/np.float(win)\nsm_fft_power2 = np.convolve(fft_power2,np.ones(win))\nsm_fft_power2 = sm_fft_power2[(win/2):-(win/2)]/np.float(win)\n\n# significance levels for smoothed spectra (pag.454 Data Analysis Methods in Phys. Oc.)\nfrom scipy.stats import chi2\nslev = 0.05 # significance level\nnu1 = 2*win#T1.size/np.float(win) *8./3. # for a Hanning window!\nnu2 = 2*win#T2.size/np.float(win) *8./3.\nsig1 = np.diff([np.log10(nu1/chi2.ppf(1-slev/2,nu1)), np.log10(nu1/chi2.ppf(slev/2,nu1))])\nsig2 = np.diff([np.log10(nu2/chi2.ppf(1-slev/2,nu2)), np.log10(nu2/chi2.ppf(slev/2,nu2))])\n\n#power1,pfreq1 = ppl.psd(T1, NFFT=N/5, Fs=1, detrend=ppl.detrend_none,\n# Fc=1e-5, noverlap=512, scale_by_freq=False)\n#power2,pfreq2 = ppl.psd(T2, NFFT=N/5, Fs=1, detrend=ppl.detrend_none,\n# Fc=1e-5, noverlap=512, scale_by_freq=True)\n\nprint ('Done.\\n Plot data...')\n\nppl.close('all')\n\nfontsize = 'medium'\nparams = {'text.fontsize': fontsize,\n 'xtick.labelsize': fontsize,\n 'ytick.labelsize': fontsize,\n 'axes.titlesize': fontsize\n }\nppl.rcParams.update(params) # Plot parameters\nfigprops = dict(figsize=(11, 7))\nfig = ppl.figure(**figprops)\nfig.subplots_adjust(hspace=0.5)\n\nunits = '^\\circ C'\n\ntitle='Fourier spectra for thermistor at depth {:.1f}m'.format(Z)\n\n# First sub-plot, the original time series anomaly.\nax = ppl.subplot2grid((3,2), (0,0), colspan=2, rowspan=1)\nax.plot(time, Data, 'k-', linewidth=1.5)\ntmin = T.min()-T.std(); tmax=T.max()+T.std()\nax.fill(np.hstack((Chunk1,Chunk1[::-1])), [tmin,tmin,tmax,tmax], 'b', alpha=0.5)\nax.fill(np.hstack((Chunk2,Chunk2[::-1])), [tmin,tmin,tmax,tmax], 'r', alpha=0.5)\nax.set_ylim(tmin,tmax)\nax.set_title('a) %s' % (title, ))\nax.set_xlabel('Time [yeardays]'.format(units))\nax.set_ylabel('Temp. [${}$]'.format(units))\n\nper1 = np.log10(1./freqs1)\nper2 = np.log10(1./freqs2)\ndata1 = np.log10(fft_power1) # data to be plotted\ndata2 = np.log10(fft_power2)\nsdata1 = np.log10(sm_fft_power1)\nsdata2 = np.log10(sm_fft_power2)\n\n# Second sub-plot, FFT spectrum of first chunk of data\nbx = ppl.subplot2grid((3,2), (1,0), colspan=1, rowspan=2)\n\n#plot spectrum\nbx.plot(per1, data1, 'b-', linewidth=0.5, alpha=0.5)\nbx.plot(per2, sdata2, 'r-', linewidth=0.5, alpha=0.4)\nbx.plot(per1, sdata1, 'b-', linewidth=1)\nxsig = np.log10(60); ysig=1 #where to centre significance bar\nbx.errorbar(xsig,ysig, yerr=sig1, color='k', lw=2)\n\nticks = np.array([10, 60, 3600, 86400])\n\nbx.set_title('b) Time interval: {}-{} days'.format(Chunk1[0],Chunk1[1]))\nbx.set_ylabel('$\\log_{10}$(Power) [$'+units+'^2 \\cdot Hz^{-1}$]')\n\n# Third sub-plot, FFT spectrum of first chunk of data\ncx = ppl.subplot2grid((3,2), (1,1), colspan=1, rowspan=2)\n\n#plot spectrum\ncx.plot(per2, data2, 'r-', linewidth=0.5, alpha=0.5)\ncx.plot(per1, sdata1, 'b-', linewidth=0.5, alpha=0.4)\ncx.plot(per2, sdata2, 'r-', linewidth=1)\ncx.errorbar(xsig,ysig, yerr=sig2, color='k', lw=2)\n\ncx.set_title('c) Time interval: {}-{} days'.format(Chunk2[0],Chunk2[1]))\n\n# plot reference lines\nxi = np.log10(np.array([86400, 3600])); xh = np.log10(np.array([2400, 180]))\nslopes = [3, 2, 5./3] # slopes to be plotted\nfor axis in [bx,cx]:\n axis.plot(xi, xi-xi[1], color='black', lw=2)\n axis.plot(xi, 2*xi-2*xi[1]+0.4, '--', color='black', lw=2)\n# for slope in slopes:\n# axis.plot(xh, slope*xh-slope*xh[1]-3, color='black', lw=2)\n # plot inertial frequency\n for per in Tides:\n axis.plot(2*[np.log10(per*3600)], [-100, 100],\\\n 'k-', lw=0.5)\n for harm in (1.,2.,3.,4.):\n axis.plot(2*[np.log10(Tf*3600/harm)], [-100, 100],\\\n 'g-', lw=0.5)\n # settings common to spectra subplots\n axis.set_xlabel('Period [hours]')\n axis.set_xticks(np.log10(ticks))\n axis.set_xticklabels([\"%.3f\" % member for member in ticks/3600.])\n axis.set_xlim(np.log10(2*86400), np.log10(10))\n axis.set_ylim(-7.9, 3.9)\n\n#\nppl.draw()\nppl.show()\nfig.savefig(OutDir+'FFT/'+\\\n 'FFT_nT_{}_day_{}_{}_SubSample_{}.png'.format(nT,Start,End,SubSamp))\n\nprint ('Done.')\n","sub_path":"CanaryBasin/FFT_Analysis.py","file_name":"FFT_Analysis.py","file_ext":"py","file_size_in_byte":6763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"587194452","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nuimethods.py\n\nCreated by 刘 智勇 on 2011-09-24.\nCopyright (c) 2011 __MyCompanyName__. All rights reserved.\n\"\"\"\n\nfrom tornado import template\n#from huwai.apps.perm import PERM_CLASS\n#from huwai.apps.tag import Tag\n\ndef ifNone(handler, v=None):\n return v if v else ''\n\ndef truncate(handler, v, length=100):\n return v[:length]\n\ndef verify(handler, perm, reference):\n if isinstance(reference, int):\n return perm == reference\n elif isinstance(reference, list):\n return (perm in reference)\n elif isinstance(reference, dict):\n s=reference.get('start', 0x00)\n e=reference.get('end', 0x99)\n return (s <= perm <= e)\n return False\n\ndef list2txt(handler, v=None):\n if isinstance(v, list):\n if None in v:v.remove(None)\n return ','.join(v)\n elif isinstance(v, unicode) or isinstance(v, str):\n return v\n return ''\n\ndef dict2txt(handler, v=None):\n if isinstance(v, dict):\n return ''.join(v.values())\n\ndef list2url(handler, v=None):\n if isinstance(v, list):\n if None in v:v.remove(None)\n l = []\n for i, c in v:\n href, txt = '/tag/'+i, c\n l.append(u'%s' % (href, txt))\n return ' '.join(l)\n elif isinstance(v, tuple):\n href = '/tag/'+v[0]\n txt = v[1]\n return u'%s' % (href, txt)\n return ''\n\ndef cntDict(handler, l, **kwargs):\n cnt = 0\n for i in l:\n plus = True\n for k, v in kwargs.items():\n if i.get(k, None) != v:\n plus = False\n if plus:cnt += 1\n return cnt\n\ndef abstract(handler, c, n=100):\n import re\n s = re.sub(r']*>','',c)\n s = s.replace(' ', '')\n if (len(s) > n):\n return s[:n-3] + '...'\n else:\n return s[:n]\n","sub_path":"uimethods.py","file_name":"uimethods.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222972130","text":"import os\nimport os.path as osp\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom tqdm import tqdm\nfrom transformers import get_linear_schedule_with_warmup\nfrom utils.logger_helper import logger\nfrom utils.file_util import delete_dir, ensure_dir\nfrom utils import send_text_to_user\nimport functools\n\nsend_text = functools.partial(send_text_to_user, user='jialeyang@xiaohongshu.com')\n\n\nclass Trainer(object):\n\n def __init__(self, config, device, dataset_train, dataset_test, optimizer, model, save_dir):\n self.config = config\n self.model = model\n self.save_dir = save_dir\n ensure_dir(self.save_dir)\n self.device = device\n self.dataset_train = dataset_train\n self.dataset_test = dataset_test\n # self.optimizer = optimizer(self.model.parameters(), lr=self.config.lr)\n bert_params = list(map(id, model.bert.parameters())) # 返回的是parameters的 内存地址\n top_params = filter(lambda p: id(p) not in bert_params, model.parameters())\n self.optimizer = optimizer([\n {'params': model.bert.parameters(), 'lr': self.config.lr},\n {'params': top_params, 'lr': self.config.lr * 15}])\n\n def train(self, data_parallel=True):\n self.model.train()\n model = self.model.to(self.device)\n if data_parallel:\n model = nn.DataParallel(model)\n total_steps = len(self.dataset_train) * self.config.epochs\n scheduler = get_linear_schedule_with_warmup(self.optimizer, num_warmup_steps=0.1 * total_steps,\n num_training_steps=total_steps) # https://cloud.tencent.com/developer/article/1833108\n global_step = 0\n best_acc_score = 0.0\n best_loss = float(\"inf\")\n for e in range(self.config.epochs):\n loss_sum = 0.\n iter_bar = tqdm(self.dataset_train, desc='Iter (loss=X.XXX)') # TODO: dataset size=1000 ?\n for i, batch in enumerate(iter_bar):\n batch = [t.to(self.device) for t in batch]\n if len(batch) == 5:\n loss, logits = model(input_ids=batch[0],\n token_type_ids=batch[1],\n attention_mask=batch[2],\n labels=batch[3],\n lattice=batch[4])\n else:\n loss, logits = model(input_ids=batch[0],\n token_type_ids=batch[1],\n attention_mask=batch[2],\n labels=batch[3])\n print(loss)\n loss_sum += loss.item()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)\n self.optimizer.step()\n scheduler.step()\n model.zero_grad()\n iter_bar.set_description('Iter (loss=%5.3f)' % (loss.item() / len(batch))) # 当前 batch 的损失\n global_step += 1\n if global_step % self.config.save_steps == 0:\n test_accuracy, test_loss = self.eval(self.dataset_test)\n msg = 'Epoch: {}/{}, Train Loss: {}, Test Loss: {}, Test Acc: {}, ' \\\n .format(e, i, loss.item() / len(batch), test_loss, test_accuracy)\n logger.info(msg)\n send_text(msg)\n if test_accuracy > best_acc_score and test_loss < best_loss:\n best_acc_score = test_accuracy\n best_loss = test_loss\n msg = 'At epoch {}/{} Model with best test acc score {} and test loss {}, saved at {}'.format(\n e, i, best_acc_score, test_loss, self.save_dir)\n logger.info(msg)\n send_text(msg)\n delete_dir(osp.dirname(self.save_dir))\n ensure_dir(self.save_dir)\n self.save(global_step)\n msg = 'Epoch {} : Average Train Loss {}'.format(e, loss_sum / len(self.dataset_train))\n logger.info(msg) # 所有已跑 batch 的平均损失\n send_text(msg)\n\n def save(self, i):\n \"\"\" save current model \"\"\"\n torch.save(self.model.state_dict(), os.path.join(self.save_dir, 'model_steps_' + str(i) + '.pt'))\n\n def load(self, model_file):\n self.model.load_state_dict(torch.load(model_file, map_location=legent(self.device)))\n\n def eval(self, test_set, data_parallel=True):\n \"\"\" Evaluation Loop\n \"\"\"\n self.model.eval() # 不再动态更新参数,该用训练好的值\n model = self.model.to(self.device)\n if data_parallel:\n model = nn.DataParallel(model)\n res_acc = []\n res_loss = []\n iter_bar = tqdm(test_set, desc='Iter (loss=X.XXX) (loss=X.XXX)')\n for batch in iter_bar:\n batch = [t.to(self.device) for t in batch]\n with torch.no_grad(): # 禁用梯度计算的上下文管理器\n batch = [t.to(self.device) for t in batch]\n if len(batch) == 5:\n loss, logits = model(input_ids=batch[0],\n token_type_ids=batch[1],\n attention_mask=batch[2],\n labels=batch[3],\n lattice=batch[4])\n else:\n loss, logits = model(input_ids=batch[0],\n token_type_ids=batch[1],\n attention_mask=batch[2],\n labels=batch[3])\n tags = self.model.crf.decode(logits, batch[2].byte()) # logits:[32, 81, 11] ;attention_mask:[32, 81]\n label_pred = [w[1:-1] for w in tags]\n acc_sum = []\n acc_count = []\n for pred, true in zip(label_pred, batch[3].tolist()):\n true_id = true[1:len(pred) + 1]\n acc = sum(np.array(pred) == np.array(true_id))\n acc_sum.append(acc)\n acc_count.append(len(pred))\n res_acc.append(sum(acc_sum) / sum(acc_count) if sum(acc_count) > 0 else 0)\n res_loss.append(loss.item() / len(batch[0]) if len(batch[0]) > 0 else 0)\n return sum(res_acc) / len(res_acc), sum(res_loss) / len(res_loss)\n","sub_path":"entity_extractor/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402612704","text":"# This puts the ptb character dataset in the same format as I have the Tedlium data\n\nimport numpy as np\n\nsetnames = ['train', 'valid', 'test']\nsetnames_out = ['train', 'dev', 'test']\n\nfor (setname, setname_out) in zip(setnames, setnames_out):\n\n with open('model/data/penn/ptb.char.'+setname+'.txt') as f:\n datalist = f.read().split(' ')[:-1]\n\n if setname=='train':\n vocab = np.unique(datalist)\n print(len(np.unique(datalist)))\n data_words = np.array([[np.where(vocab==word)[0][0] for word in datalist]]).T\n data_durs = np.random.randn(data_words.shape[0],2)\n\n outfile = './data/for_training/data_ptbchar_'+setname_out\n\n np.savez(outfile, data_words=np.array([data_words]),\n data_durs=np.array([data_durs]),\n talknames=np.array(['ptb']), vocab=vocab)\n","sub_path":"ptb_model_data_char.py","file_name":"ptb_model_data_char.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"649686515","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is a RidgemontResources spider created on top of the ATSSpider\nscrapy crawl ridgemontresources -a mining_job_id=999 -a iteration=1 -a extract=1 -a url=\"http://jobs.ridgemontresources.com/JobSeeker/Search.aspx\"\n\nsample url:\n http://jobs.ridgemontresources.com/JobSeeker/Search.aspx\n\"\"\"\n\nfrom re import compile\nfrom urlparse import urljoin\n\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, Strip, RemoveBadElements, ConvertDateString\n\n\nclass RidgemontResources(ATSSpider):\n\n name = 'ridgemontresources'\n ref_re = compile(\".*_([^\\.]*)\")\n\n def parse(self, response):\n form_data = {\n '__EVENTTARGET': 'ctl00$ContentPlaceHolder1$btnSearch'\n }\n yield FormRequest.from_response(\n response=response, formdata=form_data,\n formxpath=\"//form[@id='form1']\", callback=self.parse_job_list\n )\n\n def parse_job_list(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath(\n \"//div[@id='dvRecordCountTop']/text()\"\n ).extract()\n if job_count:\n self.expected_job_count = job_count[0].split(\"of\")[-1]\n\n jobs = sel.xpath(\n \"//div[div[@class='posTitle']]\"\n )\n for job in jobs:\n job_link = job.xpath(\"div[@class='posTitle']//a/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'title': job.xpath(\n \".//div[@class='posTitleLink']//text()\"\n ).extract(),\n 'location': job.xpath(\n \".//span[@class='src_res_job_location']/text()\"\n ).extract(),\n 'date': job.xpath(\n \".//div[@class='postDate']//text()\"\n ).extract(),\n }\n yield Request(\n url=job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next_page = sel.xpath(\"//a[@class='lnkNext']/@href\").extract()\n if next_page:\n next_url = urljoin(response.url, next_page[0])\n yield Request(url=next_url, callback=self.parse_job_list)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value(\n 'date', response.meta['date'], ConvertDateString(\"%b %d, %Y\")\n )\n loader.add_value('location', response.meta['location'], Strip(\"- \"))\n loader.add_xpath(\n 'jobtype',\n \"//span[@id='ContentPlaceHolder1_lblJobType']/text()\"\n )\n loader.add_xpath(\n 'description', \"//div[@id='dvDescription']\",\n RemoveBadElements(['img', 'style']), HtmlFormatter()\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/ridgemontresources.py","file_name":"ridgemontresources.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102569215","text":"# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\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 are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its 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 FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\n__all__ = ['basis', 'qutrit_basis', 'coherent', 'coherent_dm', 'fock_dm',\n 'fock', 'thermal_dm', 'maximally_mixed_dm', 'ket2dm', 'projection',\n 'qstate', 'ket', 'bra', 'state_number_enumerate',\n 'state_number_index', 'state_index_number', 'state_number_qobj',\n 'phase_basis', 'zero_ket', 'spin_state', 'spin_coherent',\n 'bell_state', 'singlet_state', 'triplet_states', 'w_state',\n 'ghz_state', 'enr_state_dictionaries', 'enr_fock',\n 'enr_thermal_dm']\n\nimport numpy as np\nfrom scipy import arange, conj, prod\nimport scipy.sparse as sp\n\nfrom qutip.qobj import Qobj\nfrom qutip.operators import destroy, jmat\nfrom qutip.tensor import tensor\n\n\ndef basis(N, n=0, offset=0):\n \"\"\"Generates the vector representation of a Fock state.\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n n : int\n Integer corresponding to desired number state, defaults\n to 0 if omitted.\n\n offset : int (default 0)\n The lowest number state that is included in the finite number state\n representation of the state.\n\n Returns\n -------\n state : qobj\n Qobj representing the requested number state ``|n>``.\n\n Examples\n --------\n >>> basis(5,2)\n Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n Qobj data =\n [[ 0.+0.j]\n [ 0.+0.j]\n [ 1.+0.j]\n [ 0.+0.j]\n [ 0.+0.j]]\n\n Notes\n -----\n\n A subtle incompatibility with the quantum optics toolbox: In QuTiP::\n\n basis(N, 0) = ground state\n\n but in the qotoolbox::\n\n basis(N, 1) = ground state\n\n \"\"\"\n if (not isinstance(N, (int, np.integer))) or N < 0:\n raise ValueError(\"N must be integer N >= 0\")\n\n if (not isinstance(n, (int, np.integer))) or n < offset:\n raise ValueError(\"n must be integer n >= 0\")\n\n if n - offset > (N - 1): # check if n is within bounds\n raise ValueError(\"basis vector index need to be in n <= N-1\")\n\n bas = sp.lil_matrix((N, 1)) # column vector of zeros\n bas[n - offset, 0] = 1 # 1 located at position n\n bas = bas.tocsr()\n\n return Qobj(bas)\n\n\ndef qutrit_basis():\n \"\"\"Basis states for a three level system (qutrit)\n\n Returns\n -------\n qstates : array\n Array of qutrit basis vectors\n\n \"\"\"\n return np.array([basis(3, 0), basis(3, 1), basis(3, 2)], dtype=object)\n\n\ndef _sqrt_factorial(n_vec):\n # take the square root before multiplying\n return np.array([np.prod(np.sqrt(np.arange(1, n + 1))) for n in n_vec])\n\n\ndef coherent(N, alpha, offset=0, method='operator'):\n \"\"\"Generates a coherent state with eigenvalue alpha.\n\n Constructed using displacement operator on vacuum state.\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n alpha : float/complex\n Eigenvalue of coherent state.\n\n offset : int (default 0)\n The lowest number state that is included in the finite number state\n representation of the state. Using a non-zero offset will make the\n default method 'analytic'.\n\n method : string {'operator', 'analytic'}\n Method for generating coherent state.\n\n Returns\n -------\n state : qobj\n Qobj quantum object for coherent state\n\n Examples\n --------\n >>> coherent(5,0.25j)\n Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n Qobj data =\n [[ 9.69233235e-01+0.j ]\n [ 0.00000000e+00+0.24230831j]\n [ -4.28344935e-02+0.j ]\n [ 0.00000000e+00-0.00618204j]\n [ 7.80904967e-04+0.j ]]\n\n Notes\n -----\n Select method 'operator' (default) or 'analytic'. With the\n 'operator' method, the coherent state is generated by displacing\n the vacuum state using the displacement operator defined in the\n truncated Hilbert space of size 'N'. This method guarantees that the\n resulting state is normalized. With 'analytic' method the coherent state\n is generated using the analytical formula for the coherent state\n coefficients in the Fock basis. This method does not guarantee that the\n state is normalized if truncated to a small number of Fock states,\n but would in that case give more accurate coefficients.\n\n \"\"\"\n if method == \"operator\" and offset == 0:\n\n x = basis(N, 0)\n a = destroy(N)\n D = (alpha * a.dag() - conj(alpha) * a).expm()\n return D * x\n\n elif method == \"analytic\" or offset > 0:\n\n data = np.zeros([N, 1], dtype=complex)\n n = arange(N) + offset\n data[:, 0] = np.exp(-(abs(alpha) ** 2) / 2.0) * (alpha ** (n)) / \\\n _sqrt_factorial(n)\n return Qobj(data)\n\n else:\n raise TypeError(\n \"The method option can only take values 'operator' or 'analytic'\")\n\n\ndef coherent_dm(N, alpha, offset=0, method='operator'):\n \"\"\"Density matrix representation of a coherent state.\n\n Constructed via outer product of :func:`qutip.states.coherent`\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n alpha : float/complex\n Eigenvalue for coherent state.\n\n offset : int (default 0)\n The lowest number state that is included in the finite number state\n representation of the state.\n\n method : string {'operator', 'analytic'}\n Method for generating coherent density matrix.\n\n Returns\n -------\n dm : qobj\n Density matrix representation of coherent state.\n\n Examples\n --------\n >>> coherent_dm(3,0.25j)\n Quantum object: dims = [[3], [3]], \\\nshape = [3, 3], type = oper, isHerm = True\n Qobj data =\n [[ 0.93941695+0.j 0.00000000-0.23480733j -0.04216943+0.j ]\n [ 0.00000000+0.23480733j 0.05869011+0.j 0.00000000-0.01054025j]\n [-0.04216943+0.j 0.00000000+0.01054025j 0.00189294+0.j\\\n ]]\n\n Notes\n -----\n Select method 'operator' (default) or 'analytic'. With the\n 'operator' method, the coherent density matrix is generated by displacing\n the vacuum state using the displacement operator defined in the\n truncated Hilbert space of size 'N'. This method guarantees that the\n resulting density matrix is normalized. With 'analytic' method the coherent\n density matrix is generated using the analytical formula for the coherent\n state coefficients in the Fock basis. This method does not guarantee that\n the state is normalized if truncated to a small number of Fock states,\n but would in that case give more accurate coefficients.\n\n \"\"\"\n if method == \"operator\":\n psi = coherent(N, alpha, offset=offset)\n return psi * psi.dag()\n\n elif method == \"analytic\":\n psi = coherent(N, alpha, offset=offset, method='analytic')\n return psi * psi.dag()\n\n else:\n raise TypeError(\n \"The method option can only take values 'operator' or 'analytic'\")\n\n\ndef fock_dm(N, n=0, offset=0):\n \"\"\"Density matrix representation of a Fock state\n\n Constructed via outer product of :func:`qutip.states.fock`.\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n n : int\n ``int`` for desired number state, defaults to 0 if omitted.\n\n Returns\n -------\n dm : qobj\n Density matrix representation of Fock state.\n\n Examples\n --------\n >>> fock_dm(3,1)\n Quantum object: dims = [[3], [3]], \\\nshape = [3, 3], type = oper, isHerm = True\n Qobj data =\n [[ 0.+0.j 0.+0.j 0.+0.j]\n [ 0.+0.j 1.+0.j 0.+0.j]\n [ 0.+0.j 0.+0.j 0.+0.j]]\n\n \"\"\"\n psi = basis(N, n, offset=offset)\n\n return psi * psi.dag()\n\n\ndef fock(N, n=0, offset=0):\n \"\"\"Bosonic Fock (number) state.\n\n Same as :func:`qutip.states.basis`.\n\n Parameters\n ----------\n N : int\n Number of states in the Hilbert space.\n\n n : int\n ``int`` for desired number state, defaults to 0 if omitted.\n\n Returns\n -------\n Requested number state :math:`\\\\left|n\\\\right>`.\n\n Examples\n --------\n >>> fock(4,3)\n Quantum object: dims = [[4], [1]], shape = [4, 1], type = ket\n Qobj data =\n [[ 0.+0.j]\n [ 0.+0.j]\n [ 0.+0.j]\n [ 1.+0.j]]\n\n \"\"\"\n return basis(N, n, offset=offset)\n\n\ndef thermal_dm(N, n, method='operator'):\n \"\"\"Density matrix for a thermal state of n particles\n\n Parameters\n ----------\n N : int\n Number of basis states in Hilbert space.\n\n n : float\n Expectation value for number of particles in thermal state.\n\n method : string {'operator', 'analytic'}\n ``string`` that sets the method used to generate the\n thermal state probabilities\n\n Returns\n -------\n dm : qobj\n Thermal state density matrix.\n\n Examples\n --------\n >>> thermal_dm(5, 1)\n Quantum object: dims = [[5], [5]], \\\nshape = [5, 5], type = oper, isHerm = True\n Qobj data =\n [[ 0.51612903 0. 0. 0. 0. ]\n [ 0. 0.25806452 0. 0. 0. ]\n [ 0. 0. 0.12903226 0. 0. ]\n [ 0. 0. 0. 0.06451613 0. ]\n [ 0. 0. 0. 0. 0.03225806]]\n\n\n >>> thermal_dm(5, 1, 'analytic')\n Quantum object: dims = [[5], [5]], \\\nshape = [5, 5], type = oper, isHerm = True\n Qobj data =\n [[ 0.5 0. 0. 0. 0. ]\n [ 0. 0.25 0. 0. 0. ]\n [ 0. 0. 0.125 0. 0. ]\n [ 0. 0. 0. 0.0625 0. ]\n [ 0. 0. 0. 0. 0.03125]]\n\n Notes\n -----\n The 'operator' method (default) generates\n the thermal state using the truncated number operator ``num(N)``. This\n is the method that should be used in computations. The\n 'analytic' method uses the analytic coefficients derived in\n an infinite Hilbert space. The analytic form is not necessarily normalized,\n if truncated too aggressively.\n\n \"\"\"\n if n == 0:\n return fock_dm(N, 0)\n else:\n i = arange(N)\n if method == 'operator':\n beta = np.log(1.0 / n + 1.0)\n diags = np.exp(-beta * i)\n diags = diags / np.sum(diags)\n # populates diagonal terms using truncated operator expression\n rm = sp.spdiags(diags, 0, N, N, format='csr')\n elif method == 'analytic':\n # populates diagonal terms using analytic values\n rm = sp.spdiags((1.0 + n) ** (-1.0) * (n / (1.0 + n)) ** (i),\n 0, N, N, format='csr')\n else:\n raise ValueError(\n \"'method' keyword argument must be 'operator' or 'analytic'\")\n return Qobj(rm)\n\n\ndef maximally_mixed_dm(N):\n \"\"\"\n Returns the maximally mixed density matrix for a Hilbert space of\n dimension N.\n\n Parameters\n ----------\n N : int\n Number of basis states in Hilbert space.\n\n Returns\n -------\n dm : qobj\n Thermal state density matrix.\n \"\"\"\n if (not isinstance(N, (int, np.int64))) or N <= 0:\n raise ValueError(\"N must be integer N > 0\")\n\n dm = sp.spdiags(np.ones(N, dtype=complex)/float(N), 0, N, N, format='csr')\n\n return Qobj(dm, isherm=True)\n\n\ndef ket2dm(Q):\n \"\"\"Takes input ket or bra vector and returns density matrix\n formed by outer product.\n\n Parameters\n ----------\n Q : qobj\n Ket or bra type quantum object.\n\n Returns\n -------\n dm : qobj\n Density matrix formed by outer product of `Q`.\n\n Examples\n --------\n >>> x=basis(3,2)\n >>> ket2dm(x)\n Quantum object: dims = [[3], [3]], \\\nshape = [3, 3], type = oper, isHerm = True\n Qobj data =\n [[ 0.+0.j 0.+0.j 0.+0.j]\n [ 0.+0.j 0.+0.j 0.+0.j]\n [ 0.+0.j 0.+0.j 1.+0.j]]\n\n \"\"\"\n if Q.type == 'ket':\n out = Q * Q.dag()\n elif Q.type == 'bra':\n out = Q.dag() * Q\n else:\n raise TypeError(\"Input is not a ket or bra vector.\")\n return Qobj(out)\n\n\n#\n# projection operator\n#\ndef projection(N, n, m, offset=0):\n \"\"\"The projection operator that projects state |m> on state |n>: |n>` or 'down' :math:`|1>` state.\n\n Parameters\n ----------\n string : str\n String containing 'u' or 'd' for each qubit (ex. 'ududd')\n\n Returns\n -------\n qstate : qobj\n Qobj for tensor product corresponding to input string.\n\n Notes\n -----\n Look at ket and bra for more general functions\n creating multiparticle states.\n\n Examples\n --------\n >>> qstate('udu')\n Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 1.]\n [ 0.]\n [ 0.]]\n\n \"\"\"\n n = len(string)\n if n != (string.count('u') + string.count('d')):\n raise TypeError('String input to QSTATE must consist ' +\n 'of \"u\" and \"d\" elements only')\n else:\n up = basis(2, 1)\n dn = basis(2, 0)\n lst = []\n for k in range(n):\n if string[k] == 'u':\n lst.append(up)\n else:\n lst.append(dn)\n return tensor(lst)\n\n\n#\n# different qubit notation dictionary\n#\n_qubit_dict = {'g': 0, # ground state\n 'e': 1, # excited state\n 'u': 0, # spin up\n 'd': 1, # spin down\n 'H': 0, # horizontal polarization\n 'V': 1} # vertical polarization\n\n\ndef _character_to_qudit(x):\n \"\"\"\n Converts a character representing a one-particle state into int.\n \"\"\"\n if x in _qubit_dict:\n return _qubit_dict[x]\n else:\n return int(x)\n\n\ndef ket(seq, dim=2):\n \"\"\"\n Produces a multiparticle ket state for a list or string,\n where each element stands for state of the respective particle.\n\n Parameters\n ----------\n seq : str / list of ints or characters\n Each element defines state of the respective particle.\n (e.g. [1,1,0,1] or a string \"1101\").\n For qubits it is also possible to use the following conventions:\n - 'g'/'e' (ground and excited state)\n - 'u'/'d' (spin up and down)\n - 'H'/'V' (horizontal and vertical polarization)\n Note: for dimension > 9 you need to use a list.\n\n\n dim : int (default: 2) / list of ints\n Space dimension for each particle:\n int if there are the same, list if they are different.\n\n Returns\n -------\n ket : qobj\n\n Examples\n --------\n >>> ket(\"10\")\n Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 0.]\n [ 1.]\n [ 0.]]\n\n >>> ket(\"Hue\")\n Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 1.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]]\n\n >>> ket(\"12\", 3)\n Quantum object: dims = [[3, 3], [1, 1]], shape = [9, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 1.]\n [ 0.]\n [ 0.]\n [ 0.]]\n\n >>> ket(\"31\", [5, 2])\n Quantum object: dims = [[5, 2], [1, 1]], shape = [10, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 1.]\n [ 0.]\n [ 0.]]\n \"\"\"\n if isinstance(dim, int):\n dim = [dim] * len(seq)\n return tensor([basis(dim[i], _character_to_qudit(x))\n for i, x in enumerate(seq)])\n\n\ndef bra(seq, dim=2):\n \"\"\"\n Produces a multiparticle bra state for a list or string,\n where each element stands for state of the respective particle.\n\n Parameters\n ----------\n seq : str / list of ints or characters\n Each element defines state of the respective particle.\n (e.g. [1,1,0,1] or a string \"1101\").\n For qubits it is also possible to use the following conventions:\n - 'g'/'e' (ground and excited state)\n - 'u'/'d' (spin up and down)\n - 'H'/'V' (horizontal and vertical polarization)\n Note: for dimension > 9 you need to use a list.\n\n\n dim : int (default: 2) / list of ints\n Space dimension for each particle:\n int if there are the same, list if they are different.\n\n Returns\n -------\n bra : qobj\n\n Examples\n --------\n >>> bra(\"10\")\n Quantum object: dims = [[1, 1], [2, 2]], shape = [1, 4], type = bra\n Qobj data =\n [[ 0. 0. 1. 0.]]\n\n >>> bra(\"Hue\")\n Quantum object: dims = [[1, 1, 1], [2, 2, 2]], shape = [1, 8], type = bra\n Qobj data =\n [[ 0. 1. 0. 0. 0. 0. 0. 0.]]\n\n >>> bra(\"12\", 3)\n Quantum object: dims = [[1, 1], [3, 3]], shape = [1, 9], type = bra\n Qobj data =\n [[ 0. 0. 0. 0. 0. 1. 0. 0. 0.]]\n\n\n >>> bra(\"31\", [5, 2])\n Quantum object: dims = [[1, 1], [5, 2]], shape = [1, 10], type = bra\n Qobj data =\n [[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]\n \"\"\"\n return ket(seq, dim=dim).dag()\n\n\n#\n# quantum state number helper functions\n#\ndef state_number_enumerate(dims, excitations=None, state=None, idx=0):\n \"\"\"\n An iterator that enumerate all the state number arrays (quantum numbers on\n the form [n1, n2, n3, ...]) for a system with dimensions given by dims.\n\n Example:\n\n >>> for state in state_number_enumerate([2,2]):\n >>> print(state)\n [ 0. 0.]\n [ 0. 1.]\n [ 1. 0.]\n [ 1. 1.]\n\n Parameters\n ----------\n dims : list or array\n The quantum state dimensions array, as it would appear in a Qobj.\n\n state : list\n Current state in the iteration. Used internally.\n\n excitations : integer (None)\n Restrict state space to states with excitation numbers below or\n equal to this value.\n\n idx : integer\n Current index in the iteration. Used internally.\n\n Returns\n -------\n state_number : list\n Successive state number arrays that can be used in loops and other\n iterations, using standard state enumeration *by definition*.\n\n \"\"\"\n\n if state is None:\n state = np.zeros(len(dims))\n\n if excitations and sum(state[0:idx]) > excitations:\n pass\n elif idx == len(dims):\n if excitations is None:\n yield np.array(state)\n else:\n yield tuple(state)\n else:\n for n in range(dims[idx]):\n state[idx] = n\n for s in state_number_enumerate(dims, excitations, state, idx + 1):\n yield s\n\n\ndef state_number_index(dims, state):\n \"\"\"\n Return the index of a quantum state corresponding to state,\n given a system with dimensions given by dims.\n\n Example:\n\n >>> state_number_index([2, 2, 2], [1, 1, 0])\n 6.0\n\n Parameters\n ----------\n dims : list or array\n The quantum state dimensions array, as it would appear in a Qobj.\n\n state : list\n State number array.\n\n Returns\n -------\n idx : list\n The index of the state given by `state` in standard enumeration\n ordering.\n\n \"\"\"\n return sum([state[i] * prod(dims[i + 1:]) for i, d in enumerate(dims)])\n\n\ndef state_index_number(dims, index):\n \"\"\"\n Return a quantum number representation given a state index, for a system\n of composite structure defined by dims.\n\n Example:\n\n >>> state_index_number([2, 2, 2], 6)\n [1, 1, 0]\n\n Parameters\n ----------\n dims : list or array\n The quantum state dimensions array, as it would appear in a Qobj.\n\n index : integer\n The index of the state in standard enumeration ordering.\n\n Returns\n -------\n state : list\n The state number array corresponding to index `index` in standard\n enumeration ordering.\n\n \"\"\"\n state = np.empty_like(dims)\n\n D = np.concatenate([np.flipud(np.cumprod(np.flipud(dims[1:]))), [1]])\n\n for n in range(len(dims)):\n state[n] = index / D[n]\n index -= state[n] * D[n]\n\n return list(state)\n\n\ndef state_number_qobj(dims, state):\n \"\"\"\n Return a Qobj representation of a quantum state specified by the state\n array `state`.\n\n Example:\n\n >>> state_number_qobj([2, 2, 2], [1, 0, 1])\n Quantum object: dims = [[2, 2, 2], [1, 1, 1]], \\\nshape = [8, 1], type = ket\n Qobj data =\n [[ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 0.]\n [ 1.]\n [ 0.]\n [ 0.]]\n\n Parameters\n ----------\n dims : list or array\n The quantum state dimensions array, as it would appear in a Qobj.\n\n state : list\n State number array.\n\n Returns\n -------\n state : :class:`qutip.Qobj.qobj`\n The state as a :class:`qutip.Qobj.qobj` instance.\n\n\n \"\"\"\n return tensor([fock(dims[i], s) for i, s in enumerate(state)])\n\n\n#\n# Excitation-number restricted (enr) states\n#\ndef enr_state_dictionaries(dims, excitations):\n \"\"\"\n Return the number of states, and lookup-dictionaries for translating\n a state tuple to a state index, and vice versa, for a system with a given\n number of components and maximum number of excitations.\n\n Parameters\n ----------\n dims: list\n A list with the number of states in each sub-system.\n\n excitations : integer\n The maximum numbers of dimension\n\n Returns\n -------\n nstates, state2idx, idx2state: integer, dict, dict\n The number of states `nstates`, a dictionary for looking up state\n indices from a state tuple, and a dictionary for looking up state\n state tuples from state indices.\n \"\"\"\n nstates = 0\n state2idx = {}\n idx2state = {}\n\n for state in state_number_enumerate(dims, excitations):\n state2idx[state] = nstates\n idx2state[nstates] = state\n nstates += 1\n\n return nstates, state2idx, idx2state\n\n\ndef enr_fock(dims, excitations, state):\n \"\"\"\n Generate the Fock state representation in a excitation-number restricted\n state space. The `dims` argument is a list of integers that define the\n number of quantums states of each component of a composite quantum system,\n and the `excitations` specifies the maximum number of excitations for\n the basis states that are to be included in the state space. The `state`\n argument is a tuple of integers that specifies the state (in the number\n basis representation) for which to generate the Fock state representation.\n\n Parameters\n ----------\n dims : list\n A list of the dimensions of each subsystem of a composite quantum\n system.\n\n excitations : integer\n The maximum number of excitations that are to be included in the\n state space.\n\n state : list of integers\n The state in the number basis representation.\n\n Returns\n -------\n ket : Qobj\n A Qobj instance that represent a Fock state in the exication-number-\n restricted state space defined by `dims` and `exciations`.\n\n \"\"\"\n nstates, state2idx, idx2state = enr_state_dictionaries(dims, excitations)\n\n data = sp.lil_matrix((nstates, 1), dtype=np.complex)\n\n try:\n data[state2idx[tuple(state)], 0] = 1\n except:\n raise ValueError(\"The state tuple %s is not in the restricted \"\n \"state space\" % str(tuple(state)))\n\n return Qobj(data, dims=[dims, 1])\n\n\ndef enr_thermal_dm(dims, excitations, n):\n \"\"\"\n Generate the density operator for a thermal state in the excitation-number-\n restricted state space defined by the `dims` and `exciations` arguments.\n See the documentation for enr_fock for a more detailed description of\n these arguments. The temperature of each mode in dims is specified by\n the average number of excitatons `n`.\n\n Parameters\n ----------\n dims : list\n A list of the dimensions of each subsystem of a composite quantum\n system.\n\n excitations : integer\n The maximum number of excitations that are to be included in the\n state space.\n\n n : integer\n The average number of exciations in the thermal state. `n` can be\n a float (which then applies to each mode), or a list/array of the same\n length as dims, in which each element corresponds specifies the\n temperature of the corresponding mode.\n\n Returns\n -------\n dm : Qobj\n Thermal state density matrix.\n \"\"\"\n nstates, state2idx, idx2state = enr_state_dictionaries(dims, excitations)\n\n if not isinstance(n, (list, np.ndarray)):\n n = np.ones(len(dims)) * n\n else:\n n = np.asarray(n)\n\n diags = [np.prod((n / (n + 1)) ** np.array(state))\n for idx, state in idx2state.items()]\n diags /= np.sum(diags)\n data = sp.spdiags(diags, 0, nstates, nstates, format='csr')\n\n return Qobj(data, dims=[dims, dims])\n\n\ndef phase_basis(N, m, phi0=0):\n \"\"\"\n Basis vector for the mth phase of the Pegg-Barnett phase operator.\n\n Parameters\n ----------\n N : int\n Number of basis vectors in Hilbert space.\n m : int\n Integer corresponding to the mth discrete phase phi_m=phi0+2*pi*m/N\n phi0 : float (default=0)\n Reference phase angle.\n\n Returns\n -------\n state : qobj\n Ket vector for mth Pegg-Barnett phase operator basis state.\n\n Notes\n -----\n The Pegg-Barnett basis states form a complete set over the truncated\n Hilbert space.\n\n \"\"\"\n phim = phi0 + (2.0 * np.pi * m) / N\n n = np.arange(N).reshape((N, 1))\n data = 1.0 / np.sqrt(N) * np.exp(1.0j * n * phim)\n return Qobj(data)\n\n\ndef zero_ket(N, dims=None):\n \"\"\"\n Creates the zero ket vector with shape Nx1 and\n dimensions `dims`.\n\n Parameters\n ----------\n N : int\n Hilbert space dimensionality\n dims : list\n Optional dimensions if ket corresponds to\n a composite Hilbert space.\n\n Returns\n -------\n zero_ket : qobj\n Zero ket on given Hilbert space.\n\n \"\"\"\n return Qobj(sp.csr_matrix((N, 1), dtype=complex), dims=dims)\n\n\ndef spin_state(j, m, type='ket'):\n \"\"\"Generates the spin state |j, m>, i.e. the eigenstate\n of the spin-j Sz operator with eigenvalue m.\n\n Parameters\n ----------\n j : float\n The spin of the state ().\n\n m : int\n Eigenvalue of the spin-j Sz operator.\n\n type : string {'ket', 'bra', 'dm'}\n Type of state to generate.\n\n Returns\n -------\n state : qobj\n Qobj quantum object for spin state\n\n \"\"\"\n J = 2 * j + 1\n\n if type == 'ket':\n return basis(int(J), int(j - m))\n elif type == 'bra':\n return basis(int(J), int(j - m)).dag()\n elif type == 'dm':\n return fock_dm(int(J), int(j - m))\n else:\n raise ValueError(\"invalid value keyword argument 'type'\")\n\n\ndef spin_coherent(j, theta, phi, type='ket'):\n \"\"\"Generates the spin state |j, m>, i.e. the eigenstate\n of the spin-j Sz operator with eigenvalue m.\n\n Parameters\n ----------\n j : float\n The spin of the state.\n\n theta : float\n Angle from z axis.\n\n phi : float\n Angle from x axis.\n\n type : string {'ket', 'bra', 'dm'}\n Type of state to generate.\n\n Returns\n -------\n state : qobj\n Qobj quantum object for spin coherent state\n\n \"\"\"\n Sp = jmat(j, '+')\n Sm = jmat(j, '-')\n psi = (0.5 * theta * np.exp(1j * phi) * Sm -\n 0.5 * theta * np.exp(-1j * phi) * Sp).expm() * spin_state(j, j)\n\n if type == 'ket':\n return psi\n elif type == 'bra':\n return psi.dag()\n elif type == 'dm':\n return ket2dm(psi)\n else:\n raise ValueError(\"invalid value keyword argument 'type'\")\n\n\ndef bell_state(state='00'):\n \"\"\"\n Returns the Bell state:\n\n |B00> = 1 / sqrt(2)*[|0>|0>+|1>|1>]\n |B01> = 1 / sqrt(2)*[|0>|0>-|1>|1>]\n |B10> = 1 / sqrt(2)*[|0>|1>+|1>|0>]\n |B11> = 1 / sqrt(2)*[|0>|1>-|1>|0>]\n\n Returns\n -------\n Bell_state : qobj\n Bell state\n\n \"\"\"\n if state == '00':\n Bell_state = tensor(\n basis(2), basis(2))+tensor(basis(2, 1), basis(2, 1))\n elif state == '01':\n Bell_state = tensor(\n basis(2), basis(2))-tensor(basis(2, 1), basis(2, 1))\n elif state == '10':\n Bell_state = tensor(\n basis(2), basis(2, 1))+tensor(basis(2, 1), basis(2))\n elif state == '11':\n Bell_state = tensor(\n basis(2), basis(2, 1))-tensor(basis(2, 1), basis(2))\n\n return Bell_state.unit()\n\n\ndef singlet_state():\n \"\"\"\n Returns the two particle singlet-state:\n\n |S>=1/sqrt(2)*[|0>|1>-|1>|0>]\n\n that is identical to the fourth bell state.\n\n Returns\n -------\n Bell_state : qobj\n |B11> Bell state\n\n \"\"\"\n return bell_state('11')\n\n\ndef triplet_states():\n \"\"\"\n Returns the two particle triplet-states:\n\n |T>= |1>|1>\n = 1 / sqrt(2)*[|0>|1>-|1>|0>]\n = |0>|0>\n that is identical to the fourth bell state.\n\n Returns\n -------\n trip_states : list\n 2 particle triplet states\n\n \"\"\"\n trip_states = []\n trip_states.append(tensor(basis(2, 1), basis(2, 1)))\n trip_states.append(\n tensor(basis(2), basis(2, 1))+tensor(basis(2, 1), basis(2)))\n trip_states.append(tensor(basis(2), basis(2)))\n return trip_states\n\n\ndef w_state(N=3):\n \"\"\"\n Returns the N-qubit W-state.\n\n Parameters\n ----------\n N : int (default=3)\n Number of qubits in state\n\n Returns\n -------\n W : qobj\n N-qubit W-state\n\n \"\"\"\n inds = np.zeros(N, dtype=int)\n inds[0] = 1\n state = tensor([basis(2, x) for x in inds])\n for kk in range(1, N):\n perm_inds = np.roll(inds, kk)\n state += tensor([basis(2, x) for x in perm_inds])\n return state.unit()\n\n\ndef ghz_state(N=3):\n \"\"\"\n Returns the N-qubit GHZ-state.\n\n Parameters\n ----------\n N : int (default=3)\n Number of qubits in state\n\n Returns\n -------\n G : qobj\n N-qubit GHZ-state\n\n \"\"\"\n state = (tensor([basis(2) for k in range(N)]) +\n tensor([basis(2, 1) for k in range(N)]))\n return state/np.sqrt(2)\n","sub_path":"qutip/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":32423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"81910556","text":"import tensorflow as tf\nfrom keras import backend as K\nfrom tensorflow.python.ops import array_ops\n\ndef generalised_dice_coef(y_true, y_pred, type_weight='Square'):\n \"\"\"\n It computes the generalised dice coefficient\n :param y_true: true labels (ground truth)\n :param y_pred: predicted labels\n :return: generalised dice coefficient score between y_true and y_pred\n \"\"\"\n# print('Y true ** ', y_true.shape)\n# print('Pred shape : ', y_pred.shape)\n# print('Pred max :', tf.reduce_max(y_pred))\n# print('True max :', tf.reduce_max(y_true))\n prediction = tf.cast(y_pred, tf.float32)\n\n ref_vol = tf.reduce_sum(y_true, axis=0)\n intersect = tf.reduce_sum(y_true * prediction, axis=0)\n seg_vol = tf.reduce_sum(prediction, axis = 0)\n\n if type_weight == 'Square':\n weights = tf.reciprocal(tf.square(ref_vol))\n elif type_weight == 'Simple':\n weights = tf.reciprocal(ref_vol)\n elif type_weight == 'Uniform':\n weights = tf.ones_like(ref_vol)\n else:\n raise ValueError(\"The variable type_weight \\\"{}\\\"\"\n \"is not defined.\".format(type_weight))\n\n new_weights = tf.where(tf.is_inf(weights), tf.zeros_like(weights), weights)\n weights = tf.where(tf.is_inf(weights), tf.ones_like(weights) *tf.reduce_max(new_weights), weights)\n\n generalised_dice_numerator = 2 * tf.reduce_sum(tf.multiply(weights, intersect))\n generalised_dice_denominator = tf.reduce_sum(tf.multiply(weights, seg_vol + ref_vol)) + 1e-6\n generalised_dice_score = generalised_dice_numerator / generalised_dice_denominator\n\n return generalised_dice_score\n\ndef gen_dice_multilabel(y_true, y_pred, numLabels=5):\n \"\"\"\n It computes the generalised dice coefficient loss making an average for each class (binary case)\n for a multi-class problem with numLabels classes\n :param y_true: true labels (ground truth)\n :param y_pred: predicted labels\n :param numLabels: number of classes\n :return: dice coefficient loss for a multi-class problem\n \"\"\"\n dice = 0\n for index in range(numLabels):\n dice += generalised_dice_coef(y_true[:,:,:,index], y_pred[:,:,:,index], type_weight='Square')\n return 1. - dice/5.\n\n\ndef focal_loss_softmax(labels,logits,gamma=2):\n \"\"\"\n Computer focal loss for multi classification\n Args:\n labels: A int32 tensor of shape [batch_size].\n logits: A float32 tensor of shape [batch_size,num_classes].\n gamma: A scalar for focal loss gamma hyper-parameter.\n Returns:\n A tensor of the same shape as `lables`\n \"\"\"\n y_pred=tf.nn.softmax(logits,dim=-1) # [batch_size,num_classes]\n labels=tf.one_hot(labels,depth=y_pred.shape[1])\n L=-labels*((1-y_pred)**gamma)*tf.log(y_pred)\n L=tf.reduce_sum(L,axis=1)\n return L\n\ndef seg_loss(y_true, y_pred, loss_weight_divisor=None):\n y_true_flat = K.batch_flatten(y_true)\n y_pred_flat = K.batch_flatten(y_pred)\n y_pred_flat = K.clip(y_pred_flat, K.epsilon(), 1 - K.epsilon())\n\n weight1 = K.sum(K.cast(K.equal(y_true_flat, 1), tf.float32))\n weight1 = K.maximum(weight1, 1) # prevent division by zero\n weight0 = K.sum(K.cast(K.equal(y_true_flat, 0), tf.float32))\n \n weighted_binary_crossentropy = -K.mean(y_true_flat * K.log(y_pred_flat) * weight0 / (weight1 * loss_weight_divisor)\n + (1 - y_true_flat) * K.log(1 - y_pred_flat), axis=-1)\n return weighted_binary_crossentropy\n\n\n\n\ndef dice_coef(y_true, y_pred, smooth = 1.):\n \"\"\"\n It computes the dice coefficient\n :param y_true: true labels (ground truth)\n :param y_pred: predicted labels\n :param smooth: parameter to ensure stability\n :return: dice coefficient score between y_true and y_pred\n \"\"\"\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\n\ndef dice_coef_multilabel(y_true, y_pred, numLabels=5):\n \"\"\"\n It computes the dice coefficient loss making an average for each class (binary case)\n for a multi-class problem with numLabels classes\n :param y_true: true labels (ground truth)\n :param y_pred: predicted labels\n :param numLabels: number of classes\n :return: dice coefficient loss for a multi-class problem\n \"\"\"\n dice = 0\n for index in range(numLabels):\n dice += dice_coef(y_true[:,:,:,index], y_pred[:,:,:,index])\n return 1. - dice/5.\n\n\n","sub_path":"codes/utils/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"574297651","text":"from bs4 import BeautifulSoup\n\nwith open('index4.html', 'r') as file:\n soup = BeautifulSoup(file.read(), 'html.parser')\n try:\n pre_tag = soup.body.find('h1')\n tag = pre_tag.find_next('h6')\n except AttributeError:\n assert()\n assert(\n pre_tag.text.strip() == 'Google Play Terms of Service'\n and tag\n and tag.text.strip() =='February 5, 2018'\n and tag.find_parent('div')\n )\n\n'''\n#components of container - 1\n\nfrom bs4 import BeautifulSoup\n\nwith open('index3.html', 'r') as file:\n soup = BeautifulSoup(file.read(), 'html.parser')\n \n for i in soup.find_all('body'):\n if i.find('div', attrs={'class':'container'}):\n if i.find('img', attrs={'src':'img_google_play.png', 'alt':'Google Play'}):\n if i.find('h1')\n print(\"성공\")\n else:\n print(\"실패\")\n\n#components of container - 2\n\nfrom bs4 import BeautifulSoup\n\nwith open('index3.html', 'r') as file:\n soup = BeautifulSoup(file.read(), 'html.parser')\n \n for i in soup.find_all('body'):\n if i.find('div', attrs={'class':'container'}):\n if i.find('h1') and i.find('h1').get_text() == \"Google Play Terms of Service\":\n print(\"성공\") \n else:\n print(\"실패\")\n'''\n'''\n#components of container - 3\n\nfrom bs4 import BeautifulSoup\n\nwith open('index3.html', 'r') as file:\n soup = BeautifulSoup(file.read(), 'html.parser')\n \n for i in soup.find_all('body'):\n if i.find('div', attrs={'class':'container'}):\n assert(i.find('h6') and i.find('h6').get_text() == \"February 5, 2018\")\n\n\n#개선 할 점\n#TC를 4개로 나누어야 함. \n#TC1: body에 div가 1개 있는지\n#TC2: div에 img가 1개 있는지\n#TC3: div에 img 밑에 h1이 1개 있는지\n#TC4: h1 밑에 h6이 1개 있는지\n'''","sub_path":"lesson_01/step_1/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"66516982","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 19 09:21:39 2016\n\n@author: ericgrimson\n\"\"\"\n\n# def bubble_sort(L):\n# swap = False\n# while not swap:\n# print('bubble sort: ' + str(L)+ ' Inside while: swap='+ str(swap))\n# swap = True\n# for j in range(1, len(L)):\n# print('j= '+str(j) + '. Inside for: swap='+ str(swap))\n# print('(J-1) = '+ str(L[j-1]) + ' vs J = ' + str(L[j]))\n# print('bubble sort: ' + str(L)+ ' Inside for')\n# if L[j-1] > L[j]:\n# swap = False\n# temp = L[j]\n# L[j] = L[j-1]\n# L[j-1] = temp\n# print('bubble sort: ' + str(L)+ ' Outside while: swap='+ str(swap))\n\ntestList = [15,22,1,3,5,7,2,6,25,18,13]\n\n# print('')\n# print(bubble_sort(testList))\n# print(testList)\n\n\ndef selection_sort(L):\n suffixSt = 0\n while suffixSt != len(L):\n print('selection sort: ' + str(L))\n for i in range(suffixSt, len(L)):\n print('i = '+ str(i) + ' vs (L[suffixSt]) =' + str(L[suffixSt]))\n if L[i] < L[suffixSt]:\n L[suffixSt], L[i] = L[i], L[suffixSt]\n print(L[suffixSt])\n suffixSt += 1\n \ntestList = [1,3,5,7,2,6,25,18,13]\n \nprint('')\nprint(selection_sort(testList))\nprint(testList)\n\n\n# def merge(left, right):\n# result = []\n# i,j = 0,0\n# while i < len(left) and j < len(right):\n# if left[i] < right[j]:\n# result.append(left[i])\n# i += 1\n# else:\n# result.append(right[j])\n# j += 1\n# while (i < len(left)):\n# result.append(left[i])\n# i += 1\n# while (j < len(right)):\n# result.append(right[j])\n# j += 1\n# print('merge: ' + str(left) + '&' + str(right) + ' to ' +str(result))\n# return result\n\n# def merge_sort(L):\n# print('merge sort: ' + str(L))\n# if len(L) < 2:\n# return L[:]\n# else:\n# middle = len(L)//2\n# left = merge_sort(L[:middle])\n# right = merge_sort(L[middle:])\n# return merge(left, right)\n \ntestList = [1,3,5,7,2,6,25,18,13]\n\n#print('')\n#print(merge_sort(testList))\n","sub_path":"searching_sorting_12.py","file_name":"searching_sorting_12.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636950600","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('series', '0014_auto_20160113_1728'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='userprofile',\n name='birth_date',\n field=models.DateField(help_text='Your Birthdate will only be shown to other Users with your permission.', verbose_name='Birthdate', default=datetime.datetime(1, 1, 1, 0, 0)),\n ),\n ]\n","sub_path":"series/migrations/0015_auto_20160119_1224.py","file_name":"0015_auto_20160119_1224.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"522272165","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # /fang/\n url(r'^$', views.index, name='index'),\n # ex: /fang/5/\n url(r'^(?P[0-9]+)/$', views.user, name='user'),\n # /fang//desc/\n url(r'^(?P[0-9]+)/desc/$', views.user_desc, name='results'),\n\n #\n url(r'^upload/$', views.upload_file, name='upload')\n]\n","sub_path":"mysite/fang/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525555048","text":"'''1. Write a Python program to sum all the items in a list.\nli=[2,3,6,6,4,5,9,4]\n\nli=(2,3,6,6,4,5,9,4)\n\nprint(\"sum:\",map(lambda x:x+2,li))\nprint(li)\n\nprint(\"sum:\",reduce(lambda x,y:x+y,li))'''\n\nli=(2,3,6,6,4,5,9,4)\nls=[]\n\n'''for x in input:\n if x not in output:\n output.append(x)\n return output'''\n\nfor x in li:\n if x not in ls:\n ls.append(x)\nprint(ls)","sub_path":"lisst.py","file_name":"lisst.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284788278","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThe script monitors a set of Twitter accounts and collects the latest posts. The new posts are consolidated in a CSV file and stored within AWS S3 storage.\nCurrently, for the CS-AWARE project, we started monitoring the accounts listed in users.json and executed this scrip every 8 hours.\nThis solution uses tweepy, an easy-to-use Python library for accessing the Twitter API, that requires a credential set sd in credential.json.\nFinally, the code is written for Python3, anyhow it could be easily adapted for Python2.\n\n@author: Matteo Bregonzio\n\"\"\"\n\nimport sys\nimport tweepy\nimport csv\nimport json\nfrom tweepy import OAuthHandler\nimport os\nimport glob\nimport pandas as pd\nimport datetime\nfrom datetime import date, datetime, timedelta\nimport boto3\n\nfrom stix2 import Bundle, ObservedData, IPv4Address, UserAccount, Bundle\nfrom stix2 import CustomObservable, properties\n\nfrom emojis import remove_emoji\nfrom unidecode import unidecode\n\n@CustomObservable('x-csaware-social', [\n ('source', properties.StringProperty()),\n ('title', properties.StringProperty()),\n ('text', properties.StringProperty()),\n ('subject', properties.StringProperty()),\n])\nclass CSAwareSocial():\n pass\n\n\nBUCKET_NAME = \"cs-aware-data-collection\"\nCREDENTIALS = './credential.json'\nUSERS = './users.json'\nPERIOD = 1 # Number of hours\nPOST_LIMIT = 200\n\n\nnow = datetime.now()\ntoday_str = now.strftime(\"%Y%m%d_%H%M\")\ndate_from = now - timedelta(hours=PERIOD)\n\n\ndef load_customer_conf():\n \"\"\"Loads user credentials\"\"\"\n with open(CREDENTIALS) as f:\n return json.load(f)\n\n\ndef load_screen_names():\n \"\"\"Loads username list\"\"\"\n with open(USERS) as f:\n return json.load(f)\n\n\ndef to_aws(local_filename):\n # Generate remote path\n remote_path = \"%d/%02d/%02d/TWITTER/%s\" % (now.year, now.month, now.day, local_filename)\n print(\"Uploading\", remote_path)\n # Upload to AWS\n with open(local_filename, \"rb\") as f:\n s3 = boto3.resource('s3')\n s3.Object(BUCKET_NAME, remote_path).upload_fileobj(f)\n # Delete local copy\n os.remove(local_filename)\n\n\ndef main():\n #reload(sys)\n #sys.setdefaultencoding(\"ISO-8859-1\")\n\n observed_data_list = []\n\n credential = load_customer_conf()\n user_to_follow = load_screen_names()['user_to_follow']\n df = pd.DataFrame()\n\n user = list(credential)[0]\n consumer_key = credential[user]['consumer_key']\n consumer_secret = credential[user]['consumer_secret']\n access_token = credential[user]['access_token']\n access_secret = credential[user]['access_secret']\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n api = tweepy.API(auth)\n\n for screen_name in user_to_follow:\n print(screen_name)\n try:\n statuses = api.user_timeline(screen_name=screen_name, count=POST_LIMIT)\n except:\n print(\"ERROR: user {} not found\".format(screen_name))\n continue\n\n col0 = [statuses[i].user.name for i in range(len(statuses))]\n col1 = [statuses[i].created_at for i in range(len(statuses))]\n col2 = [statuses[i].text for i in range(len(statuses))]\n col3 = [statuses[i]._json for i in range(len(statuses))]\n \n #print(col2)\n \n df = df.append(pd.DataFrame({\"username\": screen_name.replace(\"@\", \"\"), \"name\":col0, \"date\":col1, \"text\":col2, \"json\":col3 }))\n df = df[df['date'] >= date_from]\n try:\n old_df = pd.read_csv(\"output_{}.csv\".format(today_str))\n except:\n print(\"initialize new file of the day\")\n old_df = pd.DataFrame()\n\n new_df = old_df.append(df)\n new_df.drop_duplicates(['username', 'date'], inplace=True)\n new_df.to_csv(\"output_{}.csv\".format(today_str), index=False, quoting = csv.QUOTE_ALL)\n file_to_write = \"output_{}.csv\".format(today_str) \n print(file_to_write)\n \n for index, row in new_df.iterrows():\n txt = remove_emoji(row['text'], remove_components=True)\n \n \"\"\"\n Replace unicode special characters with the nearest ASCII look-alike.\n See alexis answer (https://stackoverflow.com/a/40692852).\n \"\"\"\n txt = unidecode(txt)\n \n args = {\n 'source': 'twitter',\n 'title': '',\n 'text': txt,\n 'subject': '',\n }\n \n observed_user = UserAccount(type='user-account', user_id=row['username'], display_name=row['name'])\n observed_object = CSAwareSocial(**args, allow_custom=True)\n objects = {\"0\": observed_user, \"1\": observed_object}\n observed_data = ObservedData(first_observed=row['date'], last_observed=row['date'], number_observed=1, objects=objects, allow_custom=True)\n observed_data_list.append(observed_data)\n\n bundle = Bundle(observed_data_list)\n\n stix_filename = file_to_write.replace('.csv', '.json')\n stix_output = open(stix_filename, 'w')\n stix_output.write(bundle.serialize(indent=4))\n stix_output.close()\n\n # Upload to AWS\n to_aws(file_to_write)\n to_aws(stix_filename)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"561044127","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\na = 0\nc = 0\nd = 0\nn = int(input('Digite o valor de n: '))\nwhile n > 0:\n n = n//10\n a = a + 1\nfor i in range (0, a, 1):\n d = d + (n%(10**(c+1))//(10**c))*(2**c)\n c = c + 1\nprint(d)","sub_path":"moodledata/vpl_data/38/usersdata/124/13422/submittedfiles/decimal2bin.py","file_name":"decimal2bin.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"170128381","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\n\n\nclass IFIDepartmentLeave(models.Model):\n\n _inherit = 'hr.department'\n\n leave_approval_user_ids = fields.Many2many('res.users', string='Leave Approval', default=lambda self: self.env.user.employee_ids[0].department_id.manager_id.user_id)\n total_employee = fields.Integer(compute='_compute_total_employee', string='Total Employee')\n\n @api.multi\n def _compute_total_employee(self):\n for department in self:\n department.total_employee = len(department.get_department_employees())\n\n @api.multi\n def write(self, vals):\n res = super(IFIDepartmentLeave, self).write(vals)\n self = self.sudo()\n if vals.get('leave_approval_user_ids', False):\n leave_group = self.env.ref('hr_holidays.group_hr_holidays_user')\n for r in self:\n for i in r.leave_approval_user_ids:\n if not i.has_group('hr_holidays.group_hr_holidays_user'):\n i.groups_id = [(4, leave_group.id)]\n return res\n\n\n","sub_path":"ifi_leaves/models/hr_department.py","file_name":"hr_department.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"36546261","text":"\n\n## input\n#N = 5\n#plans = [\"R\",\"R\",\"R\",\"U\",\"D\",\"D\"]\ndx = [0,0,-1,1]\ndy = [-1,1,0,0]\nmove_types = [\"L\",\"R\",\"U\",\"D\"]\n\ndef implementation1(N,plans):\n x, y = 1, 1\n for plan in plans:\n for i in range(len(move_types)):\n if plan == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 1 or ny < 1 or nx > N or ny > N:\n continue\n x, y = nx, ny\n return nx, ny\n\n# answer is 3, 4\n#print(implementation(N,plans))\n\n## input\n#N = 1\ndef implementation2(N):\n count = 0\n for h in range(N+1):\n for m in range(60):\n for s in range(60):\n if '3' in str(h)+str(m)+str(s):\n count += 1\n return count\n## answer is 3150\n#print(implementation2(1))\n\n## input\n#N = 'a1'\n#x = int(N[1])\n#y = int(ord(N[0])) - int(ord('a')) + 1\ndx = [-1,1,-1,1,-2,-2,2,2]\ndy = [-2,-2,2,2,-1,1,-1,1]\nmove_types = [\"LLU\",\"LLD\",\"RRU\",\"RRD\",\"UUL\",\"UUR\",\"DDL\",\"DDR\"]\n\ndef implementation3(x,y):\n count = 0\n for i in range(len(move_types)):\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 1 or nx > 8 or ny < 1 or ny > 8:\n continue\n count += 1\n return count\n## answer is 2\n#print(implementation3(x,y))\n\n## input\n#input_str = \"K1KA5CB7\"\n\ndef implementation4(input_str):\n number = 0\n alpha = []\n for char in input_str:\n if char.isdigit():\n number += int(char)\n else:\n alpha.append(char)\n alpha.sort()\n return \"\".join(alpha)+str(number) if number > 0 else \"\"\n\n## answer is ABCKK13\n#print(implementation4(input_str))","sub_path":"basic_code/implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29348190","text":"from django.contrib import admin\nfrom myproject.myapp.models import Document\nfrom myproject.myapp.models import Image\n\nclass DocumentAdmin(admin.ModelAdmin):\n fieldsets = [\n (\"Document Name\", {'fields':['Name',]}),\n (\"File\", {'fields':['docfile',]}),\n (\"Date\", {'fields':['upload_date']}),]\n \n list_display = ('Name', 'upload_date')\n list_filter = ['upload_date']\n\nclass ImageAdmin(admin.ModelAdmin):\n\tfieldsets = [\n\t('Image name', {'fields':['Name',]}),\n\t(\"File\",{'fields':['imagefile']}),\n\t(\"Date\", {'fields':['upload_date']}),]\n\t\n\tlist_display = ('Name', 'upload_date')\n\tlist_filter = ['upload_date']\n\t\nadmin.site.register(Document, DocumentAdmin)\nadmin.site.register(Image, ImageAdmin)\n","sub_path":"myproject/myproject/myapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"622525151","text":"import matplotlib\r\nmatplotlib.use(\"TkAgg\")\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nimport cartopy.crs as ccrs\r\n\r\n# https://openavalancheproject.org/#\r\n#\r\n# def data_US_avalanche_Report() -> list:\r\n# \"\"\"Erstellt vier Listen: Longitude, Latitude, Name (der Region), Anzahl\r\n# (der Lawinen je Region. Gibt die beiden Listen Longitude und Latitude\r\n# über return zurück\"\"\"\r\n\r\nfilename = \"../US_avalanche_report\"\r\n\r\nwith open(filename) as f:\r\n US_avalanche_report = json.load(f)\r\navalanches = US_avalanche_report[\"features\"]\r\n\r\n# print(type(US_avalanche_report))\r\n# print(US_avalanche_report.keys())\r\n# print(len(US_avalanche_report[\"features\"]))\r\n\r\nlons, lats = [], []\r\n\r\nfor avalanche in avalanches: # erstellt Liste \"lons\" und \"lats\"\r\n for key_1, value_1 in avalanche.items():\r\n if key_1 == \"geometry\":\r\n for key_2, value_2 in value_1.items():\r\n if key_2 == \"coordinates\":\r\n val2 = value_2[0]\r\n for i in val2:\r\n if isinstance(i[0], float) and isinstance(i[1], float):\r\n lon = i[0]\r\n lat = i[1]\r\n lons.append(lon)\r\n lats.append(lat)\r\n\r\n# print(len(names))\r\n# print(len(amounts))\r\n# print(len(lons))\r\n# print(len(lats))\r\n# print(f\"names: {names[0:5]}.\")\r\n# print(f\"amount: {amounts[0:5]}.\")\r\n# print(f\"lons: {lons[0:5]}.\")\r\n# print(f\"lats: {lats[0:5]}.\")\r\n\r\nax = plt.axes(projection=ccrs.PlateCarree())\r\nax.stock_img()\r\nax.coastlines()\r\n\r\nscatter = ax.scatter(lons, lats, color=\"deepskyblue\", s=20, alpha=1.0, label=\"Lawinenabhänge\\nhttps://openavalancheproject.org/#\", edgecolors=\"dodgerblue\")\r\n\r\nax.set_xlim(-170, 10)\r\nax.set_ylim(-20, 90)\r\nax.legend()\r\n\r\nmng = plt.get_current_fig_manager()\r\nmng.window.showMaximized()\r\n\r\nplt.show()\r\n","sub_path":"save_data_from_gui/Archiv/my_matplotlib.py","file_name":"my_matplotlib.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"105799893","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom setuptools import setup, find_packages\n\nversion = \"0.2.7-dev\"\n\nif sys.argv[-1] == 'tag':\n os.system(\"git tag -a %s -m 'version %s'\" % (version, version))\n os.system(\"git push --tags\")\n sys.exit()\n\nrequirements = [\n 'pandas',\n 'unidecode',\n 'pyyaml',\n 'orderedattrdict',\n 'typing',\n 'cookiecutter',\n 'Click',\n 'daff'\n]\n\nsetup(\n name='ddf_utils',\n version=version,\n description='Commonly used functions/utilities for DDF file model.',\n url='https://github.com/semio/ddf_utils',\n author='Semio Zheng',\n author_email='prairy.long@gmail.com',\n license='MIT',\n packages=find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=requirements,\n entry_points={\n 'console_scripts': [\n 'ddf = ddf_utils.cli:ddf'\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"540992831","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport scipy\nimport scipy.stats\nimport scipy.optimize\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef leer_datos(file_name):\n with open(file_name) as f:\n for n in f:\n yield float(n)\n\nnombre_del_fichero = sys.argv[1]\ny = list(leer_datos(nombre_del_fichero))\nsize = len(y)\nx = list(range(size))\n\nh = plt.hist(y, bins=range(48), color='w')\n\ndist_names = [\n ('truncnorm', [0]),\n ('weibull_min', []),\n ('expon', [])\n]\n\nfor dist_name, params in dist_names:\n dist = getattr(scipy.stats, dist_name)\n param = dist.fit(y, *params)\n print(dist_name, param)\n pdf_fitted = dist.pdf(x, *param[:-2], loc=param[-2], scale=param[-1]) * size\n plt.plot(pdf_fitted, label=dist_name)\n #plt.xlim(0, 50)\nplt.legend(loc='upper right')\nplt.show()\n","sub_path":"entregable 2/sacar-funcion.py","file_name":"sacar-funcion.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456626402","text":"from flask import session\n\n\ndef format_message(message):\n transid = ''\n if 'transaction_id' in session:\n transid = \"T:{}\".format(session['transaction_id'])\n\n userstr = ''\n if 'username' in session:\n userstr = \"U:{}\".format(session['username'])\n\n return \"{} {} {}\".format(transid, userstr, message)\n","sub_path":"application/logformat.py","file_name":"logformat.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"110878324","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 1 16:28:49 2016\n\n@author: katherinebarnhart\n\"\"\"\n\n#%%\n\n#import cProfile, pstats, StringIO\n\nimport datetime\nimport numpy as np\n\nfrom landlab import RasterModelGrid\nfrom matplotlib import pylab as plt\n\nfrom landlab.components import FlowAccumulator\n\nimport cProfile, pstats, io\n\n#%%\n\nn=[]\nactive_links=[]\ntoOne=[]\ntoMultiple=[]\nfor nn in range(2,12):\n \n t0=datetime.datetime.now()\n x=2**nn\n n.append(x**2)\n \n setupTime=datetime.datetime.now()-t0\n \n mg = RasterModelGrid((x,x))\n _ = mg.add_field('topographic__elevation', 2*mg.node_x + mg.node_y, at = 'node')\n fa = FlowAccumulator(mg, flow_director='MFD')\n \n t=datetime.datetime.now()\n fa.run_one_step()\n multidirection_elapsed=datetime.datetime.now()-t \n durations=[multidirection_elapsed.total_seconds()]\n toMultiple.append(np.mean(durations))\n active_links.append(np.sum(mg.at_node['flow__receiver_proportions']>0))\n del mg, fa\n\n\n mg = RasterModelGrid((x,x))\n _ = mg.add_field('topographic__elevation', 2*mg.node_x + mg.node_y, at = 'node')\n fa = FlowAccumulator(mg) \n t2=datetime.datetime.now()\n fa.run_one_step() \n unidirection_elapsed=datetime.datetime.now()-t2\n durations2=[unidirection_elapsed.total_seconds()]\n\n toOne.append(np.mean(durations2)) \n del mg, fa\n \n print(nn, x, x**2 )\n print(datetime.datetime.now())\n print(setupTime)\n print(toOne[-1], toMultiple[-1])\n print(toOne[-1]/n[-1], toMultiple[-1]/active_links[-1], '\\n')\n \n\n\n#%%\nmg = RasterModelGrid((x,x))\n_ = mg.add_field('topographic__elevation', 2*mg.node_x + mg.node_y, at = 'node')\nfa = FlowAccumulator(mg, flow_director='MFD')\n\npr = cProfile.Profile()\npr.enable()\n \nfa.run_one_step() \n\npr.disable()\ns = io.StringIO()\nsortby = 'cumulative'\nps = pstats.Stats(pr, stream=s).sort_stats(sortby)\nps.print_stats()\nprint(s.getvalue())\n\n#%%\nplt.figure()\nplt.semilogx(n, toOne, '.-')\nplt.semilogx(n, toMultiple,'.-')\nplt.xlabel('Number of Nodes')\nplt.ylabel('Total Seconds')\nplt.legend(['Braun and Willet, 2013', 'Multiple Flow Directions'])\nplt.savefig('TotalDuration.pdf')\n\nplt.figure()\nplt.semilogx(n, np.array(toOne)/np.array(n),'.-')\nplt.semilogx(n, np.array(toMultiple)/np.array(n),'.-')\nplt.xlabel('Number of Nodes')\nplt.ylabel('Total Seconds / Number of Nodes')\nplt.legend(['Braun and Willet, 2013', 'Multiple Flow Directions'])\nplt.savefig('Normalized to Nodes.pdf')\n\nplt.figure()\nplt.semilogx(n, np.array(toOne)/np.array(n),'.-')\nplt.semilogx(n, np.array(toMultiple)/np.array(active_links),'.-')\nplt.xlabel('Number of Nodes')\nplt.ylabel('Total Seconds/Number of Active Links')\nplt.legend(['Braun and Willet, 2013', 'Multiple Flow Directions'])\nplt.savefig('NormalizedToLinks.pdf')\n\nplt.figure()\nplt.semilogx(n, (np.array(toMultiple)/np.array(active_links))/(np.array(toOne)/np.array(n)),'.-')\nplt.ylabel('Normalized Preformance Difference')\nplt.xlabel('Number of Nodes')\nplt.savefig('NormalizedPreformance.pdf')\n","sub_path":"testingAccumulatorSpeed.py","file_name":"testingAccumulatorSpeed.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"73128072","text":"import os\nimport sys\nfrom datetime import datetime, timedelta\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nfrom . import session\nfrom .. import test\nfrom .. import lib\nfrom .. import paths\nfrom ..configuration import IrodsConfig\nfrom ..controller import IrodsController\n\nclass Test_Misc(session.make_sessions_mixin([('otherrods', 'rods')], []), unittest.TestCase):\n\n plugin_name = IrodsConfig().default_rule_engine_plugin\n\n def setUp(self):\n super(Test_Misc, self).setUp()\n self.admin = self.admin_sessions[0]\n\n def tearDown(self):\n super(Test_Misc, self).tearDown()\n\n @unittest.skipIf(test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_invalid_client_irodsProt_handled_cleanly__issue_4130(self):\n env = os.environ.copy()\n env['irodsProt'] = '2'\n out, err, ec = lib.execute_command_permissive(['ils'], env=env)\n self.assertTrue('Invalid protocol value.' in err)\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_disallow_registration_of_path_with_missing_data_object_name__issue_4494(self):\n config = IrodsConfig()\n core_re_path = os.path.join(config.core_re_directory, 'core.re')\n\n with lib.file_backed_up(core_re_path):\n with open(core_re_path, 'a') as core_re:\n core_re.write('''\n test_registration_issue_4494 {{ \n *lpath = '{0}';\n *ppath = '';\n msiPhyPathReg(*lpath, 'null', *ppath, 'null', *status);\n }}\n '''.format(self.admin.session_collection + '/'))\n\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n self.admin.assert_icommand(['irule', '-r', rep, 'test_registration_issue_4494', 'null', 'ruleExecOut'],\n 'STDERR', ['-317000 USER_INPUT_PATH_ERR'])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_disallow_creation_of_collections_with_path_navigation_elements_as_the_name__issue_4750(self):\n config = IrodsConfig()\n core_re_path = os.path.join(config.core_re_directory, 'core.re')\n\n with lib.file_backed_up(core_re_path):\n with open(core_re_path, 'a') as core_re:\n core_re.write('''\n test_dot_issue_4750 {{ \n *path = '{0}';\n *recursive = 0;\n msiCollCreate(*path, *recursive, *status);\n }}\n\n test_dot_dot_issue_4750 {{ \n *path = '{1}';\n *recursive = 0;\n msiCollCreate(*path, *recursive, *status);\n }}\n\n test_slash_slash_issue_4750 {{ \n *path = '{2}';\n *recursive = 0;\n msiCollCreate(*path, *recursive, *status);\n }}\n '''.format(self.admin.session_collection + '/.',\n self.admin.session_collection + '/..',\n self.admin.session_collection + '//'))\n\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n\n for rule in ['test_dot_issue_4750', 'test_dot_dot_issue_4750']:\n self.admin.assert_icommand(['irule', '-r', rep, rule, 'null', 'ruleExecOut'], 'STDERR', ['-317000 USER_INPUT_PATH_ERR'])\n\n self.admin.assert_icommand(['irule', '-r', rep, 'test_slash_slash_issue_4750', 'null', 'ruleExecOut'],\n 'STDERR', ['-809000 CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME'])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_catalog_reflects_truncation_on_open__issues_4483_4628(self):\n config = IrodsConfig()\n core_re_path = os.path.join(config.core_re_directory, 'core.re')\n\n with lib.file_backed_up(core_re_path):\n filename = os.path.join(self.admin.local_session_dir, 'truncated_file')\n lib.make_file(filename, 1024, 'arbitrary')\n self.admin.assert_icommand(['iput', filename])\n\n with open(core_re_path, 'a') as core_re:\n core_re.write('''\n test_truncate_on_open_4483_4628 {{ \n *path = '{0}';\n *ec = 0;\n\n msiDataObjOpen('objPath=*path++++openFlags=O_WRONLYO_TRUNC', *fd);\n\n msiSplitPath(*path, *parent_path, *data_object);\n foreach (*row in select DATA_SIZE where COLL_NAME = *parent_path and DATA_NAME = *data_object) {{\n if (*row.DATA_SIZE != '0') {{\n *ec = -1;\n }}\n }}\n\n msiDataObjClose(*fd, *status);\n\n *ec;\n }}\n '''.format(os.path.join(self.admin.session_collection, os.path.basename(filename))))\n\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n self.admin.assert_icommand(['irule', '-r', rep, 'test_truncate_on_open_4483_4628', 'null', 'ruleExecOut'])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_return_error_on_incompatible_open_flags__issue_4782(self):\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n rule = \"msiDataObjOpen('objPath=++++openFlags=O_RDONLYO_TRUNC', *fd)\"\n self.admin.assert_icommand(['irule', '-r', rep, rule, 'null', 'ruleExecOut'], 'STDERR', ['-404000 USER_INCOMPATIBLE_OPEN_FLAGS'])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_trailing_slashes_are_removed_when_creating_collections__issue_3892(self):\n collection = os.path.join(self.admin.session_collection, 'col_3892.d')\n self.admin.assert_icommand(['imkdir', collection])\n\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n rule = 'msiCollCreate(\"{0}\", 0, *ignored)'.format(collection + '/')\n self.admin.assert_icommand(['irule', '-r', rep, rule, 'null', 'ruleExecOut'], 'STDERR', ['-809000 CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME'])\n\n def test_trailing_slashes_generate_an_error_when_opening_data_objects__issue_3892(self):\n data_object = os.path.join(self.admin.session_collection, 'dobj_3892')\n\n rep = 'irods_rule_engine_plugin-irods_rule_language-instance'\n rule = 'msiDataObjOpen(\"objPath={0}++++openFlags=O_WRONLYO_TRUNC\", *fd)'.format(data_object + '/')\n self.admin.assert_icommand(['irule', '-r', rep, rule, 'null', 'ruleExecOut'], 'STDERR', ['-317000 USER_INPUT_PATH_ERR'])\n\n rule = 'msiDataObjCreate(\"{0}\", \"\", *out)'.format(data_object + '/')\n self.admin.assert_icommand(['irule', '-r', rep, rule, 'null', 'ruleExecOut'], 'STDERR', ['-317000 USER_INPUT_PATH_ERR'])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_return_error_on_resolution_of_empty_hostname__issue_5085(self):\n resource = 'issue_5085_resc'\n\n try:\n start = datetime.now()\n self.admin.assert_icommand(['iadmin', 'mkresc', resource, 'replication', ':'], 'STDOUT', [\"'' is not a valid DNS entry\"])\n self.assertLess(datetime.now() - start, timedelta(seconds=5))\n finally:\n self.admin.assert_icommand(['iadmin', 'rmresc', resource])\n\n @unittest.skipIf(plugin_name == 'irods_rule_engine_plugin-python' or test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_server_removes_leftover_temporary_rulebase_pid_files_on_startup__issue_5224(self):\n # Create the rulebase file and three leftover rulebase PID files.\n rulebase_filename = os.path.join(paths.config_directory(), 'leftover_rulebase.re')\n pid_file_1 = rulebase_filename + '.101'\n pid_file_2 = rulebase_filename + '.202'\n pid_file_3 = rulebase_filename + '.303'\n for fn in [rulebase_filename, pid_file_1, pid_file_2, pid_file_3]:\n lib.make_file(fn, 1, 'arbitrary')\n\n # Verify that the rulebase files exist.\n for fn in [rulebase_filename, pid_file_1, pid_file_2, pid_file_3]:\n self.assertTrue(os.path.isfile(fn))\n\n # Add the rulebase to the rulebase list.\n config = IrodsConfig()\n\n with lib.file_backed_up(config.server_config_path):\n found_nrep = False\n for rep in config.server_config['plugin_configuration']['rule_engines']:\n if rep['plugin_name'] == 'irods_rule_engine_plugin-irods_rule_language':\n found_nrep = True\n filename = os.path.basename(rulebase_filename)\n rep['plugin_specific_configuration']['re_rulebase_set'].append(os.path.splitext(filename)[0])\n lib.update_json_file_from_dict(config.server_config_path, config.server_config)\n break\n\n # Make sure that the NREP was updated.\n self.assertTrue(found_nrep)\n\n # Restart the server. On startup, the PID files will be removed.\n IrodsController().restart(test_mode=True)\n\n # Verify that the original rulebase file exists and that the PID files were removed.\n self.assertTrue(os.path.isfile(rulebase_filename))\n for fn in [pid_file_1, pid_file_2, pid_file_3]:\n self.assertFalse(os.path.exists(fn))\n\n @unittest.skipIf(test.settings.RUN_IN_TOPOLOGY, \"skip for topology testing\")\n def test_server_respawns_processes__issue_4977(self):\n import psutil\n import time\n from collections import defaultdict\n main_server = None\n sescoln = self.admin.session_collection\n # Find the main server process\n for proc in psutil.process_iter():\n # It won't have any parents.\n if proc.name() == 'irodsServer' \\\n and proc.parent().name() != 'irodsServer':\n main_server = proc\n # Kill the agent factory and the rule server\n for child in proc.children(recursive=True):\n child.kill()\n break\n #It should run every 5 seconds but it's probably best to wait a lot longer just in case\n time.sleep(15)\n object_name = sescoln+\"/hello\"\n self.assertTrue(len(main_server.children()) >= 2)\n # If the API is up after this it seems it should be entirely working.\n self.admin.assert_icommand(['itouch', object_name])\n seen_process_names = defaultdict(int)\n for i in main_server.children():\n seen_process_names[i.name()] += 1\n # There should only be a single delay server instance\n self.assertTrue(seen_process_names['irodsReServer'] == 1)\n self.assertTrue(seen_process_names['irodsServer'] == 1)\n attribute = \"a1\"\n # Test the delay server\n self.admin.assert_icommand(['irule', '-r',\n \"irods_rule_engine_plugin-irods_rule_language-instance\",\n 'delay(\"irods_rule_engine_plugin-irods_rule_language-instance\") {{ msiModAVUMetadata(\"-d\", \"{0}\", \"add\", \"{1}\", \"v1\", \"u2\") }}'.format(object_name, attribute),\n 'null',\n 'ruleExecOut'])\n\n # Wait for the delay server to process the rule\n time.sleep(45)\n self.admin.assert_icommand('imeta ls -d %s' % (object_name), 'STDOUT_SINGLELINE', ['attribute: ' + attribute])\n self.admin.assert_icommand(['irm', \"-f\", 'hello'])\n","sub_path":"scripts/irods/test/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":12125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"218468451","text":"#main script\ntry:\n\timport hashlib\n\timport custom_cipher\n\timport silent_input\n\timport sys\n\thash1=hashlib.sha1\nexcept ImportError:\n\tprint(\"one or more of the dependent modules could not be found\")\n\ndef quit_check(user_input):\n\tif user_input == \"q\": sys.exit(0) #quit\n\n##login##\nprint(\"\\n\\nwelcome to chat-safe\\n\")\nprint(\"select a mode:\")\nprint(\"[1]\\tP2P\\n[2]\\tPrint to file\")\n\nsupported_modes=set([1,2]);\nwhile True:\n\tmode=input(\"\\n\")\n\tquit_check(mode)#quit if q\n\tif not mode.isnumeric(): #not number\n\t\tprint(\"Please enter the number of the mode you wish to select\")\n\t\tcontinue\n\telse:\n\t\tif len(supported_modes.intersection(set([int(mode)])))==1: #good choice\n\t\t\tbreak\n\t\telse: #not good choice\n\t\t\tprint(\"Please enter the number of the mode you wish to select\")\n##enter username\n##enter keyword\n##select send or receive (for now)\n##initialize appropriate header file\n##login##\n\n##sender##\n#get keyword for message\n#read in message as typed\n#add username to message\n#hash message\n#custom encode message\n#pair message and autheticator\n#send\n##sender##\n\n##receiver##\n#input keyword\n#listen for message\n#split hash and encoded messsage\n#decode message with keyword\n#hash message and keyword\n#compare reciever and sender side hash\n#report decoded message\n#report authenticated or not\n##receiver##\n","sub_path":"chat-safe.py","file_name":"chat-safe.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57964971","text":"from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi, sqrt, log, pi, exp, log10\nimport math\nfrom math import e\nimport sys \nsys.path.append('..')\nimport mapOnRectangle as mor\nfrom fwdProblem import *\nfrom invProblem2d import *\nfrom rectangle import *\nimport smtplib\nfrom email.mime.text import MIMEText\n\nrect = Rectangle((0,0), (1,1), resol=7)\ngamma = 0.01\n\ndef myUTruth(x, y):\n\t\t\"\"\"if x[0] <= 0.5 +tol and x[0] >= 0.45 - tol and x[1] <= 0.5+tol:\n\t\t\treturn -4\n\t\telif x[0] <= 0.5+tol and x[0] >= 0.45 - tol and x[1] >= 0.6 - tol:\n\t\t\treturn -4\n\t\telif x[0] <= 0.75 + tol and x[0] >= 0.7 - tol and x[1] >= 0.2 - tol and x[1] <= 0.8+tol:\n\t\t\treturn 2\n\t\telse:\n\t\t\treturn 0\"\"\"\n\t\t#if x.ndim == 1 and x.shape[0] == 2:\n\t\treturn -4/log10(e)*np.logical_or(np.logical_and(np.logical_and(x < 0.5, x >= 0.4375), y < 0.5), np.logical_and(np.logical_and( x< 0.5 , x >= 0.4375) ,y >= 0.625 - tol)) + 2/log10(e)*np.logical_and(np.logical_and(x < 0.8125, x >= 0.75), np.logical_and(y >= 0.1875, y < 0.75)) + 0\n\ndef myUTruth2(x, y):\n\treturn np.logical_and(np.logical_and((x-1)**2 + y**2 <= 0.65**2, (x-1)**2 + y**2 > 0.55**2), x<0.85)*-2/log10(e) + np.sin(4*x)*0.5/log10(e) - 4/log10(e)*np.logical_and(np.logical_and( x< 0.5 , x >= 0.4375) ,y >= 0.625 - tol) \n\t\ndef u_D_term(x, y):\n\treturn np.logical_and(x <= 0.01, True)*0.0\n\nu_D = mor.mapOnRectangle(rect, \"handle\", lambda x,y: u_D_term(x,y))\n\ndef boundary_D_boolean(x): # special Dirichlet boundary condition\n\t\tif x[0] <= tol:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nf = mor.mapOnRectangle(rect, \"handle\", lambda x, y: (((x-.8)**2 + (y-.2)**2) < 0.2**2)*(20.0))\n\nfwd = linEllipt2dRectangle(rect, f, u_D, boundary_D_boolean)\nm1 = GeneralizedGaussianWavelet2d(rect, 0.1, 1.5, 7)\ninvProb = inverseProblem(fwd, m1, gamma)\n\n\nN_obs = 500\nobspos = np.random.uniform(0, 1, (2, N_obs))\nobspos = [obspos[0,:], obspos[1, :]]\ninvProb.obspos = obspos\n\n#uTruth = mor.mapOnRectangle(rect, \"wavelet\", packWavelet(unitvec(4, 2)+0.5*unitvec(4,3)))\n#uTruth = m1.sample()\nuTruth = mor.mapOnRectangle(rect, \"handle\", lambda x, y: myUTruth2(x, y))\n\nobs = invProb.Gfnc(uTruth) + np.random.normal(0, gamma, (N_obs,))\ninvProb.plotSolAndLogPermeability(uTruth, obs=obs, save=\"ground_truth.png\")\ninvProb.obs = obs\n#u0 = mor.mapOnRectangle(rect, \"wavelet\", m1._mean)\nu0 = mor.mapOnRectangle(rect, \"wavelet\", m1._mean)\n#uOpt = invProb.find_uMAP(u0, nit=3, method='BFGS', adjoint=False)\nstart=time.time()#\nuOpt_adj = invProb.find_uMAP(u0, nit=200, method = 'BFGS', adjoint=True, version=0)\n#uOpt_adj = invProb.find_uMAP(uOpt_adj, nit=200, method = 'BFGS', adjoint=True, version=0)\nend=time.time()\nprint(\"Optimization took \" + str(end-start) + \" seconds\")\ninvProb.plotSolAndLogPermeability(uOpt_adj, obs=obs)\n\n\"\"\"\nu = uOpt_adj\nh = (m1.sample()) - uOpt_adj\ninvProb.plotSolAndLogPermeability(u+h, obs=obs)\n\nFu = invProb.Ffnc(u)\nFu_ = invProb.Ffnc(u, pureFenicsOutput=True)\n\nvtkfile = File('solution.pvd')\nvtkfile << Fu_\n\nf = invProb.fwd\nV = f.V\nmesh = f.mesh\n\n\nkappa = mor.mapOnRectangle(invProb.rect, \"handle\", lambda x,y: np.exp(u.handle(x,y)))\nkappa1 = mor.mapOnRectangle(invProb.rect, \"handle\", lambda x,y: np.exp(u.handle(x,y))*h.handle(x,y))\nif isinstance(kappa, mor.mapOnRectangle):\n\tk = morToFenicsConverter(kappa, invProb.fwd.mesh, invProb.fwd.V)\n\nif isinstance(kappa1, mor.mapOnRectangle):\n\tk1 = morToFenicsConverter(kappa1, invProb.fwd.mesh, invProb.fwd.V)\n\n\nw = TrialFunction(V)\nv = TestFunction(V)\nL = -k1*dot(grad(Fu_), grad(v))*dx\na = k*dot(grad(w), grad(v))*dx\n\nwSol = Function(V)\nsolve(a == L, wSol, DirichletBC(invProb.fwd.V, Constant(0), invProb.fwd.boundary_markers, 1))\nvals = np.reshape(wSol.compute_vertex_values(), (2**invProb.rect.resol+1, 2**invProb.rect.resol+1))\nDp = mor.mapOnRectangle(invProb.rect, \"expl\", vals[0:-1,0:-1])\nvtkfile = File('solution_temp.pvd')\nvtkfile << wSol\n\nDG_of_u_h = Dp.handle(obspos[0], obspos[1])\n\ndiscrepancy = obs - Fu.handle(obspos[0], obspos[1])\nprimalDPhi = -1.0/(gamma**2)*np.dot(discrepancy, DG_of_u_h)\nweights = -discrepancy/gamma**2\n\nwtilde = TrialFunction(V)\nv = TestFunction(V)\nL2 = Constant(0)*v*dx\na2 = a\n\nA2, b2 = assemble_system(a2, L2, DirichletBC(invProb.fwd.V, Constant(0), invProb.fwd.boundary_markers, 1))\n\n\nfor l, weight in enumerate(weights):\n\td = PointSource(V, Point(obspos[0][l], obspos[1][l]), weight)\n\td.apply(b2)\n\nwtildeSol = Function(V)\nsolve(A2, wtildeSol.vector(), b2)\nvtkfile = File('solution_temptilde.pvd')\nvtkfile << wtildeSol\n\n\ndualDPhi = -assemble(k1*dot(grad(Fu_),grad(wtildeSol))*dx)\nfnc = project(k*dot(grad(Fu_), grad(wtildeSol)), V)\nvtkfile = File('fnc.pvd')\nvtkfile << fnc\nhh = morToFenicsConverter(h, invProb.fwd.mesh, invProb.fwd.V)\nvalsfnc = np.reshape(fnc.compute_vertex_values(), (2**f.rect.resol+1, 2**f.rect.resol+1))\nmorfnc = mor.mapOnRectangle(f.rect, \"expl\", valsfnc[0:-1,0:-1]) #cut vals to fit in rect grid\n\n\nDPhi_dual = invProb.DPhi_adjoint_vec_wavelet(u)\ndef unitwave(N, l):\n\ttemp = np.zeros((N, ))\n\ttemp[l] = 1\n\treturn mor.mapOnRectangle(f.rect, \"wavelet\", packWavelet(temp))\n\n\"\"\"\n\"\"\"\n\n\n\nprint(primalDPhi)\nprint(invProb.DPhi(u, h))\nprint(dualDPhi)\nprint(invProb.DPhi_adjoint(u, h))\n\n\n# trying to improve DPhi_adjoint\npermObspos = kappa.handle(obspos[0], obspos[1])\n\nl1 = [ind for ind in range(len(permObspos)) if permObspos[ind] > 200]\nl2 = [ind for ind in range(len(permObspos)) if permObspos[ind] <= 200]\n\nweights1 = weights[l1]\nweights2 = weights[l2]\npos1_x = obspos[0][l1]\npos1_y = obspos[1][l1]\npos2_x = obspos[0][l2]\npos2_y = obspos[1][l2]\npos3_x = obspos[0][:]\npos3_y = obspos[1][:]\n\nwtilde = TrialFunction(V)\nv = TestFunction(V)\nL2 = Constant(0)*v*dx\na2 = k*dot(grad(w), grad(v))*dx\n\n\nA2_1, b2_1 = \tassemble_system(a2, L2, DirichletBC(invProb.fwd.V, Constant(0), invProb.fwd.boundary_markers, 1))\nA2_2, b2_2 = \tassemble_system(a2, L2, DirichletBC(invProb.fwd.V, Constant(0), invProb.fwd.boundary_markers, 1))\nA2_3, b2_3 = \tassemble_system(a2, L2, DirichletBC(invProb.fwd.V, Constant(0), invProb.fwd.boundary_markers, 1))\n\nfor l, weight in enumerate(weights1):\n\td = PointSource(V, Point(pos1_x[l], pos1_y[l]), weight)\n\td.apply(b2_1)\n\nfor l, weight in enumerate(weights2):\n\td = PointSource(V, Point(pos2_x[l], pos2_y[l]), weight)\n\td.apply(b2_2)\n\nfor l, weight in enumerate(weights):\n\td = PointSource(V, Point(pos3_x[l], pos3_y[l]), weight)\n\td.apply(b2_3)\n\n\n\t\nwtildeSol1 = Function(V)\nsolve(A2_1, wtildeSol1.vector(), b2_1)\nwtildeSol2 = Function(V)\nsolve(A2_2, wtildeSol2.vector(), b2_2)\nwtildeSol3 = Function(V)\nsolve(A2_3, wtildeSol3.vector(), b2_3)\n\n\n\n\n\n-assemble(k1*dot(grad(Fu_),grad(wtildeSol1))*dx)-assemble(k1*dot(grad(Fu_),grad(wtildeSol2))*dx)\"\"\"\n\n\n\n\n\n\n\"\"\"m2 = GaussianFourier2d(rect, np.zeros((11,11)), 1.0, 1.0)\ninvProb2 = inverseProblem(fwd, m2, gamma, obspos, obs)\nu0_fourier = mor.mapOnRectangle(rect, \"fourier\", np.zeros((11,11)))\nuOpt_fourier = invProb2.find_uMAP(u0_fourier, nit=100, nfev=100)\"\"\"\n\n#uList, uListUnique, PhiList = invProb.randomwalk_pCN(u0, 1000)\n#u_new, u_new_mean, us, vals, vals_mean = invProb.EnKF(obs, 50, KL=False, N = 10, beta = 0.05)\n#plt.figure(); plt.semilogy(PhiList)\n#invProb.plotSolAndLogPermeability(uList[-1])\n\"\"\"plt.figure();\nplt.semilogy(vals)\nplt.semilogy(vals_mean, 'r', linewidth=4)\ninvProb.plotSolAndLogPermeability(u_new_mean)\"\"\"\n\n\n\"\"\"Is = []\nhvals = np.linspace(-1,1,200)\n\nfor k in range(16):\n\td = mor.mapOnRectangle(rect, \"wavelet\", packWavelet(unitvec(16, k)))\n\tIs.append([invProb.I(u_new_mean + d*h) for h in hvals])\n\nplt.figure()\nfor k in range(16):\n\tplt.subplot(4,4,k+1)\n\tplt.plot(hvals, Is[k])\"\"\"\n","sub_path":"Test/test_invProblem_2d_2a.py","file_name":"test_invProblem_2d_2a.py","file_ext":"py","file_size_in_byte":7535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"194031028","text":"import os\nfrom django.contrib.gis.utils import LayerMapping\nfrom .models import Greenmodel\n\ngreenmodel_mapping = {\n 'pntnum' : 'PntNum',\n 'panoid' : 'panoID',\n 'panodate' : 'panoDate',\n 'greenview' : 'greenView',\n 'url_0' : 'url_0',\n 'url_60' : 'url_60',\n 'url_120' : 'url_120',\n 'url_180' : 'url_180',\n 'url_240' : 'url_240',\n 'url_300' : 'url_300', \n 'geom' : 'MULTIPOINT',\n}\ngreenmodel_shp = os.path.abspath(\n os.path.join(os.path.dirname(__file__), 'data', 'thisgreen.shp'),\n)\n\ndef run(verbose=True):\n lm = LayerMapping(\n Greenmodel, greenmodel_shp, greenmodel_mapping,\n transform=False, encoding='UTF-8',\n )\n lm.save(strict=True, verbose=verbose)\n\n\n\n\n","sub_path":"green/loadgreen.py","file_name":"loadgreen.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233620768","text":"import smbus2 as smbus\nimport time\n\nclass I2C_BASE:\n def __init__(self):\n self.bus=smbus.SMBus(1)\n\nclass FND(I2C_BASE):\n def __init__(self):\n I2C_BASE.__init__(self)\n self.addr=0x20\n self.config_port=0x06\n self.out_port=0x02\n # 0 1 2 3 4 5 6 7 8 9\n self.data=(0xFC,0x60,0xDA,0xF2,0x66,0xB6,0x3E,0xE0,0xFE,0xF6)\n # seg1 seg2 seg3 seg4 seg5 seg6\n self.digit=(0x7f,0xBF,0xDF,0xEF,0xF7,0xFB)\n self.out_disp=0\n def fnd(self,num):\n try:\n self.bus.write_word_data(self.addr,self.config_port,0x0000)\n out_disp=0x0003\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n n1=int(num%10)\n n2=int((num/10)%10)\n n3=int((num/100)%10)\n n4=int((num/1000)%10)\n n5=int((num/10000)%10)\n n6=int((num/100000)%10)\n while True:\n if num!=0:\n out_disp=self.data[n1]<<8 | self.digit[5]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n if n2!=0:\n out_disp=self.data[n2]<<8 | self.digit[4]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n if n3!=0:\n out_disp=self.data[n3]<<8 | self.digit[3]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n if n4!=0: \n out_disp=self.data[n4]<<8 | self.digit[2]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n if n5!=0: \n out_disp=self.data[n5]<<8 | self.digit[1]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n if n6!=0: \n out_disp=self.data[n6]<<8 | self.digit[0]\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n time.sleep(0.00000005)\n #out_disp=self.data[num]<<8 | self.digit[sel+1]\n #self.bus.write_word_data(self.addr,self.out_port,out_disp)\n out_disp=0x0003\n self.bus.write_word_data(self.addr,self.out_port,out_disp)\n\n except KeyboardInterrupt:\n #out_disp=0x03\n #self.bus.write_word_data(self.addr,self.out_port,out_disp)\n pass\nclass LIGHT(I2C_BASE):\n def __init__(self):\n I2C_BASE.__init__(self)\n self.addr=0x23 #조도센서 주소\n self.reset=0x07 #pdf 99페이지에서 확인 가능\n self.con_hr_mode=0x10 #이것도 99페이지에서 확인 가능 모드설정. 민감도?\n\n self.data1=0\n self.data2=0\n self.val=0\n self.light_val=0\n\n def light(self):\n try:\n self.bus.write_byte(self.addr,self.reset) #주소, 데이터\n time.sleep(0.05)\n\n self.bus.write_byte(self.addr,self.con_hr_mode)\n time.sleep(0.2)\n\n self.data1= self.bus.read_byte(self.addr) #데이터 읽어오기\n self.data2=self.bus.read_byte(self.addr)\n self.val=(self.data1<<8)|self.data2 #16비트가 상위 하위로 나눠서 들어오기 떄문에 이렇게 함\n self.light_val=self.val/1.2\n\n print('light_val=%.2f'%self.light_val)\n return self.light_val\n except KeyboardInterrupt:\n #do no anything\n pass\n finally:\n pass\nclass TEM_HUM(I2C_BASE):\n def __init__(self):\n I2C_BASE.__init__(self)\n self.addr=0x40\n self.cmd_temp=0xf3\n self.cmd_humi=0xf5\n self.soft_reset=0xfe\n self.temp=0.0\n self.humi=0.0\n self.val=0\n self.data=[0,0]\n def tem_hum(self):\n try:\n self.bus.write_byte(self.addr,self.soft_reset)\n time.sleep(0.05)\n\n #temp\n self.bus.write_byte(self.addr,self.cmd_temp)\n time.sleep(0.26)\n for i in range(0,2,1):\n self.data[i]=self.bus.read_byte(self.addr)\n self.val=self.data[0]<<8|self.data[1]\n self.temp=-46.85+175.72/65536*self.val\n #hum\n self.bus.write_byte(self.addr,self.cmd_humi)\n time.sleep(0.26)\n for i in range(0,2,1):\n self.data[i]=self.bus.read_byte(self.addr)\n self.val=self.data[0]<<8|self.data[1]\n self.humi=-6.0+125.0/65536*self.val\n print('temp: %.2f, humi: %.2f'%(self.temp,self.humi))\n return self.temp, self.humi\n except KeyboardInterrupt:\n pass\n\n\nif __name__=='__main__':\n f=FND()\n lig=LIGHT()\n t_h=TEM_HUM()\n# lig.light()\n # f.fnd(123456)\n th=t_h.tem_hum()\n \n f.fnd(123456)\n","sub_path":"Ras_I2C.py","file_name":"Ras_I2C.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"88086444","text":"# ##### GENERADORES (generan iteradores) #####\n\n## Uso de yeild / next, y excepcion StopIterator\ndef pares(n):\n for numero in range(n+1):\n if numero % 2 == 0:\n yield numero\n\ngen=pares(2)\nprint(f\"Imprime generados: {next(gen)},{next(gen)}\")\n\ntry:\n next(gen)\nexcept StopIteration:\n print(f\"FIN de la iteracion\")\n\n\n\n\n## Recorrer con bucle:\ndef pares(n):\n for numero in range(n+1):\n if numero % 2 == 0:\n yield numero\nfor num in pares(10):\n print(num)\n\n\n\n\n\n\n# ##### ITERADORES #####\n\n## iter(..): Crear un iterador a traves de una coleccion\nlista = [1,2,3,4,5]\nlista_iterable = iter(lista)\nprint(next(lista_iterable))\nprint(next(lista_iterable))\n","sub_path":"python/ejemploPython/ejemploGeneradoresIteradores.py","file_name":"ejemploGeneradoresIteradores.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"234513949","text":"\"\"\"Functionality for awesome-streamlit.org\"\"\"\nfrom panel.pane import Markdown\n\n\ndef title_awesome(body: str) -> Markdown:\n \"\"\"Writes the title as f'Awesome Panel {body}'\n - plus the awesome badge\n - plus a link to the awesome-panel GitHub page\n\n Arguments:\n body {str} -- [description]\n\n Returns:\n Markdown -- A 'Awesome Panel {body} title with the awesome badge\n \"\"\"\n return Markdown(\n f\"# Awesome Panel {body} \"\n \"![Awesome Badge](https://cdn.rawgit.com/sindresorhus/awesome/\"\n \"d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)\"\n )\n","sub_path":"package/awesome_panel/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"390419971","text":"#!/usr/bin/env python3\nimport sys\n\nclass Node():\n\tdef __init__(self):\n\t\tself.key = None\n\t\tself.pre = 0\n\t\tself.post = 0\n\t\tself.group = None\n\t\tself.adj = None\n\ntopolist = []\ndef dfs(node, v, group):\n\tglobal topolist\n\tdfs.clock += 1\n\tv.pre = dfs.clock\n\tv.group = group\n\tfor w in v.adj:\n\t\t#print(w)\n\t\tif node[w].pre == 0:\n\t\t\tdfs(node, node[w], group)\n\t\telif node[w].pre != 0 and node[w].post == 0:\n\t\t\tdfs.detect_cycle = 1\n\n\tdfs.clock += 1\n\tv.post = dfs.clock\n\ttopolist.append(v.key)\n\ndef toposort(adj):\n\tglobal topolist\n\n\tdfs.detect_cycle = 0\n\tdfs.clock = 0\n\tgroup = 0\n\tnode = []\n\tfor i in range(len(adj)):\n\t\tnode.append(Node())\n\tfor i in range(len(adj)):\n\t\tnode[i].key = i\n\tfor i in range(len(adj)):\n\t\tnode[i].adj = adj[i]\n\n\tfor n in node:\n\t\tif n.pre == 0:\n\t\t\tgroup += 1\n\t\t\tdfs(node, n, group)\n\n\treturn\ttopolist\n\n'''\nclass Node():\n\tdef __init__(self, adj):\n\t\t# color = None, not has been visited\n\t\t# color = 0, has been visited\n\t\t# color = 1, has been backtracked\n\t\tself.color = [None] * len(adj)\n\t\tself.visited = [None] * len(adj) \n\t\tself.tmp = 0\n\t\tself.l = []\n\ndef dfs(adj, v, node):\n\t#print('===')\n\tif node.color[v] == 0:\n\t\tnode.tmp = 1\n\t\treturn 1\n\n\t#print(node.color)\n\t#print(node.visited)\n\t\n\tnode.visited[v] = 0\n\tnode.color[v] = 0\n\tfor w in adj[v]:\n\t\t#print(w)\n\t\t\n\t\tif node.visited[w] is None:\n\t\t\t#print('aaa')\n\t\t\tdfs(adj, w, node)\n\t\telif node.color[w] == 0:\n\t\t\tnode.tmp = 1\n\t\t\treturn 1\n\tnode.color[v] = 1\n\tnode.l.append(v)\n\treturn \n\n\ndef toposort(adj):\n\tnode = Node(adj)\n\tfor index, item in enumerate(node.visited):\n\t\tif item is None:\n\t\t\tif dfs(adj, index, node) == 1:\n\t\t\t\treturn 1\n\treturn node.l\n'''\nif __name__ == '__main__':\n\tinput = sys.stdin.read()\n\tdata = list(map(int, input.split()))\n\tn, m = data[0:2]\n\tdata = data[2:]\n\tedges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))\n\tadj = [[] for _ in range(n)]\n\tfor (a, b) in edges:\n\t\tadj[a - 1].append(b - 1)\n\n\torder = toposort(adj)\n\t#print(order)\n\tfor x in order[::-1]:\n\t\tprint(x + 1, end=' ')\n\n","sub_path":"algorithms_on_graphs/01_toposort.py","file_name":"01_toposort.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"106840455","text":"import sqlite3\r\nfrom time import sleep as sl\r\nconnection = sqlite3.connect('assist.db')\r\nc = connection.cursor()\r\n\r\ndef create_table():\r\n c.execute('CREATE TABLE IF NOT EXISTS gastos(nome text, valor real)')\r\n c.execute('CREATE TABLE IF NOT EXISTS receitas(nome text, valor real)')\r\n return True\r\n\r\ndef insert_gastos(nome,valor):\r\n c.execute(\"INSERT INTO gastos(nome,valor) VALUES(?,?)\",(nome,valor))\r\n connection.commit()\r\n return True\r\n \r\ndef insert_receitas(nome,valor):\r\n c.execute('INSERT INTO receitas(nome,valor) VALUES(?,?)',(nome,valor))\r\n connection.commit()\r\n return True\r\n\r\ndef ler_gastos():\r\n sql = 'SELECT * FROM gastos'\r\n itens=[]\r\n for linha in c.execute(sql):\r\n itens.append(linha)\r\n return itens\r\n\r\ndef ler_receitas():\r\n sql = 'SELECT * FROM receitas'\r\n itens=[]\r\n for linha in c.execute(sql):\r\n itens.append(linha)\r\n return itens\r\n","sub_path":"assistV1.1/bd.py","file_name":"bd.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"394943944","text":"from rasa.core.channels.channel import RestInput, UserMessage, CollectingOutputChannel\nimport inspect\nfrom asyncio import CancelledError\nfrom sanic import Blueprint, response\nfrom sanic.request import Request\nfrom typing import Text, Callable, Awaitable\nfrom sanic.log import logger\nimport rasa.utils.endpoints\nfrom sanic.response import HTTPResponse\n\n\nclass MyRestInput(RestInput):\n \"\"\"自定义渠道\"\"\"\n\n @classmethod\n def name(cls) -> Text:\n return \"my_channel\"\n\n def blueprint(\n self, on_new_message: Callable[[UserMessage], Awaitable[None]]\n ) -> Blueprint:\n custom_webhook = Blueprint(\n \"custom_webhook_{}\".format(type(self).__name__),\n inspect.getmodule(self).__name__,\n )\n\n # noinspection PyUnusedLocal\n @custom_webhook.route(\"/\", methods=[\"GET\"])\n async def health(request: Request) -> HTTPResponse:\n return response.json({\"status\": \"ok\"})\n\n @custom_webhook.route(\"/webhook\", methods=[\"POST\"])\n async def receive(request: Request) -> HTTPResponse:\n sender_id = await self._extract_sender(request)\n text = self._extract_message(request)\n should_use_stream = rasa.utils.endpoints.bool_arg(\n request, \"stream\", default=False\n )\n input_channel = self._extract_input_channel(request)\n metadata = self.get_metadata(request)\n\n if should_use_stream:\n return response.stream(\n self.stream_response(\n on_new_message, text, sender_id, input_channel, metadata\n ),\n content_type=\"text/event-stream\",\n )\n else:\n collector = CollectingOutputChannel()\n # noinspection PyBroadException\n try:\n await on_new_message(\n UserMessage(\n text,\n collector,\n sender_id,\n input_channel=input_channel,\n metadata=metadata,\n )\n )\n except CancelledError:\n logger.error(\n \"Message handling timed out for \"\n \"user message '{}'.\".format(text)\n )\n except Exception:\n logger.exception(\n \"An exception occured while handling \"\n \"user message '{}'.\".format(text)\n )\n return response.json(collector.messages)\n\n return custom_webhook\n","sub_path":"channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"334490164","text":"#!/usr/bin/env python\n\nimport sys\n'''\nDescription: A program to parse the Task Expression Language\nOutput => A preorder tree traversal and a YAML file\n'''\n\nSymbol = str\n\n#Preposition offsets\ndef get_offsets(word):\n offset_dict = {\n '' : [0, 0, 0],\n 'on' : [0.330056,0.354265,0.028489],\n 'onto' : [0.292087,0.016732,-0.015673],\n 'in+front+of' : [0.718193,-0.298247,0.990027],\n 'on_l' : [0.250604,-0.04831,0.004393],\n 'on_r' : [0.26528,0.272534,0.011394] \n }\n return offset_dict[word]\n\n# Tokenize the input stream of characters based on the language\ndef tokenize(chars):\n return chars.replace('(', ' ( ').replace(')', ' ) ').split()\n\ndef read_from_tokens(tokens):\n if len(tokens) == 1:\n raise SyntaxError('Unexpected EOF while reading')\n token = tokens.pop(0)\n if '(' == token:\n L = []\n while tokens[0] != ')':\n L.append(read_from_tokens(tokens))\n tokens.pop(0)\n return L\n elif ')' == token:\n raise SyntaxError('Unexpected [)] symbol')\n else:\n return atom(token)\n\ndef atom(token):\n try: return int(token)\n except ValueError:\n try: return float(token)\n except ValueError:\n return Symbol(token)\n\n# Parse the input character stream and output syntax tree\ndef parse(program):\n program = \"(ROOT\" + program + \")\"\n return read_from_tokens(tokenize(program))\n\nclass Env(dict):\n \"An environment: a dict of {'var':val} pairs, with an outer Env.\"\n def __init__(self, parms=(), args=(), outer=None):\n self.update(zip(parms, args))\n self.outer = outer if outer else {}\n def find(self, var):\n \"Find the innermost Env where var appears.\"\n return self if (var in self) else None\n\n\ndef CreateRootObject(robot_id, node_id, parent='NONE'):\n return TaskObject('ROOT', 4, robot_id, node_id, parent)\n\ndef CreateThenObject(robot_id, node_id, parent):\n return TaskObject('THEN', 0, robot_id, node_id, parent)\n\ndef CreatePlaceObject(robot_id, node_id, parent):\n return PlaceObject('PLACE', 6, robot_id, node_id, parent)\n\ndef CreateAndObject(robot_id, node_id, parent):\n return TaskObject('AND', 2, robot_id, node_id, parent)\n\ndef CreateOrObject(robot_id, node_id, parent):\n return TaskObject('OR', 1, robot_id, node_id, parent)\n\n\nclass TaskObject(object):\n def __init__(self, name='', node_type=0, robot_id=0, node_id=0, parent=''):\n self.node_type = node_type\n self.robot_id = robot_id\n self.node_id = node_id\n self.name = '%s_%d_%d_%03d' % (name, node_type, robot_id, node_id)\n self.children = ['NONE']\n self.parent = parent\n self.peers = ['NONE']\n\n def __call__(self, *args):\n self.children = [child.name for child in args]\n print(self)\n return self\n\n def __repr__(self):\n string = (\n '%(name)s:\\n'\n ' mask:\\n'\n ' type: %(node_type)d\\n'\n ' robot: %(robot_id)d\\n'\n ' node: %(node_id)d\\n'\n ' parent: %(parent)s\\n'\n ' children: %(children)s\\n'\n ' peers: %(peers)s'\n % {\n 'name': self.name,\n 'node_type': self.node_type,\n 'robot_id': self.robot_id,\n 'node_id': self.node_id,\n 'parent': self.parent,\n 'children': self.children,\n 'peers': self.peers\n }\n )\n return string\n\nclass PlaceObject(TaskObject):\n def __init__(self, name='', node_type=0, robot_id=0, node_id=0, parent=''):\n super(PlaceObject, self).__init__(name, node_type, robot_id, node_id, parent)\n self.place_object = ''\n self.dest_object = ''\n self.off_x = 0.0\n self.off_y = 0.0\n self.off_z = 0.0\n\n def __call__(self, item, dest = \"\", prep = \"\"):\n self.place_object = item\n self.dest_object = dest\n offsets = get_offsets(prep)\n self.off_x = offsets[0]\n self.off_y = offsets[1]\n self.off_z = offsets[2]\n print(self)\n return self\n\n def __repr__(self):\n parent_str = super(PlaceObject, self).__repr__()\n string = ( \n '%(parentString)s\\n' \n ' object: %(object)s\\n' \n ' loc_obj: %(location)s\\n' \n ' off_x: %(offset_x)3.6f\\n' \n ' off_y: %(offset_y)3.6f\\n' \n ' off_z: %(offset_z)3.6f' \n % { \n 'parentString': parent_str, \n 'object': self.place_object, \n 'location': self.dest_object, \n 'offset_x': self.off_x,\n 'offset_y': self.off_y, \n 'offset_z': self.off_z \n } \n ) \n return string\n\ndef standard_env():\n env = Env()\n env.update({\n\n 'THEN': CreateThenObject,\n 'PLACE': CreatePlaceObject,\n 'AND': CreateAndObject,\n 'OR': CreateOrObject,\n 'ROOT': CreateRootObject,\n })\n return env\nglobal_env = standard_env()\n\n# \"Evaluate an expression in an environment.\"\ndef eval(x, env=global_env, func_index=[0], parent=\"'NONE'\"):\n if isinstance(x, Symbol): # x is a string\n if env.find(x):\n value = env.find(x)[x](0, func_index[0], parent)\n func_index[0] += 1\n return value\n return x\n else: # x is a list\n proc = eval(x[0], env, parent=parent)\n args = [eval(arg, env, parent=proc.name) for arg in x[1:]]\n# return proc(*args)\n return proc(*args)\n\ndef parse_command(command):\n parse_str = parse(command)\n x = eval(parse_str)\n\nif __name__ == '__main__':\n\n command = sys.argv[1]\n parse_command (command)\n","sub_path":"src/parse_task_tree.py","file_name":"parse_task_tree.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626363853","text":"\"\"\"\nCalculate several distance along axis metrics for the CSC \ngrid and compare.\n\"\"\"\nimport six\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom stompy.grid import unstructured_grid\nfrom stompy import utils\nfrom sklearn.linear_model import LinearRegression\nimport stompy.plot.cmap as scmap\nfrom stompy.plot import plot_utils\ncmap=scmap.load_gradient('ncview_banded.cpt')\n\n## \n\ngrid_file=\"~/src/csc/dflowfm/CacheSloughComplex_v111-edit19fix-bathy.nc\"\nsix.moves.reload_module(unstructured_grid)\n\ng=unstructured_grid.UnstructuredGrid.read_ugrid(grid_file)\n\nds=g.write_to_xarray()\n\n##\n\n# Define a downstream d=0\nx_down=np.array([610016, 4215971.])\n\n##\nfrom stompy.model import unstructured_diffuser\nsix.moves.reload_module(unstructured_diffuser)\n\n##\n\nfig=plt.figure(1)\nfig.clf()\nax=fig.add_subplot(1,1,1)\ng.plot_edges(lw=0.5,color='k',ax=ax)\nncoll=g.plot_nodes(values=g.nodes['depth'],ax=ax,cmap='jet')\nplt.colorbar(ncoll)\n\n# node depths are positive up.\n\n##\ndef fig_dist(C,num=2,log=False,title=\"\",local_max=False, direction=False):\n fig=plt.figure(num)\n fig.clf()\n fig.set_size_inches([6,9],forward=True)\n ax=fig.add_subplot(1,1,1)\n cax=fig.add_axes([0.05,0.6,0.03,0.35])\n fig.subplots_adjust(left=0,right=1,top=1,bottom=0)\n if log:\n C=np.log10(C.clip(1e-10,np.inf))\n label='log$_{10}$'\n else:\n label='linear'\n \n ccoll=g.plot_cells(values=C,ax=ax,cmap=cmap)\n ccoll.set_lw(0.05)\n ccoll.set_edgecolor('face')\n \n # plt.colorbar(ccoll,cax=cax,label=label)\n plot_utils.cbar(ccoll,cax=cax,label=label)\n \n if local_max:\n is_local_max=np.ones(g.Ncells(),np.bool8)\n e2c=g.edge_to_cells()\n internal=e2c.min(axis=1)>=0\n c1=e2c[internal,0]\n c2=e2c[internal,1]\n c1_less=C[c1]=0] )\n #y=C[cells]\n #X=np.c_[cc[cells]-cc[cells].mean(axis=0),\n # np.ones(len(cells))] # location and bias\n #beta_hat=np.linalg.lstsq(X,y,rcond=None)[0]\n #UV[i,:]=beta_hat[:2] # [gradx,grady]\n low=cells[ np.argmin(C[cells]) ]\n high=cells[ np.argmax(C[cells]) ]\n UV[i,:]=(cc[high]-cc[low])/(C[high]-C[low])\n ax.quiver( XY[:,0], XY[:,1], UV[:,0], UV[:,1],pivot='tip',scale=60,width=0.005)\n \n ax.xaxis.set_visible(0)\n ax.yaxis.set_visible(0)\n ax.axis('equal')\n ax.text(0.5,0.98,title,transform=ax.transAxes,va='top',ha='center')\n return fig\n\nfig=fig_dist(cell_costs,num=6,log=False,title='Dijkstra',local_max=False, direction=True)\n\n##\n\n\ndef cost_to_dist(C,g=g,monotonic_search=True):\n \"\"\"\n given some cost metric C on the cells of the grid,\n use the shortest path from C.min() to C.max() to translate\n cost C into geographic distance.\n\n monotonic_search: shortest path only traverses edges of increasing\n cost. Fails if there are local maxima along all paths between\n global min/max.\n \"\"\"\n c_min=np.argmin(C)\n c_max=np.argmax(C)\n e2c=g.edge_to_cells()\n \n edge_selector=lambda j,direc: (direc*C[e2c[j,0]]Lindsey\")\n\n##\n\n# Plot each of the distance fields and save to figure.\n\nfor v in ds.data_vars:\n if not v.startswith('dist'): continue\n print(v)\n\n fig=fig_dist(ds[v].values,log=False,title=ds[v].attrs['desc'],num=10)\n fig.savefig('map_%s.png'%v,dpi=200)\n\n##\n\n# And what does magnitude of distance gradient look like?\nfrom stompy.model.stream_tracer import U_perot\n\ne2c=g.edge_to_cells().copy()\ncc=g.cells_center()\nec=g.edges_center()\n\nc1=e2c[:,0]\nc2=e2c[:,1]\nc1[c1<0]=c2[c1<0]\nc2[c2<0]=c1[c2<0]\ndg=np.where(c1==c2,\n 1.0, # cell differences will always be zero, so this doesn't matter.\n utils.dist(cc[c1] - cc[c2]))\n\ndef dist_ratio(D):\n # calculate per-edge gradients\n dDdn=(D[c2]-D[c1])/dg\n gradD=U_perot(g,g.edges_length()*dDdn,g.cells_area())\n gradmag=utils.mag(gradD)\n return gradmag\n\n##\n\nfrom matplotlib.colors import LogNorm\n\n\nfor v in ds.data_vars:\n if not v.startswith('dist'): continue\n print(v)\n\n gradmag=dist_ratio(ds[v].values)\n \n fig=plt.figure(1)\n fig.clf()\n ax=fig.add_axes([0,0,1,1])\n cax=fig.add_axes([0.05,0.05,0.03,0.25])\n\n ccoll=g.plot_cells(values=gradmag,cmap='jet',norm=LogNorm(vmin=0.1,vmax=10),ax=ax)\n # ccoll.set_clim([0.1,10])\n plot_utils.cbar(ccoll,cax=cax)\n cax.set_title(r'$|| \\nabla D ||$')\n ax.axis('equal')\n ax.axis( (601757, 628944., 4220689, 4249561) )\n ax.text(0.05,0.9,v,transform=ax.transAxes)\n\n fig.savefig('gradient_%s.png'%v,dpi=200)\n","sub_path":"distances/csc_distances.py","file_name":"csc_distances.py","file_ext":"py","file_size_in_byte":10354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"586523744","text":"#! /usr/bin/env python\n\n\"\"\"Grab data from the ALS X/Y channels and idetify times when left\nunshuttered in locked time\n\"\"\"\n\nfrom glue import segments\nfrom gwpy.segments import DataQualityFlag\nfrom gwsumm.data import get_timeseries_dict\nimport argparse\nimport numpy\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument('-s', '--start', type=int, required=True, help='start time')\nparser.add_argument('-e', '--end', type=int, required=True, help='end time')\nparser.add_argument('-ln', '--low-noise', type=str, \n default='H1:DMT-GRD_ISC_LOCK_NOMINAL:1', \n help='low noise flag (optional)')\nparser.add_argument('-t', '--threshold', type=float, default=0.01,\n help='Threshold to set on ALS channels. This is a +/- '\n 'value (optional)')\nparser.add_argument('-st', '--stride', type=float, default=1, \n help='Stide for the flag (s) (optional)')\n\nargs = parser.parse_args()\n\n# Define the ALS channels needed\nchannels = ['H1:ALS-X_TR_A_LF_OUT16','H1:ALS-Y_TR_A_LF_OUT16']\n\n# Define the segment file name and flag name\nsegment_file = 'H1_ALS_UNSHUTTERED_%s-%s.xml' % (args.start, \n abs(args.end-args.start))\nflag_name = 'H1:DCH-ALS_UNSHUTTERED:1'\n\n# Find times when the low noise flag is active\nactive = DataQualityFlag.query_dqsegdb(args.low_noise, args.start, \n args.end).active\n\n# Grab ALS channel data only during low noise time\nals = get_timeseries_dict(channels, active, frametype='H1_R')\n\n# Define empty segment list\nsegs = segments.segmentlist()\n\n# loop over channels and find times when the timseries of each channel strays\n# +/- threshold\nfor c in channels:\n\n # Find times when the timeseries > threshold\n time1 = [j.times[j.value > args.threshold] for j in als[c]]\n time1 = numpy.concatenate(time1)\n # Find times when the timeseries < -threshold\n time2 = [j.times[j.value < -1*args.threshold] for j in als[c]]\n time2 = numpy.concatenate(time2)\n # Concatenate the two sets of times\n times = numpy.concatenate([time1.value,time2.value], axis=0)\n\n # Extend the segment list to include the most recent times when a \n # channel is above/below threshold band\n segs.extend([segments.segment(int(t), int(t)+args.stride) for t in times])\n\n# Coalesce the segment list \nsegs = segs.coalesce()\n\n# Set up the xml file. Here we are making a list of all the start and end \n# times of the segments separately\nstart_time = []\nstart_time.extend([t[0] for t in segs])\nend_time = []\nend_time.extend([t[1] for t in segs])\n \n# Put all the times in to a DQ flag and write to xml file\nflag = DataQualityFlag(flag_name, active=zip(start_time,end_time), \n known=[[args.start,args.end]])\nflag.write(segment_file)\n","sub_path":"scripts/DCH-ALS_UNSHUTTERED/als_unshuttered_veto.py","file_name":"als_unshuttered_veto.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"221961074","text":"#Embedded file name: /Applications/Ableton Live 9 Suite.app/Contents/App-Resources/MIDI Remote Scripts/LiveControl_2_0/LC2SessionSnapshot.py\nfrom LC2Sysex import LC2Sysex\n\nclass LC2SessionBank:\n\n def set_song(song):\n LC2SessionBank.song = song\n\n set_song = staticmethod(set_song)\n\n def set_timer_callback(func):\n LC2SessionBank.timer_callback = func\n\n set_timer_callback = staticmethod(set_timer_callback)\n\n def release_attributes():\n LC2SessionBank.song = None\n LC2SessionBank.timer_callback = None\n\n release_attributes = staticmethod(release_attributes)\n\n def __init__(self):\n self._snapshots = {}\n self._send_states()\n\n def add(self, id):\n self._snapshots[id] = LC2SessionSnapshot()\n self._send_states()\n\n def _send_states(self):\n sysex = LC2Sysex('SNAPSHOT_STATES')\n val = 0\n for t in self.get_states():\n sysex.byte(t)\n\n sysex.send()\n\n def load(self, id):\n if id in self._snapshots:\n self._snapshots[id].load()\n\n def get_states(self):\n states = []\n for i in range(16):\n states.append(i in self._snapshots and 1 or 0)\n\n return states\n\n def playing_slot_changed(self, name, slot_id):\n for id in self._snapshots:\n self._snapshots[id].playing_slot_changed(name, slot_id)\n\n\nclass LC2SessionSnapshot:\n\n def __init__(self):\n self._waiting_for_load = 0\n self._trigger_slot = -1\n self._trigger_name = None\n self._tracks = []\n self._tempo = LC2SessionBank.song().tempo\n for track in LC2SessionBank.song().tracks:\n self._tracks.append(LC2TrackSnapshot(track))\n if self._tracks[-1]._has_playing_clip() and self._trigger_slot == -1:\n self._trigger_slot = self._tracks[-1]._playing_slot_id()\n self._trigger_name = self._tracks[-1]._get_track_name()\n\n def load(self):\n self._waiting_for_load = 1\n if self._trigger_slot == -1:\n self._load_snapshot()\n self._waiting_for_load = 0\n for tr in self._tracks:\n tr._launch(LC2SessionBank.song().tracks)\n\n def playing_slot_changed(self, track_name, slot_id):\n if self._waiting_for_load and track_name == self._trigger_name and slot_id == self._trigger_slot:\n LC2SessionBank.timer_callback(1, self._load_snapshot)\n\n def _load_snapshot(self):\n for tr in self._tracks:\n tr._load(LC2SessionBank.song().tracks)\n\n LC2SessionBank.song().tempo = self._tempo\n self._waiting_for_load = 0\n\n\nclass LC2TrackSnapshot:\n\n def __init__(self, track):\n self._track_name = track.name\n self._playing_slot = track.playing_slot_index\n self._solo = track.solo\n self._mute = track.mute\n self._vol = track.mixer_device.volume.value\n self._pan = track.mixer_device.panning.value\n self._sends = []\n for send in track.mixer_device.sends:\n self._sends.append(send.value)\n\n def _has_playing_clip(self):\n return self._playing_slot > -1\n\n def _playing_slot_id(self):\n return self._playing_slot\n\n def _get_track_name(self):\n return self._track_name\n\n def _load(self, tracks):\n return\n track = self.find_track(tracks)\n if track is not None:\n track.solo = self._solo\n track.mute = self._mute\n track.mixer_device.volume.value = self._vol\n track.mixer_device.panning.value = self._pan\n for id, send in enumerate(track.mixer_device.sends):\n if id < len(self._sends):\n send.value = self._sends[id]\n\n def _launch(self, tracks):\n track = self.find_track(tracks)\n if track is not None:\n if hasattr(track, 'clip_slots'):\n if self._playing_slot > -1:\n if self._playing_slot < len(track.clip_slots):\n if track.clip_slots[self._playing_slot].has_clip:\n track.clip_slots[self._playing_slot].clip.fire()\n else:\n track.stop_all_clips()\n else:\n track.stop_all_clips()\n\n def find_track(self, tracks):\n track = None\n for tr in tracks:\n if tr.name == self._track_name:\n track = tr\n break\n\n return track","sub_path":"AbletonLive9_RemoteScripts/LiveControl_2_0/LC2SessionSnapshot.py","file_name":"LC2SessionSnapshot.py","file_ext":"py","file_size_in_byte":4460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"497952797","text":"\n\nfrom xai.brain.wordbase.nouns._bittern import _BITTERN\n\n#calss header\nclass _BITTERNS(_BITTERN, ):\n\tdef __init__(self,): \n\t\t_BITTERN.__init__(self)\n\t\tself.name = \"BITTERNS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"bittern\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_bitterns.py","file_name":"_bitterns.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"361343060","text":"import requests\nimport json\nimport random\n\n\ndef pipeline_health(topic_list):\n print(f\"Get the Health of all topics {topic_list}\")\n json_data = {}\n for topic in topic_list:\n topic_data = topic_stats(topic)\n json_data[topic] = random.randint(1,10)\n return json_data\n\ndef topic_stats(topic_name):\n print(f\"Get the stats on {topic_name}\")\n str = f'http://localhost:8080/admin/v2/persistent/public/default/{topic_name}/stats'\n print(str)\n return requests.get(str).json()\n \n","sub_path":"pipeline-monitor-backend/pulsar_controller.py","file_name":"pulsar_controller.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33050379","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport datetime\r\nimport h5py\r\nimport numpy as np\r\nimport os\r\nimport trkpy.path as path\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Group(h5py.Group):\r\n\r\n @classmethod\r\n def from_file(cls, filename, mode='a'):\r\n\r\n h5_path, h5_filename = os.path.split(filename)\r\n if not os.path.exists(h5_path):\r\n os.makedirs(h5_path)\r\n\r\n return cls(h5py.File(filename, mode, libver='latest', driver='sec2').id)\r\n\r\n\r\n @classmethod\r\n def from_files(cls, filenames, num=None, mode=None):\r\n\r\n # sanatize num\r\n if num is None:\r\n num = len(filenames)\r\n\r\n # sanatize filenames\r\n if len(filenames) == 0:\r\n raise Exception('need more than zero files')\r\n elif len(filenames) == 1:\r\n filenames = filenames*num\r\n elif len(filenames) == num:\r\n pass\r\n else:\r\n raise Exception('got '+str(len(filenames))+' filenames, dont know how to expand to '+str(num))\r\n\r\n # sanatize mode\r\n if mode is None:\r\n mode = ['a']*num\r\n elif mode in ['a', 'r', 'w']:\r\n mode = [mode]*num\r\n elif len(mode) > 1:\r\n if len(mode) == num:\r\n for m in mode:\r\n if m not in ['a', 'r', 'w']:\r\n raise Exception('invalid mode(s) definition: '+str(mode))\r\n else:\r\n raise Exception('please make sure that mode has the same length as number of filenames')\r\n else:\r\n raise Exception('invalid mode(s) definition')\r\n\r\n # build result\r\n result = []\r\n for i, (fn, m) in enumerate(zip(filenames, mode)):\r\n try:\r\n result.append(cls.from_file(fn, m))\r\n except OSError as e:\r\n print(e)\r\n return result\r\n\r\n\r\n def create(self, cls):\r\n\r\n date_string = str(datetime.datetime.utcnow())\r\n name = str(cls.gtype[0])+'_V'+str(cls.gtype[1])\r\n\r\n sub_group = self.create_group(date_string+'_'+name)\r\n sub_group.attrs['created'] = date_string\r\n sub_group.attrs['name'] = str(cls.gtype[0])\r\n sub_group.attrs['version'] = str(cls.gtype[1])\r\n\r\n dtype = [\r\n ('name', h5py.special_dtype(vlen=str)),\r\n ('version', h5py.special_dtype(vlen=str))\r\n ]\r\n d = np.empty(len(cls.gtypes), dtype=dtype)\r\n for i, gtype in enumerate(cls.gtypes):\r\n d[i] = str(gtype[0]), str(gtype[1])\r\n\r\n sub_group.attrs.create('gtypes', data=d)\r\n\r\n return Group(sub_group.id)\r\n\r\n\r\n def _search_deep(group, cls):\r\n\r\n groups = []\r\n try:\r\n for name, item in sorted(group.items()):\r\n try:\r\n groups.append(cls(Group(item.id)))\r\n except ValueError as ve: # group can not be used as base for cls\r\n # print(ve)\r\n groups.extend(_search_deep(Group(item.id), cls))\r\n except AttributeError as ae:\r\n # print(ae)\r\n pass\r\n return groups\r\n\r\n\r\n def search(self, cls, deep=True, drop_duplicates=True):\r\n\r\n matches = []\r\n for name, item in sorted(self.items()):\r\n try:\r\n grp = Group(item.id)\r\n except ValueError as ve:\r\n # print('a',type(e))\r\n pass\r\n else:\r\n if deep:\r\n matches.extend(grp.search(cls, deep=deep, drop_duplicates=drop_duplicates))\r\n try:\r\n matches.append(cls(grp))\r\n except Exception as e:\r\n # print(e)\r\n pass\r\n\r\n if drop_duplicates:\r\n matches_filtered = []\r\n groups = set()\r\n for m in matches:\r\n if m.group not in groups:\r\n matches_filtered.append(m)\r\n groups.add(m.group)\r\n matches = matches_filtered\r\n\r\n return matches\r\n # # remove douplicate groups\r\n # if drop_duplicates:\r\n # groups_accepted = []\r\n # for g in groups:\r\n # if g not in groups_accepted:\r\n # groups_accepted.append(g)\r\n # groups = groups_accepted\r\n\r\n # try to wrap groups\r\n # matches = []\r\n # for g in groups_accepted:\r\n # try:\r\n # matches.append(cls(g))\r\n # except Exception as e:\r\n # print(e)\r\n\r\n\r\n # for name, item in sorted(self.items()):\r\n # # print(name, item)\r\n # if ignore:\r\n\r\n # # parse all subnodes\r\n # for inner_name, inner_item in sorted(item.items()):\r\n # matches.extend(self.search(cls, select, backwards, name, version, ignore))\r\n\r\n # # try to add current group\r\n # try:\r\n # matches.append(cls(Group(item.id)))\r\n # except Exception as e:\r\n # print(e)\r\n\r\n # elif not backwards:\r\n # gtypes = item.attrs.get('gtypes', [])\r\n # for gtype in gtypes:\r\n # if gtype[0] == gtype_name and gtype[1] == gtype_version:\r\n # matches.append(cls(Group(item.id)))\r\n # else:\r\n # if item.attrs['name'] == gtype_name and item.attrs['version'] == gtype_version:\r\n # matches.append(cls(Group(item.id)))\r\n\r\n # if select is None:\r\n # return matches\r\n # elif select == 'first':\r\n # if len(matches) > 0:\r\n # return matches[0]\r\n # else:\r\n # raise Exception('no matches found, cant return first')\r\n # elif select == 'latest':\r\n # if len(matches) > 0:\r\n # return matches[-1]\r\n # else:\r\n # raise Exception('no matches found, cant return latest')\r\n # else:\r\n # select = int(select)\r\n # if select >= 0 and select < len(matches):\r\n # return matches[select]\r\n # else:\r\n # raise Exception('invalid selection index '+str(select)+'for '+str(len(matches))+' groups')\r\n\r\n\r\n\r\n\r\n# class GroupType(object):\r\n\r\n# def __init__(self, name, version):\r\n# self.name = name\r\n# self.version = version\r\n\r\n# def __str__(self):\r\n# return str(self.name)+'_V'+str(self.version)\r\n\r\n\r\n\r\n\r\n\r\ndef datetime64_to_str(original):\r\n \"\"\" parse original structured array and replace datetime64['ms'] columns with of S26 \"\"\"\r\n\r\n\r\n new_dtype = []\r\n dt64_names = []\r\n for name in original.dtype.names:\r\n if original.dtype[name] == np.dtype('datetime64[ms]'):\r\n new_dtype.append((name, 'S26'))\r\n dt64_names.append(name)\r\n else:\r\n new_dtype.append((name, original.dtype[name]))\r\n\r\n result = np.empty(original.shape, dtype=new_dtype)\r\n\r\n for name in original.dtype.names:\r\n if name in dt64_names:\r\n result[name] = original[name].astype('S26')\r\n else:\r\n result[name] = np.array(original[name])\r\n\r\n return result\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# class classproperty(property):\r\n# \"\"\"ClassProperty decorator, stolen from stackoverflow.com\"\"\"\r\n\r\n# def __get__(self, cls, owner):\r\n\r\n# return classmethod(self.fget).__get__(None, owner)()\r\n\r\n\r\n\r\n# class TestGroup(object):\r\n\r\n# @classproperty\r\n# def __str__(cls):\r\n\r\n# if hasattr(cls, '__id') and hasattr(cls, '__version'):\r\n# return str(cls.__id)+'_V'+str(cls.__version)\r\n# else:\r\n# raise Exception('could not build type')\r\n\r\n\r\n# @classproperty\r\n# def id(cls):\r\n\r\n# return cls.__id\r\n\r\n\r\n# @classproperty\r\n# def version(cls):\r\n\r\n# return cls.__version\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# def new(filename, test=None, step=None, version=None, message=None):\r\n\r\n# h5_path, h5_filename = os.path.split(filename)\r\n# if not os.path.exists(h5_path):\r\n# os.makedirs(h5_path)\r\n\r\n# parent = enhanced_hdf5_group(h5py.File(filename, 'a').id)\r\n# return enhanced_hdf5_group(parent.create_test_group(test=test, step=step, version=version, message=message).id)\r\n\r\n\r\n\r\n# def search(filename, test=None, step=None, version=None, selector=None):\r\n\r\n# parent = enhanced_hdf5_group(h5py.File(filename, 'a').id)\r\n# return parent.search_test_group(test=test, step=step, version=version, selector=selector)\r\n\r\n\r\n\r\n# def latest(filename, test=None, step=None, version=None, selector='latest'):\r\n\r\n# parent = enhanced_hdf5_group(h5py.File(filename, 'a').id)\r\n# return enhanced_hdf5_group(parent.search_test_group(test=test, step=step, version=version, selector=selector).id)\r\n\r\n\r\n\r\n\r\n\r\n# class enhanced_hdf5_group(h5py.Group):\r\n\r\n# def create_test_group(self, test=None, step=None, version=None, name=None, message=None):\r\n\r\n# if name is None:\r\n# name = str(datetime.datetime.utcnow())\r\n\r\n# group = self.create_group(name+'.'+str(test)+'.'+str(step)+'.'+str(version))\r\n# if test is not None:\r\n# group.attrs['test']=str(test)\r\n# if step is not None:\r\n# group.attrs['step']=str(step)\r\n# if version is not None:\r\n# group.attrs['version']=str(version)\r\n# if not (message is None or message == ''):\r\n# group.attrs['message'] = message\r\n# return enhanced_hdf5_group(group.id)\r\n\r\n\r\n\r\n# def search_test_group(self, test=None, step=None, version=None, name=None, selector=None):\r\n\r\n# if name:\r\n# return enhanced_hdf5_group(self[name].id)\r\n\r\n# if (selector in ['latest', 'newest']):\r\n# return self._find_newest(version, test, step)\r\n\r\n# elif selector is not None:\r\n# try:\r\n# selector = int(selector)\r\n# matches = self._find_all(version, test, step)\r\n# if selector >= 0:\r\n# if len(matches) < selector+1:\r\n# raise Exception('cant select nr. '+str(selector)+'out of '+str(len(matches))+' candidates in '+\r\n# str(self)+' matching: test='+str(test)+' and step='+str(step)+' and version='+str(version))\r\n# return matches[selector]\r\n# else:\r\n# if len(matches) < abs(selector):\r\n# raise Exception('cant select nr. '+str(selector)+'out of '+str(len(matches))+' candidates in '+\r\n# str(self)+' matching: test='+str(test)+' and step='+str(step)+' and version='+str(version))\r\n# return matches[selector]\r\n# except ValueError:\r\n# raise Exception('unknown selector type')\r\n# else:\r\n# return self._find_all(version, test, step)\r\n\r\n\r\n\r\n# def _find_all(self, version, test, step):\r\n\r\n# matches = []\r\n# for name, item in self.items():\r\n# if item.attrs.get('version') == str(version):\r\n# if item.attrs.get('test') == str(test):\r\n# if item.attrs.get('step') == str(step):\r\n# matches.append(enhanced_hdf5_group(item.id))\r\n# return matches\r\n\r\n# def _find_newest(self, version, test, step):\r\n\r\n# newest = None\r\n# for name, item in self.items():\r\n# if item.attrs.get('version') == str(version):\r\n# if item.attrs.get('test') == str(test):\r\n# if item.attrs.get('step') == str(step):\r\n# newest = item\r\n# if newest is None:\r\n# raise Exception('no new test group found in '+str(self)+' matching: test='+str(test)+' and step='+str(step)+' and version='+str(version))\r\n# return enhanced_hdf5_group(newest.id)\r\n\r\n\r\n\r\n # def find_test_groups(self, version=None, test=None, step=None):\r\n # # search for the newest matching the criteria\r\n\r\n # matches = []\r\n # for name, item in self.items():\r\n # if item.attrs.get('version') == str(version):\r\n # if item.attrs.get('test') == str(test):\r\n # if item.attrs.get('step') == str(step):\r\n # matches.append(enhanced_hdf5_group(item.id))\r\n # return matches\r\n\r\n\r\n\r\n\r\n\r\n\r\n# def new2(config, filename=None, test=None, step=None, version=None, message=None):\r\n# \"\"\"create new data file.\r\n\r\n# if filename is fully qualified: only respect this filename\r\n# otherwise: take default path from config, add year and week subfolders\r\n# \"\"\"\r\n\r\n\r\n# time = datetime.datetime.utcnow()\r\n# date = time.isocalendar()\r\n# year = date[0]\r\n# cw = date[1]\r\n\r\n# if filename is None:\r\n# path = os.path.join(config.get('path'), str(year), str(cw))\r\n# filename = datetime.datetime.utcnow().strftime('%Y%m%d %H%M%S')+'.'+test+'.'+step+'.h5'\r\n\r\n# else:\r\n# path, filename = os.path.split(filename)\r\n\r\n# if path == '':\r\n# path = os.path.join(config.get('path'), str(year), str(cw))\r\n\r\n# if not filename.endswith('.h5'):\r\n# filename = filename + '.h5'\r\n\r\n# if not os.path.exists(full_path):\r\n# os.makedirs(plot_path)\r\n\r\n# parent = enhanced_hdf5_group(h5py.File(config.get('file'), 'a').id)\r\n\r\n# return enhanced_hdf5_group(parent.create_test_group(test=test, step=step, version=version).id)\r\n\r\n\r\n\r\n\r\n# def init_file(kwargs):\r\n# return enhanced_hdf5_file(kwargs.get('file'), 'a')\r\n\r\n# def init_files(kwargs):\r\n# files = enhanced_hdf5_file_collection(h5py)\r\n# for idx, file_ in enumerate(kwargs.get('files', [])):\r\n# name = file_.get('name', str(idx))\r\n# fn = file_.get('fn')\r\n# mode = file_.get('mode', 'a')\r\n# files[name] = enhanced_hdf5_file(fn, mode)\r\n# return files\r\n\r\n\r\n# class enhanced_hdf5_file_collection(dict):\r\n# def __init__(self, h5py_impl):\r\n# super().__init__()\r\n# self.h5py = h5py_impl\r\n\r\n\r\n\r\n # # def create_group(self, test, step, version='0'):\r\n # # return self.__file.create_group('/'+test+'/'+str(version)+'/'+step+'/'+str(datetime.datetime.utcnow()))\r\n # def create_group(self, *args):\r\n # return self.__file.create_group('/'+('/'.join(args))+'/')\r\n # def require_group(self, *args):\r\n # group = self.__file.require_group('/')\r\n # for i in args:\r\n # group = group.require_group(str(i)+'/')\r\n # return group\r\n # def find_latest(self, test, step, version='0'):\r\n # group = self.__file[test+'/'+str(version)+'/'+step]\r\n # return find_newest(group)\r\n # def find_all(self, test, step, version='0'):\r\n # try:\r\n # group = self.__file[test+'/'+str(version)+'/'+step]\r\n # except KeyError as ke:\r\n # group = {}\r\n # ds = []\r\n # grps = []\r\n # for name, child in group.items():\r\n # if hasattr(child, 'shape'):\r\n # ds.append(child)\r\n # else:\r\n # grps.append(child)\r\n # return ds, grps\r\n # def find_timed_group(self, test, step, time, version=0):\r\n # return self.__file[test+'/'+str(version)+'/'+step+'/'+time]\r\n # def find_named(self, test, step, name, version=0):\r\n # return self.__file[test+'/'+str(version)+'/'+step+'/'+name]\r\n # def find_group(self, name):\r\n # return self.__file[name]\r\n # def find_latest_group(self, parent):\r\n # return find_newest(self.__file[parent])\r\n\r\n","sub_path":"trkpy/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":15612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509458526","text":"#! /usr/bin/env python3\n# coding: utf-8\n\nfrom model.category import CategoryDatabase\nfrom model.product import ProductDatabase\nfrom model.registered_product import RegisteredProductDatabase\nfrom view.consoleapplicationview import ConsoleApplicationView\nfrom .dbupdate import UpdateDatabase\n\nclass Application:\n \"\"\" This class is the main class of the program. It manages the main loop\n and all the necessary features. The start() method is the brain of the\n application and triggers all the features when it is necessary. \"\"\"\n\n def __init__(self):\n self.interface = ConsoleApplicationView()\n self.db_category = CategoryDatabase()\n self.db_product = ProductDatabase()\n self.db_registered_product = RegisteredProductDatabase()\n self.update = UpdateDatabase()\n\n self.cat_information = ()\n self.cat_id_selected = 0\n self.prd_tuple = ()\n self.subst_prd_tuple = ()\n\n self.play = True\n\n def start(self):\n \"\"\" This method manages the different steps of the application\"\"\"\n while self.play:\n self.update.update_database()\n action = self.action_choice()\n if action == 'research':\n self.category_selection()\n self.product_selection()\n self.selected_substitute_products()\n self.save_substitute_product()\n else:\n self.consult_product_saved()\n #Quit or new action?\n self.new_action()\n\n def category_selection(self):\n \"\"\" This method manages the category selection \"\"\"\n self.cat_id_selected = 0 #to be sure to ask category each time\n self.cat_information = self.db_category.get_categories_with_id()\n self.interface.print_category_selection(self.cat_information)\n while self.cat_id_selected < 1 or self.cat_id_selected > len(self.cat_information):\n try:\n self.cat_id_selected = int(input(\"numéro de la catégorie: \"))\n except:\n self.interface.print_error_input_not_int()\n self.interface.print_category_selected(self.cat_information, self.cat_id_selected)\n\n def product_selection(self):\n \"\"\" This method manages the product selection \"\"\"\n\n self.prd_tuple = self.db_product.get_dirty_product_from_category(self.cat_id_selected)\n self.interface.print_product_selection(self.prd_tuple)\n prd_number = self.__prd_input(self.prd_tuple)\n #prd_number - 1 because index starts from zero\n self.interface.print_product_selected(self.prd_tuple, prd_number - 1)\n\n def selected_substitute_products(self):\n \"\"\" This method manages the selection of substitute products \"\"\"\n\n self.subst_prd_tuple = self.db_product.get_subsitute_products(self.cat_id_selected)\n self.interface.print_subsitute_products(self.subst_prd_tuple)\n\n def save_substitute_product(self):\n \"\"\" This method manages the substitute product registered feature \"\"\"\n\n save = True\n while save:\n self.interface.print_save_product_question()\n answer = 'W'\n while answer != 'Y' and answer != 'N':\n answer = input(\"Votre réponse: \").upper()\n\n if answer == 'Y':\n self.interface.print_product_to_save_question()\n prd_number = self.__prd_input(self.subst_prd_tuple)\n self.__product_save_process(self.subst_prd_tuple[prd_number - 1][5])\n else:\n save = False\n self.interface.print_end_save_process_message()\n\n def new_action(self):\n \"\"\" This method manages the process of reloading a research or stopping\n the application \"\"\"\n self.interface.print_new_action()\n answer = 'W'\n while answer != 'Y' and answer != 'N':\n answer = input(\"Votre réponse: \").upper()\n\n if answer == 'Y':\n self.play = True\n else:\n self.play = False\n self.interface.print_good_bye_message()\n\n def action_choice(self):\n \"\"\"This method manages the choice of the user between doing a research\n or seeing his saved products\"\"\"\n self.interface.print_action_choice()\n answer = 0\n while answer != 1 and answer != 2:\n try:\n answer = int(input(\"Votre choix:\"))\n except:\n self.interface.print_error_input_not_int()\n\n if answer == 1:\n return 'research'\n\n def consult_product_saved(self):\n \"\"\" This method prints all the products saved by the user\"\"\"\n products = self.db_registered_product.get_all_products_saved()\n self.interface.print_products_saved(products)\n\n def __prd_input(self, product_tuple):\n \"\"\" This method manages the product selection \"\"\"\n prd_number = 0\n while prd_number < 1 or prd_number > len(product_tuple):\n try:\n prd_number = int(input(\"numéro de produit: \"))\n except:\n self.interface.print_error_input_not_int()\n\n return prd_number\n\n def __product_save_process(self, product_ref):\n \"\"\" This private method manages the process to save a product \"\"\"\n product_to_save = self.db_registered_product.get_product_from_ref(product_ref)\n #Si le produit a déjà été enregistré\n if product_to_save:\n self.interface.print_product_already_saved()\n else:\n self.db_registered_product.inject_product(product_ref, 'disponible')\n self.interface.print_selected_product_to_save()\n","sub_path":"app/controller/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230960583","text":"from flask import Flask\nfrom flask_restplus import Api\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\ndb = SQLAlchemy()\n\ndef create_app():\n app = Flask(__name__)\n app.secret_key = b'uH\\x88fP9t\\xc8\\xf3\\x1e\\\\\\xb2_\\x90\\x9d\\xf2'\n\n from config import Config\n app.config.from_object(Config)\n db.init_app(app)\n\n @app.route('/hello')\n def hello():\n return \"Goodbye World!\"\n\n authorizations = {\n 'apikey': {\n 'type': 'apiKey',\n 'in': 'header',\n 'name': 'X-API-KEY'\n }\n }\n\n from .apis.tweets import api as tweets\n api = Api()\n api.add_namespace(tweets)\n api.init_app(app, authorizations=authorizations)\n\n login_manager = LoginManager()\n login_manager.init_app(app)\n\n @login_manager.request_loader\n def load_user_from_request(request):\n from app.models import User\n # first, try to login using the api_key url arg\n api_key = request.args.get('api_key')\n print(api_key)\n if api_key:\n user = db.session.query(User).filter(User.api_key == api_key).first()\n if user:\n return user\n\n # next, try to login using Basic Auth\n api_key = request.headers.get('X-API-Key')\n print(api_key)\n if api_key:\n user = db.session.query(User).filter(User.api_key == api_key).first()\n if user:\n return user\n\n # finally, return None if both methods did not login the user\n return None\n\n app.config['ERROR_404_HELP'] = False\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"271478594","text":"import numpy as np\nfrom PIL import ImageGrab\nimport cv2 as cv\nimport pyautogui\nimport time\nimport sys\nimport json\nfrom random import choice\n\nscreen_resolution = (1920,1080)\ngame_roi = None\n\n\nclass PreCapture:\n def __init__(self):\n\n self.halfscrn_cap = None\n self.region_of_interest = None\n self.autodetect = False\n self.roi_preview = None\n self.saved_roi = self.get_saved_roi()\n\n if self.saved_roi:\n print(\"Press -enter- to validate previously saved region\\n\",\n \"\\bPress -space- to get a new region with auto-detection\\n\",\n \"\\bPress -escape- to quit\")\n\n else:\n print(\"Press -enter- to validate region\\n\",\n \"\\bPress -escape- to quit\")\n \n\n def main_loop(self):\n \n while True:\n # capture current overall right-half screen\n self.halfscrn_cap = np.array(ImageGrab.grab(bbox=(\n screen_resolution[0]/2+50, 0,\n screen_resolution[0], screen_resolution[1]-50)))\n if self.autodetect:\n self.roi_preview = self.get_roi_preview()\n else:\n self.roi_preview = self.saved_roi\n\n if self.roi_preview:\n cv.rectangle(self.halfscrn_cap, tuple(self.roi_preview[:2]),\n tuple(self.roi_preview[2:]), (0,255,0), 2)\n else:\n pass\n\n cv.imshow('screen catpure', self.halfscrn_cap)\n\n k = cv.waitKey(25) & 0xFF\n if k == 27:\n print(\"Pressed -escape- > Bye bye.\")\n cv.destroyAllWindows()\n sys.exit(0)\n elif k == 13:\n if self.roi_preview:\n self.save_roi()\n print(\"Pressed -Enter- > region validated\")\n break\n else:\n print(\"Pressed -Enter- > Couldn't find any region to capture\")\n elif k == 32 and self.autodetect == False:\n self.autodetect = True\n print(\"Pressed -space- > switching to autodetect mode\") \n \n\n cv.destroyAllWindows()\n return self.region_of_interest\n\n def get_saved_roi(self):\n try:\n with open(\"saved_roi.json\", 'r') as read_file:\n return json.load(read_file)\n except FileNotFoundError:\n print(\"Couldn't find an existing saved region of interest\")\n print(\"Starting auto-detection\")\n self.autodetect = True\n\n\n def get_roi_preview(self):\n\n # create 2 kernels for topleft and botright corners\n # of selection rectangle\n kernel_TLcorner = np.zeros((51,51), dtype='int')\n kernel_TLcorner[23:25, 23:51] = -1\n kernel_TLcorner[23:51, 23:25] = -1\n kernel_TLcorner[25:51, 25:51] = 1\n # inverted topleft gets us botright\n kernel_BRcorner = kernel_TLcorner[::-1,::-1]\n\n # convert catpured screen to gray to get b&w threshold\n gray = cv.cvtColor(self.halfscrn_cap, cv.COLOR_BGR2GRAY)\n ret, thresh = cv.threshold(gray,50,255,cv.THRESH_BINARY)\n\n # filter the screen with kernels to get the corners\n hitmiss = cv.morphologyEx(thresh, cv.MORPH_HITMISS, kernel_TLcorner) \\\n + cv.morphologyEx(thresh, cv.MORPH_HITMISS, kernel_BRcorner)\n\n # exclude top left and bottom right corners of the filtered screen\n hitmiss[0:2,0:2] = 0\n hitmiss[self.halfscrn_cap.shape[0]-2:self.halfscrn_cap.shape[0],\n self.halfscrn_cap.shape[1]-2:self.halfscrn_cap.shape[0]] = 0\n\n # get coordinates and draw rectangle of interest over screen\n # tuple(zip) method to extract only coords\n rect_indices = np.where(hitmiss == 255)\n rect_coords = tuple(zip(rect_indices[0], rect_indices[1]))\n\n if len(rect_coords) == 2:\n # extract from tuple coordinates for visual cue rectangle\n # invert x and y with negative increment\n rect_TL = rect_coords[0][::-1]\n rect_BR = rect_coords[1][::-1]\n roi_preview = [int(i) for i in rect_TL] + [int(j) for j in rect_BR]\n print(roi_preview)\n return roi_preview\n else:\n pass\n\n def save_roi(self):\n # get region of interest real screen coordinates\n # by adding half screen horizontally and +50/50 pix safe zone\n print(\"roi_preview :\", self.roi_preview)\n with open(\"saved_roi.json\", 'w') as write_file:\n json.dump(self.roi_preview, write_file)\n\n self.region_of_interest = [\n self.roi_preview[0] + int(screen_resolution[0]/2+50),\n self.roi_preview[1],\n self.roi_preview[2] + int(screen_resolution[0]/2+50),\n self.roi_preview[3]\n ]\n\n \n\nclass RoICapture:\n def __init__(self):\n self.roi_cap = None\n self.roi_toggle = True\n self.bot_toggle = False\n self.tiles_roi, self.skills_roi, self.lifebars_roi, self.plcmt_roi = (\n self.get_regions())\n self.tiles_val = np.zeros((8,8), dtype=np.uint8)\n self.skills_val = np.zeros((3,4), dtype=bool)\n self.teamup_toggle = False\n self.lifebars = [True, True, True, True, True, True]\n self.player_turn = False\n self.skill_plcmt = False\n\n\n print(\"Captured region coordinates are :\", game_roi)\n\n print(\"Press -r- to show/hide captured regions\\n\",\n \"Press -t- to activate/deactivate teamup's skills\\n\",\n \"Press -enter- to start/stop bot\\n\",\n \"Press -d- for debugging info\\n\",\n \"Press -s- to take a screenshot\\n\",\n \"Press -escape- to quit\")\n\n\n def main_loop(self):\n\n while True:\n self.roi_cap = np.array(ImageGrab.grab(bbox=(game_roi)))\n # cv.imwrite('RoI_capture.png', self.roi_cap)\n\n self.get_regions_info()\n\n if self.bot_toggle:\n game_bot.input(self.lifebars, self.skills_val, self.tiles_val,\n self.player_turn, self.skill_plcmt)\n\n else:\n pass\n\n if self.roi_toggle:\n self.show_regions(self.tiles_roi, self.skills_roi,\n self.lifebars_roi, self.plcmt_roi)\n else:\n cv.destroyWindow('Regions of interest')\n\n self.show_color_scrn()\n\n k = cv.waitKey(25) & 0xFF\n if k == 27: # key = escape\n print(\"Pressed -escape- > Bye bye.\")\n break\n elif k == ord('r'): # key = r\n self.roi_toggle = not self.roi_toggle\n print(\n \"Pressed -r- :\", \"Showing\" if self.roi_toggle else \"Hiding\",\n \"regions of interest\"\n )\n\n elif k == 13: # key = enter\n\n if np.any(self.tiles_val == 0) and not self.bot_toggle:\n print(\n \"Pressed -enter- > Can't start bot without a complete board\"\n )\n else:\n self.bot_toggle = not self.bot_toggle\n print(\n \"Pressed -enter- > Bot is\", \"ON\" if self.bot_toggle else \"OFF\"\n )\n elif k == ord('d'): # debug\n print(\"Pressed -d- > Debug info:\")\n print(\"grid colors :\\n\", self.tiles_val)\n print(\"skills :\\n\", self.skills_val)\n print(\"player turn :\", self.player_turn)\n print(\"player's life :\", self.lifebars[:3])\n print(\"enemy's life :\", self.lifebars[3:])\n print(\"skill placement :\", self.skill_plcmt)\n\n elif k == ord('t'): # key = t\n self.teamup_toggle = not self.teamup_toggle\n print(\n \"Pressed -t- > Teamups are\", \"ON\" if self.teamup_toggle else \"OFF\"\n )\n\n elif k == ord('s'): # key = s\n cv.imwrite('capture.png', self.roi_cap)\n print(\"Pressed -s- > Screen captured as 'capture.png'\")\n\n\n cv.destroyAllWindows()\n\n\n def get_regions(self):\n ht = game_roi[3] - game_roi[1]\n wd = game_roi[2] - game_roi[0]\n\n\n def get_lifebars_regions():\n lifebars_roi = []\n # get line dimensions\n y = int(ht*0.042)\n a = int(wd*0.007), int(wd*0.091)\n b = int(wd*0.139), int(wd*0.240)\n c = int(wd*0.289), int(wd*0.403)\n d = int(wd*0.594), int(wd*0.713)\n e = int(wd*0.767), int(wd*0.867)\n f = int(wd*0.917), int(wd*0.998)\n\n for i in a,b,c,d,e,f:\n lifebars_roi.append((i[0], y, i[1], y))\n\n return lifebars_roi\n\n def get_plcmt_region():\n y = int(ht*0.14)\n x1, x2 = int(wd*0.2), int(wd*0.8)\n plcmt_roi = (x1, y, x2, y)\n return plcmt_roi\n\n\n def get_skills_regions():\n skills_roi = np.zeros((3,4,4), int)\n # get line dimensions\n line_width = wd*0.075\n left_shift = wd*0.01\n line_v_spacing = ht*0.018\n line_h_spacing = wd*0.2475\n x1 = int(wd*0.178)\n y = int(ht*0.313)\n x2 = int(x1 + line_width)\n\n for i in range(4):\n for j in range(3):\n skills_roi[j,i] = (\n (x1 + int(line_h_spacing*i) - int(left_shift*j)),\n (y + int(line_v_spacing*j)),\n (x2 + int(line_h_spacing*i) - int(left_shift*j)),\n (y + int(line_v_spacing*j))\n )\n return skills_roi\n\n\n def get_tiles_regions():\n tiles_roi = np.zeros((8,8,4), int)\n # get squares dimensions\n box_width = ht*0.029\n box_spacing = wd*0.1205\n TLx = int(wd*0.054)\n TLy = int(ht*0.422)\n BRx = int(TLx + box_width)\n BRy = int(TLy + box_width)\n\n\n for i in range(8):\n for j in range(8):\n tiles_roi[j,i] = (\n (TLx + int(box_spacing*i)),\n (TLy + int(box_spacing*j)),\n (BRx + int(box_spacing*i)),\n (BRy + int(box_spacing*j))\n )\n return tiles_roi\n\n\n return (\n get_tiles_regions(), get_skills_regions(), get_lifebars_regions(),\n get_plcmt_region()\n )\n\n def show_regions(self, tiles_roi, skills_roi, lifebars_roi, plcmt_roi):\n for i in range(8):\n for j in range(8):\n [cv.rectangle(self.roi_cap, (tiles_roi[i,j,0], tiles_roi[i,j,1]),\n (tiles_roi[i,j,2], tiles_roi[i,j,3]), (0,255,0), 2)]\n\n for i in range(4):\n for j in range(3):\n [cv.line(self.roi_cap, (skills_roi[j,i,0], skills_roi[j,i,1]),\n (skills_roi[j,i,2], skills_roi[j,i,3]), (0,255,0), 2)]\n\n for i in lifebars_roi:\n cv.line(self.roi_cap, (i[0], i[1]), (i[2], i[3]), (0,255,0), 2)\n\n cv.line(self.roi_cap, plcmt_roi[:2], plcmt_roi[2:], (0,255,0), 2)\n\n cv.imshow('Regions of interest', self.roi_cap)\n\n def get_regions_info(self):\n\n def get_lifebars_status():\n for x in range(6):\n x1, y1, x2, _ = self.lifebars_roi[x]\n roi = self.roi_cap[y1, x1:x2]\n # print(roi) # debug\n self.lifebars[x] = (any((n[0]>=205 for n in roi)))\n\n def get_plcmt_status():\n x1, y1, x2, _ = self.plcmt_roi\n self.skill_plcmt = np.all(self.roi_cap[y1, x1:x2] == 236) \n\n\n def get_skills_status():\n \n for x in range(4):\n for y in range(3):\n x1, y1, x2, _ = self.skills_roi[y, x]\n # print(x1, y1 , x2)\n roi = self.roi_cap[y1, x1:x2]\n # print(\"skill roi:\", x, y, roi)\n self.skills_val[y, x] = (\n any((all(j>200 for j in roi[:,i]) for i in range(3)))\n ) or (np.all(roi == 75))\n\n if not self.teamup_toggle:\n self.skills_val[:,3] = False\n else:\n pass\n\n\n def get_tiles_color():\n # get board colors by the mean of their region hsv values\n for x in range(8):\n for y in range(8):\n TLx, TLy, BRx, BRy = self.tiles_roi[x, y]\n roi = cv.cvtColor(self.roi_cap[TLy:BRy, TLx:BRx], cv.COLOR_RGB2HSV)\n h, s, v, _ = (int(i) for i in cv.mean(roi))\n # print(x, y, \"h, s, v :\", h, s, v) #debug\n\n if s > 60 and 0 <= h < 15:\n self.tiles_val[x,y] = 1\n elif s > 60 and 20 < h < 40:\n self.tiles_val[x,y] = 2\n elif s > 60 and 45 < h < 65:\n self.tiles_val[x,y] = 3\n elif s > 60 and 105 < h < 115:\n self.tiles_val[x,y] = 4\n elif s > 60 and 140 < h < 155:\n self.tiles_val[x,y] = 5\n elif s < 32 and h < 30:\n self.tiles_val[x,y] = 6\n elif 60 < s < 70 and 165 < v < 180:\n self.tiles_val[x,y] = 7\n else:\n self.tiles_val[x,y] = 0\n # print(f\"{x, y}, h : {h}, s : {s}, v : {v}\") # debug\n\n def get_bottom_pix():\n # get rgb value for a pixel right under board\n # mainly to check if it's player's turn\n wd = game_roi[2] - game_roi[0]\n ht = game_roi[3] - game_roi[1]\n x = int(wd / 2)\n y = int(ht * 0.96)\n pix = self.roi_cap[y, x]\n if pix[0] < 5 and 35 < pix[1] < 45 and 105 < pix[2] < 115:\n self.player_turn = True\n else:\n self.player_turn = False\n\n get_lifebars_status()\n get_skills_status()\n get_tiles_color()\n get_bottom_pix()\n get_plcmt_status()\n\n\n def show_color_scrn(self):\n color_preview = np.zeros((8,8,3), np.uint8)\n int_to_color = {\n 0:(125,125,125), 1:(255,0,0), 2:(255,255,0), 3:(0,255,0),\n 4:(0,0,255), 5:(255,0,255), 6:(0,0,0), 7:(245, 245, 245)\n }\n for x in range(8):\n for y in range(8):\n color_preview[x,y] = int_to_color[self.tiles_val[x,y]]\n\n color_preview = cv.cvtColor(color_preview, cv.COLOR_BGR2RGB) #debug\n # cv.imwrite('preview_colors.png',color_preview)\n\n resized_preview = cv.resize(color_preview, (300, 300),\n interpolation=cv.INTER_NEAREST)\n cv.imshow('colors captured', resized_preview)\n\nclass Bot:\n def __init__(self):\n # self.player_life = lifebars[:3]\n # self.enemy_life = lifebars[3:]\n\n # self.lifebars_delay = 4\n self.lifebars_check_time = None\n \n # self.action_timer = 1.5\n self.last_action_time = time.time()\n\n # self.player_action = True\n\n # skill_check is here to ensure once detected a readied skill is exec\n # self.skill_check = False\n\n\n def input(self, lifebars, skills_val, tiles_val, player_turn, plcmt):\n player_life = lifebars[:3]\n enemy_life = lifebars[3:]\n self.skills = skills_val\n \n if plcmt == False and ((not any(enemy_life)) or (not any(player_life))):\n if self.get_lifebars_timer(4):\n self.game_over('win' if player_life else 'lost')\n else:\n pass\n\n \n if player_turn:\n if plcmt:\n print(\"skill tile placement :\", plcmt)\n self.random_tile(tiles_val)\n elif self.get_action_timer(1): \n if np.any(skills_val):\n self.skill_use(skills_val)\n # self.last_action_time = time.time()\n \n elif np.any(tiles_val):\n self.tile_flip(tiles_val) \n # self.last_action_time = time.time()\n else:\n game_capture.bot_toggle = False\n print(\"\\aBot is OFF : couldn't find any move to do!\")\n else:\n pass\n \n else:\n pass\n \n\n def get_lifebars_timer(self, delay):\n if self.lifebars_check_time:\n delay = time.time() - self.lifebars_check_time\n if 6 > delay > delay:\n return True\n elif delay >= 6:\n self.lifebars_check_time = time.time()\n return False\n else:\n return False\n else:\n self.lifebars_check_time = time.time()\n return False\n\n def random_tile(self, tiles_val):\n\n possible_tiles = tuple(zip(*np.where(tiles_val!=0)))\n tile = choice(possible_tiles)\n mouse.click_tile(tile)\n \n\n def get_action_timer(self, delay):\n if self.last_action_time:\n if (time.time() - self.last_action_time) > delay:\n self.last_action_time = None\n return True\n else:\n return False\n else:\n self.last_action_time = time.time()\n return False\n\n def skill_use(self, skills_val): \n for i in range(4):\n for j in range(3):\n if skills_val[j,i]:\n mouse.click_skill((j,i))\n return\n\n def tile_flip(self, tiles_val):\n current_board = Board(tiles_val)\n coords = current_board.get_best_move()\n mouse.drag_tile(coords)\n\n\n def game_over(self, outcome):\n # time.sleep(1)\n \n if outcome == 'win':\n game_capture.bot_toggle = False\n print(\"\\aBot is OFF : enemy's life bars are empty!\")\n print(\"You win!\")\n elif outcome == 'lost':\n game_capture.bot_toggle = False\n print(\"\\aBot is OFF : player's life bars are empty!\")\n print(\"\\aYou lost!\")\n else:\n pass\n\n\n\n\n\nclass Board:\n def __init__(self, board):\n self.current_board = board\n\n def h_flip(self, y, x):\n tmp = self.current_board.copy()\n\n if (0 <= x < 7) and (tmp[y,x] != tmp[y,x+1]):\n tmp[y, x:x+2] = tmp[y, x:x+2][::-1]\n else:\n pass\n\n left_tile_chain = self.get_neighbors(y, x, tmp)\n right_tile_chain = self.get_neighbors(y, x+1, tmp)\n\n nb_chains = (left_tile_chain > 0) + (right_tile_chain > 0)\n max_chain = max(left_tile_chain, right_tile_chain)\n\n if nb_chains != 0:\n return max_chain, nb_chains\n\n\n def v_flip(self, y, x):\n tmp = self.current_board.copy()\n\n if (0 <= y < 7) and (tmp[y,x] != tmp[y+1,x]):\n tmp[y:y+2, x] = tmp[y:y+2, x][::-1]\n else:\n pass\n\n up_tile_chain = self.get_neighbors(y, x, tmp)\n down_tile_chain = self.get_neighbors(y+1, x, tmp)\n\n nb_chains = (up_tile_chain > 0) + (down_tile_chain > 0)\n max_chain = max(up_tile_chain, down_tile_chain)\n\n if nb_chains != 0:\n return max_chain, nb_chains\n\n\n def get_neighbors(self, y, x, temp_board):\n tmp = temp_board\n chain = {(y,x)}\n color = tmp[y,x]\n # find max connected tiles of same color on horizontal\n def get_h_nbr():\n if len(tmp[y, x-1:x+2]) == 3 and np.all(tmp[y, x-1:x+2] == color):\n chain.add((y, x-1))\n chain.add((y, x+1))\n if len(tmp[y, x:x+3]) == 3 and np.all(tmp[y, x:x+3] == color):\n chain.add((y, x+1))\n chain.add((y, x+2))\n if len(tmp[y, x-2:x+1]) == 3 and np.all(tmp[y, x-2:x+1] == color):\n chain.add((y, x-2))\n chain.add((y, x-1))\n\n # find max connected tiles of same color on vertical\n def get_v_nbr():\n if len(tmp[y-1:y+2, x]) == 3 and np.all(tmp[y-1:y+2, x] == color):\n chain.add((y-1, x))\n chain.add((y+1, x))\n if len(tmp[y:y+3, x]) == 3 and np.all(tmp[y:y+3, x] == color):\n chain.add((y+1, x))\n chain.add((y+2, x))\n if len(tmp[y-2:y+1, x]) == 3 and np.all(tmp[y-2:y+1, x] == color):\n chain.add((y-2, x))\n chain.add((y-1, x))\n\n get_h_nbr()\n get_v_nbr()\n\n return len(chain) if len(chain) >= 3 else 0\n\n\n def find_moves(self):\n moves = {}\n for y in range(8):\n for x in range(8):\n h_res = self.h_flip(y,x) if x!=7 else None\n if h_res:\n moves[((y,x),(y,x+1))] = h_res\n\n v_res = self.v_flip(y,x) if y!=7 else None\n if v_res:\n moves[((y,x),(y+1,x))] = v_res\n\n return moves\n\n def get_best_move(self):\n moves = self.find_moves()\n max = (0,0)\n best = None\n for k, v in moves.items():\n if v >= max:\n max = v\n best = k\n else:\n pass\n # print(f\"best move is {best}\") # debug\n return best\n\n\nclass MouseControl:\n\n def __init__(self):\n ht = game_roi[3] - game_roi[1]\n wd = game_roi[2] - game_roi[0]\n # top left tile position and tile spacing\n self.t0 = game_roi[0] + int(wd*0.082), game_roi[1] + int(ht*0.436)\n self.tile_spacing = int(wd*0.12)\n # left skill big button position and skill spacing\n self.s0 = game_roi[0] + int(wd*0.089), game_roi[1] + int(ht*0.332)\n self.skill_spacing = int(wd*0.25)\n # get a grid with all click politions for color skill buttons\n self.radialskill = np.zeros((3,4,2))\n # fill grid with tuples of x,y for every skill\n self.radialskill[0,0] = game_roi[0] + int(wd*0.183), game_roi[1] + int(ht*0.555)\n self.radialskill[1,0] = game_roi[0] + int(wd*0.39), game_roi[1] + int(ht*0.51)\n self.radialskill[2,0] = game_roi[0] + int(wd*0.5), game_roi[1] + int(ht*0.415)\n self.radialskill[0,1] = game_roi[0] + int(wd*0.358), game_roi[1] + int(ht*0.555)\n self.radialskill[1,1] = game_roi[0] + int(wd*0.565), game_roi[1] + int(ht*0.51)\n self.radialskill[2,1] = game_roi[0] + int(wd*0.675), game_roi[1] + int(ht*0.415)\n self.radialskill[0,2] = game_roi[0] + int(wd*0.59), game_roi[1] + int(ht*0.555)\n self.radialskill[1,2] = game_roi[0] + int(wd*0.797), game_roi[1] + int(ht*0.51)\n self.radialskill[2,2] = game_roi[0] + int(wd*0.907), game_roi[1] + int(ht*0.415)\n # TODO : 4th column (teamups)\n\n # validate tile choice button coordinates\n self.button = game_roi[0]+int(wd*0.5), game_roi[1]+int(ht*0.2)\n\n\n def click_skill(self, coords):\n print(\"click skill at x, y :\", coords)\n ax = self.s0[0] + coords[1] * self.skill_spacing\n ay = self.s0[1]\n # print(\"ax, ay :\", ax, ay)\n pyautogui.moveTo(ax, ay, 0.25)\n pyautogui.click(duration=0.25)\n bx, by = self.radialskill[coords[0], coords[1]]\n # print(\"bx, by :\", bx, by)\n pyautogui.moveTo(bx, by, 0.25)\n # pyautogui.click(clicks=2, interval=0.25)\n pyautogui.click(clicks=2, interval=0.1)\n\n def click_tile(self, coords):\n # click a random tile then click the validate button\n # tile_coordinates:\n tx = self.t0[0] + int(coords[1] * self.tile_spacing)\n ty = self.t0[1] + int(coords[0] * self.tile_spacing)\n \n pyautogui.moveTo(tx, ty, 0.5)\n pyautogui.click()\n pyautogui.moveTo(self.button[0], self.button[1])\n pyautogui.click()\n\n\n def drag_tile(self, tiles_coords):\n \n ax = self.t0[0] + tiles_coords[0][1] * self.tile_spacing\n ay = self.t0[1] + tiles_coords[0][0] * self.tile_spacing\n bx = self.t0[0] + tiles_coords[1][1] * self.tile_spacing\n by = self.t0[1] + tiles_coords[1][0] * self.tile_spacing\n # print(\"mouse movement\", ax,ay,bx,by) # debug\n pyautogui.moveTo(ax, ay, 0.25)\n pyautogui.dragTo(bx, by, 0.25, button='left')\n\n # pyautogui.moveTo(self.tx0 + self.tile_spacing, self.ty0 + self.tile_spacing, 1)\n\n\n\ncapture = PreCapture()\ngame_roi = capture.main_loop()\nmouse = MouseControl()\ngame_capture = RoICapture()\ngame_bot = Bot()\ngame_capture.main_loop()\n","sub_path":"match3-bot.1.4.py","file_name":"match3-bot.1.4.py","file_ext":"py","file_size_in_byte":24799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"141383070","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nsys.path.append('src')\n\nfrom activation import identity, sigmoid\nfrom cost_function import neg_log_likelihood, residual_sum_of_squares\n\nclass LinearModel:\n \"\"\"Sub-class for Linear and Logistic Regression\"\"\"\n def initialize_with_zeros(self, dim):\n \"\"\"Creates vector full of zeros of shape (dim, 1) for w and initializes b to 0.\n\n Args:\n dim: int\n Size of the w vector needed.\n \n Returns:\n parameters: dict\n w: numpy.array\n Initialized vectors full of zeros. Shape dim by 1.\n b: int\n Initialized scalar equal to 0.\n \"\"\"\n w = np.zeros((dim, 1))\n b = int(np.zeros(1))\n assert(w.shape == (dim, 1))\n assert(isinstance(b, float) or isinstance(b, int))\n parameters = {'w':w, 'b':b}\n return parameters\n\n def forward_propagation(self, X, parameters, activation):\n \"\"\"Computes forward propagation.\n\n Args:\n X: numpy.array\n Input data of size n_x by m.\n parameters: dict\n Dictionnary that contaits w and b as values.\n activation: func\n The activation function to used in forward propagation.\n\n Returns:\n a: numpy.array\n The output of the activation function.\n \"\"\"\n # Unpack parameters from dict\n w = parameters['w']\n b = parameters['b']\n # Implement forward propagation\n z = np.dot(w.T, X) + b\n a = activation(z)\n a = a.reshape((X.shape[1], 1))\n return a\n\n def compute_cost(self, a, y, cost_function):\n \"\"\"Computes a given cost function.\n\n Args:\n a: numpy.array\n The output of a activation function.\n y: numpy.array\n The independante variable of the model.\n cost_function: func\n A cost function.\n \n Returns:\n cost: numpy.array\n The output of the given cost function.\n \"\"\"\n return cost_function(self._m, a, y)\n\n def backward_propagation(self, X, y, a):\n \"\"\"Computes backward propagation.\n\n Args:\n X: numpy.array\n Input data of size n_x by m.\n a: numpy.array\n The output of a activation function.\n y: numpy.array\n The independante variable of the model. \n\n Returns:\n grads: dict\n Dictionnary that contains gradients with respect to \n the differents parameters.\n \"\"\"\n dw = 1 / self._m * np.dot(X, (a - y))\n db = 1 / self._m * np.sum(a - y)\n grads = {'dw':dw, 'db':db}\n return grads\n\n def fit(self, X, y, num_iterations, learning_rate = 0.01, nx_axis = 1, print_cost = False, plot_cost = False):\n \"\"\"Finds the optimal parameters by running gradient descent algorithm.\n\n Args:\n X: numpy.array\n Input data of size n_x by m.\n y: numpy.array\n The independante variable of the model. \n num_iterations: int\n The number of iterations to run the gradient descent.\n learning_rate: float\n The rate at which the algorithm is changing the gradient.\n nx_axis: int, default = 1\n On which axis are the features.\n print_cost: bool, default = False\n Print the cost every 100 iterations if True.\n plot: bool, default = False\n Print a plot of the cost function if True.\n \n Attributes:\n params: dict\n A dictionnary that contains the parameters of the model.\n grads: dict\n A dictionnary that contains the final gradients of the descent.\n costs: list\n A list of the final values of the costs.\n\n Returns:\n self: Object\n \"\"\"\n if nx_axis == 1:\n X = X.T\n y = y.reshape((X.shape[1], 1))\n\n self._m = X.shape[1]\n parameters = self.initialize_with_zeros(X.shape[0])\n costs = []\n\n for i in range(num_iterations):\n a = self.forward_propagation(X, parameters, self.activation)\n grads = self.backward_propagation(X, y, a)\n assert(grads['dw'].shape == parameters['w'].shape)\n parameters['w'] -= learning_rate * grads['dw']\n parameters['b'] -= learning_rate * grads['db']\n # Records of costs\n cost = self.compute_cost(a, y, self.cost_function)\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print(\"The cost after iterations {0}: {1}\".format(i, cost))\n \n print(\"The cost after iterations {0}: {1}\".format(num_iterations, cost))\n # Set final parameters\n self.params = {'w' : parameters['w'], 'b': parameters['b']}\n self._grads = {'dw': grads['dw'], 'db' : grads['db']}\n self._cost = costs\n # Plot\n if plot_cost:\n plt.plot(np.squeeze(costs))\n plt.xlabel('Iterations per hundred')\n plt.ylabel('Cost')\n plt.title('Learning rate ' + str(learning_rate))\n plt.show()\n return self\n\n def _predict(self, newdata, nx_axis = 1):\n \"\"\"Predict the value of yhats.\n \n Args:\n newdata: numpy.array\n Features to predict the fitted model on.\n nx_axis: int, default = 1\n On which axis are the features.\n \n Returns:\n y_hat: numpy.array\n The predicted values.\n \"\"\"\n try:\n getattr(self, 'params')\n except:\n raise RuntimeError(\"Fit must be executed before the predict method.\")\n if nx_axis == 1:\n newdata = newdata.T\n y_hat = self.forward_propagation(newdata, self.params, self.activation)\n return y_hat\n\n\nclass LinearRegression(LinearModel):\n \"\"\"Computes a linear regression model.\"\"\"\n def __init__(self):\n self.activation = identity\n self.cost_function = residual_sum_of_squares\n\n def predict(self, newdata, nx_axis = 1):\n \"\"\"Predict the value of yhats.\n \n Args:\n newdata: numpy.array\n Features to predict the fitted model on.\n nx_axis: int, default = 1\n On which axis are the features.\n \n Returns:\n y_hat: numpy.array\n The predicted values.\n \"\"\"\n return self._predict(newdata, nx_axis=1)\n\n\nclass LogisticRegression(LinearModel):\n \"\"\"Computes Logistic Regression for binary target variable.\"\"\"\n def __init__(self):\n self.activation = sigmoid\n self.cost_function = neg_log_likelihood\n\n def predict(self, newdata, nx_axis = 1, returns_probability = False, threshold = 0.5):\n \"\"\"Predict the value of yhats.\n \n Args:\n newdata: numpy.array\n Features to predict the fitted model on.\n nx_axis: int, default = 1\n On which axis are the features.\n returns_probability: bool, default = True\n Wheter returns the outputted probability or a\n categorical y_hat.\n threshold: float, default = 0.5\n The threshold at which choose 1 instead of 0. \n \n Returns:\n y_hat: numpy.array\n The predicted values.\n \"\"\"\n if threshold >= 1 or threshold <= 0:\n raise ValueError(\"threshold must be between 0 and 1.\")\n prob = self._predict(newdata, nx_axis)\n if returns_probability:\n return prob\n else:\n y_hat = np.zeros((len(prob), 1))\n y_hat[prob > threshold] = 1\n return np.array(y_hat)\n\n\n\n\n \n","sub_path":"src/linear_model.py","file_name":"linear_model.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"159658332","text":"n_list = [1,2,3,4,5,6,7,8,9,10]\r\nr1 = range(1500, 3001)\r\n\r\n\r\nresult_list = []\r\n\r\nprint(r1)\r\n\r\nfor i in r1:\r\n\tif i % 7 == 0 and i % 5 == 0:\r\n\t\tresult_list.append(i)\r\n\r\nprint(result_list)\r\n\r\n'''\r\nfor i in r1:\r\n\tprint('Range Element: ', i)\r\n'''\r\n\r\n'''\r\n1500 to 3000\r\nprint the integers that are divisible by 7 and multiples of 5.\r\n'''\r\n\r\n","sub_path":"loops/for-demo.py","file_name":"for-demo.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"406366861","text":"#########################################################################\r\n# MXDeploy\r\n# Copyright MXDeploy 2014\r\n# All Rights Reserved.\r\n#\r\n# Script: AdminCell.py\r\n# Author: Fabio Santos B. da Silva - fsbsilva@gmail.com\r\n# Version: 1.0.0\r\n#\r\n# Date: 01/01/2014\r\n# Purpose: Configure Cell\r\n#########################################################################\r\nimport re\r\n\r\nfrom com.wds.bean import Cell, EndPoint\r\n\r\nimport AdminUtil\r\nimport logging\r\n\r\nimport AdminConfig, AdminControl, AdminApp, Help\r\n\r\ndef getCellName():\r\n cell = AdminConfig.list('Cell')\r\n return AdminConfig.showAttribute(cell,'name') \r\n\r\ndef checkIfWebServerExists(wsName):\r\n \r\n wsList=AdminConfig.list('WebServer')\r\n wsList=AdminUtil.convertToList(wsList)\r\n \r\n for value in wsList:\r\n name = AdminConfig.showAttribute(value,'name')\r\n if( name.find(wsName)!=-1 ):\r\n return 1\r\n \r\n return 0\r\n\r\n\r\ndef getWebServerNode(wsName):\r\n wsList=AdminConfig.list('WebServer')\r\n wsList=AdminUtil.convertToList(wsList)\r\n \r\n for value in wsList:\r\n name = AdminConfig.showAttribute(value,'name')\r\n if( name.find(wsName)!=-1 ):\r\n server = AdminConfig.showAttribute(value,'server')\r\n # This Method is using Regular Expression to get the Node from the WebServer\r\n matchObj = re.search( r'nodes.(.+?).servers', server, re.M|re.I)\r\n return matchObj.group(1)\r\n return \"\"\r\n \r\ndef loadBean():\r\n cell = Cell()\r\n \r\n cellID = AdminConfig.list('Cell')\r\n cellName = AdminConfig.showAttribute(cellID,'name')\r\n \r\n cell.setName( cellName )\r\n \r\n serverIndexList = AdminConfig.list('ServerIndex')\r\n serverIndexList = AdminUtil.convertToList(serverIndexList)\r\n\r\n for serverIndex in serverIndexList:\r\n value = AdminConfig.showall(serverIndex)\r\n if (value.find(\"DEPLOYMENT_MANAGER\") != -1 ):\r\n serverEntries = AdminConfig.showAttribute(serverIndex,'serverEntries')\r\n serverEntries = AdminUtil.convertToList(serverEntries)\r\n serverEntry = serverEntries[0]\r\n\r\n specialEndpoints = AdminConfig.showAttribute(serverEntry,'specialEndpoints')\r\n specialEndpoints = AdminUtil.convertToList(specialEndpoints)\r\n\r\n endPoint = EndPoint()\r\n cell.setEndPoint(endPoint)\r\n \r\n endPoint.setType(EndPoint.TYPE_DEPLOYMENT_MANAGER);\r\n \r\n \r\n for specialEndpoint in specialEndpoints:\r\n endPointNameAttr = AdminConfig.showAttribute(specialEndpoint,'endPointName')\r\n endPointAttr = AdminConfig.showAttribute(specialEndpoint,'endPoint')\r\n port = AdminConfig.showAttribute(endPointAttr,'port')\r\n\r\n if( endPointNameAttr == EndPoint.ORB_LISTENER_ADDRESS_NAME ):\r\n endPoint.setOrbListenerAddress(port)\r\n \r\n if( endPointNameAttr == EndPoint.SOAP_CONNECTOR_ADDRESS_NAME ):\r\n endPoint.setSoapConnectorAddress(port)\r\n \r\n if( endPointNameAttr == EndPoint.BOOTSTRAP_ADDRESS_NAME ):\r\n endPoint.setBootStrapAddress(port)\r\n \r\n if( endPointNameAttr == EndPoint.WC_DEFAULTHOST_SECURE_NAME ):\r\n endPoint.setWCDefaultHostSecure(port) \r\n \r\n if( endPointNameAttr == EndPoint.WC_ADMINHOST_SECURE_NAME ):\r\n endPoint.setWCAdminHostSecure(port) \r\n \r\n if( endPointNameAttr == EndPoint.WC_DEFAULTHOST_NAME ):\r\n endPoint.setWCDefaultHost(port)\r\n \r\n if( endPointNameAttr == EndPoint.WC_ADMINHOST_NAME ):\r\n endPoint.setWCAdminHost(port) \r\n \r\n# logging.info( \"+---------------------------------------------------------------------+\" )\r\n# logging.info( \"+ Cell \"+cell.getName()+\" - Synchronized\" )\r\n# logging.info( \"+---------------------------------------------------------------------+\" )\r\n# logging.info( \" \" )\r\n \r\n return cell","sub_path":"jython/ext/AdminCell.py","file_name":"AdminCell.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"293863525","text":"from Path.image_function import transform, combine, detect, lane_detect, transform2, get_stop_line, ret_shift_const, gamma_correction\nimport cv2\n\nclass Line:\n def __init__(self, db):\n self.db = db\n \n #차량의 조향각과 현재 차선을 기준으로 얼마나 치우쳐져 있는지를 db의 position과 degree에 값을 리턴한다.\n #degree는 0도 일 때 정면이며, -일경우로 왼쪽, +일 경우 오른쪽으로 치우쳐져 있음을 나타내고\n #position은 0.5일 때 중앙, 0.5보다 작을 경우 왼쪽, 클 경우 오른쪽으로 치우쳐져 있다.\n def set_info(self):\n left_cam = self.db.main_cam.data # db로부터 Camera law data를 받는다.\n right_cam = self.db.sub_cam.data\n img_left, img_right = transform(left_cam, right_cam) # image_function의 transform 함수로 원근변환한다.\n img_concat = combine(img_left, img_right) # 원근변환한 이미지를 붙인다.\n img_bin = detect(img_concat) # 붙인 이미지를 이진변환한다.\n position, degree, ret_img = lane_detect(img_bin) # 이진변환한 이미지로부터, 라인을 추출하고 position과 degree를 도출한다.\n img_ret = cv2.add(ret_img, img_bin) #img_ret은 추출한 라인과 degree, position을 함께 볼 수 있는 결과 이미지다.\n cv2.imshow(\"img_ret\", img_ret)\n cv2.waitKey(1)\n\n self.db.position = position #db에 position과 degree를 넣는다. 이는 나중에 제어에서 사용하게 된다.\n self.db.degree = degree\n \n #정지선을 검출하고 정지신호를 보낸다.\n def check_stop_line(self):\n front_cam = self.db.parking_cam.data # db로부터 정면 Camera law data를 받는다.\n gamma_correction(front_cam, 2) # 감마보정을 이용하는데, 두번째 argument는 상황에 따라 조정해야 한다.\n img_front = transform2(front_cam) # 받은 이미지를 원근 변환한다.\n img_bin = detect(img_front) # 원근 변환한 이미지를 이진화한다.\n cv2.imshow(\"Crosswalk\", img_bin)\n return get_stop_line(img_bin) # 이진화된 이미지를 get_stop_line를 이용해 정지선을 검출한다.\n \n #concat할 때 좌우 라인의 공간을 직접 측정하여 넣게 되는데, 이 값은 shift_const와 관계가 있다. 이를 리턴한다.\n def get_shift_const(self):\n return ret_shift_const\n","sub_path":"PAMS_2019/Path/Line.py","file_name":"Line.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222053924","text":"from bottle import response,request as req\nimport models\n\ndef rest():\n\tres = logic(req.query.get(\"note-id\"))\n\tresponse.status = res[\"code\"]\n\treturn res[\"res\"]\n\ndef logic(noteId):\n\tif(not noteId):\n\t\tstatus = 400\n\t\tres = {\"error\":\"empty-note-id\"}\n\telse:\n\t\tnote = models.Note.objects(id=noteId)\n\t\tif(note):\n\t\t\tstatus = 200\n\t\t\tres = note[0].to_rest()\n\t\telse:\n\t\t\tstatus = 404\n\t\t\tres = {\"error\":\"note-not-found\"}\n\treturn {\"code\":status,\"res\":res}\n","sub_path":"src/api/note/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"550133184","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport requests\nimport os\nfrom time import sleep\n\ndef download(url, fileName):\n\t\"\"\"\n\tDownloads file given by url to given filename.\n\tIf already something exists with this filename, it replaces this.\n\tIt is implemented with streams so that also very large files can be\n\tdownloaded without having a memory overload.\n\t\"\"\"\n\t\"\"\"The function will do at most 10 attemps to download the file\"\"\"\n\tfor i in range(10):\n\t\ttry:\n\t\t\ttry:\n\t\t\t\t\"\"\"Delete existing file with filename\"\"\"\n\t\t\t\tos.remove(fileName) \n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\t\n\t\t\t\"\"\"file is downloaded in chunks\"\"\"\n\t\t\twith requests.get(url, stream=True) as r:\n\t\t\t\tr.raise_for_status()\n\t\t\t\twith open(fileName, 'wb') as f:\n\t\t\t\t\tfor chunk in r.iter_content(chunk_size=8192): \n\t\t\t\t\t\tif chunk:\n\t\t\t\t\t\t\tf.write(chunk)\n\t\t\treturn fileName\n\t\texcept:\n\t\t\t\"\"\"Wait between requests increases because some servers will\n\t\t\tblock it when to many requests are asked at once\"\"\"\n\t\t\tprint(\"Download\", url,\"failed:\",i)\n\t\t\tsleep(5*(i+1))\n \ndef uniprotRetrieve(fileName, query=\"\",format=\"list\",columns=\"\",include=\"no\",compress=\"no\",limit=0,offset=0):\n \"\"\"Downloads file from uniprot for given parameters\n \n If no parameters are given the function will download a list of all the \n proteins ID's. More information about how the URL should be constructed can\n be found on: \n https://www.uniprot.org/help/api%5Fqueries\n \n Parameters\n ----------\n fileName : str\n name for the downloaded file\n query : str (Default='')\n query that would be searched if as you used the webinterface on \n https://www.uniprot.org/. If no query is provided, all protein entries\n are selected. \n format : str (Default='list')\n File format you want to retrieve from uniprot. Available format are:\n html | tab | xls | fasta | gff | txt | xml | rdf | list | rss\n columns : str (Default='')\n Column information you want to know for each entry in the query \n when format tab or xls is selected.\n include : str (Default='no')\n Include isoform sequences when the format parameter is set to fasta.\n Include description of referenced data when the format parameter is set to rdf.\n This parameter is ignored for all other values of the format parameter.\n compress : str (Default='no')\n download file in gzipped compression format.\n limit : int (Default=0)\n Limit the amount of results that is given. 0 means you download all.\n offset : int (Default=0)\n When you limit the amount of results, offset determines where to start.\n \n Returns\n -------\n fileName : str\n Name of the downloaeded file.\n \"\"\"\n def generateURL(baseURL, query=\"\",format=\"list\",columns=\"\",include=\"no\",compress=\"no\",limit=\"0\",offset=\"0\"):\n \"\"\"Generate URL with given parameters\"\"\"\n def glueParameters(**kwargs):\n gluedParameters = \"\"\n for parameter, value in kwargs.items():\n gluedParameters+=parameter + \"=\" + str(value) + \"&\"\n return gluedParameters.replace(\" \",\"+\")[:-1] #Last \"&\" is removed, spacec replaced by \"+\"\n return baseURL + glueParameters(query=query,\n format=format,\n columns=columns,\n include=include,\n compress=compress,\n limit=limit,\n offset=offset)\n URL = generateURL(\"https://www.uniprot.org/uniprot/?\",\n query=query,\n format=format,\n columns=columns,\n include=include,\n compress=compress,\n limit=limit,\n offset=offset)\n return download(URL, fileName)\n\ndef mapping(queryFile,outputFile, parameterDictionary):\n def addQuery():\n with open(queryFile) as f:\n parameterDictionary[\"query\"]=\"\".join(f.readlines())\n def main():\n addQuery()\n url = 'https://www.uniprot.org/uploadlists/'\n data = urllib.parse.urlencode(parameterDictionary)\n data = data.encode('utf-8')\n req = urllib.request.Request(url, data)\n with urllib.request.urlopen(req) as f:\n response = f.read()\n with open(outputFile, 'b+w') as f:\n f.write(response)\n for i in range(10):\n main()\n try:\n if os.stat(outputFile).st_size != 0:\n break\n except:\n print(\"Try\",i,\"Failed\")\n sleep(5*(i+1))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533826502","text":"import string\n\nsdict = { '' : ('') }\ndigits = { '1' : 1, '2' : 1, '3' : 1, '4' : 1,\n '5' : 1, '6' : 1, '7' : 1, '8' : 1,\n '9' : 1, '0' : 1 }\n\ndef splitter (s):\n global sdict\n if s in sdict:\n return sdict[s]\n last = 0\n items = []\n sl = string.lower (s)\n in_digits = sl[0] in digits\n for i in range(0, len(sl)):\n if (sl[i] in digits) != in_digits:\n if in_digits:\n items.append (string.atoi(sl[last:i]))\n else:\n items.append (sl[last:i])\n last = i\n in_digits = not in_digits\n if in_digits:\n items.append (string.atoi (sl[last:]))\n else:\n items.append (sl[last:])\n sdict[s] = tuple(items)\n return sdict[s]\n\ndef nomenCompare (s1, s2):\n return cmp(splitter(s1), splitter(s2))\n","sub_path":"mgipython/service/helpers/symbolsort.py","file_name":"symbolsort.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212951902","text":"import os\nfrom time import sleep\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom fileUtil import getVideoFiles,getAccounts,moveFile,removeLinkLine,getConfigByKey,removeAccountLine,convertList\nfrom jiebaUtil import dividewords\nfrom queue import Queue\nimport random\n\nclass NetbaseRobot:\n loginUrl = \"http://dy.163.com/wemedia/login.html\"\n accountList = []\n videoList = []\n videoIndex = 0\n articleList = []\n articleIndex = 0\n articleQueue =Queue()\n articleTitleDic = {}\n\n def __init__(self):\n self.accountList = getAccounts()\n self.videoList = getVideoFiles()\n linksContent = open(\"links.txt\", encoding='utf-8').read()\n\n for link in linksContent.split(\"\\n\"):\n link = link.strip()\n if link == \"\":\n continue\n arr = convertList(link)\n self.articleQueue.put(arr[0])\n if len(arr)>1:\n self.articleTitleDic[arr[0]] = arr[1]\n self.driver = webdriver.Chrome()\n self.wait = WebDriverWait(self.driver, 60)\n self.driver.maximize_window()\n self.downloadArticleOrNot()\n\n def downloadArticleOrNot(self):\n # self.driver.set_page_load_timeout(15)\n print(\"程序检查是否需要再下载文章,总共有\"+ str(self.articleQueue.qsize()) +\"文章没下载\")\n while not self.articleQueue.empty() and len(self.articleList) - self.articleIndex<7:\n newLink = self.articleQueue.get()\n title, content = self.fetchLinksContent(newLink)\n if title == \"\" or content == \"\":\n removeLinkLine(newLink)\n continue\n self.articleList.append({\"title\": title, \"content\": content,\"url\":newLink})\n # self.driver.set_page_load_timeout(30)\n\n def login(self,idx):\n if len(self.accountList) <= idx:\n print(\"无法登陆了\")\n return\n account = self.accountList[idx][0]\n pw = self.accountList[idx][1]\n print(account + \" 准备登陆\")\n self.driver.get(self.loginUrl)\n\n frame =self.wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'iframe')))\n # frame = self.driver.find_element_by_tag_name(\"iframe\")\n id = frame.get_attribute(\"id\")\n self.driver.switch_to.frame(id)\n nameElement = self.wait.until(EC.visibility_of_element_located((By.NAME, 'email')))\n # nameElement = self.driver.find_element_by_name(\"email\")\n nameElement.clear()\n nameElement.send_keys(account)\n pwElement = self.driver.find_element_by_name(\"password\")\n pwElement.clear()\n pwElement.send_keys(pw)\n loginButton = self.driver.find_element_by_id(\"dologin\")\n loginButton.click()\n sleep(2)\n if \"account-banned\" in self.driver.current_url:\n print(account +\"帐号被禁了,程序会从account.txt中移除它\")\n removeAccountLine(account,pw)\n self.turnToNextAccout(idx)\n return\n self.driver.execute_script(\"\"\"\n if(document.getElementsByClassName(\"ne-confirm\").length>0){\n document.querySelector(\".ne-btn-hollow\").click();\n }\n \"\"\")\n # 发布文章\n while True:\n article = self.chooseArticle()\n if article is None:\n break\n isDone = self.doFormSubmit(article, account)\n if isDone == False:\n self.turnToNextAccout(idx)\n return\n else:\n self.articleIndex = self.articleIndex + 1\n\n # 发布视频\n while True:\n video = self.chooseVideo()\n if video is None:\n break\n isDone = self.submitVideoForm(video)\n if isDone == False:\n self.turnToNextAccout(idx)\n return\n else:\n self.videoIndex = self.videoIndex + 1\n\n print(\"操作结束,原因有可能是没有可更新的资源\")\n self.driver.close()\n\n\n def turnToNextAccout(self,idx):\n sleep(1)\n if \"account-banned\" not in self.driver.current_url:\n self.logOut()\n idx = idx + 1\n if len(self.accountList) > idx:\n self.login(idx)\n else:\n print(\"帐号用完了,操作结束\")\n self.driver.close()\n\n def chooseArticle(self):\n if self.articleIndex < len(self.articleList):\n return self.articleList[self.articleIndex]\n return None\n\n def chooseVideo(self):\n if self.videoIndex < len(self.videoList):\n return self.videoList[self.videoIndex]\n return None\n\n # 爬虫抓取文章内容\n def fetchLinksContent(self,link):\n print(\"开始下载文章\"+link)\n httpIndex = link.find(\"http://\")\n httpsIndex = link.find(\"https://\")\n if httpIndex>0 or httpsIndex>0:\n link = link[httpsIndex+httpIndex+1:]\n self.driver.get(link)\n\n try:\n if \"kuaibao.qq.com\" in self.driver.current_url:\n titleElement = self.wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'title')))\n self.driver.execute_script(\n '$(\"#content\").find(\".title\").remove();$(\"#content\").find(\".cardBoxWrap\").remove();')\n elif \"mbd.baidu.com\" in self.driver.current_url:\n titleElement = self.driver.execute_script('return document.querySelector(\"h1\")')\n if titleElement is None:\n titleElement = self.driver.find_element_by_xpath(\"//span[@class='titleTxt']\")\n self.driver.execute_script(\"\"\"\n $(\".packupButton\").click(); \n \"\"\")\n elif \"51taojinge.com\" in self.driver.current_url or \"html.1sapp.com\" in self.driver.current_url:\n titleElement = self.driver.execute_script('return document.querySelector(\"h1\")')\n elif \"a.mp.uc.cn\" in self.driver.current_url:\n titleElement = self.wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'article-title')))\n self.driver.execute_script(\"\"\"\n $(\".show-all\").click();\n $(\".weixin\").remove();\n $(\".article-content\").find(\"iframe\").remove();\n Array.prototype.slice.call(document.querySelector(\".article-content\").querySelectorAll(\"img\")).forEach(function(img){ img.src = img.attributes[\"data-original\"].value})\n \"\"\")\n else:\n if \"po.baidu.com/feed/error\" in self.driver.current_url:\n print(\"文章被禁,从links.txt中移除\")\n return \"\", \"\"\n titleElement = self.wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'h1')))\n self.driver.execute_script(\"\"\"\n (function(){\n window.scroll(0,document.body.scrollHeight); \n })();\n \"\"\")\n contentElement = None\n if \"baijiahao.baidu.com\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//div[@id='content']\")\n elif \"mbd.baidu.com\" in self.driver.current_url:\n contentElement = self.driver.execute_script('return $(\".mainContent\")[0]')\n elif \"a.mp.uc.cn\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//div[@class='article-content simple-ui']\")\n elif \"kuaibao.qq.com\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//div[@class='content-box']\")\n elif \"toutiao.com\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//div[@class='article-content']\")\n elif \"sohu.com\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//article[@class='article']\")\n elif \"51taojinge.com\" in self.driver.current_url or \"html.1sapp.com\" in self.driver.current_url:\n contentElement = self.driver.find_element_by_xpath(\"//div[@class='content']\")\n content = self.driver.execute_script(\"return arguments[0].innerHTML\", contentElement)\n content = content.replace(' src=\"//', ' src=\"http://')\n content = content.replace(' src=\"https//', ' src=\"http://')\n content = content.replace(\"&\", \"&\")\n content = content.replace(\"padding-top\", \"padding-top-x\")\n return titleElement.text, content\n except:\n print(\"抓取异常\")\n return \"\",\"\"\n\n # 每个帐号每天的限额是6个,判断上传的资源是否超出6\n def canSubmit(self):\n result = self.driver.execute_script('return parseInt($(\".z-red-font\").text())')\n return result < 6\n\n # 退出登陆\n def logOut(self):\n logOutButton = self.wait.until(EC.element_to_be_clickable((By.ID, 'logout')))\n #logOutButton = self.driver.find_element_by_id(\"logout\")\n logOutButton.click()\n print(\"退出登陆\")\n sleep(1)\n self.downloadArticleOrNot()\n\n # 点击发布MENU\n def clickDeliveryMenu(self):\n articleMenu = self.wait.until(EC.element_to_be_clickable((By.XPATH, '(//li[@class=\"menu-item\"])[2]')))\n articleMenu.click()\n\n # 保存文章\n def doFormSubmit(self,article, account):\n sleep(random.choice([2, 4, 6]))\n title, content = article[\"title\"], article[\"content\"]\n if article[\"url\"] in self.articleTitleDic.keys():\n title = self.articleTitleDic[article[\"url\"]]\n self.clickDeliveryMenu()\n\n if self.canSubmit() == False:\n return False\n\n sleep(2)\n titleElement = self.driver.find_element_by_id(\"title\")\n titleElement.clear()\n if len(title) > 27:\n title = title[0:27]\n while len(title) < 12:\n title = title + \"一\"\n titleElement.send_keys(title)\n editorElement = self.driver.find_element_by_id(\"container\")\n editorElement.clear()\n # editorElement.send_keys(content)\n content = content.replace(\"\\n\", \"\")\n self.driver.execute_script(\"arguments[0].innerHTML = '\" + content + \"'\", editorElement)\n dropDownToggle = self.driver.find_element_by_class_name(\"dropdown-toggle\")\n dropDownToggle.click()\n categoryName = '' + getConfigByKey(\"文章分类\") + ''\n categoryAnchor = self.wait.until(EC.element_to_be_clickable((By.XPATH, \"//a[@data-normalized-text='\" + categoryName + \"']\")))\n categoryAnchor.click()\n\n self.driver.find_element_by_xpath(\"//a[@href='#auto']\").click()\n sleep(random.randrange(5, 10))\n #self.driver.find_element_by_xpath(\"//div[@class='cover-img']\").click()\n\n self.driver.find_element_by_class_name(\"js_article_submit\").click()\n sleep(random.randrange(1, 2))\n btnOk = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'js-btn-ok')))\n result = self.driver.execute_script('return $(\".modal-body\").text()')\n print(\"帐号:\" + account + \" 标题:\" + title + \" 处理结果:\" + result)\n btnOk.click()\n if result.__contains__(\"已经发布过\"):\n\n removeLinkLine(article[\"url\"])\n print(\"发布失败:\" + result)\n sleep(1)\n self.driver.execute_script(\"\"\"\n (function(){\n window.scroll(0,0); \n })();\n \"\"\")\n self.driver.refresh()\n self.driver.switch_to.alert.accept()\n anchorCancel = self.driver.find_element_by_xpath(\"//a[text()='取消']\")\n self.jsClick(anchorCancel)\n self.driver.find_element_by_xpath(\"//a[contains(text(),'内容管理')]\").click()\n else:\n removeLinkLine(article[\"url\"])\n print(\"发布成功,从links.txt文件中移除链接\"+article[\"url\"])\n\n return True\n\n # 提交视频\n def submitVideoForm(self,video):\n filePath = video[\"url\"]\n try:\n self.clickDeliveryMenu()\n except:\n self.driver.refresh()\n self.submitVideoForm(filePath)\n\n if self.canSubmit() == False:\n return False\n\n tabs = self.driver.find_elements_by_class_name(\"tab\")\n tabs[2].click()\n sleep(1)\n nameWithExtendsion = os.path.basename(filePath)\n nameWithExtendsion = nameWithExtendsion.split(\".\")[0]\n if len(nameWithExtendsion) < 11 or len(nameWithExtendsion) > 27:\n print(\"invalid path name\")\n return False\n titleElement = self.driver.find_element_by_id(\"video-up-input\")\n titleElement.send_keys(filePath)\n keywords = dividewords(nameWithExtendsion,video[\"category\"])\n sleep(1)\n tagsInput = self.driver.find_element_by_id(\"form-tags-input\")\n descriptionInput = self.driver.find_element_by_id(\"description\")\n for keyword in keywords:\n tagsInput.clear()\n tagsInput.send_keys(keyword)\n descriptionInput.clear()\n sleep(1)\n\n # 选择视频分类为娱乐\n self.driver.find_element_by_xpath(\"//button[@data-id='c-first']\").click()\n\n categoryName = '' + video[\"category\"] + ''\n categoryAnchor = self.driver.find_element_by_xpath(\"//a[@data-normalized-text='\" + categoryName + \"']\");\n categoryAnchor.click()\n # 默认选择自动\n self.driver.find_element_by_xpath(\"//label[@for='cover1']\").click()\n # 选择封面\n sleep(3)\n cover = self.driver.find_element_by_class_name(\"pic-cut\")\n coverList = cover.find_elements_by_tag_name(\"li\")\n\n #有可能视频传得慢,所以这里要等\n retryCount = 20\n while len(coverList) <=0 and retryCount>0:\n sleep(2)\n coverList = cover.find_elements_by_tag_name(\"li\")\n retryCount = retryCount -1\n\n if len(coverList) <=0:\n print(\"上传失败,有可能是视频上传较慢导致,请检查网络是否畅通,视频大小是否正常\")\n return False\n else:\n coverList[0].click()\n # 提交表单\n sleep(1)\n self.driver.find_element_by_xpath(\"//button[@type='submit']\").click()\n btnOk = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'js-btn-ok')))\n result = self.driver.execute_script('return $(\".modal-body\").text()')\n print( \" 视频文件:\" + filePath + \" 处理结果:\" + result)\n btnOk.click()\n moveFile(video[\"url\"])\n print(\"将\"+video[\"url\"]+\"移动到handled文件夹中\")\n return True\n\ntry:\n robot = NetbaseRobot()\n robot.login(0)\nexcept Exception as e :\n print(e)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"510079141","text":"candidate_itemsets = None\nfrequent_itemsets = None\ninput_file = None\noutput_file = None\nnum_item = 0\nnum_tran = 0\nmin_sup = 0\ntrans_list = []\nfrom itertools import combinations\nimport sys\n\n\ndef config(args = [\"market_data_binary.txt\",0.5,\"output.txt\"]):\n global input_file,output_file\n global min_sup\n global num_trans, num_item\n global trans_list\n num_trans = 0\n # Get the input args\n input_file = args[0]\n min_sup = float(args[1])\n if 1 < min_sup < 0:\n raise Exception\n output_file = args[2]\n\n # initialize num_trans and num_item\n with open (input_file,'r') as f:\n for line in f:\n split_line = line.split()\n split_line = [int(i) for i in split_line]\n trans_list.append(split_line)\n num_trans += 1\n num_item = len(split_line)\n f.close()\n print(\"Input File \" + input_file + \"Output File\" + output_file)\n print(\"Input configuration: \" + str(num_item) + \"items, \" + str(num_trans) + \"transactions, \")\n print(\"minsup = \" + str(min_sup))\n\n\ndef assign(a_list,var):\n if len(a_list) == 0:\n a_list = var\n else:\n a_list.append(var)\n\ndef execute():\n try:\n curr_length = 1\n global candidate_itemsets, frequent_itemsets\n global num_item\n candidate_itemsets = [[]]\n frequent_itemsets = [[]]\n candidate_itemsets.append([])\n for i in range(num_item):\n cand = [i]\n candidate_itemsets[-1].append(cand)\n while len(candidate_itemsets[-1])> 0:\n frequent_itemsets.append([])\n gen_frequent_itemsets(curr_length)\n curr_length += 1\n candidate_itemsets.append([])\n if len(frequent_itemsets[curr_length-1]) != 0:\n gen_candidate_itemsets(curr_length)\n except:\n raise Exception\n\n# Choose frequent itemsets based on candidate itemsets\ndef gen_frequent_itemsets(curr_length):\n st = []\n for line in trans_list:\n fi2 = []\n j=0\n for ele in line:\n if ele == 1:\n fi2.append('I'+str(j));\n j=j+1\n st.append(fi2)\n#-------------------------------------------------\n ci2=[]\n for i in range(num_item):\n if ci2.count('I'+str(i))==0:\n ci2.append('I'+str(i))\n#-------------------------------------------------\n freq = []\n cand = []\n dd = iter(ci2,st)\n freq = dd[0][:]\n cand = dd[1][:]\n frequent_itemsets.append(freq)\n while len(freq)>1:\n s = allT(freq)\n dd = iter3(freq,s,st)\n cand=dd[1][:]\n freq=dd[0][:]\n if len(cand)>0:\n candidate_itemsets.append(cand)\n if len(freq)>0:\n frequent_itemsets.append(freq)\n \ndef iter3(set,against,st):\n cl = [];fl = [];final = [];finale = [];\n cand = []\n p=1\n target_size=len(set[0])+1\n for ele1 in set:\n for ele2 in against:\n wz=collide(ele1,[ele2])\n if len(wz)>=target_size:\n wp = cunt(wz,[],st)\n if wp>0:\n final.append(wz)\n if wp>=(len(trans_list)*min_sup):\n finale.append(wz)\n p+=1\n la = compil(finale)\n laz = compil(final)\n for ele1 in laz:\n p=0\n for ele2 in set:\n if contained_in(ele2,ele1):\n p+=1\n if p>=target_size:\n cand.append(ele1)\n return (la,cand)\n \ndef contained_in(wx,wy):\n possible = True\n for ele in wx:\n if wy.count(ele)==0:\n return False\n return True\n \ndef compil(res):\n final=[]\n for ele in res:\n ele.sort()\n if final.count(ele)==0:\n final.append(ele)\n return final\n \ndef collide(wx,wy):\n final = []\n wx.sort()\n wy.sort()\n for ele1 in wx:\n if final.count(ele1)==0:\n final.append(ele1)\n for ele2 in wy:\n if final.count(ele2)==0:\n final.append(ele2)\n return final\n \ndef iter(set,st):\n fl=[]\n cl=[]\n for req in set:\n if cl.count(req)==0:\n cl.append([req])\n if cunt([req],[],st)>=(len(trans_list)*min_sup):\n if fl.count(req)==0:\n fl.append([req])\n return(fl,cl)\n \ndef allT(lst):\n final=[]\n for ele1 in lst:\n for ele2 in ele1:\n if final.count(ele2)==0:\n final.append(ele2)\n return final\n \ndef cunt(wx,wy,st):\n pas = 0\n cnt = 0\n for trans in st:\n possible=True\n for ele in wx:\n if st[pas].count(ele)==0:\n possible=False\n for ele in wy:\n if st[pas].count(ele)==0:\n possible=False\n if possible == True:\n cnt+=1\n pas+=1\n return cnt\n\ndef output_result():\n global output_file\n global frequent_itemsets\n global candidate_itemsets\n with open (output_file, 'w') as f:\n for i in range(1, len(frequent_itemsets)-1):\n f.write(\"Lengh \" + str(i) + \":\\n\")\n candidate_itemsets[i].sort()\n f.write(\"Candidate: \\n\")\n for j in range(len(candidate_itemsets[i])):\n f.write(str(candidate_itemsets[i][j]) + \" \")\n f.write(\"\\n\")\n f.write(\"Number of candidates: \" + str(len(candidate_itemsets[i])) + \"\\n\")\n frequent_itemsets[i].sort()\n f.write(\"Frequent Itemsets: \\n\")\n for j in frequent_itemsets[i+1]:\n f.write(str(j) + \" \")\n f.write(\"\\n\")\n f.write(\"Number of frequent itemssets: \" + str(len(frequent_itemsets[i+1])) + \"\\n\")\n f.close()\n \n\ndef main():\n arg = sys.argv[1:]\n if len(arg) > 2:\n arg[1] = float(arg[1])\n config(arg)\n else:\n config()\n execute()\n output_result()\nmain()\n","sub_path":"files/other/DM_Apriori/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"404547438","text":"import requests\nimport pandas as pd\nimport datetime\nimport os\n##################Second API query(using 'FlightInfo')\napikey = '7038ce657e42de52eaf5af4126a5fbbf0f4f0a43'\nusername = 'yangxi1994'\nurl_base = ''.join(['http://', username,':',\n apikey,'@flightxml.flightaware.com/json/FlightXML2/FlightInfo'])\n\nairline=pd.read_csv('Departure_Output/noondeparture.csv')\nairline=list(airline['ident'])\n\nurl_post = {'ident': airline[0],\n 'howmany':'15',\n }\nresponse=requests.get(url_base, url_post)\njsontxt = response.json()\ndf=pd.DataFrame(jsontxt['FlightInfoResult']['flights'][0],index=[airline[0]])\nfor i in range(1,len(jsontxt['FlightInfoResult']['flights'])):\n df2=pd.DataFrame(jsontxt['FlightInfoResult']['flights'][i],index=[airline[0]])\n df=df.append(df2)\n\n\nfor item in airline[1:(len(airline)-1)]:\n url_post = {'ident': item,\n 'howmany':'15',\n }\n \n # Use the get function of requests library to get data.\n response=requests.get(url_base, url_post)\n \n # The result is convereted to json format\n jsontxt = response.json()\n for i in range(0,len(jsontxt['FlightInfoResult']['flights'])):\n df2=pd.DataFrame(jsontxt['FlightInfoResult']['flights'][i],index=[item])\n df=df.append(df2)","sub_path":"Part1/Group3 Project Part1/Python/Collection/collect_flightinfo.py","file_name":"collect_flightinfo.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"394372805","text":"import random\n\nimport factory\nfrom django.contrib.gis.geos import Polygon, Point\n\nfrom supply.models import Supplier, ServiceArea, Service\n\n\ndef get_random_phone_number():\n return '+{}'.format(random.randint(79068077767, 89968077767))\n\n\ndef get_random_geo_polygon():\n count = random.randint(2, 5)\n first_point = Point(\n random.randint(-90, 90),\n random.randint(-90, 90), srid=4326\n )\n last_point = first_point\n\n polys_points = ()\n for _ in range(count):\n while True:\n point = Point(\n first_point.x + random.randint(-5, 5),\n first_point.y + random.randint(-5, 5),\n srid=4326\n )\n if not first_point.equals(point):\n polys_points += (point,)\n break\n poly = (first_point,) + polys_points + (last_point,)\n return Polygon(poly, srid=4326)\n\n\ndef get_random_service_price():\n return '{}'.format((random.randint(1, 1200000)))\n\n\nclass SupplierFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Supplier\n\n title = factory.Faker('first_name')\n phone_number = factory.LazyAttribute(lambda x: get_random_phone_number())\n email = factory.LazyAttribute(\n lambda x: '{}@example.com'.format(x.title).lower()\n )\n address = factory.Faker('address')\n\n\nclass ServiceAreaFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = ServiceArea\n\n title = factory.Faker('last_name')\n poly = factory.LazyAttribute(lambda x: get_random_geo_polygon())\n supplier = factory.SubFactory(SupplierFactory)\n\n\nclass ServiceFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Service\n\n title = factory.Faker('first_name')\n price = factory.LazyAttribute(lambda x: get_random_service_price())\n service_area = factory.SubFactory(ServiceAreaFactory)\n","sub_path":"supply/tests/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"418056763","text":"\"\"\"\n1437. Check If All 1's Are at Least Length K Places Away\nMedium\n\nGiven an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.\n\nExample 1:\n\nInput: nums = [1,0,0,0,1,0,0,1], k = 2\nOutput: true\nExplanation: Each of the 1s are at least 2 places away from each other.\n\nExample 2:\n\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: false\nExplanation: The second 1 and third 1 are only one apart from each other.\n\nExample 3:\n\nInput: nums = [1,1,1,1,1], k = 0\nOutput: true\n\nExample 4:\n\nInput: nums = [0,1,0,1], k = 1\nOutput: true\n\nConstraints:\n\n1 <= nums.length <= 10^5\n0 <= k <= nums.length\nnums[i] is 0 or 1\n\"\"\"\n\nfrom typing import List\n\n###############################################################################\n\"\"\"\nSolution: \n\nO(n) time\nO(1) extra space\n\"\"\"\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n if k == 0:\n return True\n\n n = len(nums)\n\n # If nums[0] is 1, then i - last = 0 - last = k if k = -last.\n # So we can initialize last to any number < -last.\n #last = float('-inf')\n last = -k - 1\n\n for i in range(n):\n if nums[i] == 1:\n if i - last <= k:\n return False\n \n last = i\n\n return True\n","sub_path":"array/1437_check_if_all_1s_are_at_least_length_k_places_away.py","file_name":"1437_check_if_all_1s_are_at_least_length_k_places_away.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441356687","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2020. Distributed under the terms of the MIT License.\nfrom math import ceil\nfrom pathlib import Path\nfrom typing import Tuple, List, Dict, Any\n\nfrom monty.serialization import loadfn\nfrom pymatgen import Composition, Element\nfrom pymatgen.io.vasp import Potcar\nfrom vise.defaults import defaults\n\nunoccupied_bands = loadfn(Path(__file__).parent / \"unoccupied_bands.yaml\")\n\n# This incar_flags should be OrderedDict, but from python 3.6, dict uses\n# order-preserving semantics. Besides, it does not affect vasp result.\nincar_categories: Dict[str, Any] = \\\n loadfn(Path(__file__).parent / \"incar_flags.yaml\")\nall_incar_flags: List[str] = sum(incar_categories.values(), [])\n\n\ndef has_f_elements(symbol_list: List[str]):\n return any([Element(el).Z > 56 for el in symbol_list])\n\n\nclass LDAU:\n def __init__(self,\n symbol_list: List[str]):\n\n self.symbol_list = symbol_list\n ldau_set = loadfn(Path(__file__).parent / \"u_parameter_set.yaml\")\n\n ldauu_set = ldau_set[\"LDAUU\"]\n ldauu_set.update(defaults.ldauu or {})\n self.ldauu = [ldauu_set.get(el, 0) for el in symbol_list]\n\n ldaul_set = ldau_set[\"LDAUL\"]\n ldaul_set.update(defaults.ldaul or {})\n self.ldaul = [ldaul_set.get(el, -1) for el in symbol_list]\n\n @property\n def lmaxmix(self):\n return 6 if has_f_elements(self.symbol_list) else 4\n\n @property\n def is_ldau_needed(self) -> bool:\n return set(self.ldauu) != {0}\n\n\ndef num_bands(composition: Composition, potcar: Potcar) -> int:\n \"\"\"Required for optical absorption, band structure, and DOS\"\"\"\n results = 0\n for element, potcar_single in zip(composition, potcar):\n num_atoms_per_element = composition[element]\n occupied_bands = potcar_single.nelectrons / 2\n num_bands_per_atom = occupied_bands + unoccupied_bands[str(element)]\n results += num_atoms_per_element * num_bands_per_atom\n\n return ceil(results)\n\n\ndef npar_kpar(num_kpoints: int, num_nodes: int) -> Tuple[int, int]:\n kpar_set = loadfn(Path(__file__).parent / \"kpar_set.yaml\")\n num_kpt_key = num_kpoints if num_kpoints in kpar_set else \"None\"\n if num_nodes == 2:\n kpar = kpar_set[num_kpt_key][1]\n elif num_nodes == 4:\n kpar = kpar_set[num_kpt_key][2]\n else:\n kpar = kpar_set[num_kpt_key][0]\n\n npar = 2 if kpar == 1 else 1\n\n return kpar, npar\n\n","sub_path":"vise/input_set/datasets/dataset_util.py","file_name":"dataset_util.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634340449","text":"#!/usr/bin/python # This is server.py file\n \nimport socket # Import socket module\n\nbuffsize =1024\nhost = '' # Get local machine name\nport = 10070 # Reserve a port for your service. \nbacklog = 5 \ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create a socket object\n \n\nprint ('Enter filename you would like to print to')\nfilename = input('Filename >> ')+'.txt'\nprint ('Server started!')\nprint ('Waiting for clients...')\n\ns.bind((host, port)) # Bind to the port\ns.listen(backlog) # Now wait for client connection.\n\nclient, address = s.accept()\nprint ('Got connection from', address)\n\nRunning = 1\nwhile Running:\n try:\n \n msg = client.recv(buffsize).decode('utf-8')\n print (address, ' >> ', msg)\n Client_msg = input('>>')\n client.send(bytes(Client_msg,'utf-8'))\n string = str(address) + ' >> ' + msg + '\\n'\n with open(filename, mode='a', encoding='utf-8') as file:\n file.write(string)\n file.close()\n if msg == '#':\n Running = 0\n s.close()\n client.send(bytes('Closing Connection','utf-8'))\n\n except KeyboardInterrupt:\n print('Closing Connection')\n s.close()\n Running = 0\n break\n \n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372311169","text":"#!/usr/local/cli/python3\n\"\"\"\nBuilds/trains the random forest classifier on a training set and then \nClassifies tracks in a test set\n\n\"\"\"\nfrom glob import glob\nimport csv\nimport json\nimport os\nimport sys\nimport pandas as pd\nimport shutil\nfrom sklearn.model_selection import StratifiedKFold\nfrom shutil import copyfile\nfrom helm.classifier.src import kernel_projection_experiment_fresh\nfrom helm.classifier.src import classify_tracks\nfrom helm.classifier.src import util\nfrom helm.classifier.src import convertTrackFilesForClassifier\n\ncwd = os.getcwd()\n\n\ndef main(argv):\n \"\"\"\n Main routine to build the classifier\n \"\"\"\n\n if not os.path.exists(argv.get('c')):\n print(\"Configuration File does not exist\")\n print(\"example usage: python classifier_train.py -c configs/config.yml -data_train /directory/to/tracks \")\n sys.exit(0)\n\n # 1. get run configuration\n config = util.obtain_configs(argv.get('c'))\n dir_cv_data = config['train_options']['dir_cv_data']\n dir_train_data = os.path.join(cwd,config['train_options']['dir_train_data'])\n dir_classifier = config['train_options']['dir_classifier']\n training_perf_chart_file = os.path.join(cwd,dir_classifier,config['train_options']['training_perf_chart_file'])\n classifier_performance_file = os.path.join(cwd,dir_classifier,config['train_options']['classifier_performance_file'])\n classifierfile = os.path.join(cwd,dir_classifier,config['train_options']['classifierfile'])\n train_track_convert_dir = os.path.join(cwd,dir_classifier,config['train_options']['train_track_convert_dir']) \n delete_temp_train_tracks = config['train_options']['delete_temp_tracks']\n sigma = config['train_options']['sigma']\n accelsigma = config['train_options']['accelsigma']\n samples = config['train_options']['samples']\n includedense = config['train_options']['includedense']\n\n if os.path.exists(os.path.join(cwd,dir_classifier)):\n shutil.rmtree(os.path.join(cwd,dir_classifier))\n\n dir_test_data = os.path.join(cwd,config['classify_options']['dir_test_data'])\n test_track_convert_dir = os.path.join(cwd,dir_classifier,config['classify_options']['test_track_convert_dir'])\n outputfile = os.path.join(cwd,dir_classifier,config['classify_options']['outputfile'])\n delete_temp_test_tracks = config['classify_options']['delete_temp_tracks']\n classification_threshold = config['classify_options']['gary_classifier_pmotility_threshold']\n dir_tracks_with_classification = os.path.join(cwd,dir_classifier,config['classify_options']['dir_tracks_with_classification'])\n if not os.path.exists(dir_tracks_with_classification):\n os.makedirs(dir_tracks_with_classification)\n print(\"example usage: python classifier_cv.py -c configs/config_cv.yml\")\n\n # 2. copy config file to output directory\n dir_classifier_path = os.path.join(cwd,config['train_options']['dir_classifier'])\n if not os.path.exists(dir_classifier_path):\n os.makedirs(dir_classifier_path)\n copyfile(argv.get('c'), os.path.join(dir_classifier_path, 'classifier_train_config.yml'))\n\n # 3.Create list (X) of all track paths to be used for cross validation and list (Y) of respective movement_types \n dir_cv_data = os.path.join(cwd,dir_cv_data)\n subfolders_byDate = [f.path for f in os.scandir(dir_cv_data) if f.is_dir() ]\n track_file_paths = []\n track_date_dirs = []\n track_movie_dirs = []\n track_name = []\n true_labels = []\n for subfolder in subfolders_byDate:\n subfolderName = os.path.basename(os.path.normpath(subfolder))\n movie_dirs = [f.path for f in os.scandir(subfolder) if f.is_dir() ]\n for movie_dir in movie_dirs:\n movie_dir_name = os.path.basename(os.path.normpath(movie_dir))\n track_files = sorted(glob(movie_dir + '/*.track'))\n for track in track_files:\n track_file_paths.append(track)\n track_date_dirs.append(subfolderName)\n track_movie_dirs.append(movie_dir_name)\n track_name.append(os.path.basename(track))\n with open(track, 'r') as f:\n data = json.load(f)\n true_labels.append(data[\"Movement_Type\"])\n df_allTracks = pd.DataFrame({\"track_file_path\":track_file_paths,\"track_date_dir\":track_date_dirs,\"track_movie_dir\":track_movie_dirs,\"track_name\": track_name, \"true_label\": true_labels})\n fileName = os.path.join(cwd,dir_classifier,\"allTracks.csv\")\n df_allTracks.to_csv(fileName)\n\n # Separating out the features\n X = track_file_paths\n # Separating out the target\n Y = true_labels\n\n\n # 4. Define inner/outer cross-validation methods\n nFolds = 2 # K = nFolds for estimating generalization error \n # Define type of K-folds (stratified results in preserved percentage of 1/0 in each fold)\n skf = StratifiedKFold(n_splits=nFolds,shuffle = True)\n\n\n # 5.0. Perform outer fold iteration\n trackPmotileAllFolds = []\n testSetIndices = []\n outerFoldNum = 0;\n for train_index, test_index in skf.split(X, Y):\n print(\"===== FOLD \",outerFoldNum)\n # Store test set indices to resort/output feature dataframe\n tracks2train = df_allTracks.iloc[train_index]\n tracks2test = df_allTracks.iloc[test_index]\n testSetIndices.extend(test_index.tolist())\n print(\"Train indices: \", train_index)\n print(\"Test indices: \", test_index)\n\n # 5.1. Copy training set tracks into train subdirectory\n for t in train_index:\n trackPath = df_allTracks[\"track_file_path\"].iloc[t]\n dateDir = df_allTracks[\"track_date_dir\"].iloc[t]\n movieDir = df_allTracks[\"track_movie_dir\"].iloc[t]\n trackDirNew = os.path.join(dir_train_data,dateDir,movieDir)\n if not os.path.exists(trackDirNew):\n os.makedirs(trackDirNew)\n shutil.copy(trackPath, trackDirNew)\n\n # 5.2. Copy test set tracks in to test subdirectory\n for t in test_index:\n trackPath = df_allTracks[\"track_file_path\"].iloc[t]\n dateDir = df_allTracks[\"track_date_dir\"].iloc[t]\n movieDir = df_allTracks[\"track_movie_dir\"].iloc[t]\n trackDirNew = os.path.join(dir_test_data,dateDir,movieDir)\n if not os.path.exists(trackDirNew):\n os.makedirs(trackDirNew)\n shutil.copy(trackPath, trackDirNew)\n\n # 5.3. Convert training set tracks to format ingested by Gary's classifier\n if not os.path.exists(train_track_convert_dir):\n os.makedirs(train_track_convert_dir)\n subfolders = [f.path for f in os.scandir(dir_train_data) if f.is_dir() ]\n newFileNames = []\n oldFileNames = []\n for subfolder in subfolders:\n oldNames, newNames = convertTrackFilesForClassifier.convertTracks(subfolder, train_track_convert_dir)\n oldFileNames.extend(oldNames)\n newFileNames.extend(newNames)\n # 5.4. Sub-routine to create labels.csv file in each movie directory\n subfolders = [f.path for f in os.scandir(train_track_convert_dir) if f.is_dir()]\n for subfolder in subfolders:\n subfolderName = os.path.basename(os.path.normpath(subfolder))\n movie_dirs = [f.path for f in os.scandir(subfolder) if f.is_dir() ]\n if len(movie_dirs) > 0:\n for movie_dir in movie_dirs:\n movie_dir_name = os.path.basename(os.path.normpath(movie_dir))\n trackIDs = []\n trackLabels = []\n check = movie_dir + '/*.track'\n track_files = sorted(glob(check))\n if len(track_files)>0:\n for track in track_files:\n with open(track, 'r') as f:\n data = json.load(f)\n trackLabels.append(data[\"Movement_Type\"])\n trackIDs.append(data[\"track_id\"])\n\n movieTrackLabelList = {}\n for i in range(len(trackIDs)):\n if trackLabels[i] == \"motile\" or trackLabels[i] == \"Motile\":\n movieTrackLabelList.update({ str(trackIDs[i]) : 'Motile'})\n else:\n movieTrackLabelList.update({ str(trackIDs[i]) : 'Other'})\n subfolderName = os.path.basename(os.path.normpath(subfolder))\n fileName = os.path.join(movie_dir,os.pardir,'labels.csv')\n with open(fileName, 'w') as myfile:\n wr = csv.writer(myfile)\n for row in movieTrackLabelList.items():\n wr.writerow(row)\n\n # 5.5. train classifier\n kernel_projection_experiment_fresh.main(train_track_convert_dir, training_perf_chart_file, sigma, accelsigma, samples, includedense, classifier_performance_file, classifierfile)\n\n # 5.6. Delete converted training tracks in train_track_convert_dir\n if delete_temp_train_tracks is True:\n print(\"Deleting converted training set tracks\")\n for tempTrackFile in newFileNames:\n os.remove(tempTrackFile)\n\n # 5.7. Convert test set tracks to format ingested by Gary's classifier\n if not os.path.exists(test_track_convert_dir):\n os.makedirs(test_track_convert_dir)\n dir_test_data = os.path.join(cwd,dir_test_data)\n subfolders = [f.path for f in os.scandir(dir_test_data) if f.is_dir() ]\n newFileNames = []\n oldFileNames = []\n for subfolder in subfolders:\n oldNames, newNames = convertTrackFilesForClassifier.convertTracks(subfolder, test_track_convert_dir)\n oldFileNames.extend(oldNames)\n newFileNames.extend(newNames)\n\n # 5.8. call classifier\n trackPmotile = classify_tracks.main(test_track_convert_dir, classifierfile, outputfile)\n\n # 5.9. Post-process/store/print classifications\n if not trackPmotile.empty:\n # Add classification to classification dataframe and save\n nTracksClassified = trackPmotile.shape[0]\n classifications = [\"other\"]*nTracksClassified\n trackPmotile['classification'] = classifications\n trackPmotile['classification'][trackPmotile['p_motile']>classification_threshold] = 'motile'\n print(\"track motility: \")\n print(trackPmotile)\n trackPmotile.to_csv(outputfile + \"fold_\" + str(outerFoldNum) + \".csv\", index=False)\n trackPmotileAllFolds.append(trackPmotile)\n\n # Insert track classificaiton in track files\n for i in range(nTracksClassified):\n track = oldFileNames[i]\n subfolderName = trackPmotile['track_subdirectory'].iloc[i]\n a_dict = {'classification': trackPmotile['classification'].iloc[i],'probability_motility': trackPmotile['p_motile'].iloc[i]}\n with open(track, 'r') as f:\n data = json.load(f)\n data.update(a_dict)\n # Export new track JSON file\n trackDirectory = os.path.join(cwd,dir_tracks_with_classification,subfolderName)\n if not os.path.exists(trackDirectory):\n os.makedirs(trackDirectory)\n\n modifiedTrackName = os.path.basename(track)\n newFileName = os.path.join(cwd,dir_tracks_with_classification,subfolderName,modifiedTrackName)\n with open(newFileName,'w') as json_file:\n json.dump(data, json_file, indent=4)\n\n else:\n print(\"No tracks classified\")\n\n # 5.10. Delete converted tracks in test_track_convert_dir\n if delete_temp_test_tracks is True:\n print(\"Deleting converted test set tracks\")\n for tempTrackFile in newFileNames:\n os.remove(tempTrackFile)\n\n outerFoldNum += 1\n\n # 5.11 Delete train and test subdirectories\n shutil.rmtree(dir_train_data)\n shutil.rmtree(dir_test_data)\n\n # 6. Combine all track classification dataframes from each fold\n df = trackPmotileAllFolds[0]\n for i in range(1,len(trackPmotileAllFolds)):\n df = df.append(trackPmotileAllFolds[i])\n\n df.to_csv(outputfile + \"_allfolds.csv\", index=False)\n\n shutil.rmtree(train_track_convert_dir)\n shutil.rmtree(test_track_convert_dir)\n\nif __name__ == \"__main__\":\n # Example call: \n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", default='', help='/path/to/config.yml')\n\n args = parser.parse_args()\n\n main(vars(args))\n","sub_path":"helm/classifier/classifier_cv.py","file_name":"classifier_cv.py","file_ext":"py","file_size_in_byte":12808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"247227125","text":"import glob\nimport os\nimport argparse\nimport shutil\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-a', '--annotation_dir', help=\"Annotation directory. For the bbox-label tool it is the Label directory.\", type=str, required=True)\nparser.add_argument('-d', '--destination_dir', help=\"Destination directory for the extracted annotations\", type=str, required=True)\nparser.add_argument('-f', '--first_position', help=\"First image position. Starts in 1. \", type=int, required=True)\nparser.add_argument('-l', '--last_position', help=\"Last image position. The last image is included.\", type=int, required=True)\nargs = parser.parse_args()\n\nannotation_list = glob.glob(os.path.join(args.annotation_dir, '**/*.txt'), recursive=True)\nannotation_list_size = len(annotation_list)\n\nif args.first_position <= 0 or args.last_position <= 0:\n raise Exception('The positions cannot be less than zero.')\n\nif args.last_position > annotation_list_size or args.first_position > annotation_list_size:\n raise Exception('The last position cannot be greater than the total number of annotation which is: ',annotation_list_size)\n\nif args.last_position < args.first_position:\n raise Exception('The last position cannot be less than the first position.')\n\nprint('##################################################################')\nprint('Be aware: the positions are for the ordered list of annotations.')\nprint('##################################################################')\n\nabs_destination_dir = os.path.abspath(args.destination_dir)\nprint('\\nExtracting...')\nannotation_list.sort()\nfor annot in annotation_list[args.first_position-1 : args.last_position]:\n annot = os.path.abspath(annot)\n dest_annot = os.path.join(abs_destination_dir, annot.replace('/','',1))\n os.makedirs(os.path.dirname(dest_annot), exist_ok=True)\n shutil.copy(annot, dest_annot)\n\nprint('Done.')\n","sub_path":"extract_labels_by_order.py","file_name":"extract_labels_by_order.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"530720999","text":"import glob\nimport os\n\nimport cv2\nimport numpy as np\nfrom keras.utils.np_utils import to_categorical\n\nfrom preprocessing import preprocess_image_batch\n\nCLASS_NAME_MAPPING = {}\nPER_CLASS_MAX_IMAGES = 24\n\n\ndef load_data(path):\n data_set_input_images_files, data_set_input_images_true_label = get_class_wise_images_and_true_label(path)\n processed_input_images = [preprocess_image_batch([image])\n for image in data_set_input_images_files]\n\n global CLASS_NAME_MAPPING\n nb_classes = len(CLASS_NAME_MAPPING.keys())\n X_train = np.concatenate(processed_input_images)\n\n y_out = np.concatenate(data_set_input_images_true_label)\n y_out = to_categorical(y_out, nb_classes=nb_classes) # to get sofmax shape of (None, nb_classes)\n Y_train = y_out\n\n from sklearn.utils import shuffle\n X_train, Y_train = shuffle(X_train, Y_train)\n\n return X_train, Y_train, nb_classes\n\n\ndef get_class_wise_images_and_true_label(path):\n print('path', path + \"/*\")\n directory = glob.glob(path + '/*')\n data_set_input_images = []\n data_set_input_images_true_label = []\n global CLASS_NAME_MAPPING\n index = 0\n for sub_directory in directory:\n if os.path.isdir(sub_directory):\n class_dir_name = sub_directory.split('/')[-1]\n CLASS_NAME_MAPPING[index] = class_dir_name\n image_class_files = glob.glob(sub_directory + '/*.jpeg')[:PER_CLASS_MAX_IMAGES]\n data_set_input_images.extend(image_class_files)\n data_set_input_images_true_label.extend([[index]] * len(image_class_files))\n index += 1\n return data_set_input_images, data_set_input_images_true_label\n\n\ndef load_inria_person(path):\n pos_path = os.path.join(path, \"pos\")\n neg_path = os.path.join(path, \"neg\")\n pos_images = [cv2.resize(cv2.imread(x), (64, 128)) for x in glob.glob(pos_path + \"/*.jpeg\")]\n pos_images = [np.transpose(img, (2, 0, 1)) for img in pos_images]\n neg_images = [cv2.resize(cv2.imread(x), (64, 128)) for x in glob.glob(neg_path + \"/*.jpeg\")]\n neg_images = [np.transpose(img, (2, 0, 1)) for img in neg_images]\n y = [1] * len(pos_images) + [0] * len(neg_images)\n y = to_categorical(y, 2)\n X = np.float32(pos_images + neg_images)\n\n return X, y\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629617960","text":"'''\nCopyright 2018 VMware, Inc.\nSPDX-License-Identifier: BSD-2-Clause\n'''\n\nimport argparse\nimport os\nimport sys\nimport tarfile\nfrom elftools.elf.elffile import ELFFile\nfrom elftools.elf.segments import InterpSegment\ntry:\n import rpm\nexcept ImportError:\n print(\"WARNING! rpm module not loaded.\", file=sys.stderr)\ntry:\n import apt\nexcept ImportError:\n print(\"WARNING! apt module not loaded.\", file=sys.stderr)\n\n\n# this is stuff that will never be part of a running container\n# /var/lib/docker/ is just in case we are in DIND or there is noise from microdump.lua\nIGNORE_SET_FILES = frozenset([\"/dev/\", \"/proc/\", \"/sys/\", \"/tmp/\", \"/var/lib/docker/\"])\nIGNORE_SET_FOLDERS = frozenset(map(lambda x: x.rstrip(\"/\"), IGNORE_SET_FILES))\n\n\nclass BaseContainer:\n \"\"\" This is the base class.\n This class contains all the information we need from the container.\n \"\"\"\n\n\n def __init__(self):\n\n # a set for all files we need to pack\n self.all_files = set()\n\n # a set for all folders we need to pack\n self.all_folders = set()\n\n # a dict for package information, used only by inherited classes\n self.package_info = {}\n\n\n def is_folder_needed(self, folder):\n \"\"\" Returns if the folder is implicitly contained in others\n Explanation:\n we may have a reference to a folder like /foo in our set,\n if we have later in the set a reference to a file like /foo/bar,\n then the folder /foo is implicit.\n \"\"\"\n\n # do we have an implicit folder in the file list?\n for entry in self.all_files:\n if entry.startswith(folder):\n return False\n\n # do we have an implicit folder in the folder list?\n for entry in self.all_folders:\n if entry.startswith(folder) and entry != folder:\n return False\n\n # if we couldn't find it...\n return True\n\n\n def generate_package_info(self, filename):\n \"\"\" Empty function for this base class. \"\"\"\n pass\n\n\nclass DEBContainer(BaseContainer):\n \"\"\" Class for containers that are DEB based. \"\"\"\n\n def __init__(self):\n\n BaseContainer.__init__(self)\n\n # open a reference to the deb cache\n self.deb_cache = apt.Cache()\n print(\"WARNING! Licence retrieval is not implemented for DEB containers.\", file=sys.stderr)\n\n\n def generate_package_info(self, filename):\n \"\"\" DEB specific package info generator \"\"\"\n\n # skip it for folder\n if os.path.isdir(filename):\n return\n\n # quite ugly, but it looks we need to traverse the cache\n for deb_cache_entry in self.deb_cache:\n\n if deb_cache_entry.is_installed and filename in deb_cache_entry.installed_files:\n\n package = deb_cache_entry.shortname + \"-\" + deb_cache_entry.versions[0].version + \\\n \"-\" + deb_cache_entry.architecture() + \" (?)\"\n\n # check if package list exists\n if self.package_info.get(package) is None:\n self.package_info[package] = []\n\n self.package_info[package].append(filename)\n return\n\n # we couldn't find anything\n if self.package_info.get(\"unknown DEB package\") is None:\n self.package_info[\"unknown DEB package\"] = []\n\n self.package_info[\"unknown DEB package\"].append(filename)\n return\n\n\nclass RPMContainer(BaseContainer):\n \"\"\" Class for containers that are RPM based. \"\"\"\n\n def __init__(self):\n\n BaseContainer.__init__(self)\n\n # open a transaction set to the RPM DB\n self.transaction_set = rpm.TransactionSet()\n\n\n def generate_package_info(self, filename):\n \"\"\" RPM specific package info generator. \"\"\"\n\n # skip it for folders\n if os.path.isdir(filename):\n return\n\n # query the RPM DB for the package this file is coming from\n match_iterator = self.transaction_set.dbMatch(\"basenames\", filename)\n\n # if you get zero or more than one result, put the file in the \"unknown RPM package\" list\n if len(match_iterator) != 1:\n\n # check if the \"unknown package\" list exists\n if self.package_info.get(\"unknown RPM package\") is None:\n self.package_info[\"unknown RPM package\"] = []\n\n self.package_info[\"unknown RPM package\"].append(filename)\n return\n\n # if we have (correctly) only one result\n for header in match_iterator:\n\n package = header[rpm.RPMTAG_NAME].decode(\"utf-8\") + \"-\" + \\\n header[rpm.RPMTAG_VERSION].decode(\"utf-8\") + \"-\" + \\\n header[rpm.RPMTAG_RELEASE].decode(\"utf-8\") + \" (\" + \\\n header[rpm.RPMTAG_LICENSE].decode(\"utf-8\") + \")\"\n\n\t# check if the \"package\" list exists\n if self.package_info.get(package) is None:\n self.package_info[package] = []\n\n self.package_info[package].append(filename)\n return\n\n\ndef filepaths_from_file(filename):\n \"\"\" Return a set of files, following symlinks.\"\"\"\n\n file_entries = set()\n\n if not os.path.islink(filename):\n\n\t# just add the file to the set and return\n # don't forget normpath to call to avoid \"A/./B\" strings\n normalized_filename = os.path.normpath(filename)\n\n # ignore a normalized_filename that is not supposed to be in a container image\n # don't forget that we might end here after following a symlink\n if any(map(normalized_filename.startswith, IGNORE_SET_FILES)):\n return frozenset()\n\n # return the single entry as a frozenset\n file_entries.add(normalized_filename)\n return frozenset(file_entries)\n\n else:\n\n # as above\n normalized_filename = os.path.normpath(filename)\n if any(map(normalized_filename.startswith, IGNORE_SET_FILES)):\n return frozenset()\n\n # now add the filename to the set\n file_entries.add(normalized_filename)\n # read the link\n link = os.readlink(normalized_filename)\n\n # if it is not absolute, create an abs path\n if not os.path.isabs(link):\n link = os.path.normpath(os.path.join(os.path.dirname(normalized_filename), link))\n\n # we can have a symlink pointing to another symlink\n # /usr/bin/java -> /etc/alternatives/java\n # /etc/alternatives/java -> /usr/lib/jvm/OpenJDK-1.8.0.151/jre/bin/java\n file_entries.update(filepaths_from_file(link))\n return frozenset(file_entries)\n\n\ndef retrieve_loader_from_interp(interp_filename):\n \"\"\" Returns the Linux dynamic loader programmatically. \"\"\"\n\n with open(interp_filename, \"rb\") as file:\n for elf_segment in ELFFile(file).iter_segments():\n if isinstance(elf_segment, InterpSegment):\n return elf_segment.get_interp_name()\n\n # this shouldn't ever fail\n raise SystemExit(\"ERROR! couldn't find the Linux Loader in file: \" + interp_filename)\n\n\ndef main():\n \"\"\" Main function of the script. \"\"\"\n\n # set up the args parser\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", metavar=\"input_list\", help=\"list from file\", required=True)\n parser.add_argument(\"-t\", metavar=\"tar_filename\", help=\"tar filename\", required=True)\n parser.add_argument(\"--excl-files\", metavar=\"excluded_file\", \\\n help=\"file exclusion list\", nargs=\"+\")\n parser.add_argument(\"--excl-folders\", metavar=\"excluded_folder\", \\\n help=\"folder exclusion list\", nargs=\"+\")\n parser.add_argument(\"--interp\", metavar=\"inter_filename\", \\\n help=\"retrieve ld-linux.so from ELF\", default=\"/bin/sh\", required=False, nargs=\"?\")\n type_group = parser.add_mutually_exclusive_group()\n type_group.add_argument(\"--rpm\", help=\"rpm based container\", action=\"store_true\")\n type_group.add_argument(\"--deb\", help=\"deb based container\", action=\"store_true\")\n\n args = parser.parse_args()\n namespace = vars(args)\n\n # add file and folder exclusion lists (reassign the globals)\n if namespace[\"excl_files\"]:\n global IGNORE_SET_FILES\n IGNORE_SET_FILES = frozenset(set(IGNORE_SET_FILES) | set(namespace[\"excl_files\"]))\n\n if namespace[\"excl_folders\"]:\n global IGNORE_SET_FOLDERS\n IGNORE_SET_FOLDERS = frozenset(set(IGNORE_SET_FOLDERS) | set(namespace[\"excl_folders\"]))\n\n # create our container instance depending on the specified type\n if namespace[\"rpm\"]:\n container = RPMContainer()\n elif namespace[\"deb\"]:\n container = DEBContainer()\n else:\n container = BaseContainer()\n\n # read the input file\n with open(namespace[\"i\"], \"r\") as import_list_file:\n\n for line in import_list_file.readlines():\n\n file_string = line.strip(\"\\n\")\n\n # with \"isfile\" or \"isdir\" methods, \"exists\" is implicit\n # also, any \"strange\" char will get ignored here like \"/folder/*\"\n if os.path.isfile(file_string):\n\n # ignore a file that is not supposed to be in a container image\n if any(map(file_string.startswith, IGNORE_SET_FILES)):\n continue\n\n # add the file to the set\n container.all_files.update(filepaths_from_file(file_string))\n\n elif os.path.isdir(file_string):\n\n # ignore a folder that is not supposed to be in a container image\n if any(map(file_string.startswith, IGNORE_SET_FOLDERS)):\n continue\n\n # add the folder to the set\n container.all_folders.add(os.path.normpath(file_string))\n\n # we may be in the corner case we have a relative string that was in PATH\n elif \"/\" not in file_string:\n\n # get PATH env variable\n if \"PATH\" in os.environ:\n\n paths_list = os.environ[\"PATH\"].split(\":\")\n for path in paths_list:\n\n new_file_string = path + \"/\" + file_string\n\n # check if you found the binary\n if os.path.isfile(new_file_string):\n\n # safety check, you shouldn't land here\n if any(map(new_file_string.startswith, IGNORE_SET_FILES)):\n continue\n\n # add the file to the set\n container.all_files.update(filepaths_from_file(new_file_string))\n break\n\n # some garbage in file_string?\n else:\n pass\n\n # end of with-open\n # we have parsed the input file and the container instance has its sets populated\n # we need to add the Linux loader\n interp_filename = namespace[\"interp\"]\n container.all_files.update(filepaths_from_file(retrieve_loader_from_interp(interp_filename)))\n\n # we want to prune the list of folders we have collected\n needed_folders = frozenset(filter(container.is_folder_needed, container.all_folders))\n\n # union the two sets\n fs_entries = needed_folders | container.all_files\n\n # create the tarfile, if a entry is a folder, import recursively\n tar = tarfile.open(namespace[\"t\"], \"w\")\n for entry in fs_entries:\n container.generate_package_info(entry)\n tar.add(entry)\n tar.close()\n\n # print the package_info to stdout\n if namespace[\"rpm\"] or namespace[\"deb\"]:\n for key in container.package_info:\n print(key + \":\")\n for value in container.package_info[key]:\n print(value)\n print()\n\n\n# this is a script, not a module\nif __name__ == '__main__':\n main()\n","sub_path":"legacy/micropacker.py","file_name":"micropacker.py","file_ext":"py","file_size_in_byte":11623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163346106","text":"str1 = \"1.不管未来有多遥远,成长的路上有你有我;不管相逢在什么时候,我们是永远的朋友。2.不管未来有多久,请珍惜相聚的每一刻;不管过了多少个春秋,我们是永远的朋友。\\\r\n3.与你同行,回想起我们曾拥有过的共同理想;与你分手,憧憬着我们重逢时的狂欢。\\\r\n4.同学啊,让往日夕暮中那些甜蜜的低语,都埋在心底,化作美丽的记忆吧!\\\r\n5.光阴似箭,一转眼,6年的同窗生涯已成为过去。但教室里,还回响着我们朗朗的读书声;操场上,还留着我们奔跑矫健的身影。这里的草坪、小溪、竹亭,是我们永远依恋的百草园。\"\r\nlist1 = []\r\n\r\nfor each in str1:\r\n if each =='\\n':\r\n print('\\\\n',str1.count(each))\r\n else:\r\n print(each,str1.count(each))\r\n list1.append(each)\r\n \r\n","sub_path":"20/def_201.py","file_name":"def_201.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"627883646","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\nfrom django.contrib import messages\nfrom django.views.generic import ListView, DetailView\nfrom django.http import HttpRequest\n\nfrom .models import Item, OrderItem, Order\n\n\ndef item_list(request: HttpRequest):\n context = {\"items\": Item.objects.all()}\n return render(request, \"home.html\", context)\n\n\ndef products(request: HttpRequest):\n return render(request, \"product.html\")\n\n\ndef checkout(request: HttpRequest):\n return render(request, \"checkout.html\")\n\n\nclass HomeView(ListView):\n model = Item\n template_name = \"home.html\"\n\n\nclass ItemDetailView(DetailView):\n model = Item\n template_name = \"product.html\"\n\n\ndef add_to_cart(request: HttpRequest, slug):\n item = get_object_or_404(Item, slug=slug)\n order_item, created = OrderItem.objects.get_or_create(\n item=item, user=request.user, ordered=False\n )\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n\n if order_qs.exists():\n order = order_qs[0]\n # check if order item is in order\n if order.items.filter(item__slug=item.slug).exists():\n order_item.quantity += 1\n order_item.save()\n messages.info(request, \"This item quantity was updated\")\n return redirect(\"core:product\", slug=slug)\n else:\n messages.info(request, \"This item was added to cart\")\n order.items.add(order_item)\n return redirect(\"core:product\", slug=slug)\n else:\n order = Order.objects.create(user=request.user, ordered_date=timezone.now())\n order.items.add(order_item)\n messages.info(request, \"This item was added to cart\")\n return redirect(\"core:product\", slug=slug)\n\n\ndef remove_from_cart(request: HttpRequest, slug):\n item = get_object_or_404(Item, slug=slug)\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n\n if order_qs.exists():\n order = order_qs[0]\n # check if the order item is in the order\n if order.items.filter(item__slug=item.slug).exists():\n order_item = OrderItem.objects.filter(\n item=item, user=request.user, ordered=False\n )[0]\n order.items.remove(order_item)\n order_item.delete()\n messages.info(request, \"This item is removed from your cart\")\n else:\n messages.error(\n request, \"This item is not in your cart\", extra_tags=\"danger\"\n )\n return redirect(\"core:product\", slug=slug)\n else:\n messages.info(request, \"You do not have an active order\")\n return redirect(\"core:product\", slug=slug)\n","sub_path":"src/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"50079781","text":"# -*- coding: UTF-8 -*-\nimport time\nimport types\nimport inspect\nimport config\n\n\ndef wait_until(condition: types.LambdaType, cycles=None, timeout=None) -> None:\n \"\"\"\n Wait's until the condition returns True\n :param condition: Lambda expression that sets a condition\n :param cycles: Number of repetitions of evaluating the condition\n :param timeout: Timeout that's put between cycles\n \"\"\"\n if cycles is None:\n cycles = config.default_explicit_wait_cycle_number\n\n if timeout is None:\n timeout = config.default_explicit_wait_cycle_timeout\n\n for _ in range(cycles):\n time.sleep(timeout)\n if condition():\n return\n raise WaitException(f'Lambda expression [{inspect.getsource(condition).strip()}] '\n f'did not work after the set timeout!')\n\n\nclass WaitException(Exception):\n \"\"\" Custom exception that signals that condition hasn't been met \"\"\"\n def __init__(self, message):\n self.message = message\n","sub_path":"Python/src/core/waiters/until.py","file_name":"until.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"435260324","text":"import httplib2\nimport os\nfrom apiclient import discovery\nfrom google.oauth2 import service_account\n\ntry:\n scope = ['https://googleapis.com/auth/drive','https://googleapis.com/auth/drive.file','https://googleapis/auth/spreadsheets']\n\n secret_file = os.path.join(os.getcwd(), \"client_secret.json\")\n credentials = service_account.Credentials.from_service_account_file(secret_file)\n service = discovery.build('sheets', 'v4', credentials=credentials)\n\n spreadsheet_id = SPREADSHEET_ID\n spreadsheet_range = SPREADSHEET_RANGE\n\n request = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=spreadsheet_range, valueRenderOption='UNFORMATTED_VALUE', dateTimeRenderOption = 'FORMATTED_STRING')\n response = request.execute()\n\n for responses in ['values']:\n raw = response[responses]\n print(raw)\n\n for text in raw:\n seperator = '\\n'\n print(seperator.join(map(str,text)) + seperator)\n\n\nexcept OSError as e:\n print(e)\n","sub_path":"subtitle.py","file_name":"subtitle.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"78633860","text":"# class Daemon(object):\n# def __init__(self):\n# self.name = None\n# self.id = None\n# self.handler = Pool_Handler()\n#\n# def __setattr__(self, key, value):\n# self.handler[key] = value\nfrom dict import Dict, Dict as dict\nfrom sarah.acp_bson import Client\nfrom katherine import citlali_maria_config, pymysql\nfrom decimal import Decimal as D\n\n\nagent_backend = Client('', 'portia/backend')\n\n\ndef handle_action_portia_print_document(msg):\n citlali_maria = pymysql.connect(**citlali_maria_config)\n citla_cursor = citlali_maria.cursor()\n document = msg.document\n _msg = Dict({'type_message': 'action', 'action': 'portia/print_document'})\n if 'params' not in msg:\n params = Dict()\n _msg.params = params\n else:\n params = msg.params\n _msg.params = params\n if 'printer' not in params:\n r = citla_cursor.execute('select printer from portia.document_type_printer where document_type = %s limit 1;',\n (document.type,))\n if r == 1:\n params.printer, = citla_cursor.fetchone()\n\n if document.type == 'serena/ticket':\n for item in document['items']:\n if 'price' in item:\n price = item.price\n if not isinstance(price, (D, int, float)) and isinstance(price, dict) and 'value' in price:\n item.price = price.value\n if 'amount' not in item and 'quanty' in item and 'price' in item:\n item.amount = item.quanty * item.price\n if 'client' in document:\n client = document.client\n if isinstance(client, dict) and 'name' in client:\n document.client = client.name\n\n _msg.document = document\n if 'copy' not in params:\n params.copy = False\n\n if 'document' in _msg:\n agent_backend(_msg)\n\n citla_cursor.close()\n citlali_maria.close()\n\n\ndef handle_action_portia_print_prices(msg):\n items = msg['items']\n\n\n\nif __name__ == '__main__':\n from sarah.handler import Pool_Handler\n from sarah.acp_bson import Recipient\n h = Pool_Handler()\n h['type_message=action.action=portia/print_document'] = handle_action_portia_print_document\n h['type_message=action.action=portia/print_prices'] = handle_action_portia_print_prices\n recipient = Recipient()\n recipient.prepare('portia', h)\n recipient.begin_receive_forever()\n","sub_path":"portiad/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"2874002","text":"import time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.wait import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nimport os\r\nfrom support.log import AutoTestLog\r\n\r\n'''\r\n注册-登录-查询-添加购物车-下单\r\n'''\r\nlog = AutoTestLog()\r\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\n\r\nclass BasePage(object):\r\n login_url = 'http://49.234.189.120'\r\n url = '/'\r\n\r\n def __init__(self, selenium_driver, base_url=login_url):\r\n self.base_url = base_url\r\n self.driver = selenium_driver\r\n self.open()\r\n self.timeout = 30\r\n\r\n def on_page(self):\r\n return self.driver.current_url == (self.base_url + self.url)\r\n\r\n def _open(self, url):\r\n url = self.base_url + url\r\n # print(self.driver.current_url)\r\n #查看页面是否和当前page类相同,如果不相同,切换到page类的url上\r\n all_handles = self.driver.window_handles\r\n for handle in all_handles:\r\n if url in self.driver.current_url:\r\n break\r\n else:\r\n self.driver.switch_to.window(handle)\r\n # if url not in self.driver.current_url:\r\n # self.driver.get(url)\r\n if self.driver.current_url == 'data:,':\r\n self.driver.get(url)\r\n\r\n def open(self):\r\n self._open(self.url)\r\n\r\n def find_element(self, *loc):\r\n return self.driver.find_element(*loc)\r\n\r\n def find_elements(self, *loc):\r\n return self.driver.find_elements(*loc)\r\n\r\n def type_value(self, key, loc):\r\n element = self.find_element(*loc)\r\n element.clear()\r\n element.send_keys(key)\r\n\r\n def screen_shot(self,name):\r\n if not name:\r\n now = time.strftime(\"%Y-%m-%d %H-%M-%S\")\r\n screen_name = BASE_DIR + '/output/screenshot/' + now + '.png'\r\n else:\r\n screen_name = BASE_DIR + '/output/screenshot/' + name + '.png'\r\n log.get_log().debug('截图到' + screen_name)\r\n return self.driver.get_screenshot_as_file(screen_name)\r\n\r\n def quit(self):\r\n self.driver.quit()\r\n\r\n\r\nclass TestChromeDriver(object):\r\n def __init__(self):\r\n self.driver = webdriver.Chrome()\r\n self.driver.maximize_window()\r\n self.driver.implicitly_wait(15)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n driver = TestChromeDriver().driver\r\n obj = BasePage(driver)\r\n obj.screen_shot()\r\n time.sleep(10)\r\n obj.quit()\r\n pass","sub_path":"selenium_test/Pages/basepage.py","file_name":"basepage.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"72592224","text":"# -*- coding: utf8 -*-\n__author__ = 'Jagerzhang'\n \nimport hmac\nimport hashlib\nimport base64\nimport requests\nimport json\nimport time\n \nclass KongHmac():\n \"\"\"生成Kong的Hmac鉴权头部\n 仅适配了hmac-sha256加密方式\n \"\"\"\n def sha256_digest_base64(self,content):\n \"\"\" sha256计算内容摘要\n \"\"\"\n content_bytes = bytes(content).decode(\"utf-8\")\n content_sha256_digest = hashlib.sha256(content_bytes).digest()\n content_sha256_digest_base64_decode = base64.b64encode(content_sha256_digest).decode()\n content_digest = 'SHA-256={}'.format(content_sha256_digest_base64_decode)\n return content_digest\n \n def hmac_sha256_base64(self, secret, str_to_sign):\n \"\"\" 生成sha256加密串\n \"\"\"\n signature = hmac.new(bytes(secret), bytes(str_to_sign),\n digestmod=hashlib.sha256).digest()\n str_base64 = base64.b64encode(signature).decode()\n return str_base64\n \n def get_auth_header(self, username, secret, body):\n # 生成body的sha256加密串\n body_digest = self.sha256_digest_base64(body)\n \n # 生成当前GMT时间,注意格式不能改变,必须形如:Wed, 14 Aug 2019 09:09:28 GMT\n gm_time = time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", time.gmtime())\n \n # 拼装待签名的数据\n str_to_sign = \"date: {}\\ndigest: {}\".format(gm_time, body_digest)\n \n # 生成签名\n signature = self.hmac_sha256_base64(secret, str_to_sign)\n \n # 拼装headers\n headers = {\n 'Authorization': 'hmac username=\\\"{}\\\", algorithm=\\\"hmac-sha256\\\", headers=\\\"date digest\\\", '\n 'signature=\\\"{}\\\"'.format(username, signature),\n 'Digest': body_digest,\n 'Date': gm_time}\n return headers\n","sub_path":"python/kong_hmac_py2.py","file_name":"kong_hmac_py2.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269982462","text":"import random\nfrom copy import deepcopy\nimport numpy as np\n\n\ndef insert_mutation(chromosome, gifts):\n assignment, trip_load, trip_seq, fitnesses, total_fitnesses = deepcopy(chromosome)\n\n gift_chosen = random.randrange(len(assignment))\n old_trip = assignment[gift_chosen]\n new_trip = random.randrange(max(assignment) + 1)\n\n while trip_load[new_trip] + gifts[gift_chosen, -1] > 1000:\n new_trip = random.randrange(max(assignment) + 1)\n\n # Update the old trip sequence.\n trip_load[old_trip] -= gifts[gift_chosen, -1]\n fitnesses[old_trip] = np.zeros(len(total_fitnesses))\n index = trip_seq[old_trip].index(gift_chosen) # Raises ValueError if GIFT_CHOSEN does not exist.\n del trip_seq[old_trip][index]\n\n # Update the new trip sequence\n assignment[gift_chosen] = new_trip\n trip_load[new_trip] += gifts[gift_chosen, -1]\n fitnesses[new_trip] = np.zeros(len(total_fitnesses))\n trip_seq[new_trip].append(gift_chosen)\n\n total_fitnesses = np.zeros(len(total_fitnesses))\n\n return [assignment, trip_load, trip_seq, fitnesses, total_fitnesses]\n\n\ndef swap_mutation(chromosome, gifts):\n assignment, trip_load, trip_seq, fitnesses, total_fitnesses = deepcopy(chromosome)\n\n gift_a = random.randrange(len(assignment))\n gift_b = random.randrange(len(assignment))\n\n trip_a = assignment[gift_a]\n trip_b = assignment[gift_b]\n\n while (\n gift_b == gift_a or\n trip_load[trip_a] - gifts[gift_a, -1] + gifts[gift_b, -1] > 1000 or\n trip_load[trip_b] - gifts[gift_b, -1] + gifts[gift_a, -1] > 1000\n ):\n gift_a = random.randrange(len(assignment))\n gift_b = random.randrange(len(assignment))\n\n trip_a = assignment[gift_a]\n trip_b = assignment[gift_b]\n\n # Update TRIP_A\n assignment[gift_b] = trip_a\n trip_load[trip_a] -= gifts[gift_a, -1]\n trip_load[trip_a] += gifts[gift_b, -1]\n fitnesses[trip_a] = np.zeros(len(total_fitnesses))\n index = trip_seq[trip_a].index(gift_a) # Raises ValueError if GIFT_CHOSEN does not exist.\n del trip_seq[trip_a][index]\n trip_seq[trip_a].append(gift_b)\n\n # Update TRIP_B\n assignment[gift_a] = trip_b\n trip_load[trip_b] -= gifts[gift_b, -1]\n trip_load[trip_b] += gifts[gift_a, -1]\n fitnesses[trip_b] = np.zeros(len(total_fitnesses))\n index = trip_seq[trip_b].index(gift_b) # Raises ValueError if GIFT_CHOSEN does not exist.\n del trip_seq[trip_b][index]\n trip_seq[trip_b].append(gift_a)\n\n total_fitnesses = np.zeros(len(total_fitnesses))\n\n return [assignment, trip_load, trip_seq, fitnesses, total_fitnesses]\n","sub_path":"src/Mutators.py","file_name":"Mutators.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"210800933","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[6]:\n\n\n\n# In[26]:\n\n\n\n\ngraph = {\n 'a' : ['b','c'],\n 'b' : [ 'd', 'e'],\n 'c' : ['f'],\n 'd' : [],\n 'e' : ['f'],\n 'f':[]\n}\n\nvisited = [] # List for visited nodes.\nqueue = [] #Initialize a queue\n\ndef bfs(visited, graph, node): #function for BFS\n visited.append(node)\n queue.append(node)\n\n while queue: # Creating loop to visit each node\n m = queue.pop(0) \n print (m, end = \" \") \n\n for neighbour in graph[m]:\n if neighbour not in visited:\n visited.append(neighbour)\n queue.append(neighbour)\n\n# Driver Code\nprint(\"Following is the Breadth-First Search\")\nbfs(visited, graph, 'd') # function calling\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"assigment02/assigment02-bfs.py","file_name":"assigment02-bfs.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"50173592","text":"#!/usr/bin/env python\r\n# encoding=UTF-8\r\n\r\n#文件名:test/TestSettingsController.py\r\n#描 述:TestSettingsController\r\n#创建日期:2009-04-21\r\n#修改日期:n/a\r\n\r\nimport unittest\r\nfrom xd547.Controllers.Settings import SettingsController\r\nfrom xd547.Error import Error as xd547Error\r\n\r\nclass TestSettingsContorller(unittest.TestCase):\r\n \r\n def setUp(self):\r\n self.GetQuery = lambda : SettingsController().GetQuery()\r\n self.IsExist = lambda : SettingsController().IsExist()\r\n \r\n def testSettingsGetQuery(self):\r\n self.GetQuery()\r\n self.failureException()\r\n \r\n def testSettingsIsExist(self):\r\n self.assert_(isinstance(self.IsExist(),(bool)))\r\n self.failureException()\r\n \r\n def testSettingsGetSettings(self):\r\n SettingsController().Get()\r\n self.assert_(isinstance(SettingsController().GetAdSwitch(), (bool)))\r\n self.assert_(isinstance(SettingsController().GetMsgSwitch(), (bool)))\r\n self.assert_(isinstance(SettingsController().GetSysSwitch(), (bool)))\r\n self.assert_(isinstance(SettingsController().GetDefalutPageEntriesCount(), (int)))\r\n self.assert_(isinstance(SettingsController().GetDefaultMsgEntriesCount(), (int)))\r\n self.failureException()\r\n \r\n def testSettingsAdd(self):\r\n settings = SettingsController()\r\n settingsAdd= lambda : settings.Add()\r\n settingsAdd()\r\n \r\n self.assertRaises(xd547Error.AddError, settingsAdd)\r\n self.failureException()\r\n \r\n def testSettingsUpdate(self):\r\n settings = SettingsController()\r\n settingsUpdate= lambda : settings.UpDate()\r\n settingsUpdate()\r\n self.assert_(isinstance(settings.GetAdSwitch(), (bool)))\r\n self.assert_(isinstance(settings.GetMsgSwitch(), (bool)))\r\n self.assert_(isinstance(settings.GetSysSwitch(), (bool)))\r\n self.assert_(isinstance(settings.GetDefalutPageEntriesCount(), (int)))\r\n self.assert_(isinstance(settings.GetDefaultMsgEntriesCount(), (int)))\r\n self.failureException()\r\n \r\n def testSettingsDel(self):\r\n settings = SettingsController()\r\n settingsDel = lambda : settings.Del()\r\n self.assertRaises(xd547Error.DelError, settingsDel)\r\n settingsAdd= lambda : settings.Add()\r\n settingsAdd()\r\n settingsDel()\r\n self.failureException()\r\n ","sub_path":"xd547/site/test/TestSettingsController.py","file_name":"TestSettingsController.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611734348","text":"from django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom .fixtures import create_user\nfrom ..models import Profile\n\n\nclass UserProfileTest(TestCase):\n\n def tearDown(self):\n for model in [Profile, User]:\n model.objects.all().delete()\n\n def test_profile_creation(self):\n user = create_user('bob', use_hash=True)\n profile = user.get_profile()\n assert profile, \"Profile wasn't created\"\n assert profile.get_absolute_url(), \"absolute URL couldn't be generated\"\n self.assertFalse(profile.has_chosen_identifier)\n\n def test_valid_identifier(self):\n user = create_user('bob', use_hash=True)\n profile = user.get_profile()\n self.assertFalse(profile.has_chosen_identifier)\n user.username = 'hello'\n user.save()\n profile = user.get_profile()\n self.assertTrue(profile.has_chosen_identifier)\n","sub_path":"popcorn_gallery/users/tests/models_tests.py","file_name":"models_tests.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"610009806","text":"#\n# Copyright 2017 NephoScale\n#\n\n\nfrom django.conf.urls import url\n\n#from astutedashboard.dashboards.admin.plan_mappings import views\nfrom astutedashboard.dashboards.billing.plan_mappings import views\n\n\nurlpatterns = [\n\n url(\n r'^$',\n views.IndexView.as_view(),\n name='index'\n ),\n\n\t\turl(\n\t\t\t\tr'^create_billing_plan_mapping/$',\n\t\t\t\tviews.CreateBillingPlanMappingView.as_view(),\n\t\t\t\tname='create_billing_plan_mapping'\n\t\t),\n\n\t\turl(\n\t\t\t\tr'^(?P[^/]+)/modify_billing_plan_mapping/$',\n\t\t\t\tviews.ModifyBillingPlanMappingView.as_view(),\n\t\t\t\tname='modify_billing_plan_mapping'\n\t\t),\n\n]\n","sub_path":"astute-dashboard/astutedashboard/dashboards/billing/plan_mappings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"55079635","text":"# -*_ coding: latin-1 -*-\n\n# The purpose of streams is to combine the stdout and stderr channels\n# into a single channel, aka a \"stream\".\n\n\nfrom .textmodel import TextModel\nfrom .textmodel.texeltree import Texel\nimport six\n\n\nclass StreamBase:\n # Stream protocol\n def output(self, obj, iserr=False):\n pass\n\n\nclass StreamRecorder(StreamBase):\n # A stream which stores all output calls into a list\n \n def __init__(self):\n self.messages = []\n\n def output(self, arg, iserr=False):\n self.messages.append((arg, iserr))\n\n\n\nclass Stream(StreamBase):\n # A stream which stores the output into a textmodel\n\n def __init__(self):\n self.model = TextModel()\n\n def output(self, obj, iserr=False):\n if isinstance(obj, Texel):\n new = TextModel()\n new.texel = obj\n else:\n if iserr:\n properties = {'textcolor':'red'}\n else:\n properties = {}\n if isinstance(obj, six.text_type):\n new = TextModel(obj, **properties)\n elif isinstance(obj, str):\n u = six.text_type(obj, 'utf-8')\n new = TextModel(u, **properties)\n else:\n new = TextModel(str(obj), **properties)\n self.model.append(new)\n","sub_path":"pynotebook/pynotebook/nbstream.py","file_name":"nbstream.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"93288490","text":"\r\n# coding: utf-8\r\n\r\n# In[ ]:\r\n\r\n\"\"\"Takes CL Logit Prediction-Frame as input.\"\"\"\r\n\r\n\r\n# In[3]:\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\n# In[39]:\r\n\r\ntest = pd.read_csv('sample1_preds.csv', index = False)\r\n\r\n\r\n# In[40]:\r\n\r\nror = pd.DataFrame()\r\nnames = ['track', 'LR', 'RFC', 'MNB', 'unigram2', 'unigram3', 'bigram2', 'bigram3', 'trigram2', 'trigram3']\r\nfor name in names:\r\n test[\"expected_\" + name] = test[name]*(test[\"ispDecimal\"].apply(lambda x: x+1))\r\n test = test.groupby(\"raceId\").apply(lambda x: x.sort_values([\"expected_\" + name], ascending = False)).reset_index(drop = True)\r\n ids = test['raceId'].unique().tolist()\r\n #left = test.loc[test[name + '_optimalFraction'].isnull() == True]['raceId'].unique().tolist()\r\n\r\n for i in ids:\r\n #for i in left:\r\n race = test.loc[test[\"raceId\"] == i]\r\n n = list(range(len(race)))\r\n frac = 1\r\n for k in n:\r\n if race.iloc[k]['expected_'+ name] > frac:\r\n sigma_k = float(race[['track_prob']][:(k+1)].sum())\r\n pi_k = float(race[[name]][:(k+1)].sum())\r\n frac = (1-pi_k)/(1-sigma_k)\r\n else:\r\n break\r\n \r\n optimalFraction = np.where((race[name] - race['track_prob']*frac)>0, race[name] - race['track_prob']*frac, 0)\r\n test.loc[test[\"raceId\"] == i, name + '_optimalFraction'] = optimalFraction\r\n race[name + '_optimalFraction'] = optimalFraction\r\n #while True:\r\n #try:\r\n #stake = (race['prizeFund']*race[name + '_optimalFraction']).sum()\r\n #assume 1 Pound bet on each race\r\n stake = race[name + '_optimalFraction'].sum()\r\n gain = ((race[name + '_optimalFraction'] + \r\n race[name + '_optimalFraction']*race['ispDecimal'])* race['winner']).sum()\r\n #gain = (race[\"base_optimalFraction\"]*(race['ispDecimal']+1)*race['winner']).sum()\r\n wins = np.repeat(gain-stake, len(race))\r\n bets = np.repeat(stake, len(race))\r\n \r\n test.loc[(test[\"raceId\"] == i), name + \"_wins\"] = wins\r\n test.loc[(test[\"raceId\"] == i), name + \"_bets\"] = bets\r\n\r\n unique = test.drop_duplicates(\"raceId\")\r\n \r\n rate = (unique[name +'_wins'].sum())/(unique[name + '_bets'].sum())\r\n ror[name] = pd.Series(rate)\r\n\r\n","sub_path":"Kelly.py","file_name":"Kelly.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"460221197","text":"import sys\nimport os\nfrom PIL import Image\n\nfrom_dir = sys.argv[1]\nto_dir = sys.argv[2]\n\n\ndef get_imgs_names(directory):\n images = filter(lambda x: x.endswith('jpg'), os.listdir(directory))\n return images\n\n\ndef get_imgs(images_names):\n converted_images = []\n\n for img_name in images_names:\n img = Image.open(f\"{from_dir}/{img_name}\")\n converted_images.append(img)\n\n return converted_images\n\n\ndef save_converted_imgs_to_dir(images, directory):\n i = 0\n for image in images:\n i += 1 #index of converted img in new dir\n image.save(f'{directory}/{i}img.png', 'png')\n\n\ndef main_function(*dirs):\n for directory in dirs: # проверяем наличие папок и создаём, если нет\n if os.path.exists(directory):\n print(f'Папка {directory} обнаружена')\n else:\n print(f'Папка {directory} не найдена')\n # если нет главной папки с картинками, то прерываем программу\n if dirs.index(directory) != 0:\n if input('Чтобы создать папку введите любую букву; чтобы не создавать, оставьте поле пустым: '):\n os.mkdir(directory, 755)\n else:\n break\n else:\n break\n\n print('Произвожу конвертирование и добавляю в новую папку')\n\n imgs_names = get_imgs_names(from_dir)\n imgs = get_imgs(imgs_names)\n\n save_converted_imgs_to_dir(imgs, to_dir)\n\n print('Операция завершена!')\n\n\nmain_function(from_dir, to_dir)\n","sub_path":"project_converter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"126226056","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pydub import AudioSegment\nimport os\n\nvideo_link = \"clip_id_easy_Medium.mp4\"\nhit_audio = \"noise_chopped.wav\"\ntracker = cv2.TrackerCSRT_create()\nvideo = cv2.VideoCapture(video_link)\n\ndef tracking(visualize=False):\n success, frame = video.read()\n init_frame = np.copy(frame)\n\n vh, vw = frame.shape[:2]\n\n '''\n #when selecting objects from a video clip the first time, copy down the location so no need to select it everytime \n bbox = cv2.selectROI(frame, False)\n drum_box = cv2.selectROI(frame, False)\n person_box = cv2.selectROI(frame, False)\n\n print(bbox)\n print(drum_box)\n print(person_box)\n return\n '''\n \n '''\n #drumclip10\n bbox = (750, 325, 55, 58)\n drum_box = (718, 347, 197, 233)\n person_box =(497, 230, 100, 413)\n '''\n \n \n #drumclip11\n bbox = (859, 304, 47, 45)\n drum_box = (801, 125, 309, 454)\n person_box = (577, 7, 191, 640)\n \n \n h, w = bbox[2:]\n dh, dw = drum_box[2:]\n tracker.init(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), bbox)\n \n display = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n p1 = (int(bbox[0]), int(bbox[1]))\n p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])) \n\n frames = []\n locs = []\n while True:\n success, frame = video.read()\n if not success:\n break\n \n ok, loc = tracker.update(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))\n\n #we are only including the frames where tracking is sucessful, because no point of analysis if tracking fails\n if ok:\n loc = tuple(map(int, loc))\n frames.append(frame)\n locs.append(loc[:2])\n else:\n print(\"failed\")\n\n '''\n #Naive way of checking contact(i.e. check if drumstick collides with drum hitbox in 2d\n contact_index = contact_made_naive(drum_box, locs, (h, w), frames)\n process_frames(frames, locs, (h, w), visualize, drum_box=drum_box)\n '''\n \n '''\n #contact method 1\n contact_index, bar = contact_made(person_box[:2], drum_box[:2], locs, frames)\n #visualize tracking and threshold\n process_frames(frames, locs, (h, w), visualize, bar=bar)\n '''\n\n \n #contact method 2\n contact_index = contact_made_2(person_box[:2], drum_box[:2], locs, frames)\n\n if visualize:\n process_frames(frames, locs, (h, w), False) #No threshold bar to visualize \n \n visualize_contact(contact_index, frames)\n\n visualize_drumstick_path(init_frame, locs, (h, w))\n\n #writing the frames where tracking is successful\n codec = cv2.VideoWriter_fourcc(*'XVID')\n video_out = cv2.VideoWriter('output.mp4', codec, 20, (vw, vh))\n\n for frame in frames:\n video_out.write(frame)\n\n video_out.release()\n\n #write the audio based on the contact frames\n out_audio = create_audio(frames, contact_index, hit_audio)\n out_audio.export('output_audio.wav', format=\"wav\")\n\n #now we have both the video and the audio, combine them\n os.system(\"ffmpeg -i output.mp4 -i output_audio.wav -y -vcodec copy -acodec copy output_vid_aud.avi\")\n \n\n'''\nDifferent methods of checking if contact has been made\n'''\ndef contact_made_naive(drum_box, locs, stick_size, frames):\n sh, sw = stick_size\n \n contact_index = []\n \n for i in range(len(locs)):\n loc = locs[i]\n #if the drum_stick lie entirely within the drum box,\n #i.e left_side_drum < left_side_stick < right_size_stick < right_side_drum\n collide = drum_box[0] < loc[0] < loc[0] + sw < drum_box[0] + drum_box[2] and drum_box[1] < loc[1] < loc[1] + sh < drum_box[1] + drum_box[3]\n if collide:\n contact_index.append(i)\n return contact_index\n\ndef contact_made(loc_person, loc_drum, all_loc_sticks, frames, threshold=0.7):\n #threshold value can be tuned. larger value means more strict restriction\n dx, dy = loc_drum\n px, py = loc_person\n\n min_x = min(all_loc_sticks)[0]\n max_x = max(all_loc_sticks)[0]\n\n diff = max_x - min_x\n \n if loc_person[0] < loc_drum[0]:\n print(\"right\")\n #drum is on the right side, so return the stick locations that are on the right\n bar = min_x + (threshold) * diff\n contact_index = [i for i in range(len(frames)) if all_loc_sticks[i][0] > min_x + (threshold) * diff]\n else:\n print(\"left\")\n #drum is on the left side, so return the stick locations that are on the left\n bar = min_x + (1 - threshold) * diff\n contact_index = [i for i in range(len(frames)) if all_loc_sticks[i][0] < min_x + (1 - threshold) * diff]\n\n return contact_index, bar\n\ndef contact_made_2(loc_person, loc_drum, all_loc_sticks, frames):\n\n dx, dy = loc_drum\n px, py = loc_person\n\n contact_index = []\n if loc_person[0] < loc_drum[0]:\n print(\"right\")\n #detect change in direction from right to left -> hit\n for i in range(1, len(frames) - 1):\n if all_loc_sticks[i][0] > all_loc_sticks[i - 1][0] and all_loc_sticks[i][0] > all_loc_sticks[i + 1][0]:\n contact_index.append(i)\n\n else:\n print(\"left\")\n #detect change in direction from left to right -> hit\n for i in range(1, len(frames) - 1):\n if all_loc_sticks[i][0] < all_loc_sticks[i - 1][0] and all_loc_sticks[i][0] < all_loc_sticks[i + 1][0]:\n contact_index.append(i)\n\n return contact_index\n \n\n'''\nA few visualization methods\n'''\ndef viz_threshold(frame, min_x, max_x, bar):\n\n #draw threshold\n frame[:, int(bar): int(bar) + 5] = np.array([255, 0, 0])\n frame[:, min_x: min_x + 5] = np.array([255, 0, 0])\n frame[:, max_x: max_x + 5] = np.array([255, 0, 0])\n\ndef viz_drum_loc(frame, drum_box):\n top_left = (drum_box[:2])\n bot_right = (top_left[0] + drum_box[2], top_left[1] + drum_box[3])\n cv2.rectangle(frame, top_left, bot_right, (255, 0, 0), thickness=5)\n\ndef process_frames(frames, locs, stick_size, visualize, bar=None, drum_box=None):\n sh, sw = stick_size\n \n min_x = min(locs)[0]\n max_x = max(locs)[0]\n \n for i in range(len(frames)): \n frame = frames[i]\n loc = locs[i]\n cv2.rectangle(frame, loc, (loc[0] + sw, loc[1] + sh), (0, 255, 0), 2)\n if visualize:\n if bar:\n viz_threshold(frame, min_x, max_x, bar)\n\n if drum_box:\n viz_drum_loc(frame, drum_box)\n\ndef visualize_contact(contact_index, frames):\n w, h = frames[0].shape[:2]\n for index in contact_index:\n frame = frames[index]\n cv2.rectangle(frame, (h // 2 - 150, 50), (h // 2 + 150, 200), (255, 255, 255), thickness = -1)\n cv2.putText(frame, \"boop\", (h // 2 - 150, 150), cv2.FONT_HERSHEY_SIMPLEX, 5, (0, 0, 255), thickness=5)\n\ndef visualize_drumstick_path(init_frame, all_loc_sticks, stick_size):\n h, w = stick_size\n\n for loc in all_loc_sticks:\n cv2.circle(init_frame, (loc[0] + w // 2, loc[1] + h // 2), 2, (255, 0, 0), thickness=2)\n\n cv2.imwrite('stick_path_viz.jpg', init_frame)\n\n\n#write the audio based on the contacted frames\ndef create_audio(frames, contact_index, audio_path):\n total_length = frames * 50 #length of the video in millseconds\n\n #each frame is 50ms(20fps), drum audio is 200ms\n drum_hit = AudioSegment.from_wav(audio_path)\n if len(drum_hit) != 200:\n drum_hit = drum_hit[:200]\n\n silent_hit = AudioSegment.silent(duration=200)\n\n #the audio that matches with the video\n out_audio = AudioSegment.silent(duration=0)\n\n for i in range(0, len(frames), 4): #4 frames per 1 interval(either silent or drum hit)\n if i in contact_index or i + 1 in contact_index or i + 2 in contact_index or i + 3 in contact_index:\n out_audio = out_audio + drum_hit\n else:\n out_audio = out_audio + silent_hit\n\n return out_audio\n \n \n\nif __name__ == '__main__':\n #capture_first_frame()\n tracking(True)\n","sub_path":"Project/test_tracking_ol.py","file_name":"test_tracking_ol.py","file_ext":"py","file_size_in_byte":7953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"199877004","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.13.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # PyNEST – Visual Cortex Model\n\n# **Modeling networks of spiking neurons with spatial connectivity using NEST**\n#\n# **BASSES 2022, 15.06.2022**\n#\n# **[Jasper Albers](mailto:j.albers@fz-juelich.de), [Johanna Senk](mailto:j.senk@fz-juelich.de)**\n\n# \n# \n# \n# \n# \n# \n# \n#
\n#
\n# \"histology\"
\n# Balaram et al. (2014): Histological features of layers and sublayers in cortical visual areas V1 and V2 of chimpanzees, macaque monkeys, and humans
\n#
\n# \n# \n#
\n# \"flow
\n# Potjans and Diesmann (2014): The Cell-Type Specific Cortical Microcircuit: Relating Structure and Activity in a Full-Scale Spiking Network Model
\n#
\n\n# In this notebook we will construct a simple model of visual cortex using spatial connectivity and a data-driven approach. We want to include the first two stages of visual processing, modeling four neuronal populations: excitatory and inhibitory neurons of both layer 4 and layer 2/3. The former is associated with receiving input from lower cortical areas; in the case of the primary visual cortex, this can be the thalamus relaying information from the retina. The latter is the main target of layer 4 neurons.\n\n#
\n# \"histology\"
\n# Architecture of our network model of visual cortex.
\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib notebook\n\n# import NEST & NEST rasterplot\nimport nest\nimport nest.raster_plot\n\n\n# -\n\ndef beautify_plot(title=None, fig=None):\n plt.xticks([-0.5, 0, 0.5])\n plt.xlabel('cortical space x [mm]')\n plt.yticks([-0.5, 0, 0.5])\n plt.ylabel('cortical space y [mm]')\n plt.xlim(-0.5,0.5)\n plt.ylim(-0.5,0.5)\n if title:\n plt.title(title, figure=fig)\n\n\n# ___\n# ## Setup\n\n# ### Define parameters\n\n# #### Simulation parameters\n\nsimtime = 5000. # simulation time (ms)\n\n# #### Network parameters\n#\n# We now want to employ a data-driven approach, using data from experimental studies of the brain that report, e.g., neuron and synapse densities as well as termination patterns for specifying the connectivity.\n\npopulations = ['L2/3E', 'L2/3I', 'L4E', 'L4I']\nscaling = 0.1 # scaling down the true number of neurons\n\n# +\nnum_neurons_all_layers = np.load('data/num_neurons_V1_1mm2.npy') # number of neurons per 1mm2 in macaque V1\n\nnum_neurons_all_layers *= scaling\n\nnum_neurons = {\n 'L2/3E': int(num_neurons_all_layers[0, 0]),\n 'L2/3I': int(num_neurons_all_layers[0, 1]),\n 'L4E': int(num_neurons_all_layers[1, 0]),\n 'L4I': int(num_neurons_all_layers[1, 1])\n}\n# -\n\n# Rather than using indegrees, we use pre-computed connection probabilities between all four populations of the model. Computing these probabilities a task of its own as different tracing studies have to be combined. Here, we simply assume this work has already been done as we want to focus on the model building.\n\nconnection_probs = np.load('data/connection_probs.npy') # connection probabilities, index: [target, source]\n\n# Let us have a look at how this connectivity looks like.\n\nimport seaborn as sns\nfig, ax = plt.subplots()\nsns.heatmap(connection_probs)\nax.set_xticklabels(populations)\nax.set_yticklabels(populations)\nax.set_xlabel('Source population')\nax.set_ylabel('Target population')\nax.set_title('Zero-distance connection probabilities')\n\n# #### Neuron parameters\n\n# Here, we are using neuron parameters obtained from the [Cell Type Atlas](https://celltypes.brain-map.org/data) by the Allen Institute for Brain Science which reports physiological recordings of single neurons.\n\nneuron_params = {\n 'C_m': np.exp(5.54 + 0.57**2 / 2), # membrane capacity (pF)\n 'E_L': -70.52, # resting membrane potential (mV)\n 'V_m': -58., # initial membrane potential (mV)\n 'V_reset': -70.52, # reset membrane potential after a spike (mV)\n 'V_th': -70.52 + 27.15, # spike threshold\n 't_ref': 2.0, # refractory period (ms)\n 'tau_m': 3.42, # membrane time constant (ms)\n}\n\n# #### Synapse parameters\n\nw = 1.36 / scaling # excitatory synaptic weight (mV)\ng = 6. # relative inhibitory to excitatory synaptic weight\nd = 1.5 # synaptic transmission delay (ms)\n\n# #### External input parameters\n\np_rate = 8. # external rate (spikes/s)\n\n# ### Configure NEST\n\n# configure kernel\nnest.ResetKernel()\nnest.SetKernelStatus({'rng_seed': 192873})\n\n# ___\n# ## Spatially distributed neurons \n\n# ### Create neurons\n#\n# We want to endow the neurons with the notion of space. This functionality is built right into NEST 3:\n\n# +\n# set default parameters for neurons and create neurons\nnest.SetDefaults('iaf_psc_delta', neuron_params)\n\npos = {}\nlayers = {}\n\nfor pop in populations:\n \n # define positions via a distribution in space (free, grid and list possible)\n pos[pop] = nest.spatial.free(\n pos=nest.random.uniform(min=-0.5, max=0.5),\n num_dimensions=2,\n edge_wrap=True)\n\n # create layers of spatially distributed neurons according to position objects\n layers[pop] = nest.Create('iaf_psc_delta', num_neurons[pop], positions=pos[pop])\n# -\n\n# Below we can check what these layers look like in 2D space.\n\n# +\nplot_e = nest.PlotLayer(layers['L2/3E'], nodecolor='cornflowerblue')\nbeautify_plot(title='excitatory neurons of L2/3', fig=plot_e)\n\nplot_i = nest.PlotLayer(layers['L2/3I'], nodecolor='tomato')\nbeautify_plot(title='inhibitory neurons of L2/3', fig=plot_i)\n# -\n\n# ### Create connections\n#\n# Our neurons are now arranged in 2D layers. What will happen if we use a standard, random connection method?\n\n# synapse specification\nsyn = {\n 'E': {'delay': d, 'weight': w},\n 'I': {'delay': d, 'weight': - g * w}\n}\n\n# We now want to take the connectivity data and connect the neuronal populations according to an exponential profile:\n#\n# $$p(x) = p_0 e^{-x/\\beta}$$\n#\n# where $x$ is the horizontal distance of a target neuron to the source neuron, and $\\beta$ is the characteristic length of the exponential profile. We obtain $\\beta$ from fitting exponential functions to the layer-specific distribution of outgoing connections measured by Sincich et al. (2001), see image at the top of notebook 1.\n\nbeta_all_layers = np.load('data/beta.npy') # decay constant of target layers\n\nbeta = {\n 'L2/3E': beta_all_layers[0, 0],\n 'L2/3I': beta_all_layers[0, 1],\n 'L4E': beta_all_layers[1, 0],\n 'L4I': beta_all_layers[1, 1]\n}\n\nfor s, source in enumerate(populations):\n for t, target in enumerate(populations):\n \n prob_distribution = nest.spatial_distributions.exponential(\n x = nest.spatial.distance,\n beta = beta[target])\n\n conn = {'rule': 'pairwise_bernoulli',\n 'p': connection_probs[t, s] * prob_distribution}\n \n nest.Connect(layers[source], layers[target], conn, syn[source[-1]])\n\n# Let's see what this connectivity actually looks like in space. \n\n# +\nfig_e = nest.PlotLayer(layers['L4E'], nodecolor='cornflowerblue', nodesize=40)\n\nsource = layers['L4E'][3]\ntarget_plot = nest.PlotTargets(source, layers['L4E'], fig=fig_e,\n src_size=250, tgt_color='indigo', tgt_size=20,\n probability_cmap='Purples')\nbeautify_plot(title='excitatory neurons of L4', fig=fig_e)\n\n# +\nfig_i = nest.PlotLayer(layers['L4I'], nodecolor='tomato', nodesize=80)\n\nsource = layers['L4I'][5]\ntarget_plot = nest.PlotTargets(source, layers['L4I'], fig=fig_i,\n src_size=250, tgt_color='indigo', tgt_size=20)\n\nbeautify_plot(title='inhibitory neurons of L4', fig=fig_i)\n# -\n\n# ## Simulate and analyze\n#\n# External input is again represented as Poisson input.\n\n# +\n# create poisson generator and set 'rate' to p_rate\npgen = nest.Create('poisson_generator', params={'rate': p_rate})\n\n# create spike recorder\nspikes = {}\nfor pop in populations:\n spikes[pop] = nest.Create('spike_recorder')\n# -\n\n# connect poisson generator using the excitatory connection weight\nfor pop in populations:\n nest.Connect(pgen, layers[pop], syn_spec=syn['E'])\n\n# Recording works by connecting the populations to recording devices.\n\n# connect excitatory / inhibitory neurons to spike recorder\nfor pop in populations:\n nest.Connect(layers[pop], spikes[pop])\n\n# #### Stimulus propagation\n\nstimulus = False\n\n# +\nif stimulus:\n stim = nest.Create('poisson_generator',\n params={'rate': p_rate / 1.7,\n 'start': 1000.,\n 'stop': 2000.})\n\n nest.Connect(stim, layers['L4E'], syn_spec=syn['E'])\n nest.Connect(stim, layers['L4I'], syn_spec=syn['E'])\n \ndef show_stimulus():\n plt.fill_between([1000, 2000], 0, 1e5, color='mediumseagreen', alpha=0.3, label='stimulus')\n plt.legend(loc='upper right')\n\n\n# -\n\n# simulate\nnest.Simulate(simtime) \n\n# Creating a raster plot gives a visual representation of the network activity.\n\n# +\n# raster plot of spiking activity using nest.raster_plot\nnest.raster_plot.from_device(spikes['L4E'], hist=False, title='spiking activity of L4 excitatory neurons')\nplt.xlim(0, 5000)\nplt.ylim(num_neurons['L2/3E'] + num_neurons['L2/3I'],\n num_neurons['L2/3E'] + num_neurons['L2/3I'] + num_neurons['L4E'])\nif stimulus:\n show_stimulus()\n\nnest.raster_plot.from_device(spikes['L4I'], hist=False, title='spiking activity of L4 inhibitory neurons')\nplt.xlim(0, 5000)\nplt.ylim(num_neurons['L2/3E'] + num_neurons['L2/3I'] + num_neurons['L4E'],\n num_neurons['L2/3E'] + num_neurons['L2/3I'] + num_neurons['L4E'] + num_neurons['L4I'])\nif stimulus:\n show_stimulus()\n\n# +\n# raster plot of spiking activity using nest.raster_plot\nnest.raster_plot.from_device(spikes['L2/3E'], hist=False, title='spiking activity of L2/3 excitatory neurons')\nplt.xlim(0, 5000)\nplt.ylim(0, num_neurons['L2/3E'])\nif stimulus:\n show_stimulus()\n \nnest.raster_plot.from_device(spikes['L2/3I'], hist=False, title='spiking activity of L2/3 inhibitory neurons')\nplt.xlim(0, 5000)\nplt.ylim(num_neurons['L2/3E'], num_neurons['L2/3E'] + num_neurons['L2/3I'])\nif stimulus:\n show_stimulus()\n# -\n# What happens when we set `stimulus = True` in the cell a few cells above? Does the activity propagate to layer 2/3 even though the stimulus only targets layer 4?\n# Note: \"Restart kernel and re-run the whole notebook\" after setting `stimulus = True`.\n\n","sub_path":"materials/nest/nest_data_driven_network/2_data_driven_network.py","file_name":"2_data_driven_network.py","file_ext":"py","file_size_in_byte":11200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154184119","text":"'''\nDanny Lin\ndl3201\nhw9q2.py\n'''\n\ndef find_all(lst, val):\n #looks at the list in terms of index\n index = 0\n locations = [] #stores the indices of found values\n while index <= len(lst)-1:\n #if the index is equal to the value, add it to locations list\n if lst[index] == val:\n locations.append(index)\n #increase index to look at each element of the lst\n index += 1\n return locations #return list of indices at which \"val\" is found\n\ndef main():\n lst = []\n n = \"\"\n val = input(\"What value do you want to look for? \")\n while n != \"done\":\n n = input(\"Please enter a string or integer or 'done': \")\n if n != \"done\":\n lst.append(n)\n indices = find_all(lst, val)\n print(\"The locations of val:\",indices)\n \nmain()\n","sub_path":"CS1114/HW9/hw9q2.py","file_name":"hw9q2.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521785766","text":"import copy\nimport falcon\nimport json\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport traceback\nfrom datetime import datetime, timedelta\nfrom sqlalchemy import func, desc\nfrom sqlalchemy.exc import SQLAlchemyError\n\nimport model\nimport endpoint\nimport util\nfrom db import engine, session\nfrom util import UserInfo\n\n# sets CORS header to *, applied when running in a docker container\nDISABLE_CORS = False\n\n# Cache of the current year.\nc_year = None\nc_year_update = None\n\n\nclass JSONTranslator(object):\n\n def process_request(self, req, resp):\n return\n\n def process_response(self, req, resp, endpoint):\n if 'result' not in req.context:\n return\n\n resp.body = json.dumps(\n req.context['result'],\n sort_keys=True,\n indent=4,\n ensure_ascii=False,\n )\n\n\nclass Authorizer(object):\n\n def process_request(self, req, resp):\n if req.auth:\n token_str = req.auth.split(' ')[-1]\n try:\n token = session.query(model.Token).get(token_str)\n\n if token is not None:\n if (req.relative_uri != '/auth' and\n token.expire < datetime.utcnow()):\n # user timeouted\n req.context['user'] = UserInfo()\n return\n\n try:\n req.context['user'] = UserInfo(\n session.query(model.User).get(token.user),\n token_str\n )\n return\n except AttributeError:\n pass\n except:\n session.rollback()\n\n req.context['user'] = UserInfo()\n\n\nclass Year_fill(object):\n\n # This middleware has 2 purposes:\n # 1) Get current year.\n # 2) Test connection with db. (this is very important!)\n def process_request(self, req, resp):\n if req.method == 'OPTIONS':\n return\n try:\n if ('YEAR' in req.headers):\n req.context['year'] = req.headers['YEAR']\n req.context['year_obj'] = session.query(model.Year).\\\n get(req.context['year'])\n else:\n year_obj = session.query(model.Year).\\\n order_by(desc(model.Year.id)).first()\n req.context['year_obj'] = year_obj\n req.context['year'] = year_obj.id\n except SQLAlchemyError:\n session.rollback()\n try:\n if ('YEAR' in req.headers):\n req.context['year'] = req.headers['YEAR']\n req.context['year_obj'] = session.query(model.Year).\\\n get(req.context['year'])\n else:\n year_obj = session.query(model.Year).\\\n order_by(desc(model.Year.id)).first()\n req.context['year_obj'] = year_obj\n req.context['year'] = year_obj.id\n except:\n session.rollback()\n raise\n\n\nclass AddCORS:\n def process_request(self, req, resp):\n return\n\n def process_response(self, req, resp, *_):\n if DISABLE_CORS:\n resp.set_header('Access-Control-Allow-Origin', '*')\n\n\ndef log(req, resp):\n try:\n ip = req.env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip()\n except KeyError:\n ip = req.env['REMOTE_ADDR']\n\n print('[%s] [%s] [%s] [%s] %s' %\n (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ip, req.method,\n resp.status, req.relative_uri))\n sys.stdout.flush()\n\n\nclass Logger(object):\n\n def process_request(self, req, resp):\n log(req, resp)\n\n\ndef log_sink(req, resp):\n resp.status = falcon.HTTP_404\n\n # Uncomment this to log sink\n # log(req, resp)\n\n\nclass Corser(object):\n\n def process_response(self, request, response, resource):\n origin = request.get_header('Origin')\n\n if origin in ('http://localhost:4200',\n 'https://ksi.fi.muni.cz',\n 'https://kyzikos.fi.muni.cz'):\n response.set_header('Access-Control-Allow-Origin', origin)\n\n response.set_header('Access-Control-Allow-Headers',\n 'authorization,content-type,year')\n response.set_header('Access-Control-Allow-Methods',\n 'OPTIONS,PUT,POST,GET,DELETE')\n\n\ndef error_handler(ex, req, resp, params):\n if isinstance(ex, falcon.HTTPError):\n req.context['result'] = {\n 'errors': [ {\n 'status': ex.status,\n 'title': ex.title,\n 'detail': ex.description,\n } ]\n }\n resp.status = ex.status\n else:\n req.context['result'] = {\n 'errors': [ {\n 'status': '500',\n 'title': 'Internal server error',\n 'detail': 'Vnitřní chyba serveru, kontaktujte správce backendu.',\n } ]\n }\n resp.status = falcon.HTTP_500\n\n log(req, resp)\n if resp.status == falcon.HTTP_500:\n dt = datetime.now().strftime('[%Y-%m-%d %H:%M:%S]')\n lines = '\\n'.join(\n [dt + ' ' + line for line in traceback.format_exc().split('\\n')]\n )\n print(lines)\n\n\n# Add Logger() to middleware for logging\napi = falcon.API(middleware=[JSONTranslator(), Authorizer(), Year_fill(),\n Corser(), AddCORS()])\napi.add_error_handler(Exception, handler=error_handler)\napi.req_options.auto_parse_form_urlencoded = True\n\n# Odkomentovat pro vytvoreni tabulek v databazi\n# model.Base.metadata.create_all(engine)\n\n# Create /tmp/box with proper permissions (for sandbox)\nif os.path.isdir(util.programming.EXEC_PATH):\n shutil.rmtree(util.programming.EXEC_PATH, ignore_errors=True)\n\ntry:\n os.makedirs(util.programming.EXEC_PATH)\nexcept FileExistsError:\n pass\n\np = subprocess.Popen([\"setfacl\", \"-d\", \"-m\", \"group:ksi:rwx\",\n util.programming.EXEC_PATH])\np.wait()\nif p.returncode != 0:\n raise Exception(\"Cannot change umask to %s!\" %\n (util.programming.EXEC_PATH))\n\napi.add_route('/robots.txt', endpoint.Robots())\napi.add_route('/csp', endpoint.CSP())\napi.add_route('/articles', endpoint.Articles())\napi.add_route('/articles/{id}', endpoint.Article())\napi.add_route('/achievements', endpoint.Achievements())\napi.add_route('/achievements/{id}', endpoint.Achievement())\napi.add_route('/achievements/special/successful', endpoint.AchievementSuccessfulParticipant())\napi.add_route('/posts', endpoint.Posts())\napi.add_route('/posts/{id}', endpoint.Post())\napi.add_route('/tasks', endpoint.Tasks())\napi.add_route('/tasks/{id}', endpoint.Task())\napi.add_route('/taskDetails/{id}', endpoint.TaskDetails())\napi.add_route('/modules/{id}', endpoint.Module())\napi.add_route('/modules/{id}/submit', endpoint.ModuleSubmit())\napi.add_route('/modules/{id}/submitFiles', endpoint.ModuleSubmit()) # alias required for swagger\napi.add_route('/submFiles/{id}', endpoint.ModuleSubmittedFile())\napi.add_route('/threads', endpoint.Threads())\napi.add_route('/threads/{id}', endpoint.Thread())\napi.add_route('/threadDetails/{id}', endpoint.ThreadDetails())\napi.add_route('/users', endpoint.Users())\napi.add_route('/users/{id}', endpoint.User())\napi.add_route('/profile/picture', endpoint.PictureUploader())\napi.add_route('/profile/{id}', endpoint.OrgProfile())\napi.add_route('/profile/', endpoint.Profile())\napi.add_route('/basicProfile/', endpoint.BasicProfile())\napi.add_route('/images/{context}/{id}', endpoint.Image())\napi.add_route('/content', endpoint.Content())\napi.add_route('/taskContent/{id}', endpoint.TaskContent())\napi.add_route('/task-content/{id}/{view}', endpoint.TaskContent())\napi.add_route('/registration', endpoint.Registration())\napi.add_route('/auth', endpoint.Authorize())\napi.add_route('/logout', endpoint.Logout())\napi.add_route('/runCode/{id}/submit', endpoint.RunCode())\napi.add_route('/feedback', endpoint.FeedbackEmail())\napi.add_route('/settings/changePassword', endpoint.ChangePassword())\napi.add_route('/forgottenPassword', endpoint.ForgottenPassword())\napi.add_route('/waves', endpoint.Waves())\napi.add_route('/waves/{id}', endpoint.Wave())\napi.add_route('/years', endpoint.Years())\napi.add_route('/years/{id}', endpoint.Year())\napi.add_route('/feedbacks', endpoint.FeedbacksTask())\napi.add_route('/feedbacks/{id}', endpoint.FeedbackTask())\napi.add_route('/diplomas/{user}', endpoint.Diploma())\napi.add_route('/diplomas/{user}/{year}/show', endpoint.DiplomaDownload())\n\n\"\"\"\ntask-content endpoint contains: (defined in endpoint/content.py, see also\n./gunicorn_cfg.py)\n * /taskContent/{id}/zadani/{file_path}\n * /taskContent/{id}/reseni/{file_path}\n * /taskContent/[id]/icon/{file_name}\n\"\"\"\n\napi.add_route('/admin/evaluations/{id}', endpoint.admin.Evaluation())\napi.add_route('/admin/corrections', endpoint.admin.Corrections())\napi.add_route('/admin/corrections/{id}', endpoint.admin.Correction())\napi.add_route('/admin/correctionsInfos', endpoint.admin.CorrectionsInfo())\napi.add_route('/admin/correctionsInfos/{id}', endpoint.admin.CorrectionInfo())\napi.add_route('/admin/correctionsEmail/{id}', endpoint.admin.CorrectionsEmail())\napi.add_route('/admin/corrections/{id}/publish', endpoint.admin.CorrectionsPublish())\napi.add_route('/admin/subm/eval/{eval_id}/', endpoint.admin.SubmFilesEval())\napi.add_route('/admin/subm/task/{task_id}/', endpoint.admin.SubmFilesTask())\napi.add_route('/admin/e-mail/', endpoint.admin.Email())\napi.add_route('/admin/atasks/', endpoint.admin.Tasks())\napi.add_route('/admin/atasks/{id}', endpoint.admin.Task())\napi.add_route('/admin/atasks/{id}/deploy', endpoint.admin.TaskDeploy())\napi.add_route('/admin/atasks/{id}/merge', endpoint.admin.TaskMerge())\napi.add_route('/admin/waves/{id}/diff', endpoint.admin.WaveDiff())\napi.add_route('/admin/achievements/grant', endpoint.admin.AchievementGrant())\napi.add_route('/admin/user-export', endpoint.admin.UserExport())\napi.add_route('/admin/evalCodes/{id}', endpoint.admin.EvalCode())\napi.add_route('/admin/execs', endpoint.admin.Execs())\napi.add_route('/admin/execs/{id}', endpoint.admin.Exec())\napi.add_route('/admin/monitoring-dashboard', endpoint.admin.MonitoringDashboard())\napi.add_route('/admin/diploma/{id}/grant', endpoint.admin.DiplomaGrant())\n\napi.add_route('/unsubscribe/{id}', endpoint.Unsubscribe())\n\napi.add_sink(log_sink)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"107281124","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 1 21:55:34 2018\r\n\r\n@author: gaoha\r\n\"\"\"\r\n\r\nfrom collections import defaultdict\r\nfrom sklearn.svm import LinearSVC \r\nimport datetime\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nimport matplotlib.pyplot as plt\r\nfrom config import config\r\n#import seaborn as sns\r\nimport numpy as np\r\nimport csv\r\n\r\ndef load_data_and_labels(data_file, labels_file):\r\n \"\"\"\r\n Loads MR polarity data from files, splits the data into words and generates labels.\r\n Returns split sentences and labels.\r\n \"\"\"\r\n x_text = []\r\n y = []\r\n \r\n with open(data_file, encoding = \"utf-8\") as csvFile:\r\n readCSV = csv.reader(csvFile, delimiter = \",\")\r\n for row in readCSV:\r\n row = \"\".join(row)\r\n x_text.append(row) \r\n \r\n with open(labels_file, encoding = \"utf-8\") as csvFile2:\r\n readCSV = csv.reader(csvFile2, delimiter = \",\")\r\n for row in readCSV:\r\n d = defaultdict(list)\r\n for k,va in [(v,i) for i,v in enumerate(row)]:\r\n d[k].append(va)\r\n \r\n for k in range(len(d.get(\"1.0\"))):\r\n index = d.get(\"1.0\")[k]\r\n row[index] = 1\r\n for k in range(len(d.get(\"0.0\"))):\r\n index = d.get(\"0.0\")[k]\r\n row[index] = 0\r\n \r\n# print(len(row))\r\n y.append(row)\r\n \r\n\r\n\r\n\r\n \r\n print(\"x = {}\".format(len(x_text)))\r\n print(\"y = {}\".format(len(y)))\r\n \r\n return x_text, y\r\n\r\n\r\n\r\ndef precision_recall(scores, y_batch): \r\n y_indices = scores.argsort()[:, -1:][:, ::-1]\r\n pre = 0.0\r\n rec = 0.0\r\n for i in range(len(y_batch)):\r\n intersec_true = 0\r\n for j in y_indices[i]:\r\n intersec_true += y_batch[i][j]\r\n true_total_count = np.count_nonzero(y_batch[i] == 1)\r\n pred_total_count = len(y_indices[i])\r\n pre += intersec_true*1.0/pred_total_count\r\n rec += intersec_true*1.0/true_total_count\r\n pre = pre/len(y_batch)\r\n rec = rec/len(y_batch)\r\n \r\n \r\n \r\n y_indices_2 = scores.argsort()[:, -2:][:, ::-1]\r\n pre_2 = 0.0\r\n rec_2 = 0.0\r\n for i in range(len(y_batch)):\r\n intersec_true = 0\r\n for j in y_indices_2[i]:\r\n intersec_true += y_batch[i][j]\r\n true_total_count = np.count_nonzero(y_batch[i] == 1)\r\n pred_total_count = len(y_indices_2[i])\r\n pre_2 += intersec_true*1.0/pred_total_count\r\n rec_2 += intersec_true*1.0/true_total_count\r\n pre_2 = pre_2/len(y_batch)\r\n rec_2 = rec_2/len(y_batch)\r\n \r\n \r\n y_indices_3 = scores.argsort()[:, -3:][:, ::-1]\r\n pre_3 = 0.0\r\n rec_3 = 0.0\r\n for i in range(len(y_batch)):\r\n intersec_true = 0\r\n for j in y_indices_3[i]:\r\n intersec_true += y_batch[i][j]\r\n true_total_count = np.count_nonzero(y_batch[i] == 1)\r\n pred_total_count = len(y_indices_3[i])\r\n pre_3 += intersec_true*1.0/pred_total_count\r\n rec_3 += intersec_true*1.0/true_total_count\r\n pre_3 = pre_3/len(y_batch)\r\n rec_3 = rec_3/len(y_batch)\r\n \r\n return pre, rec, pre_2, rec_2, pre_3, rec_3\r\n\r\n\r\nx_text, y = load_data_and_labels(config.data_source, config.label_source)\r\ny = np.array(y)\r\n\r\n\r\n\r\ntime_str = datetime.datetime.now().isoformat()\r\nprint(time_str)\r\n\r\nlength = 1000\r\n\r\na = np.zeros(shape=(len(y),length))\r\nb = []\r\n\r\nW2V = {}\r\n\r\nW2V_file = csv.reader(open(\".\\data\\gaozhong\\gaozhong_english\\W2V.csv\",\"r\",encoding = \"utf-8\"))\r\n\r\nh = 1\r\nfor stu in W2V_file:\r\n W2V[stu[1]] = stu[2]\r\n# if h % 1000 == 0 :\r\n# print(stu[1])\r\n# print(stu[2])\r\n h += 1\r\n\r\nm = 0\r\nfor x in x_text:\r\n if m % 1000 == 1:\r\n print(m)\r\n li = x.split(\" \")\r\n k = 0\r\n for i in li:\r\n# print(i)\r\n if k == length-1 :\r\n break\r\n i = i.encode('utf-8').decode('utf-8-sig')\r\n b = W2V[i].split(\",\")\r\n b = [ float(x) for x in b ]\r\n a[m][k] = np.mean(b)\r\n k += 1 \r\n m += 1\r\n\r\n\r\n\r\nprint(a.shape)\r\nprint(\"a\")\r\n\r\n# Randomly shuffle data\r\nnp.random.seed(10) # 使得随机数列可预测\r\n# 产生一个array:起始点0,结束点len(y),步长1。然后将其打乱。\r\nshuffle_indices = np.random.permutation(np.arange(len(a))) \r\nx_shuffled = a[shuffle_indices] # 将文件句子和标签以同样的方式打乱\r\ny_shuffled = y[shuffle_indices]\r\n\r\n\r\n# Split train/test set\r\n#直接把dev_sample_index前用于训练,dev_sample_index后的用于训练;\r\ndev_sample_index = -1 * int(0.1 * float(len(y))) # -1:代表从后往前取\r\nx_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\r\ny_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\r\n\r\ntime_str = datetime.datetime.now().isoformat()\r\nprint(time_str)\r\n\r\nTP=0 \r\nTN=0\r\nFP=0\r\nFN=0\r\n\r\nprint(x_train.shape)\r\nprint(x_dev.shape)\r\nprint(y_train)\r\nprint(y_dev)\r\n \r\nclf = OneVsRestClassifier(LinearSVC())\r\n\r\n \r\nx_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\r\ny_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\r\n\r\nprint(\"开始训练模型\")\r\n\r\n\r\nclf = clf.fit(x_train, y_train)\r\ntest_predictions = clf.predict(x_dev)\r\n\r\n#print(\"测试集准确率: %s \" % accuracy_score(y_dev, test_predictions))\r\n\r\nprint(test_predictions[0])\r\nprint(test_predictions)\r\nprint(len(test_predictions[0]))\r\n\r\ntime_str = datetime.datetime.now().isoformat()\r\nprint(time_str)\r\n\r\n\r\nprint(\"开始评价\")\r\n\r\n# =============================================================================\r\n# \r\n# writeFile2 = open('.\\\\data\\\\gaozhong\\\\gaozhong_english\\\\test_data_english_eval.csv','a+', newline='') # 设置newline,否则两行之间会空一行\r\n# writer2 = csv.writer(writeFile2)\r\n# writer2.writerow(scores[0])\r\n# writeFile2.close()\r\n# \r\n# =============================================================================\r\n\r\npre, rec, pre_2, rec_2, pre_3, rec_3 = precision_recall(test_predictions, y_dev)\r\n\r\nprint(\"pre_1 {}, rec_1 {:g}\".format(pre, rec))\r\nprint(\"pre_2 {}, rec_2 {:g}\".format(pre_2, rec_2))\r\nprint(\"pre_3 {}, rec_3 {:g}\".format(pre_3, rec_3)) \r\n\r\n\r\nwriteFile2 = open('.\\\\data\\\\gaozhong\\\\gaozhong_english\\\\dev_data_english_eval.csv','a+', newline='') # 设置newline,否则两行之间会空一行\r\nwriter2 = csv.writer(writeFile2)\r\nwriter2.writerow([h, pre, rec, pre_2, rec_2, pre_3, rec_3])\r\nwriteFile2.close()\r\n\r\n# =============================================================================\r\n# \r\n# conf_mat = confusion_matrix(test_predictions, y_dev)\r\n# fig, ax = plt.subplots(figsize=(8,6))\r\n# sns.heatmap(conf_mat, annot=True, fmt='d')\r\n# plt.ylabel('Actual')\r\n# plt.xlabel('Predicted')\r\n# plt.show()\r\n# =============================================================================\r\n","sub_path":"text_classification_gaozhong_english/SVM/train_HAN.py","file_name":"train_HAN.py","file_ext":"py","file_size_in_byte":6882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"588912664","text":"#!/usr/bin/python3\n# Creator: Andrew De La Fuente And Paul Smith\n# Assignment: Project #3\n# Date: December 05, 2018\n\nimport datetime\nimport uuid\nimport os\nfrom flask_basicauth import BasicAuth\nfrom flask import Flask, g, jsonify, request, current_app\nfrom flask_cassandra import CassandraCluster\nfrom cassandra.query import dict_factory\n\nclass my_BasicAuth(BasicAuth):\n \"\"\" Class to overide the check_credentials method from the BacisAuth class\"\"\"\n\n def check_credentials(self, given_name, given_password):\n \"\"\"\" Checks a database to see if the given credentials match what \n was given by the user.\n\n Args:\n given_name(string): first given parameter\n given_password(string): second given parameter\n Returns:\n bool: The return value. True for success, False otherwise.\"\"\"\n session = get_db()\n user_lookup_stmt = session.prepare(\"SELECT password FROM users WHERE username=?\")\n rows = session.execute(user_lookup_stmt, [given_name])\n # May change later?\n auth = False\n if rows:\n if rows[0]['password'] == given_password:\n app.config['BASIC_AUTH_USERNAME'] = given_name\n auth = True\n return auth\n\n\napp = Flask(__name__)\nbasic_auth = my_BasicAuth(app)\ncassandra = CassandraCluster()\napp.config['CASSANDRA_NODES'] = ['172.17.0.2']\n\ndef get_db():\n session = cassandra.connect()\n session.set_keyspace(\"web_api\")\n session.row_factory = dict_factory\n return session\n\n\n@app.route(\"/create_DB\")\ndef cassandra_test():\n session = cassandra.connect()\n start = []\n cql1 = \"DROP KEYSPACE IF EXISTS web_api\"\n session.execute(cql1)\n cql2 = \"DROP TABLE IF EXISTS users\"\n start.append(cql2)\n cql3 = \"DROP TABLE IF EXISTS forums\"\n start.append(cql3)\n cql4 = \"DROP TABLE IF EXISTS posts\"\n start.append(cql4)\n cql5 = \"CREATE KEYSPACE web_api WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};\"\n session.execute(cql5)\n cql6 = \"CREATE TYPE IF NOT EXISTS thread (threadNumber uuid, title text, creator text, threadTime timestamp)\"\n start.append(cql6)\n cql7 = \"CREATE TYPE IF NOT EXISTS post (author text, postText text, postTime timestamp)\"\n start.append(cql7)\n cql8 = \"CREATE TABLE users (username text PRIMARY KEY,password text)\"\n start.append(cql8)\n cql9 = \"CREATE TABLE forums (forumId uuid PRIMARY KEY, forumName text, creator text, allThreads list>)\"\n start.append(cql9)\n cql10 = \"CREATE TABLE posts (threadNumber uuid PRIMARY KEY, title text, creator text, threadTime timestamp, allPosts list>)\"\n start.append(cql10)\n cql11 = \"INSERT INTO users (username, password) VALUES ('Paul', '1234')\"\n start.append(cql11)\n\n session.set_keyspace('web_api')\n for x in start:\n session.execute(x)\n response = jsonify()\n return response\n\n@app.teardown_appcontext\ndef teardown_db(exception):\n db = g.pop('db', None)\n if db is not None:\n db.close()\n\n\n@app.route(\"/forums\", methods=['GET'])\ndef get_forums():\n # http GET localhost:5000/forums\n \"\"\"Method that takes HTTP GET request for the page '/forums' and returns all \n forums from the database.\n\n Returns:\n All of the forums. Results are returned in the format of the \n dict_factory() function and are then returned in JSON format\n \"\"\"\n session = get_db()\n rows = session.execute('SELECT forumId, forumName, creator FROM forums')\n results = []\n for row in rows:\n results.append(row)\n return jsonify(results)\n\n\n@app.route(\"/forums\", methods=['POST'])\n@basic_auth.required\ndef post_forums():\n # http POST localhost:5000/forums name=\"SQL\" --auth Paul:1234\n \"\"\"Method that takes HTTP POST request for the page '/forums' and if \n authenticated creates a post with the information from the HTTP post.\n\n Returns: \n JSON response . If the forums does not already exists, the \n responce is 201 and the header location is changed to the the \n new forum. If the forum already exists than the 409 reponce is \n sent. \n \"\"\"\n data = request.get_json()\n name = data.get('name')\n creator = app.config['BASIC_AUTH_USERNAME']\n session = get_db()\n response = jsonify()\n id_ = uuid.uuid4()\n rows = session.execute('SELECT forumName FROM forums')\n for row in rows:\n if row['forumname'] == name:\n response.status_code = 409\n return response\n session.execute(\"INSERT INTO forums (forumId, forumName,creator) VALUES (%s, %s,%s)\", (id_, name, creator))\n response.status_code = 201\n response.headers['location'] = \"/forums/{}\".format(id_)\n return response\n\n\n@app.route(\"/forums/\", methods=['GET'])\ndef get_forums_id(forum_id):\n # http GET localhost:5000/forums/1\n \"\"\"Method that takes HTTP GET request for the page '/forums/' and returns all \n forums from the database.\n\n Returns:\n All of the forums with deafault 202 status code. Results are returned in the \n format of the dict_factory() function and are then returned in JSON format. If the forum\n ID number does not exist than a 404 status code is returned in JSON format.\n \"\"\"\n session = get_db()\n thread_lookup_stmt = session.prepare(\"SELECT allThreads FROM forums WHERE forumId=?\")\n rows = session.execute(thread_lookup_stmt, [forum_id])\n if not rows[0]['allthreads'] == None:\n results = []\n for row in rows[0]['allthreads']:\n if row:\n tmp = {'threadNumber' : row[0] , 'title' : row[1], 'creator' : row[2], 'threadTime' : row[3]}\n results.append(tmp)\n results.reverse()\n return jsonify(results)\n else:\n response = jsonify()\n response.status_code = 404\n return response\n\n\n@app.route(\"/forums/\", methods=['POST'])\n@basic_auth.required\ndef post_thread(forum_id):\n #(threadNumber uuid, title text, creator text, threadTime timestamp)\"\n #(author text, postText text, postTime timestamp)\n # http POST localhost:5000/forums/ac4bb49f-1f6a-44dd-bf18-08bb5a412dd9 title=\"What is R\" text=\"What type of language is R?\" --auth Paul:1234\n \"\"\"Method that takes HTTP POST request for the page '/forums/'\n and if authenticated creates a new forum and first post with the\n information from the HTTP POST.\n\n Returns: \n JSON response. If the forum number exists the responce is 201 and\n the header location is changed to the new thread. If the forum\n does not exist than the 404 response is sent. \n \"\"\"\n data = request.get_json()\n title_ = data.get('title')\n text = data.get('text')\n creator_ = app.config['BASIC_AUTH_USERNAME']\n\n\n session = get_db()\n response = jsonify()\n\n thread_lookup_stmt = session.prepare(\"SELECT allThreads FROM forums WHERE forumId=?\")\n rows = session.execute(thread_lookup_stmt, [forum_id])\n try:\n check = rows[0]\n forum_check = True\n except:\n forum_check = False\n if forum_check:\n id_ = uuid.uuid4()\n time_ = datetime.datetime.now()\n insert_stmt = session.prepare(\"UPDATE forums SET allThreads = allThreads + ? WHERE forumId = ?\")\n session.execute(insert_stmt, [[(id_,title_,creator_, time_)], forum_id])\n thread_id = id_\n dateTime = time_\n insert_stmt = session.prepare(\"INSERT INTO posts(threadNumber, title, creator, threadTime, allPosts) VALUES(?,?,?,?,?)\")\n session.execute(insert_stmt, [thread_id,title_,creator_, dateTime, [(creator_, text, dateTime)] ])\n\n response.headers['location'] = \"/forums/{}/{}\".format(forum_id, thread_id)\n response.status_code = 201\n else:\n response.status_code = 404\n return response\n\n\n@app.route(\"/forums//\", methods=['GET'])\ndef get_threads(forum_id, thread_id):\n # http GET localhost:5000/forums/1/1 --auth paul:12345\n \"\"\"Method that takes HTTP GET request for the page '/forums//'\n and returns all posts, from a specific thread, from the database.\n\n Returns:\n All of the forums with deafault 202 status code. Results are returned in the \n format of the dict_factory() function and are then returned in JSON format. If the forum\n ID number does not exist than a 404 status code is returned in JSON format.\n \"\"\"\n session = get_db()\n\n forum_check_stmt = session.prepare('SELECT forumId FROM forums WHERE forumId =?')\n rows = session.execute(forum_check_stmt, [forum_id])\n\n forum_check = False\n for row in rows:\n if row['forumid'] == forum_id:\n forum_check = True\n if forum_check:\n thread_lookup_stmt = session.prepare(\"SELECT allPosts FROM posts WHERE threadNumber =?\")\n rows = session.execute(thread_lookup_stmt, [thread_id])\n if rows:\n results = []\n for row in rows[0]['allposts']:\n if row:\n tmp = {'author' : row[0] , 'postText' : row[1], 'postTime' : row[2]}\n results.append(tmp)\n return jsonify(results)\n else:\n response = jsonify()\n response.status_code = 404\n return response\n else:\n response = jsonify()\n response.status_code = 404\n return response\n\n\n@app.route(\"/forums//\", methods=['POST'])\n@basic_auth.required\ndef post_threads(forum_id, thread_id):\n # http POST localhost:5000/forums/ac4bb49f-1f6a-44dd-bf18-08bb5a412dd9/d90a20c7-2098-4c0b-b9d9-4fd85944eff7 text=\"Google it\" --auth Paul:1234\n \"\"\"Method that takes HTTP POST request for the page \n '/forums//' and if authenticated creates\n a post with the information from the HTTP POST.\n\n Returns: \n JSON response. If the forum number exists the responce is 201 and\n the header location is changed to the new thread. If the forum\n does not exist than the 404 response is sent. \n \"\"\"\n data = request.get_json()\n text = data.get('text')\n author = app.config['BASIC_AUTH_USERNAME']\n time_ = datetime.datetime.now()\n response = jsonify()\n\n\n session = get_db()\n forum_check_stmt = session.prepare('SELECT * FROM forums WHERE forumId =?')\n rows1 = session.execute(forum_check_stmt, [forum_id])\n forum_check = False\n for row in rows1:\n if row['forumid'] == forum_id:\n forum_check = True\n if forum_check:\n thread_lookup_stmt = session.prepare(\"SELECT allPosts FROM posts WHERE threadNumber =?\")\n rows2 = session.execute(thread_lookup_stmt, [thread_id])\n\n if not rows2[0]['allposts'] == None:\n for row in rows2:\n if row:\n insert_stmt = session.prepare(\"UPDATE posts SET allPosts = allPosts + ? WHERE threadNumber = ?\")\n session.execute(insert_stmt, [[(author, text, time_)], thread_id])\n response.headers['location'] = \"/forums/{}/{}\".format(forum_id, thread_id)\n\n thread_lookup_stmt = session.prepare(\"SELECT allThreads FROM forums WHERE forumId=?\")\n rows = session.execute(thread_lookup_stmt, [forum_id])\n for row in rows[0]['allthreads']:\n if row[0] == thread_id:\n old_thread = row\n break\n insert_stmt = session.prepare(\"UPDATE forums SET allThreads = allThreads - ? WHERE forumId = ?\")\n session.execute(insert_stmt, [[(old_thread)], forum_id])\n insert_stmt = session.prepare(\"UPDATE forums SET allThreads = allThreads + ? WHERE forumId = ?\")\n session.execute(insert_stmt, [[(old_thread[0],old_thread[1],old_thread[2], time_)], forum_id])\n response.status_code = 201\n return response\n else:\n response.status_code = 404\n return response\n else:\n response.status_code = 404\n return response\n\n\n@app.route(\"/users\", methods=['POST'])\ndef post_users():\n # http POST localhost:5000/users username=\"paul\" password=\"12345\"\n \"\"\"Method that takes HTTP POST request for the page '/users' and \n creates a new user with the information from the HTTP post.\n\n Returns: \n JSON response . If the user does not already exists, the \n responce is 201. If the user already exists than the 409\n response is sent. \n \"\"\"\n data = request.get_json()\n given_name = data.get('username')\n given_password = data.get('password')\n session = get_db()\n response = jsonify()\n\n rows = session.execute('SELECT username FROM users')\n for row in rows:\n if row['username'] == given_name:\n response.status_code = 409\n return response\n session.execute(\"INSERT INTO users (username, password) VALUES (%s,%s)\", (given_name, given_password))\n response.status_code = 201\n return response\n\n\n@app.route(\"/users/\", methods=['PUT'])\n@basic_auth.required\ndef put_users(user_name):\n # http PUT localhost:5000/users/paul username=\"Paul\" password=\"54321\" --auth Paul:12345\n \"\"\"Method that takes HTTP PUT request for the page '/users/' and \n if authenticated updates the users password.\n\n Returns: \n JSON response . If the user exists already and \n the user is authenticated, the responce is 201. If the\n user does not exist than the 404 response is sent. If the\n user is authenticated but is trying to update another users\n password than the 409 responce code is given.\n \"\"\"\n data = request.get_json()\n given_name = data.get('username')\n given_password = data.get('password')\n session = get_db()\n response = jsonify()\n name_exist = False\n rows = session.execute('SELECT username FROM users')\n for row in rows:\n if row['username'] == given_name:\n name_exist = True\n\n if name_exist:\n # Checks to see if the user is authenticated for the usernam/password they are trying to change\n if user_name == given_name and app.config['BASIC_AUTH_USERNAME'] == given_name:\n session.execute(\"INSERT INTO users (username, password) VALUES (%s,%s)\", (given_name, given_password))\n response.status_code = 201\n else:\n response.status_code = 409\n else:\n response.status_code = 404\n return response\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n\n","sub_path":"web_service_api.py","file_name":"web_service_api.py","file_ext":"py","file_size_in_byte":14825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"382861543","text":"# Copyright (c) 2015 Prabhu Gurumurthy \n\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nimport os\nimport yaml\n\nfrom pyparsing import alphas, alphanums, delimitedList, oneOf, Literal\nfrom pyparsing import Keyword, OneOrMore, Word, White, ParseFatalException\nfrom pyparsing import ParseException, LineEnd, pythonStyleComment\nfrom pyparsing import cppStyleComment, StringEnd, ZeroOrMore, Combine\nfrom pyparsing import Group\nfrom yaml.parser import ParserError as YAMLParserError\nfrom yaml.scanner import ScannerError as YAMLScannerError\n\nfrom exception import XMLCreateError, ParserError\nfrom ncconf import Configure\nfrom ncxml import xmlcreate, XMLCreate\nfrom netconf import validate_action, NetConfCommand\n\nclass FileParser(object):\n def __init__(self):\n super(FileParser, self).__init__()\n self._spaceChars = ' \\t'\n self._space = Word(self._spaceChars, exact = 1)\n\n def __call__(self, handle):\n device = oneOf(\"device dev\").suppress()\n do = oneOf(\"do then\").suppress()\n end = oneOf(\"end done\").suppress()\n interface = oneOf(\"interfaces interface int if\")\n ident = Word(alphas + alphanums + \"/-_.\")\n scolon = Literal(\";\").suppress()\n\n action = oneOf(\"delete create disable enable down up add shut noshut\\\n dis en del shutdown noshutdown +\") + LineEnd()\n # ifList = Keyword(\"set\").suppress() + interface + OneOrMore(\n # ident) + action\n ifList = Keyword(\"set\").suppress() + interface + delimitedList(\n ident, delim = White(r\" \", exact = 1)) + action \n term = device + ident + scolon + do + ifList + end + LineEnd()\n term.ignore(Literal(\"\\\\\") + LineEnd())\n term.ignore(pythonStyleComment)\n term.ignore(cppStyleComment)\n\n results = None\n try:\n results = term.parseString(handle.read())\n except ParseFatalException as error:\n raise ParserError(error)\n except ParseException as error:\n print(error)\n raise ParserError(\"syntax error on line %d \\\"%s\\\"\" %(\n error.lineno, error.line.strip()))\n else:\n print(results)\n\nclass Parser(NetConfCommand):\n def __init__(self, **kwargs):\n super(Parser, self).__init__(**kwargs)\n self._filename = None\n self._fh = None\n self._new = False\n self._yaml = False\n\n if kwargs[\"yaml\"]:\n self._yaml = kwargs[\"yaml\"]\n\n if kwargs[\"new\"]:\n self._new = kwargs[\"new\"]\n\n if \"filename\" in kwargs:\n self._filename = kwargs[\"filename\"]\n\n if self._yaml and self._device:\n self.error(\"cannot define a yaml file and device\")\n\n if self._yaml is False and self._device is None:\n self.error(\"target device is NOT defined\")\n\n def error(self, strformat, *args):\n if self._fh:\n self._fh.close()\n\n super(Parser, self).error(strformat, *args)\n\n def __call__(self, *args):\n if self._filename:\n if not os.path.exists(self._filename):\n self.error(\"filename %s does NOT exist\", self._filename)\n\n with open(self._filename, \"r\") as self._fh:\n if self._yaml is False:\n self.fileparse()\n else:\n self.yamlparse()\n else:\n print(\"call\", args)\n\n def fileparse(self):\n if self._new:\n try:\n parser = FileParser()\n parser(self._fh)\n except ParserError as error:\n self.error(\"%s in file %s\", error, self._filename)\n else:\n for line in self._fh.readlines():\n line = line.strip()\n print(line)\n\n def yamlparse(self):\n config = None\n try:\n config = yaml.load(self._fh.read())\n except YAMLParserError as err:\n self.error(str(err))\n except YAMLScannerError as err:\n self.error(str(err))\n","sub_path":"core/lib/ncparse.py","file_name":"ncparse.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521626207","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom typing import *\nfrom collections import OrderedDict, defaultdict\nfrom api.misc.dict2instance import Dict2InstanceDeSer, get_object_map_deser, get_object_list_deser, DeSer\nfrom api.models.repr.location import Location\nfrom api.models.repr.alignments import AlignmentDeSer, AlignmentEnum, ValueAlignment, DimAlignment\nfrom api.models.repr.ext_resource import ExtResource\nfrom api.models.repr.preprocessing import PreprocessingDeSer, PreprocessingFunc, PMap, PFilter\nfrom api.models.repr.resources import ResourceDeSer, ResourceEnum, CSVResource, JSONResource\nfrom api.models.repr.semantic_model import SemanticModel, Relation, DataNode, LiteralNode\nfrom api.models.repr.variables import Variable\nfrom drepr import DRepr, models\n\nif TYPE_CHECKING:\n from api.models.resource import Resource\n\n\nclass Representation(Dict2InstanceDeSer):\n \"\"\"An extension of the representation in order to keep track of resources\"\"\"\n class_properties = {\n \"ext_resources\": get_object_map_deser(\"ext_resources\", ExtResource),\n \"resources\": get_object_map_deser(\"resources\", ResourceDeSer),\n \"preprocessing\": get_object_list_deser(\"preprocessing\", PreprocessingDeSer),\n \"variables\": get_object_map_deser(\"variables\", Variable),\n \"alignments\": get_object_list_deser(\"alignments\", AlignmentDeSer),\n \"semantic_model\": SemanticModel\n }\n\n def __init__(self, ext_resources: Dict[str, ExtResource], resources: Dict[str, ResourceEnum],\n preprocessing: List[PreprocessingFunc], variables: Dict[str, Variable],\n alignments: List[AlignmentEnum], semantic_model: SemanticModel):\n self.resources = resources\n self.preprocessing = preprocessing\n self.variables = variables\n self.alignments = alignments\n self.semantic_model = semantic_model\n self.ext_resources = ext_resources\n\n @staticmethod\n def default():\n return Representation({}, {}, [], {}, [], SemanticModel.default())\n\n @staticmethod\n def from_repr(ds_model: DRepr, ext_resources: Dict[str, ExtResource]):\n repr = Representation(ext_resources, {}, [], {}, [], SemanticModel.default())\n\n for res in ds_model.resources:\n if res.type == models.ResourceType.CSV:\n repr.resources[res.id] = CSVResource(\n res.id, res.prop.delimiter if res.prop.delimiter is not None else None)\n elif res.type == models.ResourceType.JSON:\n repr.resources[res.id] = JSONResource(res.id)\n else:\n raise NotImplementedError()\n\n for prepro in ds_model.preprocessing:\n if prepro.type == models.PreprocessingType.pmap:\n repr.preprocessing.append(\n PMap(\n Location.from_path(prepro.value.resource_id, prepro.value.path),\n prepro.value.output, prepro.value.code))\n elif prepro.type == models.PreprocessingType.pfilter:\n repr.preprocessing.append(\n PFilter(\n Location.from_path(prepro.value.resource_id, prepro.value.path),\n prepro.value.output, prepro.value.code))\n else:\n raise NotImplementedError()\n\n for attr in ds_model.attrs:\n repr.variables[attr.id] = Variable(attr.id,\n Location.from_path(attr.resource_id,\n attr.path), attr.unique,\n attr.sorted.value, attr.value_type.value,\n set(attr.missing_values))\n\n for align in ds_model.aligns:\n if isinstance(align, models.RangeAlignment):\n repr.alignments.append(\n DimAlignment(align.source, align.target, [{\n \"source\": ad.source_idx,\n \"target\": ad.target_idx\n } for ad in align.aligned_steps]))\n elif isinstance(align, models.ValueAlignment):\n repr.alignments.append(ValueAlignment(align.source, align.target))\n else:\n raise NotImplementedError()\n\n repr.semantic_model.prefixes = ds_model.sm.prefixes\n # for generating class id in the semantic model\n class_ids = defaultdict(lambda: {})\n\n for edge in ds_model.sm.edges:\n source = ds_model.sm.nodes[edge.source_id]\n target = ds_model.sm.nodes[edge.target_id]\n\n if isinstance(source, models.ClassNode):\n if source.node_id not in class_ids[source.label]:\n class_ids[source.label][\n source.node_id] = f\"{source.label}:{len(class_ids[source.label])}\"\n\n source_id = class_ids[source.label][source.node_id]\n if isinstance(target, models.ClassNode):\n if target.node_id not in class_ids[target.label]:\n class_ids[target.label][\n target.node_id] = f\"{target.label}:{len(class_ids[target.label])}\"\n\n target_id = class_ids[target.label][target.node_id]\n repr.semantic_model.relations.append(Relation(source_id, edge.label, target_id))\n elif isinstance(target, models.DataNode):\n repr.semantic_model.data_nodes[target.attr_id] = DataNode(\n source_id, source.label, edge.label,\n target.data_type.value if target.data_type is not None else None)\n elif isinstance(target, models.LiteralNode):\n repr.semantic_model.literal_nodes.append(\n LiteralNode(\n source_id, source.label, edge.label, target.value,\n target.data_type.value if target.data_type is not None else None))\n else:\n raise NotImplementedError()\n else:\n assert False\n return repr\n\n @staticmethod\n def to_repr(wrepr: dict) -> DRepr:\n repr: Representation = Representation.deserialize(wrepr)\n ds_model = DRepr.empty()\n\n for res in repr.resources.values():\n if isinstance(res, CSVResource):\n ds_model.resources.append(\n models.Resource(res.id, models.ResourceType.CSV, models.CSVProp(res.delimiter)))\n elif isinstance(res, JSONResource):\n ds_model.resources.append(models.Resource(res.id, models.ResourceType.JSON, None))\n else:\n raise NotImplementedError()\n\n for prepro in repr.preprocessing:\n if isinstance(prepro, PMap):\n ds_model.preprocessing.append(models.Preprocessing(\n models.PreprocessingType.pmap,\n models.PMap(prepro.input.resource_id, prepro.input.get_path(),\n prepro.code, prepro.output, None)\n ))\n elif isinstance(prepro, PFilter):\n ds_model.preprocessing.append(models.Preprocessing(\n models.PreprocessingType.pfilter,\n models.PFilter(\n prepro.input.resource_id, prepro.input.get_path(),\n prepro.code, prepro.output\n )))\n else:\n raise NotImplementedError()\n\n for attr in repr.variables.values():\n ds_model.attrs.append(models.Attr(\n attr.id, attr.location.resource_id,\n attr.location.get_path(), list(attr.missing_values),\n attr.unique, models.Sorted(attr.sorted), models.ValueType(attr.value_type)\n ))\n\n for align in repr.alignments:\n if isinstance(align, DimAlignment):\n ds_model.aligns.append(models.RangeAlignment(align.source, align.target, [\n models.AlignedStep(s['source'], s['target'])\n for s in align.aligned_dims\n ]))\n elif isinstance(align, ValueAlignment):\n ds_model.aligns.append(models.ValueAlignment(align.source, align.target))\n else:\n raise NotImplementedError()\n\n for attr_id, node in repr.semantic_model.data_nodes.items():\n dnode_id = f\"dnode:{attr_id}\"\n ds_model.sm.nodes[dnode_id] = models.DataNode(\n dnode_id, attr_id,\n models.DataType(node.data_type) if node.data_type is not None else None)\n\n if node.node_id not in ds_model.sm.nodes:\n ds_model.sm.nodes[node.node_id] = models.ClassNode(node.node_id, node.class_uri)\n ds_model.sm.edges.append(models.Edge(node.node_id, dnode_id, node.predicate))\n\n for i, node in enumerate(repr.semantic_model.literal_nodes):\n lnode_id = f\"lnode:{i}\"\n ds_model.sm.nodes[lnode_id] = models.LiteralNode(\n lnode_id, node.data,\n models.DataType(node.data_type) if node.data_type is not None else None)\n\n if node.node_id not in ds_model.sm.nodes:\n ds_model.sm.nodes[node.node_id] = models.ClassNode(node.node_id, node.class_uri)\n ds_model.sm.edges.append(models.Edge(node.node_id, lnode_id, node.predicate))\n\n for rel in repr.semantic_model.relations:\n ds_model.sm.edges.append(models.Edge(rel.source_id, rel.target_id, rel.predicate))\n\n ds_model.sm.prefixes = repr.semantic_model.prefixes\n return ds_model\n\n @staticmethod\n def unsafe_get_resource_db_id(raw_wrepr: dict, resource_id: str) -> int:\n return raw_wrepr['ext_resources'][resource_id]['resource_db_id']\n\n def get_resource_db_id(self, resource_id: str) -> int:\n return self.ext_resources[resource_id].resource_db_id\n\n def add_resource(self, record: 'Resource'):\n self.ext_resources[record.resource_id] = ExtResource.from_resource(record)\n r = {'type': record.resource['type'], **record.resource}\n self.resources[record.resource_id] = ResourceDeSer.deserialize(r)\n\n def has_resource(self, resource_id: str):\n return resource_id in self.ext_resources\n\n def remove_resource(self, resource_id: str):\n self.ext_resources.pop(resource_id)\n self.resources.pop(resource_id)\n\n for vid in list(self.variables.keys()):\n var = self.variables[vid]\n if var.location.resource_id == resource_id:\n self.remove_variable(vid)\n\n def has_variable(self, variable_id: str):\n return variable_id in self.variables\n\n def add_variable(self, variable: Variable):\n self.variables[variable.id] = variable\n\n def remove_variable(self, variable_id: str):\n self.variables.pop(variable_id)\n for i in range(len(self.alignments) - 1, -1, -1):\n align = self.alignments[i]\n if variable_id == align.source or variable_id == align.target:\n self.alignments.pop(i)\n\n if variable_id in self.semantic_model.data_nodes:\n self.semantic_model.remove_data_node(variable_id)\n\n def replace_variable(self, prev_var_id: str, var: Variable):\n self.variables.pop(prev_var_id)\n self.variables[var.id] = var\n\n for align in self.alignments:\n if prev_var_id == align.source:\n align.source = var.id\n elif prev_var_id == align.target:\n align.target = var.id\n\n if prev_var_id in self.semantic_model.data_nodes:\n self.semantic_model.data_nodes[prev_var_id] = self.semantic_model.data_nodes.pop(\n prev_var_id)\n\n def set_alignments(self, alignments: List[AlignmentEnum]):\n self.alignments = alignments\n\n def set_semantic_model(self, sm: SemanticModel):\n self.semantic_model = sm\n","sub_path":"www/api/models/repr/representation.py","file_name":"representation.py","file_ext":"py","file_size_in_byte":11955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476178519","text":"'''\nMake an IMF\nSam Geen, March 2016\n'''\n\nimport random\nimport numpy as np\n\nimport pickle as pik\nimport os, glob\n\nimport customplot\nimport matplotlib.pyplot as plt\n\ndef SampleIMF(Mcluster,seed=None):\n # Cravenly stolen from:\n # https://python4mpia.github.io/fitting_data/MC-sampling-from-Salpeter.html\n # Convert limits from M to logM.\n cachename = None\n if seed is not None:\n # Cache format \"caches/cache_mass_?????.dat\")\n mstr = str(int(Mcluster)).zfill(7)\n cachestr = str(seed).zfill(5)\n cachename = 'cache/imfs/imf_'+mstr+'_'+cachestr+'.dat' \n if os.path.exists(cachename):\n f = open(cachename,\"rb\")\n Mcluster = pik.load(f)\n masses = pik.load(f)\n f.close()\n return np.array(masses)\n print(\"Making IMF...\",)\n mMin = 1.0\n mMax = 120.0\n log_M_Min = np.log(mMin)\n log_M_Max = np.log(mMax)\n alpha = 2.35\n # Since Salpeter SMF decays, maximum likelihood occurs at M_min\n maxlik = mMin**(1.0 - alpha)\n # Prepare array for output masses.\n masses = []\n # Fill in array.\n lastM = 0.0\n while np.sum(masses) < Mcluster:\n # Draw candidate from logM interval.\n logM = random.uniform(log_M_Min,log_M_Max)\n M = np.exp(logM)\n lastM = M\n # Compute likelihood of candidate from Salpeter SMF.\n likelihood = M**(1.0 - alpha)\n # Accept randomly.\n u = random.uniform(0.0,maxlik)\n if (u < likelihood):\n masses.append(M)\n # Find closest answer to target mass\n if np.abs(np.sum(masses) - Mcluster) > \\\n np.abs(np.sum(masses) - M - Mcluster):\n masses.remove(M)\n masses.sort()\n # Save (if a seed is specified)\n if cachename is not None:\n f = open(cachename,\"wb\")\n pik.dump(Mcluster,f)\n pik.dump(masses,f)\n f.close()\n print(\"Done\")\n return np.array(masses)\n\ndef testplot(mcluster):\n masses = SampleIMF(mcluster)\n n = np.arange(0,len(masses))+1.0\n sample = np.arange(0,len(masses),10)\n sample = np.concatenate([sample,[len(masses)-1]])\n \n print(sample)\n dndm = np.diff(n) / np.diff(masses)\n mcent = 0.5*(masses[1:] + masses[:-1])\n sx = dndm\n hist,edges = np.histogram(masses,bins=masses[sample])\n ecent = 0.5*(edges[1:] + edges[:-1])\n x = []\n y = []\n for i in range(0,len(hist)):\n dx = edges[i+1] - edges[i]\n if dx == 0.0:\n dx = 1e-5\n hist[i] = 0.0\n x.append(edges[i])\n x.append(edges[i+1])\n y.append(hist[i]/dx)\n y.append(hist[i]/dx)\n plt.plot(mcent,dndm)\n plt.plot(x,y)\n plt.xlim([1.0,120.0])\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.xlabel(\"M / Msun\")\n plt.ylabel(\"dN/dM\")\n plt.savefig(\"testimf.pdf\")\n\nif __name__==\"__main__\":\n testplot(1e3)\n","sub_path":"WindInUV/makeimf.py","file_name":"makeimf.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"612507719","text":"from typing import *\nfrom .UtilText_Screen import UtilText_Screen\nfrom .UtilText_Component import UtilText_Component\n\n\nclass UtilText_Table(UtilText_Component):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\t# data\n\t\t# config\n\t\t# TODO: not yet completed: self._padding\n\t\t# self._padding:\t\tList[int] = [0, 0, 0, 0] # top, left, right, bottom\n\t\tself._separation:\tList[int] = [0, 1, 1, 0] # top, left, right, bottom\n\n\t\t# row info\n\t\tself._row_list:\tList[List[UtilText_Component]] = []\n\n\t\tself._col_length_list:\tList[int] = []\n\t\tself._row_length_list:\tList[int] = []\n\n\t\t# data\n\t\tself._data = {\n\t\t\t\"separation\": self._separation\n\t\t}\n\n\t\t# render\n\t\tself._buffer_table: UtilText_Screen = UtilText_Screen()\n\n\t\t# operation\n\t\tself.addChild(self)\n\n\tdef __del__(self):\n\t\treturn\n\n\t# Operation\n\t# column\n\tdef addRow(self, column_list: List[UtilText_Component]) -> bool:\n\t\t# row list\n\t\tself._row_list.append(column_list)\n\n\t\t# child / component list\n\t\tfor component in column_list:\n\t\t\tself.addChild(component)\n\n\t\treturn True\n\n\t# TODO: not yet completed\n\tdef rmRow(self, index: int) -> bool:\n\t\treturn False\n\n\t# TODO: not yet completed\n\tdef resetRow(self) -> bool:\n\t\treturn False\n\n\t# Protected\n\tdef _getContent_(self) -> List[List[str]]:\n\t\t# reset table\n\t\tself._buffer_table.reset()\n\t\tself._buffer_table.expand((0, 0), (self._size[0], self._size[1]))\n\n\t\t# draw line\n\t\t# horizontal line\n\t\t# currently only one horizontal line\n\t\tself._buffer_table.fill(\n\t\t\t(0, self._row_length_list[0] + self._separation[0] + self._separation[3]),\n\t\t\t(self._size[0], 1),\n\t\t\t'-'\n\t\t)\n\n\t\t# vertical line\n\t\tcumulative_x: int = 0\n\t\tfor index_col, col in enumerate(self._col_length_list):\n\n\t\t\tif index_col == len(self._col_length_list) - 1:\n\t\t\t\tcontinue\n\n\t\t\t# += separation - left\n\t\t\t# += width of this col\n\t\t\t# += separation - right\n\t\t\tcumulative_x += self._separation[1]\n\t\t\tcumulative_x += col\n\t\t\tcumulative_x += self._separation[2]\n\n\t\t\t# draw\n\t\t\tself._buffer_table.fill(\n\t\t\t\t(cumulative_x, 0),\n\t\t\t\t(1, self._size[1]),\n\t\t\t\t'|'\n\t\t\t)\n\n\t\t\t# vertical line\n\t\t\tcumulative_x += 1\n\n\t\t# intersection\n\t\t# currently only one horizontal line\n\t\tcumulative_x: int = 0\n\t\tfor index_col, col in enumerate(self._col_length_list):\n\n\t\t\tif index_col == len(self._col_length_list) - 1:\n\t\t\t\tcontinue\n\n\t\t\t# += separation - left\n\t\t\t# += width of this col\n\t\t\t# += separation - right\n\t\t\tcumulative_x += self._separation[1]\n\t\t\tcumulative_x += col\n\t\t\tcumulative_x += self._separation[2]\n\n\t\t\t# draw\n\t\t\tself._buffer_table.fill(\n\t\t\t\t(cumulative_x, self._row_length_list[0] + self._separation[0] + self._separation[3]),\n\t\t\t\t(1, 1),\n\t\t\t\t'*'\n\t\t\t)\n\n\t\t\t# vertical line\n\t\t\tcumulative_x += 1\n\n\t\treturn self._buffer_table.getBuffer(is_copy=False)\n\n\tdef _updateBox_(self) -> None:\n\t\tself._updateLength_()\n\t\tself._updatePosition_()\n\t\tself._updateSize_()\n\n\tdef _updateLength_(self) -> None:\n\t\t# ----- grid -----\n\t\tgrid_h: int = 0\n\t\tgrid_w: int = 0\n\n\t\t# height\n\t\tgrid_h = len(self._row_list)\n\n\t\t# width\n\t\tfor row in self._row_list:\n\t\t\tgrid_w = max(grid_w, len(row))\n\n\t\t# ----- length list -----\n\t\t# first get the max row length and column length\n\t\t# row length: max height of each row\n\t\t# col length: max width of each row\n\t\tself._col_length_list.clear()\n\t\tself._row_length_list.clear()\n\n\t\tself._col_length_list = [0 for _ in range(grid_w)]\n\t\tself._row_length_list = [0 for _ in range(grid_h)]\n\n\t\t# foreach component in row_list\n\t\tfor index_row, row in enumerate(self._row_list):\n\t\t\tfor index_col, component in enumerate(row):\n\n\t\t\t\tself._col_length_list[index_col] = max(self._col_length_list[index_col], component.getSize()[0])\n\t\t\t\tself._row_length_list[index_row] = max(self._row_length_list[index_row], component.getSize()[1])\n\n\tdef _updatePosition_(self) -> None:\n\t\t# the first one is self (render the table line)\n\t\tindex: int = 1\n\n\t\t# foreach component in row_list\n\t\tcumulative_y: int = 0\n\t\tfor index_row, row in enumerate(self._row_list):\n\n\t\t\t# separation - top\n\t\t\tcumulative_y += self._separation[0]\n\n\t\t\tcumulative_x: int = 0\n\t\t\tfor index_col, component in enumerate(row):\n\t\t\t\t# separation - left\n\t\t\t\tcumulative_x += self._separation[1]\n\n\t\t\t\t# set position\n\t\t\t\tself._position_list[index] = (cumulative_x, cumulative_y)\n\n\t\t\t\t# += width of this col\n\t\t\t\t# += separation - right\n\t\t\t\t# += vertical line of the table\n\t\t\t\tcumulative_x += self._col_length_list[index_col]\n\t\t\t\tcumulative_x += self._separation[2]\n\t\t\t\tcumulative_x += 1\n\n\t\t\t\t# index of next item\n\t\t\t\tindex += 1\n\n\t\t\t# += height of this row\n\t\t\t# += separation - bottom\n\t\t\tcumulative_y += self._row_length_list[index_row]\n\t\t\tcumulative_y += self._separation[3]\n\n\t\t\t# there will be a horizontal line between first and second row\n\t\t\tif index_row == 0:\n\t\t\t\tcumulative_y += 1\n\n\tdef _updateSize_(self) -> None:\n\t\t# width\n\t\tself._size[0] = 0\n\t\tself._size[0] += sum(self._col_length_list)\n\t\tself._size[0] += max(0, len(self._col_length_list) - 1) * (self._separation[1] + self._separation[2] + 1)\n\t\tself._size[0] += self._separation[1] + self._separation[2]\n\n\t\t# height\n\t\tself._size[1] = 0\n\t\tself._size[1] += sum(self._row_length_list)\n\t\tself._size[1] += max(0, len(self._col_length_list) - 1) * (self._separation[0] + self._separation[3])\n\t\tself._size[1] += self._separation[0] + self._separation[3]\n\t\tself._size[1] += 1\n","sub_path":"Source/UtilText_Table.py","file_name":"UtilText_Table.py","file_ext":"py","file_size_in_byte":5190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"206668047","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nMatemática com Python\nUm Guia Prático\n\nGráficos - Formatação - Legenda\n\nExemplo 7.7\n\nAutor: Guilherme A. Barucke Marcondes\n\"\"\"\n\n# Importa função de elaboração de gráficos da biblioteca pylab.\n# Função plot para plotar o gráfico.\n# Função arange para definir as faixas de valores.\n# Funções legend para incluir legenda.\nfrom pylab import plot, arange, legend\n\n# Limpa a área de console para facilitar a visualização do resultado.\nprint ('\\n' * 100)\n\n# Define valores a serem plotados no gráfico.\nx = arange(0, 4, 0.5) # Faixa de valores para x.\ny = 2 * x\ny1 = 3 * y\ny2 = y ** 2\n\n# Exibe gráfico com várias sequências de pontos.\n# Gráfico com marcadores e linhas diferentes:\n# círculos e linha tracejada verdes\n# cruzes e linha pontilhada vermelhas\n# quadrados e linha tracejada pretos.\n# Inclui legenda. Os rótulos são associados na ordem em cada linha \"plot\".\nplot(x, y, 'g8--', label='Linha_1')\nplot(x, y1, 'r+:', label='Linha_2')\nplot(x, y2, 'bs--', label='Linha_3')\nlegend(loc=2) # Define posição da legenda.\n","sub_path":"matematica_com_python/Cap 7_Gráficos/Gráficos_Exemplo_7_7.py","file_name":"Gráficos_Exemplo_7_7.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"221917633","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 1 17:30:33 2017\n\n@author: Think\n\"\"\"\n\nclass Solution(object):\n def searchInsert(self, nums,target):\n l = 0\n r = len(nums) - 1\n if target < nums[0]:\n return 0\n if target > nums[r]:\n return r+1\n while l<=r:\n m = (l+r) //2\n if nums[m] == target:\n return m\n elif nums[m] < target:\n l = m + 1\n if l target:\n return l\n else:\n return len(nums)\n elif nums[m] > target:\n r = m - 1\n if r >= 0:\n if nums[r] < target:\n return r + 1\n else:\n return 0\n\nif __name__ == '__main__':\n nums = [2,7,11,15]\n target = 18\n result = Solution().searchInsert(nums,target)\n print(result)","sub_path":"35. Search Insert Position.py","file_name":"35. Search Insert Position.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"91990467","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^p/(?P.*)', 'main.views.landing_page.landing_page'),\n url(r'^hp/', 'main.views.honeypot.honeypot'),\n\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"cloaker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"75644026","text":"#!/usr/bin/env python3\n\nfrom transmorph.datasets import load_test_datasets_small\nfrom transmorph.engine.matching import OT\nfrom transmorph.stats import edge_accuracy\n\n\ndef test_matching_ot_accuracy():\n # Tests matching quality of OT matching on small controlled dataset\n datasets = load_test_datasets_small()\n src, ref = datasets[\"src\"], datasets[\"ref\"]\n scores = [0.8, 0.8, 0.5, 0.9]\n for i, solver in enumerate([\"emd\", \"sinkhorn\", \"partial\", \"unbalanced\"]):\n kwargs = {}\n if solver == \"partial\":\n kwargs[\"partial_transport_mass\"] = 0.5\n mt = OT(solver=solver, **kwargs)\n results = mt.fit([src.X, ref.X])\n T = results[0, 1]\n accuracy = edge_accuracy(src, ref, T, \"class\")\n assert accuracy >= scores[i]\n\n\nif __name__ == \"__main__\":\n test_matching_ot_accuracy()\n","sub_path":"tests/engine/matching/test_ot.py","file_name":"test_ot.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"205904522","text":"import csv\nimport os\nimport sys\nimport subprocess\nimport shutil\nimport matplotlib.pyplot as plt\n\nnew_path = os.path.join(\"./\", \"LGTM_Results\")\nif not os.path.exists(new_path):\n os.mkdir(new_path)\nelse:\n shutil.rmtree(new_path)\n os.mkdir(new_path)\ncreate = \"../Tools/LGTM/codeql/codeql database create --language=javascript --source-root {} {}\"\nupgrade = \"../Tools/LGTM/codeql/codeql database upgrade {}\"\nrunQuery = \"../Tools/LGTM/codeql/codeql database analyze ./LGTM_Results/benchmarkDB ../Tools/LGTM/ql/javascript/ql/src/OSC_CodeQueries/customCodeInjection2.ql --format=csv --output=./LGTM_Results/customCodeInjection2results.csv\"\nprint(\"Creating CodeQL Database\")\noutputCreate = subprocess.check_output(create.format(\"./\", \"./LGTM_Results/benchmarkDB\"), stderr=subprocess.STDOUT, shell=True).decode().split(\"\\n\")\nprint(\"Upgrading CodeQL Database\")\noutputUpgrade = subprocess.check_output(upgrade.format(\"./LGTM_Results/benchmarkDB\"), stderr=subprocess.STDOUT, shell=True).decode().split(\"\\n\")\nprint(\"Running Query(ies)\")\noutputRunQueries = subprocess.check_output(runQuery, stderr=subprocess.STDOUT, shell=True).decode().split(\"\\n\")\n\ndef makeGraph(fpr=0, tpr=0, title=\"Scorecard Graph\"):\n x = fpr\n y = tpr\n plt.plot(x, y, marker='o', markerfacecolor='red', markersize=12)\n plt.plot([0,1], [0,1], color='black', linestyle='dashed', linewidth = 3)\n plt.xlabel('false positive rate')\n plt.ylabel('true positive rate')\n plt.title(title)\n plt.savefig(title+'.png')\n\n\nprint(\"Creating scorecard\")\nbenchmarks = []\n#cwes = [94, 89, 78]\nmap = {\"Code injection\" : 94}\ntotal_TP = 0\ntotal_FN = 0\ntotal_TN = 0\ntotal_FP = 0\ntotal_total = 0\n#print(benchmarks)\n\n# name of csv file\nfilename = \"scorecard.csv\"\n# writing to csv file\nwith open('customCodeInjection2 over benchmark'+'.csv', 'w') as csvfile:\n # creating a csv writer object\n csvwriter = csv.writer(csvfile)\n\n # writing the fields\n csvwriter.writerow(['CWE', 'TP', 'FN','TN','FP','Total', 'TPR', 'FPR', 'Score'])\n #print(benchmarks)\n for cwe in map:\n truepos = 0\n falsepos = 0\n trueneg = 0\n falseneg = 0\n total = 0\n with open('index.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV:\n #print(row)\n if ('File Name' not in row[0]):\n benchmarks.append(row)\n for row in benchmarks:\n row.append(\"FALSE\")\n try:\n with open('./LGTM_Results/customCodeInjection2results.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV:\n for line in benchmarks:\n if line[0] in row[4] and cwe in row[0]:\n #cwe_used = line[1]\n line[4] = \"TRUE\"\n if line[2] == \"TRUE\":\n truepos += 1\n else:\n falsepos += 1\n except IOError:\n print(\"'output.csv' file is found or is not accessible\")\n raise\n\n for line in benchmarks:\n if line[1] == str(map[cwe]):\n if line[4] == \"FALSE\" and line[2] == \"TRUE\":\n falseneg += 1\n else:\n pass\n else:\n trueneg += 1\n total = truepos + trueneg + falsepos + falseneg\n tpr = truepos / (truepos+falseneg)\n fpr = falsepos / (falsepos + trueneg)\n score = tpr - fpr\n\n results = [str(map[cwe])+\":\"+cwe, truepos, falseneg, trueneg, falsepos, total, tpr, fpr, score]\n results = [str(i) for i in results]\n #print(results)\n\n total_TP += truepos\n total_FN += falseneg\n total_TN += trueneg\n total_FP += falsepos\n total_total += total\n # writing the data rows\n csvwriter.writerow(results)\n avg_tpr = total_TP / (total_TP+total_FN)\n avg_fpr = total_FP / (total_FP + total_TN)\n avg_score = avg_tpr - avg_fpr\n csvwriter.writerow([\"\", \"Total TP:\\n\" + str(total_TP), \"Total FN:\\n\" + str(total_FN), \"Total TN:\\n\" + str(total_TN), \"Total FP:\\n\" + str(total_FP), \"Total Test Cases:\\n\" + str(total_total), \"Average TPR:\\n\" + str(avg_tpr), \"Average FPR:\\n\" + str(avg_fpr), \"Average Score:\\n\" + str(avg_score)])\n makeGraph(avg_fpr, avg_tpr, 'customCodeInjection2 over benchmark')\n\nshutil.rmtree(new_path)\n","sub_path":"benchmark/scorecard_LGTM.py","file_name":"scorecard_LGTM.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"333147072","text":"#!/usr/bin/env python3\n# Get fluxes with python NetCDF4\nimport os\nimport sys\n\nimport netCDF4 as nc4\n\nfilename = sys.argv[1]\nget_dict = lambda obj: {key: val for key, val in obj.__dict__.items() if key[:1] != '_'}\nwith nc4.Dataset(filename, 'r') as f:\n # Get dimensions\n time_var = f['time']\n plev_var = f['plev']\n lon_var = f['lon']\n lat_var = f['lat']\n time = time_var[:]\n plev = plev_var[:]\n lon = lon_var[:]\n lat = lat_var[:]\n\n # Get data\n u_var = f['u']\n v_var = f['v']\n t_var = f['t']\n u = u_var[:]\n v = v_var[:]\n t = t_var[:]\n\n # Get attributes\n time_att = get_dict(time_var)\n plev_att = get_dict(plev_var)\n lat_att = get_dict(lat_var)\n\n# Perform calculations\nemf = (\n (u - u.mean(axis=-1, keepdims=True)) * (v - v.mean(axis=-1, keepdims=True))\n).mean(axis=-1)\nehf = (\n (t - t.mean(axis=-1, keepdims=True)) * (v - v.mean(axis=-1, keepdims=True))\n).mean(axis=-1)\n\n# Save file\noutname = 'out/netcdf4.nc'\nif os.path.exists(outname):\n os.remove(outname)\nwith nc4.Dataset(outname, 'w') as f:\n # Make dimensions\n # NOTE: This is very similar syntax to low-level C and Fortran libs\n f.createDimension('time', None)\n f.createDimension('plev', plev.size)\n f.createDimension('lat', lat.size)\n\n # Make new variables\n time_var = f.createVariable('time', 'f8', ('time',))\n plev_var = f.createVariable('plev', 'f8', ('plev',))\n lat_var = f.createVariable('lat', 'f8', ('lat',))\n ehf_var = f.createVariable('ehf', 'f8', ('time', 'plev', 'lat',))\n emf_var = f.createVariable('emf', 'f8', ('time', 'plev', 'lat',))\n\n # Add attributes\n # WARNING: Updating __dict__ silently fails for some reason!\n for var, dict_ in ((time_var, time_att), (plev_var, plev_att), (lat_var, lat_att)):\n for key, value in dict_.items():\n setattr(var, key, value)\n for var, dict_ in (\n (emf_var, {'long_name': 'eddy momentum flux', 'units': 'm**2/s**2'}),\n (ehf_var, {'long_name': 'eddy heat flux', 'units': 'K*m/s'}),\n ):\n for key, value in dict_.items():\n setattr(var, key, value)\n\n # Write to vars\n time_var[:] = time\n plev_var[:] = plev\n lat_var[:] = lat\n ehf_var[:] = ehf\n emf_var[:] = emf\n","sub_path":"fluxes/nc4.py","file_name":"nc4.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193676382","text":"import tweepy\nimport json\nimport pprint\n\nclaves = open(r'C:\\Users\\gonza\\Documents\\Trabajo\\EANT\\Python\\PDP\\EANT-PDP-0-MODELO\\5_NoSQL\\claves.txt')\nkeys = [clave.strip('\\n') for clave in claves]\nconsumer_key = keys[0]\nconsumer_secret = keys[1]\naccess_token = keys[2]\naccess_token_secret = keys[3]\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n#Mi perfil\nusuario = api.me()\npprint.pprint(usuario._json)\n#%%\n#Otro usuario\notro_usuario = api.get_user('DrBrianMay')\npprint.pprint(otro_usuario._json)\n#%%\nseguidores = api.followers(screen_name = 'DrBrianMay')\nfor seguidor in seguidores:\n print(seguidor._json['name'])\n#%%\nfor amigo in tweepy.Cursor(api.friends, screen_name = 'DrBrianMay').items(100):\n nombre = amigo._json['screen_name']\n print(nombre)\n#%%\ncontador = 1\nfor tweet in tweepy.Cursor(api.user_timeline, screen_name = 'theweeknd', tweet_mode = 'extended').items(10):\n print(contador)\n pprint.pprint(tweet._json['full_text'])\n contador += 1\n#%%\nfor tweet in tweepy.Cursor(api.search, q = 'Rexona', tweet_mode = 'extended').items(50):\n print(tweet._json['full_text'])\n","sub_path":"Clase 13/tutorial_twitter.py","file_name":"tutorial_twitter.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"308108922","text":"import cv2\nimport numpy as np\nimport sqlite3\nimport os\nimport argparse\n\ndef runTest(testData='./testData'):\n imagePaths = [os.path.join(testData,f) for f in os.listdir(testData)]\n results = []\n (total, correct) = (0,0)\n\n for imagePath in imagePaths:\n if imagePath.endswith('.jpg'):\n img = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)\n faces = face_cascade.detectMultiScale(img, 1.3, 5)\n\n for (x,y,w,h) in faces:\n total += 1\n\n im = img[y:y+h,x:x+w]\n if resize:\n im = cv2.resize(im,(resize_size))\n ids,conf = recognizer.predict(im)\n c.execute(\"select name from users where id = (?);\", (ids,))\n result = c.fetchall()\n name = result[0][0]\n\n if error_check:\n # get user id from imagePath. requires test data to have user id in name.\n actual_name = imagePath.split('/')[-1].split('.')[0]\n if str(actual_name) == str(name):\n correct += 1\n print('match!', end=\" \")\n else:\n print('error!', end=\" \")\n print(\"Predicted User %s : %s\" %(name, conf))\n\n results.append(conf)\n print('------------')\n print(\"Average confidence score: %s\" % (sum(results) / (len(results))))\n if error_check:\n print(\"Average accuracy score: %s%%\" %((correct / total) * 100))\n\ndef createRecognizer(t):\n rczr = None\n global resize\n if t.lower() == 'lbph':\n rczr = cv2.face.LBPHFaceRecognizer_create()\n resize=False\n elif t.lower() == 'fisher':\n rczr = cv2.face.FisherFaceRecognizer_create()\n resize=True\n elif t.lower() == 'eigen':\n rczr = cv2.face.EigenFaceRecognizer_create()\n resize=True\n else:\n rczr = cv2.face.LBPHFaceRecognizer_create()\n resize=False\n\n return rczr\n\ndef main():\n parser = argparse.ArgumentParser(description='Runs detector against testdata')\n parser.add_argument('--test-data',\n help=\"Path to test data directory. Default: './testData'\")\n parser.add_argument('--cascade-classifier',\n help=\"Path to cascade classifier to use. Default: 'haarcascade_frontalface_default.xml'\")\n parser.add_argument('--learning-algorithm',\n help=\"Learning Algorithm used. Options:'lbph','fisher','eigen'. Default: 'lbph'\")\n parser.add_argument('--resize-width',\n help=\"Integer which all facial images will be resized to. Only used if the learning algorithm needs it.\")\n parser.add_argument('--resize-height',\n help=\"Integer which all facial images will be resized to. Only used if the learning algorithm needs it.\")\n parser.add_argument('--error-check',\n help=\"Flag to run error checking\",\n action='store_true')\n\n args = parser.parse_args()\n\n global error_check\n if args.error_check:\n error_check = True\n else:\n error_check = False\n\n width = 100\n if args.resize_width:\n width = args.resize_width\n\n height = 100\n if args.resize_height:\n width = args.resize_height\n\n global resize_size\n resize_size = (width,height)\n\n conn = sqlite3.connect('database.db')\n global c\n c = conn.cursor()\n\n fname = \"recognizer/trainingData.yml\"\n if not os.path.isfile(fname):\n print(\"Please train the data first\")\n exit(0)\n\n #Cascade file\n classifierFile = './cascadeClassifiers/haarcascade_frontalface_default.xml'\n if args.cascade_classifier:\n classifierFile = args.cascade_classifier\n\n global face_cascade\n\n face_cascade = cv2.CascadeClassifier(classifierFile)\n\n global recognizer\n if args.learning_algorithm:\n recognizer = createRecognizer(args.learning_algorithm)\n else:\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n\n recognizer.read(fname)\n\n if args.test_data:\n runTest(args.test_data)\n else:\n runTest()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"132303930","text":"from django.contrib import admin\nfrom django.db import models\nfrom django.db.models import Count\n\nfrom .models import InboundCall, OutboundCall\nfrom customers import models as Customer\nfrom users import models as Company\nfrom users import models as User\n\n# Register class\n#class callInline(admin.TabularInline):\n# model = Customer\n\n# list_display = ('customer_name')\n\n# Class InboundCallAdmin for InboundCalls\nclass InboundCallAdmin(admin.ModelAdmin):\n \n # Foreign keys\n customer = models.ForeignKey(Customer.Customer, on_delete=models.CASCADE, default=\"\", blank=True)\n company = models.ForeignKey(Company.Company, on_delete=models.CASCADE, default=\"\", blank=True)\n\n def customer_name(self, instance):\n return instance.customer.customer_name\n\n def company_name(self, instance):\n return instance.company\n\n model = InboundCall, \n list_display = ('id',\n 'inboundcall_name',\n 'customer_name', \n 'inboundcall_email', \n 'inboundcall_phone', \n 'inboundcall_subject',\n 'inboundcall_send',\n 'company_name',\n )\n\n list_display_links = ('id', 'inboundcall_name',)\n\n search_fields = ['inboundcall_name','customer__customer_name',]\n\n# Class OutboundCallAdmin for InboundCalls\nclass OutboundCallAdmin(admin.ModelAdmin):\n # Foreign keys\n customer = models.ForeignKey(Customer.Customer, on_delete=models.CASCADE, default=\"\", blank=True)\n company = models.ForeignKey(Company.Company, on_delete=models.CASCADE, default=\"\", blank=True)\n \n \n\n def customer_name(self, instance):\n return instance.customer.customer_name\n\n def company_name(self, instance):\n return instance.company.company_name\n\n model = OutboundCall\n list_display = ('id',\n 'outboundcall_name',\n 'customer_name', \n 'outboundcall_email', \n 'outboundcall_phone', \n 'outboundcall_subject',\n 'outboundcall_send',\n 'company_name', \n )\n\n list_display_links = ('id', 'outboundcall_name',)\n\n search_fields = ['outboundcall_name','customer__customer_name',]\n\n\n# Register your models here.\nadmin.site.register(InboundCall, InboundCallAdmin)\n\nadmin.site.register(OutboundCall, OutboundCallAdmin)","sub_path":"calls/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"496486359","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nfrom PIL import Image\nimport os\nimport keras\n\n\"\"\"\nImportiamo tutte le immagini dalle varie cartelle\n\"\"\"\n\ndata=[]\nlabels=[]\n\nheight = 30\nwidth = 30\nchannels = 3\nclasses = 43\nn_inputs = height * width*channels\n\"\"\"\nItera per tutta la cartella numerata con ogni elemento della variabile target e ne estrae il campione di immagini per ciascuna etichetta.\nSuccessivamente salvami il valore della matrice della foto in una lista mentre in un altra la classe della variabile target associata\n\"\"\"\nfor i in range(0,classes):\n path = \"/Users/lorenzofamiglini/Desktop/MsC_2_anno/PROGETTO_AML_DSIM/gtsrb-german-traffic-sign/Train/{0}/\".format(i)\n Class=os.listdir(path)\n for a in Class:\n image=cv2.imread(path+a)\n image_from_array = Image.fromarray(image, 'RGB')\n #size_image = image_from_array.resize((height, width))\n data.append(np.array(image_from_array))\n labels.append(str(i))\n\nX_train =np.array(data)\ny_train=np.array(labels)\n#Converto y_train da stringa a valore intero\ny_train = y_train.astype(np.int)\nlen(data)\nlen(y_train)\nnp.unique(y_train)\nnp.shape(data)\n\n\"\"\"\nANALISI DATI\n\"\"\"\ncount_label = pd.DataFrame(y_train, columns = [\"Target\"])\ncount_label\n\ndf = pd.read_csv(\"/Users/lorenzofamiglini/Desktop/MsC_2_anno/PROGETTO_AML_DSIM/Object-and-Sound-detection/count_target.csv\")\ndf.shape\ndf_merge = pd.merge(count_label, df, left_on = \"Target\", right_on = \"target\", how = \"right\")\ndf_merge.drop(['Target', 'Unnamed: 0'], axis=1, inplace = True)\ncount_df = df_merge.groupby(['title']).count()\n\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\ncount_df = count_df.reset_index()\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\n\nstyle.use('ggplot')\n\nplt.figure(figsize=(10,10))\nplt.barh(\"title\",\"type\", data = count_df,align='center', alpha=0.5)\nplt.xlabel('Count')\nplt.title(\"Observations count per class\")\nplt.show()\n\ndf_merge[\"type\"].value_counts()\n\npd.DataFrame(df_merge[\"title\"].value_counts()).sort_values\n\n\n\"\"\"\nAnalisi della dimensione dei pixel\n\"\"\"\nlista_hei = [height.shape[0] for height in X_train]\nlista_wid = [width.shape[1] for width in X_train]\ndf_hw = pd.DataFrame()\ndf_hw[\"height\"] = lista_hei\ndf_hw[\"width\"] = lista_wid\ndf_hw[\"height\"].mean()\ndf_hw[\"width\"].mean()\ng = sns.JointGrid(x=\"height\", y=\"width\", data=df_hw)\ng.plot_joint(sns.regplot, order=2)\ng.plot_marginals(sns.distplot)\n\ng = sns.jointplot(x=\"height\", y=\"width\", data=df_hw, kind='kde')\n\n\"\"\"\nData augmentation\n\"\"\"\nfrom keras.preprocessing import image\nfor i in range(0,10):\n x = X_train[i].reshape((1,)+ X_train[i].shape)\n x.shape\n\n\n datagen = keras.preprocessing.image.ImageDataGenerator(featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=False)\n i = 0\n for batch in datagen.flow(x, batch_size=1):\n plt.figure(i)\n app = (batch - batch.min()) / (batch.max()-batch.min())\n #imgplot= plt.imshow(app[0])\n plt.imshow(cv2.cvtColor(app[0], cv2.COLOR_BGR2RGB))\n i += 1\n if i % 10 == 0:\n break\n plt.show()\n\n\n\"\"\"\nNormalizzazione\n\"\"\"\n\nX_train = (X_train-X_train.min())/(X_train.max()-X_train.min())\nX_train = X_train.reshape(X_train.shape[0],30*30,3)\nX_train.max()\nX_train.min()\n\n\n\n\"\"\"\nShuffle dataset\n\"\"\"\nfrom sklearn.utils import shuffle\ny_train = y_train.reshape(y_train.shape[0])\nX_train, y_train = shuffle(X_train,y_train, random_state=1)\n","sub_path":"Data_aug_trafficSign.py","file_name":"Data_aug_trafficSign.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"208077741","text":"import numpy as np\nimport argparse\nimport cv2\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--image\", required = True, help = \"Path to image\")\nargs = vars(parser.parse_args())\n\nimage = cv2.imread(args[\"image\"])\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(image, (5,5), 0)\ncv2.imshow(\"Image\", image)\n\n(T, thresh) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY)\ncv2.imshow(\"Threshold Binary\", thresh)\n\n(T, thresInv) = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY_INV)\ncv2.imshow(\"Inverse Threshold Binary\", thresInv)\n\ncv2.imshow(\"Coins\", cv2.bitwise_and(image, image, mask = thresInv))\n\ncv2.waitKey(0)","sub_path":"ch.9/simple_thresholding.py","file_name":"simple_thresholding.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"343506588","text":"\nimport numpy as np\nimport pandas as pd\nfrom decimal import Decimal\nimport re\n\n# Regex for preventing lots of trailing characters\nREGEX = re.compile('[0-9]+\\.[0-9]*([0]{6,}|[9]{6,})')\nREGEX_FLOAT = re.compile('\\d+\\.\\d+')\nREGEX_TRAILING = re.compile('([0]+)$')\n\ndef readCSV(file_path, column_to_filter, value_to_filter):\n csv_data = pd.read_csv(file_path, header = 0)\n \n csv_data = csv_data[csv_data[column_to_filter] == value_to_filter]\n \n return_dict = csv_data.to_dict(orient = 'records')[0]\n \n for k, v in return_dict.items():\n if type(v) in [int, float]:\n return_dict[k] = Decimal(str(v))\n \n return DotDict(return_dict)\n\nclass DotDict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n def __getattr__(self, attr):\n return self.get(attr)\n __setattr__= dict.__setitem__\n __delattr__= dict.__delitem__\n\n def __getstate__(self):\n return self\n\n def __setstate__(self, state):\n self.update(state)\n self.__dict__ = self\n\ndef convertToSnakeCase(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\n\n# Convert a number (usually a decimal or string) to a sensible rounding error\ndef automagicallyRound(val):\n # Attempts to fix the rounding issue\n # Convert to string\n if type(val) != str:\n val_str = str(val)\n else:\n val_str = val\n \n # Try and match\n m = REGEX.match(val_str)\n if m:\n m_dec = Decimal(m[0])\n numDecPlaces = m_dec.as_tuple().exponent\n m_rounded = round(m_dec, abs(numDecPlaces) - 1)\n val_str = str(m_rounded)\n \n # Only removing trailing zeroes if there are numbers after the decimal point (to prevent truncating 1000 etc)\n if REGEX_FLOAT.match(val_str):\n val_str = str(REGEX_TRAILING.sub('', val_str))\n \n return val_str\n \n\n# A group by which won't remove rows when the grouped columns have NaN values in them\ndef safeGroupBy(df, group_cols, agg_dict):\n # set name of group col to unique value\n group_id = 'group_id'\n while group_id in df.columns:\n group_id += 'x'\n # get final order of columns\n agg_col_order = (group_cols + list(agg_dict.keys()))\n # create unique index of grouped values\n group_idx = df[group_cols].drop_duplicates()\n group_idx[group_id] = np.arange(group_idx.shape[0])\n # merge unique index on dataframe\n df = df.merge(group_idx, on=group_cols)\n # group dataframe on group id and aggregate values\n df_agg = df.groupby(group_id, as_index=True).agg(agg_dict)\n # merge grouped value index to results of aggregation\n df_agg = group_idx.set_index(group_id).join(df_agg)\n # rename index\n df_agg.index.name = None\n # return reordered columns\n return df_agg[agg_col_order]\n \n\n# Import a class dynamically based on its name\ndef importClassByName(name):\n components = name.split('.')\n mod = __import__(components[0])\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n\n\n ","sub_path":"lib/petites.py","file_name":"petites.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"129695595","text":"some_list = [('Roman', 2, 'Python'), ('Igor', 12, 'Java'), ('Ira', 4, 'Ruby'), ('Roman', 3, 'Python')]\n\nsec_list = sorted(some_list, key=lambda x: x[1])\n\n\ndef some_print(slist):\n new_list = []\n for i in sec_list:\n new_list.append(f\"{i[0]} - {i[1]} years, {i[2]}\")\n\n return new_list\n\n\n\ndef fired_empl(key_name):\n for i in some_list:\n if i[0] == key_name:\n some_list.remove(i)\n break\n else:\n if i[0] != key_name:\n print(\"an employee with such name not found!\")\n break\n\n\n\n\n\n\n\n\n\n#print(some_print(sec_list))\n\nprint(some_list)\nprint(fired_empl(\"Roman\"))\nprint(some_list)\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"268877866","text":"import requests\n\n# 常用变量\nurl = 'http://www.baidu.com/'\nheaders = {'User-Agent': 'Mozilla/5.0'}\n# 发请求获取响应内容\nres = requests.get(url, headers=headers)\nhtml = res.text\n# 查看响应字符编码\nres.encoding = 'utf-8'\nprint(res.encoding)\n\n# 获取bytes数据类型\nprint(type(res.content))\n\n# 获取http的响应码\nprint(res.status_code)\n\n\n# print(html)\n","sub_path":"12-spider/2019-4-2/day02/08-requests示例.py","file_name":"08-requests示例.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154571831","text":"from setuptools import setup, find_packages\n\n\nwith open('requirements.txt', 'r') as f:\n required = f.read().splitlines()\n\nsetup(\n name = 'drcme',\n version = '0.1.0',\n description = \"\"\"dimensionality reduction and clustering for morphology and electrophysiology\"\"\",\n author = \"Nathan Gouwens\",\n author_email = \"nathang@alleninstitute.org\",\n url = '',\n packages = find_packages(),\n install_requires = required,\n include_package_data=True,\n setup_requires=['pytest-runner'],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"117014283","text":"from typing import Set\nfrom kalc.model.kinds.Pod import Pod\nfrom kalc.model.kinds.Node import Node\nfrom kalc.model.kinds.Service import Service\nfrom kalc.model.system.Scheduler import Scheduler\nfrom kalc.model.system.globals import GlobalVar\nfrom kalc.misc.const import *\nfrom poodle import planned\nfrom kalc.policy import policy_engine, BasePolicy\n\nfrom kalc.model.system.Scheduler import Scheduler\nfrom kalc.model.system.globals import GlobalVar\nfrom kalc.model.kinds.Service import Service\nfrom kalc.model.kinds.Node import Node\nfrom kalc.model.kinds.Pod import Pod\nfrom kalc.model.kinds.Deployment import Deployment\nfrom kalc.model.kinds.DaemonSet import DaemonSet\nfrom kalc.model.kinds.PriorityClass import PriorityClass\nfrom kalc.model.kubernetes import KubernetesCluster\nfrom kalc.misc.const import *\n\n\nclass BalancedClusterPolicy(BasePolicy):\n TYPE = \"property\"\n\n def register(self):\n GlobalVar.register_property(name=\"deploymentsWithAntiaffinityBalanced\", type=bool, default=False)\n GlobalVar.register_property(name=\"add_node_enabled\", type=bool, default=False)\n\n def set(self, val: bool):\n assert isinstance(val, bool), \"Can only accept True or False\"\n\n if val:\n # enable\n\n def hypothesis_do_rebalance_2_pods():\n # TODO: hypotheses can not work in parallel this way: will modify main object\n self.register_goal(self.target_object.deploymentsWithAntiaffinityBalanced, \"==\", True)\n\n def hypothesis_do_rebalance_allow_add_node():\n # TODO: hypotheses can not work in parallel this way: will modify main object\n self.target_object.add_node_enabled = True\n self.register_goal(self.target_object.deploymentsWithAntiaffinityBalanced, \"==\", True)\n \n self.register_hypothesis(\"2 pods rebalanced\", hypothesis_do_rebalance_2_pods, order=1)\n self.register_hypothesis(\"Added node to help with pods rebalancing\", hypothesis_do_rebalance_allow_add_node, order=10)\n else:\n # disable\n pass\n\n @planned(cost=1)\n def mark_checked_pod_as_antiaffinity_checked_for_target_pod(self,\n target_pod: Pod,\n antiaffinity_pod: Pod,\n globalVar: GlobalVar,\n scheduler: Scheduler,\n antiaffinity_pod_node: Node):\n if antiaffinity_pod.atNode != target_pod.atNode and \\\n target_pod.antiaffinity_set == True and \\\n antiaffinity_pod not in target_pod.calc_antiaffinity_pods_list:\n target_pod.calc_antiaffinity_pods_list.add(antiaffinity_pod)\n target_pod.calc_antiaffinity_pods_list_length += 1\n assert antiaffinity_pod in target_pod.podsMatchedByAntiaffinity \n assert antiaffinity_pod.atNode == antiaffinity_pod_node\n assert antiaffinity_pod_node.isNull == False\n # assert globalVar.block_policy_calculated == True\n globalVar.block_policy_calculated = True\n\n\n @planned(cost=1)\n def calculate_length_of_nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod(self,\n target_pod: Pod,\n antiaffinity_pod: Pod,\n antiaffinity_pod_node: Node,\n debug_nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod_length: int):\n assert antiaffinity_pod in target_pod.podsMatchedByAntiaffinity\n assert antiaffinity_pod in target_pod.calc_affinity_pods_list\n assert antiaffinity_pod_node == antiaffinity_pod.atNode\n if antiaffinity_pod_node not in target_pod.nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod:\n assert debug_nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod_length == target_pod.nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod_length \n target_pod.nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod.add(antiaffinity_pod_node)\n target_pod.nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod_length += 1\n\n\n @planned(cost=1)\n def mark_checked_pod_as_affinity_checked_for_target_pod(self,\n target_pod: Pod,\n checked_pod: Pod,\n globalVar: GlobalVar,\n scheduler: Scheduler):\n if checked_pod.atNode == target_pod.atNode and \\\n target_pod.affinity_set == True and \\\n checked_pod not in target_pod.calc_affinity_pods_list:\n target_pod.calc_affinity_pods_list.add(checked_pod)\n target_pod.calc_affinity_pods_list_length += 1\n assert checked_pod in target_pod.podsMatchedByAffinity \n # assert globalVar.block_policy_calculated == True \n globalVar.block_policy_calculated = True\n\n\n @planned(cost=1)\n def mark_that_node_cant_allocate_pod_by_cpu(self,\n pod: Pod,\n node: Node,\n globalVar: GlobalVar):\n if not node in pod.nodesThatCantAllocateThisPod:\n assert pod.cpuRequest > node.cpuCapacity - node.currentFormalCpuConsumption\n pod.nodesThatCantAllocateThisPod.add(node)\n pod.nodesThatCantAllocateThisPod_length += 1\n # assert globalVar.block_policy_calculated == True\n globalVar.block_policy_calculated = True\n assert node.isNull == False\n\n\n @planned(cost=1)\n def mark_that_node_cant_allocate_pod_by_mem(self,\n pod: Pod,\n node: Node,\n globalVar: GlobalVar):\n assert node.isNull == False\n if not node in pod.nodesThatCantAllocateThisPod:\n assert pod.memRequest > node.memCapacity - node.currentFormalMemConsumption\n pod.nodesThatCantAllocateThisPod.add(node)\n pod.nodesThatCantAllocateThisPod_length += 1\n # assert globalVar.block_policy_calculated == True\n globalVar.block_policy_calculated = True\n\n \n @planned(cost=1)\n def mark_antiaffinity_met_because_all_antiaffinity_pods_are_matched(self,\n pod: Pod,\n globalVar: GlobalVar):\n assert pod.calc_antiaffinity_pods_list_length == pod.podsMatchedByAntiaffinity_length\n assert pod.antiaffinity_set == True\n # assert globalVar.block_policy_calculated == True\n pod.antiaffinity_met = True\n globalVar.block_policy_calculated = True\n\n\n @planned(cost=1)\n def mark_affinity_met_because_all_affinity_pods_are_matched(self,\n pod: Pod,\n globalVar: GlobalVar):\n assert pod.calc_affinity_pods_list_length == pod.podsMatchedByAffinity_length\n assert pod.affinity_set == True\n # assert globalVar.block_policy_calculated == True\n pod.affinity_met = True\n globalVar.block_policy_calculated = True\n\n\n @planned(cost=1)\n def mark_antiaffinity_met_because_all_antiaffinity_pods_are_matched_and_those_that_cant_dont_suite(self,\n pod: Pod,\n globalVar: GlobalVar):\n assert pod.calc_antiaffinity_pods_list_length == pod.target_number_of_antiaffinity_pods\n assert pod.antiaffinity_set == True\n # assert globalVar.block_policy_calculated == True\n pod.antiaffinity_met = True\n globalVar.block_policy_calculated = True\n\n\n # @planned(cost=1)\n def mark_antiaffinity_met_because_all_antiaffinity_pods_are_matched_and_those_that_cant_dont_suite_below_the_limit_for_node_amount(self,\n pod: Pod,\n globalVar: GlobalVar):\n assert pod.nodesThatHaveAllocatedPodsThatHaveAntiaffinityWithThisPod_length + pod.nodesThatCantAllocateThisPod_length == globalVar.amountOfNodes_limit\n assert pod.antiaffinity_set == True\n pod.antiaffinity_met = True\n\n \n @planned(cost=1)\n def Set_antiaffinity_between_pods_of_deployment(self,\n pod1: Pod,\n pod2: Pod,\n deployment: Deployment,\n globalVar: GlobalVar):\n if pod1 not in pod2.podsMatchedByAffinity and pod2 not in pod1.podsMatchedByAffinity:\n assert pod1 in deployment.podList\n assert pod2 in deployment.podList\n assert deployment.NumberOfPodsOnSameNodeForDeployment == globalVar.maxNumberOfPodsOnSameNodeForDeployment\n pod1.antiaffinity_set = True\n pod1.podsMatchedByAffinity.add(pod2)\n pod1.podsMatchedByAffinity_length += 1\n pod2.antiaffinity_set = True\n pod2.podsMatchedByAffinity.add(pod1)\n pod2.podsMatchedByAffinity_length += 1\n\n \n @planned(cost=1)\n def Reduce_maxNumberOfPodsOnSameNodeForDeployment(self,\n globalVar: GlobalVar):\n globalVar.maxNumberOfPodsOnSameNodeForDeployment -= 1 \n \n\n @planned(cost=1)\n def Calculate_fulfilled_antiaffinity_pods_of_deployment(self,\n pod1: Pod,\n pod2: Pod,\n deployment: Deployment):\n assert pod1 in deployment.podList\n assert deployment.amountOfActivePods > 0\n assert pod1.podsMatchedByAffinity_length == deployment.amountOfActivePods\n deployment.amountOfPodsWithAntiaffinity += 1\n \n\n @planned(cost=1)\n def Calculate_fulfilled_antiaffinity_pods_of_deployment_with_limited_number_of_pods(self,\n pod1: Pod,\n pod2: Pod,\n deployment: Deployment,\n globalVar: GlobalVar):\n assert pod1 in deployment.podList\n assert globalVar.target_amountOfPodsWithAntiaffinity > 0\n assert pod1.podsMatchedByAffinity_length == globalVar.target_amountOfPodsWithAntiaffinity\n deployment.amountOfPodsWithAntiaffinity += 1\n\n\n @planned(cost=1)\n def mark_finalization_of_antiaffinity_setting_for_pods_of_deployment(self,\n deployment: Deployment,\n globalVar: GlobalVar):\n assert deployment.amountOfPodsWithAntiaffinity == deployment.amountOfActivePods\n globalVar.amountOfDeploymentsWithAntiaffinity += 1\n \n\n @planned(cost=1)\n def mark_finalization_of_antiaffinity_setting_for_pods_of_deployment2(self,\n deployment: Deployment,\n globalVar: GlobalVar):\n assert globalVar.amountOfDeploymentsWithAntiaffinity == globalVar.target_amountOfDeploymentsWithAntiaffinity\n globalVar.deploymentsWithAntiaffinityBalanced = True\n\n\n @planned(cost=1)\n def Add_node(self,\n node : Node,\n globalVar: GlobalVar):\n assert globalVar.add_node_enabled == True\n assert node.status == STATUS_NODE[\"New\"]\n node.status = STATUS_NODE[\"Active\"]\n globalVar.amountOfNodes += 1\n \npolicy_engine.register(Service, \"self_antiaffinity\", BalancedClusterPolicy)\n\n","sub_path":"kalc/policies/rebalancing.py","file_name":"rebalancing.py","file_ext":"py","file_size_in_byte":10371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"175670314","text":"import itertools\n\nSERVICE_ADAPTATIONS = {u'CBI', u'LLI', u'BSL', u'MIN', u'TYP', u'SWC', u'OAD',\n u'TPC', u'TAF', u'FRS', u'NAR', u'OTH', u'MAR'}\n\nEXEMPTION_CODES = {u'ECHI', u'EDET', u'EPRE'}\n\nDISABILITY_INDICATOR = {u'NCD', u'MHC', u'LDD', u'ILL', u'OTH', u'UKN', u'MOB',\n u'DEA',\n u'HEA', u'VIS', u'BLI', u'PNS', u'PHY', u'SEN', u'COG'}\n\nADVICE_TYPES = {u'TA', u'OA', u'FF'}\n\nAGE_RANGE = {u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'U'}\n\nELIGIBILITY_CODES = {u'S', u'T', u'V', u'W', u'X', u'Z'}\n\nDETERMINATION_CODES = {u'OOSC', u'OSPF', u'CHNM', u'FINI', u'DVCA'}\n\nCATEGORY_SPEC = {\n u'debt': {\n 'OUTCOME_CODES': {u'DA', u'DC', u'DD', u'DG', u'DH', u'DI', u'DU',\n u'DV', u'DW', u'DX', u'DY', u'DZ'},\n 'MATTER_TYPE1': {u'DPDE', u'DNPD', u'DMDE', u'DMCA', u'DMAP', u'DIVB',\n u'DORH', u'DTOT'},\n 'MATTER_TYPE2': {u'DVAL', u'DMIX', u'DCRE', u'DIBP', u'DORD', u'DOTH'},\n 'STAGE_REACHED': {u'DA', u'DB', u'DC', u'DD'}\n },\n u'discrimination': {\n 'OUTCOME_CODES': {u'QA', u'QB', u'QC', u'QD', u'QE', u'QF', u'QG',\n u'QH', u'QI', u'QJ', u'QK', u'QL', u'QM', u'QT',\n u'QU', u'QV', u'QW', u'QX', u'QY', u'QZ'},\n 'MATTER_TYPE1': {u'QPRO', u'QEMP', u'QEQP', u'QPRE', u'QFUN', u'QEDU',\n u'QPUB', u'QCON'},\n 'MATTER_TYPE2': {u'QAGE', u'QDIS', u'QGEN', u'QMCP', u'QPRM', u'QRAC',\n u'QROB', u'QSEX', u'QSOR', u'QMDI'},\n 'STAGE_REACHED': {u'QA', u'QB', u'QC', u'QD', u'QE', u'QF', u'QG',\n u'QH'}\n },\n u'education': {\n 'OUTCOME_CODES': {u'EA', u'EB', u'EC', u'ED', u'EE', u'EF', u'EG',\n u'EH', u'EI', u'EJ', u'EK', u'EU', u'EV', u'EW',\n u'EX', u'EY'},\n 'MATTER_TYPE1': {u'ESEN', u'ENEG', u'EXCE', u'EDOT', u'EADM', u'EGTO',\n u'EPRO', u'EDDA', u'EREO', u'EEQU'},\n 'MATTER_TYPE2': {u'ENUR', u'EDSC', u'EPRU', u'ECOL', u'EUNI', u'EAAP',\n u'ELOC', u'EIAP', u'ESOS', u'EHEF', u'EOTH'},\n 'STAGE_REACHED': {u'EA', u'EB', u'EC', u'ED'}\n },\n u'family': {\n 'OUTCOME_CODES': {u'FA', u'FB', u'FC', u'FD', u'FE', u'FF', u'FG',\n u'FH', u'FI', u'FJ', u'FT', u'FU', u'FV', u'FW',\n u'FX', u'FY', u'FZ', u'FS'},\n 'MATTER_TYPE1': {u'FAMA', u'FAMB', u'FAMC', u'FAMD', u'FAME', u'FAMF',\n u'FAMG', u'FAMH', u'FAMI', u'FAMJ', u'FAMK', u'FAML',\n u'FAMM', u'FAMN', u'FAMO', u'FAMP', u'FAMQ', u'FAMR',\n u'FAMS', u'FAMT', u'FAMU', u'FAMV', u'FAMW', u'FAMX',\n u'FAMY', u'FAMZ', u'FAM1', u'FAM2', u'FAM3', },\n 'MATTER_TYPE2': {u'FADV', u'FPET', u'FRES', u'FAPP', u'FREP', u'FCHG',\n u'FCHS', u'FOTH', u'FMEC', u'FMEF', u'FMEA'},\n 'STAGE_REACHED': {u'FA', u'FB', u'FC', u'FD'}\n },\n u'housing': {\n 'OUTCOME_CODES': {u'HA', u'HD', u'HE', u'HF', u'HG', u'HH', u'HI',\n u'HJ', u'HK', u'HL', u'HM', u'HU', u'HV', u'HW',\n u'HX', u'HY', u'HZ'},\n 'MATTER_TYPE1': {u'HRNT', u'HMOR', u'HPOT', u'HANT', u'HDIS', u'HREP',\n u'HREH', u'HHOM', u'HBFT', u'HULE', u'HLAN', u'HOOT'},\n 'MATTER_TYPE2': {u'HPUB', u'HPRI', u'HHAC', u'HNAS', u'HOWN', u'HHLS',\n u'HLAN', u'HOTH'},\n 'STAGE_REACHED': {u'HA', u'HB', u'HC', u'HD'}\n },\n u'welfare': {\n 'OUTCOME_CODES': {u'WA', u'WB', u'WC', u'WD', u'WE', u'WG', u'WU',\n u'WV', u'WZ'},\n 'MATTER_TYPE1': {u'WDLA', u'WBAA', u'WICB', u'WSFP', u'WHBT', u'WIST',\n u'WJSA', u'WIIB', u'WBBT', u'WTAX', u'WMUL', u'WOTH',\n u'WESA', u'WBPI', u'WBUC'},\n 'MATTER_TYPE2': {u'WREA', u'WREV', u'WSSC', u'WAPL', u'WOVE', u'WBAC',\n u'WLGO', u'WOTH', u'WNAS', u'WBPA', u'WBUT', u'WBCA',\n u'WBSC', u'WBHC'},\n 'STAGE_REACHED': {u'WA', u'WB', u'WC', u'WD'}\n }\n}\n\nPREFIX_CATEGORY_LOOKUP = {\n u'D': u'debt',\n u'W': u'welfare',\n u'H': u'housing',\n u'F': u'family',\n u'E': u'education',\n u'Q': u'discrimination'\n}\n\nVALID_OUTCOMES = list(itertools.chain.from_iterable([v['OUTCOME_CODES'] for k, v in CATEGORY_SPEC.items()]))\nVALID_STAGE_REACHED = list(itertools.chain.from_iterable([v['STAGE_REACHED'] for k, v in CATEGORY_SPEC.items()]))\nVALID_MATTER_TYPE1 = list(itertools.chain.from_iterable([v['MATTER_TYPE1'] for k, v in CATEGORY_SPEC.items()]))\nVALID_MATTER_TYPE2 = list(itertools.chain.from_iterable([v['MATTER_TYPE2'] for k, v in CATEGORY_SPEC.items()]))\n\nSTAGE_REACHED_REQUIRED_MT1S = {\n u'DMCA', u'DMAP', u'DIVB', u'DORH', u'DTOT', u'QPRO', u'QEMP', u'QEQP',\n u'QPRE', u'QFUN', u'QEDU', u'QPUB', u'QCON', u'ESEN', u'ENEG', u'EXCE',\n u'EDOT', u'EADM', u'EGTO', u'EPRO', u'EDDA', u'EREO', u'EEQU', u'HRNT',\n u'HPOT', u'HANT', u'HDIS', u'HREP', u'HHOM', u'HULE', u'HOOT', u'HPPO',\n u'HPWA', u'HRAR', u'HPOS', }\n\nSTAGE_REACHED_NOT_ALLOWED_MT1S = {\n u'WDLA', u'WBAA', u'WICB', u'WSFP', u'WHBT', u'WIST', u'WJSA', u'WIIB',\n u'WBBT', u'WTAX', u'WMUL', u'WOTH', u'WESA', u'WBPI', u'FAMA', u'FAMB',\n u'FAMC', u'FAMD', u'FAME', u'FAMF', u'FAMG', u'FAMH', u'FAMI', u'FAMJ',\n u'FAMK', u'FAML', u'FAMM', u'FAMN', u'FAMO', u'FAMP', u'FAMQ', u'FAMR',\n u'FAMS', u'FAMV', u'FAMW', u'FAMX', u'FAMY', u'FAMZ', u'FAM1', u'FAM2', u'FAM3'\n}\n\n\nPOSTCODE_RE = r'''(?: # UK POSTCODE\n ( G[I1]R \\s* [0O]AA | NFA | INT \\s INT ) # special postcode\n |\n ( [A-PR-UWYZ01][A-Z01]? ) # area\n ( [0-9IO][0-9A-HJKMNPR-YIO]? ) # district\n (?: \\s*\n ( [0-9IO] ) # sector\n ( [ABD-HJLNPQ-Z10]{2} ) # unit\n )\n)$'''\n","sub_path":"cla_backend/apps/legalaid/utils/csvupload/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"320194077","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n# Author:SemaseMing \n# Email: admin@v-api.cn\n# Time:2016-08-29 23:23\n'''\ngood\n1、我记得这个作业应该是添加配置的时候应该是用过json添加的\n 不过这样应该也可以无非就是有个解析json的过程\n inputBackend = input(\"请输入的您要添加的Backend:\")\n serverip = input(\"输入新的serverip值:\")\n weight = input(\"输入新的weight值:\")\n maxconn = input(\"输入新的maxconn值:\")\n2、还是这里,是不是要对输入的参数做一个判断输入的是否符合要求,因为毕竟是配置文件,判断的越细,出错的概率就越低\n3、new.write(\" \" * 8 + server_link + \"\\n\")还是要少用这种方式处理字符串\n总的来说还不错的,思路比较清晰,并且考虑到了回滚\n'''\nimport os\nimport shutil\nCFG_FILE = \"HAproxy.cfg\" # 配置文件名称\nCFG_FILE_BAK = \"HAproxy.cfg.bak\" # 备份配置文件名称\nCFG_FILE_TEMP = \"HAproxy.cfg.temp\" # 临时配置文件名称\nQUIT_CHAR = 'q' # 退出字符\nflag = True # 循环标记\n\n# 检查配置文件是否存在\nif os.path.exists(CFG_FILE):\n print(\"配置文件加载成功\")\nelse:\n print(\"配置文件丢失。退出\")\n exit(1)\n\n\n# 备份文件,并生成新的配置文件\ndef filecopy():\n shutil.copy(CFG_FILE, CFG_FILE_BAK)\n shutil.copy(CFG_FILE_TEMP, CFG_FILE)\n\n\n# 获取配置文件中的backend列��\ndef getdominlist():\n \"\"\" 获取配置信息中的域名列表 \"\"\"\n domainList = []\n f = open(CFG_FILE, 'r+', encoding='utf-8')\n for i in f:\n if i.strip().startswith(\"backend\"):\n domainList.append(i.strip().split(\" \")[1])\n f.close()\n return domainList\n\n# 获取对应backend的server列表\ndef getserver(backend):\n server = []\n domain_1 = 'backend %s' % backend\n with open(CFG_FILE, 'r+', encoding='utf-8') as f:\n flag = False\n for i in f:\n if i.strip().startswith(\"backend\") and i.strip() == domain_1:\n flag = True\n continue\n if flag and i.strip().startswith(\"backend\"):\n flag = False\n break\n if flag and i.strip():\n server.append(i.strip())\n return server\n\n\n# 获取HAproxy配置信息\ndef getinfo():\n \"\"\" 获取HAproxy配置信息 \"\"\"\n domainList = getdominlist()\n for i in domainList:\n print(domainList.index(i), i)\n domain_num = input(\"请输入您要查看的那个域名序号:\")\n if domain_num.isdigit():\n domain_int_num = int(domain_num)\n if domain_int_num < len(domainList):\n server = getserver(domainList[domain_int_num])\n for i in server:\n print(i)\n else:\n print(\"输入的序号不正确\")\n else:\n print(\"输入的序号不正确\")\n\n\n# 添加HAproxy配置信息\ndef addinfo():\n \"\"\" 添加HAproxy配置信息 \"\"\"\n print(\"添加backend 和sever信息\")\n domainList = getdominlist()\n inputBackend = input(\"请输入的您要添加的Backend:\")\n serverip = input(\"输入新的serverip值:\")\n weight = input(\"输入新的weight值:\")\n maxconn = input(\"输入新的maxconn值:\")\n inputserver = \"\"\" server %s %s weight %s maxconn %s\\n\"\"\" % (serverip, serverip, weight, maxconn)\n if inputBackend not in domainList:\n \"\"\" backend 不在原配置文件中 \"\"\"\n with open(CFG_FILE, 'r') as old, open(CFG_FILE_TEMP, 'w', encoding='utf-8') as new:\n for line in old:\n new.write(line)\n new.write(\"\\nbackend \" + inputBackend + \"\\n\")\n new.write(inputserver)\n filecopy()\n print(\"添加数据成功\")\n else:\n server = getserver(inputBackend)\n if inputserver.strip() in server:\n print(\"您要添加的数据已经存在\")\n else:\n server.append(inputserver.strip())\n with open(CFG_FILE, 'r') as old, open(CFG_FILE_TEMP, 'w', encoding='utf-8') as new:\n flag = False\n for line in old:\n if line.strip().startswith('backend') and line.strip() == 'backend '+inputBackend:\n flag = True\n new.write(line)\n for new_server in server:\n new.write(\" \"*8 + new_server + \"\\n\")\n print(new_server)\n continue\n elif flag and line.strip().startswith('backend'):\n flag = False\n new.write(line)\n continue\n elif line.strip() and not flag:\n new.write(line)\n filecopy()\n print(\"添加数据成功\")\n\n\n# 修改HAproxy配置信息\ndef updateinfo():\n \"\"\"修改HAproxy配置信息 \"\"\"\n print(\"修改backend 和sever信息 \")\n domainList = getdominlist()\n for i in domainList:\n print(domainList.index(i), i)\n domain_num = input(\"请输入您要修改的那个域名序号:\")\n if domain_num.isdigit():\n domain_int_num = int(domain_num)\n if domain_int_num < len(domainList):\n server = getserver(domainList[domain_int_num])\n for i in server:\n print(server.index(i), i)\n server_num= input(\"选择您要修改的server信息:\")\n if server_num.isdigit():\n server_int_num = int(server_num)\n if server_int_num < len(server):\n serverip = input(\"输入新的serverip值:\")\n weight = input(\"输入新的weight值:\")\n maxconn = input(\"输入新的maxconn值:\")\n upserverdate = \"\"\" server %s %s weight %s maxconn %s\\n\"\"\" % (serverip, serverip, weight, maxconn)\n with open(CFG_FILE, 'r') as old, open(CFG_FILE_TEMP, 'w', encoding='utf-8') as new:\n flag = False\n for line in old:\n if line.strip().startswith('backend') and line.strip() == 'backend ' + domainList[domain_int_num]:\n flag = True\n new.write(line)\n for server_link in server:\n if server_link == server[server_int_num]:\n new.write(upserverdate)\n else:\n new.write(\" \" * 8 + server_link + \"\\n\")\n elif flag and line.strip().startswith('backend'):\n flag = False\n new.write(line)\n continue\n elif line.strip() and not flag:\n new.write(line)\n filecopy()\n print(\"修改成功\")\n else:\n print(\"输入错误的序号\")\n else:\n print(\"输入错误的序号\")\n else:\n print(\"输入错误的序号\")\n\n\n# 删除HAproxy配置信息\ndef delinfo():\n \"\"\" 删除HAproxy配置信息 \"\"\"\n print(\"删除backend和sever信息\")\n domainList = getdominlist()\n for i in domainList:\n print(domainList.index(i), i)\n domain_num = input(\"请输入您要删除的域名序号:\")\n if domain_num.isdigit():\n domain_int_num = int(domain_num)\n if domain_int_num < len(domainList):\n str_sip = \"\"\" 删除选项\n 1.整个backend\n 2.某条server信息\"\"\"\n print(str_sip)\n choose = input(\"您的选择:\")\n if choose == '1':\n print(\"删除整个backend\")\n with open(CFG_FILE, 'r') as old, open(CFG_FILE_TEMP, 'w', encoding='utf-8') as new:\n flag = False\n for line in old:\n if line.strip().startswith(\"backend\") and line.strip() == 'backend ' + domainList[domain_int_num]:\n flag = True\n elif flag and line.strip().startswith(\"backend\"):\n flag = False\n new.write(line)\n elif line.strip() and not flag:\n new.write(line)\n filecopy()\n print(\"删除成功\")\n elif choose == '2':\n print(\"删除某条server\")\n server = getserver(domainList[domain_int_num])\n for i in server:\n print(server.index(i), i)\n server_num = input(\"选择您要修改的server信息的序号:\")\n if server_num.isdigit():\n server_int_num = int(server_num)\n if server_int_num < len(server):\n with open(CFG_FILE, 'r') as old, open(CFG_FILE_TEMP, 'w', encoding='utf-8') as new:\n flag = False\n for line in old:\n if line.strip().startswith(\"backend\") and line.strip() == 'backend ' + domainList[domain_int_num]:\n flag = True\n new.write(line)\n for serverlist in server:\n if serverlist != server[server_int_num]:\n new.write(serverlist)\n elif flag and line.strip().startswith(\"backend\"):\n flag = False\n new.write(line)\n elif line.strip() and not flag:\n new.write(line)\n filecopy()\n else:\n print(\"输入错误的序号\")\n else:\n print(\"输入错误的序号\")\n else:\n print(\"输入错误的序号\")\n\n\n# 备份HAproxy配置文件\ndef bakupinfo():\n \"\"\" 备份HAproxy配置文件 \"\"\"\n print(\"备份配置文件\")\n shutil.copy(CFG_FILE, CFG_FILE_BAK)\n print(\"备份成功\")\n\n\n# 回滚HAproxy配置文件\ndef rollback():\n \"\"\" 回滚HAproxy配置文件 \"\"\"\n print(\" 回滚HAproxy配置文件 \")\n shutil.copy(CFG_FILE_BAK, CFG_FILE)\n print(\"回滚成功\")\n\n\nstr1 = \"\"\"\n------------------------------------\n| 欢迎来到HAproxy管理脚本 v1.0.0 |\n------------------------------------\n| 1.获取backend 和sever信息 |\n| 2.添加backend 和sever信息 |\n| 3.修改backend 和sever信息 |\n| 4.删除backend 和sever信息 |\n| 5.备份配置文件 |\n| 6.回滚配置文件 |\n------------------------------------\n| %s:退出 数字:选择 |\n------------------------------------\n\"\"\" % QUIT_CHAR\nwhile flag:\n print(str1)\n num = input(\"请输入您的选择:\")\n if num.isdigit():\n num_int = int(num)\n if num_int == 1:\n \"\"\" 获取backend 和sever信息 \"\"\"\n getinfo()\n elif num_int == 2:\n \"\"\" 添加backend 和sever信息 \"\"\"\n addinfo()\n\n elif num_int == 3:\n \"\"\" 修改backend 和sever信息 \"\"\"\n updateinfo()\n elif num_int == 4:\n \"\"\" 删除backend 和sever信息 \"\"\"\n delinfo()\n\n elif num_int == 5:\n \"\"\" 备份配置文件 \"\"\"\n bakupinfo()\n\n elif num_int == 6:\n \"\"\" 回滚配置文件 \"\"\"\n rollback()\n else:\n print(\"不正确的选项,请重新选择\")\n else:\n if num == QUIT_CHAR:\n print(\"退出\")\n flag = False\n\n","sub_path":"homework/03.HAproxy配置文件操作/HAproxy配置文件操作v2老师批改.py","file_name":"HAproxy配置文件操作v2老师批改.py","file_ext":"py","file_size_in_byte":11906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"100324040","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# vim: set ts=4 sw=4 tw=0 et pm=:\n\nimport os\nimport sys\nimport re\nimport fileinput\nimport getopt\nimport datetime\nimport time\nimport collections.abc\n\nimport bitsparser\n\noptions, remainder = getopt.getopt(sys.argv[1:], 'vgi:o:pes', [\n 'verbose',\n 'good',\n 'uw-ec',\n 'harder',\n 'confidence=',\n 'input=',\n 'output=',\n 'perfect',\n 'disable-freqclass',\n 'errorfree',\n 'interesting',\n 'satclass',\n 'plot=',\n 'filter=',\n 'voice-dump=',\n 'format=',\n 'errorfile=',\n 'errorstats',\n 'forcetype=',\n 'channelize',\n 'sigmf-annotate=',\n 'stats',\n ])\n\nverbose = False\nperfect = False\nerrorfree = False\ninteresting = False\ngood = False\ndosatclass = False\ninput= \"raw\"\noutput= \"line\"\nofmt= None\nlinefilter={ 'type': 'All', 'attr': None, 'check': None }\nplotargs=[\"time\", \"frequency\"]\nvdumpfile=None\nerrorfile=None\nerrorstats=None\nsigmffile=None\ndo_stats=False\n\nfor opt, arg in options:\n if opt in ['-v', '--verbose']:\n bitsparser.verbose = True\n elif opt in ['-g','--good']:\n good = True\n min_confidence=90\n elif opt in ['--uw-ec']:\n bitsparser.uwec = True\n elif opt in ['--harder']:\n bitsparser.harder = True\n elif opt in ['--confidence']:\n good = True\n min_confidence=int(arg)\n elif opt in ['--interesting']:\n interesting = True\n elif opt in ['-p', '--perfect']:\n bitsparser.perfect = True\n perfect = True\n elif opt in ['--disable-freqclass']:\n bitsparser.freqclass = False\n elif opt in ['-e', '--errorfree']:\n errorfree = True\n elif opt in ['-s', '--satclass']:\n dosatclass = True\n elif opt in ['--plot']:\n plotargs=arg.split(',')\n elif opt in ['--filter']:\n linefilter['type']=arg\n if ',' in linefilter['type']:\n (linefilter['type'],linefilter['check'])=linefilter['type'].split(',',2)\n if '+' in linefilter['type']:\n (linefilter['type'],linefilter['attr'])=linefilter['type'].split('+')\n bitsparser.linefilter=linefilter\n elif opt in ['--voice-dump']:\n vdumpfile=arg\n elif opt in ['-i', '--input']:\n input=arg\n elif opt in ['-o', '--output']:\n output=arg\n elif opt in ['--errorfile']:\n errorfile=arg\n bitsparser.errorfile=arg\n elif opt in ['--errorstats']:\n errorstats={}\n elif opt in ['--forcetype']:\n bitsparser.forcetype=arg\n elif opt in ['--channelize']:\n bitsparser.channelize=True\n elif opt in ['--format']:\n ofmt=arg.split(',');\n elif opt in ['--sigmf-annotate']:\n sigmffile=arg\n output=\"sigmf\"\n elif opt in ['--stats']:\n do_stats=True\n else:\n raise Exception(\"unknown argument?\")\n\nif input == \"dump\" or output == \"dump\":\n import pickle as pickle\n dumpfile=\"pickle.dump\"\n\nif output == \"sigmf\":\n import json\n\nif output == \"zmq\":\n do_stats=True\n errorfree=True\n\nif do_stats:\n import curses\n curses.setupterm(fd=sys.stderr.fileno())\n statsfile=sys.stderr\n el=curses.tigetstr('el')\n cr=curses.tigetstr('cr') or b'\\r'\n nl=curses.tigetstr('nl') or b'\\n'\n if el is None:\n eol= (nl).decode(\"ascii\")\n eolnl=(nl).decode(\"ascii\")\n else:\n eol= (el+cr).decode(\"ascii\")\n eolnl=(el+nl).decode(\"ascii\")\n stats={}\n\nsigmfjson=None\nsigmfout=None\nif sigmffile is not None:\n try:\n sigmfjson=json.load(open(sigmffile,'r'))\n sigmfjson.pop('annotations', None)\n except FileNotFoundError:\n print(\"WARN: no sigmf-meta source file. Using (probably-wrong) hardcoded defaults\", file=sys.stderr)\n sigmfjson={\n \"global\":\n {\"core:datatype\": \"cf32_le\", \"core:sample_rate\": 10e6, \"core:version\": \"0.0.1\"},\n \"captures\": [\n {\"core:sample_start\": 0, \"core:frequency\": 1626000000}\n ]\n }\n sigmfout=open(sigmffile+'.tmp','w')\n print(\"{\", file=sigmfout)\n for key in sigmfjson:\n print('\"%s\":'%key, file=sigmfout)\n json.dump(sigmfjson[key],sigmfout)\n print(',', file=sigmfout)\n print('\"%s\": ['%\"annotations\", file=sigmfout)\n\nif sigmfout is None:\n sigmfout=sys.stdout\n\nif dosatclass == True:\n import satclass\n satclass.init()\n\nif (linefilter['type'] != 'All') and bitsparser.harder:\n raise Exception(\"--harder and --filter (except type=Any) can't be use at the same time\")\n\nif vdumpfile != None:\n vdumpfile=open(vdumpfile,\"wb\")\n\nif errorfile != None:\n errorfile=open(errorfile,\"w\")\n\nif output == \"dump\":\n file=open(dumpfile,\"wb\")\n\nif output == \"plot\":\n import matplotlib.pyplot as plt\n import matplotlib.ticker as ticker\n xl=[]\n yl=[]\n cl=[]\n sl=[]\n\nif output == \"zmq\":\n import zmq\n\n url = \"tcp://127.0.0.1:4223\"\n\n context = zmq.Context()\n socket = context.socket(zmq.XPUB)\n socket.setsockopt(zmq.XPUB_VERBOSE, True)\n socket.bind(url)\n\n stats['clients']=0\n def zmq_thread(socket, stats):\n try:\n while True:\n event = socket.recv()\n # Event is one byte 0=unsub or 1=sub, followed by topic\n if event[0] == 1:\n log(\"new subscriber for\", event[1:])\n stats['clients'] += 1\n elif event[0] == 0:\n log(\"unsubscribed\",event[1:])\n stats['clients'] -= 1\n except zmq.error.ContextTerminated:\n pass\n\n def log(*msg):\n s=time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime())\n print(\"%s:\"%s,*msg, end=eolnl, file=statsfile)\n\n from threading import Thread\n zthread = Thread(target = zmq_thread, args = [socket, stats], daemon= True, name='zmq')\n zthread.start()\n\ndef stats_thread(stats):\n ltime=time.time()\n lline=0\n stime=stats['start']\n stop=stats['stop']\n\n while not stop.wait(timeout=1.0):\n now=time.time()\n nowl=stats['in']\n td=now-stime\n s=time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime())\n ts=\"%02d:%02d:%02d\"%(td/60/60,td/60%60,td%60)\n hdr=\"%s [%s]\"%(s, ts)\n progress=\"\"\n if 'files' in stats and stats['files']>1:\n progress+=\"%d/%d:\"%(stats['fileno'],stats['files'])\n if 'size' in stats and stats['size']>0:\n pos=os.lseek(fileinput.fileno(),0,os.SEEK_CUR)\n progress+=\"%4.1f%%\"%(100*pos/stats['size'])\n eta=stats['size']/(pos/td) - td\n te=\"%02d:%02d\"%(eta/60%60,eta%60)\n if eta>60*60:\n te=\"%02d:\"%(eta/60/60)+te\n progress+=\"/\"+te\n if progress:\n hdr+=\" [%s]\"%progress\n else:\n hdr+=\" l:%6d\"%stats['in']\n if output=='zmq':\n hdr+=\" %2d clients\"%stats['clients']\n print (hdr, \"[%.1f l/s] filtered:%3d%%\"%((nowl-lline)/(now-ltime),100*(1-stats['out']/(stats['in'] or 1))), end=eol, file=statsfile)\n ltime=now\n lline=nowl\n print (hdr, \"[%.1f l/s] drop:%3d%%\"%((nowl)/(now-stime),100*(1-stats['out']/(stats['in'] or 1))), end=eolnl, file=statsfile)\n\nselected=[]\n\ndef openhook(filename, mode):\n ext = os.path.splitext(filename)[1]\n if ext == '.gz':\n import gzip\n return gzip.open(filename, 'rt')\n elif ext == '.bz2':\n import bz2\n return bz2.open(filename, 'rt')\n elif ext == '.xz':\n import lzma\n return lzma.open(filename, 'rt')\n else:\n return open(filename, 'rt')\n\ndef do_input(type):\n if type==\"raw\":\n if do_stats:\n stats['files']=len(remainder)\n stats['fileno']=0\n for line in fileinput.input(remainder, openhook=openhook):\n if do_stats:\n if fileinput.isfirstline():\n stats['fileno']+=1\n stat=os.fstat(fileinput.fileno())\n stats['size']=stat.st_size\n stats['in']+=1\n if good:\n q=bitsparser.Message(line.strip())\n try:\n if q.confidence0):\n return\n q.descramble_extra=\"\"\n if errorfree:\n if q.error:\n return\n q.descramble_extra=\"\"\n if linefilter['type']!=\"All\" and type(q).__name__ != linefilter['type']:\n return\n if linefilter['attr'] and linefilter['attr'] not in q.__dict__:\n return\n if linefilter['check'] and not eval(linefilter['check']):\n return\n if do_stats:\n stats[\"out\"]+=1\n if vdumpfile != None and type(q).__name__ == \"IridiumVOMessage\":\n if len(q.voice)!=312:\n raise Exception(\"illegal Voice frame length\")\n for bits in slice(q.voice, 8):\n byte = int(bits[::-1],2)\n vdumpfile.write(chr(byte))\n if output == \"err\":\n if(q.error):\n selected.append(q)\n elif output == \"sat\":\n if not q.error:\n selected.append(q)\n elif output == \"dump\":\n pickle.dump(q,file,1)\n elif output == \"plot\":\n selected.append(q)\n elif output == \"line\":\n if (q.error):\n print(q.pretty()+\" ERR:\"+\", \".join(q.error_msg))\n else:\n if not ofmt:\n print(q.pretty())\n else:\n print(\" \".join([str(q.__dict__[x]) for x in ofmt]))\n elif output == \"zmq\":\n socket.send_string(q.pretty())\n elif output == \"rxstats\":\n print(\"RX\",\"X\",q.globaltime, q.frequency,\"X\",\"X\", q.confidence, q.level, q.symbols, q.error, type(q).__name__)\n elif output == \"sigmf\":\n try:\n sr=sigmfjson['global'][\"core:sample_rate\"]\n center=sigmfjson['captures'][0][\"core:frequency\"]\n except TypeError:\n sr=10e6\n center=1626000000\n SYMBOLS_PER_SECOND = 25000\n if q.error:\n desc=q.error_msg[0]\n elif \"msgtype\" in q.__dict__:\n desc=\"\"\n if q.uplink:\n desc+=\"UL\"\n else:\n desc+=\"DL\"\n desc+=\"_\"+q.msgtype\n else:\n desc=type(q).__name__\n print(json.dumps({\n \"core:comment\": \"Frame #%d: \"%int(q.id)+type(q).__name__,\n \"core:description\": desc+\"#%d\"%int(q.id),\n \"core:freq_lower_edge\": q.frequency-20e3,\n \"core:freq_upper_edge\": q.frequency+20e3,\n \"core:sample_count\": int(q.symbols * (sr/SYMBOLS_PER_SECOND)),\n \"core:sample_start\": int(q.timestamp * (sr/1000))\n }), end=\",\\n\", file=sigmfout)\n else:\n print(\"Unknown output mode.\", file=sys.stderr)\n exit(1)\n\ndef bitdiff(a, b):\n return sum(x != y for x, y in zip(a, b))\n\nif do_stats:\n from threading import Thread, Event\n stats['start']=time.time()\n stats['in']=0\n stats['out']=0\n stats['stop']= Event()\n sthread = Thread(target = stats_thread, args = [stats], daemon= True, name= 'stats')\n sthread.start()\n\ntry:\n do_input(input)\nexcept KeyboardInterrupt:\n pass\n\nif do_stats:\n stats['stop'].set()\n sthread.join()\n\nif output=='zmq':\n socket.close()\n context.term()\n\nif sigmffile is not None:\n import os\n print(\"{}]}\", file=sigmfout)\n sigmfout.close()\n os.rename(sigmffile, sigmffile+\".bak\")\n os.rename(sigmffile+\".tmp\", sigmffile)\n\nif output == \"sat\":\n print(\"SATs:\")\n sats=[]\n for m in selected:\n f=m.frequency\n t=m.globalns/1e9\n no=-1\n for s in range(len(sats)):\n fdiff=(sats[s][0]-f)//(t+.000001-sats[s][1])\n if f-1:\n m.fdiff=(sats[no][0]-f)//(t-sats[no][1])\n sats[no][0]=f\n sats[no][1]=t\n else:\n no=len(sats)\n sats.append([f,t])\n m.fdiff=0\n m.satno=no\n for s in range(len(sats)):\n print(\"Sat: %03d\"%s)\n for m in selected:\n if m.satno == s: print(m.pretty())\n\nif isinstance(errorstats, collections.abc.Mapping):\n total=0\n for (msg,count) in sorted(errorstats.items()):\n total+=count\n print(\"%7d: %s\"%(count, msg), file=sys.stderr)\n print(\"%7d: %s\"%(total, \"Total\"), file=sys.stderr)\n\nif output == \"err\":\n print(\"### \")\n print(\"### Error listing:\")\n print(\"### \")\n sort={}\n for m in selected:\n msg=m.error_msg[0]\n if(msg in sort):\n sort[msg].append(m)\n else:\n sort[msg]=[m]\n for msg in sort:\n print(msg+\":\")\n for m in sort[msg]:\n print(\"- \"+m.pretty())\n\ndef plotsats(plt, _s, _e):\n for ts in range(int(_s),int(_e),10):\n for v in satclass.timelist(ts):\n plt.scatter( x=v[0], y=v[1], c=int(v[2]), alpha=0.3, edgecolor=\"none\", vmin=10, vmax=90)\n\nif output == \"plot\":\n name=\"%s over %s\"%(plotargs[1],plotargs[0])\n if len(plotargs)>2:\n name+=\" with %s\"%plotargs[2]\n filter=\"\"\n if len(linefilter)>0 and linefilter['type']!=\"All\":\n filter+=\"type==%s\"%linefilter['type']\n name=(\"%s \"%linefilter['type'])+name\n if linefilter['attr']:\n filter+=\" containing %s\"%linefilter['attr']\n name+=\" having %s\"%linefilter['attr']\n if linefilter['check']:\n x=linefilter['check']\n if x.startswith(\"q.\"):\n x=x[2:]\n filter+=\" and %s\"%x\n name+=\" where %s\"%x\n plt.suptitle(filter)\n plt.xlabel(plotargs[0])\n plt.ylabel(plotargs[1])\n if plotargs[0]==\"time\":\n plotargs[0]=\"globalns\"\n def format_date(x, pos=None):\n return datetime.datetime.fromtimestamp(x/10**9).strftime('%Y-%m-%d %H:%M:%S')\n plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(format_date))\n plt.gcf().autofmt_xdate()\n\n if False:\n plotsats(plt,selected[0].globaltime,selected[-1].globaltime)\n\n for m in selected:\n xl.append(m.__dict__[plotargs[0]])\n yl.append(m.__dict__[plotargs[1]])\n if len(plotargs)>2:\n cl.append(m.__dict__[plotargs[2]])\n\n if len(plotargs)>2:\n plt.scatter(x = xl, y= yl, c= cl)\n plt.colorbar().set_label(plotargs[2])\n else:\n plt.scatter(x = xl, y= yl)\n\n mng = plt.get_current_fig_manager()\n mng.resize(*mng.window.maxsize())\n plt.savefig(re.sub(r'[/ ]','_',name)+\".png\")\n plt.show()\n","sub_path":"iridium-parser.py","file_name":"iridium-parser.py","file_ext":"py","file_size_in_byte":17011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255985057","text":"#-*- encode: utf-8 -*-\nfrom apps.categorizacion.helpers.debug_printer import dprint\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.template.defaultfilters import filesizeformat\nfrom django.core.exceptions import ValidationError\nfrom utils.forms_helpers import ModelFormBaseClass\nfrom django.db.models.loading import get_model\nfrom apps.categorizacion.models import *\nfrom django.db.models import FileField\nfrom django.db import models\nfrom django import forms\nfrom os import path\nimport sys\n\n\nEXTS_CONTENT_TYPE = {\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'pdf': 'application/pdf',\n 'png': 'image/png',\n}\n\n\ndef validate_negative(value):\n\tif value < 0:\n\t\traise ValidationError('Este campo debe ser mayor a 0')\n\ndef max_integer(value):\n\tif value > sys.maxint:\n\t\traise ValidationError('Este valor es demasiado grande')\n\ndef max_float(value):\n\tif value > sys.float_info.max:\n\t\traise ValidationError('Este valor es demasiado grande')\n\n\ndef validator_file(data, rf, content_types, max_upload_size):\n\tsize= rf.size\n\tcontent_type= rf.content_type\n\tdprint(\"hello\")\n\tfobj = data\n\tif content_type in content_types:\n\t\tif size > max_upload_size:\t\t\t\n\t\t\treturn False\n\telse:\n\t\treturn False\n\treturn content_type\n\n\ndef validate_file_type(rf,e, content_types, max_upload_size):\n\tclass ModeloTrap(models.Model):\t \n\t archivo_upload = FileField(\n\t null = True,\n\t blank = True,\n\t max_length = 255,\n\t upload_to = \"/\",\n\t )\n\n\tclass Validador(forms.ModelForm):\n\t class Meta:\n\t model = ModeloTrap\n\n\tform = Validador(rf)\n\t\n\tif form.is_valid():\n\t\tarchive = FileField(\n\t\t\tform.fields['archivo_upload'], \n\t\t\tmax_length = 255, upload_to = \"/\",\n\t\t)\n\t\treturn validator_file(archive,rf[e], content_types, max_upload_size)\t\t\n\telse:\n\t\treturn False\n","sub_path":"apps/categorizacion/helpers/validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578514767","text":"from turtle import *\n\nspeed('fastest')\n\n# turning the turtle to face upwards\nright(-90)\n\n# the acute angle between\n# the base and branch of the Y\nangle = 30\n\n\n# function to plot a Y\ndef tree(size, level):\n if level > 0:\n colormode(255)\n\n # splitting the rgb range for green\n # into equal intervals for each level\n # setting the colour according\n # to the current level\n pencolor(0, 255 // level, 0)\n\n # drawing the base\n forward(size)\n\n right(angle)\n\n # recursive call for\n # the right subtree\n tree(0.8 * size, level - 1)\n\n pencolor(0, 255 // level, 0)\n\n left(2 * angle)\n\n # recursive call for\n # the left subtree\n tree(0.8 * size, level - 1)\n\n pencolor(0, 255 // level, 0)\n\n right(angle)\n forward(-size)\n\n\n# tree of size 70 and level 7\ntree(70, 7)\n\ndone()\n","sub_path":"fractal.py","file_name":"fractal.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284621060","text":"import os\n# import skimage.io\nimport cv2\nimport sys\n\nlanenet_path = '/aimldl-cod/external/lanenet-lane-detection'\n\nif lanenet_path not in sys.path:\n sys.path.insert(0, lanenet_path)\n\nfrom lanenet_model import lanenet\nfrom lanenet_model import lanenet_postprocess\n\npath='/aimldl-dat/rld-samples/tusimple'\nimage_name = '1492626270684175793-20.jpg'\nbinary_seg_image = cv2.imread(os.path.join(path,'binary_mask_image-1492626270684175793-20-151019_140034.png'), cv2.IMREAD_UNCHANGED)\ninstance_seg_image = cv2.imread(os.path.join(path,'instance_mask_image-1492626270684175793-20-151019_140034.png'), cv2.IMREAD_UNCHANGED)\nimage_vis = cv2.imread(os.path.join(path,image_name), cv2.IMREAD_COLOR)\n\n\npostprocessor = lanenet_postprocess.LaneNetPostProcessor()\n\npostprocess_result = postprocessor.postprocess(\n binary_seg_result=binary_seg_image,\n instance_seg_result=instance_seg_image,\n source_image=image_vis,\n image_name=image_name\n)\n\nprint(\"postprocess_result: {}\".format(postprocess_result))","sub_path":"tools/test_postprocessor.py","file_name":"test_postprocessor.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"211523317","text":"good_nums = [1,2,3,4,5]\nbad_nums = [7,8,9,10]\n\ndef s_search(my_nums, target):\n ans = 'False'\n for num in my_nums:\n if target == num:\n ans = 'True'\n print(ans)\n\n# Call function Here\ns_search(good_nums, 7)\n","sub_path":"warmup/while/s_search.py","file_name":"s_search.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"596698066","text":"import sys\nfrom PySide2.QtWidgets import *\n#\timport (QApplication, QLabel, QPushButton, QVBoxLayout, QWidget)\nfrom PySide2.QtCore import Slot, Qt\n\nclass DemoWidget(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n \n self.textlabel = QLabel(\"Start Text\")\n self.text2change = QLabel(\"\")\n self.button = QPushButton(\"Click me!\")\n self.textbox = QLineEdit(self)\n \n self.layout = QVBoxLayout()\n \n self.layout.addWidget(self.textbox)\n self.layout.addWidget(self.text2change)\n self.layout.addWidget(self.textlabel)\n self.layout.addWidget(self.button)\n \n self.setLayout(self.layout)\n \n self.button.clicked.connect(self.press)\n self.textbox.textChanged.connect(self.text_change)\n \n @Slot()\n def press(self):\n self.textlabel.setText('Button Pressed!')\n\n '''\n neues QLabel und bei jedem change Signal von textbox, den text \n neu setzen\n '''\n \n @Slot()\n def text_change(self):\n self.text2change.setText(self.textbox.text())\n \n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n widget = DemoWidget()\n widget.resize(400,400)\n widget.show()\n \n sys.exit(app.exec_())","sub_path":"023-qt/qt-demo.py","file_name":"qt-demo.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"596077265","text":"import maya.cmds as cmds\nimport sgBFunction_ui\nimport sgBFunction_dag\nimport sgBFunction_selection\nimport os\nfrom functools import partial\nfrom maya.OpenMaya import MGlobal\n\n\n\nclass WinA_Global:\n \n winName = \"sgExportKey\"\n title = \"Export Key\"\n width = 500\n height = 50\n titleBarMenu = True\n \n exportPath_txf = ''\n exportType_radio = ''\n searchFor_txf = ''\n \n searchFor_txf = ''\n \n searchForType_radio = ''\n searchForType_check = ''\n searchForType_txf = ''\n \n fld_startFrame = ''\n fld_endFrame = ''\n \n chk_exportByMatrix =''\n \n import sgBFunction_fileAndPath\n infoFolderPath = sgBFunction_fileAndPath.getLocusCommPackagePrefsPath() + '/sgPWindow_data_key_export'\n infoPathPath = sgBFunction_fileAndPath.getLocusCommPackagePrefsPath() + '/sgPWindow_data_key/filePath.txt'\n infoPath = sgBFunction_fileAndPath.getLocusCommPackagePrefsPath() + '/sgPWindow_data_key_export/info.txt'\n \n \n\n\n\nclass WinA_Title:\n \n def __init__(self, label, bgc, h=30 ):\n \n self.label = label\n self.height = h\n self.bgc = bgc\n \n def create(self):\n \n form = cmds.formLayout( bgc=self.bgc )\n \n text = cmds.text( l= self.label, h=self.height, al='center' )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1,\n af=[( text, 'top', 0 ), ( text, 'left', 0 ), ( text, 'right', 0 )])\n \n self.form = form\n return form\n\n\n\n\nclass WinA_ExportPath:\n \n def __init__(self, label, w, h, al ):\n \n self.label = label\n self.width = w\n self.height = h\n self.aline = al\n\n\n def create(self):\n \n form = cmds.formLayout()\n \n text = cmds.text( l=self.label, w=self.width, h=self.height, al= self.aline )\n txf = cmds.textField( h = self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af = [( text, 'top', 0 ), ( text, 'left', 0 ),\n ( txf, 'top', 0 ), ( txf, 'right', 0 )],\n ac = [( txf, 'left', 0, text )] )\n \n WinA_Global.exportPath_txf = txf\n WinA_Global.exportPath_form = form\n \n return form\n\n\n\n\n\nclass WinA_ExportType:\n \n def __init__(self, label, type1Label, type2Label, type3Label, **options ):\n \n self.label = label\n self.type1 = type1Label\n self.type2 = type2Label\n self.type3 = type3Label\n self.options = options\n\n \n def create(self):\n \n form = cmds.formLayout()\n text = cmds.text( l=self.label, **self.options )\n radio = cmds.radioCollection()\n rb1 = cmds.radioButton( l=self.type1, sl=1 )\n rb2 = cmds.radioButton( l=self.type2 )\n rb3 = cmds.radioButton( l=self.type3 )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af=[( text, 'top', 0 ), ( text, 'left', 0 ),\n ( rb1, 'top', 0 )],\n ac=[( rb1, 'left', 0, text ),\n ( rb2, 'left', 0, text ), ( rb2, 'top', 0, rb1 ),\n ( rb3, 'left', 0, text ), ( rb3, 'top', 0, rb2 )] )\n \n WinA_Global.exportType_radio = radio\n WinA_Global.exportType_form = form\n \n return form\n\n\n\n\n\nclass WinA_searchFor:\n \n def __init__(self, label, w1, w2, h, al ):\n \n self.label = label\n self.width1 = w1\n self.width2 = w2\n self.height = h\n self.aline = al\n \n\n def create(self):\n \n form = cmds.formLayout()\n text = cmds.text( l=self.label, w=self.width1, h=self.height, al = self.aline )\n txf = cmds.textField( w= self.width2, h = self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af = [( text, 'top', 0 ), ( text, 'left', 0 ),\n ( txf, 'top', 0 )],\n ac = [( txf, 'left', 0, text )] )\n \n WinA_Global.searchFor_txf = txf\n WinA_Global.searchFor_form = form\n \n return form\n\n\nclass WinA_searchForType:\n \n def __init__(self, label, rbLabel1, rbLabel2, rbLabel3, rbLabel4, \n w1, w2, w3, w4, h, al ):\n \n self.label = label\n self.rbLabel1 = rbLabel1\n self.rbLabel2 = rbLabel2\n self.rbLabel3 = rbLabel3\n self.rbLabel4 = rbLabel4\n self.width1 = w1\n self.width2 = w2\n self.width3 = w3\n self.width4 = w4\n self.height = h\n self.aline = al\n \n \n def create(self):\n \n form = cmds.formLayout()\n text = cmds.text( l= self.label, w=self.width1, h=self.height, al= self.aline )\n radio = cmds.radioCollection()\n rb1 = cmds.radioButton( l=self.rbLabel1, w=self.width2, sl=1 )\n rb2 = cmds.radioButton( l=self.rbLabel2, w=self.width3 )\n rb3 = cmds.radioButton( l=self.rbLabel3, w=self.width4 )\n check = cmds.checkBox( l=self.rbLabel4 )\n txf = cmds.textField( en=0 )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1,\n af = [( text, 'top', 0 ),( text, 'left', 0 ),\n ( rb1, 'top', 0 ), ( rb2, 'top', 0 ), ( rb3, 'top', 0 )],\n ac = [( rb1, 'left', 0, text ), ( rb2, 'left', 0, rb1 ), ( rb3, 'left', 0, rb2 ),\n ( check, 'top', 0, text ), ( check, 'left', 0, text ),\n ( txf, 'top', 0, text ), ( txf, 'left', 0, check )] )\n \n WinA_Global.searchForType_radio = radio\n WinA_Global.searchForType_check = check\n WinA_Global.searchForType_txf = txf\n WinA_Global.searchForType_form = form\n \n return form\n\n\n\n\nclass WinA_TimeRanges:\n \n def __init__(self, label1, label2, w1, w2, h ):\n \n self.label1 = label1\n self.label2 = label2\n self.width1 = w1\n self.width2 = w2\n self.height = h\n \n \n def create(self):\n \n form = cmds.formLayout()\n text1 = cmds.text( l= self.label1, w=self.width1, h=self.height, al='right' )\n text2 = cmds.text( l= self.label2, w=self.width1, h=self.height, al='right' )\n field1 = cmds.intField( w=self.width2, h=self.height )\n field2 = cmds.intField( w=self.width2, h=self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af=[( text1, 'top', 0 ), ( text1, 'left', 0 ),\n ( text2, 'top', 0 )],\n ac=[( text1, 'right', 0, field1 ), ( field2, 'left', 0, text2 )],\n ap=[( field1, 'right', 0, 50 ),( text2, 'left', 0, 50 )] )\n \n WinA_Global.fld_startFrame = field1\n WinA_Global.fld_endFrame = field2\n \n self.form = form\n return form\n\n\n\n\nclass WinA_ExportByMatrix:\n \n def __init__(self, label, w=1, h=1 ):\n \n self.label = label\n self.width = w\n self.height = h\n \n \n def create(self):\n \n form = cmds.formLayout()\n checkbox = cmds.checkBox( l= self.label, h= self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1, \n af = [( checkbox, 'left', self.width )])\n \n WinA_Global.chk_exportByMatrix = checkbox\n \n self.form = form\n \n return form\n \n\n\n\n\nclass WinA_Buttons:\n \n def __init__(self, label1, label2, h ):\n \n self.label1 = label1\n self.label2 = label2\n self.height = h\n \n \n def create(self):\n \n form = cmds.formLayout()\n button1 = cmds.button( l= self.label1, h=self.height )\n button2 = cmds.button( l= self.label2, h=self.height )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1,\n af =[ ( button1, 'top', 0 ), ( button1, 'left', 0 ),\n ( button2, 'top', 0 ), ( button2, 'right', 0 ) ],\n ap = [( button1, 'right', 0, 50 ), ( button2, 'left', 0, 50 )])\n\n return form\n \n \n \n \nclass WinA_Cmd:\n \n @staticmethod\n def setWindowCondition( *args ):\n \n i = WinA_Cmd.getExportType()\n \n if i == 0: enable = False \n else: enable = True\n cmds.formLayout( WinA_Global.searchFor_form, e=1, en=enable )\n cmds.formLayout( WinA_Global.searchFor_form, e=1, en=enable )\n cmds.formLayout( WinA_Global.searchForType_form, e=1, en=enable )\n \n check = cmds.checkBox( WinA_Global.searchForType_check, q=1, v=1 )\n if check: enable = True\n else: enable = False\n cmds.textField( WinA_Global.searchForType_txf, e=1, en= enable )\n \n \n @staticmethod\n def getExportType():\n\n items = cmds.radioCollection( WinA_Global.exportType_radio, q=1, cia=1 )\n \n for i in range( len( items ) ):\n if cmds.radioButton( items[i], q=1, sl=1 ):\n break\n return i\n \n \n @staticmethod\n def getSearchForType():\n \n items = cmds.radioCollection( WinA_Global.searchForType_radio, q=1, cia=1 )\n for i in range( len( items ) ):\n if cmds.radioButton( items[i], q=1, sl=1 ):\n break\n return i\n \n \n @staticmethod\n def getSplitName():\n \n check = cmds.checkBox( WinA_Global.searchForType_check, q=1, v=1 )\n searchForTypeText = cmds.textField( WinA_Global.searchForType_txf, q=1, tx=1 )\n \n if not check: return ''\n return searchForTypeText\n \n \n @staticmethod\n def read_windowInfo():\n \n import cPickle\n import sgBFunction_fileAndPath\n \n if not os.path.exists( WinA_Global.infoPath ):\n sgBFunction_fileAndPath.makeFile( WinA_Global.infoPath )\n \n try:\n f = open( WinA_Global.infoPath, 'r' )\n data = cPickle.load( f )\n f.close()\n except: return None\n \n if not data: return None\n \n try:exportPath, exportType, searchFor, searchForType, splitStringAndSerchCheck, splitStringAndSearchString, exportByMatrix = data\n except: return None\n \n cmds.textField( WinA_Global.exportPath_txf, e=1, tx= exportPath )\n items = cmds.radioCollection( WinA_Global.exportType_radio, q=1, cia=1 )\n cmds.radioButton( items[ exportType ], e=1, sl=1 )\n cmds.textField( WinA_Global.searchFor_txf, e=1, tx=searchFor )\n items = cmds.radioCollection( WinA_Global.searchForType_radio, q=1, cia=1 )\n cmds.radioButton( items[ searchForType ], e=1, sl=1 )\n cmds.checkBox( WinA_Global.searchForType_check, e=1, v=splitStringAndSerchCheck )\n cmds.textField( WinA_Global.searchForType_txf, e=1, tx=splitStringAndSearchString )\n cmds.checkBox( WinA_Global.chk_exportByMatrix, e=1, v= exportByMatrix )\n \n @staticmethod\n def write_windowInfo():\n \n exportPath = cmds.textField( WinA_Global.exportPath_txf, q=1, tx=1 )\n exportType = WinA_Cmd.getExportType()\n searchFor = cmds.textField( WinA_Global.searchFor_txf, q=1, tx=1 )\n searchForType = WinA_Cmd.getSearchForType()\n splitStringAndSearchCheck = cmds.checkBox( WinA_Global.searchForType_check, q=1, v=1 )\n splitStringAndSearchString = cmds.textField( WinA_Global.searchForType_txf, q=1, tx=1 )\n exportByMatrix = cmds.checkBox( WinA_Global.chk_exportByMatrix, q=1, v=1 )\n \n data = [ exportPath, exportType, searchFor, searchForType, splitStringAndSearchCheck, splitStringAndSearchString, exportByMatrix ]\n \n import cPickle\n import sgBFunction_fileAndPath\n sgBFunction_fileAndPath.makeFolder( WinA_Global.infoFolderPath )\n sgBFunction_fileAndPath.makeFile( WinA_Global.infoPathPath, False )\n f = open( WinA_Global.infoPath, 'w' )\n cPickle.dump( data, f )\n f.close()\n \n f = open( WinA_Global.infoPathPath, 'w' )\n cPickle.dump( exportPath, f )\n f.close()\n \n \n @staticmethod\n def splitStringEnable( *args ):\n \n check = cmds.checkBox( WinA_Global.searchForType_check, q=1, v=1 )\n if check:\n cmds.textField( WinA_Global.searchForType_txf, e=1, en=1 )\n else:\n cmds.textField( WinA_Global.searchForType_txf, e=1, en=0 )\n \n \n @staticmethod\n def export( *args ):\n\n import sgBExcute_data\n import sgBFunction_fileAndPath\n \n WinA_Cmd.write_windowInfo()\n path = cmds.textField( WinA_Global.exportPath_txf, q=1, tx=1 )\n \n if not os.path.exists( path ):\n try:\n sgBFunction_fileAndPath.makeFolder( path ) \n except:\n cmds.error( '\"%s\" is not exist path' % path )\n return None\n \n if not os.path.isdir( path ):\n cmds.error( '\"%s\" is not Directory' % path )\n return None\n\n path = cmds.textField( WinA_Global.exportPath_txf, q=1, tx=1 )\n startFrame = cmds.intField( WinA_Global.fld_startFrame, q=1, v=1 )\n endFrame = cmds.intField( WinA_Global.fld_endFrame, q=1, v=1 )\n exportTargets = WinA_Cmd.getExportTargets()\n exportByMatrix = cmds.checkBox( WinA_Global.chk_exportByMatrix, q=1, v=1 )\n if not exportTargets:\n cmds.error( 'Target is not exists' )\n else:\n sgBExcute_data.exportSgKeyData( exportTargets, startFrame, endFrame, path, exportByMatrix )\n\n\n @staticmethod\n def getExportTargets( *args ):\n \n exportTargets = []\n \n def searchIsRight( tr, searchForType, searchFor, splitName ):\n if splitName: compairTr = tr.split( splitName )[-1]\n else: compairTr = tr\n if searchForType == 0 and compairTr.find( searchFor ) != -1:\n return True\n elif searchForType == 1 and compairTr[ :len(searchFor) ] == searchFor:\n return True\n elif searchForType == 2 and compairTr[ -len( searchFor ): ] == searchFor:\n return True\n \n exportType = WinA_Cmd.getExportType()\n if exportType == 0:\n \n meshObjs = sgBFunction_selection.getMeshObjectFromGroup( cmds.ls( sl=1 ) )\n\n parents = []\n for sel in meshObjs:\n parents += sgBFunction_dag.getParents( sel )\n parents = list( set( parents ) )\n targetParents = []\n for parent in parents:\n if not sgBFunction_dag.itHasTransformConnection( parent ): continue\n targetParents.append( parent )\n\n for meshObj in meshObjs:\n if not sgBFunction_dag.itHasTransformConnection( meshObj ): continue\n exportTargets.append( meshObj )\n exportTargets += targetParents;\n \n elif exportType == 1:\n searchFor = cmds.textField( WinA_Global.searchFor_txf, q=1, tx=1 )\n searchForType = WinA_Cmd.getSearchForType()\n splitName = WinA_Cmd.getSplitName()\n if not searchFor: cmds.error( \"Check Search For String\" )\n \n targets = []\n for tr in cmds.ls( tr=1 ):\n if searchIsRight( tr, searchForType, searchFor, splitName ):\n targets.append( tr )\n \n parents = []\n for target in targets:\n parents += sgBFunction_dag.getParents( target )\n parents = list( set( parents ) )\n \n targetParents = []\n for parent in parents:\n if not sgBFunction_dag.itHasTransformConnection( parent ): continue\n targetParents.append( parent )\n \n meshObjs = sgBFunction_selection.getMeshObjectFromGroup( targets )\n for meshObj in meshObjs:\n if not sgBFunction_dag.itHasTransformConnection( meshObj ): continue\n exportTargets.append( meshObj )\n exportTargets += targetParents;\n \n elif exportType == 2:\n searchFor = cmds.textField( WinA_Global.searchFor_txf, q=1, tx=1 )\n searchForType = WinA_Cmd.getSearchForType()\n splitName = WinA_Cmd.getSplitName()\n if not searchFor: cmds.error( \"Check Search For String\" )\n \n targets = []\n trChildren = cmds.listRelatives( cmds.ls( sl=1 ), c=1, ad=1, f=1, type='transform' )\n trChildren += cmds.ls( sl=1 )\n for tr in trChildren:\n if searchIsRight( tr, searchForType, searchFor, splitName ):\n targets.append( tr )\n \n parents = []\n for target in targets:\n parents += sgBFunction_dag.getParents( target )\n parents = list( set( parents ) )\n \n targetParents = []\n for parent in parents:\n if not sgBFunction_dag.itHasTransformConnection( parent ): continue\n targetParents.append( parent )\n \n meshObjs = sgBFunction_selection.getMeshObjectFromGroup( targets )\n for meshObj in meshObjs:\n if not sgBFunction_dag.itHasTransformConnection( meshObj ): continue\n exportTargets.append( meshObj )\n exportTargets += targetParents;\n \n return exportTargets\n\n @staticmethod\n def setDefaultUICondition( *args ):\n\n minValue = cmds.playbackOptions( q=1, min=1 )\n maxValue = cmds.playbackOptions( q=1, max=1 )\n cmds.intField( WinA_Global.fld_startFrame, e=1, v=minValue )\n cmds.intField( WinA_Global.fld_endFrame, e=1, v=maxValue )\n\n\n\n\n\nclass WinA:\n\n def __init__(self):\n\n self.uiExportPath = WinA_ExportPath( \"Export Path : \", w=120, h=22, al='right' )\n self.uiExportType = WinA_ExportType( \"Export Type : \", \n \"Export By Selection\", \"Export By Name \", \"Export By Name And Selection\",\n w=120, h=22, al='right' )\n self.uisearchFor = WinA_searchFor( \"Search For : \", w1= 120, w2=150, h=21, al='right' )\n self.uisearchForType = WinA_searchForType( \"Search For Type : \", \"Any position\", \"Start position\", \"End Position\", \n \"Split String and Search :\",\n w1= 120, w2=110, w3=110, w4=110, h=22, al='right' )\n self.uiTimeRanges = WinA_TimeRanges( \"Start Frame : \", \"End Frame : \", 120, 50, 22 )\n self.uiCheckbox = WinA_ExportByMatrix( \"Export by Matrix\", 100, 22 )\n \n self.uiButtons = WinA_Buttons( \"Export\", \"Close\", 30 )\n\n\n def create(self):\n \n if cmds.window( WinA_Global.winName, ex=1 ):\n cmds.deleteUI( WinA_Global.winName, wnd=1 )\n cmds.window( WinA_Global.winName, title = WinA_Global.title, titleBarMenu = WinA_Global.titleBarMenu )\n \n form = cmds.formLayout()\n exportPathForm = self.uiExportPath.create()\n exportTypeForm = self.uiExportType.create()\n searchForForm = self.uisearchFor.create()\n searchForTypeForm = self.uisearchForType.create()\n timeRanges = self.uiTimeRanges.create()\n separator = cmds.separator()\n checkbox = self.uiCheckbox.create()\n buttonsForm = cmds.button( l='<< EXPORT K E Y >>', bgc=[0.6,0.5,0.5], h=30 )\n cmds.setParent( '..' )\n \n cmds.formLayout( form, e=1,\n af = [( exportPathForm, 'top', 8 ), ( exportPathForm, 'left', 0 ), ( exportPathForm, 'right', 5 ),\n ( exportTypeForm, 'left',0 ), ( exportTypeForm, 'right', 0 ),\n ( searchForForm, 'left', 0 ),\n ( searchForTypeForm, 'left', 0 ),\n ( timeRanges, 'left', 0 ), ( timeRanges, 'right', 0 ),\n ( separator, 'left', 0 ),( separator, 'right', 0 ),\n ( checkbox, 'left', 0 ),\n ( buttonsForm, 'left', 0 ), ( buttonsForm, 'right', 0 ) ],\n ac = [( exportTypeForm, 'top', 8, exportPathForm ),\n ( searchForForm, 'top', 8, exportTypeForm ),\n ( searchForTypeForm, 'top', 8, searchForForm ),\n ( timeRanges, 'top', 8, searchForTypeForm ),\n ( separator, 'top', 12, timeRanges ),\n ( checkbox, 'top', 8, separator ),\n ( buttonsForm, 'top', 8, checkbox )] )\n\n cmds.window( WinA_Global.winName, e=1,\n w = WinA_Global.width, h = WinA_Global.height )\n cmds.showWindow( WinA_Global.winName )\n\n self.button = buttonsForm\n self.setUiCommand()\n\n WinA_Cmd.read_windowInfo()\n WinA_Cmd.setDefaultUICondition()\n WinA_Cmd.setWindowCondition()\n\n\n def setUiCommand(self):\n \n cmds.button( self.button, e=1, c= WinA_Cmd.export )\n \n items = cmds.radioCollection( WinA_Global.exportType_radio, q=1, cia=1 )\n for item in items:\n cmds.radioButton( item, e=1, cc= WinA_Cmd.setWindowCondition )\n \n cmds.checkBox( WinA_Global.searchForType_check, e=1, cc= WinA_Cmd.splitStringEnable )\n \n exportPathPopup = cmds.popupMenu( p=WinA_Global.exportPath_txf )\n sgBFunction_ui.updatePathPopupMenu( WinA_Global.exportPath_txf, exportPathPopup )\n\n\n\nmc_showWindow = \"\"\"import sgPWindow_data_key_export\nsgPWindow_data_key_export.WinA().create()\"\"\"","sub_path":"maya_tools_backup/3dGroupTools/python/sgPWindow_data_key_export.py","file_name":"sgPWindow_data_key_export.py","file_ext":"py","file_size_in_byte":22161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"635971969","text":"\"\"\"Basic functionality for iterated maps\"\"\"\n\nimport scipy\nfrom matplotlib import pylab\n\ndef Iterate(g, x0, N):\n \"\"\"\n Iterate the function g N times, starting at x0, with extra parameters\n passed in as a tuple args. Return g(g(...(g(x))...)). Used to find a \n point on the attractor starting from some arbitrary point x0.\n\n Calling Iterate for the Feigenbaum map at mu=0.9 would look like\n Iterate(logistic_map(0.9), 0.1, 1000)\n \"\"\"\n \n for i in xrange(N):\n x0 = g(x0)\n return x0\n\ndef IterateArray(g, x0, N):\n \"\"\"Iterate the function g N-1 times, starting at x0\n\n Returns the entire list \n (x, g(x), g(g(x)), ... g(g(...(g(x))...))). \n\n Can be used to explore the dynamics starting from an arbitrary point \n x0, or to explore the attractor starting from a point x0 on the \n attractor (say, initialized using Iterate).\n\n For example, you can use Iterate to find a point xAttractor on the \n attractor and IterateArray to create a long series of points attractorXs\n (thousands, or even millions long, if you're in the chaotic region), \n and then use\n pylab.hist(attractorXs, bins=500, normed=1)\n pylab.show()\n to see the density of points.\n \"\"\"\n xs = scipy.empty(N,scipy.Float)\n xs[0] = float(x0)\n for i in xrange(1,N):\n xs[i] = g(xs[i-1])\n return xs\n\ndef BifurcationDiagram(g, x0, nTransient, nCycle, etaArray,marker='k.'):\n \"\"\"\n For each parameter value eta in etaArray,\n iterate g nTransient times to find a point on the attractor, and then\n make a list nCycle long to explore the attractor.\n\n To generate etaArray, it's convenient to use frange: for example,\n BifurcationDiagram(f, 0.1, 500, 128, scipy.linspace(0,1,600)).\n\n Assemble the points on the attractors into a huge list xList, and the \n corresponding values of eta onto a list of the same length etaList.\n Use\n pylab.plot(etaList, xList, 'k.')\n pylab.show()\n to visualize the resulting bifurcation diagram, where 'k.' denotes \n black points.\n \"\"\"\n etaList = []\n xList = []\n ones = scipy.ones\n for eta in etaArray:\n etaList.extend([eta]*nCycle)\n f = g(eta)\n xList.extend(IterateArray(f, Iterate(f, x0, nTransient),nCycle))\n pylab.plot(etaList, xList, marker)\n","sub_path":"examples/logistic/sethna_ori/01-chaos_lyapunov/IterateMaps.py","file_name":"IterateMaps.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"338887786","text":"def plot_spectrum(MZ, I, show=True):\n \"\"\"A simple stem-plot stick spectrum.\n \n You need to have matplotlib installed for this method to work.\n \n Args:\n MZ (iterable): mass over charge values.\n I (iterable): intensities corresponding to mass over charge ratios.\n show (bool): show the plot\n \"\"\"\n import matplotlib.pyplot as plt\n plt.stem(MZ, I)\n if show:\n plt.show()\n\n\ndef plot3d(x, y, z, show=True, **kwds):\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n Axes3D.scatter(ax, xs=x, ys=y, zs=z)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n if show:\n plt.show()\n","sub_path":"timspy/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"203360045","text":"import random\n\n\n# functions\ndef question_check(question, answer_list, error_message):\n valid = False\n while not valid:\n\n response = input(question).lower()\n\n for item in answer_list:\n if response == item[0] or response == item:\n answer = item\n return answer\n\n # output error if item not in list\n print(error_message)\n print()\n\n\ndef number_checker(question, mini, maxi, error_message):\n\n valid = False\n while not valid:\n try:\n # ask the question\n response = int(input(question))\n # if the amount is too low/ too high give\n if mini < response <= maxi:\n return response\n\n else:\n print(error_message)\n except ValueError:\n print(error_message)\n\n\ndef instruction():\n print(\"instruction\")\n\n\ndef deal(pick_amount, who_deck, who_num_deck):\n for i in range(pick_amount):\n card = deck.pop()\n who_deck.append(card)\n if card == \"J\" or card == \"Q\" or card == \"K\":\n who_num_deck.append(10)\n else:\n who_num_deck.append(card)\n\n\ndef counter(add):\n count = sum(add)\n return count\n\n# ##########################LISTS###################################\n\n\nyes_no = [\"yes\", \"no\"]\n# moves\navailable_moves = [\"hit\", \"stay\", \"double up\"]\nunavailable_moves = []\ncards_amount = [\"2\", \"3\", \"4\", \"5\"]\nbank_allow = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"]\n# cards\n# user cards\nuser_deck = []\nuser_num_deck = []\nuser_total = 0\n\n# dealer cards\ndeal_deck = []\ndealer_num_deck = []\ndealer_total = 0\n\n# main\nplay = question_check(\"do you want to play BlackJack\", yes_no, \"please answer 'yes' or 'no'\")\n# want to play\nif play == \"yes\":\n # instructions\n instruct = question_check(\"do you want the instructions\", yes_no, \"please answer 'yes' or 'no'\")\n if instruct == \"yes\":\n print(instruction)\n print()\n else:\n print()\n\n deck_amount = question_check(\"how many decks do you want to play\", cards_amount, \"please pick a number from 2-5\")\n\n\n# ######################################where the loop starts?##################################\n go = \"yes\"\n while go == \"yes\":\n\n bank = number_checker(\"how much would you like to put into the bank from 1-10\", 1, 10, \"please pick a number between 1 and 10\")\n print(\"you have ${:.2f} in the bank\".format(bank))\n\n bet = number_checker(\"how much would you like to bet for this round\", 1, bank, \"please pick a number between 1 and the amount in the bank\")\n print(\"you bet ${:.2f} for this round\".format(bet))\n # shuffle deck\n deck = [\"A\", 2, 3, 4, 5, 6, 7, 8, 9, \"J\", \"K\", \"Q\"]*(int(deck_amount)*4)\n random.shuffle(deck)\n # deal 2 cards\n deal(2, user_deck, user_num_deck)\n deal(2, deal_deck, dealer_num_deck)\n # show total of user\n print(user_deck)\n user_total += counter(user_num_deck)\n print(\"your total is {}\".format(user_total))\n\n\n# don't want to play\nelse:\n print(\"you quit\")\n quit()\n","sub_path":"Black Jack/BlackJack.py","file_name":"BlackJack.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"296180386","text":"# -*- coding:utf-8 -*-\n\n\nclass ISList:\n def __init__(self, lis=None):\n self.r = lis\n\n def swap(self, i, j):\n \"\"\"定义一个交换元素的方法,方便后面调用。\"\"\"\n self.r[i], self.r[j] = self.r[j], self.r[i]\n\n def insert_sort(self):\n for i in range(len(self.r) - 1):\n curNum, preIndex = self.r[i+1], i # curNum 保存当前待插入的数\n while preIndex >= 0 and curNum < self.r[preIndex]: # 将比 curNum 大的元素向后移动\n self.r[preIndex + 1] = self.r[preIndex]\n preIndex -= 1\n self.r[preIndex + 1] = curNum # 待插入的数的正确位置\n\n def __str__(self):\n ret = \"\"\n for i in self.r:\n ret += \" %s\" % i\n return ret\n\n\nif __name__ == '__main__':\n Lis = [4, 1, 7, 3, 8, 5, 9, 2, 6]\n islist = ISList(Lis)\n islist.insert_sort()\n print(islist)\n","sub_path":"py/Insertion Sort.py","file_name":"Insertion Sort.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"381726406","text":"pares, impares, positivos, negativos = 0, 0, 0, 0\n\nfor i in range(5):\n valor = float(input())\n pares += 1 if valor % 2 == 0 else 0\n impares += 1 if valor % 2 != 0 else 0\n positivos += 1 if valor > 0 else 0\n negativos += 1 if valor < 0 else 0\n\nprint(pares, 'valor(es) par(es)')\nprint(impares, 'valor(es) impar(es)')\nprint(positivos, 'valor(es) positivo(s)')\nprint(negativos, 'valor(es) negativo(s)')\n","sub_path":"URIs/Iniciante/1066.py","file_name":"1066.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472608581","text":"from setuptools import setup, find_packages\r\n\r\nwith open('requirements.txt') as f:\r\n requirements = f.readlines()\r\n\r\nsetup(\r\n name='quantile_normalize',\r\n version='0.1',\r\n description=\"\"\"scikit-learn extension that adds quantile normalization\"\"\",\r\n url='https://github.com/r-a-qureshi/quantile_normalize/',\r\n author='Rehman Qureshi',\r\n python_requires=\">=3.6\",\r\n packages=find_packages(),\r\n install_requires=requirements,\r\n keywords=[\"quantile normalization\", \"scikit-learn\", \"sklearn\"],\r\n test_suite=\"test\",\r\n zip_safe=False,\r\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"306417230","text":"import heapq\nfrom nltk.translate.bleu_score import sentence_bleu, SmoothingFunction\nimport re\n\n\nclass TopKElement:\n def __init__(self, k):\n self.k = k\n self._id = 0\n self.queue = []\n\n def push(self, score, get_data):\n #if len(self.queue) == self.k and score < self.queue[0][0]:\n # return\n heapq.heappush(self.queue, [score, self._id, get_data()])\n self._id += 1\n while len(self.queue) > self.k:\n x = heapq.heappop(self.queue)\n\n\ndef bleu4(reference, candidate):\n sm = SmoothingFunction()\n\n def tokenize(code):\n code = re.sub(r'([^A-Za-z0-9_])', r' \\1 ', code)\n code = re.sub(r'([a-z])([A-Z])', r'\\1 \\2', code)\n code = re.sub(r'\\s+', ' ', code)\n code = re.sub(r'[\"\\']', '`', code)\n tokens = [t for t in code.split(' ') if t]\n return tokens\n\n ref = tokenize(reference)\n cand = tokenize(candidate)\n return sentence_bleu([ref],\n cand,\n weights=[0.25] * min(4, len(ref)),\n smoothing_function=sm.method3)\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"51986379","text":"from __future__ import division\n\nfrom collections import MutableSequence\nfrom copy import copy\nfrom math import *\n\ntry:\n from math import tau\nexcept ImportError:\n tau = pi * 2\n\n\"\"\"\nThis file is derived from regebro's svg.path project ( https://github.com/regebro/svg.path )\nsome of the math is from mathandy's svgpathtools project ( https://github.com/mathandy/svgpathtools ).\nThe Zingl-Bresenham plotting algorithms are from Alois Zingl's \"The Beauty of Bresenham's Algorithm\"\n( http://members.chello.at/easyfilter/bresenham.html ). They are all MIT Licensed and this library is\nalso MIT licensed. In the case of Zingl's work this isn't explicit from his website, however from personal\ncorrespondence \"'Free and open source' means you can do anything with it like the MIT licence.\"\n\nThe goal is to provide svg like path objects and structures. The svg standard 1.1 and elements of 2.0 will\nbe used to provide much of the decisions within path objects. Such that if there is a question on\nimplementation if the SVG documentation has a methodology it should be used.\n\"\"\"\n\nMIN_DEPTH = 5\nERROR = 1e-12\n\nmax_depth = 0\n\n\ndef segment_length(curve, start, end, start_point, end_point, error, min_depth, depth):\n \"\"\"Recursively approximates the length by straight lines\"\"\"\n mid = (start + end) / 2\n mid_point = curve.point(mid)\n length = abs(end_point - start_point)\n first_half = abs(mid_point - start_point)\n second_half = abs(end_point - mid_point)\n\n length2 = first_half + second_half\n if (length2 - length > error) or (depth < min_depth):\n # Calculate the length of each segment:\n depth += 1\n return (segment_length(curve, start, mid, start_point, mid_point,\n error, min_depth, depth) +\n segment_length(curve, mid, end, mid_point, end_point,\n error, min_depth, depth))\n # This is accurate enough.\n return length2\n\n\nclass Point:\n \"\"\"Point is a general subscriptable point class with .x and .y as well as [0] and [1]\n\n For compatibility with regbro svg.path we accept complex numbers as x + yj,\n and provide .real and .imag as properties. As well as float and integer values as (v,0) elements.\n\n With regard to SGV 7.15.1 defining SVGPoint this class provides for matrix transformations.\n \"\"\"\n\n def __init__(self, x, y=None):\n if y is None:\n try:\n y = x[1]\n x = x[0]\n except TypeError: # not subscriptable, must be a legacy complex\n if isinstance(x, complex):\n y = x.imag\n x = x.real\n else:\n y = 0\n self.x = x\n self.y = y\n\n def __key(self):\n return (self.x, self.y)\n\n def __hash__(self):\n return hash(self.__key())\n\n def __eq__(self, other):\n a0 = self[0]\n a1 = self[1]\n if isinstance(other, (Point, list, tuple)):\n b0 = other[0]\n b1 = other[1]\n elif isinstance(other, complex):\n b0 = other.real\n b1 = other.imag\n else:\n return NotImplemented\n c0 = abs(a0 - b0) <= ERROR\n c1 = abs(a1 - b1) <= ERROR\n return c0 and c1\n\n def __ne__(self, other):\n return not self == other\n\n def __getitem__(self, item):\n if item == 0:\n return self.x\n elif item == 1:\n return self.y\n else:\n raise IndexError\n\n def __setitem__(self, key, value):\n if key == 0:\n self.x = value\n elif key == 1:\n self.y = value\n else:\n raise IndexError\n\n def __repr__(self):\n return \"Point(%.12f,%.12f)\" % (self.x, self.y)\n\n def __copy__(self):\n return Point(self.x, self.y)\n\n def __str__(self):\n return \"(%g,%g)\" % (self.x, self.y)\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n v = other.point_in_matrix_space(self)\n self[0] = v[0]\n self[1] = v[1]\n elif isinstance(other, (int, float)): # Emulates complex point multiplication by real.\n self.x *= other\n self.y *= other\n else:\n return NotImplemented\n return self\n\n def __mul__(self, other):\n if isinstance(other, (Matrix, int, float)):\n n = copy(self)\n n *= other\n return n\n\n __rmul__ = __mul__\n\n def __iadd__(self, other):\n if isinstance(other, (Point, tuple, list)):\n self[0] += other[0]\n self[1] += other[1]\n elif isinstance(other, complex):\n self[0] += other.real\n self[1] += other.imag\n elif isinstance(other, (float, int)):\n self[0] += other\n else:\n return NotImplemented\n return self\n\n def __add__(self, other):\n if isinstance(other, (Point, tuple, list, complex, int, float)):\n n = copy(self)\n n += other\n return n\n\n __radd__ = __add__\n\n def __isub__(self, other):\n if isinstance(other, (Point, tuple, list)):\n self[0] -= other[0]\n self[1] -= other[1]\n elif isinstance(other, complex):\n self[0] -= other.real\n self[1] -= other.imag\n elif isinstance(other, (float, int)):\n self[0] -= other\n else:\n return NotImplemented\n return self\n\n def __sub__(self, other):\n if isinstance(other, (Point, tuple, list, complex, int, float)):\n n = copy(self)\n n -= other\n return n\n\n def __rsub__(self, other):\n if isinstance(other, (Point, tuple, list)):\n x = other[0] - self[0]\n y = other[1] - self[1]\n elif isinstance(other, complex):\n x = other.real - self[0]\n y = other.imag - self[1]\n elif isinstance(other, (float, int)):\n x = other - self[0]\n y = self[1]\n else:\n return NotImplemented\n return Point(x, y)\n\n def __abs__(self):\n return hypot(self.x, self.y)\n\n def __pow__(self, other):\n r_raised = abs(self) ** other\n argz_multiplied = self.argz() * other\n\n real_part = round(r_raised * cos(argz_multiplied))\n imag_part = round(r_raised * sin(argz_multiplied))\n return self.__class__(real_part, imag_part)\n\n def conjugate(self):\n return self.__class__(self.real, -self.imag)\n\n def argz(self):\n return atan(self.imag / self.real)\n\n @property\n def real(self):\n \"\"\"Emulate svg.path use of complex numbers\"\"\"\n return self.x\n\n @property\n def imag(self):\n \"\"\"Emulate svg.path use of complex numbers\"\"\"\n return self.y\n\n def matrix_transform(self, matrix):\n self *= matrix\n\n def move_towards(self, p2, amount=1):\n self.x = amount * (p2[0] - self[0]) + self[0]\n self.y = amount * (p2[1] - self[1]) + self[1]\n\n def distance_to(self, p2):\n return Point.distance(self, p2)\n\n def angle_to(self, p2):\n return Point.angle(self, p2)\n\n def polar_to(self, angle, distance):\n return Point.polar(self, angle, distance)\n\n def reflected_across(self, p):\n m = p + p\n m -= self\n return m\n\n @staticmethod\n def orientation(p, q, r):\n val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])\n if val == 0:\n return 0\n elif val > 0:\n return 1\n else:\n return 2\n\n @staticmethod\n def convex_hull(pts):\n if len(pts) == 0:\n return\n points = sorted(set(pts), key=lambda p: p[0])\n first_point_on_hull = points[0]\n point_on_hull = first_point_on_hull\n while True:\n yield point_on_hull\n endpoint = point_on_hull\n for t in points:\n if point_on_hull is endpoint \\\n or Point.orientation(point_on_hull, t, endpoint) == 2:\n endpoint = t\n point_on_hull = endpoint\n if first_point_on_hull is point_on_hull:\n break\n\n @staticmethod\n def distance(p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n dx *= dx\n dy *= dy\n return sqrt(dx + dy)\n\n @staticmethod\n def polar(p1, angle, r):\n dx = cos(angle) * r\n dy = sin(angle) * r\n return Point(p1[0] + dx, p1[1] + dy)\n\n @staticmethod\n def angle(p1, p2):\n return Angle.radians(atan2(p2[1] - p1[1], p2[0] - p1[0]))\n\n @staticmethod\n def towards(p1, p2, amount):\n tx = amount * (p2[0] - p1[0]) + p1[0]\n ty = amount * (p2[1] - p1[1]) + p1[1]\n return Point(tx, ty)\n\n\nclass Angle(float):\n \"\"\"CSS Angle defines as used in SVG\"\"\"\n\n def __repr__(self):\n return \"Angle(%.12f)\" % self\n\n def __eq__(self, other):\n # Python 2\n c1 = abs(self - other) <= 1e-11\n return c1\n\n @classmethod\n def parse(cls, angle_string):\n if not isinstance(angle_string, str):\n return\n angle_string = angle_string.lower()\n if angle_string.endswith('deg'):\n return Angle.degrees(float(angle_string[:-3]))\n if angle_string.endswith('rad'):\n return Angle.radians(float(angle_string[:-3]))\n if angle_string.endswith('grad'):\n return Angle.gradians(float(angle_string[:-4]))\n if angle_string.endswith('turn'):\n return Angle.turns(float(angle_string[:-4]))\n return Angle.degrees(float(angle_string))\n\n @classmethod\n def radians(cls, radians):\n return cls(radians)\n\n @classmethod\n def degrees(cls, degrees):\n return cls(tau * degrees / 360.0)\n\n @classmethod\n def gradians(cls, gradians):\n return cls(tau * gradians / 400.0)\n\n @classmethod\n def turns(cls, turns):\n return cls(tau * turns)\n\n @property\n def as_radians(self):\n return self\n\n @property\n def as_degrees(self):\n return self * 360.0 / tau\n\n @property\n def as_positive_degrees(self):\n v = self * 360.0 / tau\n while v < 0:\n v += 360.0\n return v\n\n @property\n def as_gradians(self):\n return self * 400.0 / tau\n\n @property\n def as_turns(self):\n return self / tau\n\n\nclass Matrix:\n \"\"\"\"\n Provides svg matrix interfacing.\n\n SVG 7.15.3 defines the matrix form as:\n [a c e]\n [b d f]\n \"\"\"\n\n def __init__(self, *components):\n if len(components) == 0:\n self.a = 1.0\n self.b = 0.0\n self.c = 0.0\n self.d = 1.0\n self.e = 0.0\n self.f = 0.0\n elif len(components) == 1:\n m = components[0]\n self.a = m[0]\n self.b = m[1]\n self.c = m[2]\n self.d = m[3]\n self.e = m[4]\n self.f = m[5]\n else:\n self.a = components[0]\n self.b = components[1]\n self.c = components[2]\n self.d = components[3]\n self.e = components[4]\n self.f = components[5]\n\n def __ne__(self, other):\n return other is None or \\\n not isinstance(other, Matrix) or \\\n self.a != other.a or self.b != other.b or \\\n self.c != other.c or self.d != other.d or \\\n self.e != other.e or self.f != other.f\n\n def __eq__(self, other):\n return not self.__ne__(other)\n\n def __len__(self):\n return 6\n\n def __matmul__(self, other):\n m = copy(self)\n m.__imatmul__(other)\n return m\n\n def __rmatmul__(self, other):\n m = copy(other)\n m.__imatmul__(self)\n return m\n\n def __imatmul__(self, other):\n self.a, self.b, self.c, self.d, self.e, self.f = Matrix.matrix_multiply(self, other)\n return self\n\n def __getitem__(self, item):\n if item == 0:\n return self.a\n elif item == 1:\n return self.b\n elif item == 2:\n return self.c\n elif item == 3:\n return self.d\n elif item == 4:\n return self.e\n elif item == 5:\n return self.f\n\n def __setitem__(self, key, value):\n if key == 0:\n self.a = value\n elif key == 1:\n self.b = value\n elif key == 2:\n self.c = value\n elif key == 3:\n self.d = value\n elif key == 4:\n self.e = value\n elif key == 5:\n self.f = value\n\n def __repr__(self):\n return \"Matrix(%3f, %3f, %3f, %3f, %3f, %3f)\" % \\\n (self.a, self.b, self.c, self.d, self.e, self.f)\n\n def __copy__(self):\n return Matrix(self.a, self.b, self.c, self.d, self.e, self.f)\n\n def __str__(self):\n \"\"\"\n Many of SVG's graphics operations utilize 2x3 matrices of the form:\n\n :returns string representation of matrix.\n \"\"\"\n return \"[%3f, %3f,\\n %3f, %3f, %3f, %3f]\" % \\\n (self.a, self.c, self.b, self.d, self.e, self.f)\n\n def value_trans_x(self):\n return self.e\n\n def value_trans_y(self):\n return self.f\n\n def value_scale_x(self):\n return self.a\n\n def value_scale_y(self):\n return self.d\n\n def value_skew_x(self):\n return self.b\n\n def value_skew_y(self):\n return self.c\n\n def reset(self):\n \"\"\"Resets matrix to identity.\"\"\"\n self.a = 1.0\n self.b = 0.0\n self.c = 0.0\n self.d = 1.0\n\n self.e = 0.0\n self.f = 0.0\n\n def inverse(self):\n \"\"\"\n [a c e]\n [b d f]\n \"\"\"\n m48s75 = self.d * 1 - self.f * 0\n m38s56 = 0 * self.e - self.c * 1\n m37s46 = self.c * self.f - self.d * self.e\n det = self.a * m48s75 + self.c * m38s56 + 0 * m37s46\n inverse_det = 1.0 / float(det)\n\n self.a = m48s75 * inverse_det\n self.b = (0 * self.f - self.c * 1) * inverse_det\n # self.g = (self.c * self.h - self.g * self.d) * inverse_det\n self.c = m38s56 * inverse_det\n self.d = (self.a * 1 - 0 * self.e) * inverse_det\n # self.h = (self.c * self.g - self.a * self.h) * inverse_det\n self.e = m37s46 * inverse_det\n self.f = (0 * self.c - self.a * self.f) * inverse_det\n # self.i = (self.a * self.d - self.c * self.c) * inverse_det\n\n def post_cat(self, *components):\n mx = Matrix(*components)\n self.__imatmul__(mx)\n\n def post_scale(self, sx=1, sy=None, x=0, y=0):\n if sy is None:\n sy = sx\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.post_cat(Matrix.scale(sx, sy))\n else:\n self.post_translate(-x, -y)\n self.post_scale(sx, sy)\n self.post_translate(x, y)\n\n def post_translate(self, tx, ty):\n self.post_cat(Matrix.translate(tx, ty))\n\n def post_rotate(self, angle, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.post_cat(Matrix.rotate(angle)) # self %= self.get_rotate(theta)\n else:\n matrix = Matrix()\n matrix.post_translate(-x, -y)\n matrix.post_cat(Matrix.rotate(angle))\n matrix.post_translate(x, y)\n self.post_cat(matrix)\n\n def post_skew_x(self, angle, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.post_cat(Matrix.skew_x(angle))\n else:\n self.post_translate(-x, -y)\n self.post_skew_x(angle)\n self.post_translate(x, y)\n\n def post_skew_y(self, angle, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.post_cat(Matrix.skew_y(angle))\n else:\n self.post_translate(-x, -y)\n self.post_skew_y(angle)\n self.post_translate(x, y)\n\n def pre_cat(self, *components):\n mx = Matrix(*components)\n self.a, self.b, self.c, self.d, self.e, self.f = Matrix.matrix_multiply(mx, self)\n\n def pre_skew_x(self, radians, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.pre_cat(Matrix.skew_x(radians))\n else:\n self.pre_translate(x, y)\n self.pre_skew_x(radians)\n self.pre_translate(-x, -y)\n\n def pre_skew_y(self, radians, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.pre_cat(Matrix.skew_y(radians))\n else:\n self.pre_translate(x, y)\n self.pre_skew_y(radians)\n self.pre_translate(-x, -y)\n\n def pre_scale(self, sx=1, sy=None, x=0, y=0):\n if sy is None:\n sy = sx\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.pre_cat(Matrix.scale(sx, sy))\n else:\n self.pre_translate(x, y)\n self.pre_scale(sx, sy)\n self.pre_translate(-x, -y)\n\n def pre_translate(self, tx, ty):\n self.pre_cat(Matrix.translate(tx, ty))\n\n def pre_rotate(self, angle, x=0, y=0):\n if x is None:\n x = 0\n if y is None:\n y = 0\n if x == 0 and y == 0:\n self.pre_cat(Matrix.rotate(angle))\n else:\n self.pre_translate(x, y)\n self.pre_rotate(angle)\n self.pre_translate(-x, -y)\n\n def point_in_inverse_space(self, v0):\n inverse = Matrix(self)\n inverse.inverse()\n return inverse.point_in_matrix_space(v0)\n\n def point_in_matrix_space(self, v0):\n return Point(v0[0] * self.a + v0[1] * self.c + 1 * self.e,\n v0[0] * self.b + v0[1] * self.d + 1 * self.f)\n\n def transform_point(self, v):\n nx = v[0] * self.a + v[1] * self.c + 1 * self.e\n ny = v[0] * self.b + v[1] * self.d + 1 * self.f\n v[0] = nx\n v[1] = ny\n\n @classmethod\n def scale(cls, sx, sy=None):\n if sy is None:\n sy = sx\n return cls(sx, 0,\n 0, sy, 0, 0)\n\n @classmethod\n def translate(cls, tx, ty):\n \"\"\"SVG Matrix:\n [a c e]\n [b d f]\n \"\"\"\n return cls(1, 0,\n 0, 1, tx, ty)\n\n @classmethod\n def rotate(cls, angle):\n ct = cos(angle)\n st = sin(angle)\n return cls(ct, st,\n -st, ct, 0, 0)\n\n @classmethod\n def skew_x(cls, angle):\n tt = tan(angle)\n return cls(1, 0,\n tt, 1, 0, 0)\n\n @classmethod\n def skew_y(cls, angle):\n tt = tan(angle)\n return cls(1, tt,\n 0, 1, 0, 0)\n\n @classmethod\n def identity(cls):\n \"\"\"\n 1, 0, 0,\n 0, 1, 0,\n \"\"\"\n return cls()\n\n @staticmethod\n def matrix_multiply(m, s):\n \"\"\"\n [a c e] [a c e] [a b 0]\n [b d f] % [b d f] = [c d 0]\n [0 0 1] [0 0 1] [e f 1]\n\n :param m0: matrix operand\n :param m1: matrix operand\n :return: muliplied matrix.\n \"\"\"\n r0 = s.a * m.a + s.c * m.b + s.e * 0, \\\n s.a * m.c + s.c * m.d + s.e * 0, \\\n s.a * m.e + s.c * m.f + s.e * 1\n\n r1 = s.b * m.a + s.d * m.b + s.f * 0, \\\n s.b * m.c + s.d * m.d + s.f * 0, \\\n s.b * m.e + s.d * m.f + s.f * 1\n\n return r0[0], r1[0], r0[1], r1[1], r0[2], r1[2]\n\n\nclass Segment:\n def __init__(self):\n self.start = None\n self.end = None\n\n def __mul__(self, other):\n if isinstance(other, Matrix):\n n = copy(self)\n n *= other\n return n\n\n __rmul__ = __mul__\n\n def __iter__(self):\n self.n = -1\n return self\n\n def __next__(self):\n self.n += 1\n try:\n val = self[self.n]\n if val is None:\n self.n += 1\n val = self[self.n]\n return val\n except IndexError:\n raise StopIteration\n\n\nclass Move(Segment):\n \"\"\"Represents move commands. Does nothing, but is there to handle\n paths that consist of only move commands, which is valid, but pointless.\n Also serve as a bridge to make discontinuous paths into continuous paths\n with non-drawn sections.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Move commands most importantly go to a place. So if one location is given, that's the end point.\n If two locations are given then first is the start location.\n\n Move(p) where p is the End point.\n Move(s,e) where s is the Start point, e is the End point.\n Move(p, start=s) where p is End point, s is the Start point.\n Move(p, end=e) where p is the Start point, e is the End point.\n Move(start=s, end=e) where s is the Start point, e is the End point.\n \"\"\"\n Segment.__init__(self)\n self.end = None\n self.start = None\n if len(args) == 0:\n if 'end' in kwargs:\n self.end = kwargs['end']\n if 'start' in kwargs:\n self.start = kwargs['start']\n elif len(args) == 1:\n if len(kwargs) == 0:\n self.end = args[0]\n else:\n if 'end' in kwargs:\n self.start = args[0]\n self.end = kwargs['end']\n elif 'start' in kwargs:\n self.start = kwargs['start']\n self.end = args[0]\n elif len(args) == 2:\n self.start = args[0]\n self.end = args[1]\n if self.start is not None:\n self.start = Point(self.start)\n if self.end is not None:\n self.end = Point(self.end)\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n if self.start is not None:\n self.start *= other\n if self.end is not None:\n self.end *= other\n return self\n\n def __copy__(self):\n return Move(self.start, self.end)\n\n def __repr__(self):\n if self.start is None:\n return 'Move(end=%s)' % repr(self.end)\n else:\n return 'Move(start=%s, end=%s)' % (repr(self.start), repr(self.end))\n\n def __eq__(self, other):\n if not isinstance(other, Move):\n return NotImplemented\n return self.start == other.start\n\n def __ne__(self, other):\n if not isinstance(other, Move):\n return NotImplemented\n return not self == other\n\n def __len__(self):\n return 2\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.end\n else:\n raise IndexError\n\n def point(self, pos):\n return self.start\n\n def length(self, error=ERROR, min_depth=MIN_DEPTH):\n return 0\n\n def plot(self):\n if self.start is not None:\n for x, y in Line.plot_line(self.start[0], self.start[1], self.end[0], self.end[1]):\n yield x, y, 0\n\n def reverse(self):\n if self.start is not None:\n return Move(self.end, self.start)\n else:\n if self.start is not None:\n return Move(self.start, self.end)\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment in the form\n (xmin, ymin, ymax, ymax).\"\"\"\n if self.start is not None:\n return self.start[0], self.start[1], self.end[0], self.end[1]\n else:\n return self.end[0], self.end[1], self.end[0], self.end[1]\n\n\nclass Close(Segment):\n \"\"\"Represents close commands. If this exists at the end of the shape then the shape is closed.\n the methodology of a single flag close fails in a couple ways. You can have multi-part shapes\n which can close or not close several times.\n \"\"\"\n\n def __init__(self, start=None, end=None):\n Segment.__init__(self)\n if end is None:\n if start is None:\n self.start = None\n self.end = None\n self.start = Point(start)\n self.end = Point(start)\n else:\n self.start = Point(start)\n self.end = Point(end)\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n if self.start is not None:\n self.start *= other\n if self.end is not None:\n self.end *= other\n return self\n\n def __copy__(self):\n return Close(self.start, self.end)\n\n def __repr__(self):\n if self.start is None and self.end is None:\n return 'Close()'\n s = self.start\n if s is not None:\n s = repr(s)\n e = self.end\n if e is not None:\n e = repr(e)\n return 'Close(start=%s, end=%s)' % (s, e)\n\n def __eq__(self, other):\n if not isinstance(other, Close):\n return NotImplemented\n return self.start == other.start\n\n def __ne__(self, other):\n if not isinstance(other, Close):\n return NotImplemented\n return not self == other\n\n def __len__(self):\n return 2\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.end\n else:\n raise IndexError\n\n def plot(self):\n if self.start is not None and self.end is not None:\n for x, y in Line.plot_line(self.start[0], self.start[1], self.end[0], self.end[1]):\n yield x, y, 1\n\n def reverse(self):\n return Close(self.end, self.start)\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment in the form\n (xmin, ymin, ymax, ymax).\"\"\"\n if self.start is None and self.end is None:\n return None\n return self.start[0], self.start[1], self.end[0], self.end[1]\n\n\nclass Line(Segment):\n def __init__(self, start, end):\n Segment.__init__(self)\n self.start = Point(start)\n self.end = Point(end)\n\n def __repr__(self):\n return 'Line(start=%s, end=%s)' % (repr(self.start), repr(self.end))\n\n def __eq__(self, other):\n if not isinstance(other, Line):\n return NotImplemented\n return self.start == other.start and self.end == other.end\n\n def __ne__(self, other):\n if not isinstance(other, Line):\n return NotImplemented\n return not self == other\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n self.start *= other\n self.end *= other\n return self\n\n def __len__(self):\n return 2\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.end\n else:\n raise IndexError\n\n def point(self, pos):\n return Point.towards(self.start, self.end, pos)\n\n def length(self, error=None, min_depth=None):\n return Point.distance(self.end, self.start)\n\n def reverse(self):\n return Line(self.end, self.start)\n\n def closest_segment_point(self, p, respect_bounds=True):\n \"\"\" Gives the t value of the point on the line closest to the given point. \"\"\"\n a = self.start\n b = self.end\n vAPx = p[0] - a[0]\n vAPy = p[1] - a[1]\n vABx = b[0] - a[0]\n vABy = b[1] - a[1]\n sqDistanceAB = vABx * vABx + vABy * vABy\n ABAPproduct = vABx * vAPx + vABy * vAPy\n if sqDistanceAB == 0:\n return 0 # Line is point.\n amount = ABAPproduct / sqDistanceAB\n if respect_bounds:\n if amount > 1:\n amount = 1\n if amount < 0:\n amount = 0\n return self.point(amount)\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment.\n xmin, ymin, xmax, ymax\n \"\"\"\n xmin = min(self.start[0], self.end[0])\n xmax = max(self.start[0], self.end[0])\n ymin = min(self.start[1], self.end[1])\n ymax = max(self.start[1], self.end[1])\n return xmin, ymin, xmax, ymax\n\n def plot(self):\n for x, y in Line.plot_line(self.start[0], self.start[1], self.end[0], self.end[1]):\n yield x, y, 1\n\n @staticmethod\n def plot_line(x0, y0, x1, y1):\n \"\"\"Zingl-Bresenham line draw algorithm\"\"\"\n x0 = int(x0)\n y0 = int(y0)\n x1 = int(x1)\n y1 = int(y1)\n dx = abs(x1 - x0)\n dy = -abs(y1 - y0)\n\n if x0 < x1:\n sx = 1\n else:\n sx = -1\n if y0 < y1:\n sy = 1\n else:\n sy = -1\n\n err = dx + dy # error value e_xy\n\n while True: # /* loop */\n yield x0, y0\n if x0 == x1 and y0 == y1:\n break\n e2 = 2 * err\n if e2 >= dy: # e_xy+e_y < 0\n err += dy\n x0 += sx\n if e2 <= dx: # e_xy+e_y < 0\n err += dx\n y0 += sy\n\n\nclass QuadraticBezier(Segment):\n def __init__(self, start, control, end):\n Segment.__init__(self)\n self.start = Point(start)\n self.control = Point(control)\n self.end = Point(end)\n\n def __repr__(self):\n return 'QuadraticBezier(start=%s, control=%s, end=%s)' % (\n repr(self.start), repr(self.control), repr(self.end))\n\n def __eq__(self, other):\n if not isinstance(other, QuadraticBezier):\n return NotImplemented\n return self.start == other.start and self.end == other.end and \\\n self.control == other.control\n\n def __ne__(self, other):\n if not isinstance(other, QuadraticBezier):\n return NotImplemented\n return not self == other\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n self.start *= other\n self.control *= other\n self.end *= other\n return self\n\n def __len__(self):\n return 3\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.control\n elif item == 2:\n return self.end\n raise IndexError\n\n def point(self, t):\n \"\"\"Calculate the x,y position at a certain position of the path\"\"\"\n x0, y0 = self.start\n x1, y1 = self.control\n x2, y2 = self.end\n x = (1 - t) * (1 - t) * x0 + 2 * (1 - t) * t * x1 + t * t * x2\n y = (1 - t) * (1 - t) * y0 + 2 * (1 - t) * t * y1 + t * t * y2\n return Point(x, y)\n\n def length(self, error=None, min_depth=None):\n \"\"\"Calculate the length of the path up to a certain position\"\"\"\n a = self.start - 2 * self.control + self.end\n b = 2 * (self.control - self.start)\n a_dot_b = a.real * b.real + a.imag * b.imag\n\n if abs(a) < 1e-12:\n s = abs(b)\n elif abs(a_dot_b + abs(a) * abs(b)) < 1e-12:\n k = abs(b) / abs(a)\n if k >= 2:\n s = abs(b) - abs(a)\n else:\n s = abs(a) * (k ** 2 / 2 - k + 1)\n else:\n # For an explanation of this case, see\n # http://www.malczak.info/blog/quadratic-bezier-curve-length/\n A = 4 * (a.real ** 2 + a.imag ** 2)\n B = 4 * (a.real * b.real + a.imag * b.imag)\n C = b.real ** 2 + b.imag ** 2\n\n Sabc = 2 * sqrt(A + B + C)\n A2 = sqrt(A)\n A32 = 2 * A * A2\n C2 = 2 * sqrt(C)\n BA = B / A2\n\n s = (A32 * Sabc + A2 * B * (Sabc - C2) + (4 * C * A - B ** 2) *\n log((2 * A2 + BA + Sabc) / (BA + C2))) / (4 * A32)\n return s\n\n def reverse(self):\n return QuadraticBezier(self.end, self.control, self.start)\n\n def is_smooth_from(self, previous):\n \"\"\"Checks if this segment would be a smooth segment following the previous\"\"\"\n if isinstance(previous, QuadraticBezier):\n return (self.start == previous.end and\n (self.control - self.start) == (previous.end - previous.control))\n else:\n return self.control == self.start\n\n def plot(self):\n for x, y in QuadraticBezier.plot_quad_bezier(self.start[0], self.start[1],\n self.control[0], self.control[1],\n self.end[0], self.end[1]):\n yield x, y, 1\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment\"\"\"\n xmin = min(self.start[0], self.control[0], self.end[0])\n ymin = min(self.start[1], self.control[1], self.end[1])\n xmax = max(self.start[0], self.control[0], self.end[0])\n ymax = max(self.start[1], self.control[1], self.end[1])\n return xmin, ymin, xmax, ymax\n\n @staticmethod\n def plot_quad_bezier_seg(x0, y0, x1, y1, x2, y2):\n \"\"\"plot a limited quadratic Bezier segment\n This algorithm can plot curves that do not inflect.\n It is used as part of the general algorithm, which breaks at the infection points\"\"\"\n sx = x2 - x1\n sy = y2 - y1\n xx = x0 - x1\n yy = y0 - y1\n xy = 0 # relative values for checks */\n dx = 0\n dy = 0\n err = 0\n cur = xx * sy - yy * sx # /* curvature */\n points = None\n\n assert (xx * sx <= 0 and yy * sy <= 0) # /* sign of gradient must not change */\n\n if sx * sx + sy * sy > xx * xx + yy * yy: # /* begin with shorter part */\n x2 = x0\n x0 = sx + x1\n y2 = y0\n y0 = sy + y1\n cur = -cur # /* swap P0 P2 */\n points = []\n if cur != 0: # /* no straight line */\n xx += sx\n if x0 < x2:\n sx = 1 # /* x step direction */\n else:\n sx = -1 # /* x step direction */\n xx *= sx\n yy += sy\n if y0 < y2:\n sy = 1\n else:\n sy = -1\n yy *= sy # /* y step direction */\n xy = 2 * xx * yy\n xx *= xx\n yy *= yy # /* differences 2nd degree */\n if cur * sx * sy < 0: # /* negated curvature? */\n xx = -xx\n yy = -yy\n xy = -xy\n cur = -cur\n dx = 4.0 * sy * cur * (x1 - x0) + xx - xy # /* differences 1st degree */\n dy = 4.0 * sx * cur * (y0 - y1) + yy - xy\n xx += xx\n yy += yy\n err = dx + dy + xy # /* error 1st step */\n while True:\n if points is None:\n yield x0, y0 # /* plot curve */\n else:\n points.append((x0, y0))\n if x0 == x2 and y0 == y2:\n if points is not None:\n for plot in reversed(points):\n yield plot\n return # /* last pixel -> curve finished */\n y1 = 2 * err < dx # /* save value for test of y step */\n if 2 * err > dy:\n x0 += sx\n dx -= xy\n dy += yy\n err += dy\n # /* x step */\n if y1 != 0:\n y0 += sy\n dy -= xy\n dx += xx\n err += dx\n # /* y step */\n if not (dy < 0 < dx): # /* gradient negates -> algorithm fails */\n break\n for plot in Line.plot_line(x0, y0, x2, y2): # /* plot remaining part to end */:\n if points is None:\n yield plot # /* plot curve */\n else:\n points.append(plot) # plotLine(x0,y0, x2,y2) #/* plot remaining part to end */\n if points is not None:\n for plot in reversed(points):\n yield plot\n\n @staticmethod\n def plot_quad_bezier(x0, y0, x1, y1, x2, y2):\n \"\"\"Zingl-Bresenham quad bezier draw algorithm.\n plot any quadratic Bezier curve\"\"\"\n x0 = int(x0)\n y0 = int(y0)\n # control points are permitted fractional elements.\n x2 = int(x2)\n y2 = int(y2)\n x = x0 - x1\n y = y0 - y1\n t = x0 - 2 * x1 + x2\n r = 0\n\n if x * (x2 - x1) > 0: # /* horizontal cut at P4? */\n if y * (y2 - y1) > 0: # /* vertical cut at P6 too? */\n if abs((y0 - 2 * y1 + y2) / t * x) > abs(y): # /* which first? */\n x0 = x2\n x2 = x + x1\n y0 = y2\n y2 = y + y1 # /* swap points */\n # /* now horizontal cut at P4 comes first */\n t = (x0 - x1) / t\n r = (1 - t) * ((1 - t) * y0 + 2.0 * t * y1) + t * t * y2 # /* By(t=P4) */\n t = (x0 * x2 - x1 * x1) * t / (x0 - x1) # /* gradient dP4/dx=0 */\n x = floor(t + 0.5)\n y = floor(r + 0.5)\n r = (y1 - y0) * (t - x0) / (x1 - x0) + y0 # /* intersect P3 | P0 P1 */\n for plot in QuadraticBezier.plot_quad_bezier_seg(x0, y0, x, floor(r + 0.5), x, y):\n yield plot\n r = (y1 - y2) * (t - x2) / (x1 - x2) + y2 # /* intersect P4 | P1 P2 */\n x0 = x1 = x\n y0 = y\n y1 = floor(r + 0.5) # /* P0 = P4, P1 = P8 */\n if (y0 - y1) * (y2 - y1) > 0: # /* vertical cut at P6? */\n t = y0 - 2 * y1 + y2\n t = (y0 - y1) / t\n r = (1 - t) * ((1 - t) * x0 + 2.0 * t * x1) + t * t * x2 # /* Bx(t=P6) */\n t = (y0 * y2 - y1 * y1) * t / (y0 - y1) # /* gradient dP6/dy=0 */\n x = floor(r + 0.5)\n y = floor(t + 0.5)\n r = (x1 - x0) * (t - y0) / (y1 - y0) + x0 # /* intersect P6 | P0 P1 */\n for plot in QuadraticBezier.plot_quad_bezier_seg(x0, y0, floor(r + 0.5), y, x, y):\n yield plot\n r = (x1 - x2) * (t - y2) / (y1 - y2) + x2 # /* intersect P7 | P1 P2 */\n x0 = x\n x1 = floor(r + 0.5)\n y0 = y1 = y # /* P0 = P6, P1 = P7 */\n for plot in QuadraticBezier.plot_quad_bezier_seg(x0, y0, x1, y1, x2, y2): # /* remaining part */\n yield plot\n\n\nclass CubicBezier(Segment):\n def __init__(self, start, control1, control2, end):\n Segment.__init__(self)\n self.start = Point(start)\n self.control1 = Point(control1)\n self.control2 = Point(control2)\n self.end = Point(end)\n\n def __repr__(self):\n return 'CubicBezier(start=%s, control1=%s, control2=%s, end=%s)' % (\n repr(self.start), repr(self.control1), repr(self.control2), repr(self.end))\n\n def __eq__(self, other):\n if not isinstance(other, CubicBezier):\n return NotImplemented\n return self.start == other.start and self.end == other.end and \\\n self.control1 == other.control1 and self.control2 == other.control2\n\n def __ne__(self, other):\n if not isinstance(other, CubicBezier):\n return NotImplemented\n return not self == other\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n self.start *= other\n self.control1 *= other\n self.control2 *= other\n self.end *= other\n return self\n\n def __len__(self):\n return 4\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.control1\n elif item == 2:\n return self.control2\n elif item == 3:\n return self.end\n else:\n raise IndexError\n\n def point(self, t):\n \"\"\"Calculate the x,y position at a certain position of the path\"\"\"\n x0, y0 = self.start\n x1, y1 = self.control1\n x2, y2 = self.control2\n x3, y3 = self.end\n x = (1 - t) * (1 - t) * (1 - t) * x0 + 3 * (1 - t) * (1 - t) * t * x1 + 3 * (\n 1 - t) * t * t * x2 + t * t * t * x3\n y = (1 - t) * (1 - t) * (1 - t) * y0 + 3 * (1 - t) * (1 - t) * t * y1 + 3 * (\n 1 - t) * t * t * y2 + t * t * t * y3\n return Point(x, y)\n\n def length(self, error=ERROR, min_depth=MIN_DEPTH):\n \"\"\"Calculate the length of the path up to a certain position\"\"\"\n start_point = self.point(0)\n end_point = self.point(1)\n return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0)\n\n def reverse(self):\n return CubicBezier(self.end, self.control2, self.control1, self.start)\n\n def is_smooth_from(self, previous):\n \"\"\"Checks if this segment would be a smooth segment following the previous\"\"\"\n if isinstance(previous, CubicBezier):\n return (self.start == previous.end and\n (self.control1 - self.start) == (previous.end - previous.control2))\n else:\n return self.control1 == self.start\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment\"\"\"\n xmin = min(self.start[0], self.control1[0], self.control2[0], self.end[0])\n ymin = min(self.start[1], self.control1[1], self.control2[1], self.end[1])\n xmax = max(self.start[0], self.control1[0], self.control2[0], self.end[0])\n ymax = max(self.start[1], self.control1[1], self.control2[1], self.end[1])\n return xmin, ymin, xmax, ymax\n\n def plot(self):\n for e in CubicBezier.plot_cubic_bezier(self.start[0], self.start[1],\n self.control1[0], self.control1[1],\n self.control2[0], self.control2[1],\n self.end[0], self.end[1]):\n yield e\n\n @staticmethod\n def plot_cubic_bezier_seg(x0, y0, x1, y1, x2, y2, x3, y3):\n \"\"\"plot limited cubic Bezier segment\n This algorithm can plot curves that do not inflect.\n It is used as part of the general algorithm, which breaks at the infection points\"\"\"\n second_leg = []\n f = 0\n fx = 0\n fy = 0\n leg = 1\n if x0 < x3:\n sx = 1\n else:\n sx = -1\n if y0 < y3:\n sy = 1 # /* step direction */\n else:\n sy = -1 # /* step direction */\n xc = -abs(x0 + x1 - x2 - x3)\n xa = xc - 4 * sx * (x1 - x2)\n xb = sx * (x0 - x1 - x2 + x3)\n yc = -abs(y0 + y1 - y2 - y3)\n ya = yc - 4 * sy * (y1 - y2)\n yb = sy * (y0 - y1 - y2 + y3)\n ab = 0\n ac = 0\n bc = 0\n cb = 0\n xx = 0\n xy = 0\n yy = 0\n dx = 0\n dy = 0\n ex = 0\n pxy = 0\n EP = 0.01\n # /* check for curve restrains */\n # /* slope P0-P1 == P2-P3 and (P0-P3 == P1-P2 or no slope change)\n # if (x1 - x0) * (x2 - x3) < EP and ((x3 - x0) * (x1 - x2) < EP or xb * xb < xa * xc + EP):\n # return\n # if (y1 - y0) * (y2 - y3) < EP and ((y3 - y0) * (y1 - y2) < EP or yb * yb < ya * yc + EP):\n # return\n\n if xa == 0 and ya == 0: # /* quadratic Bezier */\n # return plot_quad_bezier_seg(x0, y0, (3 * x1 - x0) >> 1, (3 * y1 - y0) >> 1, x3, y3)\n sx = floor((3 * x1 - x0 + 1) / 2)\n sy = floor((3 * y1 - y0 + 1) / 2) # /* new midpoint */\n\n for plot in QuadraticBezier.plot_quad_bezier_seg(x0, y0, sx, sy, x3, y3):\n yield plot\n return\n x1 = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + 1 # /* line lengths */\n x2 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3) + 1\n\n while True: # /* loop over both ends */\n ab = xa * yb - xb * ya\n ac = xa * yc - xc * ya\n bc = xb * yc - xc * yb\n ex = ab * (ab + ac - 3 * bc) + ac * ac # /* P0 part of self-intersection loop? */\n if ex > 0:\n f = 1 # /* calc resolution */\n else:\n f = floor(sqrt(1 + 1024 / x1)) # /* calc resolution */\n ab *= f\n ac *= f\n bc *= f\n ex *= f * f # /* increase resolution */\n xy = 9 * (ab + ac + bc) / 8\n cb = 8 * (xa - ya) # /* init differences of 1st degree */\n dx = 27 * (8 * ab * (yb * yb - ya * yc) + ex * (ya + 2 * yb + yc)) / 64 - ya * ya * (xy - ya)\n dy = 27 * (8 * ab * (xb * xb - xa * xc) - ex * (xa + 2 * xb + xc)) / 64 - xa * xa * (xy + xa)\n # /* init differences of 2nd degree */\n xx = 3 * (3 * ab * (3 * yb * yb - ya * ya - 2 * ya * yc) - ya * (3 * ac * (ya + yb) + ya * cb)) / 4\n yy = 3 * (3 * ab * (3 * xb * xb - xa * xa - 2 * xa * xc) - xa * (3 * ac * (xa + xb) + xa * cb)) / 4\n xy = xa * ya * (6 * ab + 6 * ac - 3 * bc + cb)\n ac = ya * ya\n cb = xa * xa\n xy = 3 * (xy + 9 * f * (cb * yb * yc - xb * xc * ac) - 18 * xb * yb * ab) / 8\n\n if ex < 0: # /* negate values if inside self-intersection loop */\n dx = -dx\n dy = -dy\n xx = -xx\n yy = -yy\n xy = -xy\n ac = -ac\n cb = -cb # /* init differences of 3rd degree */\n ab = 6 * ya * ac\n ac = -6 * xa * ac\n bc = 6 * ya * cb\n cb = -6 * xa * cb\n dx += xy\n ex = dx + dy\n dy += xy # /* error of 1st step */\n try:\n pxy = 0\n fx = fy = f\n while x0 != x3 and y0 != y3:\n if leg == 0:\n second_leg.append((x0, y0)) # /* plot curve */\n else:\n yield x0, y0 # /* plot curve */\n while True: # /* move sub-steps of one pixel */\n if pxy == 0:\n if dx > xy or dy < xy:\n raise StopIteration # /* confusing */\n if pxy == 1:\n if dx > 0 or dy < 0:\n raise StopIteration # /* values */\n y1 = 2 * ex - dy # /* save value for test of y step */\n if 2 * ex >= dx: # /* x sub-step */\n fx -= 1\n dx += xx\n ex += dx\n xy += ac\n dy += xy\n yy += bc\n xx += ab\n elif y1 > 0:\n raise StopIteration\n if y1 <= 0: # /* y sub-step */\n fy -= 1\n dy += yy\n ex += dy\n xy += bc\n dx += xy\n xx += ac\n yy += cb\n if not (fx > 0 and fy > 0): # /* pixel complete? */\n break\n if 2 * fx <= f:\n x0 += sx\n fx += f # /* x step */\n if 2 * fy <= f:\n y0 += sy\n fy += f # /* y step */\n if pxy == 0 and dx < 0 and dy > 0:\n pxy = 1 # /* pixel ahead valid */\n except StopIteration:\n pass\n xx = x0\n x0 = x3\n x3 = xx\n sx = -sx\n xb = -xb # /* swap legs */\n yy = y0\n y0 = y3\n y3 = yy\n sy = -sy\n yb = -yb\n x1 = x2\n if not (leg != 0):\n break\n leg -= 1 # /* try other end */\n for plot in Line.plot_line(x3, y3, x0, y0): # /* remaining part in case of cusp or crunode */\n second_leg.append(plot)\n for plot in reversed(second_leg):\n yield plot\n\n @staticmethod\n def plot_cubic_bezier(x0, y0, x1, y1, x2, y2, x3, y3):\n \"\"\"Zingl-Bresenham cubic bezier draw algorithm\n plot any quadratic Bezier curve\"\"\"\n x0 = int(x0)\n y0 = int(y0)\n # control points are permitted fractional elements.\n x3 = int(x3)\n y3 = int(y3)\n n = 0\n i = 0\n xc = x0 + x1 - x2 - x3\n xa = xc - 4 * (x1 - x2)\n xb = x0 - x1 - x2 + x3\n xd = xb + 4 * (x1 + x2)\n yc = y0 + y1 - y2 - y3\n ya = yc - 4 * (y1 - y2)\n yb = y0 - y1 - y2 + y3\n yd = yb + 4 * (y1 + y2)\n fx0 = x0\n fx1 = 0\n fx2 = 0\n fx3 = 0\n fy0 = y0\n fy1 = 0\n fy2 = 0\n fy3 = 0\n t1 = xb * xb - xa * xc\n t2 = 0\n t = [0] * 5\n # /* sub-divide curve at gradient sign changes */\n if xa == 0: # /* horizontal */\n if abs(xc) < 2 * abs(xb):\n t[n] = xc / (2.0 * xb) # /* one change */\n n += 1\n elif t1 > 0.0: # /* two changes */\n t2 = sqrt(t1)\n t1 = (xb - t2) / xa\n if abs(t1) < 1.0:\n t[n] = t1\n n += 1\n t1 = (xb + t2) / xa\n if abs(t1) < 1.0:\n t[n] = t1\n n += 1\n t1 = yb * yb - ya * yc\n if ya == 0: # /* vertical */\n if abs(yc) < 2 * abs(yb):\n t[n] = yc / (2.0 * yb) # /* one change */\n n += 1\n elif t1 > 0.0: # /* two changes */\n t2 = sqrt(t1)\n t1 = (yb - t2) / ya\n if abs(t1) < 1.0:\n t[n] = t1\n n += 1\n t1 = (yb + t2) / ya\n if abs(t1) < 1.0:\n t[n] = t1\n n += 1\n i = 1\n while i < n: # /* bubble sort of 4 points */\n t1 = t[i - 1]\n if t1 > t[i]:\n t[i - 1] = t[i]\n t[i] = t1\n i = 0\n i += 1\n t1 = -1.0\n t[n] = 1.0 # /* begin / end point */\n for i in range(0, n + 1): # /* plot each segment separately */\n t2 = t[i] # /* sub-divide at t[i-1], t[i] */\n fx1 = (t1 * (t1 * xb - 2 * xc) - t2 * (t1 * (t1 * xa - 2 * xb) + xc) + xd) / 8 - fx0\n fy1 = (t1 * (t1 * yb - 2 * yc) - t2 * (t1 * (t1 * ya - 2 * yb) + yc) + yd) / 8 - fy0\n fx2 = (t2 * (t2 * xb - 2 * xc) - t1 * (t2 * (t2 * xa - 2 * xb) + xc) + xd) / 8 - fx0\n fy2 = (t2 * (t2 * yb - 2 * yc) - t1 * (t2 * (t2 * ya - 2 * yb) + yc) + yd) / 8 - fy0\n fx3 = (t2 * (t2 * (3 * xb - t2 * xa) - 3 * xc) + xd) / 8\n fx0 -= fx3\n fy3 = (t2 * (t2 * (3 * yb - t2 * ya) - 3 * yc) + yd) / 8\n fy0 -= fy3\n x3 = floor(fx3 + 0.5)\n y3 = floor(fy3 + 0.5) # /* scale bounds */\n if fx0 != 0.0:\n fx0 = (x0 - x3) / fx0\n fx1 *= fx0\n fx2 *= fx0\n if fy0 != 0.0:\n fy0 = (y0 - y3) / fy0\n fy1 *= fy0\n fy2 *= fy0\n if x0 != x3 or y0 != y3: # /* segment t1 - t2 */\n # plotCubicBezierSeg(x0,y0, x0+fx1,y0+fy1, x0+fx2,y0+fy2, x3,y3)\n for plot in CubicBezier.plot_cubic_bezier_seg(x0, y0, x0 + fx1, y0 + fy1, x0 + fx2, y0 + fy2, x3, y3):\n yield plot\n x0 = x3\n y0 = y3\n fx0 = fx3\n fy0 = fy3\n t1 = t2\n\n\nclass Arc(Segment):\n def __init__(self, *args, **kwargs):\n \"\"\"Arc objects can take different parameters to create arcs.\n Since we expect taking in SVG parameters. We accept SVG parameterization which is:\n start, rx, ry, rotation, arc_flag, sweep_flag, end.\n\n To do matrix transitions, the native parameterization is start, end, center, prx, pry, sweep\n\n 'start, end, center, prx, pry' are points and sweep amount is a value in tau radians.\n If points are modified by an affine transformation, the arc is transformed.\n There is a special case for when the scale factor inverts, it inverts the sweep.\n\n prx is the point at angle 0 of the non-rotated ellipse.\n pry is the point at angle tau/4 of the non-rotated ellipse.\n The theta-rotation can be defined as the angle from center to prx\n\n The sweep angle can be a value greater than tau and less than -tau.\n However if this is the case conversion back to Path.d() is expected to fail.\n\n prx -> center -> pry should form a right triangle.\n angle(center,end) - angle(center, start) should equal sweep or mod thereof.\n\n start and end should fall on the ellipse defined by prx, pry and center.\n \"\"\"\n Segment.__init__(self)\n self.start = None\n self.end = None\n self.center = None\n self.prx = None\n self.pry = None\n self.sweep = None\n if len(args) == 6 and isinstance(args[1], complex):\n self.svg_complex_parameterize(*args)\n return\n elif len(kwargs) == 6 and 'rotation' in kwargs:\n self.svg_complex_parameterize(**kwargs)\n return\n elif len(args) == 7:\n # This is an svg parameterized call.\n # A: rx ry x-axis-rotation large-arc-flag sweep-flag x y\n self.svg_parameterize(args[0], args[1], args[2], args[3], args[4], args[5], args[6])\n return\n # TODO: account for L, T, R, B, startAngle, endAngle, theta parameters.\n # cx = (left + right) / 2\n # cy = (top + bottom) / 2\n #\n # rx = (right - left) / 2\n # cy = (bottom - top) / 2\n # startAngle, endAngle, theta\n len_args = len(args)\n if len_args > 0:\n self.start = Point(args[0])\n if len_args > 1:\n self.end = Point(args[1])\n if len_args > 2:\n self.center = Point(args[2])\n if len_args > 3:\n self.prx = Point(args[3])\n if len_args > 4:\n self.pry = Point(args[4])\n if len_args > 5:\n self.sweep = args[5]\n return # The args gave us everything.\n if 'start' in kwargs:\n self.start = kwargs['start']\n if 'end' in kwargs:\n self.end = kwargs['end']\n if 'center' in kwargs:\n self.center = kwargs['center']\n if 'prx' in kwargs:\n self.prx = kwargs['prx']\n if 'pry' in kwargs:\n self.pry = kwargs['pry']\n if 'sweep' in kwargs:\n self.sweep = kwargs['sweep']\n if self.center is not None:\n if 'r' in kwargs:\n r = kwargs['r']\n if self.prx is None:\n self.prx = [self.center[0] + r, self.center[1]]\n if self.pry is None:\n self.pry = [self.center[0], self.center[1] + r]\n if 'rx' in kwargs:\n rx = kwargs['rx']\n if self.prx is None:\n if 'rotation' in kwargs:\n theta = kwargs['rotation']\n self.prx = Point.polar(self.center, theta, rx)\n else:\n self.prx = [self.center[0] + rx, self.center[1]]\n if 'ry' in kwargs:\n ry = kwargs['ry']\n if self.pry is None:\n if 'rotation' in kwargs:\n theta = kwargs['rotation']\n theta += tau / 4.0\n self.pry = Point.polar(self.center, theta, ry)\n else:\n self.pry = [self.center[0], self.center[1] + ry]\n if self.start is not None and (self.prx is None or self.pry is None):\n radius_s = Point.distance(self.center, self.start)\n self.prx = Point(self.center[0] + radius_s, self.center[1])\n self.pry = Point(self.center[0], self.center[1] + radius_s)\n if self.end is not None and (self.prx is None or self.pry is None):\n radius_e = Point.distance(self.center, self.end)\n self.prx = Point(self.center[0] + radius_e, self.center[1])\n self.pry = Point(self.center[0], self.center[1] + radius_e)\n if self.sweep is None and self.start is not None and self.end is not None:\n start_angle = Point.angle(self.center, self.start)\n end_angle = Point.angle(self.center, self.end)\n self.sweep = end_angle - start_angle\n if self.sweep is not None and self.start is not None and self.end is None:\n start_angle = Point.angle(self.center, self.start)\n end_angle = start_angle + self.sweep\n r = Point.distance(self.center, self.start)\n self.end = Point.polar(self.center, end_angle, r)\n if self.sweep is not None and self.start is None and self.end is not None:\n end_angle = Point.angle(self.center, self.end)\n start_angle = end_angle - self.sweep\n r = Point.distance(self.center, self.end)\n self.start = Point.polar(self.center, start_angle, r)\n else: # center is None\n pass\n\n def __repr__(self):\n return 'Arc(%s, %s, %s, %s, %s, %s)' % (\n repr(self.start), repr(self.end), repr(self.center), repr(self.prx), repr(self.pry), self.sweep)\n\n def __eq__(self, other):\n if not isinstance(other, Arc):\n return NotImplemented\n return self.start == other.start and self.end == other.end and \\\n self.prx == other.prx and self.pry == other.pry and \\\n self.center == other.center and self.sweep == other.sweep\n\n def __ne__(self, other):\n if not isinstance(other, Arc):\n return NotImplemented\n return not self == other\n\n def __copy__(self):\n return Arc(self.start, self.end, self.center, self.prx, self.pry, self.sweep)\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n self.start *= other\n self.center *= other\n self.end *= other\n self.prx *= other\n self.pry *= other\n if other.value_scale_x() < 0:\n self.sweep = -self.sweep\n if other.value_scale_y() < 0:\n self.sweep = -self.sweep\n return self\n\n def __len__(self):\n return 5\n\n def __getitem__(self, item):\n if item == 0:\n return self.start\n elif item == 1:\n return self.end\n elif item == 2:\n return self.center\n elif item == 3:\n return self.prx\n elif item == 4:\n return self.pry\n raise IndexError\n\n @property\n def theta(self):\n \"\"\"legacy property\"\"\"\n return self.get_start_angle().as_positive_degrees\n\n @property\n def delta(self):\n \"\"\"legacy property\"\"\"\n return Angle.radians(self.sweep).as_degrees\n\n def point_at_angle(self, t):\n rotation = self.get_rotation()\n cos_theta_rotation = cos(rotation)\n sin_theta_rotation = sin(rotation)\n cos_angle = cos(t)\n sin_angle = sin(t)\n rx = self.rx\n ry = self.ry\n x = (cos_theta_rotation * cos_angle * rx - sin_theta_rotation * sin_angle * ry + self.center[0])\n y = (sin_theta_rotation * cos_angle * rx + cos_theta_rotation * sin_angle * ry + self.center[1])\n return Point(x, y)\n\n def point(self, t):\n if self.start == self.end and self.sweep == 0:\n # This is equivalent of omitting the segment\n return self.start\n angle = self.get_start_angle() - self.get_rotation() + self.sweep * t\n return self.point_at_angle(angle)\n\n def length(self, error=ERROR, min_depth=MIN_DEPTH):\n \"\"\"The length of an elliptical arc segment requires numerical\n integration, and in that case it's simpler to just do a geometric\n approximation, as for cubic bezier curves.\n \"\"\"\n if self.start == self.end and self.sweep == 0:\n # This is equivalent of omitting the segment\n return 0\n start_point = self.point(0)\n end_point = self.point(1)\n return segment_length(self, 0, 1, start_point, end_point, error, min_depth, 0)\n\n def reverse(self):\n return Arc(self.end, self.start, self.center, self.prx, self.pry, -self.sweep)\n\n def svg_complex_parameterize(self, start, radius, rotation, arc, sweep, end):\n \"\"\"Parameterization with complex radius and having rotation factors.\"\"\"\n self.svg_parameterize(Point(start), radius.real, radius.imag, rotation, bool(arc), bool(sweep), Point(end))\n\n def svg_parameterize(self, start, rx, ry, rotation, large_arc_flag, sweep_flag, end):\n \"\"\"Conversion from svg parameterization, our chosen native native form.\n http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes \"\"\"\n\n start = Point(start)\n self.start = start\n end = Point(end)\n self.end = end\n if start == end:\n # If start is equal to end, there are infinite number of circles so these void out.\n # We still permit this kind of arc, but SVG parameterization cannot be used to achieve it.\n self.sweep = 0\n self.prx = Point(start)\n self.pry = Point(start)\n self.center = Point(start)\n return\n cosr = cos(radians(rotation))\n sinr = sin(radians(rotation))\n dx = (start.real - end.real) / 2\n dy = (start.imag - end.imag) / 2\n x1prim = cosr * dx + sinr * dy\n x1prim_sq = x1prim * x1prim\n y1prim = -sinr * dx + cosr * dy\n y1prim_sq = y1prim * y1prim\n\n rx_sq = rx * rx\n ry_sq = ry * ry\n\n # Correct out of range radii\n radius_check = (x1prim_sq / rx_sq) + (y1prim_sq / ry_sq)\n if radius_check > 1:\n rx *= sqrt(radius_check)\n ry *= sqrt(radius_check)\n rx_sq = rx * rx\n ry_sq = ry * ry\n\n t1 = rx_sq * y1prim_sq\n t2 = ry_sq * x1prim_sq\n c = sqrt(abs((rx_sq * ry_sq - t1 - t2) / (t1 + t2)))\n\n if large_arc_flag == sweep_flag:\n c = -c\n cxprim = c * rx * y1prim / ry\n cyprim = -c * ry * x1prim / rx\n\n center = Point((cosr * cxprim - sinr * cyprim) +\n ((start.real + end.real) / 2),\n (sinr * cxprim + cosr * cyprim) +\n ((start.imag + end.imag) / 2))\n\n ux = (x1prim - cxprim) / rx\n uy = (y1prim - cyprim) / ry\n vx = (-x1prim - cxprim) / rx\n vy = (-y1prim - cyprim) / ry\n n = sqrt(ux * ux + uy * uy)\n p = ux\n theta = degrees(acos(p / n))\n if uy < 0:\n theta = -theta\n theta = theta % 360\n\n n = sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy))\n p = ux * vx + uy * vy\n d = p / n\n # In certain cases the above calculation can through inaccuracies\n # become just slightly out of range, f ex -1.0000000000000002.\n if d > 1.0:\n d = 1.0\n elif d < -1.0:\n d = -1.0\n delta = degrees(acos(d))\n if (ux * vy - uy * vx) < 0:\n delta = -delta\n delta = delta % 360\n if not sweep_flag:\n delta -= 360\n # built parameters, delta, theta, center\n\n rotate_matrix = Matrix()\n rotate_matrix.post_rotate(Angle.degrees(rotation).as_radians, center[0], center[1])\n\n self.center = center\n self.prx = Point(center[0] + rx, center[1])\n self.pry = Point(center[0], center[1] + ry)\n\n self.prx.matrix_transform(rotate_matrix)\n self.pry.matrix_transform(rotate_matrix)\n self.sweep = Angle.degrees(delta).as_radians\n\n def as_quad_curves(self):\n sweep_limit = tau / 12\n arc_required = int(ceil(abs(self.sweep) / sweep_limit))\n if arc_required == 0:\n return\n slice = self.sweep / float(arc_required)\n\n start_angle = self.get_start_angle()\n theta = self.get_rotation()\n p_start = self.start\n\n current_angle = start_angle - theta\n\n for i in range(0, arc_required):\n next_angle = current_angle + slice\n q = Point(p_start[0] + tan((p_end[0] - p_start[0]) / 2.0))\n yield QuadraticBezier(p_start, q, p_end)\n p_start = Point(p_end)\n current_angle = next_angle\n\n def as_cubic_curves(self):\n sweep_limit = tau / 12\n arc_required = int(ceil(abs(self.sweep) / sweep_limit))\n if arc_required == 0:\n return\n slice = self.sweep / float(arc_required)\n\n start_angle = self.get_start_angle()\n theta = self.get_rotation()\n rx = self.rx\n ry = self.ry\n p_start = self.start\n current_angle = start_angle - theta\n x0 = self.center[0]\n y0 = self.center[1]\n cos_theta = cos(theta)\n sin_theta = sin(theta)\n\n for i in range(0, arc_required):\n next_angle = current_angle + slice\n\n alpha = sin(slice) * (sqrt(4 + 3 * pow(tan((slice) / 2.0), 2)) - 1) / 3.0\n\n cos_start_angle = cos(current_angle)\n sin_start_angle = sin(current_angle)\n\n ePrimen1x = -rx * cos_theta * sin_start_angle - ry * sin_theta * cos_start_angle\n ePrimen1y = -rx * sin_theta * sin_start_angle + ry * cos_theta * cos_start_angle\n\n cos_end_angle = cos(next_angle)\n sin_end_angle = sin(next_angle)\n\n p2En2x = x0 + rx * cos_end_angle * cos_theta - ry * sin_end_angle * sin_theta\n p2En2y = y0 + rx * cos_end_angle * sin_theta + ry * sin_end_angle * cos_theta\n p_end = (p2En2x, p2En2y)\n if i == arc_required - 1:\n p_end = self.end\n\n ePrimen2x = -rx * cos_theta * sin_end_angle - ry * sin_theta * cos_end_angle\n ePrimen2y = -rx * sin_theta * sin_end_angle + ry * cos_theta * cos_end_angle\n\n p_c1 = (p_start[0] + alpha * ePrimen1x, p_start[1] + alpha * ePrimen1y)\n p_c2 = (p_end[0] - alpha * ePrimen2x, p_end[1] - alpha * ePrimen2y)\n\n yield CubicBezier(p_start, p_c1, p_c2, p_end)\n p_start = Point(p_end)\n current_angle = next_angle\n\n def is_circular(self):\n a = self.rx\n b = self.ry\n return a == b\n\n @property\n def radius(self):\n \"\"\"Legacy complex radius property\n\n Point will work like a complex for legacy reasons.\n \"\"\"\n return Point(self.rx, self.ry)\n\n @property\n def rx(self):\n return Point.distance(self.center, self.prx)\n\n @property\n def ry(self):\n return Point.distance(self.center, self.pry)\n\n def get_rotation(self):\n return Point.angle(self.center, self.prx)\n\n def get_start_angle(self):\n return Point.angle(self.center, self.start)\n\n def get_end_angle(self):\n return Point.angle(self.center, self.end)\n\n def bbox_rotated(self):\n theta = Point.angle(self.center, self.prx)\n a = Point.distance(self.center, self.prx)\n b = Point.distance(self.center, self.pry)\n cos_theta = cos(theta)\n sin_theta = sin(theta)\n xmax = sqrt(a * a * cos_theta * cos_theta + b * b * sin_theta * sin_theta)\n xmin = -xmax\n ymax = sqrt(a * a * sin_theta * sin_theta + b * b * cos_theta * cos_theta)\n ymin = -xmax\n return xmin + self.center[0], ymin + self.center[1], xmax + self.center[0], ymax + self.center[1]\n\n def bbox(self):\n \"\"\"returns the bounding box for the segment\"\"\"\n # TODO: The bbox rotated command should be integrated into here. It's not enough to min and max the start, end,\n # and center, but rather needs to find the min and max of the path along the arc.\n xmin = min(self.start[0], self.center[0], self.end[0])\n ymin = min(self.start[1], self.center[1], self.end[1])\n xmax = max(self.start[0], self.center[0], self.end[0])\n ymax = max(self.start[1], self.center[1], self.end[1])\n return xmin, ymin, xmax, ymax\n\n def plot(self):\n # TODO: This needs to work correctly. Should actually plot the arc according to the pixel-perfect standard.\n for curve in self.as_cubic_curves():\n for value in curve.plot():\n yield value\n\n @staticmethod\n def plot_arc(arc):\n theta = Point.angle(arc.center, arc.prx)\n a = Point.distance(arc.center, arc.prx)\n b = Point.distance(arc.center, arc.pry)\n cos_theta = cos(theta)\n sin_theta = sin(theta)\n xmax = sqrt(a * a * cos_theta * cos_theta + b * b * sin_theta * sin_theta)\n ymax = sqrt(a * a * sin_theta * sin_theta + b * b * cos_theta * cos_theta)\n angle_xmax = Point.distance(arc.center, [xmax, ymax])\n # TODO: need to plug this back into the arc to solve for the position of xmax,\n # y-unknown on the ellipse.\n\n yield arc.start[0], arc.start[1]\n # TODO: Actually write this, divide into proper segments\n yield arc.end[0], arc.end[1]\n\n @staticmethod\n def plot_arc_seg(xm, ym, ar, br=None, theta=0):\n if br is None:\n br = ar\n x = -ar\n y = 0\n e2 = br * br\n err = x * (2 * e2 + x) + e2\n sx = 1\n sy = 1\n while True:\n yield xm + x, ym + y\n e2 = 2 * err\n if e2 >= (x * 2 + 1) * br * br:\n x = x + sx\n err += (x * 2 + 1) * br * br\n if e2 <= (y * 2 + 1) * ar * ar:\n y = y + sy\n err += (y * 2 + 1) * ar * ar\n if x <= 0:\n break\n\n\nclass Path(MutableSequence):\n \"\"\"A Path is a sequence of path segments\"\"\"\n\n def __init__(self, *segments):\n self._segments = list(segments)\n self._length = None\n self._lengths = None\n\n def __copy__(self):\n p = Path()\n for seg in self._segments:\n p.append(copy(seg))\n return p\n\n def __getitem__(self, index):\n return self._segments[index]\n\n def __setitem__(self, index, value):\n self._segments[index] = value\n self._length = None\n\n def __delitem__(self, index):\n del self._segments[index]\n self._length = None\n\n def __imul__(self, other):\n if isinstance(other, Matrix):\n for e in self._segments:\n e *= other\n return self\n\n def __mul__(self, other):\n if isinstance(other, Matrix):\n n = copy(self)\n n *= other\n return n\n\n __rmul__ = __mul__\n\n def __reversed__(self):\n for segment in reversed(self._segments):\n yield segment.reverse()\n\n def __len__(self):\n return len(self._segments)\n\n def __repr__(self):\n return 'Path(%s)' % (', '.join(repr(x) for x in self._segments))\n\n def __eq__(self, other):\n if not isinstance(other, Path):\n return NotImplemented\n if len(self) != len(other):\n return False\n for s, o in zip(self._segments, other._segments):\n if not s == o:\n return False\n return True\n\n def __ne__(self, other):\n if not isinstance(other, Path):\n return NotImplemented\n return not self == other\n\n @property\n def first_point(self):\n \"\"\"First point along the Path. This is the start point of the first segment unless it starts\n with a Move command with a None start in which case first point is that Move's destination.\"\"\"\n if len(self._segments) == 0:\n return None\n if self._segments[0].start is not None:\n return Point(self._segments[0].start)\n return Point(self._segments[0].end)\n\n @property\n def current_point(self):\n if len(self._segments) == 0:\n return None\n return Point(self._segments[-1].end)\n\n @property\n def z_point(self):\n \"\"\"\n Z doesn't necessarily mean the first_point, it's the destination of the last Move.\n This behavior of Z is defined in svg spec:\n http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand\n \"\"\"\n end_pos = None\n for segment in reversed(self._segments):\n if isinstance(segment, Move):\n end_pos = segment.end\n break\n if end_pos is None:\n end_pos = self._segments[0].start\n return end_pos\n\n @property\n def smooth_point(self):\n \"\"\"Returns the smoothing control point for the smooth commands.\n With regards to the SVG standard if the last command was a curve the smooth\n control point is the reflection of the previous control point.\n\n If the last command was not a curve, the smooth_point is coincident with the current.\n https://www.w3.org/TR/SVG/paths.html#PathDataCubicBezierCommands\n \"\"\"\n\n if len(self._segments) == 0:\n return None\n start_pos = self.current_point\n last_segment = self._segments[-1]\n if isinstance(last_segment, QuadraticBezier):\n previous_control = last_segment.control\n return previous_control.reflected_across(start_pos)\n elif isinstance(last_segment, CubicBezier):\n previous_control = last_segment.control2\n return previous_control.reflected_across(start_pos)\n return start_pos\n\n def start(self):\n pass\n\n def end(self):\n pass\n\n def move(self, *points):\n end_pos = points[0]\n if len(self._segments) > 0:\n if isinstance(self._segments[-1], Move):\n # If there was just a move command update that.\n self._segments[-1].end = Point(end_pos)\n return\n start_pos = self.current_point\n self.append(Move(start_pos, end_pos))\n if len(points) > 1:\n self.line(*points[1:])\n\n def line(self, *points):\n start_pos = self.current_point\n end_pos = points[0]\n if end_pos == 'z':\n self.append(Line(start_pos, self.z_point))\n self.closed()\n return\n self.append(Line(start_pos, end_pos))\n if len(points) > 1:\n self.line(*points[1:])\n\n def absolute_v(self, *y_points):\n y_pos = y_points[0]\n start_pos = self.current_point\n self.append(Line(start_pos, Point(start_pos[0], y_pos)))\n if len(y_points) > 1:\n self.absolute_v(*y_points[1:])\n\n def relative_v(self, *dys):\n dy = dys[0]\n start_pos = self.current_point\n self.append(Line(start_pos, Point(start_pos[0], start_pos[1] + dy)))\n if len(dys) > 1:\n self.relative_v(*dys[1:])\n\n def absolute_h(self, *x_points):\n x_pos = x_points[0]\n start_pos = self.current_point\n self.append(Line(start_pos, Point(x_pos, start_pos[1])))\n if len(x_points) > 1:\n self.absolute_h(*x_points[1:])\n\n def relative_h(self, *dxs):\n dx = dxs[0]\n start_pos = self.current_point\n self.append(Line(start_pos, Point(start_pos[0] + dx, start_pos[1])))\n if len(dxs) > 1:\n self.relative_h(*dxs[1:])\n\n def smooth_quad(self, *points):\n \"\"\"Smooth curve. First control point is the \"reflection\" of\n the second control point in the previous path.\"\"\"\n start_pos = self.current_point\n control1 = self.smooth_point\n end_pos = points[0]\n if end_pos == 'z':\n self.append(QuadraticBezier(start_pos, control1, self.z_point))\n self.closed()\n return\n self.append(QuadraticBezier(start_pos, control1, end_pos))\n if len(points) > 1:\n self.smooth_quad(*points[1:])\n\n def quad(self, *points):\n start_pos = self.current_point\n control = points[0]\n if control == 'z':\n self.append(QuadraticBezier(start_pos, self.z_point, self.z_point))\n self.closed()\n return\n end_pos = points[1]\n if end_pos == 'z':\n self.append(QuadraticBezier(start_pos, control, self.z_point))\n self.closed()\n return\n self.append(QuadraticBezier(start_pos, control, end_pos))\n if len(points) > 2:\n self.quad(*points[2:])\n\n def smooth_cubic(self, *points):\n \"\"\"Smooth curve. First control point is the \"reflection\" of\n the second control point in the previous path.\"\"\"\n start_pos = self.current_point\n control1 = self.smooth_point\n control2 = points[0]\n if control2 == 'z':\n self.append(CubicBezier(start_pos, control1, self.z_point, self.z_point))\n self.closed()\n return\n end_pos = points[1]\n if end_pos == 'z':\n self.append(CubicBezier(start_pos, control1, control2, self.z_point))\n self.closed()\n return\n self.append(CubicBezier(start_pos, control1, control2, end_pos))\n if len(points) > 2:\n self.smooth_cubic(*points[2:])\n\n def cubic(self, *points):\n start_pos = self.current_point\n control1 = points[0]\n if control1 == 'z':\n self.append(CubicBezier(start_pos, self.z_point, self.z_point, self.z_point))\n self.closed()\n return\n control2 = points[1]\n if control2 == 'z':\n self.append(CubicBezier(start_pos, control1, self.z_point, self.z_point))\n self.closed()\n return\n end_pos = points[2]\n if end_pos == 'z':\n self.append(CubicBezier(start_pos, control1, control2, self.z_point))\n self.closed()\n return\n self.append(CubicBezier(start_pos, control1, control2, end_pos))\n if len(points) > 3:\n self.cubic(*points[3:])\n\n def arc(self, *arc_args):\n start_pos = self.current_point\n rx = arc_args[0]\n ry = arc_args[1]\n rotation = arc_args[2]\n arc = arc_args[3]\n sweep = arc_args[4]\n end_pos = arc_args[5]\n if end_pos == 'z':\n self.append(Arc(start_pos, rx, ry, rotation, arc, sweep, self.z_point))\n self.closed()\n return\n self.append(Arc(start_pos, rx, ry, rotation, arc, sweep, end_pos))\n if len(arc_args) > 6:\n self.arc(*arc_args[6:])\n\n def closed(self):\n start_pos = self.current_point\n end_pos = self.z_point\n self.append(Close(start_pos, end_pos))\n\n def _calc_lengths(self, error=ERROR, min_depth=MIN_DEPTH):\n if self._length is not None:\n return\n\n lengths = [each.length(error=error, min_depth=min_depth) for each in self._segments]\n self._length = sum(lengths)\n self._lengths = [each / self._length for each in lengths]\n\n def point(self, pos, error=ERROR):\n # Shortcuts\n if pos == 0.0:\n return self._segments[0].point(pos)\n if pos == 1.0:\n return self._segments[-1].point(pos)\n\n self._calc_lengths(error=error)\n # Find which segment the point we search for is located on:\n segment_start = 0\n for index, segment in enumerate(self._segments):\n segment_end = segment_start + self._lengths[index]\n if segment_end >= pos:\n # This is the segment! How far in on the segment is the point?\n segment_pos = (pos - segment_start) / (segment_end - segment_start)\n break\n segment_start = segment_end\n\n return segment.point(segment_pos)\n\n def length(self, error=ERROR, min_depth=MIN_DEPTH):\n self._calc_lengths(error, min_depth)\n return self._length\n\n def plot(self):\n for segment in self._segments:\n for e in segment.plot():\n yield e\n\n def insert(self, index, value):\n self._segments.insert(index, value)\n self._length = None\n\n def reverse(self):\n reversed_segments = self._segments[::-1]\n for i in range(0, len(reversed_segments)):\n reversed_segments[i] = reversed_segments[i].reverse()\n path = Path()\n path._segments = reversed_segments\n return path\n\n def as_subpaths(self):\n last = 0\n subpath = Path()\n for current, seg in enumerate(self):\n if current != last and isinstance(seg, Move):\n subpath._segments = self[last:current]\n yield subpath\n last = current\n subpath._segments = self[last:]\n yield subpath\n\n def as_points(self):\n \"\"\"Returns the list of defining points within path\"\"\"\n for seg in self:\n for p in seg:\n if not isinstance(p, Point):\n yield Point(p)\n else:\n yield p\n\n def bbox(self):\n \"\"\"returns a bounding box for the input Path\"\"\"\n bbs = [seg.bbox() for seg in self._segments if not isinstance(Close, Move)]\n try:\n xmins, ymins, xmaxs, ymaxs = list(zip(*bbs))\n except ValueError:\n return None # No bounding box items existed. So no bounding box.\n xmin = min(xmins)\n xmax = max(xmaxs)\n ymin = min(ymins)\n ymax = max(ymaxs)\n return xmin, ymin, xmax, ymax\n\n def d(self):\n parts = []\n previous_segment = None\n if len(self) == 0:\n return ''\n for segment in self:\n if isinstance(segment, Move):\n parts.append('M {0:G},{1:G}'.format(segment.end[0], segment.end[1]))\n elif isinstance(segment, Line):\n parts.append('L {0:G},{1:G}'.format(\n segment.end[0], segment.end[1])\n )\n elif isinstance(segment, CubicBezier):\n if segment.is_smooth_from(previous_segment):\n parts.append('S {0:G},{1:G} {2:G},{3:G}'.format(\n segment.control2[0], segment.control2[1],\n segment.end[0], segment.end[1])\n )\n else:\n parts.append('C {0:G},{1:G} {2:G},{3:G} {4:G},{5:G}'.format(\n segment.control1[0], segment.control1[1],\n segment.control2[0], segment.control2[1],\n segment.end[0], segment.end[1])\n )\n elif isinstance(segment, QuadraticBezier):\n if segment.is_smooth_from(previous_segment):\n parts.append('T {0:G},{1:G}'.format(\n segment.end[0], segment.end[1])\n )\n else:\n parts.append('Q {0:G},{1:G} {2:G},{3:G}'.format(\n segment.control[0], segment.control[1],\n segment.end[0], segment.end[1])\n )\n\n elif isinstance(segment, Arc):\n parts.append('A {0:G},{1:G} {2:G} {3:d},{4:d} {5:G},{6:G}'.format(\n segment.rx, segment.ry, segment.get_rotation().as_degrees,\n int(abs(segment.sweep) > (tau / 2.0)), int(segment.sweep >= 0),\n segment.end[0], segment.end[1])\n )\n elif isinstance(segment, Close):\n parts.append('Z')\n previous_segment = segment\n return ' '.join(parts)\n","sub_path":"path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":83824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"608804767","text":"# Determine if a string has all unique characters\n\n# With an auxiliary data structure\ndef all_unique(astring):\n astring = astring.lower()\n astring = astring.replace(' ', '')\n\n characters = {}\n\n for char in astring:\n if char not in characters:\n characters[char] = 1\n else:\n return 'Not all unique'\n return 'All unique'\n\nprint(all_unique('Hello world'))\nprint(all_unique('world '))\n\n\n# Without an auxiliary data structure\n\ndef all_unique2(astring):\n astring = astring.lower()\n astring = astring.replace(' ', '')\n\n count = 0\n\n for char in astring:\n count = astring.count(char)\n if count>1:\n return 'Not all unique'\n astring = astring.replace(char, '')\n return 'All unique'\n\nprint(all_unique2('Hello world'))\nprint(all_unique2('world '))\n\n\n# Without auxiliary data structure - simplest\n\ndef all_unique3(astring):\n # use set function \n # it returns a set of all the characters in the string, duplicates removed\n # if a string only contains unique chars, the length of the set will be equal to the length of the original string as nothing will have been removed\n # if a string contains duplicates, the length of the set will be different to the length of the original string\n\n astring = astring.lower()\n astring = astring.replace(' ', '')\n\n return len(astring) == len(set(astring))\n\nprint(all_unique3('Hello world'))\nprint(all_unique3('world '))\n \n \n \n\n","sub_path":"string processing/strings_all_unique.py","file_name":"strings_all_unique.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"627027351","text":"from __future__ import unicode_literals\n\nfrom .. import (\n filename_parser_re, find_objects_below, nop, pypeline_setup,\n LazyFakeModule, TestCase,\n)\n\n\nclass T(TestCase):\n def test(self):\n pypeline_setup()\n parse_filename_re = filename_parser_re(r'xpypefakemods')\n rv = find_objects_below(r'xpypefakemods', just_modules=True)\n rv = tuple(rv)\n rv = rv[0]\n l = LazyFakeModule(rv, parse_filename_re)\n ns = dict(l=l)\n _0, _1, _2 = self.try_eval(ns)\n expected = True, True, AttributeError\n actual = _0() == r'xpypefakemods.a.a', _0 is _1, _2\n self.assert_are(expected, actual)\n\n @staticmethod\n def try_eval(ns):\n g = r'aab'\n for y in (r'l.' + y for y in g):\n try:\n y = eval(y, ns) # pylint: disable=eval-used\n except AttributeError as e:\n y = e.__class__\n else:\n nop()\n yield y\n","sub_path":"pypeline/test/dyload/lazy_load.py","file_name":"lazy_load.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"439340600","text":"from Tkinter import *\nclass App:\n def __init__(self, master):\n frame=Frame(master)\n frame.pack()\n self.button=Button(frame, text=\"QUIT\", fg=\"red\",command=master.destroy)\n self.button.pack(side=LEFT)\n self.slogan=Button(frame, text=\"Wanna see a fat cat?\",\n command=self.create_window)\n self.slogan.pack(side=LEFT)\n def create_window(self):\n window=Toplevel(root)\n logo=PhotoImage(file=\"/Users/Guzel/Desktop/CSCI233/fatcat.gif\")\n words=\"Fatty-fatty catty\"\n w1=Label(window,compound=CENTER, text=words,font=\"Baskerville 24 bold\",\n fg=\"turquoise\", wraplength=300)\n w1.pack()\n w1.image=logo\nroot=Tk()\nroot.title(\"CatMad\")\napplic=App(root)\nroot.mainloop()\n\nprint (\"Oh my, oh my!!!\")\n \n","sub_path":"tkinter1.py","file_name":"tkinter1.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525895293","text":"import os\nimport inspect\n\nfrom . import hooks\n# Set version\n__version__ = (1, 0, 0)\n\n# Set root directory\nif \"runpy.py\" in inspect.stack()[-1][1]:\n _ROOT = os.path.abspath(os.path.dirname(inspect.stack()[0][1]))\nelse:\n _ROOT = os.path.abspath(os.path.dirname(inspect.stack()[-1][1]))\n\n# Get data file\ndef get_data(file):\n return os.path.join(_ROOT, 'data', file)\n","sub_path":"deploypy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150136344","text":"#!/usr/bin/python\n\nimport auto\nimport sys\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 2:\n\t\tprint('please enter an input string')\n\t\tsys.exit()\n\n\tinputString = sys.argv[1]\n\n\tstate0 = auto.State(0, {'0': 1, '1': 2, '.': 3})\n\tstate1 = auto.State(1, { '1': 2, '.': 3})\n\tstate2 = auto.State(2, {'0': 1, '.': 3})\n\tstate3 = auto.State(3, {'0': 4, '.': 6})\n\tstate4 = auto.State(4, {'0': 5 })\n\tstate5 = auto.State(5, {'0': 3 })\n\tstate6 = auto.State(6, { '.': 7})\n\tstate7 = auto.State(7, { })\n\n\tstateList = [state0, state1, state2, state3, state4, state5, state6, state7]\n\tautomata = auto.StateMachine(stateList)\n\n\tfor char in inputString:\n\t\tif not automata.move(char):\n\t\t\tprint('parse error')\n\t\t\tsys.exit()\n\n\tprint('parse complete, no error occured')\n","sub_path":"Lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"134708262","text":"\"\"\"\nHMM module\n\nContains an Ngram Hidden Markov Model implementation that\nhandles a special case of only predicting hidden states\nthat are not already given.\n\nFor example: our use case is given a partial sentenc with BLANKS\nand tags, we predict what words fill in the BLANKs to create the\nmost probable sentence\n\nCasey Gowrie\nCOMP150NLP\n5/12/16\n\"\"\"\n\nimport sys\nimport operator\nimport string\nfrom collections import defaultdict\nfrom collections import Counter\nfrom nltk.corpus import treebank\nfrom nltk.tag.util import untag # Untags a tagged sentence. \n\nfrom ngramLM import *\nfrom utils import *\n\n\n\nclass NgramHMM:\n \"\"\" Class to represent Hidden Markov model to determine best labels\n on a partially unlabeled sequence.\n\n Takes a n to use for ngram context in state sequence probs\n \"\"\"\n\n def __init__(self, n, vocabulary = set()):\n \"\"\" Initializes the NgramHMM class, using ngram context for state\n \"\"\"\n self.n = n\n self.vocabulary = vocabulary\n\n # counter for all states in training corpus\n self.state_counts = Counter() \n # observations -> state list\n self.obeservations_to_states = defaultdict(list) \n # observations -> state counter for word\n self.obeservations_to_state_count = defaultdict(lambda: Counter())\n\n self.A = NgramLM(self.n) # Transition probs, determined with NgramLM\n self.B = defaultdict(lambda: defaultdict(float)) # Emission probs\n\n def train(self, training_set):\n \"\"\" Trains the HMM, calculating tansition and emission \n probabilities from the given data\n\n Args:\n training_set -- list of labeled observation sequences\n \"\"\"\n state_list = []\n for sequence in training_set:\n for (o,q) in sequence:\n self.obeservations_to_states[o].append(q)\n state_list.append(q)\n\n # create counters\n self.state_counts = Counter(state_list)\n for obs, state_list in self.obeservations_to_states.items():\n self.obeservations_to_state_count[obs] = Counter(state_list)\n\n # create emmision probabilities given counts\n for obs, state_counter in self.obeservations_to_state_count.items():\n for q, count in state_counter.items():\n self.B[obs][q] = float(count) / float(self.state_counts[q])\n\n # train the ngram linear model using states from train_set\n state_vocab = self.state_counts.keys()\n self.A = NgramLM(self.n, state_vocab)\n training_states = just_labels(training_set)\n self.A.train(training_states)\n self.A.estimate_Ngrams(training_states)\n\n def joint_probability(self, labeled_sequence):\n \"\"\" Computes joint probability of a labeled seq based on Trained\n model, starting at first real label (not including start state).\n \"\"\"\n logProb = 0.0\n\n for i in range(self.n - 1, len(labeled_sequence)):\n obs, state = labeled_sequence[i]\n states = [s for (o,s) in labeled_sequence[i - self.n + 1:i + 1]]\n prior = self.A.prob(tuple(states))\n likelihood = self.B[obs][state]\n logProb += log(prior) + log(likelihood)\n\n return logProb\n\n def corpus_joint_probability(self, labeled_sequence):\n \"\"\" Computes joint log probability for entire list of seqs \"\"\"\n return sum([self.joint_probability(s) for s in labeled_sequence])\n\n \n def __viterbi_prob(self, viterbi, obs, state, prev_states, t):\n \"\"\" Computes the best joint log probability for labeling,\n transitioning from the previous labels used in step t-1\n\n Args:\n viterbi -- matrix up to current timestep\n obs -- observation being labeled\n states -- potential states to compute prob for\n prev_states -- states used in previous timestep to get viterbi from t-1\n t -- timestep of observation\n\n Returns:\n tuple with the previous states that resulted in best joint prob and\n max log probability\n \"\"\"\n\n prev_viterbis = [viterbi[prev[-1]][t-1] for prev in prev_states]\n a_ijs = [log(self.A.prob(prev + (state,))) for prev in prev_states]\n b_ts = log(self.B[obs][state])\n probs = [b_ts + x + y for (x, y) in zip(prev_viterbis, a_ijs)]\n\n max_index, max_prob = max(enumerate(probs), key=lambda l: l[1])\n return (prev_states[max_index], max_prob)\n\n def __follow_backpointers(self, backpointer, t):\n \"\"\" Returns a list of states through following the backpointers \n from end state\n \"\"\"\n labels = []\n q = END_TOKEN\n i = t - 1\n while i >= 0:\n labels = [q] + labels\n q = backpointer[q][i + 1][-1]\n i -= 1\n\n return labels\n\n def viterbi(self, sequence):\n \"\"\" Runs the viterbi algorithm and returns the best labeling\n of the partially unlabeled sequence provided\n\n The viterbi modification shown here only predicts the hidden\n state if the state associated with the sequence is BLANK, otherwise\n the hidden state is given to us\n\n Note this implementation doesn't consider all sates for a obs,\n just the ones that were seen associated with it at train time\n\n Args:\n sequence -- labeled sequence\n \"\"\"\n\n viterbi = defaultdict(lambda: defaultdict(float))\n backpointer = defaultdict(lambda: defaultdict(str))\n\n most_common_state = self.state_counts.most_common(1)[0]\n\n # init, generalized to account for start token padding\n for i in range(1, self.n):\n viterbi[START_TOKEN][i] = 1.0\n backpointer[START_TOKEN][i] = (START_TOKEN,) * (self.n - 1)\n prev_states = [(START_TOKEN,) * (self.n - 1)]\n\n\n allinf = True # if all log probs at time step are -inf\n t = len(sequence)\n # recusion\n for i in range(self.n, t):\n allinf = True\n obs = sequence[i - 1][0]\n potential_state = sequence[i - 1][1]\n\n # determine whether we need to attempt to label\n if potential_state == BLANK_TOKEN:\n # add most common tag in case no states for tag, \n # also ensures prev not empty\n states = self.B[obs].keys() + [most_common_state]\n else:\n # if we don't need to label, only give one option\n states = [potential_state]\n \n for q in states:\n bp, max_prob = self.__viterbi_prob(viterbi, obs, q, \\\n prev_states, i)\n viterbi[q][i] = max_prob\n backpointer[q][i] = bp\n\n if max_prob != float(\"-inf\"): # received non -inf log prob\n allinf = False\n\n # if state prob is 0 for all obs, reset viterbi matrix at time i\n if allinf:\n for q in states:\n viterbi[q][i] = 0.0\n\n # get list of obs from previous obs state\n prev_states = [tuple(backpointer[s][i][1:]) + (s,) for s in states]\n\n\n # finalize\n bp, max_prob = self.__viterbi_prob(viterbi, sequence[t-1][0], \\\n END_TOKEN, prev_states, t)\n viterbi[END_TOKEN][t] = max_prob\n backpointer[END_TOKEN][t] = bp\n\n labeled_seq = zip(untag(sequence), \\\n self.__follow_backpointers(backpointer, t))\n return labeled_seq\n\n def test(self, unlabeled_seqs):\n return [self.viterbi(s) for s in unlabeled_seqs]\n","sub_path":"hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":7565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"136365075","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: MIT. See LICENSE\n\nimport frappe\nfrom frappe.model.document import Document\n\n\nclass DocField(Document):\n\tdef get_link_doctype(self):\n\t\t\"\"\"Returns the Link doctype for the docfield (if applicable)\n\t\tif fieldtype is Link: Returns \"options\"\n\t\tif fieldtype is Table MultiSelect: Returns \"options\" of the Link field in the Child Table\n\t\t\"\"\"\n\t\tif self.fieldtype == \"Link\":\n\t\t\treturn self.options\n\n\t\tif self.fieldtype == \"Table MultiSelect\":\n\t\t\ttable_doctype = self.options\n\n\t\t\tlink_doctype = frappe.db.get_value(\n\t\t\t\t\"DocField\",\n\t\t\t\t{\"fieldtype\": \"Link\", \"parenttype\": \"DocType\", \"parent\": table_doctype, \"in_list_view\": 1},\n\t\t\t\t\"options\",\n\t\t\t)\n\n\t\t\treturn link_doctype\n\n\tdef get_select_options(self):\n\t\tif self.fieldtype == \"Select\":\n\t\t\toptions = self.options or \"\"\n\t\t\treturn [d for d in options.split(\"\\n\") if d]\n\n\tdef __repr__(self):\n\t\tunsaved = \"unsaved\" if not self.name else \"\"\n\t\tdoctype = self.__class__.__name__\n\n\t\tdocstatus = f\" docstatus={self.docstatus}\" if self.docstatus else \"\"\n\t\tparent = f\" parent={self.parent}\" if getattr(self, \"parent\", None) else \"\"\n\n\t\treturn f\"<{self.fieldtype}{doctype}: {self.fieldname}{docstatus}{parent}{unsaved}>\"\n","sub_path":"frappe/core/doctype/docfield/docfield.py","file_name":"docfield.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"271531070","text":"import os\n\nimport rosbag\nimport pandas as pd\n\nfrom manual.update import update_yolo_data, update_images_bBox\nfrom constants import CLASS_BAG, BAG_NAME, EVENT_FOLDER, BAG_BASE_PATH\nfrom events.anotation import anotate_events\nfrom events.plot_data import plot_events_imgs_by_name, plot_events_images, plot_all_events_at_image_fr\n\n\ndef get_number_of_annotated_events(class_name, bag_name, data_folder=\"data_bBox\"):\n folder = os.path.join(os.path.join(data_folder, class_name), bag_name)\n folder = os.path.join(folder, EVENT_FOLDER)\n\n annot_file = os.path.join(folder, \"annotate_events.txt\")\n if not os.path.exists(annot_file):\n return 0\n with open(annot_file) as fd:\n return len(fd.readlines()) - 1\n\n\ndef fix_csv_unnamed(f='data_bBox/chair/Record01/events/annotate_events.txt'):\n df = pd.read_csv(f, index_col=0)\n df.to_csv(f, index=False)\n\n\nif __name__ == \"__main__\":\n class_bag = CLASS_BAG\n bag_name = BAG_NAME\n path = os.path.join(BAG_BASE_PATH, \"{0}/{1}.bag\".format(class_bag, bag_name))\n bag = rosbag.Bag(path)\n # img_annotate_file = \"annotate.txt\"\n img_annotate_file = \"edited_annotate.txt\"\n\n start_indx = get_number_of_annotated_events(class_bag, bag_name)\n print(start_indx)\n ammount = -1\n\n # update_yolo_data(CLASS_BAG, BAG_NAME)\n # update_images_bBox(class_bag, bag)\n\n anotate_events(bag, class_bag=class_bag, start_indx=start_indx,\n how_many=ammount, img_annotate_file=img_annotate_file)\n # plot_events_images(class_bag, bag_name)\n # plot_events_imgs_by_name(class_bag, bag_name, \"1594373652690415658.png\")\n # 1594373551270458649.png\n # plot_all_events_at_image_fr(bag, class_bag=class_bag, img_annotate_file=img_annotate_file)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164978593","text":"def dfs(adj, visited, current_node):\n if visited[current_node] != 0:\n return\n\n visited[current_node] = 1\n\n for i in range(len(adj[current_node])): # not a pythonic way\n adjacent_node = adj[current_node][i]\n if visited[adjacent_node] == 0:\n dfs(adj, visited, adjacent_node)\n\n print(current_node, end=' ')\n\n # for neighbour in adj[current_node]: # pythonic way\n # if visited[neighbour] == 0: # if neighbour not in visited:\n # dfs(adj, visited, neighbour)\n\n\nn = int(input(\"Enter the number of nodes: \"))\ne = int(input(\"Enter the number of edges: \"))\n\nadj_list = [[] for i in range(n)]\n\nprint(\"Enter edges in separate lines.\")\nfor i in range(e):\n u, v = map(int, input().split())\n adj_list[u].append(v)\n adj_list[v].append(u)\n\n\nprint(adj_list)\n\nvisited = [0 for i in range(n)]\nprint('DFS: ', end=\"\")\nfor i in range(n):\n if visited[i] == 0:\n dfs(adj_list, visited, i)\n\n\n\"\"\"\nSample input / output\nEnter the number of nodes: 5\nEnter the number of edges: 4\nEnter edges in separate lines.\n0 2\n2 1\n2 3\n0 4\nDFS: 1 3 2 4 0\n\"\"\"","sub_path":"graph_dfs.py","file_name":"graph_dfs.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226992280","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, ValidationError\nimport datetime\nimport random\n\ntry: \n import qrcode\nexcept ImportError:\n qrcode = None\n\nimport base64\nimport io\nimport xlwt\nimport xlsxwriter\nimport requests\n\n#Encuestas\nclass Survey(models.Model):\n _inherit = 'survey.survey'\n \n qr_survey = fields.Binary('QR Survey')\n qr_survey_name = fields.Char(default=\"survey_qr.png\")\n excel_file_result = fields.Binary('Excel file result')\n excel_file_result_name = fields.Char('Excel file result name', size=64)\n \n def generate_qr(self):\n qr = qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=20,border=4,)\n name = self.title+'_QR.png'\n qr.add_data(self.public_url)\n qr.make(fit=True)\n img = qr.make_image()\n buffer = io.BytesIO() \n img.save(buffer, format=\"PNG\")\n img_str = base64.b64encode(buffer.getvalue())\n self.write({'qr_survey': img_str,'qr_survey_name':name})\n \n action = {\n 'name': 'QrEncuesta',\n 'type': 'ir.actions.act_url',\n 'url': \"web/content/?model=survey.survey&id=\" + str(self.id) + \"&filename_field=qr_survey_name&field=qr_survey&download=true&filename=\" + self.qr_survey_name,\n 'target': 'self',\n }\n return action\n\n def generate_excel(self):\n \n #Traer Columnas\n \n #Traer Preguntas \n obj_survey_question = self.env['survey.question'].search([('survey_id', '=', self.id),('is_page','=',False)])\n #Traer entrada de usuario\n obj_survey_user_input = self.env['survey.user_input'].search([('survey_id', '=', self.id)])\n #Traer label\n question_matrix = []\n for question in obj_survey_question: \n matrix = []\n obj_survey_label = self.env['survey.label'].search([('question_id_2', '=', question.id)])\n if obj_survey_label:\n matrix.append(question.title)\n for label in obj_survey_label:\n matrix.append(label.value)\n question_matrix.append(matrix)\n \n #query_columns = '''\n # Select distinct\n # b.title || ' ' || case when d.value_suggested_row is not null then e.value else '' end as Pregunta\n # from survey_survey as A\n # inner join survey_question as b on b.survey_id = a.id\n # inner join survey_user_input as c on c.survey_id = a.id\n # inner join survey_user_input_line as d on D.user_input_id = c.id and a.id = d.survey_id and b.id = d.question_id\n # left join survey_label as e on d.value_suggested = e.id\n # left join survey_label as f on d.value_suggested_row = f.id\n # where a.id = %s\n #''' % (self.id)\n \n #self._cr.execute(query_columns)\n #result_columns = self._cr.dictfetchall()\n \n columns_str = ''\n for question in obj_survey_question: \n text_question = question.title\n \n #Recorrer Array question matrix\n text_questions_matrix = ''\n for m in question_matrix:\n text_question_q = ''\n i = 1\n for q in m: \n if i == 1:\n text_question_q = q\n if text_question_q == text_question and i != 1: \n if text_questions_matrix != '':\n text_questions_matrix = text_questions_matrix+'|'+text_question_q+' - '+q \n else:\n text_questions_matrix = text_question_q+' - '+q \n i = i + 1\n if text_questions_matrix:\n text_question = text_questions_matrix\n \n #Asignar Columnas\n if columns_str != '':\n columns_str = columns_str+'|'+text_question\n else:\n columns_str = text_question\n \n #columns_str = 'Encuesta creada por|Quien Responde|'+columns_str\n columns = columns_str.split(\"|\")\n #raise ValidationError(_(columns)) \n \n #Traer Consultas\n \n #Traer Preguntas \n obj_survey_question = self.env['survey.question'].search([('survey_id', '=', self.id),('is_page','=',False)])\n #Traer entrada de usuario\n obj_survey_user_input = self.env['survey.user_input'].search([('survey_id', '=', self.id),('state','=','done')])\n \n results = []\n for user_input in obj_survey_user_input:\n result_user = []\n result_user.append('IDUSER:'+str(user_input.id))\n for question in obj_survey_question:\n obj_survey_user_input_line = self.env['survey.user_input_line'].search([('survey_id', '=', self.id),('user_input_id','=',user_input.id),('question_id','=',question.id)])\n for result in obj_survey_user_input_line:\n if result.value_suggested and result.value_suggested_row: \n result_user.append(question.title+' - '+result.value_suggested_row.value)\n else:\n result_user.append(question.title)\n \n if result.value_text:\n result_user.append(result.value_text)\n if result.value_number:\n result_user.append(result.value_number)\n if result.value_date:\n result_user.append(result.value_date)\n if result.value_datetime:\n result_user.append(result.value_datetime)\n if result.value_free_text:\n result_user.append(result.value_free_text)\n if result.value_little_faces:\n result_user.append(result.value_little_faces)\n if result.value_suggested:\n result_user.append(result.value_suggested.value) \n #value_suggested,value_suggested_row\n results.append(result_user)\n \n #query = '''\n # Select c.id,\n # b.title || ' ' || case when d.value_suggested_row is not null then e.value else '' end as Pregunta,\n # Usu_respu.name as Usuario_Respuesta,\n # case when d.answer_type = 'text' then d.value_text\n # when d.answer_type = 'number' then cast(d.value_number as varchar)\n # when d.answer_type = 'date' then cast(d.value_date as varchar)\n # when d.answer_type = 'datetime' then cast(d.value_datetime as varchar)\n # when d.answer_type = 'suggestion' and d.value_suggested_row is null then cast(e.value as varchar)\n # when d.answer_type = 'suggestion' and d.value_suggested_row is not null then cast(f.value as varchar)\n # when d.answer_type = 'free_text' then cast(d.value_free_text as varchar) \n # when d.answer_type = 'little_faces' then cast(d.value_little_faces as varchar) else '' end as Respuesta,\n # usu_crea.\"name\" as Encuenta_Creada_Por\n # from survey_survey as A\n # \n # inner join survey_question as b on b.survey_id = a.id\n # inner join survey_user_input as c on c.survey_id = a.id\n # inner join survey_user_input_line as d on D.user_input_id = c.id and a.id = d.survey_id and b.id = d.question_id\n # left join survey_label as e on d.value_suggested = e.id\n # left join survey_label as f on d.value_suggested_row = f.id\n # \n # left join res_users n on n.id = a.create_uid\n # left join res_users o on o.id = a.write_uid\n # left join res_users p on p.id = c.write_uid\n # left join res_partner usu_crea on usu_crea.id = n.partner_id\n # left join res_partner usu_mod on usu_mod.id = o.partner_id\n # left join res_partner Usu_respu on Usu_respu.id = p.partner_id\n # where a.id = %s \n # order by c.id, b.\"sequence\"\n #''' % (self.id)\n \n #self._cr.execute(query)\n #result_query = self._cr.dictfetchall()\n \n if results and columns: \n filename= 'Resultados-'+str(self.title)+'.xlsx'\n stream = io.BytesIO()\n book = xlsxwriter.Workbook(stream, {'in_memory': True})\n sheet = book.add_worksheet(str(self.title))\n\n #Agregar columnas\n aument_columns = 0\n for col in columns: \n sheet.write(0, aument_columns, col)\n aument_columns = aument_columns + 1\n \n #Agregar respuestas\n i_user = 1\n aument_columns = 0\n aument_rows = 1\n id_user = ''\n id_user_ant = ''\n str_pregunta = ''\n str_respuesta = ''\n for query in results: \n if i_user == 1:\n id_user_ant = query[0] \n else:\n id_user_ant = id_user \n id_user = query[0]\n \n if id_user != id_user_ant: \n aument_rows = aument_rows + 1\n \n i = 1\n for result_x_user in query:\n if i != 1:\n #Si la posición en el array es par es pregunta sino es respuesta\n if i % 2 == 0:\n str_pregunta = result_x_user\n else:\n str_respuesta = result_x_user\n \n if str_pregunta and str_respuesta:\n position_col = 0\n for col in columns:\n if col == str_pregunta: \n sheet.write(aument_rows, position_col, str_respuesta)\n str_pregunta = ''\n str_respuesta = ''\n position_col = position_col + 1 \n i = i + 1\n \n \n i_user = i_user + 1\n \n book.close()\n \n self.write({\n 'excel_file_result': base64.encodestring(stream.getvalue()),\n 'excel_file_result_name': filename,\n })\n \n action = {\n 'name': str(self.title),\n 'type': 'ir.actions.act_url',\n 'url': \"web/content/?model=survey.survey&id=\" + str(self.id) + \"&filename_field=excel_file_result_name&field=excel_file_result&download=true&filename=\" + self.excel_file_result_name,\n 'target': 'self',\n }\n return action \n \n \n\nclass SurveyQuestion(models.Model):\n _inherit = 'survey.question'\n \n question_type = fields.Selection(selection_add = [('little_faces', 'Califíquenos')], string='Question Type')\n \n \nclass SurveyUserInputLine(models.Model):\n _inherit = 'survey.user_input_line'\n \n answer_type = fields.Selection(selection_add = [('little_faces', 'little_faces')], string='Answer Type')\n value_little_faces = fields.Integer('Nivel de Satisfacción (Emojis)')\n \n @api.constrains('answer_type')\n def _check_answer_type(self):\n for uil in self:\n fields_type = {\n 'text': bool(uil.value_text),\n 'number': (bool(uil.value_number) or uil.value_number == 0),\n 'date': bool(uil.value_date),\n 'free_text': bool(uil.value_free_text),\n 'suggestion': bool(uil.value_suggested),\n 'little_faces': bool(uil.value_little_faces)\n }\n if not fields_type.get(uil.answer_type, True):\n raise ValidationError(_('The answer must be in the right type'))\n \n @api.model\n def save_line_little_faces(self, user_input_id, question, post, answer_tag):\n vals = {\n 'user_input_id': user_input_id,\n 'question_id': question.id,\n 'survey_id': question.survey_id.id,\n 'skipped': False\n }\n if answer_tag in post and post[answer_tag].strip():\n vals.update({'answer_type': 'little_faces', 'value_little_faces': post[answer_tag]})\n else:\n vals.update({'answer_type': None, 'skipped': True})\n old_uil = self.search([\n ('user_input_id', '=', user_input_id),\n ('survey_id', '=', question.survey_id.id),\n ('question_id', '=', question.id)\n ])\n if old_uil:\n old_uil.write(vals)\n else:\n old_uil.create(vals)\n return True","sub_path":"logyca/models/models_survey.py","file_name":"models_survey.py","file_ext":"py","file_size_in_byte":13392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222357997","text":"\"\"\" \nThis module provides several preprocessing functions to change raw feature vectors \ninto a representation that is more suitable for the downstream estimators. \n\"\"\"\n\nfrom prep import constants\nimport numpy as np\n\ndef split_dataset(input_data, target_data, normalized_input_data = None, proportion = constants.data_proportion, shuffle = True):\n \"\"\" Return training set and testing set in tuple.\n\n # Arguments:\n\n input_data: numpy array\n The numpy array which is used as the input of the model. \n target_data: numpy array\n The numpy array which is used as the target of the model's output.\n normalized_input_data: numpy array, optional\n The numpy array which is normalized input data.\n proportion: float, optional\n Float between 0 and 1. Fraction of the data to be used as training data.\n shuffle: boolean, optional\n Whether to shuffle the training data before splitting.\n\n # Return:\n\n Tuple of Numpy arrays: (x_train, y_train, z_train), (x_test, y_test, z_test) if 'normalized_input_data' is not None\n x_train and x_test are numpy arrays used for training, \n y_train and y_test are numpy arrays used for testing,\n z_train and z_test are numpy arrays used for simulation.\n\n Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test) if 'normalized_input_data' is None\n x_train and x_test are numpy arrays used for training, \n y_train and y_test are numpy arrays used for testing.\n \"\"\"\n\n # Insert debugging assertions\n assert type(input_data) is np.ndarray, \"The 'input_data' must be numpy array.\"\n assert type(target_data) is np.ndarray, \"The 'target_data' must be numpy array.\"\n assert type(normalized_input_data) is np.ndarray or normalized_input_data is None, \"The 'normalized_input_data' must be numpy array or None.\"\n assert len(input_data) == len(target_data), \"The 'input_data' and the 'target_data' must have same size along the first axis (batch size).\"\n assert 0 <= proportion <= 1, \"The 'proportion' must be float between 0 and 1.\"\n assert type(shuffle) is bool, \"The 'shuffle' must be boolean.\"\n\n # Initialization of variables\n num_of_samples = len(input_data)\n\n if normalized_input_data is not None:\n # Shuffle the input numpy array along the first axis. The order is changed but their contents remains the same \n if shuffle:\n randomize = np.arange(len(normalized_input_data))\n np.random.shuffle(randomize)\n normalized_input_data = normalized_input_data[randomize]\n input_data = input_data[randomize]\n target_data = target_data[randomize]\n\n # Calculate the slicing index\n slice_index = int(num_of_samples * proportion)\n\n # Split the normalized input data into training part and testing part\n x_train = normalized_input_data[:slice_index]\n x_test = normalized_input_data[slice_index:]\n\n # Split the target data into training part and testing part\n y_train = target_data[:slice_index]\n y_test = target_data[slice_index:]\n\n # Split the input data into training part and testing part\n z_train = input_data[:slice_index]\n z_test = input_data[slice_index:]\n\n # Return traning set and testing set \n return (x_train, y_train, z_train), (x_test, y_test, z_test)\n\n else:\n # Shuffle the input numpy array along the first axis. The order is changed but their contents remains the same \n if shuffle:\n randomize = np.arange(len(input_data))\n np.random.shuffle(randomize)\n input_data = input_data[randomize]\n target_data = target_data[randomize]\n\n # Calculate the slicing index\n slice_index = int(num_of_samples * proportion)\n\n # Split the input data into training part and testing part\n x_train = input_data[:slice_index]\n x_test = input_data[slice_index:]\n\n # Split the target data into training part and testing part\n y_train = target_data[:slice_index]\n y_test = target_data[slice_index:]\n\n # Return traning set and testing set \n return (x_train, y_train), (x_test, y_test)\n\ndef get_input_shape(input_data):\n \"\"\" Return input shape (does not include the batch axis) of the given input numpy array.\n\n # Argument:\n\n input_data: numpy array\n The numpy array which is used as the input of the model. \n\n # Return:\n\n input_shape: tuple\n Tuple of interger, does not include the batch axis.\n e.g. input_shape = (3, 128, 128) for 128 x 128 RGB image if data_format = 'channels_first', \n or (128, 128, 3) for 128 x 128 RGB image if data_format = 'channels_last'.\n \"\"\"\n\n # Insert debugging assertions\n assert type(input_data) is np.ndarray, \"The 'input_data' must be numpy array.\"\n\n # Calculate the shape of input data and exclude the batch axis\n input_shape = input_data.shape[1:]\n\n # Return input shape\n return input_shape\n\ndef get_target_shape(target_data):\n \"\"\" Return target shape (does not include the batch axis) of the given target numpy array.\n\n # Argument:\n\n target_data: numpy array\n The numpy array which is used as the target of the model's output. \n\n # Return:\n\n target_shape: int\n Dimensionality of the output space.\n \"\"\"\n\n # Insert debugging assertions\n assert type(target_data) is np.ndarray, \"The 'target_data' must be numpy array.\"\n\n # Calculate the shape of target data and exclude the batch axis\n target_shape = target_data.shape[1]\n\n # Return target shape\n return target_shape\n\ndef reshape_input_data_3D(input_data, image_data_format, rows, cols, channels):\n \"\"\" Gives a new shape (3D) to input numpy array without changing its data.\n\n # Arguments:\n\n input_data: numpy array\n The numpy array which is used as the input of the model.\n image_data_format: string\n Either 'channels_first' or 'channels_last'.\n It specifics which data format convention Keras will follow. (keras.backend.image_data_format() returns it)\n rows: int\n The first dimension of the new shape (does not include the batch axis).\n cols: int\n The second dimension of the new shape (does not include the batch axis).\n channels: int\n The third dimension of the new shape (does not include the batch axis).\n\n # Return \n\n reshaped_input_data: numpy array\n This will be a new view object if possible; otherwise, the ValueError will be raised.\n \"\"\"\n\n # Insert debugging assertions\n assert type(input_data) is np.ndarray, \"The 'input_data' must be numpy array.\"\n assert type(image_data_format) is str, \"The 'image_data_format' must be string.\"\n assert type(rows) is int, \"The 'rows' must be integer.\"\n assert type(cols) is int, \"The 'cols' must be integer.\"\n assert type(channels) is int, \"The 'channels' must be integer.\"\n\n # Initialization of variables\n batch_size = len(input_data)\n\n # Reshape the input data\n if image_data_format == 'channels_first':\n reshaped_input_data = np.reshape(input_data, (batch_size, channels, rows, cols))\n elif image_data_format == 'channels_last':\n reshaped_input_data = np.reshape(input_data, (batch_size, rows, cols, channels))\n else:\n raise ValueError(\"The 'image_data_format' must be 'channels_first' or 'channels_last'.\") \n\n # Return reshaped input data\n return reshaped_input_data\n\ndef reshape_input_data_2D(input_data, steps, channels):\n \"\"\" Gives a new shape (2D) to input numpy array without changing its data.\n\n # Arguments:\n\n input_data: numpy array\n The numpy array which is used as the input of the model.\n steps: int\n The first dimension of the new shape (does not include the batch axis).\n channels: int\n The second dimension of the new shape (does not include the batch axis).\n\n # Return \n\n reshaped_input_data: numpy array\n This will be a new view object if possible; otherwise, the ValueError will be raised.\n \"\"\"\n\n # Insert debugging assertions\n assert type(input_data) is np.ndarray, \"The 'input_data' must be numpy array.\"\n assert type(steps) is int, \"The 'steps' must be integer.\"\n assert type(channels) is int, \"The 'channels' must be integer.\"\n\n # Initialization of variables\n batch_size = len(input_data)\n\n # Reshape the input data\n reshaped_input_data = np.reshape(input_data, (batch_size, steps, channels))\n\n # Return reshaped input data\n return reshaped_input_data\n\ndef reshape_input_data_1D(input_data):\n \"\"\" Gives a new shape (1D) to input numpy array without changing its data.\n\n # Arguments:\n\n input_data: numpy array\n The numpy array which is used as the input of the model.\n \n # Return \n\n reshaped_input_data: numpy array\n This will be a new view object if possible; otherwise, the ValueError will be raised.\n \"\"\"\n\n # Insert debugging assertions\n assert type(input_data) is np.ndarray, \"The 'input_data' must be numpy array.\"\n\n # Initialization of variables\n batch_size = len(input_data)\n length = 1\n\n # Loop over all dimensions\n for element in input_data.shape[1:]:\n length *= element\n\n # Reshape the input data\n reshaped_input_data = np.reshape(input_data, (batch_size, length))\n\n # Return reshaped input data\n return reshaped_input_data\n\ndef get_max_length(target_data_list):\n \"\"\" Return maximum length of the target data in the target data list.\n\n # Arguments:\n\n target_data_list: list of numpy arrays\n List of target data in different parameters setting (e.g., number of cells, number of CUEs, and number of D2Ds),\n each element in the list corresponds to a target data.\n\n # Return:\n\n max_length: int\n Maximum length of all target data in the target data list.\n \"\"\"\n\n # Insert debugging assertions\n assert type(target_data_list) is list, \"The 'target_data_list' must be list.\"\n\n # Initialization of variable\n max_length = 0\n\n # Get the maximum length of all target data in the target data list\n for target_data in target_data_list:\n if target_data.shape[1] > max_length:\n max_length = target_data.shape[1]\n\n # Return maximum length\n return max_length\n\ndef zero_padding(target_data, max_length):\n \"\"\" Add zeros to end of a target data to increases its length.\n\n # Arguments:\n\n target_data: numpy array\n The numpy array which is used as the target of the model's output.\n max_length: int\n Maximum length of all target data in the target data list.\n\n # Return:\n\n padded_target_data: numpy array\n The padded numpy array which is used as the target of the model's output.\n \"\"\"\n\n # Insert debugging assertions\n assert type(target_data) is np.ndarray, \"The 'target_data' must be numpy array.\"\n assert type(max_length) is int, \"The 'max_length' must be integer.\"\n\n # Add zeros to end of a target data if its length is less than or equal to max length\n if target_data.shape[1] < max_length:\n padded_target_data = np.pad(target_data, ((0, 0), (0, max_length - target_data.shape[1])), 'constant')\n elif target_data.shape[1] == max_length:\n padded_target_data = target_data\n else:\n raise ValueError(\"The length of 'target_data' along the second axis must be less than or equal to 'max_length'.\")\n\n # Return padded target data\n return padded_target_data\n\ndef remove_redundant_zeros(padded_target_data, num_of_cells, num_of_CUEs, num_of_D2Ds):\n \"\"\" Remove redundant zeros in the end of a padded target data to decreases its length.\n\n # Arguments:\n\n padded_target_data: numpy array\n The padded numpy array which is used as the target of the model's output.\n num_of_cells: int\n Number of the cells in the cellular system.\n num_of_CUEs: int\n Number of the CUEs in each cell.\n num_of_D2Ds: int\n Number of the D2D pairs in each cell.\n\n # Return:\n\n target_data: numpy array\n The numpy array which is used as the target of the model's output.\n \"\"\"\n\n # Insert debugging assertions\n assert type(padded_target_data) is np.ndarray, \"The 'padded_target_data' must be numpy array.\"\n assert num_of_cells in constants.cell_range, f\"The 'num_of_cells' must be element in {constants.cell_range}.\"\n assert num_of_CUEs in constants.CUE_range, f\"The 'num_of_CUEs' must be element in {constants.CUE_range}.\"\n assert num_of_D2Ds in constants.D2D_range, f\"The 'num_of_D2Ds' must be element in {constants.D2D_range}.\"\n\n # Initialization of variable\n output_dims = num_of_cells * num_of_CUEs * (1 + num_of_D2Ds)\n\n # Remove redundant zeros in the end of a padded target data\n if padded_target_data.shape[1] > output_dims:\n target_data = padded_target_data[:, :output_dims]\n elif padded_target_data.shape[1] == output_dims:\n target_data = padded_target_data\n else:\n raise ValueError(\"The length of 'padded_target_data' along the second axis must be greater than or equal to output dimensions.\")\n\n # Return target data\n return target_data","sub_path":"training-and-testing/prep/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":13466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"264188221","text":"import pytest \n\n\ndef test_techniques_have_tactics(attck_fixture):\n \"\"\"All MITRE Enterprise ATT&CK Techniques should have tactics\n \n Args:\n attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture\n \"\"\"\n for technique in attck_fixture.enterprise.techniques:\n if technique.tactics:\n assert getattr(technique,'tactics')\n \ndef test_techniques_have_mitigations(attck_fixture):\n \"\"\"Some MITRE Enterprise ATT&CK Techniques should have mitigations\n \n Args:\n attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture\n \"\"\"\n count = 0\n for technique in attck_fixture.enterprise.techniques:\n if not hasattr(technique, 'mitigations'):\n if technique.mitigations:\n count += 1\n if count >= 1:\n assert True\n\ndef test_techniques_have_actors(attck_fixture):\n \"\"\"All MITRE Enterprise ATT&CK Techniques should have Actors\n \n Args:\n attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture\n \"\"\"\n count = 0\n for technique in attck_fixture.enterprise.techniques:\n if not hasattr(technique, 'actors'):\n if technique.actors:\n count += 1\n if count >= 1:\n assert True\n\n\n\ndef test_some_techniques_have_generated_datasets_properties(attck_fixture):\n \"\"\"Some MITRE Enterprise ATT&CK Techniques should have generated datasets properties\n \n Args:\n attck_fixture ([type]): our default MITRE Enterprise ATT&CK JSON fixture\n \"\"\"\n command_list_count = 0\n commands_count = 0\n queries_count = 0\n datasets_count = 0\n possible_detections_count = 0\n \n for technique in attck_fixture.enterprise.techniques:\n if hasattr(technique, 'commant_list'):\n command_list_count += 1\n if hasattr(technique, 'commands'):\n commands_count += 1\n if hasattr(technique, 'queries'):\n queries_count += 1\n if hasattr(technique, 'datasets'):\n datasets_count += 1\n if hasattr(technique, 'possible_detections'):\n possible_detections_count += 1\n \n\n if command_list_count >= 1 and commands_count >= 1 and queries_count >= 1 and datasets_count >= 1 and possible_detections_count >= 1:\n assert True\n","sub_path":"tests/enterprise/test_techniques.py","file_name":"test_techniques.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"316559160","text":"# CreateDAFileset\n\n# This program creates additional DA filesets to enable testing so\n# that there are multiple filesets present for AudioHLS\n\nimport hashlib\nfrom SQLUtility import *\n\nclass CreateDAFileset:\n\n\tdef __init__(self):\n\t\tself.db = SQLUtility(\"localhost\", 3306, \"root\", \"hls_dbp\")\n\n\tdef process(self, filesetId, bitrate):\n\t\tresultSet = self.db.select(\"SELECT hash_id, asset_id, set_type_code, set_size_code, hidden\"\n\t\t\t\" FROM bible_filesets WHERE id = %s\", (filesetId))\n\t\trow = resultSet[0]\n\t\thashId = row[0]\n\t\tassetId = row[1]\n\t\tsetTypeCode = row[2]\n\t\tsetSizeCode = row[3]\n\t\thidden = row[4]\n\t\tnewFilesetId = filesetId + bitrate\n\t\tnewHashId = self.getHashId(assetId, newFilesetId, setTypeCode)\n\t\tsql = (\"INSERT INTO bible_filesets (id, hash_id, asset_id, set_type_code, set_size_code, hidden)\"\n\t\t\t\t\t\" VALUES (%s, %s, %s, %s, %s, %s)\")\n\t\tself.db.execute(sql, (newFilesetId, newHashId, assetId, setTypeCode, setSizeCode, hidden))\n\n\t\tsql = (\"INSERT INTO bible_files (hash_id, book_id, chapter_start, chapter_end, verse_start, verse_end,\"\n\t\t\t\t\" file_name, file_size, duration)\"\n\t\t\t\t\" SELECT %s, book_id, chapter_start, chapter_end, verse_start, verse_end,\"\n\t\t\t\t\" file_name, file_size, duration FROM bible_files WHERE hash_id = %s\")\n\t\tself.db.execute(sql, (newHashId, hashId))\n\n\n\tdef getHashId(self, bucket, filesetId, setTypeCode):\n\t\tmd5 = hashlib.md5()\n\t\tmd5.update(filesetId.encode(\"latin1\"))\n\t\tmd5.update(bucket.encode(\"latin1\"))\n\t\tmd5.update(setTypeCode.encode(\"latin1\"))\n\t\thash_id = md5.hexdigest()\n\t\treturn hash_id[:12]\n\n\ntest = CreateDAFileset()\ntest.process(\"ENGESVN2DA\", \"48\")\n","sub_path":"obsolete/analysis/py/CreateDAFileset.py","file_name":"CreateDAFileset.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"15645230","text":"from decient.selenium import SeleniumWrapper\n\n\ngoogle = 'https://www.google.ru/#q='\ndef clicker(site):\n service_args = [\n '--proxy={}'.format(site.get_unused_proxy),\n '--proxy-type=http',\n ]\n sel = SeleniumWrapper(host=google+site.text, service_args=service_args)\n\n#class=\"b navend\"","sub_path":"clicker/clicker.py","file_name":"clicker.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"173763325","text":"# django packages\nfrom django.contrib import messages\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\n# third party packages\nimport requests\nfrom requests import ConnectionError, ConnectTimeout\n\n\ndef build_form_input_attrs(key):\n return {\n \"id\": key,\n \"aria-describedby\": \"{}_errors\".format(key),\n \"class\": \"form-control\",\n }\n\n\ndef generic_api_delete(request, endpoint, instance, tpl_name, redirect, custom_messages={}):\n DEFAULT_SUCCESS_MESSAGE = \"Se elimino el registro correctamente.\"\n DEFAULT_SERVER_CONNECTION_ERROR = 'Un error ha ocurrido intentando conectar con el servidor'\n if request.method == \"POST\":\n try:\n response = requests.delete(endpoint, cookies=request.COOKIES)\n except (ConnectionError, ConnectTimeout) as err:\n messages.error(request, DEFAULT_SERVER_CONNECTION_ERROR)\n return HttpResponseRedirect(redirect)\n # Se comprueba si se elimino el registro con exito\n if response.status_code != 204:\n messages.error(request, custom_messages.get('error'))\n return HttpResponseRedirect(redirect)\n # En este punto estamos seguros que se borro el registro e informamos al cliente\n messages.success(request, custom_messages.get('success') or DEFAULT_SUCCESS_MESSAGE)\n return HttpResponseRedirect(redirect)\n return render(request, tpl_name, {\n 'object': instance,\n 'redirect': redirect,\n })\n","sub_path":"djRefugioAnimales/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"160276384","text":"import json\n\nfrom django.http import FileResponse, Http404\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.views.decorators.http import require_http_methods\n\nfrom .models import Track, Album\nfrom .serializers import TrackSerializer, AlbumSerializer\n\n\n@ensure_csrf_cookie\ndef index(request):\n tracks = Track.objects.all()\n albums = Album.objects.all()\n tracks_data = TrackSerializer(tracks, many=True).data\n albums_data = AlbumSerializer(albums, many=True).data\n state = {\n 'tracks': tracks_data,\n 'albums': albums_data,\n 'playlist': [],\n 'now_playing': None,\n }\n state = json.dumps(state)\n context = {\n 'state': state\n }\n return render(request, 'index.html', context)\n\n\n@require_http_methods(['POST', ])\ndef mp3(request, pk):\n track = get_object_or_404(Track, pk=pk)\n if not track.mp3:\n raise Http404\n response = FileResponse(open(track.mp3.file.name, 'rb'), content_type='application/octet-stream')\n return response\n","sub_path":"apps/music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"79032242","text":"\"\"\" Models for Blogly \"\"\"\n# import datetime\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.sql import func\n\ndb = SQLAlchemy()\n\nDEFAULT_IMG_URL = \"https://www3.nd.edu/~streslab/assets/img/ra_pics/Placeholder_Photo.png\"\n\n\ndef connect_db(app):\n \"\"\" Connects to Database\"\"\"\n db.app = app\n db.init_app(app)\n\n\nclass User(db.Model):\n \"\"\" Users \"\"\"\n\n __tablename__ = \"users\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement = True)\n first_name = db.Column(db.String(50),\n nullable= False)\n last_name = db.Column(db.String(50),\n nullable= False)\n image_url = db.Column(db.Text,\n default= DEFAULT_IMG_URL)\n\n posts = db.relationship('Post', backref=\"user\", cascade=\"all, delete-orphan\")\n \n def __repr__(self):\n u = self\n return f\"\"\n \n @property\n def full_name(self):\n \"\"\" Return full name of user \"\"\"\n return f\"{self.first_name} {self.last_name}\"\n\n\nclass Post(db.Model):\n \"\"\" Posts \"\"\"\n\n __tablename__= \"posts\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement=True)\n title = db.Column(db.String(100),\n nullable=False)\n content = db.Column(db.Text,\n nullable=False)\n created_at = db.Column(db.DateTime(timezone=True), \n server_default=func.now(), index=True)\n # default=datetime.datetime.now\n user_id = db.Column(db.Integer,\n db.ForeignKey('users.id'),\n nullable=False)\n\n posts_tags = db.relationship('PostTag',\n backref='posts',\n cascade=\"all, delete-orphan\")\n \n tags = db.relationship('Tag',\n secondary='posts_tags',\n backref='posts')\n \n\nclass Tag(db.Model):\n \"\"\" Tags \"\"\"\n\n __tablename__ = \"tags\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement=True)\n name = db.Column(db.String(30),\n nullable=False,\n unique=True)\n\n posts_tags = db.relationship('PostTag',\n backref='tags')\n\nclass PostTag(db.Model):\n \"\"\" Post and Tag Middle Table \"\"\"\n\n __tablename__ = \"posts_tags\"\n\n post_id = db.Column(db.Integer,\n db.ForeignKey(\"posts.id\"),\n primary_key=True)\n tag_id = db.Column(db.Integer,\n db.ForeignKey(\"tags.id\"),\n primary_key=True)","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"618714877","text":"import sys\n\nN = int(input())\n\nw = []\n\nlimit = 0\n\nfor _ in range(N):\n\n ai, bi = map(int, input().split())\n w.append((ai, bi))\n\nw = sorted(w, key=lambda x:x[1])\n\nnow = 0\nfor v in w:\n limit = v[1]\n now += v[0]\n if now > limit:\n print('No')\n sys.exit()\n\nprint('Yes')\n","sub_path":"contests/19_06_22/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613254676","text":"# coding=utf-8\nfrom flask import Flask, jsonify\n\nimport os\nimport update\n\nbase_dir = os.getcwd()\napp = Flask(__name__)\napp.config['DEBUG'] = False\n\nupdate_dir = base_dir + '/updates'\n\n\n@app.route('/')\ndef index():\n return 'Матрица Доступа - rSafe Update Server'\n\n\n@app.route('/api/updates', methods=['GET'])\ndef get_updates():\n updates = update.check_for_update(update_dir)\n return jsonify(updates)\n\n\nif __name__ == '__main__':\n app.run(debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174364432","text":"import cv2\nimport paho.mqtt.client as mqtt\nimport numpy as np\nimport math\nimport json\nimport time\n\nANGLE = 45\nCAMERA_SET_ID = 0\n\n\ndef detect_object(frame, index, camera):\n st1 = time.time()\n if index == 'cam 2':\n frame = cv2.flip(frame, -1)\n frame_bgr = frame\n frame_rgb = np.asarray(cv2.cvtColor(\n frame_bgr, cv2.COLOR_BGR2RGB), dtype='uint8')\n #frame_rgb = frame_rgb[240:,:,:]\n fram_red = frame_rgb[:, :, 0]\n frame_gray = np.asarray(cv2.cvtColor(\n frame_rgb, cv2.COLOR_RGB2GRAY), dtype='uint8')\n frame_sub = np.maximum(np.subtract(\n fram_red, frame_gray, dtype='int8'), np.zeros([480, 640]))\n frame_sub = frame_sub.astype('uint8')\n frame_filterd = cv2.medianBlur(frame_sub, 5)\n\n # cv2.imshow(index, frame_bgr)\n # return 1, 2\n ret, thresh = cv2.threshold(frame_sub, 25, 255, cv2.THRESH_BINARY)\n\n im2, contours, hierarchy = cv2.findContours(\n thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n cx = 0\n cy = 0\n mikoto = 0\n if len(contours) != 0:\n for cont in contours:\n M = cv2.moments(cont)\n if M['m00'] > 50:\n #x, y, w, h, the = cv2.minAreaRect(cont)\n #cv2.drawContours(frame_bgr, cont, -1, 255, 3)\n # cv2.rectangle(frame_bgr, (x, y),\n # (x + w, y + h), (0, 255, 0), 2)\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n mikoto = 55/320*(cx-320)\n cv2.circle(thresh, (cx, cy), 3, (255, 255, 255), -1)\n # area = M['m00']\n # cv2.putText(frame_bgr, \"Area: %f\" % area, cv2.FONT_HERSHEY_SIMPLEX,\n # 0.5, (0, 255, 0), 2)\n # cv2.imshow(index,thresh)\n en1 = time.time()\n print(\"Pre TIme is %.2gs\" % (en1-st1))\n return cx, cy, thresh, mikoto\n\n\ndef measure(cx1, cx2):\n dis = 0\n if cx1 != cx2:\n dis = 0.029*630*100/(cx2-cx1)\n if dis < 0:\n dis = -dis\n return dis\n\n\ndef process_camera(client, broker):\n hd = 480\n wd = 640\n camera1 = cv2.VideoCapture(0)\n camera2 = cv2.VideoCapture(1)\n\n # camera1.set(cv2.CAP_PROP_BRIGHTNESS, -10)\n camera1.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)\n camera1.set(cv2.CAP_PROP_EXPOSURE, 0.0015)\n camera1.set(cv2.CAP_PROP_GAIN, 0.6)\n camera1.set(cv2.CAP_PROP_FRAME_WIDTH, wd)\n camera1.set(cv2.CAP_PROP_FRAME_HEIGHT, hd)\n\n # camera1.set(cv2.CAP_PROP_CONTRAST, 32)\n camera2.set(cv2.CAP_PROP_GAIN, 0.6)\n camera2.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)\n camera2.set(cv2.CAP_PROP_EXPOSURE, 0.0015)\n # camera2.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)\n camera2.set(cv2.CAP_PROP_FRAME_WIDTH, wd)\n camera2.set(cv2.CAP_PROP_FRAME_HEIGHT, hd)\n # camera2.set(cv2.CAP_PROP_CONTRAST, 32)\n\n print(\"capture 1 is open: \" + str(camera1.isOpened()))\n print(\"capture 2 is open: \" + str(camera2.isOpened()))\n\n client.connect(broker, 1883, 60)\n client.loop_start()\n\n ret = 1\n ret2 = 1\n shana = 0\n if (ret & ret2):\n while True:\n start = time.time()\n ret, frame_bgr = camera1.read()\n ret2, frame_bgr_2 = camera2.read()\n en1 = time.time()\n print(\"Get TIme is %.2gs\" % (en1-start))\n # detect target\n # cv2.imshow('ori', frame_bgr)\n\n cx1, cy1, th1, misaka1 = detect_object(frame_bgr, 'cam 1', camera1)\n cx2, cy2, th2, misaka2 = detect_object(\n frame_bgr_2, 'cam 2', camera2)\n shana = 0\n # if np.abs(cx1-cx2) > 20:\n shana = measure(cx1, cx2)\n # shana _xc = shana\n if cx1 == 0 | cx2 == 0:\n shana = 0\n misaka = (misaka1+misaka2)/2\n cv2.putText(th1, \"distance:\" + str(shana) + \"cx1:\" + str(cx1) + \"cx2:\" + str(cx2), (cx1-70, cy1+80),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.imshow('dis', th1)\n # cv2.putText(th1, \"cx: \" + str(cx) + \" cy: \" + str(cy), (cx + 20, cy + 20),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n end = time.time()\n print(\"Total TIme is %.2gs\" % (end-start))\n\n\n json_data = json.dumps({\n 'TimeStamp': en1,\n 'Distance': shana,\n 'EnemyAngle': misaka,\n 'EnemyXS': 0,\n 'EnemyYS': 0,\n 'EnemyPhi': 0\n })\n if shana != 0:\n print(\"Publishing message to topic\", \"ENEMIES/EnemyXC\")\n client.publish(\"/ENEMIES/EnemyXC\", json_data)\n cv2.waitKey(1)\n else:\n raise RuntimeError(\"Error while reading from camera.\")\n client.loop_stop()\n\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \" + str(rc))\n\n\ndef on_message(client, userdata, message):\n print(\"message received \", str(message.payload.decode(\"utf-8\")))\n print(\"message topic=\", message.topic)\n print(\"message qos=\", message.qos)\n print(\"message retain flag=\", message.retain)\n\n\ndef main():\n start = time.time()\n client = mqtt.Client(\"EP1\")\n broker_address = \"192.168.1.2\"\n client.on_connect = on_connect # attach function to callback\n client.on_message = on_message # attach function to callback\n\n process_camera(client, broker_address)\n # process_camera()\n #end = time.time()\n #print(\"TIme is %.2gs\" %(end-start))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"enemyPositioning.py","file_name":"enemyPositioning.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"449825022","text":"import tensorflow as tf \nimport os\nimport tensorflow.contrib.slim as slim \nimport importlib\nimport random\nfrom PIL import Image\nimport glob\nimport facenet\nimport sys\nimport argparse\nfrom datetime import datetime\nimport align.detect_face\nfrom scipy import misc\nimport numpy as np\n\ndef load_and_align_data(image_paths, image_size, margin = 0, gpu_memory_fraction=1.0):\n minsize = 20 # minimum size of face\n threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\n factor = 0.709 # scale factor\n \n print('Creating networks and loading parameters')\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)\n \n nrof_samples = len(image_paths)\n img_list = [None] * nrof_samples\n for i in xrange(nrof_samples):\n img = misc.imread(os.path.expanduser(image_paths[i]))\n if img.ndim == 2:\n img = facenet.to_rgb(img)\n img = img[:,:,0:3]\n img_size = np.asarray(img.shape)[0:2]\n bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n det = np.squeeze(bounding_boxes[0,0:4])\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin/2, 0)\n bb[1] = np.maximum(det[1]-margin/2, 0)\n bb[2] = np.minimum(det[2]+margin/2, img_size[1])\n bb[3] = np.minimum(det[3]+margin/2, img_size[0])\n cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n img_list[i] = prewhitened\n images = np.stack(img_list)\n return images\n\nclass FaceNetPredictor:\n def createLogsDirIfNecessary(self, base_dir):\n subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')\n log_dir = os.path.join(os.path.expanduser(base_dir), subdir)\n if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist\n os.makedirs(log_dir)\n\n return log_dir\n\n def storeRevisionInfoIfNecessary(self, log_dir):\n src_path,_ = os.path.split(os.path.realpath(__file__))\n facenet.store_revision_info(src_path, log_dir, ' '.join(sys.argv))\n\n def load_training_data_and_labels(self, samples_dir, image_size):\n train_set = facenet.get_dataset(samples_dir)\n train_image_path_list, train_label_list = facenet.get_image_paths_and_labels(train_set)\n\n train_image_list = facenet.load_data(train_image_path_list, False, False, image_size, True)\n\n return train_image_list, train_label_list, train_set\n\n def knn(self, embeddings, samples_embedding_list, samples_labels_oneHot, session, k=4):\n embeddings_placeholder = tf.placeholder(tf.float32, shape=[None, 128])\n train_embeddings_placeholder = tf.placeholder(tf.float32, shape=[None, 128])\n train_labels_placeholder = tf.placeholder(tf.int32, shape=[None,samples_labels_oneHot.shape[1]])\n\n # L1\n #distance = tf.reduce_sum(tf.abs(tf.subtract(train_embeddings_placeholder, tf.expand_dims(embeddings_placeholder,1))), axis=2)\n\n # L2\n distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(train_embeddings_placeholder, tf.expand_dims(embeddings_placeholder,1))), axis=2))\n \n # Predict: Get min distance index (Nearest neighbor)\n top_k_samples_distances, top_k_samples_indices = tf.nn.top_k(tf.negative(distance), k=k)\n prediction_indices = tf.gather(train_labels_placeholder, top_k_samples_indices)\n\n # Predict the mode category\n count_of_predictions = tf.reduce_sum(prediction_indices, axis=1)\n prediction_op = tf.argmax(count_of_predictions, axis=1)\n\n feed_dict = {embeddings_placeholder:embeddings, train_embeddings_placeholder: samples_embedding_list, train_labels_placeholder: samples_labels_oneHot}\n predictions = session.run(prediction_op, feed_dict=feed_dict)\n\n return predictions\n\ndef main(args):\n # get file list \n fp = FaceNetPredictor()\n files = glob.glob(args.data_dir + '/*')\n images = load_and_align_data(files, args.image_size)\n #model_dir = args.model_dir\n\n # load graph into session from checkpoint\n # with tf.Graph().as_default():\n # with tf.Session() as sess:\n\n # print('Model directory: %s' % model_dir)\n # meta_file, ckpt_file = facenet.get_model_filenames(os.path.expanduser(model_dir))\n \n # print('Metagraph file: %s' % meta_file)\n # print('Checkpoint file: %s' % ckpt_file)\n # facenet.load_model(model_dir, meta_file, ckpt_file)\n\n # images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n # embeddings_placeholder = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n # phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # feed_dict = {images_placeholder:images, phase_train_placeholder:False}\n # embeddings = sess.run(embeddings_placeholder,feed_dict=feed_dict)\n\n train_images_list, train_labels_list, data_set = fp.load_training_data_and_labels(args.samples_dir, args.image_size)\n\n train_image = train_images_list[5]\n inception_image = images[0]\n\n misc.imsave(\"/Users/d063632/train_image.png\", train_image)\n misc.imsave(\"/Users/d063632/inception_image.png\", inception_image)\n print(train_image) \n print(inception_image)\n print(train_image.shape)\n print(inception_image.shape)\n\n # feed_dict = {images_placeholder:train_images_list, phase_train_placeholder:False}\n # train_embeddings = sess.run(embeddings_placeholder,feed_dict=feed_dict)\n\n # num_labels = np.max(train_labels_list)+1\n\n # num_labels_placeholder = tf.placeholder(tf.int32)\n # train_labels_placeholder = tf.placeholder(tf.int32, shape=[len(train_labels_list)])\n # one_hot_op = tf.one_hot(train_labels_placeholder, num_labels_placeholder)\n\n # feed_dict = {num_labels_placeholder: num_labels, train_labels_placeholder: train_labels_list}\n # train_labels_list_one_hot = sess.run(one_hot_op, feed_dict=feed_dict)\n\n # k = 4\n # predictions = fp.knn(embeddings, train_embeddings, train_labels_list_one_hot, sess, k)\n # print(\"Predictions\")\n # print(predictions)\n\n # predicted_labels = []\n # for prediction in predictions:\n # class_name = data_set[prediction].name\n # predicted_labels.append(class_name)\n # print(predicted_labels)\n\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--logs_base_dir', type=str, required=False,\n help='Directory where to write event logs.', default='~/logs/facenet')\n parser.add_argument('--model_dir', type=str, required=True,\n help='Directory where to load the model from.')\n parser.add_argument('--data_dir', type=str, required=True,\n help='Path to the data directory containing images for which to create predictions.')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--samples_dir', type=str, required=True,\n help='Path to the directory containing folders for each class with training images.')\n\n return parser.parse_args(argv)\n \n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))","sub_path":"src/image_load_test.py","file_name":"image_load_test.py","file_ext":"py","file_size_in_byte":7721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509791134","text":"#!/usr/bin/python\nimport urllib.request\nimport sqlite3\nconn = sqlite3.connect('../NFL.db')\nresponse = urllib.request.urlopen('http://espn.go.com/nfl/standings')\nhtml = response.read()\nresponse.close()\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(html)\nEquipes = soup.find('table').find_all('tr')\n\n\nconn.execute('''DELETE FROM Equipes''')\nfor Equipe in Equipes:\n rowLenght = len(Equipe.find_all('td'))\n rowContent = Equipe.find_all('td')\n conn.execute('''CREATE TABLE IF NOT EXISTS Equipes (EquipeID integer PRIMARY KEY,EquipeNom text,EquipeDefaites integer,EquipeVictoires integer,EquipePF integer,EquipePA integer)''')\n if rowLenght > 1 and rowContent[1].get_text() != 'W':\n equipe = [(str(rowContent[0].get_text().strip()),rowContent[2].get_text(),rowContent[1].get_text(),rowContent[9].get_text(),rowContent[10].get_text())]\n conn.executemany('INSERT INTO Equipes (EquipeNom,EquipeDefaites,EquipeVictoires,EquipePF,EquipePA) VALUES (?,?,?,?,?)', equipe)\n\nconn.commit()\nconn.close()","sub_path":"Python/GetEquipes.py","file_name":"GetEquipes.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"259161581","text":"import os\n# 目录\nPROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\n\nMODEL_STORE_DIR = os.path.dirname(os.path.realpath(__file__)) + \"/model_store\"\nPNET_MODEL_FILE = os.path.dirname(os.path.realpath(__file__)) + '/model_store/pnet_epoch.pt'\nRNET_MODEL_FILE = os.path.dirname(os.path.realpath(__file__)) + '/model_store/rnet_epoch.pt'\nONET_MODEL_FILE = os.path.dirname(os.path.realpath(__file__)) + '/model_store/onet_epoch.pt'\n\nANNO_STORE_DIR = os.path.dirname(os.path.realpath(__file__)) + \"/anno_store\"\nANNOTATION_FILE = os.path.dirname(os.path.realpath(__file__)) + '/anno_store/anno_train_fixed.txt'\nPNET_ANNOTATION_FILE = os.path.dirname(os.path.realpath(__file__)) + '/anno_store/trainPnet'\nRNET_ANNOTATION_FILE = os.path.dirname(os.path.realpath(__file__)) + '/anno_store/trainRnet'\nONET_ANNOTATION_FILE = os.path.dirname(os.path.realpath(__file__)) + '/anno_store/trainOnet'\nONET_LANDMARK_ANNOTATION_FILE = os.path.dirname(os.path.realpath(__file__)) + '/data_set/face_landmark/CNN_FacePoint/train/trainImageList.txt'\n\nWIDERFACE_IMG_DIR = os.path.dirname(os.path.realpath(__file__)) + \\\n '/data_set/face_detection/WIDERFACE/WIDER_train/WIDER_train/images'\nONET_CNN_FACEPOINT_IMG_DIR = os.path.dirname(os.path.realpath(__file__)) + '/data_set/face_landmark/CNN_FacePoint/train'\n\nPNET_TRAINDATA_STORE = os.path.dirname(os.path.realpath(__file__)) + '/data_set/trainPnet'\nRNET_TRAINDATA_STORE = os.path.dirname(os.path.realpath(__file__)) + '/data_set/trainRnet'\nONET_TRAINDATA_STORE = os.path.dirname(os.path.realpath(__file__)) + '/data_set/trainOnet'\n\n\nLOG_DIR = os.path.dirname(os.path.realpath(__file__))+\"/log\"\n\nUSE_CUDA = True\n\nTRAIN_BATCH_SIZE = 512\n\nTRAIN_LR = 0.01\n\nEND_EPOCH = 10\n\nPNET_POSTIVE_ANNO_FILENAME = \"pos_12.txt\"\nPNET_NEGATIVE_ANNO_FILENAME = \"neg_12.txt\"\nPNET_PART_ANNO_FILENAME = \"part_12.txt\"\nPNET_LANDMARK_ANNO_FILENAME = \"landmark_12.txt\"\n\nRNET_POSTIVE_ANNO_FILENAME = \"pos_24.txt\"\nRNET_NEGATIVE_ANNO_FILENAME = \"neg_24.txt\"\nRNET_PART_ANNO_FILENAME = \"part_24.txt\"\nRNET_LANDMARK_ANNO_FILENAME = \"landmark_24.txt\"\n\nONET_POSTIVE_ANNO_FILENAME = \"pos_48.txt\"\nONET_NEGATIVE_ANNO_FILENAME = \"neg_48.txt\"\nONET_PART_ANNO_FILENAME = \"part_48.txt\"\nONET_LANDMARK_ANNO_FILENAME = \"landmark_48.txt\"\n\nPNET_TRAIN_IMGLIST_FILENAME = \"imglist_anno_12.txt\"\nRNET_TRAIN_IMGLIST_FILENAME = \"imglist_anno_24.txt\"\nONET_TRAIN_IMGLIST_FILENAME = \"imglist_anno_48.txt\"","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97132947","text":"'''\n\nFind the longest common word in the list of words. Words are delimited by multiple spaces.\nInput: [\"Echo\", \"Alexa\", \"Kindle\", \"Echo Show\", \"Amazon\"]\nOutput: \"Echo\"\n\nInput: [\"Echo Show\", \"Echo Show 8\"]\nOutput: \"Echo Show\"\n\nIf there are multiple longest common words, return an empty string. \nIf there is no common word, return an empty string.\n\n'''\ndef logestWord(words):\n word_dict = {}\n for word in words:\n h = word.split()\n for i in h:\n if i in word_dict:\n word_dict[i] +=1\n else:\n word_dict[i] = 1\n return max(word_dict, key=word_dict.get)\n\nlogestWord([\"Echo\", \"Alexa\", \"Kindle\", \"Echo Show\", \"Amazon\"])","sub_path":"OA/Amazon/FindLongestCommonWordsInList.py","file_name":"FindLongestCommonWordsInList.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"2967340","text":"import datetime\nimport pytest\nfrom uuid import UUID\nfrom functools import reduce\nimport numpy as np\nimport pandas as pd\n\nfrom simulacrum import types\nfrom simulacrum import dataset\n\ndef _default_test(listToCheck, typeToWait, length):\n return len(listToCheck) == length\\\n and reduce(lambda p, n: p and type(n) == typeToWait, listToCheck, True)\n\ndef test_uuid_data():\n \"\"\"Test uuid data.\"\"\"\n uuids_list = types.uuid_data(30)\n assert _default_test(uuids_list, UUID, 30)\\\n and len(set(uuids_list)) == len(uuids_list)\n\ndef test_faker_data_ipv6():\n \"\"\"Test faker data.\"\"\"\n ipv6_list = types.faker_data(**{\n \"provider\": \"ipv6\",\n \"network\": False\n }, length=23)\n random_element_list = types.faker_data(**{\n \"provider\": \"random_element\",\n \"elements\": ('a', 'b', 'c', 'd'),\n }, length=13)\n assert _default_test(ipv6_list, str, 23)\\\n and _default_test(random_element_list, str, 13)\\\n and reduce(lambda p, n: p and n in ['a', 'b', 'c', 'd'], random_element_list, True)\n\ndef test_name_data():\n names = types.name_data(10)\n assert len(names) == 10\n assert names.dtype == np.dtype('O')\n for item in names:\n assert isinstance(item, str)\n\ndef test_text_data():\n text = types.text_data(10)\n assert len(text) == 10\n assert text.dtype == np.dtype('O')\n for item in text:\n assert isinstance(item, str)\n text_max_10 = types.text_data(10, 10)\n assert len(text_max_10) == 10\n lengths = text_max_10.apply(lambda x: len(x))\n assert lengths.max() <= 10\n with pytest.raises(TypeError):\n text = types.text_data(10, bad_param=100)\n\ndef test_address_data():\n addresses = types.address_data(10)\n assert len(addresses) == 10\n assert addresses.dtype == np.dtype('O')\n for item in addresses:\n assert isinstance(item, str)\n with pytest.raises(TypeError):\n addresses = types.address_data(10, bad_param=100)\n\ndef test_num_data():\n nums = types.num_data(1000, min=0, max=1)\n assert len(nums) == 1000\n assert nums.max() <= 1\n assert nums.min() >= 0\n assert nums.dtype == np.dtype('float')\n with pytest.raises(TypeError):\n nums = types.num_data(10, min=0, bad_param=100)\n\ndef test_num_int():\n nums = types.num_int(1000, min=0, max=100)\n assert len(nums) == 1000\n assert nums.max() <= 100\n assert nums.min() >= 0\n assert nums.dtype == np.dtype('int')\n\ndef test_norm_data():\n nums = types.norm_data(1000, mean=0, sd=100)\n assert len(nums) == 1000\n assert nums.dtype == np.dtype('float')\n\ndef test_exp_data():\n nums = types.exp_data(1000, lam=10)\n assert len(nums) == 1000\n assert nums.dtype == np.dtype('float')\n assert nums.max() >= 0\n\ndef test_binom_data():\n nums = types.binom_data(10)\n assert len(nums) == 10\n assert nums.dtype == np.dtype('int')\n\ndef test_poisson_data():\n nums = types.poisson_data(10)\n assert len(nums) == 10\n assert nums.dtype == np.dtype('int')\n\ndef test_date_data():\n dates = types.date_data(length=1000)\n assert len(dates) == 1000\n assert len(dates.unique()) > 1\n assert dates.dtype == np.dtype(' 1\n assert dates.min() >= datetime.datetime(2000, 1, 1)\n assert dates.max() < datetime.datetime(2001, 1, 1)\n assert dates.dtype == np.dtype(' 1\n assert dates.min() >= datetime.datetime(2000, 1, 1)\n assert dates.max() < datetime.datetime(2001, 1, 1)\n assert dates.dtype == np.dtype(' 1\n assert dates.min() >= datetime.datetime(2017, 1, 1)\n assert dates.max() < datetime.datetime(2017, 6, 1)\n assert dates.dtype == np.dtype('ij', B, B, invmass)\n# Hartrees, Angstrom, amu \nGF = G.dot(inthess)\nprint(GF)\n#print(inthess * 4.3597482 * 1e-18 * (1 / 1.6605402e-27) * (1e10)**2 )\nlamda, L = np.linalg.eig(GF)\n# Converts Hartree to attojoule to Joule, then amu to kg, then Ang to Meters. All SI. Then convert to Hertz\n#print(lamda)\n#print(L)\nlamda = lamda * 4.3597482 * 1e-18 * (1 / 1.6605402e-27) * (1e10)**2 \nhertz = np.sqrt(lamda) / (2* np.pi)\nhz2cm = 1 / 2.99792458e10\nfrequencies = hertz*hz2cm\nprint(\"Psi4 Frequencies\\n\",np.array(wfn.frequencies()))\nprint(\"Psi4/PyOPTKING Frequencies\\n\",frequencies)\n\n\nfrom peslearn.ml import NeuralNetwork\nfrom peslearn import InputProcessor\nimport numpy as np\nimport torch\n\nnn = NeuralNetwork('PES.dat', InputProcessor(''), molecule_type='A2B')\nparams = {'layers': (128, 128, 128), 'morse_transform': {'morse': False}, 'pip': {'degree_reduction': True, 'pip': True}, 'scale_X': {'activation': 'tanh', 'scale_X': 'std'}, 'scale_y': 'mm01', 'lr': 0.2}\n\nX, y, Xscaler, yscaler = nn.preprocess(params, nn.raw_X, nn.raw_y)\nmodel = torch.load('model.pt')\n\n# Track gradients: 1. Initial geometry 2. Morse transform 3. PIP transform 4. Scale transform\n# Compute energy, and reverse scaling \n# point 161\ninp1 = torch.tensor([1.570333028514,0.949630647150,0.949630647150], dtype=torch.float64, requires_grad=True)\n# Careful! Degree reduce?\ninp4 = torch.stack((inp1[0], inp1[1] + inp1[2], torch.sum(torch.pow(inp1[1:],2))**0.5), dim=0)\ninp5 = (inp4 - torch.tensor(Xscaler.mean_, dtype=torch.float64)) / torch.tensor(Xscaler.scale_, dtype=torch.float64)\nout1 = model(inp5)\nout2 = (out1 - torch.tensor(yscaler.min_, dtype=torch.float64)) / torch.tensor(yscaler.scale_, dtype=torch.float64)\nprint(out2)\n\ng = torch.autograd.grad(out2, inp1, create_graph=True)[0]\nprint(\"Pytorch Gradient:\\n\", g)\nh1 = torch.autograd.grad(g[0], inp1, create_graph=True)[0]\nh2 = torch.autograd.grad(g[1], inp1, create_graph=True)[0]\nh3 = torch.autograd.grad(g[2], inp1, create_graph=True)[0]\nF = torch.stack([h1,h2,h3])\nprint(\"Pytorch Hessian:\\n\", F)\n\nGF = G.dot(F.detach().numpy())\nlamda, L = np.linalg.eig(GF)\nprint(L)\n# Converts Hartree to attojoule to Joule, then amu to kg, then Ang to Meters. All SI. Then convert to Hertz\nlamda = lamda * 4.3597482 * 1e-18 * (1 / 1.6605402e-27) * (1e10)**2 \nhertz = np.sqrt(lamda) / (2* np.pi)\nhz2cm = 1 / 2.99792458e10\nfrequencies = hertz*hz2cm\nprint(\"NN Frequencies\\n\", frequencies)\n\n# We must have 'create_graph=True' up until our last derivative we desire, which just needs retain_graph=True\n# Cubic 'Hessian'\nc1 = torch.autograd.grad(h1[0], inp1, retain_graph=True)[0] \nc2 = torch.autograd.grad(h1[1], inp1, retain_graph=True)[0] \nc3 = torch.autograd.grad(h1[2], inp1, retain_graph=True)[0] \nc4 = torch.autograd.grad(h2[0], inp1, retain_graph=True)[0] \nc5 = torch.autograd.grad(h2[1], inp1, retain_graph=True)[0] \nc6 = torch.autograd.grad(h2[2], inp1, retain_graph=True)[0] \nc7 = torch.autograd.grad(h3[0], inp1, retain_graph=True)[0] \nc8 = torch.autograd.grad(h3[1], inp1, retain_graph=True)[0] \nc9 = torch.autograd.grad(h3[2], inp1, retain_graph=True)[0] \ntmp1 = torch.stack([c1, c2, c3])\ntmp2 = torch.stack([c4, c5, c6])\ntmp3 = torch.stack([c7, c8, c9])\ncubic = torch.stack([tmp1, tmp2, tmp3], dim=1)\n#print(\"Pytorch Third Derivative Tensor:\\n\", cubic)\n#\n#\n","sub_path":"ml_testbed/5_pytorch_gradients/gradient_transformations/build_model/1_supertight/model1_data/eq_geom.py","file_name":"eq_geom.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112260624","text":"\"\"\"\n利用插空法,首先找到频率最高的任务,然后按照要求的冷却时间隔开,中间插入其他任务;\n如果冷却时间过短,由最频繁任务构建的空间不足以放入其他任务时,实际上在尾部完全可以\n分别间隔实行完成不需要多余的冷却时间,此时所需最短时间就是任务的长度\n\"\"\"\n\nclass Solution:\n def leastInterval(self, tasks, n):\n \"\"\"\n :type tasks: List[str]\n :type n: int\n :rtype: int\n \"\"\"\n from collections import Counter\n length = len(tasks)\n if length == 1:\n return 1\n if n == 0:\n return length\n task_freq = Counter(tasks).most_common()\n most_freq = task_freq[0]\n time = (n + 1) * (most_freq[1] - 1)\n for _, f in task_freq:\n if f == most_freq[1]:\n time += 1\n return max(length, time)","sub_path":"leastInterval.py","file_name":"leastInterval.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101919837","text":"from aiogram import types\r\nimport re\r\n\r\nfrom aiogram.dispatcher import FSMContext\r\nfrom aiogram.dispatcher.filters import Command, CommandStart\r\nfrom aiogram.types import InputFile\r\nimport math\r\nfrom aiogram.utils.markdown import hbold, hcode, hitalic, hunderline, hstrikethrough, hlink\r\nimport datetime\r\n\r\nfrom data.config import allowed_users\r\nfrom data.party_day import group_day\r\nfrom loader import dp, bot, db\r\n\r\n\r\n@dp.inline_handler()\r\nasync def empty_query(query: types.InlineQuery):\r\n print(query.from_user.values)\r\n print(query.values['query'])\r\n\r\n user = db.select_user(id=query.from_user.id)\r\n\r\n if user == None:\r\n await query.answer(\r\n results=[],\r\n switch_pm_text=\"Бот недоступен. Подключить бота\",\r\n switch_pm_parameter=\"connect_user\",\r\n cache_time=5)\r\n return\r\n\r\n # Обработка команды перевода в дБ\r\n if re.match(r\"convert\\s?\\d+\", query.values['query']):\r\n\r\n result = re.findall(r'\\d+', query.values['query'])\r\n\r\n if len(result) == 1:\r\n\r\n dbm = 10 * math.log10(int(result[0]) / 0.001)\r\n db_power = 10 * math.log10(int(result[0]))\r\n db_voltage = 20 * math.log10(int(result[0]))\r\n print(dbm)\r\n bell = db_power / 10\r\n\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Результаты\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Выполнение\\n\"\r\n f\"Элемент {result[0]}\\n\"\r\n f\"{dbm:.5f} dBm\\n\"\r\n f\"{db_power:.5f} dB по мощности\\n\"\r\n f\"{db_voltage:.5f} dB по напряжению\\n\"\r\n f\"{bell:.5f} в Беллах\",\r\n parse_mode=\"HTML\"\r\n ),\r\n description=f\"{dbm} dBm\\n\"\r\n f\"{db_power} dB по мощности\\n\"\r\n f\"{db_voltage} dB по напряжению\"\r\n ),\r\n ],\r\n cache_time=5)\r\n\r\n elif len(result) == 2:\r\n Np = math.log(int(result[0]) / int(result[1]))\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Результаты\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Выполнение\\n\"\r\n f\"Элементы {result[0]} и {result[1]}\\n\"\r\n f\"Отношение двух величин: {Np:.5f} непер\",\r\n parse_mode=\"HTML\"\r\n ),\r\n description=f\"Отношение двух величин: {Np:.5f} непер\"\r\n ),\r\n ],\r\n cache_time=5)\r\n\r\n else:\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Результаты\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Перебор элементов перебора\\n\",\r\n parse_mode=\"HTML\"\r\n ),\r\n description=f\"Для перевода долно быть от одного до двух элементов\"\r\n ),\r\n ],\r\n cache_time=5)\r\n\r\n # Обработка команды перевода по мощности и амплитуде\r\n elif re.match(r\"(cnt)?\\s?[+-]?([0-9]*[.,])?[0-9]+[VvWwВвТт]\", query.values['query']):\r\n\r\n if query.values['query'][-1] in ['V', 'v', 'В', 'в']:\r\n result = re.findall(r'[+-]?([0-9]+([.,]\\d+)?)', query.values['query'])\r\n result = float(result[0][0].replace(',', '.'))\r\n # print(result)\r\n dBV = 20 * math.log10(result)\r\n dBmcV = dBV + 120\r\n dBmW = dBmcV - 90 - 10 * math.log10(50)\r\n dBW = dBmW - 30\r\n time = datetime.datetime.now()\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Результаты\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Отношение амплитуд\\n\"\r\n f\"{result} В, вольт\\n\"\r\n f\"{dBV:.5f} dBV, децибел-вольт\\n\"\r\n f\"{dBmcV:.5f} дБмкВ, децибел-микровольт\\n\"\r\n f\"\\n\"\r\n f\"Преобразование дБмкВ в дБмВт\\n\"\r\n f\"{dBmW:.5f} дБмВт, децибел-милливатт\\n\"\r\n f\"{dBW:.5f} дБВт, децибел-ватт\\n\"\r\n f\"
{time.hour} : {time.minute}   ({time.date()})
\",\r\n parse_mode=\"HTML\"\r\n ),\r\n description=f\"Отношение напряжений относительно одного вольта или микровольта.\\n\"\r\n f\"{dBV:.5f} dBV, децибел-вольт\\n\"\r\n ),\r\n ],\r\n cache_time=5)\r\n\r\n else:\r\n result = re.findall(r'[+-]?([0-9]+([.,]\\d+)?)', query.values['query'])\r\n result = float(result[0][0].replace(',', '.'))\r\n dBW = 10 * math.log10(result)\r\n dBmW = dBW + 30\r\n dBmW_in_dBmcB = dBmW + 90 + 10 * math.log10(50)\r\n dBV = dBmW_in_dBmcB - 120\r\n time = datetime.datetime.now()\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Результаты\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Децибел по мощности\\n\"\r\n f\"{result} Вт, ватт\\n\"\r\n f\"{dBW:.5f} дБВт, децибел-ватт\\n\"\r\n f\"{dBmW:.5f} дБмВт, децибел-милливатт\\n\"\r\n f\"\\n\"\r\n f\"Преобразование дБмВт в дБмкВ\\n\"\r\n f\"{dBmW_in_dBmcB:.5f} дБмкВ, децибел-микровольт\\n\"\r\n f\"{dBV:.5f} дБВ, децибел-вольт\\n\"\r\n f\"
{time.hour} : {time.minute}   ({time.date()})
\",\r\n parse_mode=\"HTML\"\r\n ),\r\n description=f\"Отношение мощностей относительно одного ватта или милливатта.\\n\"\r\n f\"{dBW:.5f} дБВт, децибел-ватт\\n\"\r\n ),\r\n ],\r\n cache_time=5)\r\n\r\n # Обработка команды выводящей рассписание\r\n elif re.match(r\"(sche(dule)?\\s?(\\d+)?)|(рас(писание)?\\s?(\\d+)?)\", query.values['query'].lower()):\r\n number_party = re.findall(r'\\d+', query.values['query'])\r\n if number_party == []:\r\n user = db.select_user(id=query.from_user.id)\r\n if user[3] is not None:\r\n number_party = [str(user[3])]\r\n else:\r\n await query.answer(\r\n results=[],\r\n switch_pm_text=\"Бот недоступен. Укажите группу\",\r\n switch_pm_parameter=\"number_party\",\r\n cache_time=5)\r\n return\r\n\r\n number_day = int(datetime.datetime.now().isoweekday()) + 1\r\n print(number_party)\r\n\r\n if number_day in [7, ]:\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultArticle(\r\n id=\"1\",\r\n title=\"Завтра нет занятий\",\r\n input_message_content=types.InputTextMessageContent(\r\n message_text=f\"Завтра нет занятий\\n\",\r\n parse_mode=\"HTML\"\r\n )\r\n ),\r\n ],\r\n cache_time=5)\r\n return\r\n\r\n await query.answer(\r\n results=[\r\n types.InlineQueryResultCachedPhoto(\r\n id='1',\r\n photo_file_id=group_day[number_party[0]][number_day][1],\r\n description=group_day[number_party[0]][number_day][0],\r\n caption=f'Рассписание на {group_day[number_party[0]][number_day][0].lower()}',\r\n title=group_day[number_party[0]][number_day][0]\r\n )\r\n ]\r\n )\r\n\r\n else:\r\n await query.answer(\r\n results=[],\r\n switch_pm_text=\"Перейти в бота\",\r\n switch_pm_parameter=\"connect_bot\",\r\n cache_time=5)\r\n return\r\n","sub_path":"handlers/users/inline_mode/inline_convert.py","file_name":"inline_convert.py","file_ext":"py","file_size_in_byte":10359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149355402","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@created on: 4/19/20,\n@author: Shreesha N,\n@version: v0.0.1\n@system name: badgod\nDescription:\n\n..todo::\n\n\"\"\"\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import tensor\nimport torch\nimport numpy as np\n\n\nclass Encoder(nn.Module):\n def __init__(self):\n super(Encoder, self).__init__()\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=[1, 2])\n self.conv1_bn = nn.BatchNorm2d(64)\n\n self.conv2 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=[1, 2])\n self.conv2_bn = nn.BatchNorm2d(128)\n self.pool1 = nn.MaxPool2d(kernel_size=4, stride=1, return_indices=True)\n self.dropout0 = nn.Dropout(p=0.4)\n\n self.conv3 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2)\n self.conv3_bn = nn.BatchNorm2d(256)\n self.conv4 = nn.Conv2d(in_channels=256, out_channels=128, kernel_size=3, stride=[1, 2])\n self.conv4_bn = nn.BatchNorm2d(128)\n self.pool2 = nn.MaxPool2d(kernel_size=4, stride=1, return_indices=True)\n\n self.conv5 = nn.Conv2d(in_channels=128, out_channels=32, kernel_size=3, stride=[1, 2])\n self.conv5_bn = nn.BatchNorm2d(32)\n\n def forward(self, x):\n # print('x.size() ', x.size())\n encoder_op1 = F.relu(self.conv1(x))\n # print('conv 1', encoder_op1.size())\n encoder_op2 = F.relu(self.conv2(encoder_op1))\n # print('conv 2', encoder_op2.size())\n encoder_op2_pool, pool1_indices = self.pool1(encoder_op2)\n # print('pool1', encoder_op2_pool.size())\n encoder_op2_pool = self.dropout0(encoder_op2_pool)\n\n encoder_op3 = F.relu(self.conv3(encoder_op2_pool))\n # print('conv 3', encoder_op3.size())\n encoder_op4 = F.relu(self.conv4(encoder_op3))\n # print('conv 4', encoder_op4.size())\n encoder_op4_pool, pool2_indices = self.pool2(encoder_op4)\n # print('pool2 ', encoder_op4_pool.size(), pool2_indices.shape)\n\n encoder_op5 = F.relu(self.conv5(encoder_op4_pool))\n # print('after conv net 5 ', encoder_op5.size())\n\n return encoder_op5, pool1_indices, pool2_indices\n\n\nclass Decoder(nn.Module):\n def __init__(self):\n super(Decoder, self).__init__()\n\n self.decoder1 = nn.ConvTranspose2d(in_channels=32, out_channels=128, kernel_size=3, stride=[1, 2],\n output_padding=[0, 1])\n self.decoder1_bn = nn.BatchNorm2d(128)\n self.unpool1 = nn.MaxUnpool2d(4, stride=1)\n self.decoder2 = nn.ConvTranspose2d(in_channels=128, out_channels=256, kernel_size=3, stride=[1, 2])\n self.decoder2_bn = nn.BatchNorm2d(256)\n self.decoder3 = nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=3, stride=[2, 2],\n output_padding=[0, 1])\n self.decoder3_bn = nn.BatchNorm2d(128)\n self.unpool2 = nn.MaxUnpool2d(4, stride=1)\n self.decoder4 = nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=3, stride=[1, 2],\n output_padding=[0, 1])\n self.decoder4_bn = nn.BatchNorm2d(64)\n self.decoder5 = nn.ConvTranspose2d(in_channels=64, out_channels=1, kernel_size=3, stride=[1, 2])\n self.decoder5_bn = nn.BatchNorm2d(1)\n\n def forward(self, x, pool1_indices, pool2_indices, final_op_shape):\n # decoder\n decoder_op1 = F.relu(self.decoder1_bn(self.decoder1(x))) # , output_size=encoder_op4_pool.size()\n # print('decoder1', decoder_op1.size())\n decoder_op1_unpool1 = self.unpool1(decoder_op1, indices=pool2_indices)\n # print(\"decoder_op1_unpool1\", decoder_op1_unpool1.size())\n decoder_op2 = F.relu(self.decoder2_bn(self.decoder2(decoder_op1_unpool1))) # , output_size=encoder_op3.size()\n # print('decoder2', decoder_op2.size())\n decoder_op3 = F.relu(self.decoder3_bn(self.decoder3(decoder_op2)))\n # print('decoder3', decoder_op3.size())\n decoder_op3_unpool2 = self.unpool2(decoder_op3, indices=pool1_indices)\n # print(\"decoder_op3_unpool2\", decoder_op3_unpool2.size())\n\n decoder_op4 = F.relu(self.decoder4_bn(self.decoder4(decoder_op3_unpool2)))\n # print('decoder4', decoder_op4.size())\n reconstructed_x = self.decoder5_bn(self.decoder5(decoder_op4, output_size=final_op_shape))\n # print('decoder5', reconstructed_x.size())\n return reconstructed_x\n\n\nclass ConvAutoEncoder(nn.Module):\n\n def __init__(self):\n super(ConvAutoEncoder, self).__init__()\n\n self.encoder = Encoder()\n self.decoder = Decoder()\n\n def forward(self, x):\n x = x.unsqueeze(1)\n latent_filter_maps, pool1_indices, pool2_indices = self.encoder(x)\n reconstructed_x = self.decoder(latent_filter_maps, pool1_indices=pool1_indices, pool2_indices=pool2_indices,\n final_op_shape=x.size())\n return reconstructed_x, latent_filter_maps\n\n\nclass OneClassNN(nn.Module):\n def __init__(self):\n super(OneClassNN, self).__init__()\n\n self.w = nn.Linear(5184, 2048)\n # self.dropout1 = nn.Dropout(p=0.3)\n self.v = nn.Linear(2048, 100)\n\n def forward(self, x):\n x = F.sigmoid(self.w(x))\n # x = self.dropout1(x)\n return self.v(x).squeeze(1), self.w, self.v\n\n\nclass OneClassCAE(nn.Module):\n def __init__(self):\n super(OneClassCAE, self).__init__()\n self.encoder = Encoder()\n self.one_class_nn = OneClassNN()\n\n def forward(self, x):\n latent_filter_maps = self.encoder(x)\n latent_vector = latent_filter_maps.view(-1, x.size()[1:].numel())\n y_hat, w, v = self.one_class_nn(latent_vector)\n return y_hat, w, v\n","sub_path":"alcoaudio/networks/oneclass_net.py","file_name":"oneclass_net.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"169592171","text":"#!/usr/bin/python3\n\n# Copyright (c) 2017-2023 California Institute of Technology (\"Caltech\"). U.S.\n# Government sponsorship acknowledged. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n\n'''A class to read/write/manipulate camera models\n\nSYNOPSIS\n\n model_for_intrinsics = mrcal.cameramodel('model0.cameramodel')\n model_for_extrinsics = mrcal.cameramodel('model1.cameramodel')\n\n model_joint = mrcal.cameramodel( model_for_intrinsics )\n\n extrinsics = model_for_extrinsics.extrinsics_rt_fromref()\n model_joint.extrinsics_rt_fromref(extrinsics)\n\n # model_joint now has intrinsics from 'model0.cameramodel' and extrinsics\n # from 'model1.cameramodel'. I write it to disk\n model_joint.write('model-joint.cameramodel')\n\nAll functions are exported into the mrcal module. So you can call these via\nmrcal.cameramodel.fff() or mrcal.fff(). The latter is preferred.\n\n'''\n\nimport sys\nimport numpy as np\nimport numpysane as nps\nimport numbers\nimport ast\nimport re\nimport warnings\nimport io\nimport base64\n\nimport mrcal\n\ndef _validateExtrinsics(e):\n r'''Raises an exception if the given extrinsics are invalid'''\n\n # Internal extrinsic representation is a 6-long array\n try:\n N = len(e)\n except:\n raise Exception(\"Valid extrinsics are an iterable of len 6\")\n\n\n if N != 6:\n raise Exception(\"Valid extrinsics are an iterable of len 6\")\n\n for x in e:\n if not isinstance(x, numbers.Number):\n raise Exception(\"All extrinsics elements should be numeric, but '{}' isn't\".format(x))\n\n\ndef _validateIntrinsics(imagersize,\n i,\n optimization_inputs = None,\n icam_intrinsics = None):\n r'''Raises an exception if given components of the intrinsics is invalid'''\n\n # need two integers in the imager size\n try:\n N = len(imagersize)\n if N != 2:\n raise Exception(\"The imagersize must be an iterable of two positive integers\")\n if imagersize[0] <= 0 or imagersize[1] <= 0:\n raise Exception(\"The imagersize must be an iterable of two positive integers\")\n if imagersize[0] != int(imagersize[0]) or imagersize[1] != int(imagersize[1]):\n raise Exception(\"The imagersize must be an iterable of two positive integers\")\n except:\n raise Exception(\"The imagersize must be an iterable of two positive integers\")\n\n try:\n N = len(i)\n except:\n raise Exception(\"Valid intrinsics are an iterable of len 2\")\n\n\n if N != 2:\n raise Exception(\"Valid intrinsics are an iterable of len 2\")\n\n lensmodel = i[0]\n intrinsics = i[1]\n\n # If this fails, I keep the exception and let it fall through\n Nintrinsics_want = mrcal.lensmodel_num_params(lensmodel)\n\n try:\n Nintrinsics_have = len(intrinsics)\n except:\n raise Exception(\"Valid intrinsics are (lensmodel, intrinsics) where 'intrinsics' is an iterable with a length\")\n\n if Nintrinsics_want != Nintrinsics_have:\n raise Exception(\"Mismatched Nintrinsics. Got {}, but model {} must have {}\".format(Nintrinsics_have,lensmodel,Nintrinsics_want))\n\n for x in intrinsics:\n if not isinstance(x, numbers.Number):\n raise Exception(\"All intrinsics elements should be numeric, but '{}' isn't\".format(x))\n\n if optimization_inputs is not None:\n # Currently this is only checked when we set the optimization_inputs by\n # calling intrinsics(). We do NOT check this if reading a file from\n # disk. This is done as an optimization: we store the unprocessed\n # _optimization_inputs_string bytes and only decode them as needed.\n # Perhaps I should expand this\n if not isinstance(optimization_inputs, dict):\n raise Exception(f\"'optimization_inputs' must be a dict. Instead got type {type(optimization_inputs)}\")\n\n if icam_intrinsics is None:\n raise Exception(f\"optimization_inputs is given, so icam_intrinsics MUST be given too\")\n if not isinstance(icam_intrinsics, int):\n raise Exception(f\"icam_intrinsics not an int. This must be an int >= 0\")\n if icam_intrinsics < 0:\n raise Exception(f\"icam_intrinsics < 0. This must be an int >= 0\")\n\n\ndef _validateValidIntrinsicsRegion(valid_intrinsics_region):\n r'''Raises an exception if the given valid_intrinsics_region is illegal'''\n\n if valid_intrinsics_region is None:\n return\n\n try:\n # valid intrinsics region is a closed contour, so I need at least 4\n # points to be valid. Or as a special case, a (0,2) array is legal, and\n # means \"intrinsics are valid nowhere\"\n if not (valid_intrinsics_region.ndim == 2 and \\\n valid_intrinsics_region.shape[1] == 2 and \\\n (valid_intrinsics_region.shape[0] >= 4 or \\\n valid_intrinsics_region.shape[0] == 0)):\n raise Exception(\"The valid extrinsics region must be a numpy array of shape (N,2) with N >= 4 or N == 0\")\n except:\n raise Exception(\"The valid extrinsics region must be a numpy array of shape (N,2) with N >= 4. Instead got type {} of shape {}\". \\\n format(type(valid_intrinsics_region), valid_intrinsics_region.shape if type(valid_intrinsics_region) is np.ndarray else None))\n\n if valid_intrinsics_region.size > 0 and \\\n nps.norm2(valid_intrinsics_region[0] - valid_intrinsics_region[-1]) > 1e-6:\n raise Exception(\"The valid extrinsics region must be a closed contour: the first and last points must be identical\")\n\n\nclass CameramodelParseException(Exception):\n r'''Raised if a .cameramodel file couldn't be parsed successfully\n\n This is just a normal \"Exception\" with a different name, so I can handle\n this specifically\n\n '''\n pass\n\n\ndef _serialize_optimization_inputs(optimization_inputs):\n r'''Convert a optimization_inputs dict to an ascii string\n\nThis is an internal function.\n\nI store the optimization inputs as an opaque string in the .cameramodel\nfile. This is a potentially large data blob that has little value in\nbeing readable to the user. To serialize I do this:\n\n- normalize the data in the dict. The numpy.save...() functions have\n quirks, so I must work around them:\n\n - All non-numpy-array values are read in as scalar numpy arrays, so I\n must extract them at reading time\n\n - Any non-trivial objects are pickled, but pickling is not safe for\n untrusted data, so I disable pickling, which means that non-trivial\n objects are not serializable. This includes None. So I store None as\n ''. This means I can't store '', which I guess is OK\n\n- np.savez_compressed() to make a compressed binary data stream\n\n- base64.b85encode() to convert to printable ascii\n\nThis works, but the normalization is ugly, and this thing is\ninefficient. b85encode() is written in Python for instance. I can\nreplace some of this with tarfile, which doesn't really solve the\nproblems, but it could be a starting point for something better in the\nfuture\n\n\n def write():\n d = dict( x = np.arange(1000) + 5,\n y = np.arange(300, dtype=float) / 2,\n z = None,\n s = 'abc',\n bt = True,\n bf = False)\n\n f = io.BytesIO()\n tar = \\\n tarfile.open(name = None,\n mode = 'w|gz',\n fileobj = f)\n\n for k in d.keys():\n v = d[k]\n if v is None: v = ''\n\n d_bytes = io.BytesIO()\n np.save(d_bytes, v, allow_pickle = False)\n\n tarinfo = tarfile.TarInfo(name=k)\n tarinfo.size = d_bytes.tell()\n d_bytes.seek(0)\n tar.addfile( tarinfo,\n fileobj = d_bytes )\n tar.close()\n sys.stdout.buffer.write(f.getvalue())\n\n def read():\n with open(\"/tmp/tst.tar.gz\", \"rb\") as f:\n tar = \\\n tarfile.open(name = None,\n mode = 'r|gz',\n fileobj = f)\n\n for m in tar:\n b = tar.extractfile(m).read()\n arr = np.load(io.BytesIO(b), allow_pickle=False, encoding='bytes')\n if arr.shape == ():\n arr = arr.item()\n if type(arr) is str and arr == '':\n arr = None\n print(arr)\n tar.close()\n '''\n\n data_bytes = io.BytesIO()\n\n optimization_inputs_normalized = dict()\n for k in optimization_inputs.keys():\n v = optimization_inputs[k]\n if v is None: v = ''\n optimization_inputs_normalized[k] = v\n\n np.savez_compressed(data_bytes, **optimization_inputs_normalized)\n return \\\n base64.b85encode(data_bytes.getvalue())\n\n\ndef _deserialize_optimization_inputs(data_bytes):\n r'''Convert an ascii string for the optimization-input to a full dict\n\nThis is an internal function.\n\n\nThis is the inverse of _serialize_optimization_inputs(). See the docstring of\nthat function for details\n\n '''\n\n optimization_inputs_bytes = io.BytesIO(base64.b85decode(data_bytes))\n\n _optimization_inputs = np.load(optimization_inputs_bytes, allow_pickle = False)\n\n # Now I need to post-process my output array. Numpy converts everything\n # to numpy arrays for some reason, even things that aren't numpy arrays.\n # So I find everything that's an array of shape (), and convert it to\n # the actual thing contained in the array\n optimization_inputs = dict()\n for k in _optimization_inputs.keys():\n arr = _optimization_inputs[k]\n if arr.shape == ():\n arr = arr.item()\n if type(arr) is str and arr == '':\n arr = None\n optimization_inputs[k] = arr\n\n # for legacy compatibility\n def renamed(s0, s1, d):\n if s0 in d and not s1 in d:\n d[s1] = d[s0]\n del d[s0]\n renamed('do_optimize_intrinsic_core',\n 'do_optimize_intrinsics_core',\n optimization_inputs)\n renamed('do_optimize_intrinsic_distortions',\n 'do_optimize_intrinsics_distortions',\n optimization_inputs)\n # renamed('icam_intrinsics_optimization_inputs',\n # 'icam_intrinsics',\n # optimization_inputs)\n\n if 'calibration_object_width_n' in optimization_inputs:\n del optimization_inputs['calibration_object_width_n' ]\n if 'calibration_object_height_n' in optimization_inputs:\n del optimization_inputs['calibration_object_height_n']\n\n return optimization_inputs\n\n\nclass cameramodel(object):\n r'''A class that describes the lens parameters and geometry of a single camera\n\nSYNOPSIS\n\n model = mrcal.cameramodel('xxx.cameramodel')\n\n extrinsics_Rt_toref = model.extrinsics_Rt_toref()\n\n extrinsics_Rt_toref[3,2] += 10.0\n\n extrinsics_Rt_toref = model.extrinsics_Rt_toref(extrinsics_Rt_toref)\n\n model.write('moved.cameramodel')\n\n # we read a model from disk, moved it 10 units along the z axis, and wrote\n # the results back to disk\n\nThis class represents\n\n- The intrinsics: parameters that describe the lens. These do not change as the\n camera moves around in space. These are represented by a tuple\n (lensmodel,intrinsics_data)\n\n - lensmodel: a string \"LENSMODEL_...\". The full list of supported models is\n returned by mrcal.supported_lensmodels()\n\n - intrinsics_data: a numpy array of shape\n (mrcal.lensmodel_num_params(lensmodel),). For lensmodels that have an\n \"intrinsics core\" (all of them, currently) the first 4 elements are\n\n - fx: the focal-length along the x axis, in pixels\n - fy: the focal-length along the y axis, in pixels\n - cx: the projection center along the x axis, in pixels\n - cy: the projection center along the y axis, in pixels\n\n The remaining elements (both their number and their meaning) are dependent\n on the specific lensmodel being used. Some models (LENSMODEL_PINHOLE for\n example) do not have any elements other than the core.\n\n- The imager size: the dimensions of the imager, in a (width,height) list\n\n- The extrinsics: the pose of this camera in respect to some reference\n coordinate system. The meaning of this \"reference\" coordinate system is\n user-defined, and means nothing to mrcal.cameramodel. If we have multiple\n cameramodels, they generally share this \"reference\" coordinate system, and it\n is used as an anchor to position the cameras in respect to one another.\n Internally this is stored as an rt transformation converting points\n represented in the reference coordinate TO a representation in the camera\n coordinate system. These are gettable/settable by these methods:\n\n - extrinsics_rt_toref()\n - extrinsics_rt_fromref()\n - extrinsics_Rt_toref()\n - extrinsics_Rt_fromref()\n\n These exist for convenience, and handle the necessary conversion internally.\n These make it simple to use the desired Rt/rt transformation and the desired\n to/from reference direction.\n\n- The valid-intrinsics region: a contour in the imager where the projection\n behavior is \"reliable\". The meaning of \"reliable\" is user-defined. mrcal is\n able to report the projection uncertainty anywhere in space, and this is a\n more fine-grained way to measure \"reliability\", but sometimes it is convenient\n to define an uncertainty limit, and to compute a region where this limit is\n met. This region can then be stored in the mrcal.cameramodel object. A missing\n valid-intrinsics region means \"unknown\". An empty valid-intrinsics region\n (array of length 0) means \"intrinsics are valid nowhere\". Storing this is\n optional.\n\n- The optimization inputs: this is a dict containing all the data that was used\n to compute the contents of this model. These are optional. These are the\n kwargs passable to mrcal.optimize() and mrcal.optimizer_callback() that\n describe the optimization problem at its final optimum. Storing these is\n optional, but they are very useful for diagnostics, since everything in the\n model can be re-generated from this data. Some things (most notably the\n projection uncertainties) are also computed off the optimization_inputs(),\n making these extra-useful. The optimization_inputs dict can be queried by the\n optimization_inputs() method. Setting this can be done only together with the\n intrinsics(), using the intrinsics() method. For the purposes of computing the\n projection uncertainty it is allowed to move the camera (change the\n extrinsics), so the extrinsics_...() methods may be called without\n invalidating the optimization_inputs.\n\nThis class provides facilities to read/write models on disk, and to get/set the\nvarious components.\n\nThe format of a .cameramodel file is a python dictionary that we (safely) eval.\nA sample valid .cameramodel file:\n\n # generated with ...\n { 'lensmodel': 'LENSMODEL_OPENCV8',\n\n # intrinsics are fx,fy,cx,cy,distortion0,distortion1,....\n 'intrinsics': [1766.0712405930,\n 1765.8925266865,\n 1944.0664501036,\n 1064.5231421210,\n 2.1648025156,\n -1.1851581377,\n -0.0000931342,\n 0.0007782462,\n -0.2351910903,\n 2.4460295029,\n -0.6697132481,\n -0.6284355415],\n\n # extrinsics are rt_fromref\n 'extrinsics': [0,0,0,0,0,0],\n 'imagersize': [3840,2160]\n }\n\n '''\n\n def _write(self, f, note=None):\n r'''Writes out this camera model to an open file'''\n\n if note is not None:\n for l in note.splitlines():\n f.write('# ' + l + '\\n')\n\n _validateIntrinsics(self._imagersize,\n self._intrinsics)\n _validateValidIntrinsicsRegion(self._valid_intrinsics_region)\n _validateExtrinsics(self._extrinsics)\n\n # I write this out manually instead of using repr for the whole thing\n # because I want to preserve key ordering\n f.write(\"{\\n\")\n f.write(\" 'lensmodel': '{}',\\n\".format(self._intrinsics[0]))\n f.write(\"\\n\")\n\n N = len(self._intrinsics[1])\n if(mrcal.lensmodel_metadata_and_config(self._intrinsics[0])['has_core']):\n f.write(\" # intrinsics are fx,fy,cx,cy,distortion0,distortion1,....\\n\")\n f.write((\" 'intrinsics': [\" + (\" {:.10g},\" * N) + \"],\\n\").format(*self._intrinsics[1]))\n f.write(\"\\n\")\n\n if self._valid_intrinsics_region is not None:\n f.write(\" 'valid_intrinsics_region': [\\n\")\n for row in self._valid_intrinsics_region:\n f.write((\" [ {:.10g}, {:.10g} ],\\n\").format(*row))\n f.write(\"],\\n\\n\")\n\n N = len(self._extrinsics)\n f.write(\" # extrinsics are rt_fromref\\n\")\n f.write((\" 'extrinsics': [\" + (\" {:.10g},\" * N) + \"],\\n\").format(*self._extrinsics))\n f.write(\"\\n\")\n\n N = 2\n f.write((\" 'imagersize': [\" + (\" {:d},\" * N) + \"],\\n\").format(*(int(x) for x in self._imagersize)))\n f.write(\"\\n\")\n\n if self._icam_intrinsics is not None:\n f.write((\" 'icam_intrinsics': {:d},\\n\").format(self._icam_intrinsics))\n f.write(\"\\n\")\n\n if self._optimization_inputs_string is not None:\n f.write(r\"\"\" # The optimization inputs contain all the data used to compute this model.\n # This contains ALL the observations for ALL the cameras in the solve. The uses of\n # this are to be able to compute projection uncertainties, to visualize the\n # calibration-time geometry and to re-run the original optimization for\n # diagnostics. This is a big chunk of data that isn't useful for humans to\n # interpret, so it's stored in binary, compressed, and encoded to ascii in\n # base-85. Modifying the intrinsics of the model invalidates the optimization\n # inputs: the optimum implied by the inputs would no longer match the stored\n # parameters. Modifying the extrinsics is OK, however: if we move the camera\n # elsewhere, the original solve can still be used to represent the camera-relative\n # projection uncertainties\n\"\"\")\n f.write(f\" 'optimization_inputs': {self._optimization_inputs_string},\\n\\n\")\n\n f.write(\"}\\n\")\n\n\n def _read_into_self(self, f):\n r'''Reads in a model from an open file, or the model given as a string\n\n Note that the string is NOT a filename, it's the model data'''\n\n # workaround for python3 idiocy\n try:\n filetype = file\n except:\n filetype = io.IOBase\n if isinstance(f, filetype):\n s = f.read()\n try:\n name = f.name\n except:\n name = None\n else:\n s = f\n name = None\n\n try:\n model = ast.literal_eval(s)\n except:\n if name is None:\n raise CameramodelParseException(\"Failed to parse cameramodel!\")\n else:\n raise CameramodelParseException(f\"Failed to parse cameramodel '{name}'\")\n\n # for legacy compatibility\n def renamed(s0, s1, d):\n if s0 in d and not s1 in d:\n d[s1] = d[s0]\n del d[s0]\n renamed('distortion_model',\n 'lensmodel',\n model)\n renamed('lens_model',\n 'lensmodel',\n model)\n renamed('icam_intrinsics_optimization_inputs',\n 'icam_intrinsics',\n model)\n model['lensmodel'] = model['lensmodel'].replace('DISTORTION', 'LENSMODEL')\n\n\n\n keys_required = set(('lensmodel',\n 'intrinsics',\n 'extrinsics',\n 'imagersize'))\n keys_received = set(model.keys())\n if keys_received < keys_required:\n raise Exception(\"Model must have at least these keys: '{}'. Instead I got '{}'\". \\\n format(keys_required, keys_received))\n\n valid_intrinsics_region = None\n if 'valid_intrinsics_region' in model:\n if len(model['valid_intrinsics_region']) > 0:\n valid_intrinsics_region = np.array(model['valid_intrinsics_region'])\n else:\n valid_intrinsics_region = np.zeros((0,2))\n\n intrinsics = (model['lensmodel'], np.array(model['intrinsics'], dtype=float))\n\n _validateIntrinsics(model['imagersize'],\n intrinsics)\n try:\n _validateValidIntrinsicsRegion(valid_intrinsics_region)\n except Exception as e:\n warnings.warn(\"Invalid valid_intrinsics region; skipping: '{}'\".format(e))\n valid_intrinsics_region = None\n\n _validateExtrinsics(model['extrinsics'])\n\n self._intrinsics = intrinsics\n self._valid_intrinsics_region = mrcal.close_contour(valid_intrinsics_region)\n self._extrinsics = np.array(model['extrinsics'], dtype=float)\n self._imagersize = np.array(model['imagersize'], dtype=np.int32)\n\n if 'optimization_inputs' in model:\n if not isinstance(model['optimization_inputs'], bytes):\n raise CameramodelParseException(\"'optimization_inputs' is given, but it's not a byte string. type(optimization_inputs)={}\". \\\n format(type(model['optimization_inputs'])))\n self._optimization_inputs_string = model['optimization_inputs']\n\n if 'icam_intrinsics' not in model:\n raise CameramodelParseException(\"'optimization_inputs' is given, but icam_intrinsics NOT given\")\n if not isinstance(model['icam_intrinsics'], int):\n raise CameramodelParseException(\"'icam_intrinsics' is given, but it's not an int\")\n if model['icam_intrinsics'] < 0:\n raise CameramodelParseException(\"'icam_intrinsics' is given, but it's <0. Must be >= 0\")\n self._icam_intrinsics = model['icam_intrinsics']\n else:\n self._optimization_inputs_string = None\n self._icam_intrinsics = None\n\n def __init__(self,\n\n file_or_model = None,\n *,\n intrinsics = None,\n imagersize = None,\n extrinsics_Rt_toref = None,\n extrinsics_Rt_fromref = None,\n extrinsics_rt_toref = None,\n extrinsics_rt_fromref = None,\n\n optimization_inputs = None,\n icam_intrinsics = None,\n\n valid_intrinsics_region = None ):\n r'''Initialize a new camera-model object\n\nSYNOPSIS\n\n # reading from a file on disk\n model0 = mrcal.cameramodel('xxx.cameramodel')\n\n # using discrete arguments\n model1 = mrcal.cameramodel( intrinsics = ('LENSMODEL_PINHOLE',\n np.array((fx,fy,cx,cy))),\n imagersize = (640,480) )\n\n # using a optimization_inputs dict\n model2 = mrcal.cameramodel( optimization_inputs = optimization_inputs,\n icam_intrinsics = 0 )\n\nWe can initialize using one of several methods, depending on which arguments are\ngiven. The arguments for the methods we're not using MUST all be None. Methods:\n\n- Read a file on disk. The filename should be given in the 'file_or_model'\n argument (possibly as a positional argument)\n\n- Read a python 'file' object. Similarly, the opened file should be given in the\n 'file_or_model' argument (possibly as a poitional argument)\n\n- Copy an existing cameramodel object. Pass the object in the 'file_or_model'\n argument (possibly as a poitional argument)\n\n- Read discrete arguments. The components of this model (intrinsics, extrinsics,\n etc) can be passed-in separetely via separate keyword arguments\n\n- optimization_inputs. If we have an optimization_inputs dict to store, this\n alone may be passed-in, and all the model components can be read from it.\n\nARGUMENTS\n\n- file_or_model: we read the camera model from a filename or a pre-opened file\n object or from an existing cameramodel object to copy. Both .cameramodel and\n the legacy .cahvor formats are supported. This may be given as a positional\n argument. Everything else may be given only as keyword arguments.\n\n- intrinsics: a tuple (lensmodel, intrinsics_data). If given, 'imagersize' is\n also required. This may be given only as a keyword argument.\n\n- imagersize: tuple (width,height) for the size of the imager. If given,\n 'intrinsics' is also required. This may be given only as a keyword argument.\n\n- extrinsics_Rt_toref: numpy array of shape (4,3) describing the Rt\n transformation FROM the camera coordinate system TO the reference coordinate\n system. Exclusive with the other 'extrinsics_...' arguments. If given,\n 'intrinsics' and 'imagersize' are both required. If no 'extrinsics_...'\n arguments are given, an identity transformation is set. This may be given only\n as a keyword argument.\n\n- extrinsics_Rt_fromref: numpy array of shape (4,3) describing the Rt\n transformation FROM the reference coordinate system TO the camera coordinate\n system. Exclusive with the other 'extrinsics_...' arguments. If given,\n 'intrinsics' and 'imagersize' are both required. If no 'extrinsics_...'\n arguments are given, an identity transformation is set. This may be given only\n as a keyword argument.\n\n- extrinsics_rt_toref: numpy array of shape (6,) describing the rt\n transformation FROM the camera coordinate system TO the reference coordinate\n system. Exclusive with the other 'extrinsics_...' arguments. If given,\n 'intrinsics' and 'imagersize' are both required. If no 'extrinsics_...'\n arguments are given, an identity transformation is set. This may be given only\n as a keyword argument.\n\n- extrinsics_rt_fromref: numpy array of shape (6,) describing the rt\n transformation FROM the reference coordinate system TO the camera coordinate\n system. Exclusive with the other 'extrinsics_...' arguments. If given,\n 'intrinsics' and 'imagersize' are both required. If no 'extrinsics_...'\n arguments are given, an identity transformation is set. This may be given only\n as a keyword argument.\n\n- optimization_inputs: a dict of arguments to mrcal.optimize() at the optimum.\n These contain all the information needed to populate the camera model (and\n more!). If given, 'icam_intrinsics' is also required. This may be given only\n as a keyword argument.\n\n- icam_intrinsics: integer identifying this camera in the solve defined by\n 'optimization_inputs'. If given, 'optimization_inputs' is required. This may\n be given only as a keyword argument.\n\n- valid_intrinsics_region': numpy array of shape (N,2). Defines a closed contour\n in the imager pixel space. Points inside this contour are assumed to have\n 'valid' intrinsics, with the meaning of 'valid' defined by the user. An array\n of shape (0,2) menas \"valid nowhere\". This may be given only as a keyword\n argument.\n\n '''\n\n Nargs = dict(file_or_model = 0,\n discrete = 0,\n extrinsics = 0,\n optimization_inputs = 0)\n\n if file_or_model is not None: Nargs['file_or_model'] += 1\n if intrinsics is not None: Nargs['discrete'] += 1\n if imagersize is not None: Nargs['discrete'] += 1\n\n if extrinsics_Rt_toref is not None:\n Nargs['discrete'] += 1\n Nargs['extrinsics'] += 1\n if extrinsics_Rt_fromref is not None:\n Nargs['discrete'] += 1\n Nargs['extrinsics'] += 1\n if extrinsics_rt_toref is not None:\n Nargs['discrete'] += 1\n Nargs['extrinsics'] += 1\n if extrinsics_rt_fromref is not None:\n Nargs['discrete'] += 1\n Nargs['extrinsics'] += 1\n\n if optimization_inputs is not None:\n Nargs['optimization_inputs'] += 1\n if icam_intrinsics is not None:\n Nargs['optimization_inputs'] += 1\n\n\n\n if Nargs['file_or_model']:\n if Nargs['discrete'] + \\\n Nargs['optimization_inputs']:\n raise Exception(\"'file_or_model' specified, so none of the other inputs should be\")\n\n if isinstance(file_or_model, cameramodel):\n self._imagersize = np.array(file_or_model._imagersize, dtype=np.int32)\n self._extrinsics = np.array(file_or_model._extrinsics, dtype=float)\n self._intrinsics = (str(file_or_model._intrinsics[0]),\n np.array(file_or_model._intrinsics[1], dtype=float))\n if file_or_model._valid_intrinsics_region is not None:\n self._valid_intrinsics_region = np.array(mrcal.close_contour(file_or_model._valid_intrinsics_region),\n dtype=float)\n else:\n self._valid_intrinsics_region = None\n\n if file_or_model._optimization_inputs_string is not None:\n self._optimization_inputs_string = str(file_or_model._optimization_inputs_string)\n else:\n self._optimization_inputs_string = None\n\n if file_or_model._icam_intrinsics is not None:\n self._icam_intrinsics = int(file_or_model._icam_intrinsics)\n else:\n self._icam_intrinsics = None\n return\n\n if type(file_or_model) is str:\n\n # Some readable file. Read it!\n def tryread(f, what):\n modelstring = f.read()\n try:\n self._read_into_self(modelstring)\n return\n except CameramodelParseException:\n pass\n\n # Couldn't read the file as a .cameramodel. Does a .cahvor\n # work?\n\n # This is more complicated than it looks. I want to read the\n # .cahvor file into self, but the current cahvor interface\n # wants to generate a new model object. So I do that, write\n # it as a .cameramodel-formatted string, and then read that\n # back into self. Inefficient, but this is far from a hot\n # path\n from . import cahvor\n try:\n model = cahvor.read_from_string(modelstring)\n except:\n raise Exception(f\"Couldn't parse {what} as a camera model (.cameramodel or .cahvor)\") from None\n modelfile = io.StringIO()\n model.write(modelfile)\n self._read_into_self(modelfile.getvalue())\n\n if file_or_model == '-':\n tryread(sys.stdin, \"STDIN\")\n else:\n with open(file_or_model, 'r') as openedfile:\n tryread(openedfile, f\"file '{file_or_model}'\")\n return\n\n self._read_into_self(file_or_model)\n return\n\n\n\n\n if Nargs['discrete']:\n\n if Nargs['file_or_model'] + \\\n Nargs['optimization_inputs']:\n raise Exception(\"discrete values specified, so none of the other inputs should be\")\n\n if Nargs['discrete']-Nargs['extrinsics'] != 2:\n raise Exception(\"Discrete values given. Must have gotten 'intrinsics' AND 'imagersize' AND optionally ONE of the extrinsics_...\")\n\n if Nargs['extrinsics'] == 0:\n # No extrinsics. Use the identity\n self.extrinsics_rt_fromref(np.zeros((6,),dtype=float))\n elif Nargs['extrinsics'] == 1:\n if extrinsics_Rt_toref is not None: self.extrinsics_Rt_toref (extrinsics_Rt_toref)\n elif extrinsics_Rt_fromref is not None: self.extrinsics_Rt_fromref(extrinsics_Rt_fromref)\n elif extrinsics_rt_toref is not None: self.extrinsics_rt_toref (extrinsics_rt_toref)\n elif extrinsics_rt_fromref is not None: self.extrinsics_rt_fromref(extrinsics_rt_fromref)\n else:\n raise Exception(\"At most one of the extrinsics_... arguments may be given\")\n\n self.intrinsics(intrinsics, imagersize=imagersize)\n\n elif Nargs['optimization_inputs']:\n if Nargs['file_or_model'] + \\\n Nargs['discrete']:\n raise Exception(\"optimization_inputs specified, so none of the other inputs should be\")\n\n if Nargs['optimization_inputs'] != 2:\n raise Exception(\"optimization_input given. Must have gotten 'optimization_input' AND 'icam_intrinsics'\")\n\n self.intrinsics( ( optimization_inputs['lensmodel'],\n optimization_inputs['intrinsics'][icam_intrinsics] ),\n imagersize = optimization_inputs['imagersizes'][icam_intrinsics],\n optimization_inputs = optimization_inputs,\n icam_intrinsics = icam_intrinsics)\n\n icam_extrinsics = mrcal.corresponding_icam_extrinsics(icam_intrinsics,\n **optimization_inputs)\n if icam_extrinsics < 0:\n self.extrinsics_rt_fromref(np.zeros((6,), dtype=float))\n else:\n self.extrinsics_rt_fromref(optimization_inputs['extrinsics_rt_fromref'][icam_extrinsics])\n\n else:\n raise Exception(\"At least one source of initialization data must have been given. Need a filename or a cameramodel object or discrete arrays or optimization_inputs\")\n\n\n self._valid_intrinsics_region = None # default\n if valid_intrinsics_region is not None:\n try:\n self.valid_intrinsics_region(valid_intrinsics_region)\n except Exception as e:\n warnings.warn(\"Invalid valid_intrinsics region; skipping: '{}'\".format(e))\n\n\n def __str__(self):\n '''Stringification\n\n Return what would be written to a .cameramodel file'''\n\n f = io.StringIO()\n self._write(f)\n return f.getvalue()\n\n def __repr__(self):\n '''Representation\n\n Return a string of a constructor function call'''\n\n funcs = (self.imagersize,\n self.intrinsics,\n self.extrinsics_rt_fromref,\n self.valid_intrinsics_region)\n\n return 'mrcal.cameramodel(' + \\\n ', '.join( f.__func__.__code__.co_name + '=' + repr(f()) for f in funcs ) + \\\n ')'\n\n\n def write(self, f, *, note=None, cahvor=False):\n r'''Write out this camera model to disk\n\nSYNOPSIS\n\n model.write('left.cameramodel')\n\nWe write the contents of the given mrcal.cameramodel object to the given\nfilename or a given pre-opened file. If the filename is 'xxx.cahv' or\n'xxx.cahvor' or 'xxx.cahvore' or if cahvor: we use the legacy cahvor file format\nfor output\n\nARGUMENTS\n\n- f: a string for the filename or an opened Python 'file' object to use\n\n- note: an optional string, defaulting to None. This is a comment that will be\n written to the top of the output file. This should describe how this model was\n generated\n\n- cahvor: an optional boolean, defaulting to False. If True: we write out the\n data using the legacy .cahvor file format\n\nRETURNED VALUES\n\nNone\n '''\n\n if cahvor:\n from . import cahvor\n cahvor.write(f, self, note)\n return\n\n if type(f) is str:\n if re.match(\".*\\.cahv(or(e)?)?$\", f):\n from . import cahvor\n cahvor.write(f, self, note)\n\n else:\n with open(f, 'w') as openedfile:\n self._write( openedfile, note )\n\n else:\n self._write( f, note )\n\n\n def intrinsics(self,\n intrinsics = None,\n *,\n imagersize = None,\n optimization_inputs = None,\n icam_intrinsics = None):\n r'''Get or set the intrinsics in this model\n\nSYNOPSIS\n\n # getter\n lensmodel,intrinsics_data = model.intrinsics()\n\n # setter\n model.intrinsics( intrinsics = ('LENSMODEL_PINHOLE',\n fx_fy_cx_cy),\n imagersize = (640,480),\n optimization_inputs = optimization_inputs,\n icam_intrinsics = 0)\n\nThis function has two modes of operation: a getter and a setter, depending on\nthe arguments.\n\n- If no arguments are given: this is a getter. The getter returns the\n (lensmodel, intrinsics_data) tuple only.\n\n - lensmodel: a string \"LENSMODEL_...\". The full list of supported models is\n returned by mrcal.supported_lensmodels()\n\n - intrinsics_data: a numpy array of shape\n (mrcal.lensmodel_num_params(lensmodel),). For lensmodels that have an\n \"intrinsics core\" (all of them, currently) the first 4 elements are\n\n - fx: the focal-length along the x axis, in pixels\n - fy: the focal-length along the y axis, in pixels\n - cx: the projection center along the x axis, in pixels\n - cy: the projection center along the y axis, in pixels\n\n The remaining elements (both their number and their meaning) are dependent\n on the specific lensmodel being used. Some models (LENSMODEL_PINHOLE for\n example) do not have any elements other than the core.\n\n- If any arguments are given, this is a setter. The setter takes in\n\n - the (lensmodel, intrinsics_data) tuple\n - (optionally) the imagersize\n - (optionally) optimization_inputs\n - (optionally) icam_intrinsics\n\n Changing any of these 4 parameters automatically invalidates the others, and\n it only makes sense to set them in unison.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- intrinsics: a (lensmodel, intrinsics_data) if we're setting; None if we're\n getting\n\n- imagersize: optional iterable of length 2. The (width,height) for the size of\n the imager. If omitted, I use the imagersize already stored in this object.\n This is useful if a valid cameramodel object already exists, and I want to\n update it with new lens parameters\n\n- optimization_inputs: optional dict of arguments to mrcal.optimize() at the\n optimum. These contain all the information needed to populate the camera model\n (and more!). If given, 'icam_intrinsics' is also required. If omitted, no\n optimization_inputs are stored; re-solving and computing of uncertainties is\n impossible.\n\n- icam_intrinsics: optional integer identifying this camera in the solve defined\n by 'optimization_inputs'. May be omitted if 'optimization_inputs' is omitted\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a (lensmodel, intrinsics_data)\ntuple where\n\n- lensmodel is a string \"LENSMODEL_...\"\n\n- intrinsics_data is a numpy array of shape\n (mrcal.lensmodel_num_params(lensmodel),)\n\n '''\n\n # This is a getter\n if \\\n imagersize is None and \\\n intrinsics is None and \\\n optimization_inputs is None and \\\n icam_intrinsics is None:\n return (str(self._intrinsics[0]),\n np.array(self._intrinsics[1], dtype=float))\n\n\n # This is a setter. The rest of this function does all that work\n if imagersize is None: imagersize = self._imagersize\n _validateIntrinsics(imagersize,\n intrinsics,\n optimization_inputs,\n icam_intrinsics)\n\n self._imagersize = np.array(imagersize, dtype=np.int32)\n self._intrinsics = (str(intrinsics[0]),\n np.array(intrinsics[1], dtype=float))\n\n if optimization_inputs is not None:\n self._optimization_inputs_string = \\\n _serialize_optimization_inputs(optimization_inputs)\n self._icam_intrinsics = icam_intrinsics\n else:\n self._optimization_inputs_string = None\n self._icam_intrinsics = None\n\n\n def _extrinsics_rt(self, toref, rt=None):\n r'''Get or set the extrinsics in this model\n\nThis function represents the pose as a 6-long numpy array that contains\na 3-long Rodrigues rotation followed by a 3-long translation in the last\nrow:\n\n r = rt[:3]\n t = rt[3:]\n R = mrcal.R_from_r(r)\n\nThe transformation is b <-- R*a + t:\n\n import numpysane as nps\n b = nps.matmult(a, nps.transpose(R)) + t\n\nif rt is None: this is a getter; otherwise a setter.\n\ntoref is a boolean. if toref: then rt maps points in the coord system of\nTHIS camera to the reference coord system. Otherwise in the opposite\ndirection\n\n '''\n\n # The internal representation is rt_fromref\n\n if rt is None:\n # getter\n if not toref:\n return np.array(self._extrinsics)\n return mrcal.invert_rt(self._extrinsics)\n\n\n # setter\n if not toref:\n self._extrinsics = np.array(rt, dtype=float)\n return True\n\n self._extrinsics = mrcal.invert_rt(rt.astype(float))\n return True\n\n\n def extrinsics_rt_toref(self, rt=None):\n r'''Get or set the extrinsics in this model\n\nSYNOPSIS\n\n # getter\n rt_rc = model.extrinsics_rt_toref()\n\n # setter\n model.extrinsics_rt_toref( rt_rc )\n\nThis function gets/sets rt_toref: a numpy array of shape (6,) describing the rt\ntransformation FROM the camera coordinate system TO the reference coordinate\nsystem.\n\nif rt is None: this is a getter; otherwise a setter.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- rt: if we're setting, a numpy array of shape (6,). The rt transformation TO\n the reference coordinate system. If we're getting, None\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a a numpy array of shape (6,).\nThe rt transformation TO the reference coordinate system.\n\n '''\n return self._extrinsics_rt(True, rt)\n\n\n def extrinsics_rt_fromref(self, rt=None):\n r'''Get or set the extrinsics in this model\n\nSYNOPSIS\n\n # getter\n rt_cr = model.extrinsics_rt_fromref()\n\n # setter\n model.extrinsics_rt_fromref( rt_cr )\n\nThis function gets/sets rt_fromref: a numpy array of shape (6,) describing the\nrt transformation FROM the reference coordinate system TO the camera coordinate\nsystem.\n\nif rt is None: this is a getter; otherwise a setter.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- rt: if we're setting, a numpy array of shape (6,). The rt transformation FROM\n the reference coordinate system. If we're getting, None\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a a numpy array of shape (6,).\nThe rt transformation FROM the reference coordinate system.\n\n '''\n return self._extrinsics_rt(False, rt)\n\n\n def _extrinsics_Rt(self, toref, Rt=None):\n r'''Get or set the extrinsics in this model\n\n This function represents the pose as a shape (4,3) numpy array that\n contains a (3,3) rotation matrix, followed by a (1,3) translation in the\n last row:\n\n R = Rt[:3,:]\n t = Rt[ 3,:]\n\n The transformation is b <-- R*a + t:\n\n import numpysane as nps\n b = nps.matmult(a, nps.transpose(R)) + t\n\n if Rt is None: this is a getter; otherwise a setter.\n\n toref is a boolean. if toref: then Rt maps points in the coord system of\n THIS camera to the reference coord system. Otherwise in the opposite\n direction\n\n '''\n\n # The internal representation is rt_fromref\n\n if Rt is None:\n # getter\n rt_fromref = self._extrinsics\n Rt_fromref = mrcal.Rt_from_rt(rt_fromref)\n if not toref:\n return Rt_fromref\n return mrcal.invert_Rt(Rt_fromref)\n\n # setter\n if toref:\n Rt_fromref = mrcal.invert_Rt(Rt.astype(float))\n self._extrinsics = mrcal.rt_from_Rt(Rt_fromref)\n return True\n\n self._extrinsics = mrcal.rt_from_Rt(Rt.astype(float))\n return True\n\n\n def extrinsics_Rt_toref(self, Rt=None):\n r'''Get or set the extrinsics in this model\n\nSYNOPSIS\n\n # getter\n Rt_rc = model.extrinsics_Rt_toref()\n\n # setter\n model.extrinsics_Rt_toref( Rt_rc )\n\nThis function gets/sets Rt_toref: a numpy array of shape (4,3) describing the Rt\ntransformation FROM the camera coordinate system TO the reference coordinate\nsystem.\n\nif Rt is None: this is a getter; otherwise a setter.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- Rt: if we're setting, a numpy array of shape (4,3). The Rt transformation TO\n the reference coordinate system. If we're getting, None\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a a numpy array of shape\n(4,3). The Rt transformation TO the reference coordinate system.\n\n '''\n return self._extrinsics_Rt(True, Rt)\n\n\n def extrinsics_Rt_fromref(self, Rt=None):\n r'''Get or set the extrinsics in this model\n\nSYNOPSIS\n\n # getter\n Rt_cr = model.extrinsics_Rt_fromref()\n\n # setter\n model.extrinsics_Rt_fromref( Rt_cr )\n\nThis function gets/sets Rt_fromref: a numpy array of shape (4,3) describing the\nRt transformation FROM the reference coordinate system TO the camera coordinate\nsystem.\n\nif Rt is None: this is a getter; otherwise a setter.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- Rt: if we're setting, a numpy array of shape (4,3). The Rt transformation FROM\n the reference coordinate system. If we're getting, None\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a a numpy array of shape\n(4,3). The Rt transformation FROM the reference coordinate system.\n\n '''\n return self._extrinsics_Rt(False, Rt)\n\n\n def imagersize(self, *args, **kwargs):\n r'''Get the imagersize in this model\n\nSYNOPSIS\n\n width,height = model.imagersize()\n\nThis function retrieves the dimensions of the imager described by this camera\nmodel. This function is NOT a setter; use intrinsics() to set all the intrinsics\ntogether.\n\nARGUMENTS\n\nNone\n\nRETURNED VALUE\n\nA length-2 tuple (width,height)\n\n '''\n if len(args) or len(kwargs):\n raise Exception(\"imagersize() is NOT a setter. Please use intrinsics() to set them all together\")\n\n return np.array(self._imagersize, dtype=np.int32)\n\n\n def valid_intrinsics_region(self, valid_intrinsics_region=None):\n r'''Get or set the valid-intrinsics region\n\nSYNOPSIS\n\n # getter\n region = model.valid_intrinsics_region()\n\n # setter\n model.valid_intrinsics_region( region )\n\nThe valid-intrinsics region is a closed contour in imager space representated as\na numpy array of shape (N,2). This is a region where the intrinsics are\n\"reliable\", with a user-defined meaning of that term. A region of shape (0,2)\nmeans \"intrinsics are valid nowhere\".\n\nif valid_intrinsics_region is None: this is a getter; otherwise a setter.\n\nThe getters return a copy of the data, and the setters make a copy of the input:\nso it's impossible for the caller or callee to modify each other's data.\n\nARGUMENTS\n\n- valid_intrinsics_region: if we're setting, a numpy array of shape (N,2). If\n we're getting, None\n\nRETURNED VALUE\n\nIf this is a getter (no arguments given), returns a numpy array of shape\n(N,2) or None, if no valid-intrinsics region is defined in this model\n\n '''\n if valid_intrinsics_region is None:\n # getter\n if self._valid_intrinsics_region is None:\n return None\n return np.array(self._valid_intrinsics_region, dtype=float)\n\n # setter\n if valid_intrinsics_region is None:\n self._valid_intrinsics_region = None\n return True\n\n valid_intrinsics_region = mrcal.close_contour(valid_intrinsics_region)\n\n # raises exception on error\n _validateValidIntrinsicsRegion(valid_intrinsics_region)\n self._valid_intrinsics_region = np.array(valid_intrinsics_region, dtype=float)\n return True\n\n\n def optimization_inputs(self):\n r'''Get the original optimization inputs\n\nSYNOPSIS\n\n b,x,j = mrcal.optimizer_callback(**model.optimization_inputs())[:3]\n\nThis function retrieves the optimization inputs: a dict containing all the data\nthat was used to compute the contents of this model. These are the kwargs\npassable to mrcal.optimize() and mrcal.optimizer_callback(), that describe the\noptimization problem at its final optimum. A cameramodel object may not contain\nthis data, in which case we return None.\n\nThis function is NOT a setter; use intrinsics() to set all the intrinsics\ntogether. The optimization inputs aren't a part of the intrinsics per se, but\nmodifying any part of the intrinsics invalidates the optimization inputs, so it\nmakes sense to set them all together\n\nARGUMENTS\n\nNone\n\nRETURNED VALUE\n\nThe optimization_inputs dict, or None if one isn't stored in this model.\n '''\n\n if self._optimization_inputs_string is None:\n return None\n x = _deserialize_optimization_inputs(self._optimization_inputs_string)\n if x['extrinsics_rt_fromref'] is None:\n x['extrinsics_rt_fromref'] = np.zeros((0,6), dtype=float)\n return x\n\n\n def _optimization_inputs_match(self, other_model):\n if self. _optimization_inputs_string is None:\n if other_model._optimization_inputs_string is None:\n return True\n else:\n return False\n\n if other_model._optimization_inputs_string is None:\n return False;\n\n # Both non-None\n return \\\n self. _optimization_inputs_string == \\\n other_model._optimization_inputs_string\n\n\n def _extrinsics_moved_since_calibration(self):\n optimization_inputs = self.optimization_inputs()\n icam_extrinsics = \\\n mrcal.corresponding_icam_extrinsics(self.icam_intrinsics(),\n **optimization_inputs)\n\n rt_cam_ref = self.extrinsics_rt_fromref()\n\n if icam_extrinsics < 0:\n # extrinsics WERE at the reference. So I should have an identity\n # transform\n return np.max(np.abs(rt_cam_ref)) > 0.0\n\n d = rt_cam_ref - \\\n optimization_inputs['extrinsics_rt_fromref'][icam_extrinsics]\n return np.max(np.abs(d)) > 1e-6\n\n\n def icam_intrinsics(self):\n r'''Get the camera index indentifying this camera at optimization time\n\nSYNOPSIS\n\n m = mrcal.cameramodel('xxx.cameramodel')\n\n optimization_inputs = m.optimization_inputs()\n\n icam_intrinsics = m.icam_intrinsics()\n\n icam_extrinsics = \\\n mrcal.corresponding_icam_extrinsics(icam_intrinsics,\n **optimization_inputs)\n\n if icam_extrinsics >= 0:\n extrinsics_rt_fromref_at_calibration_time = \\\n optimization_inputs['extrinsics_rt_fromref'][icam_extrinsics]\n\nThis function retrieves the integer identifying this camera in the solve defined\nby 'optimization_inputs'. When the optimization happened, we may have been\ncalibrating multiple cameras at the same time, and only one of those cameras is\ndescribed by this 'cameramodel' object. The 'icam_intrinsics' index returned by\nthis function specifies which camera this is.\n\nThis function is NOT a setter; use intrinsics() to set all the intrinsics\ntogether. The optimization inputs and icam_intrinsics aren't a part of the\nintrinsics per se, but modifying any part of the intrinsics invalidates the\noptimization inputs, so it makes sense to set them all together\n\nARGUMENTS\n\nNone\n\nRETURNED VALUE\n\nThe icam_intrinsics integer, or None if one isn't stored in this model.\n\n '''\n\n if self._icam_intrinsics is None:\n return None\n return self._icam_intrinsics\n","sub_path":"mrcal/cameramodel.py","file_name":"cameramodel.py","file_ext":"py","file_size_in_byte":52924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"543789742","text":"from unittest import TestCase\nimport pandas as pd\nfrom pasigram.controller.candidate_generation.utils \\\n import compute_right_most_path_nodes, add_new_forward_edge, compute_relevant_forward_edges, \\\n compute_relevant_backward_edges\nfrom pasigram.model.graph import Graph\n\n\nclass TestRightMostPath(TestCase):\n\n def test_compute_right_most_path_nodes(self):\n expected = sorted([1, 0, 2])\n edges = pd.DataFrame.from_dict({0: [0, 1, \"a\"],\n 1: [1, 0, \"b\"],\n 2: [1, 2, \"a\"]}, orient='index',\n columns=['source', 'target', 'label'])\n\n right_most_path = [0, 1, 2]\n right_most_path_nodes = sorted(compute_right_most_path_nodes(right_most_path, edges))\n print(right_most_path_nodes)\n self.assertEqual(expected, right_most_path_nodes, msg=\"Test for the matrix\")\n\n def test_compute_relevant_edges(self):\n expected_result = pd.DataFrame.from_dict({'DBDMa': ['DB', 'DM', 'a', int(2)],\n 'DBIRb': ['DB', 'IR', 'b', int(3)], }, orient='index',\n columns=['source', 'target', 'label', 'frequency'])\n frequent_edges = pd.DataFrame.from_dict({'DBDMa': ['DB', 'DM', 'a', int(2)],\n 'DBIRb': ['DB', 'IR', 'b', int(3)],\n 'IRDMc': ['IR', 'DM', 'c', int(2)],\n 'IRIRe': ['IR', 'IR', 'e']}, orient='index',\n columns=['source', 'target', 'label', 'frequency'])\n current_node_label = 'DB'\n\n relevant_edges = compute_relevant_forward_edges(current_node_label, frequent_edges)\n\n self.assertEqual(expected_result.values.tolist(), relevant_edges.values.tolist(),\n msg=\"Test for the relevant forward edges\")\n\n def test_add_new_forward_edge(self):\n edges = pd.DataFrame.from_dict({0: [0, 1, \"b\"]}, orient='index', columns=['source', 'target', 'label'])\n nodes = pd.DataFrame.from_dict({0: [\"DB\"],\n 1: [\"IR\"]}, orient='index', columns=['label'])\n\n graph = Graph(nodes, edges)\n\n graph.root_node = 0\n\n new_edge = pd.Series(data=['DB', 'DM', 'a'], index=['source', 'target', 'label'])\n\n new_graph = add_new_forward_edge(graph, new_edge, 0)\n\n print(new_graph.edges)\n print(new_graph.nodes)\n print(new_graph.csp_graph)\n\n def test_compute_relevant_backward_edges(self):\n edges = pd.DataFrame.from_dict({0: [0, 1, \"a\"],\n 1: [1, 0, \"a\"]}, orient='index', columns=['source', 'target', 'label'])\n nodes = pd.DataFrame.from_dict({0: [\"IR\"],\n 1: [\"IR\"]}, orient='index', columns=['label'])\n\n graph = Graph(nodes, edges)\n graph.root_node = 0\n graph.right_most_node = 1\n graph.right_most_path = [0, 1]\n\n relevant_backward_edges = compute_relevant_backward_edges(graph.right_most_node, graph.right_most_path,\n graph.edges).values\n\n expected = pd.DataFrame.from_dict({0: [1, 0, \"a\"],\n 1: [0, 1, \"a\"]}, orient='index',\n columns=['source', 'target', 'label']).values\n print(relevant_backward_edges)\n\n self.assertEqual(relevant_backward_edges.tolist(), expected.tolist(),\n msg=\"Test for the relevant backward edges of a node\")\n","sub_path":"tests/test_candidate_generation.py","file_name":"test_candidate_generation.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"316987623","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'riddles'\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^([0-9]+)/$', views.detail, name='detail'),\n url(r'^([0-9]+)/answer/$', views.answer, name='answer'),\n url(r'^register/$', views.RegisterFormView.as_view()),\n url(r'^login/$', views.LoginFormView.as_view()),\n url(r'^logout/$', views.LogoutView.as_view()),\n url(r'^password-change/', views.PasswordChangeView.as_view()),\n # отправка сообщения\n url(r'^([0-9]+)/post/$', views.post, name='post'),\n # отправка списка сообщений\n url(r'^([0-9]+)/msg_list/$', views.msg_list, name='msg_list'),\n # отправка оценки\n url(r'^([0-9]+)/post_mark/$', views.post_mark, name='post_mark'),\n # средняя оценка\n url(r'^([0-9]+)/get_mark/$', views.get_mark, name='get_mark'),\n url(r'^admin/$', views.admin, name='admin'),\n url(r'^post_riddle/$', views.post_riddle, name='post_riddle'),\n url(r'^subscribe/$', views.SubscribeView.as_view()),\n url(r'^unsubscribe/$', views.unsubscribe, name='unsubscribe'),\n]\n","sub_path":"riddles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"50289613","text":"from rest_framework.test import APITransactionTestCase\nfrom qleader.tests.data_handler import post_data, examples\nfrom qleader.models.result import Result\n\n\n# The test class for Result's custom methods\nclass ResultsTests(APITransactionTestCase):\n\n def test_get_optimizer(self):\n for optimizer, data in examples:\n response = post_data(self, data)\n result_id = response.data\n result = Result.objects.filter(id=result_id)[0]\n self.assertTrue(optimizer == result.get_optimizer())\n\n def test_get_runs(self):\n for optimizer, data in examples:\n response = post_data(self, data)\n result_id = response.data\n result = Result.objects.filter(id=result_id)[0]\n self.assertTrue(15 == len(result.get_runs()))\n for run in result.get_runs():\n self.assertEqual(result_id, run.result.id)\n self.assertTrue(optimizer == result.optimizer)\n","sub_path":"qleader/tests/test_result.py","file_name":"test_result.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"647575911","text":"from zoundry.appframework.global_services import getApplicationModel\r\nfrom zoundry.appframework.global_services import getResourceRegistry\r\nfrom zoundry.appframework.resources.resourceutils import ZMappedImageList\r\nfrom zoundry.appframework.ui.widgets.controls.common.menu.menu import ZMenu\r\nfrom zoundry.appframework.ui.widgets.controls.common.menu.menumodel import ZModelBasedMenuContentProvider\r\nfrom zoundry.appframework.ui.widgets.controls.common.menu.menumodel import ZModelBasedMenuEventHandler\r\nfrom zoundry.appframework.ui.widgets.controls.listex import IZListViewExContentProvider\r\nfrom zoundry.appframework.ui.widgets.controls.listex import ZListViewEx\r\nfrom zoundry.base.exceptions import ZAbstractMethodCalledException\r\nfrom zoundry.blogapp.constants import IZBlogAppServiceIDs\r\nfrom zoundry.blogapp.messages import _extstr\r\nfrom zoundry.blogapp.services.docindex.index import IZBlogBasedSearchFilter\r\nfrom zoundry.blogapp.services.docindex.indeximpl import ZBlogBasedSearchFilter\r\nfrom zoundry.blogapp.services.docindex.indeximpl import ZDocumentSearchFilter\r\nfrom zoundry.blogapp.ui.actions.blogpost.postactions import ZOpenBlogPostAction\r\nfrom zoundry.blogapp.ui.menus.blogpost.postmenu import ZBlogPostActionContext\r\nfrom zoundry.blogapp.ui.menus.blogpost.postmenumodel import ZBlogPostMenuModel\r\nfrom zoundry.blogapp.ui.util.blogutil import getBlogFromIds\r\nfrom zoundry.blogapp.ui.util.dateformatutil import formatLocalDateAndTime\r\nfrom zoundry.blogapp.ui.util.viewutil import fireViewSelectionEvent\r\nfrom zoundry.blogapp.ui.util.viewutil import fireViewUnselectionEvent\r\nfrom zoundry.blogapp.ui.views.viewselimpl import ZDocumentSelection\r\nimport wx\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Model used to query index to get list of posts\r\n# ------------------------------------------------------------------------------\r\nclass ZAbstractBlogPostsListQueryModel:\r\n\r\n def __init__(self):\r\n self.blogPosts = None\r\n self.accountIdCriteria = None\r\n self.blogIdCriteria = None\r\n self.blogEntryIdCriteria = None\r\n self.indexService = getApplicationModel().getService(IZBlogAppServiceIDs.DOCUMENT_INDEX_SERVICE_ID)\r\n # end __init__()\r\n\r\n def getBlogPosts(self):\r\n if self.blogPosts is None:\r\n self.blogPosts = self._findBlogPosts()\r\n return self.blogPosts\r\n # end getBlogPosts()\r\n\r\n def getDocumentIDO(self, index):\r\n return self.getBlogPosts()[index]\r\n\r\n def _findBlogPosts(self):\r\n searchFilter = self._createSearchFilter()\r\n if searchFilter is not None:\r\n if isinstance( searchFilter, ZBlogBasedSearchFilter):\r\n searchFilter.setAccountIdCriteria(self.accountIdCriteria)\r\n searchFilter.setBlogIdCriteria(self.blogIdCriteria)\r\n searchFilter.setBlogEntryIdCriteria(self.blogEntryIdCriteria)\r\n\r\n return self.indexService.findDocuments(searchFilter)\r\n else:\r\n return None\r\n # end _findBlogPosts()\r\n\r\n def clear(self):\r\n # reset the result set\r\n self.blogPosts = None\r\n self.accountIdCriteria = None\r\n self.blogIdCriteria = None\r\n self.blogEntryIdCriteria = None\r\n # end clear()\r\n\r\n def setAccountIdCriteria(self, id):\r\n self.accountIdCriteria = id\r\n # end setAccountIdCriteria()\r\n\r\n def setBlogIdCriteria(self, id):\r\n self.blogIdCriteria = id\r\n # end setBlogIdCriteria()\r\n\r\n def setBlogEntryIdCriteria(self, id):\r\n self.blogEntryIdCriteria = id\r\n # end setBlogEntryIdCriteria()\r\n\r\n def setBlogSearchCriteriaFilter(self, blogSearchFilter):\r\n if isinstance(blogSearchFilter, IZBlogBasedSearchFilter):\r\n self.setAccountIdCriteria( blogSearchFilter.getAccountIdCriteria())\r\n self.setBlogIdCriteria( blogSearchFilter.getBlogIdCriteria())\r\n self.setBlogEntryIdCriteria( blogSearchFilter.getBlogEntryIdCriteria())\r\n # end setBlogSearchCriteriaFilter()\r\n\r\n # Lets sub classes create concrete filter.\r\n def _createSearchFilter(self):\r\n raise ZAbstractMethodCalledException(unicode(self.__class__), u\"_createSearchFilter\") #$NON-NLS-1$\r\n # end _createSearchFilter()\r\n\r\n# end ZAbstractBlogPostsListQueryModel()\r\n\r\n# ------------------------------------------------------------------------------\r\n# Model used to query based on post\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostsListQueryModel(ZAbstractBlogPostsListQueryModel):\r\n\r\n def __init__(self):\r\n ZAbstractBlogPostsListQueryModel.__init__(self)\r\n # end __init__()\r\n\r\n def _createSearchFilter(self):\r\n return ZDocumentSearchFilter()\r\n # end _createSearchFilter()\r\n\r\n# end ZBlogPostsListQueryModel\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Model used to query based on tag\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostsListByTagQueryModel(ZBlogPostsListQueryModel):\r\n\r\n def __init__(self):\r\n ZBlogPostsListQueryModel.__init__(self)\r\n self.tagIDO = None\r\n self.tagId = None\r\n\r\n def setTagIDO(self, tagIDO):\r\n self.tagIDO = tagIDO\r\n id = None\r\n if self.tagIDO:\r\n id = self.tagIDO.getId()\r\n self.setTagId(id)\r\n\r\n def setTagId(self, id):\r\n self.tagId = id\r\n self.clear()\r\n\r\n def _createSearchFilter(self):\r\n searchFilter = None\r\n if self.tagId is not None:\r\n searchFilter = ZDocumentSearchFilter()\r\n searchFilter.setTagIdCriteria(self.tagId)\r\n return searchFilter\r\n# end ZBlogPostsListByTagQueryModel\r\n\r\n# ------------------------------------------------------------------------------\r\n# Model used to query based on image url\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostsListByImageQueryModel(ZBlogPostsListQueryModel):\r\n\r\n def __init__(self):\r\n ZBlogPostsListQueryModel.__init__(self)\r\n self.imageIDO = None\r\n self.imageUrl = None\r\n # end __init__()\r\n\r\n def setImageIDO(self, imageIDO):\r\n self.imageIDO = imageIDO\r\n url = None\r\n if self.imageIDO:\r\n url = self.imageIDO.getUrl()\r\n self.setImageUrl(url)\r\n # end setImageIDO()\r\n\r\n def setImageUrl(self, imageUrl):\r\n self.imageUrl = imageUrl\r\n self.clear()\r\n # end setImageUrl()\r\n\r\n def _createSearchFilter(self):\r\n searchFilter = None\r\n if self.imageUrl is not None:\r\n searchFilter = ZDocumentSearchFilter()\r\n searchFilter.setImageURLCriteria(self.imageUrl)\r\n return searchFilter\r\n # end _createSearchFilter()\r\n\r\n# end ZBlogPostsListByImageQueryModel\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Model used to query based on iurl link url name\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostsListByLinkQueryModel(ZBlogPostsListQueryModel):\r\n\r\n def __init__(self):\r\n ZBlogPostsListQueryModel.__init__(self)\r\n self.linkIDO = None\r\n self.linkUrl = None\r\n\r\n def setLinkIDO(self, linkIDO):\r\n self.linkIDO = linkIDO\r\n url = None\r\n if self.linkIDO:\r\n url = self.linkIDO.getUrl()\r\n self.setLinkUrl(url)\r\n\r\n def setLinkUrl(self, linkUrl):\r\n self.linkUrl = linkUrl\r\n self.clear()\r\n\r\n def _createSearchFilter(self):\r\n searchFilter = None\r\n if self.linkUrl is not None:\r\n searchFilter = ZDocumentSearchFilter()\r\n searchFilter.setLinkURLCriteria(self.linkUrl)\r\n return searchFilter\r\n# end ZBlogPostsListByLinkQueryModel\r\n\r\n\r\n# FIXME share with image info and posts view?\r\nIMAGE_LIST_DATA = [\r\n (u\"document\", u\"images/perspectives/standard/contextinfo/postsview/document.png\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n (u\"draft\", u\"images/perspectives/standard/contextinfo/postsview/draft.png\") #$NON-NLS-1$ #$NON-NLS-2$\r\n]\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# A list view provider that provides the blog post information for the tag.\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostListProvider(IZListViewExContentProvider):\r\n\r\n def __init__(self, blogPostsListQueryModel):\r\n self.blogPostsListQueryModel = blogPostsListQueryModel\r\n self.imageList = self._createImageList()\r\n self.columnInfo = self._createColumnInfo()\r\n # end __init__()\r\n\r\n def _createColumnInfo(self):\r\n cstyle = wx.LIST_FORMAT_LEFT\r\n # FIXME (PJ / EPW) cols should be: Title, LastModified, Post/PublishedDate and CreatedDate (the post/published date is imported when viewing published entries)\r\n columnInfo = [\r\n (_extstr(u\"blogpostslist.Title\"), None, cstyle, ZListViewEx.COLUMN_RELATIVE, 70), #$NON-NLS-1$\r\n (_extstr(u\"blogpostslist.Created\"), None, cstyle, ZListViewEx.COLUMN_RELATIVE, 30) #$NON-NLS-1$\r\n ]\r\n return columnInfo\r\n\r\n def _createImageList(self):\r\n imgList = ZMappedImageList()\r\n for (label, imagePath) in IMAGE_LIST_DATA:\r\n imgList.addImage(label, getResourceRegistry().getBitmap(imagePath))\r\n return imgList\r\n # end _createImageList()\r\n\r\n def getImageList(self):\r\n return self.imageList\r\n # end getImageList()\r\n\r\n def getNumColumns(self):\r\n return len(self.columnInfo)\r\n # end getNumColumns()\r\n\r\n def getNumRows(self):\r\n rows = self.blogPostsListQueryModel.getBlogPosts()\r\n if rows is not None:\r\n return len(rows)\r\n return 0\r\n # end getNumRows()\r\n\r\n def getColumnInfo(self, columnIndex):\r\n if columnIndex >= 0 and columnIndex < len(self.columnInfo):\r\n return self.columnInfo[columnIndex]\r\n else:\r\n return (u\"unknown-col-%d\" % columnIndex, None, 0, ZListViewEx.COLUMN_RELATIVE, 20) #$NON-NLS-1$\r\n # end getColumnInfo()\r\n\r\n def getRowText(self, rowIndex, columnIndex):\r\n posts = self.blogPostsListQueryModel.getBlogPosts()\r\n if posts and rowIndex < len(posts): \r\n data = posts[rowIndex]\r\n if columnIndex == 0:\r\n title = data.getTitle()\r\n if not title:\r\n title = u\"(%s)\" % _extstr(u\"blogpostslist.NoTitle\") #$NON-NLS-1$ #$NON-NLS-2$\r\n return title\r\n if columnIndex == 1:\r\n # note: data.getPublishedTime() is None for local/unpublished documents\r\n return formatLocalDateAndTime (data.getCreationTime() )\r\n return u\"\" #$NON-NLS-1$\r\n # end getRowText()\r\n\r\n def getRowImage(self, rowIndex, columnIndex):\r\n if columnIndex == 0:\r\n posts = self.blogPostsListQueryModel.getBlogPosts()\r\n if posts and rowIndex < len(posts):\r\n docIDO = posts[rowIndex]\r\n if self._isDraft(docIDO):\r\n return self.imageList[u\"draft\"] #$NON-NLS-1$\r\n else:\r\n return self.imageList[u\"document\"] #$NON-NLS-1$\r\n return -1\r\n # end getRowImage()\r\n\r\n def _isDraft(self, docIDO):\r\n for pubIDO in docIDO.getPubDataIDOs():\r\n if pubIDO.getDraft():\r\n return True\r\n return False\r\n # end _isDraft()\r\n\r\n# end ZBlogPostListProvider\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# List view control panel that displays a list of blog posts.\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostListView(ZListViewEx):\r\n\r\n def __init__(self, parent, blogPostsListQueryModel = None, provider = None):\r\n if not blogPostsListQueryModel:\r\n blogPostsListQueryModel = ZBlogPostsListQueryModel()\r\n self.blogPostsListQueryModel = blogPostsListQueryModel\r\n if provider is None:\r\n provider = ZBlogPostListProvider(self.blogPostsListQueryModel)\r\n self.openAction = ZOpenBlogPostAction()\r\n self.blogPostContextMenu = ZBlogPostMenuModel()\r\n\r\n ZListViewEx.__init__(self, provider, parent)\r\n\r\n self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onEntryActivated, self)\r\n self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onEntryRightClick, self)\r\n # end __init__()\r\n\r\n def getModel(self):\r\n return self.blogPostsListQueryModel\r\n # end getModel()\r\n\r\n def onEntryActivated(self, event):\r\n index = event.GetIndex()\r\n docIDO = self.blogPostsListQueryModel.getDocumentIDO(index)\r\n actionContext = ZBlogPostActionContext(self, docIDO)\r\n self.openAction.runAction(actionContext)\r\n # end onEntryActivated()\r\n\r\n def onEntryRightClick(self, event):\r\n index = event.GetIndex()\r\n docIDO = self.blogPostsListQueryModel.getDocumentIDO(index)\r\n actionContext = ZBlogPostActionContext(self, docIDO)\r\n provider = ZModelBasedMenuContentProvider(self.blogPostContextMenu, actionContext)\r\n handler = ZModelBasedMenuEventHandler(self.blogPostContextMenu, actionContext)\r\n menu = ZMenu(self, self.blogPostContextMenu.getRootNode(), provider, handler)\r\n self.PopupMenu(menu)\r\n event.Skip()\r\n # end onEntryRightClick()\r\n\r\n# end ZBlogPostListView\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Convenience class for a list of blog posts with a static box.\r\n# ------------------------------------------------------------------------------\r\nclass ZBlogPostListViewWithStaticBox(wx.Panel):\r\n\r\n def __init__(self, parent, blogPostsListQueryModel, provider = None, label = u\"\"): #$NON-NLS-1$\r\n wx.Panel.__init__(self, parent, wx.ID_ANY)\r\n self.model = blogPostsListQueryModel\r\n self.blogPostsStaticBox = wx.StaticBox(self, wx.ID_ANY, label)\r\n self.blogPostListView = ZBlogPostListView(self, self.model, provider = provider)\r\n bpSBox = wx.StaticBoxSizer(self.blogPostsStaticBox, wx.HORIZONTAL)\r\n bpSBox.Add(self.blogPostListView, 1, wx.EXPAND | wx.ALL, 2)\r\n vBox = wx.BoxSizer(wx.VERTICAL)\r\n vBox.AddSizer(bpSBox, 1, wx.EXPAND)\r\n self.SetSizer(vBox)\r\n self.SetAutoLayout(True)\r\n # end __init__()\r\n\r\n def getModel(self):\r\n return self.model\r\n # end getModel()\r\n\r\n def getListView(self):\r\n return self.blogPostListView\r\n # end getListView()\r\n\r\n# end ZBlogPostListViewWithStaticBox\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Convenience class for where found list view with static box.\r\n# ------------------------------------------------------------------------------\r\nclass ZWhereFoundBlogPostListView(ZBlogPostListViewWithStaticBox):\r\n\r\n def __init__(self, parent, blogPostsListQueryModel, provider = None): #$NON-NLS-1$\r\n self.document = None\r\n self.blog = None\r\n self.docStore = getApplicationModel().getService(IZBlogAppServiceIDs.DATA_STORE_SERVICE_ID)\r\n\r\n label = _extstr(u\"blogpostslist.WhereFound\") #$NON-NLS-1$\r\n ZBlogPostListViewWithStaticBox.__init__(self, parent, blogPostsListQueryModel, provider, label)\r\n\r\n self._bindWidgetEvents()\r\n # end __init__()\r\n \r\n def refresh(self):\r\n self.getListView().deselectAll()\r\n self.getListView().refresh()\r\n # end refresh()\r\n\r\n def _bindWidgetEvents(self):\r\n self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onBlogPostSelected, self.blogPostListView)\r\n\r\n wx.EVT_SET_FOCUS(self.blogPostListView, self.onFocus)\r\n wx.EVT_KILL_FOCUS(self.blogPostListView, self.onUnFocus)\r\n # end _bindWidgetEvents()\r\n\r\n def onBlogPostSelected(self, event):\r\n index = event.GetIndex()\r\n docIDO = self.model.getBlogPosts()[index]\r\n docId = docIDO.getId()\r\n self.document = self.docStore.getDocument(docId)\r\n self.blog = None\r\n \r\n if docIDO.getPubDataIDOs():\r\n pubDataIDO = docIDO.getPubDataIDOs()[0]\r\n self.blog = getBlogFromIds(pubDataIDO.getAccountId(), pubDataIDO.getBlogId())\r\n\r\n if self.document:\r\n fireViewSelectionEvent(ZDocumentSelection(self.document, self.blog))\r\n else:\r\n fireViewUnselectionEvent()\r\n\r\n event.Skip()\r\n # end onBlogPostSelected()\r\n\r\n def onFocus(self, event):\r\n if self.document:\r\n fireViewSelectionEvent(ZDocumentSelection(self.document, self.blog))\r\n else:\r\n fireViewUnselectionEvent()\r\n event.Skip()\r\n # end onFocus()\r\n\r\n def onUnFocus(self, event):\r\n fireViewUnselectionEvent()\r\n event.Skip()\r\n # end onUnFocus()\r\n\r\n# end ZWhereFoundBlogPostListView\r\n","sub_path":"src/python/zoundry/blogapp/ui/common/blogpostswidgets.py","file_name":"blogpostswidgets.py","file_ext":"py","file_size_in_byte":16888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"366769858","text":"import asyncio\nfrom typing import AnyStr, List, Type\n\nimport h11\nimport pytest\nfrom wsproto import ConnectionType, WSConnection\nfrom wsproto.events import AcceptConnection, CloseConnection, Message, Request\n\nfrom hypercorn.asyncio.wsproto import WebsocketServer\nfrom hypercorn.config import Config\nfrom hypercorn.typing import ASGIFramework\nfrom .helpers import MockTransport\nfrom ..helpers import BadFramework, EchoFramework\n\n\nclass MockHTTPConnection:\n def __init__(\n self,\n path: str,\n event_loop: asyncio.AbstractEventLoop,\n *,\n framework: Type[ASGIFramework] = EchoFramework,\n ) -> None:\n self.transport = MockTransport()\n self.client = h11.Connection(h11.CLIENT)\n self.server = WebsocketServer( # type: ignore\n framework, event_loop, Config(), self.transport\n )\n self.server.data_received(\n self.client.send(\n h11.Request(\n method=\"GET\",\n target=path,\n headers=[\n (\"Host\", \"Hypercorn\"),\n (\"Upgrade\", \"WebSocket\"),\n (\"Connection\", \"Upgrade\"),\n (\"Sec-WebSocket-Version\", \"13\"),\n (\"Sec-WebSocket-Key\", \"121312\"),\n ],\n )\n )\n )\n\n def get_events(self) -> list:\n events = []\n self.client.receive_data(self.transport.data)\n while True:\n event = self.client.next_event()\n if event in (h11.NEED_DATA, h11.PAUSED):\n break\n events.append(event)\n if isinstance(event, h11.ConnectionClosed):\n break\n return events\n\n\nclass MockWebsocketConnection:\n def __init__(\n self,\n path: str,\n event_loop: asyncio.AbstractEventLoop,\n *,\n framework: Type[ASGIFramework] = EchoFramework,\n ) -> None:\n self.transport = MockTransport()\n self.server = WebsocketServer( # type: ignore\n framework, event_loop, Config(), self.transport\n )\n self.connection = WSConnection(ConnectionType.CLIENT)\n self.server.data_received(self.connection.send(Request(target=path, host=\"hypercorn\")))\n\n async def send(self, data: AnyStr) -> None:\n self.server.data_received(self.connection.send(Message(data=data)))\n await asyncio.sleep(0) # Allow the server to respond\n\n async def receive(self) -> List[Message]:\n await self.transport.updated.wait()\n self.connection.receive_data(self.transport.data)\n self.transport.clear()\n return [event for event in self.connection.events()]\n\n def close(self) -> None:\n self.server.data_received(self.connection.send(CloseConnection(code=1000)))\n\n\n@pytest.mark.asyncio\nasync def test_websocket_server(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockWebsocketConnection(\"/ws\", event_loop)\n events = await connection.receive()\n assert isinstance(events[0], AcceptConnection)\n await connection.send(\"data\")\n events = await connection.receive()\n assert events[0].data == \"data\"\n connection.close()\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"path\", [\"/\", \"/no_response\", \"/call\"])\nasync def test_bad_framework_http(path: str, event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockHTTPConnection(path, event_loop, framework=BadFramework)\n await asyncio.sleep(0) # Yield to allow the server to process\n await connection.transport.closed.wait()\n response, *_ = connection.get_events()\n assert isinstance(response, h11.Response)\n assert response.status_code == 500\n\n\n@pytest.mark.asyncio\nasync def test_bad_framework_websocket(event_loop: asyncio.AbstractEventLoop) -> None:\n connection = MockWebsocketConnection(\"/accept\", event_loop, framework=BadFramework)\n await asyncio.sleep(0) # Yield to allow the server to process\n *_, close = await connection.receive()\n assert isinstance(close, CloseConnection)\n assert close.code == 1000\n","sub_path":"tests/asyncio/test_wsproto.py","file_name":"test_wsproto.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"142086600","text":"import os\nimport sys\n\ndef toString(a):\n return ''.join(a)\n\ndef permute (a, l, r):\n if l == r:\n print (toString(a))\n else:\n for i in range(l, r+1):\n a[l],a[i] = a[i], a[l]\n permute(a, l+1, r)\n a[l], a[i] = a[i],a[l]\n \nstring = \"ABC\"\nn = len(string)\na = list(string)\npermute(a, 0, n-1)\n","sub_path":"string_perm.py","file_name":"string_perm.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491934341","text":"import sys\nfrom trainAndClassify import *\nimport tensorflow as tf\nsess = tf.Session()\ng = network()\nsess.run(tf.global_variables_initializer())\ng['saver'].restore(sess,\"./MachineLearning/TauNetSave\")\n\ndef classify(input_string):\n\tx = classifySample(sess,g,\"./DataFiles/DataOut/\",int(input_string)>>24)\n\t#print(x)\n\treturn x\n\ndef close():\n\tsess.close()\n\texit(0)\n","sub_path":"MachineLearning/classifySingleSample.py","file_name":"classifySingleSample.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229729970","text":"#coding:utf-8\n\n#opencv的python库\nimport cv2 as cv\nimport numpy as np\n\n\n#读取照片\nimg = cv.imread('D:/python/opencv/cfly.jpg')\n\n#创建一个窗口\ncv.namedWindow('blue')\ncv.namedWindow('red')\ncv.namedWindow('green')\n\n#分离不同通道\nb,g,r=cv.split(img)\n\n#在窗口中显示图像\ncv.imshow('blue',b)\ncv.imshow('green',g)\ncv.imshow('red',r)\n\n\n#用于使图像停留\ncv.waitKey(0)\n\n#释放窗口\ncv.destroyAllWindows()","sub_path":"element_deal/channel_split.py","file_name":"channel_split.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"340411076","text":"#!/usr/bin/python\n# ex:set fileencoding=utf-8:\n\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom djangobmf.categories import BaseCategory\nfrom djangobmf.categories import ViewFactory\nfrom djangobmf.categories import Accounting\nfrom djangobmf.sites import site\n\nfrom .models import Invoice\nfrom .models import InvoiceProduct\nfrom .serializers import InvoiceSerializer\nfrom .views import InvoiceCreateView\nfrom .views import InvoiceUpdateView\n\n\nsite.register_module(Invoice, **{\n 'create': InvoiceCreateView,\n 'update': InvoiceUpdateView,\n 'serializer': InvoiceSerializer,\n 'report': True,\n})\n\n\nsite.register_module(InvoiceProduct, **{\n})\n\n\nclass InvoiceCategory(BaseCategory):\n name = _('Invoices')\n slug = \"invoices\"\n\n\nsite.register_dashboards(\n Accounting(\n InvoiceCategory(\n ViewFactory(\n model=Invoice,\n name=_(\"Open invoices\"),\n slug=\"open\",\n manager=\"open\",\n ),\n ViewFactory(\n model=Invoice,\n name=_(\"All invoices\"),\n slug=\"all\",\n date_resolution=\"month\",\n ),\n ),\n ),\n)\n","sub_path":"djangobmf/contrib/invoice/bmf_module.py","file_name":"bmf_module.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455641133","text":"import numpy as np\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport pickle\r\n\r\n# When copy-n-paste, think \"function\"\r\ndef loadData(filepath, lowerbound, upperbound):\r\n\r\n with open(filepath, 'rb') as file:\r\n data = pickle.load(file)\r\n positions = data['positions']\r\n times = data['time']\r\n\r\n new_positions = np.nan * np.ones((len(positions), 50, 2))\r\n for i, c in enumerate(positions):\r\n for j, cc in enumerate(c):\r\n if cc[1] < lowerbound or cc[1] > upperbound:\r\n new_positions[i, j, :] = [np.nan, np.nan]\r\n else:\r\n new_positions[i, j, :] = cc\r\n\r\n return times, new_positions\r\n\r\n#Data conversion Recording A\r\nprepend = 'E:/rec/2,5/1,5'\r\nlowerbound, upperbound = 0, 2.8\r\na50times, a50pos = loadData('{}1_before_pressure_increase_2,5cm_0,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\na100times, a100pos = loadData('{}2_pressure_increase_2,5cm_0,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\na150times, a150pos = loadData('{}3_after_pressure_increase_2,5cm_0,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\na200times, a200pos = loadData('{}4_pressure_decrease_2,5cm_0,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\na250times, a250pos = loadData('{}5_after_pressure_decrease_2,5cm_0,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\n\r\n#Data conversion Recording B\r\nb50times, b50pos = loadData('{}1_before_pressure_increase_2,5cm_1x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\nb100times, b100pos = loadData('{}2_pressure_increase_2,5cm_1x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\nb150times, b150pos = loadData('{}3_after_pressure_increase_2,5cm_1x_light.pickle'.format(prepend), lowerbound, upperbound)\r\nb200times, b200pos = loadData('{}4_pressure_decrease_2,5cm_1x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\nb250times, b250pos = loadData('{}5_after_pressure_decrease_2,5cm_1x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\n\r\n#Data conversion Recording C\r\nc50times, c50pos = loadData('{}1_before_pressure_increase_2,5cm_1,5x_light.pickle'.format(prepend), lowerbound, upperbound)\r\nc100times, c100pos = loadData('{}2_pressure_increase_2,5cm_1,5x_light.pickle'.format(prepend), lowerbound, upperbound)\r\nc150times, c150pos = loadData('{}3_after_pressure_increase_2,5cm_1,5x_light.pickle'.format(prepend), lowerbound, upperbound)\r\nc200times, c200pos = loadData('{}4_pressure_decrease_2,5cm_1,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\nc250times, c250pos = loadData('{}5_after_pressure_decrease_2,5cm_1,5x_Light.pickle'.format(prepend), lowerbound, upperbound)\r\n\r\n#Deleting nan-values, calculating mean\r\n\r\ndef normParams(values):\r\n return np.nanmedian(values), np.nanstd(values) # nanmean/nanstd ignore NaNs by default\r\n\r\n\r\na50_mean, a50_std = normParams(a50pos[5:3000, :9, 1])\r\na100_mean, a100_std = normParams(a100pos[5:3000, :9, 1])\r\na150_mean, a150_std = normParams(a150pos[5:3000, :9, 1])\r\na200_mean, a200_std = normParams(a200pos[5:3000, :9, 1])\r\na250_mean, a250_std = normParams(a250pos[5:3000, :9, 1])\r\n\r\nb50_mean, b50_std = normParams(b50pos[5:3000, :9, 1])\r\nb100_mean, b100_std = normParams(b100pos[5:3000, :9, 1])\r\nb150_mean, b150_std = normParams(b150pos[5:3000, :9, 1])\r\nb200_mean, b200_std = normParams(b200pos[5:3000, :9, 1])\r\nb250_mean, b250_std = normParams(b250pos[5:3000, :9, 1])\r\n\r\nc50_mean, c50_std = normParams(c50pos[5:3000, :9, 1])\r\nc100_mean, c100_std = normParams(c100pos[5:3000, :9, 1])\r\nc150_mean, c150_std = normParams(c150pos[5:3000, :9, 1])\r\nc200_mean, c200_std = normParams(c200pos[5:3000, :9, 1])\r\nc250_mean, c250_std = normParams(c250pos[5:3000, :9, 1])\r\n\r\n#Chart values\r\n\r\nRecordings = ['before PI', 'during PI', 'after PI', 'during PD', 'after PD']\r\ncount = np.arange(len(Recordings))\r\n\r\n#sorting means\r\n\r\nmeans = [a50_mean, a100_mean, a150_mean, a200_mean, a250_mean, b50_mean, b100_mean, b150_mean, b200_mean, b250_mean, c50_mean, c100_mean, c150_mean, c200_mean, c250_mean]\r\nmeans50 = means[::5]\r\nmeans100 = means[1::5]\r\nmeans150 = means[2::5]\r\nmeans200 = means[3::5]\r\nmeans300 = means[4::5]\r\n\r\n#sorting errors\r\n\r\nstd = [a50_std, a100_std, a150_std, a200_std, a250_std, b50_std, b100_std, b150_std, b200_std, b250_std, c50_std, c100_std, c150_std, c200_std, c250_std]\r\nerror50 = std[::5]\r\nerror100 = std[1::5]\r\nerror150 = std[2::5]\r\nerror200 = std[3::5]\r\nerror250 = std[4::5]\r\nwidth = 0.66\r\n\r\nfig, ax = plt.subplots()\r\n\r\nrects1 = ax.bar(count - width/5, means50, width/3, yerr=error50, align='center', alpha=0.8, ecolor='blue', capsize=4, label='before PI')\r\nrects2 = ax.bar(count - width/5, means100, width/3, yerr=error100, align='center', alpha=0.8, ecolor='red', capsize=4, label='during PI')\r\nrects3 = ax.bar(count, means150, width/3, yerr=error150, align='center', alpha=0.8, ecolor='green', capsize=4, label='after PI')\r\nrects4 = ax.bar(count + width/5, means200, width/3, yerr=error200, align='center', alpha=0.8, ecolor='orange', capsize=4, label='before PD')\r\nrects5 = ax.bar(count + width/5, means250, width/3, yerr=error250, align='center', alpha=0.8, ecolor='purple', capsize=4, label='after PD')\r\n\r\nax.set_xticks(count)\r\nax.set_xticklabels(Recordings)\r\nax.yaxis.grid(True)\r\nax.set_ylabel('Distance from Water surface')\r\nax.set_xlabel('Waterlevel')\r\nax.set_title('Swimmingheight in dependency of Waterlevel and Groundtexture scaling')\r\nax.legend()\r\n\r\ndef autolabel(rects):\r\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\r\n for rect in rects:\r\n height = rect.get_height()\r\n ax.annotate('{:.2f}'.format(height),\r\n xy=(rect.get_x() + rect.get_width() / 2, height),\r\n xytext=(0, 10), # 3 points vertical offset\r\n textcoords=\"offset points\",\r\n ha='center', va='bottom')\r\nautolabel(rects1)\r\nautolabel(rects2)\r\nautolabel(rects3)\r\nautolabel(rects4)\r\nautolabel(rects5)\r\n\r\nplt.tight_layout()\r\nplt.show()","sub_path":"gbc_pressurechange_2,5_scals.py","file_name":"gbc_pressurechange_2,5_scals.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651503612","text":"\"\"\"\nQuadrature, i.e. numerical integration.\n\nThis module collects both classic and Bayesian quadrature rules used for numerical\nintegration of functions.\n\nBayesian quadrature methods integrate a function by iteratively building a probabilistic\nmodel and using its predictions to adaptively choose points to evaluate the integrand.\n\"\"\"\n\nfrom probnum.quad.bayesian import *\nfrom probnum.quad.polynomial import *\nfrom probnum.quad.quadrature import *\n\n# Public classes and functions. Order is reflected in documentation.\n__all__ = [\n \"quad\",\n \"nquad\",\n \"bayesquad\",\n \"nbayesquad\",\n \"Quadrature\",\n \"PolynomialQuadrature\",\n \"BayesianQuadrature\",\n \"VanillaBayesianQuadrature\",\n \"WSABIBayesianQuadrature\",\n \"ClenshawCurtis\",\n]\n\n# Set correct module paths. Corrects links and module paths in documentation.\nQuadrature.__module__ = \"probnum.quad\"\nBayesianQuadrature.__module__ = \"probnum.quad\"\nPolynomialQuadrature.__module__ = \"probnum.quad\"\n","sub_path":"src/probnum/quad/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"105545752","text":"from flask import Flask\nfrom flask_restful import Api\nfrom python_helper import Constant as c\nfrom python_helper import log, Function, ReflectionHelper, SettingHelper, ObjectHelper, StringHelper\nimport globals\nfrom python_framework.api.src.helper import Serializer\nfrom python_framework.api.src.service.flask import FlaskManager\nfrom python_framework.api.src.service import SqlAlchemyProxy\nfrom python_framework.api.src.service import Security\nfrom python_framework.api.src.service import SchedulerManager\nfrom python_framework.api.src.service.openapi import OpenApiManager\n\nDOT_PY = '.py'\n\ndef getPythonFrameworkResourceByType(resourceType) :\n return FlaskManager.PYTHON_FRAMEWORK_RESOURCE_NAME_DICTIONARY.get(resourceType, [])\n\ndef isNotPythonFrameworkApiInstance(apiInstance) :\n return apiInstance.globals.apiName not in FlaskManager.PYTHON_FRAMEWORK_INTERNAL_MODULE_NAME_LIST\n\ndef isFromPythonFramework(apiInstance, resourceType, resourceName) :\n return not (resourceName in getPythonFrameworkResourceByType(resourceType) and isNotPythonFrameworkApiInstance(apiInstance))\n\ndef getResourceModuleNameAjusted(apiInstance, resourceType, resourceName) :\n return resourceName if isFromPythonFramework(apiInstance, resourceType, resourceName) else FlaskManager.PYTHON_FRAMEWORK_MODULE_NAME\n\ndef getResourceNameAjusted(apiInstance, resourceType, resourceName) :\n return resourceName if isFromPythonFramework(apiInstance, resourceType, resourceName) else f'{resourceName}{c.DOT}{resourceName}'\n\ndef isControllerResourceName(resourceName) :\n return FlaskManager.KW_CONTROLLER_RESOURCE == resourceName[-len(FlaskManager.KW_CONTROLLER_RESOURCE):]\n\n@Function\ndef getResourceName(resourceFileName) :\n return resourceFileName.split(DOT_PY)[0]\n\n@Function\ndef isResourceType(resourceFileName,resourceType) :\n splitedResourceFileName = resourceFileName.split(resourceType)\n return len(splitedResourceFileName)>1 and splitedResourceFileName[1] == DOT_PY\n\n@Function\ndef getResourceNameList(apiTree, resourceType) :\n resourceNameList = []\n if apiTree or type(apiTree).__name__ == c.DICT :\n for package,subPackageTree in apiTree.items() :\n if isResourceType(package, resourceType) :\n resourceNameList.append(getResourceName(package))\n resourceNameList += getResourceNameList(\n subPackageTree,\n resourceType\n )\n return resourceNameList\n\n@Function\ndef getControllerNameList(controllerName) :\n controllerNameList = [controllerName]\n controllerNameList.append(f'{controllerName[:-len(FlaskManager.KW_CONTROLLER_RESOURCE)]}{Serializer.KW_BATCH}{FlaskManager.KW_CONTROLLER_RESOURCE}')\n # controllerNameList = [name for name in dir(__import__(controllerName)) if not name.startswith(c.UNDERSCORE)]\n # return ReflectionHelper.getAttributeOrMethodNameList(__import__(controllerName))\n return controllerNameList\n\n@Function\ndef getControllerList(resourceName, resourceModuleName) :\n controllerNameList = getControllerNameList(resourceName)\n importedControllerList = []\n for controllerName in controllerNameList :\n resource = globals.importResource(controllerName, resourceModuleName=resourceModuleName)\n if resource :\n importedControllerList.append(resource)\n if 0 == len(importedControllerList) :\n raise Exception(f'Not possible to import {resourceName} controller')\n return importedControllerList\n\n@Function\ndef getResourceList(apiInstance, resourceType) :\n resourceNameList = getResourceNameList(\n apiInstance.globals.apiTree[apiInstance.globals.apiPackage],\n resourceType\n )\n if isNotPythonFrameworkApiInstance(apiInstance) :\n resourceNameList += getPythonFrameworkResourceByType(resourceType)\n resourceList = []\n for resourceName in resourceNameList :\n resource = None\n ajustedResourceName = getResourceNameAjusted(apiInstance, resourceType, resourceName)\n ajustedResourceModuleName = getResourceModuleNameAjusted(apiInstance, resourceType, resourceName)\n if isControllerResourceName(resourceName) :\n resource = getControllerList(ajustedResourceName, ajustedResourceModuleName)\n else :\n resource = globals.importResource(ajustedResourceName, resourceModuleName=ajustedResourceModuleName)\n if ObjectHelper.isEmpty(resource) :\n raise Exception(f'Error while importing {ajustedResourceName} resource from {ajustedResourceModuleName} module. Resource not found.')\n elif ObjectHelper.isList(resource) :\n resourceList += resource\n else :\n resourceList.append(resource)\n return resourceList\n\n@Function\ndef addGlobalsTo(apiInstance) :\n FlaskManager.validateFlaskApi(apiInstance)\n apiInstance.globals = FlaskManager.getGlobals()\n apiInstance.globals.api = apiInstance\n apiInstance.bindResource = FlaskManager.bindResource\n\n@Function\ndef initialize(\n rootName,\n refferenceModel,\n) :\n\n app = Flask(rootName)\n api = Api(app)\n addGlobalsTo(api)\n SchedulerManager.addScheduler(api, app)\n securityKey = api.globals.getApiSetting('api.security.secret')\n if SettingHelper.LOCAL_ENVIRONMENT == SettingHelper.getActiveEnvironment() :\n log.setting(initialize, f'JWT secret: {securityKey}')\n jwt = Security.getJwtMannager(app, securityKey)\n\n args = [api, app, jwt]\n for resourceType in FlaskManager.KW_RESOURCE_LIST :\n args.append(getResourceList(api, resourceType))\n args.append(refferenceModel)\n addFlaskApiResources(*args)\n api.app = app\n return api, app, jwt\n\n@Function\ndef addControllerListTo(apiInstance, controllerList) :\n for controller in controllerList :\n OpenApiManager.addControllerDocumentation(controller, apiInstance)\n mainUrl = f'{apiInstance.baseUrl}{controller.url}'\n urlList = [mainUrl]\n infoList = [f'Controller: {mainUrl}']\n controllerMethodList = ReflectionHelper.getAttributePointerList(controller)\n for controllerMethod in controllerMethodList :\n if ReflectionHelper.hasAttributeOrMethod(controllerMethod, FlaskManager.KW_URL) and ObjectHelper.isNotEmpty(controllerMethod.url) :\n controllerUrl = f'{mainUrl}{controllerMethod.url}'\n if controllerUrl not in urlList :\n urlList.append(controllerUrl)\n infoList.append(f'{c.TAB}{ReflectionHelper.getName(controllerMethod)}: {controllerUrl}')\n # subUrlList = controllerMethod.url.split(c.SLASH)\n # concatenatedSubUrl = c.NOTHING\n # for subUrl in subUrlList :\n # if subUrl :\n # concatenatedSubUrl += f'{c.SLASH}{subUrl}'\n # if c.LESSER == subUrl[0] and c.BIGGER == subUrl[-1] :\n # newUrl = f'{apiInstance.baseUrl}{controller.url}{concatenatedSubUrl}'\n # if not newUrl in urlList :\n # urlList.append(newUrl)\n OpenApiManager.addEndPointDocumentation(controllerUrl, controllerMethod, controller, apiInstance)\n log.debug(addControllerListTo, f'{controller.url} -> {StringHelper.prettyPython(infoList)}')\n apiInstance.add_resource(controller, *urlList)\n\n@Function\ndef addServiceListTo(apiInstance,serviceList) :\n for service in serviceList :\n apiInstance.bindResource(apiInstance,service())\n\n@Function\ndef addSchedulerListTo(apiInstance,schedulerList) :\n for scheduler in schedulerList :\n apiInstance.bindResource(apiInstance,scheduler())\n\n@Function\ndef addClientListTo(apiInstance,clientList) :\n for client in clientList :\n apiInstance.bindResource(apiInstance,client())\n\n@Function\ndef addRepositoryTo(apiInstance, repositoryList, model) :\n apiInstance.repository = SqlAlchemyProxy.SqlAlchemyProxy(\n model,\n apiInstance.globals,\n echo = False\n )\n for repository in repositoryList :\n apiInstance.bindResource(apiInstance,repository())\n\n@Function\ndef addValidatorListTo(apiInstance,validatorList) :\n for validator in validatorList :\n apiInstance.bindResource(apiInstance,validator())\n\ndef addMapperListTo(apiInstance,mapperList) :\n for mapper in mapperList :\n apiInstance.bindResource(apiInstance,mapper())\n\n@Function\ndef addHelperListTo(apiInstance,helperList) :\n for helper in helperList :\n apiInstance.bindResource(apiInstance,helper())\n\n@Function\ndef addConverterListTo(apiInstance,converterList) :\n for converter in converterList :\n apiInstance.bindResource(apiInstance,converter())\n\nclass FlaskResource:\n ...\n\n@Function\ndef addResourceAttibutes(apiInstance) :\n ReflectionHelper.setAttributeOrMethod(apiInstance, FlaskManager.KW_RESOURCE, FlaskResource())\n for resourceName in FlaskManager.KW_RESOURCE_LIST :\n ReflectionHelper.setAttributeOrMethod(apiInstance.resource, f'{resourceName[0].lower()}{resourceName[1:]}', FlaskResource())\n\n@Function\ndef addFlaskApiResources(\n apiInstance,\n appInstance,\n jwtInstance,\n controllerList,\n schedulerList,\n serviceList,\n clientList,\n repositoryList,\n validatorList,\n mapperList,\n helperList,\n converterList,\n model\n ) :\n apiInstance.scheme = apiInstance.globals.getApiSetting('api.server.scheme')\n apiInstance.host = apiInstance.globals.getApiSetting('api.server.host')\n apiInstance.port = apiInstance.globals.getApiSetting('api.server.port')\n apiInstance.baseUrl = apiInstance.globals.getApiSetting('api.server.base-url')\n OpenApiManager.newDocumentation(apiInstance, appInstance)\n addResourceAttibutes(apiInstance)\n addRepositoryTo(apiInstance, repositoryList, model)\n addSchedulerListTo(apiInstance, schedulerList)\n addClientListTo(apiInstance, clientList)\n addServiceListTo(apiInstance, serviceList)\n addControllerListTo(apiInstance, controllerList)\n addValidatorListTo(apiInstance, validatorList)\n addMapperListTo(apiInstance, mapperList)\n addHelperListTo(apiInstance, helperList)\n addConverterListTo(apiInstance, converterList)\n SchedulerManager.initialize(apiInstance, appInstance)\n Security.addJwt(jwtInstance)\n OpenApiManager.addSwagger(apiInstance, appInstance)\n","sub_path":"python_framework/api/src/service/flask/ResourceManager.py","file_name":"ResourceManager.py","file_ext":"py","file_size_in_byte":10357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"168822547","text":"'''\n PyCrypto\n'''\n\nfrom Crypto.PublicKey.RSA import _RSAobj\n# PYTHON_CRYPTO_BAD_PADDING 03a2e1\ntextbookRSA = _RSAobj()\n\n'''\n cryptography\n'''\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\n\n# PYTHON_CRYPTO_BAD_PADDING bab4de\nciphertext = public_key.encrypt(\n message,\n padding.PKCS1v15(\n mgf=padding.MGF1(algorithm=hashes.SHA1()),\n algorithm=hashes.SHA1(),\n label=None\n )\n)","sub_path":"PYTHON_CRYPTO_BAD_PADDING.py","file_name":"PYTHON_CRYPTO_BAD_PADDING.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"500712614","text":"from flask import render_template, url_for, flash, request, redirect, Blueprint, abort\nfrom flask_login import current_user, login_required\nfrom PyAny_MainApp import db\nfrom PyAny_MainApp.models import BlogPost\nfrom PyAny_MainApp.posts.forms import BlogPostForm\nfrom datetime import datetime\n\nblog_posts = Blueprint('blog_posts',__name__)\n\n# Create Blog Post\n@blog_posts.route('/create_post',methods=['GET','POST'])\n@login_required\ndef create_post():\n form = BlogPostForm()\n username = current_user.username\n if form.validate_on_submit():\n blog_post = BlogPost( title = form.title.data,\n text=form.text.data,\n user_id=current_user.id,\n timestamp=datetime.now(),\n )\n db.session.add(blog_post)\n db.session.commit()\n flash('Blog post created!')\n return redirect(url_for('core.index'))\n\n return render_template('create_post.html',form=form,username=username)\n\n# View(Read) Blog Post\n@blog_posts.route('/')\ndef blog_post(blog_post_id):\n blog_post = BlogPost.query.get_or_404(blog_post_id)\n return render_template('blog_post.html',\n title=blog_post.title,\n timestamp=blog_post.timestamp,\n post=blog_post\n )\n\n# Update Blog Post\n@blog_posts.route('//update_post',methods=['GET','POST'])\n@login_required\ndef update_post(blog_post_id):\n blog_post = BlogPost.query.get_or_404(blog_post_id)\n\n if blog_post.author != current_user:\n abort(403)\n\n form = BlogPostForm()\n\n if form.validate_on_submit():\n blog_post.title = form.title.data\n blog_post.text = form.text.data\n db.session.commit()\n flash('Blog post updated!')\n return redirect(url_for('blog_posts.blog_post',blog_post_id=blog_post.id))\n\n elif request.method == 'GET':\n form.title.data = blog_post.title\n form.text.data = blog_post.text\n\n return render_template('create_post.html',\n form=form,\n title='Updating'\n )\n\n# Delete Blog Post\n@blog_posts.route('//delete_post',methods=['POST'])\n@login_required\ndef delete_post(blog_post_id):\n blog_post = BlogPost.query.get_or_404(blog_post_id)\n\n if blog_post.author != current_user:\n abort(403)\n \n db.session.delete(blog_post)\n db.session.commit()\n flash('Blog post deleted!')\n return redirect(url_for('core.index'))","sub_path":"PyAny_MainApp/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216327718","text":"bolos = ['Asrul', 'Asrul', 'Anis', 'Asrul']\n\n# get unique data\nprint(set(bolos))\n\na = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\nb = set(a)\nb.add(5)\n# b.pop()\nprint(b)\n","sub_path":"structur_data/sets/sets.py","file_name":"sets.py","file_ext":"py","file_size_in_byte":156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178981725","text":"import os.path\n\nfrom django.db import models\nfrom django.conf import settings\n\nfrom sorl.thumbnail.fields import ImageWithThumbnailsField\nfrom sorl.thumbnail.tests.base import BaseTest, RELATIVE_PIC_NAME\n\nthumbnail = {\n 'size': (50,50)\n}\nextra_thumbnails = {\n 'admin': {\n 'size': (30, 30),\n 'options': ('crop',),\n }\n}\n\n# Temporary model for field_tests\nclass TestThumbnailFieldModel(models.Model):\n photo = ImageWithThumbnailsField(upload_to='test', thumbnail=thumbnail,\n extra_thumbnails=extra_thumbnails)\n\nclass FieldTest(BaseTest):\n def test_thumbnail(self):\n model = TestThumbnailFieldModel(photo=RELATIVE_PIC_NAME)\n thumb = model.photo.thumbnail\n tag = model.photo.thumbnail_tag\n expected_filename = os.path.join(settings.MEDIA_ROOT,\n 'sorl-thumbnail-test_source_jpg_50x50_q85.jpg')\n self.verify_thumbnail((50, 37), thumb, expected_filename)\n expected_tag = '\"\"' % \\\n '/'.join((settings.MEDIA_URL.rstrip('/'),\n 'sorl-thumbnail-test_source_jpg_50x50_q85.jpg'))\n self.assertEqual(tag, expected_tag)\n\n def test_extra_thumbnails(self):\n model = TestThumbnailFieldModel(photo=RELATIVE_PIC_NAME)\n self.assertTrue('admin' in model.photo.extra_thumbnails)\n thumb = model.photo.extra_thumbnails['admin']\n tag = model.photo.extra_thumbnails_tag['admin']\n expected_filename = os.path.join(settings.MEDIA_ROOT,\n 'sorl-thumbnail-test_source_jpg_30x30_crop_q85.jpg')\n self.verify_thumbnail((30, 30), thumb, expected_filename)\n expected_tag = '\"\"' % \\\n '/'.join((settings.MEDIA_URL.rstrip('/'),\n 'sorl-thumbnail-test_source_jpg_30x30_crop_q85.jpg'))\n self.assertEqual(tag, expected_tag)\n","sub_path":"coopdirectory/sorl/thumbnail/tests/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64257461","text":"import os\nimport pandas as pd\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import sessionmaker\n\nfrom operator import attrgetter\n\n\nclass DBFacade:\n\n def __init__(self):\n self.engine, self.metadata, self.session, self.Base = self.create_connection()\n\n def create_connection(self):\n \"\"\"\n Function that initialize connection to the database\n :return: sqlalchemy objects\n \"\"\"\n db_path = os.path.join(os.getcwd(), \"project.db\")\n db_path = 'sqlite:///' + db_path\n engine = create_engine(db_path)\n\n metadata = MetaData()\n metadata.reflect(engine)\n\n Base = automap_base(metadata=metadata)\n Base.prepare()\n\n DB_session = sessionmaker(bind=engine)\n session = DB_session()\n\n return engine, metadata, session, Base\n\n # def facade_manager(self):\n #\n # engine, metadata, session, Base = create_engine()\n\n def get_tables(self):\n \"\"\"\n Function that get tables name from database\n :return:\n \"\"\"\n tables = list(self.metadata.tables.keys())\n return tables\n\n def get_columns(self, table_name):\n table = attrgetter(table_name)\n table = table(self.Base.classes)\n\n results = self.session.query(table).first()\n\n columns = list(results.__dict__.keys())[1:]\n\n return columns\n\n def get_headers(self, result):\n \"\"\"\n Function that get headers from row in database query result\n :param result:\n :return:\n \"\"\"\n return list(result.__dict__.keys())[1:]\n\n def building_results_array(self, headers, results):\n \"\"\"\n Function prasing a bd query results inot a 2D array\n :param headers:\n :param results:\n :return:\n \"\"\"\n results_array = [headers]\n for result in results:\n result_array = []\n for header in headers:\n header = attrgetter(header)\n result_array.append(header(result))\n results_array.append(result_array)\n\n results_array = pd.DataFrame(results_array)\n return results_array\n\n def prinitng_select_all(self, results):\n \"\"\"\n Function that prints the results of a query\n :param results:\n :return:\n \"\"\"\n print('\\n')\n print(results.to_string(index=False, header=False))\n print('\\n')\n\n def select_all(self, table_name):\n \"\"\"\n Function that supports a 'select * from table_name' query\n :param table_name:\n :return:\n \"\"\"\n table = attrgetter(table_name)\n table = table(self.Base.classes)\n\n results = self.session.query(table).all()\n\n # print('results: ', results)\n\n headers = self.get_headers(results[0])\n results_array = self.building_results_array(headers, results)\n self.prinitng_select_all(results_array)\n\n def select_by_criterion(self, table_name, criterion, answer):\n \"\"\"\n Function that supports a select by criterion query\n :param table_name:\n :param criterion:\n :param answer:\n :return:\n \"\"\"\n print('table_name: ', table_name, ' criterion: ', criterion, ' = ', answer)\n\n table = attrgetter(table_name)\n table = table(self.Base.classes)\n\n atribute = attrgetter(criterion)\n critertion = atribute(table)\n\n results = self.session.query(table).filter(critertion == answer)\n\n try:\n headers = self.get_headers(results[0])\n results_array = self.building_results_array(headers, results)\n self.prinitng_select_all(results_array)\n except:\n print('Nie znaleziono wyników.')\n\n def raw_results_printing(self, results):\n results_array = pd.DataFrame(results)\n print(results_array.to_string(index=False, header=False), '\\n')\n\n def select_by_user_query(self, query):\n results = self.engine.execute(query)\n headers = tuple(results.keys())\n results = results.fetchall()\n\n results.insert(0, headers)\n\n self.raw_results_printing(results)\n","sub_path":"Facade/db_facade.py","file_name":"db_facade.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"244266913","text":"\n\n\ndef get_file_lines(filename='/usr/share/dict/words'):\n \"\"\"Return a list of strings on separate lines in the given text file with\n any leading and trailing whitespace characters removed from each line.\"\"\"\n # Open file and remove whitespace from each line\n with open(filename) as file:\n lines = [line.strip() for line in file]\n return lines\n\n# https://stackoverflow.com/questions/11989502/producing-all-the-anagrams-from-a-string-python\ndef get_perms(elements):\n if len(elements) <=1:\n return elements\n else:\n tmp = []\n for perm in get_perms(elements[1:]):\n for i in range(len(elements)):\n tmp.append(perm[:i] + elements[0:1] + perm[i:])\n return tmp\n\ndef binary_search_recursive(array, item, left=None, right=None):\n\n # start index of the array\n if left == None:\n left = 0\n # starting end index of the array\n if right == None:\n right = int(len(array) - 1)\n\n midpoint = int((left + right) / 2)\n\n if left > right:\n return None\n\n if array[midpoint] == item:\n return midpoint\n\n if item > array[midpoint]:\n left = midpoint + 1\n return binary_search_recursive(array, item, left, right)\n\n if item < array[midpoint]:\n left = 0\n right = midpoint - 1\n return binary_search_recursive(array, item, left, right)\n\ndictionary = get_file_lines()\nperms = list()\nscram_words = ['tefon', 'sokik', 'niumem', 'siconu']\n\ndef find_word_jumbles():\n jumbles = list()\n # perms = get_perms(word)\n for word in scram_words:\n perms.append(get_perms(word))\n\n # for all permutations check to see if in dictionary using binary search\n for array in perms:\n for words in array:\n print(words)\n if binary_search_recursive(dictionary, words) is not None:\n jumbles.append(dictionary[binary_search_recursive(dictionary, words)])\n return jumbles\n\nprint(find_word_jumbles())\n","sub_path":"Lessons/source/word_jumble.py","file_name":"word_jumble.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407435843","text":"#\n# @lc app=leetcode.cn id=70 lang=python3\n#\n# [70] 爬楼梯\n#\n# https://leetcode-cn.com/problems/climbing-stairs/description/\n#\n# algorithms\n# Easy (50.43%)\n# Likes: 1213\n# Dislikes: 0\n# Total Accepted: 276.5K\n# Total Submissions: 547.7K\n# Testcase Example: '2'\n#\n# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。\n# \n# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?\n# \n# 注意:给定 n 是一个正整数。\n# \n# 示例 1:\n# \n# 输入: 2\n# 输出: 2\n# 解释: 有两种方法可以爬到楼顶。\n# 1. 1 阶 + 1 阶\n# 2. 2 阶\n# \n# 示例 2:\n# \n# 输入: 3\n# 输出: 3\n# 解释: 有三种方法可以爬到楼顶。\n# 1. 1 阶 + 1 阶 + 1 阶\n# 2. 1 阶 + 2 阶\n# 3. 2 阶 + 1 阶\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def climbStairs(self, n: int) -> int:\n pre = 1\n curr = 1\n while n>1:\n t = pre\n pre = curr\n curr += t\n n-=1\n return curr\n# @lc code=end\n\n","sub_path":"70.爬楼梯.py","file_name":"70.爬楼梯.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"94313680","text":"from tkinter import *\nimport tkinter.font\nimport datetime\nimport threading\nfrom certification import new_window\nfrom route import assign_static_ip\n\n\nclass Settings(Frame):\n\n def __init__(self, master=None, main=None, data=None, board_close_callback=None, save_callback=None):\n Frame.__init__(self, master)\n self.pack(fill='both', expand=1)\n self.root = master\n self.main = main\n\n # Header Fame\n header = Frame(self, relief='flat', bd=2)\n header.pack(side='top', fill='both', padx=5, pady=5)\n\n main_button = Button(header, overrelief='solid', height=1, width=5, text='메인', command=self.main_callback)\n main_button.pack(side='left', anchor='w')\n setting_button = Button(header, overrelief='solid', height=1, width=5, text='설정')\n setting_button.pack(side='left', anchor='e')\n font = tkinter.font.Font(family='맑은 고딕', size=20)\n title_frame = Frame(header, relief='flat', bd=2)\n title_frame.pack(side='top', anchor='center', fill=None)\n title_label = Label(title_frame, text='AQS Client', font=font)\n title_label.pack(side='bottom', anchor='center')\n s = datetime.datetime.now()\n s = str(s).split('.')[0]\n\n inform_frame = Frame(header, relief='flat', bd=2)\n inform_frame.pack(side='right', fill='both', anchor='center')\n self.datetime_label = Label(inform_frame, text=s)\n self.datetime_label.pack(side='top', anchor='n')\n ver_label = Label(inform_frame, text='Ver: 1.1')\n ver_label.pack(side='bottom', anchor='se')\n\n # Setting Frame\n setting_frame = Frame(self, relief='solid', bd=2)\n setting_frame.pack(side='top', anchor='center', fill='both')\n\n # Server Setting Frame\n server_frame = Frame(setting_frame, relief='flat', bd=2)\n server_frame.pack(side='left', anchor='center', padx=5, pady=5)\n desc_label = Label(server_frame, text='서버 설정')\n desc_label.pack(side='top', anchor='center', padx=5, pady=5)\n\n # IP Frame\n ip_frame = Frame(server_frame, relief='flat', bd=2)\n ip_frame.pack(side='top', anchor='s')\n\n desc_label = Label(ip_frame, text='IP : ')\n desc_label.pack(side='left', anchor='w')\n\n self.ip_var = StringVar()\n\n ip_entry = Entry(ip_frame, width=12, textvariable=self.ip_var)\n ip_entry.pack(side='left', anchor='w', padx=5)\n\n desc_label = Label(ip_frame, text='PORT : ')\n desc_label.pack(side='left', anchor='w')\n\n self.server_port_var = StringVar()\n\n port_entry = Entry(ip_frame, width=5, textvariable=self.server_port_var)\n port_entry.pack(side='left', anchor='w')\n\n # Client ID Frame\n id_entry_frame = Frame(server_frame, relief='flat', bd=2)\n id_entry_frame.pack(side='top', anchor='s')\n\n desc_label = Label(id_entry_frame, text='클라이언트ID : ')\n desc_label.pack(side='left', anchor='w')\n\n self.first_var = StringVar()\n self.second_var = StringVar()\n self.third_var = StringVar()\n\n first_entry = Entry(id_entry_frame, width=3, textvariable=self.first_var)\n first_entry.pack(side='left', anchor='w')\n desc_label = Label(id_entry_frame, text='-')\n desc_label.pack(side='left', anchor='w')\n second_entry = Entry(id_entry_frame, width=4, textvariable=self.second_var)\n second_entry.pack(side='left', anchor='w')\n desc_label = Label(id_entry_frame, text='-')\n desc_label.pack(side='left', anchor='w')\n third_entry = Entry(id_entry_frame, width=4, textvariable=self.third_var)\n third_entry.pack(side='left', anchor='w')\n\n # Server Frequency Frame\n server_frequency_frame = Frame(server_frame, relief='flat', bd=2)\n server_frequency_frame.pack(side='top', anchor='s')\n\n desc_label = Label(server_frequency_frame, text='통신주기 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.server_frequency = StringVar()\n\n frequency_entry = Entry(server_frequency_frame, width=19, textvariable=self.server_frequency)\n frequency_entry.pack(side='left', anchor='w')\n\n # Communication Method Frame\n method_frame = Frame(server_frame, relief='flat', bd=2)\n method_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(method_frame, text='통신방식 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.method_var = StringVar()\n method_choice = ['유선랜', '무선CDMA(SKT)']\n self.method_var.set('유선랜')\n\n method_dropbox = OptionMenu(method_frame, self.method_var, *method_choice)\n method_dropbox.pack(side='left', anchor='w')\n\n # Outer Board Frame\n board_frame = Frame(setting_frame, relief='flat', bd=2)\n board_frame.pack(side='left', anchor='n', padx=200, pady=10)\n desc_label = Label(board_frame, text='외부보드 설정')\n desc_label.pack(side='top', anchor='n')\n\n # Port Setting Frame\n port_frame = Frame(board_frame, relief='flat', bd=2)\n port_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(port_frame, text='COM포트 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.port_var = StringVar()\n port_choice = []\n for i in range(0, 20):\n port_choice.append('/dev/ttyUSB' + str(i))\n self.port_var.set('/dev/ttyUSB0')\n\n port_dropbox = OptionMenu(port_frame, self.port_var, *port_choice)\n port_dropbox.pack(side='left', anchor='w')\n\n # Board Rate Frame\n rate_frame = Frame(board_frame, relief='flat', bd=2)\n rate_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(rate_frame, text='포트 속도 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.rate_var = StringVar()\n rate_choice = ['110', '300', '1200', '2400', '4800', '9600', '19200', '38400', '57600', '115200', '230400',\n '460800', '921600']\n self.rate_var.set('9600')\n\n rate_dropbox = OptionMenu(rate_frame, self.rate_var, *rate_choice)\n rate_dropbox.pack(side='left', anchor='w')\n\n # Board Frequency Frame\n board_frequency_frame = Frame(board_frame, relief='flat', bd=2)\n board_frequency_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(board_frequency_frame, text='통신 주기 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.board_frequency_var = StringVar()\n\n board_frequency_entry = Entry(board_frequency_frame, textvariable=self.board_frequency_var)\n board_frequency_entry.pack(side='left', anchor='w')\n\n # Client Frame\n client_frame = Frame(setting_frame, relief='flat', bd=2)\n client_frame.pack(side='left', anchor='n', padx=50, pady=10)\n desc_label = Label(client_frame, text='클라이언트 설정')\n desc_label.pack(side='top', anchor='n')\n\n # IP Address Assign\n ip_address_frame = Frame(client_frame, relief='flat', bd=2)\n ip_address_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(ip_address_frame, text='IP 주소 : ')\n desc_label.pack(side='left', anchor='w')\n\n self.ip_address_var = StringVar()\n\n ip_address_entry = Entry(ip_address_frame, textvariable=self.ip_address_var)\n ip_address_entry.pack(side='left', anchor='w')\n\n # SubnetMask Assign\n subnetmask_frame = Frame(client_frame, relief='flat', bd=2)\n subnetmask_frame.pack(side='top', anchor='s', fill='both', padx=2)\n\n desc_label = Label(subnetmask_frame, text=\"서브넷 : \")\n desc_label.pack(side='left', anchor='w')\n\n self.subnetmask_var = StringVar()\n\n subnetmask_entry = Entry(subnetmask_frame, textvariable=self.subnetmask_var)\n subnetmask_entry.pack(side='left', anchor='w')\n\n # Gateway Assign\n gateway_frame = Frame(client_frame, relief='flat', bd=2)\n gateway_frame.pack(side='top', anchor='s', fill='both')\n\n desc_label = Label(gateway_frame, text=\"게이트 : \")\n desc_label.pack(side='left', anchor='w', padx=1)\n\n self.gateway_var = StringVar()\n\n gateway_entry = Entry(gateway_frame, textvariable=self.gateway_var)\n gateway_entry.pack(side='top', anchor='s', fill='both')\n\n # IP Address Assgin Button\n ip_address_button_frame = Frame(client_frame, relief='flat', bd=2)\n ip_address_button_frame.pack(side='top', anchor='s', fill='both')\n\n ip_address_button = Button(ip_address_button_frame, text='변경', command=self.ip_address_assign)\n ip_address_button.pack(side='left', anchor='w', padx=60)\n\n # Start Timer\n self.start_timer()\n\n # Setting Button\n setting_button.config(state=DISABLED)\n\n # Button Frame\n button_frame = Frame(self, relief='flat', bd=2)\n button_frame.pack(side='bottom', anchor='center', pady=10)\n\n # Change Button\n change_button = Button(button_frame, text='변경/시작', command=self.change)\n change_button.pack(side='left', anchor='center', padx=5)\n\n # Certification Button\n cert_button = Button(button_frame, text='인증', command=self.cert_command)\n cert_button.pack(side='left', anchor='center', padx=5)\n\n # Stop Button\n stop_button = Button(button_frame, text='중지', command=self.stop)\n stop_button.pack(side='left', anchor='center', padx=5)\n\n # Init Value\n self.new_window_token = False\n self.cert = False\n self.data = data\n self.board_close_callback = board_close_callback\n self.save_callback = save_callback\n\n if data['client_id'] is not None:\n self.first_var.set(data['client_id'][:3])\n self.second_var.set(data['client_id'][3:7])\n self.third_var.set(data['client_id'][7:])\n\n if data['server_frequency'] != 0:\n self.server_frequency.set(data['server_frequency'])\n if data['server_method'] is not None:\n self.method_var.set(data['server_method'])\n if data['port_name'] is not None:\n self.port_var.set(data['port_name'])\n if data['port_rate'] is not None:\n self.rate_var.set(data['port_rate'])\n if data['port_frequency'] != 0:\n self.board_frequency_var.set(data['port_frequency'])\n if data['ip'] is not None:\n self.ip_var.set(data['ip'])\n if data['port'] is not None:\n self.server_port_var.set(data['port'])\n\n if data['ip'] is None:\n self.ip_var.set('121.179.45.130')\n if data['port'] is None:\n self.server_port_var.set('15300')\n\n def stop(self):\n self.data['running'] = False\n self.board_close_callback()\n\n def ip_address_assign(self):\n assign_static_ip(self.ip_address_var.get(), self.subnetmask_var.get(), self.gateway_var.get())\n\n def change(self):\n client_id = self.first_var.get() + self.second_var.get() + self.third_var.get()\n server_frequency = int(self.server_frequency.get())\n server_method = self.method_var.get()\n port_name = self.port_var.get()\n port_rate = self.rate_var.get()\n port_frequency = int(self.board_frequency_var.get())\n ip = self.ip_var.get()\n port = self.server_port_var.get()\n\n if client_id != '':\n self.data['client_id'] = client_id\n if ip != '':\n self.data['ip'] = ip\n if port != '':\n self.data['port'] = port\n if server_frequency is not None:\n self.data['server_frequency'] = server_frequency\n if server_method != '':\n self.data['server_method'] = server_method\n if port_name != '':\n self.data['port_name'] = port_name\n if port_rate != '':\n self.data['port_rate'] = port_rate\n if port_frequency is not None:\n self.data['port_frequency'] = port_frequency\n self.data['running'] = True\n\n self.save_callback()\n\n def cert_command(self):\n if self.new_window_token is True:\n return\n new_window(self, self.cert_callback, self.window_update, self.cert)\n\n def cert_callback(self):\n self.cert = True\n self.data['cert'] = True\n\n def window_update(self):\n self.new_window_token = not self.new_window_token\n\n def start_timer(self):\n timer = threading.Timer(1, self.start_timer)\n timer.start()\n\n s = datetime.datetime.now()\n s = str(s).split('.')[0]\n try:\n self.datetime_label['text'] = s\n except RuntimeError:\n timer.cancel()\n\n def main_callback(self):\n self.pack_forget()\n self.main()\n\n\nif __name__ == \"__main__\":\n window = Tk()\n window.geometry(\"1150x500+100+100\")\n window.resizable(False, False)\n app = Settings(window)\n app.mainloop()\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":13017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"37413080","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: MergeSort(Recursively)\n Description :\n Author : zdf's desktop\n date: 2018/9/19\n-------------------------------------------------\n Change Activity:\n 2018/9/19:21:24\n-------------------------------------------------\n\"\"\"\n\n\ndef merge(left, right):\n result = []\n while left and right:\n if left[0] <= right[0]:\n result.append(left.pop(0))\n else:\n result.append(right.pop(0))\n if left:\n result += left\n if right:\n result += right\n return result\n\n\ndef merge_sort(L):\n if len(L) <= 1:\n # When D&C to 1 element, just return it\n return L\n mid = len(L) // 2\n left = L[:mid]\n right = L[mid:]\n\n left = merge_sort(left)\n right = merge_sort(right)\n # conquer sub-problem recursively\n return merge(left, right)\n # return the answer of sub-problem\n\n\nif __name__ == \"__main__\":\n test = [1, 4, 2, 3.6, -1, 0, 25, -34, 8, 9, 1, 0]\n print(\"original:\", test)\n print(\"Sorted:\", merge_sort(test))","sub_path":"ZDF/CSCI 6212/MergeSort(Recursively).py","file_name":"MergeSort(Recursively).py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553236241","text":"#William Brown\n#MOD3 Program\n#CIS129, Gregory Wagner\n#Date 3/6/2017\n\n#Use library import random feature to access Pyhton data base \nimport random\n\n#Def sets a randomizer loop for slot machine. outcome = [none]*3 b/c we have 3 options. Range 0,3 for three outcomes\ndef casinoInput(series):\n outcome = [None]*3\n for display in range(0,3):\n random.shuffle(series)\n outcome[display]=series[0]\n return outcome\n\n#Set up functions for three possible outcomes on slot machine with if, elif and else.\n\ndef spiderman(series,question):\n if series[0]== series[1] and series[0]== series[2]:\n return question*3\n elif series[0]== series[1] or series[2]==series[1] or series[0]==series[2]:\n return question*2\n else:\n return 0\n\n\ndef myNeckHurts(series,question):\n print(\"Your results are \")\n print(series[0]+ \" \" + series[1] + \" \" + series[2])\n if question != 0:\n print (\"winner!\")\n print (question)\n else:\n print (\"You lose\")\n\n\n#declaring random outcomes\nsymbols = [\"Cherries\", \"Oranges\", \"Plums\", \"Bells\", \"Melons\", \"bars\",]\n\n \n#How much money do you want to put in the slot machine?\nquestion = float(input(\"Please enter the amount of money you wish to put in this slot machine \"))\n\n\nresultSeries = casinoInput(symbols)\n\nquestion = spiderman(resultSeries,question)\nmyNeckHurts(resultSeries,question)\n\n","sub_path":"CIS129-WILLIAM-PC3.py","file_name":"CIS129-WILLIAM-PC3.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"357110193","text":"import sys\nfrom datetime import datetime,timedelta,date\nimport boto3\nimport logging\nfrom Config import *\nimport calendar\nimport os\nfrom botocore.exceptions import ClientError\nfrom dateutil.relativedelta import relativedelta\n\nWEEKNUMBER = date.today().isocalendar()[1]\nTODAY_DATE_FULL=datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")\nlogging.basicConfig(filename='Cost_Explorer_'+str(TODAY_DATE_FULL)+'.log', level=int(Level),\n format='%(asctime)s:%(levelname)s:%(message)s',filemode='w')\n\nFILENAME=\"Airtel_Streaming_AWS_Billing_Report_\"+str(TODAY_DATE_FULL)+\".report\"\nf = open(FILENAME, \"w\")\n\n#checking whether account_details\nif len(account_details)==0:\n logging.info(+str(sys.argv[0])+\"Please Provide at least one account details in config file\")\n sys.exit(0)\n\n# loop is goingon in account_details\nfor x in account_details:\n #try to set profile withRole arn\n try:\n region=\"aws configure set default.region us-west-2\"\n profile=\"aws configure set profile.\" + x['Account_Name'] + \".role_arn arn:aws:iam::\" + x['Account_ID'] + \":role/\"+x['role']\n meta_data=\"aws configure set profile.\" + x['Account_Name'] + \".credential_source Ec2InstanceMetadata\"\n os.system(region)\n os.system(profile)\n os.system(meta_data)\n session=boto3.Session(profile_name=x['Account_Name'])\n sts = session.client('sts')\n sts.get_caller_identity()\n logging.info(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" account has valid role and successfully login with role in account \")\n except ClientError as e:\n logging.warning(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" account has invalid Role. Please configure proper IAM roles and now we are trying with access keys for this account \")\n logging.debug(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" account has invalid Role. Please configure proper IAM role and policies in account \")\n try:\n if e.response['Error']['Code'] == 'AccessDenied':\n session=boto3.Session(aws_access_key_id=x['access_key'],aws_secret_access_key=x['secret_access_key'])\n sts = session.client('sts')\n sts.get_caller_identity()\n logging.info(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" account has valid accesskey and secret-accesskey and successfully login in account \")\n except:\n logging.info(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" account has invalid Details. Please configure proper IAM roles or access keys for this account \")\n continue\n #required Variables\n FIRST_DAY_DATE = str(date.today().replace(day=1))\n TOMORROW_DAY_DATE = str(date.today() + timedelta(days=1))\n NEXT_MONTH_FIRST_DATE = str(date.today().replace(day=1) + relativedelta(months=1))\n NOW = datetime.now()\n MONTH_NAME = NOW.strftime('%B')\n LAST_DAY_OF_CURRENT_MONTH=calendar.monthrange(date.today().year,date.today().month)[1]\n TODAY_DATE_IN_DAY=date.today().day\n digits=2\n TODAY_DATE_FULL=str(date.today())\n\n ce_client = session.client('ce')\n\n cost_usage_response = ce_client.get_cost_and_usage(TimePeriod={\"Start\": FIRST_DAY_DATE,\"End\": NEXT_MONTH_FIRST_DATE},Granularity='MONTHLY',Metrics=['UNBLENDED_COST',],GroupBy=[{'Type': 'DIMENSION','Key': 'LINKED_ACCOUNT'},],)\n for groups in cost_usage_response['ResultsByTime']:\n for amount in groups['Groups']:\n fnum1=str(amount['Metrics']['UnblendedCost']['Amount'])\n MONTH_TO_DATE_COST = float(fnum1[:fnum1.find('.') + digits + 1])\n\n logging.info(str(sys.argv[0])+\" : \"+x['Account_Name']+\" : \"+x['Account_ID']+\" For account \"+x['Account_ID']+\" With Name \"+x['Account_Name']+\" :\")\n logging.info(\"-----------------------------------------\")\n logging.info(str(sys.argv[0])+\" : \"+str(MONTH_NAME)+\" month to date cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(MONTH_TO_DATE_COST))\n f.write(str(MONTH_NAME)+\" month to date cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(MONTH_TO_DATE_COST)+\" \\n\")\n\n#Taking projection cost from forecast\n\n if TODAY_DATE_IN_DAY == LAST_DAY_OF_CURRENT_MONTH:\n logging.info(str(sys.argv[0])+\" : \"+str(MONTH_NAME)+\" months Projection cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(MONTH_TO_DATE_COST)+\" \\n\")\n f.write(str(MONTH_NAME)+\" months Projection cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(MONTH_TO_DATE_COST)+\" \\n\")\n f.write(\"\\n\")\n else:\n forecast_response = ce_client.get_cost_forecast(TimePeriod={'Start': TOMORROW_DAY_DATE,'End': NEXT_MONTH_FIRST_DATE},Metric='BLENDED_COST',Granularity='MONTHLY',PredictionIntervalLevel=99)\n fnum2=str(forecast_response['Total']['Amount'])\n PROJECTION_COST = float(fnum2[:fnum2.find('.') + digits + 1])\n logging.info(str(sys.argv[0])+\" : \"+str(MONTH_NAME)+\" months Projection cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(PROJECTION_COST)+\" \\n\")\n f.write(str(MONTH_NAME)+\" months Projection cost for account \"+ x['Account_Name'] +\" (\"+x['Account_ID']+\") is : $\"+str(PROJECTION_COST)+\" \\n\")\n f.write(\"\\n\")\n\nf.close()\n#copy=\"aws s3 cp \"+str(FILENAME)+\" \"+s3_bucket\n#os.system(copy)\nf = open(FILENAME, \"r\")\nreport=f.read()\nremove=\"rm \"+str(FILENAME)\nos.system(remove)\nprint(\"done\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"369749025","text":"from multiprocessing import Pool\n\n\ndef exec_function_in_parallel(function_, list_: list, workers: int) -> list:\n pool = Pool(workers)\n results = pool.map(function_, list_)\n pool.close()\n pool.join()\n return results\n\n\ndef exec_processes_in_parallel(process_list: list):\n for p in process_list:\n p.start()\n for p in process_list:\n p.join()\n # if a child process throws an exception it's not propagated to the parent\n if p.exitcode != 0:\n raise Exception(\"Child process failed\")\n","sub_path":"datautils/multiprocessing.py","file_name":"multiprocessing.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33298847","text":"#!/usr/bin/python3\n# Filename: rangeFind.py\n\n# sample script to read range values from Maxbotix ultrasonic rangefinder\n\nfrom time import sleep\nimport maxSonarTTY\n\ndef sonar_detect():\n serialPort = \"/dev/ttyAMA0\"\n maxRange = 5000 # change for 5m vs 10m sensor\n sleepTime = 1\n minMM = 9999\n maxMM = 0\n t = 0\n text_file = open(\"Sonar.txt\", \"w\")\n while t<2:\n mm = maxSonarTTY.measure(serialPort)\n if mm >= maxRange:\n #print(\"no target\")\n sleep(sleepTime)\n continue\n if mm < minMM:\n minMM = mm\n if mm > maxMM:\n maxMM = mm\n\n #print(\"distance:\", mm, \" min:\", minMM, \"max:\", maxMM)\n text_file.write(str(mm) + \" \")\n \n sleep(1)\n t = t+1\n text_file.close()\n\nsonar_detect()","sub_path":"hardware_testing/Sonar/rangeFind.py","file_name":"rangeFind.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"320648655","text":"#!/usr/bin/env python3\n# -*-coding: utf-8-*-\n# Author : Chris\n# Blog : http://blog.chriscabin.com\n# GitHub : https://www.github.com/chrisleegit\n# File : gui-streams.py\n# Date : 16-7-5\n# Version: 0.1\n# Description: ...\nfrom tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\n\n\nclass GuiConsole(Frame):\n def __init__(self, master=None, cnf={}, **kw):\n super(GuiConsole, self).__init__(master, cnf, **kw)\n self.pack(fill=BOTH, expand=YES)\n self.console = ScrolledText(self, font=('Source Code Pro', 12, 'normal'))\n self.console.pack(side=TOP, fill=BOTH, expand=YES, padx=5, pady=5)\n self.console.focus()\n self.console.mark_set(INSERT, '1.0')\n\n def clear(self):\n self.console.delete('1.0', END)\n\n def write(self, text):\n text = '{}'.format(text)\n self.console.insert(INSERT, text)\n self.console.mark_set(INSERT, INSERT+'+{}c'.format(len(text)))\n\n def writeline(self, text):\n self.write('{}\\n'.format(text))\n\n def writelines(self, lines):\n for line in lines:\n self.writeline(line)\n\n def read(self):\n pass\n\n\ndef main():\n import sys\n app = Tk()\n c = GuiConsole(app)\n save_streams = sys.stdin, sys.stdout\n sys.stdout = c\n for x in range(10):\n print('Hello, output to Text widget: {}'.format(x))\n sys.stdin, sys.stdout = save_streams\n app.mainloop()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ch10/gui-streams.py","file_name":"gui-streams.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"552529280","text":"#Dana Feldman YA4\r\n#input 3 string type keys and 3 int type values into dictionary\r\n#check if input is a key in the dictionary\r\ndef main():\r\n MakeDict()\r\n\r\n\r\ndef MakeDict():\r\n#returns dictionary with 3 string type keys(input) and 3 int type values(input)\r\n dict={\r\n input(\"enter key: \"): eval(input(\"enter value: \")),\r\n input(\"enter key: \"): eval(input(\"enter value: \")),\r\n input(\"enter key: \"): eval(input(\"enter value: \"))\r\n }\r\n CheckKey(dict)\r\n return (dict)\r\n\r\n\r\ndef CheckKey(dict):\r\n#recieves dictionary\r\n#print \"yes\" if input is a key in the dictionary\r\n#else, print \"no\"\r\n x=input(\"enter key: \")\r\n if x in dict:\r\n print (\"yes\")\r\n else:\r\n print (\"no\")\r\n\r\n\r\nmain()","sub_path":"dictionary1.py","file_name":"dictionary1.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"315367630","text":"\"\"\"\nOpen Sound Control for Python 3\nCopyright (C) 2013 Trevor Hinkley, University of Glasgow\n\nThis library is free software; you can redistribute it and/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free\nSoftware Foundation; either version 2.1 of the License, or (at your option) any\nlater version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU Lesser General Public License for more\ndetails.\n\nYou should have received a copy of the GNU Lesser General Public License along\nwith this library; if not, write to the Free Software Foundation, Inc., 59\nTemple Place, Suite 330, Boston, MA 02111-1307 USA\n\nFor questions regarding this module contact Trevor Hinkley (trevor.hinkley@glasgow.ac.uk)\n\"\"\"\n\nimport struct, math, datetime, sys, socket, re, time, base64\nfrom threading import Thread\nimport types\nfrom select import select\nfrom queue import Queue\n\nSOCKET_BUF_SIZE = 4096 * 8\n\n\ndef printBin(byteString):\n\ta = []\n\tfor i in byteString:\n\t\ta.append(\"%.02X\"%i)\n\treturn \"\".join(a)\n\nclass Exception(Exception):\n\tpass\n\nclass Binarize(object):\n\tdef __getattr__(self, name):\n\t\tif name == \"bin\":\n\t\t\treturn self.getBinary()\n\t\telse:\n\t\t\treturn self.__getattribute__(name)\n\nclass MetaAtom(type):\n\tdef __init__(cls, name, baseClasses, nameSpace):\n\t\tif \"pythonClass\" in nameSpace:\n\t\t\tAtom.mapPythonToOSC(nameSpace[\"pythonClass\"], cls)\n\t\tif \"tag\" in nameSpace:\n\t\t\tAtom.mapTagToOSC(nameSpace[\"tag\"], cls)\n\n\n\n################\n#\n# OSC atomic types, which can be encoded into a binary format\n#\n\n\nclass Atom(Binarize, metaclass = MetaAtom):\n\t\"\"\"Atom is basic class for encodable OSC types, from which the rest of the OSC data-types are derived\n\t\"\"\"\n\ttoOSCMapping = []\n\ttagMap = {}\n\t\n\t@classmethod\n\tdef mapPythonToOSC(cls, thingFrom, thingTo):\n\t\tcls.toOSCMapping.append((thingFrom, thingTo))\n\t\n\t@classmethod\n\tdef mapTagToOSC(cls, tag, thingTo):\n\t\tcls.tagMap[tag] = thingTo\n\n\tdef __new__(cls, inThing, bin=None):\n\t\tif cls == Atom:\n\t\t\tfor pyCls, OSCCls in cls.toOSCMapping:\n\t\t\t\tif isinstance(inThing, pyCls):\n\t\t\t\t\tcls = OSCCls\n\t\t\t\t\tbreak\n\t\tif cls == Atom:\n\t\t\traise(TypeError(str(type(inThing)) + \" Cannot be encoded as an OSC type.\"))\n\t\telse:\n\t\t\tneonate = object.__new__(cls)\n\t\t\tneonate.__init__(inThing)\n\t\t\treturn neonate\n\t\n\tdef __init__(self, inThing):\n\t\tself.val = inThing\n\t\tself.bin = self.OSCEncode()\n\n\tdef __eq__(self, other):\n\t\treturn self.val == other.val\n\n\tdef __repr__(self):\n\t\treturn \"osc\"+self.__class__.__name__+\"(\"+repr(self.val)+\")\"\n\n\tdef getBinary(self):\n\t\traise(Exception(\"Atom should never not have a binary representation.\"))\n\n\t@classmethod\n\tdef reprCType(cls, typeStream):\n\t\t\"\"\" Return a C representation of the type\n\t\t\"\"\"\n\t\treturn cls.cType\n\n\n\nclass String(Atom):\n\t\"\"\" The length of the resulting string is always a multiple of 4 bytes.\n\t The string ends with 1 to 4 zero-bytes ('\\x00') \n\t\"\"\"\n\ttag = \"s\"\n\tpythonClass = str\n\tdef OSCEncode(self):\n\t\tstringLength = math.ceil((len(self.val)+1) / 4.0) * 4\n\t\treturn struct.pack(\">%ds\" % (stringLength), bytes(self.val,encoding=\"ASCII\"))\n\t\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\t\"\"\"Reads the next (null-terminated) block of data\n\t\t\"\"\"\n\t\treturn binaryReader.readString()\n\nclass Blob(Atom):\n\t\"\"\" An OSC-Blob is a binary encoded block of data, prepended by a 'size' (int32).\n\t The size is always a mutiple of 4 bytes. \n\t The blob ends with 0 to 3 zero-bytes ('\\x00') \n\t\"\"\"\n\ttag = \"b\"\n\tpythonClass = bytes\n\tdef OSCEncode(self):\n\t\tif isinstance(self.val, Atom):\n\t\t\tval = self.val.bin\n\t\telse:\n\t\t\tval = self.val\n\t\tblobLength = math.ceil((len(val)) / 4.0) * 4\n\t\treturn struct.pack(\">i%ds\" % (blobLength), blobLength, val)\n\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\tlength, = struct.unpack(\">i\", binaryReader.readData(4))\n\t\treturn binaryReader.readData(length)\n\n\n\nclass Boolean(Atom):\n\t\"\"\" A boolean value, this will be encoded as a type-tag only\n\t\"\"\"\n\tpythonClass = bool\n\tdef __init__(self, inThing):\n\t\tself.val = inThing\n\t\tif inThing:\n\t\t\tself.tag = \"T\"\n\t\telse:\n\t\t\tself.tag = \"F\"\n\t\tself.bin = b\"\"\n\tdef OSCEncode(self):\n\t\treturn b\"\"\n\t\n\nclass TrueBool(Boolean):\n\ttag = \"T\"\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn True\n\nclass FalseBool(Boolean):\n\ttag = \"F\"\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn False\n\nclass Float(Atom):\n\t\"\"\" A 32-bit floating-point value\n\t\"\"\"\n\ttag = \"f\"\n\tpythonClass = float\n\tdef OSCEncode(self):\n\t\treturn struct.pack(\">f\", self.val)\n\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn struct.unpack(\">f\", binaryReader.readData(4))[0]\n\nclass Double(Atom):\n\t#Don't announce this one\n\t\"\"\" A 64-bit floating-point value\n\t\"\"\"\n\ttag = \"d\"\n\tdef OSCEncode(self):\n\t\treturn struct.pack(\">d\", self.val)\n\t\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn struct.unpack(\">d\", binaryReader.readData(8))[0]\n\nclass Int(Atom):\n\t\"\"\" A 32-bit integer value\n\t\"\"\"\n\ttag = \"i\"\n\tpythonClass = int\n\tdef OSCEncode(self):\n\t\treturn struct.pack(\">i\", self.val)\n\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn struct.unpack(\">i\", binaryReader.readData(4))[0]\n\nclass Long(Atom):\n\t#Don't announce this one\n\t\"\"\" A 64-bit integer value\n\t\"\"\"\n\ttag = \"h\"\n\tdef OSCEncode(self):\n\t\treturn struct.pack(\">q\", self.val)\n\t\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn struct.unpack(\">q\", binaryReader.readData(8))[0]\n\nclass TimeTag(Atom):\n\t\"\"\" A time tag, this will encoded into a 64-bit NTP value\n\t\"\"\"\n\ttag = \"t\"\n\tpythonClass = datetime.datetime\n\tNTPEpoch = datetime.datetime(1900,1,1,0,0)\n\tNTPUnitsPerSecond = 0x100000000\n\tNTPUnitsPerMicrosecond = 0x100000000 / 1000000\n\tdef OSCEncode(self):\n\t\tdelta = self.val - self.NTPEpoch \n\t\tsecs = delta.total_seconds()\n\t\tfract, secs = math.modf(secs)\n\t\tbinary = struct.pack('>LL', int(secs), int(fract * self.NTPUnitsPerSecond))\n\t\treturn binary\n\t\n\tdef __repr__(self):\n\t\treturn \"osc\"+self.__class__.__name__+\"(\"+str(self.val)+\")\"\n\t\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\thigh, low = struct.unpack(\">LL\", binaryReader.readData(8))\n\t\tif high == 0 and low == 1:\n\t\t\treturn cls.now\n\t\treturn cls.NTPEpoch + datetime.timedelta(seconds = high, microseconds = low / cls.NTPUnitsPerMicrosecond)\n\nclass Immediately(TimeTag):\n\t\"\"\" A special timetag specifying immediate execution\n\t\"\"\"\n\tinstance = None\n\tdef __init__(self):\n\t\tself.bin = self.OSCEncode()\n\n\tdef __new__(cls):\n\t\tif not cls.instance:\n\t\t\tcls.instance = object.__new__(cls)\n\t\t\tcls.instance.__init__()\n\t\treturn cls.instance\n\n\tdef OSCEncode(self):\n\t\tbinary = struct.pack('>LL', 0, 1)\n\t\treturn binary\n\n\tdef __repr__(self):\n\t\treturn \"\"\n\nTimeTag.now = Immediately()\n\nclass Array(Atom):\n\t\"\"\" An implementation of the python \"list\", as opposed to the python tuple, which gets encoded as a message\n\t\"\"\"\n\ttag = \"[\"\n\tpythonClass = list\n\tcType = \"OSCArray\"\n\tdef __init__(self, inThing):\n\t\tself.val = [i if isinstance(i,Atom) else Atom(i) for i in inThing]\n\t\tself.tag = \"[%s]\"%\"\".join([i.tag for i in self.val])\n\t\tself.bin = self.OSCEncode()\n\t\n\tdef OSCEncode(self):\n\t\treturn b\"\".join([i.bin for i in self.val])\n\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\tary = []\n\t\tfor tag in binaryReader.typeTags:\n\t\t\t#Array is a special case\n\t\t\tif tag == \"]\":\n\t\t\t\treturn ary\n\t\t\telse:\n\t\t\t\tary.append(binaryReader.decodeByTag(tag))\n\t\traise(Exception(\"Array does not end\"))\n\n\n#TODO: Consider making this take a subsequent representation\nclass MessageTag(Atom):\n\t\"\"\"Tag appended to a message so that it can be uniquely identified\n\t\"\"\"\n\ttag = \"#\"\n\t@classmethod\n\tdef readBinary(cls, binaryReader):\n\t\treturn cls(Int.readBinary(binaryReader))\n\n\n\n################\n#\n# OSC encapsulation types\n#\n\n\n\nclass Message(Atom):\n\tdef __init__(self, address, *args):\n\t\t\"\"\"Instantiate a new OSCMessage.\n\t\tThe OSC-address can be specified with the 'address' argument.\n\t\tThe rest of the arguments are appended as data.\n\t\t\"\"\"\n\t\tself.message = []\n\t\tself.setAddress(address)\n\t\tfor arg in args:\n\t\t\tself.append(arg)\n\n\tdef __new__(cls, address, *args):\n\t\tneonate = object.__new__(cls)\n\t\tneonate.__init__(address, *args)\n\t\treturn neonate\n\tdef __repr__(self):\n\t\treturn repr(self.address)+\" - \"+repr(self.message)\n\n\tdef __str__(self):\n\t\treturn \"%s: %s\" % (self.address, str(self.message))\n\n\tdef __iadd__(self, thing):\n\t\tfor i in thing:\n\t\t\tself.append(i)\n\t\treturn self\n\n\n\tdef clearCache(self):\n\t\tself.bin = None\n\t\tdelattr(self, \"bin\")\n\n\tdef setAddress(self, address):\n\t\t\"\"\"Set or change the OSC-address\n\t\t\"\"\"\n\t\tself.clearCache()\n\t\tif isinstance(address, String):\n\t\t\tself.address = address\n\t\telse:\n\t\t\tself.address = String(address)\n\n\tdef clear(self):\n\t\t\"\"\"Clear any arguments appended so far\n\t\t\"\"\"\n\t\tself.clearCache()\n\t\tself.message = []\n\n\tdef append(self, argument):\n\t\t\"\"\"Appends data to the message, converting into an OSC Atom if necessary\n\t\t\"\"\"\n\t\tself.clearCache()\n\t\tif not isinstance(argument, Atom):\n\t\t\targument = Atom(argument)\n\t\t\n\t\tself.message.append(argument)\n\n\tdef getBinary(self):\n\t\t\"\"\"Returns the binary representation of the message\n\t\t\"\"\"\n\t\tbinary = self.address.bin\n\t\ttags = \",\"\n\t\tbinMsg = b\"\"\n\t\tfor i in self.message:\n\t\t\ttags += i.tag\n\t\t\tbinMsg += i.bin\n\t\tbinary += String(tags).bin\n\t\tbinary += binMsg\n\t\tself.bin = binary\n\t\treturn binary\n\n\n\nclass Bundle(Message):\n\theaderString = String(\"#bundle\")\n\tdef __init__(self, time, *args):\n\t\tself.setTime(time)\n\t\tself.members = []\n\t\tfor arg in args:\n\t\t\tself.append(arg)\n\n\tdef __repr__(self):\n\t\treturn repr(self.time)+\" - \"+repr(self.members)\n\n\tdef __str__(self):\n\t\treturn \"%s: %s\" % (str(self.time), str(self.members))\n\n\tdef clear(self):\n\t\tself.clearCache()\n\t\tself.members = []\n\t\n\tdef setTime(self, time):\n\t\tself.clearCache()\n\t\tif not isinstance(time, TimeTag):\n\t\t\tself.time = TimeTag(time)\n\t\telse:\n\t\t\tself.time = time\n\n\tdef append(self, argument):\n\t\tself.clearCache()\n\t\tif not isinstance(argument, (Message, Bundle)):\n\t\t\traise(TypeError(\"Can only add a Message or a Bundle to a Bundle\"))\n\t\tself.members.append(argument)\n\n\tdef getBinary(self):\n\t\t\"\"\"Returns the binary representation of the message\n\t\t\"\"\"\n\t\tbinary = type(self).headerString.bin\n\t\tbinary += self.time.bin\n\t\tfor i in self.members:\n\t\t\tbinary += struct.pack(\">i\" , len(i.bin))\n\t\t\tbinary += i.bin\n\t\tself.bin = binary\n\t\t\n\t\treturn binary\n\nclass RecvBundle(list):\n\tdef __init__(self, time):\n\t\tself.time = time\n\tdef __repr__(self):\n\t\treturn \"bundle:%s\"%super().__repr__()\n\nclass RecvMessage(list):\n\tmessageTag = None\n\n\tdef __init__(self, address):\n\t\tself.address = address\n\tdef __repr__(self):\n\t\treturn \"message:%s\"%super().__repr__()\n\nclass OSCZeroDataError(Exception):\n\t\"\"\" This class is the exception for cases where a zero data blob\n\t is received which some clients use to signal socket disconnection (aka LabView Fuckup) \n \"\"\"\n\tpass\n\nclass OSCDecoder:\n\talign = 4\n\tdef __init__(self, data, pos = 0, remnantStream = None):\n\t\tself.data = data\n\t\tself.pos = pos\n\t\tself.remnant = remnantStream\n\n\tdef bufferEmpty(self):\n\t\tif self.pos >= len(self.data):\n\t\t\tself.data = b\"\"\n\t\t\tself.pos = 0\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef fillFromRemnant(self):\n\t\tif not self.remnant:\n\t\t\traise(IndexError( \"Bytestream is truncated '%s'\"%self.data[self.pos:]))\n\t\tself.data = self.data[self.pos:]\n\t\tself.pos = 0\n\t\tnewData = self.remnant.read(SOCKET_BUF_SIZE)\n\t\tif len(newData) == 0:\n\t\t\traise(OSCZeroDataError)\n\t\tself.data = self.data + newData\n\n\tdef _checkPos(self, length):\n\t\twhile self.pos+length > len(self.data):\n\t\t\tself.fillFromRemnant()\n\n\tdef alignPos(self, pos):\n\t\talign = pos % self.align\n\t\tif align:\n\t\t\treturn pos - align + self.align\n\t\telse:\n\t\t\treturn pos\n\n\tdef readData(self, length):\n\t\tnextPos = self.pos + length\n\t\twhile nextPos > len(self.data):\n\t\t\tself.fillFromRemnant()\n\t\t\tnextPos = self.pos + length\n\t\tret = self.data[self.pos:nextPos]\n\t\tself.pos = self.alignPos(nextPos)\n\t\treturn ret\n\n\tdef readString(self):\n\t\tnextPos = self.data.find(b\"\\0\",self.pos)\n\t\twhile nextPos == -1:\n\t\t\tself.fillFromRemnant()\n\t\t\tnextPos = self.data.find(b\"\\0\",self.pos)\n\t\tret = self.data[self.pos:nextPos]\n\t\tself.pos = self.alignPos(nextPos+1)\n\t\treturn ret.decode(\"ASCII\")\n\n\tdef decodeByTag(self, tag):\n\t\tif not tag in Atom.tagMap:\n\t\t\traise(Exception(\"Error on tag '%s' at '%s' with %s \"%(tag,printBin(self.data[self.pos:]), printBin(self.data))))\n\t\treturn Atom.tagMap[tag].readBinary(self)\n\n\tdef decode(self):\n\t\taddress = self.readString()\n\t\tif address == \"#bundle\":\n\t\t\treturn self.decodeBundle()\n\t\telse:\n\t\t\treturn self.decodeMessage(address)\n\n\tdef decodeBundle(self):\n\t\tdecoded = RecvBundle(TimeTag.readBinary(self))\n\t\twhile self.pos < len(self.data):\n\t\t\tlength = Int.readBinary(self)\n\t\t\tdecoded.append(OSCDecoder(self.data,self.pos).decode())\n\t\t\tself.pos += length\n\t\treturn decoded\n\n\tdef decodeMessage(self, address):\n\t\tdecoded = RecvMessage(address)\n\t\ttypeTags = String.readBinary(self)\n\t\tself.typeTags = iter(typeTags)\n\t\tif next(self.typeTags) != \",\":\n\t\t\traise (Exception(\"Message's typetag-string lacks the magic ','.\"))\n\t\telse:\n\t\t\tfor tag in self.typeTags:\n\t\t\t\tdatum = self.decodeByTag(tag)\n\t\t\t\tif isinstance(datum, MessageTag):\n\t\t\t\t\tdecoded.responseTag = datum.val\n\t\t\t\telse:\n\t\t\t\t\tdecoded.append(datum)\n\t\treturn decoded\n\nclass SocketWrapper:\n\t\"\"\" SocketWrapper is a class which acts as an intermediate\n\t between the OSC decoder and the actual socket\n\t\"\"\"\n\tdef __init__(self, socket):\n\t\tself.sock = socket\n\tdef read(self, n):\n\t\treturn self.sock.recv(n)\n\nclass SocketWrapperSLIP:\n\tdef __init__(self, socket):\n\t\tself.sock = socket\n\tdef read(self, n):\n\t\treturn self.sock.recv(n)\n\n# A translation-table for mapping OSC-address expressions to Python 're' expressions\nOSCtrans = str.maketrans(\"{,}?\",\"(|).\")\nreDict = {}\n\ndef getRegEx(pattern):\n\t\"\"\"Compiles and returns a 'regular expression' object for the given address-pattern.\"\"\"\n\tif not pattern in reDict:\n\t\tpattern = pattern.replace(\".\", r\"\\.\")\t\t# first, escape all '.'s in the pattern.\n\t\tpattern = pattern.replace(\"(\", r\"\\(\")\t\t# escape all '('s.\n\t\tpattern = pattern.replace(\")\", r\"\\)\")\t\t# escape all ')'s.\n\t\tpattern = pattern.replace(\"*\", r\".*\")\t\t# replace a '*' by '.*' (match 0 or more characters)\n\t\tpattern = pattern.translate(OSCtrans)\t\t# change '?' to '.' and '{,}' to '(|)'\n\t\treDict[pattern] = re.compile(pattern+\"$\")\n\treturn reDict[pattern]\n\nbadList=\" #*,/?[]{}\"\ndef _stringCheck(string):\n\tfor i in badList:\n\t\tif i in string:\n\t\t\treturn True\n\treturn False\n\n\nclass OSCSelector:\n\tdef matchFull(self, stringList):\n\t\tif len(self) != len(stringList):\n\t\t\treturn False\n\t\tfor i,j in zip(self.matchList, stringList):\n\t\t\tif not i.match(j):\n\t\t\t\treturn False\n\t\treturn True\n\tdef __init__(self, string):\n\t\tself.matchString = string\n\t\tself.matchList = [getRegEx(i) for i in string.split(\"/\")[1:]]\n\tdef __len__(self):\n\t\treturn len(self.matchList)\n\tdef __getitem__(self, idx):\n\t\treturn self.matchList[idx]\n\nclass AddressResolver:\n\tdef retrieveAddress(self, string):\n\t\tmatchList = OSCSelector(string)\n\t\treturn tuple(set(self.match(matchList,0)))\n\n\nclass AddressNode(AddressResolver):\n\tdef __init__(self):\n\t\tself.children = []\n\t\tself.leaf = ()\n\t\tself.subs = []\n\tdef match(self, matchList, pos):\n\t\tif pos == len(matchList):\n\t\t\treturn self.leaf\n\t\tmatcher = matchList[pos]\n\t\tmatches = tuple()\n\t\tfor string, node in self.children:\n\t\t\tif matcher.match(string):\n\t\t\t\tmatches += node.match(matchList,pos+1)\n\t\tfor sub in self.subs:\n\t\t\tmatches += sub.match(matchList[pos:], 0)\n\t\treturn matches\n\n\nclass AddressTree(AddressNode):\n\t\"\"\" Address tree is used to store the response-address tree for a Responder/Socket\n\t\"\"\"\n\tdef __getitem__(self, string):\n\t\treturn self.retrieveAddress(string)\n\tdef __setitem__(self, string, value):\n\t\tmatchList = string.split(\"/\")[1:]\n\t\tcurNode = self\n\t\tfor curString in matchList:\n\t\t\tfoundNode = None\n\t\t\tfor string, node in self.children:\n\t\t\t\tif curString == string:\n\t\t\t\t\tfoundNode = node\n\t\t\t\t\tbreak\n\t\t\tif foundNode == None:\n\t\t\t\tif _stringCheck(curString):\n\t\t\t\t\traise(Exception(\"Bad character in %s\"%curString))\n\t\t\t\tfoundNode = AddressNode()\n\t\t\t\tcurNode.children.append((curString, foundNode))\n\t\t\tcurNode = foundNode\n\t\tif isinstance(value, (AddressTree, Responder)):\n\t\t\tcurNode.subs.append(value)\n\t\telse:\n\t\t\tcurNode.leaf = (value,) + curNode.leaf\n\n\nclass MetaResponder(type, AddressResolver):\n\tclass Exposure:\n\t\tdef __init__(self, func, path):\n\t\t\tself.func = func\n\t\t\tself.path = path\n\t\n\t@classmethod\n\tdef expose(cls, path):\n\t\tdef inner(func):\n\t\t\treturn cls.Exposure(func, path)\n\t\treturn inner\n\t\n\tdef __new__(cls, name, bases, nameSpace):\n\t\tdel nameSpace[\"expose\"]\n\t\ttargets = list()\n\t\tfor i in nameSpace:\n\t\t\te = nameSpace[i]\n\t\t\tif isinstance(e, MetaResponder.Exposure):\n\t\t\t\ttargets.append(e)\n\t\t\t\tnameSpace[i] = e.func\n\t\tnameSpace[\"classTargets\"] = targets\n\t\treturn super().__new__(cls, name, bases, nameSpace)\n\t\n\tdef __init__(self, name, bases, nameSpace):\n\t\ttargets = AddressTree()\n\t\tfor i in nameSpace[\"classTargets\"]:\n\t\t\ttargets[i.path] = i.func\n\t\tself.classTargets = targets\n\t\n\t@classmethod\n\tdef __prepare__(meta, name, bases):\n\t\treturn dict(expose=meta.expose)\n\nclass Responder(metaclass = MetaResponder):\n\t@classmethod\n\tdef match(cls, matchList, pos):\n\t\t\"\"\"Used to retrieve a split address from this object\"\"\"\n\t\tresponse = cls.classTargets.match(matchList, pos)\n\t\tfor sup in cls.__bases__:\n\t\t\tif isinstance(sup, Responder):\n\t\t\t\tresponse = response + sup.match(matchList, pos)\n\t\treturn response\n\n\t@classmethod\n\tdef getResponse(cls, address):\n\t\tresponse = cls.classTargets[address]\n\t\tfor sup in cls.__bases__:\n\t\t\tif issubclass(sup, Responder):\n\t\t\t\tresponse = response + sup.getResponse(address)\n\t\treturn response\n\n\n\n\nclass SocketSend:\n\tdef __init__(self, socket, IPAddr = None, OSCAddr = None, sendTag = None):\n\t\tself.sock = socket\n\t\tself.IPAddr = IPAddr\n\t\tself.OSCAddr = OSCAddr\n\t\tself.OSCSendTag = sendTag\n\n\tdef __getitem__(self, OSCAddr):\n\t\tif self.OSCSendTag:\n\t\t\traise(Exception(\"Tagged send cannot be further subsetted\"))\n\t\torigin = None\n\t\tif self.OSCAddr:\n\t\t\tOSCAddr = self.OSCAddr = OSCAddr\n\t\treturn SocketSend(self.sock, self.IPAddr, OSCAddr)\n\t\n\tdef __lshift__(self, thing):\n\t\treturn self.send(thing)\n\n\tdef send(self, thing):\n\t\tif not self.OSCAddr:\n\t\t\traise(Exception(\"No OSC destination has been specified\"))\n\t\tif None is thing:\n\t\t\tthing = Message(self.OSCAddr)\n\t\telif not isinstance(thing, tuple):\n\t\t\tthing = Message(self.OSCAddr, thing)\n\t\telse:\n\t\t\tthing = Message(self.OSCAddr, *thing)\n\t\tif self.IPAddr:\n\t\t\tself.sock.sendto(thing.bin, self.IPAddr)\n\t\telse:\n\t\t\tself.sock.sendall(thing.bin)\n\n\n\nclass OSCDeviceResponder(Responder):\n\tdef __init__(self, parallelMessages = False):\n\t\tself.prlMsg = parallelMessages\n\t\tself.targets = None\n\n\tdef __setitem__(self, target, handle):\n\t\tself.addTarget(target, handle)\n\t\n\tdef addTarget(self, target, handle):\n\t\t\"\"\" Add an instance target to this OSC socket\n\t\t\"\"\"\n\t\tif self.targets:\n\t\t\tself.targets[target] = handle\n\t\telse:\n\t\t\traise(Exception(\"Socket was not set up as a listening socket\"))\n\n\tdef logMessageException(self, packet, exception):\n\t\tprint(self, packet.address, packet, exception)\n\n\tdef runMessage(self, handle, packet, source):\n\t\tresponse = self.makeResponse(packet, source)\n\t\ttry:\n\t\t\thandle(response, *packet)\n\t\texcept Exception as E:\n\t\t\tself.logMessageException(args, E)\n\n\tdef makeResponse(self, packet, source):\n\t\tif packet.messageTag:\n\t\t\tresponse = SocketResponse(self, packet.messageTag, source)\n\t\telse:\n\t\t\tresponse = SocketSend(self, source)\n\t\treturn response\n\n\tdef handleMessage(self, packet, source):\n\t\tif isinstance(packet, RecvBundle):\n\t\t\tThread(target=self.handleBundle, args=(packet,source)).start()\n\t\telif isinstance(packet, RecvMessage):\n\t\t\thandles = self.getResponse(packet.address)\n\t\t\tif self.targets != None:\n\t\t\t\thandles = handles + self.targets[packet.address]\n\t\t\tif len(handles) == 0:\n\t\t\t\tself.logMessageException(packet, Exception(\"Message has no targets\"))\n\t\t\telse:\n\t\t\t\tif self.prlMsg:\n\t\t\t\t\tfor handle in handles:\n\t\t\t\t\t\tThread(target=self.runMessage, args = (handle, packet, source)).start()\n\t\t\t\telse:\n\t\t\t\t\tfor handle in handles:\n\t\t\t\t\t\tself.runMessage(handle, packet, source)\n\t\n\t#TODO: This probably shouldn't be done this way\n\t# it would be better to have a priority queue so a bazillion threads aren't made?\n\tdef handleBundle(self, packet, source):\n\t\tdelta = (datetime.datetime.now() - packet.time).total_seconds()\n\t\tif delta > 0:\n\t\t\tsleep(delta)\n\t\tfor i in packet:\n\t\t\tself.handleMessage(i, source)\n\n\nclass OSCDevice(OSCDeviceResponder):\n\tdef __init__(self, parallelMessages = False):\n\t\tsuper().__init__(parallelMessages)\n\t\tself.baseProxy = SocketSend(self)\n\t\tself.tagCount = 0\n\t\tself.running = False\n\t\tself.outAddresses = set()\n\t\tself.whiteList = []\n\n\tdef __getitem__(self, arg):\n\t\treturn self.baseProxy[arg]\n\t\n\tdef __call__(self, address, port):\n\t\treturn SocketSend(self, IPAddr=(address,port))\n\n\tdef __del__(self):\n\t\tif self.running:\n\t\t\tself.close()\n\t\n\tdef generateTag(self, responseAddress):\n\t\tself.tagCount += 1\n\t\treturn self.tagCount\n\n\tdef addToWhiteList(self, address):\n\t\t\"\"\" Add an address to the white-list. If there is currently no\n\t\t white-list then this function will create the white-list\n\t\t\"\"\"\n\t\tif not \":\" in address:\n\t\t\taddress = address+\":[0-9]+\"\n\t\tself.whiteList.append(re.compile(address+\"$\"))\n\t\n\tdef isWhiteListed(self, source):\n\t\t\"\"\" If a white-list has been added to this OSC socket then this\n\t\t function will check whether the source is registerd in that\n\t\t list and return the results. Returns True if there is no\n\t\t white-list\n\t\t\"\"\"\n\t\tif not self.whiteList:\n\t\t\treturn True\n\t\tfor wl in self.whiteList:\n\t\t\tif wl.match(\"%s:%d\"%source):\n\t\t\t\treturn True\n\t\treturn False\n\t\n\tdef registerDestination(self, address, port):\n\t\t\"\"\" Add an address to the broadcast list for this socket, all messages\n\t\t sent out in broadcast mode will now be sent to this address.\n\t\t\"\"\"\n\t\tself.outAddresses.add((address, port))\n\t\n\tdef sendall(self, thing):\n\t\t\"\"\" Send a message out in broadcast mode\n\t\t\"\"\"\n\t\tif isinstance(thing, Message):\n\t\t\tfor dest in self.outAddresses:\n\t\t\t\tself.sendto(thing, dest)\n\t\telse:\n\t\t\traise(Exception(\"Invalid thing being sent down the tubes: \"+repr(thing)))\n\t\n\tdef close(self):\n\t\tself.running = False\n\n\tdef __lshift__(self, thing):\n\t\tself.sendall(thing)\n\t\nclass DecodingError(Exception):\n\tpass\n\nclass HandlingError(Exception):\n\tpass\n\n\nclass OSCDeviceUDP(OSCDevice):\n\t# set socket buffer sizes (32k)\n\n\tdef __init__(self, inPort=None, parallelMessages = False, addressFamily = socket.AF_INET):\n\t\tsuper().__init__(parallelMessages = parallelMessages)\n\t\tif inPort != None:\n\t\t\tself.targets = AddressTree()\n\t\t\tself.connectInUDP(inPort,addressFamily)\n\t\t\tself.outSocket = self.inSocket\n\t\telse:\n\t\t\tself.connectOutUDP(addressFamily)\n\t\t\tself.inSocket = None\n\t\tself.outSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n\t\tself.outSocket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCKET_BUF_SIZE)\n\n\tdef connectInUDP(self, inPort, addressFamily):\n\t\t\"\"\" Called during initialization to create a UDP socket in listen\n\t\t mode. This socket is create asynchronously.\n\t\t\"\"\"\n\t\tself.inSocket = socket.socket(addressFamily, socket.SOCK_DGRAM)\n\t\tself.inSocket.settimeout(1)\n\t\tself.inSocket.bind((\"\",inPort))\n\t\tself.thread = Thread(target=self.listenUDPThread)\n\t\tself.thread.start()\n\n\tdef connectOutUDP(self, addressFamily):\n\t\t\"\"\" Called during initialization to create a UDP socket if this\n\t\t OSC socket has not been created in listen mode\n\t\t\"\"\"\n\t\tself.outSocket = socket.socket(addressFamily, socket.SOCK_DGRAM)\n\t\tself.outSocket.bind((\"\",0))\n\n\tdef listenUDPThread(self):\n\t\tself.running = True\n\t\twhile self.running:\n\t\t\ttry:\n\t\t\t\tdata,source = self.inSocket.recvfrom(SOCKET_BUF_SIZE)\n\t\t\t\tif self.isWhiteListed(source):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tpacket = OSCDecoder(data).decode()\n\t\t\t\t\texcept:\n\t\t\t\t\t\traise(DecodingError())\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself.handleMessage(packet, source)\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\traise(HandlingError(e))\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Invalid attempt to access from %s\"%repr(data[1]))\n\t\t\texcept socket.error:\n\t\t\t\tpass\n\t\t\texcept DecodingError:\n\t\t\t\tprint(\"Invalid message from (%s,%s)\"%source)\n\t\t\texcept HandlingError as e:\n\t\t\t\tprint(\"Error handling message %s with %s\"%(data, e))\n\t\t\t\t\n\tdef close(self):\n\t\tsuper().close()\n\t\tself.outSocket.close()\n\n\tdef sendto(self, thing, address):\n\t\t\"\"\" Send a message out to a specific address\n\t\t\"\"\"\n\t\treturn self.outSocket.sendto(thing, address)\n\n\nclass SLIPException(Exception):\n\tpass\n\nSLIP_END = 0xC0\nSLIP_ESC = 0xDB\nSLIP_ESC_END = 0xDC\nSLIP_ESC_ESC = 0xDD\nclass SLIPEncoderDecoder:\n\t\"\"\" This class acts as an intermediary to a socket, it sends data packets in\n\t SLIP format and processes incoming (in SLIP) to normal datagrams\n\t\"\"\"\n\tdef __init__(self, socket):\n\t\tself.socket = socket\n\t\tself.inPacketBuf = Queue()\n\t\tself.workingRetrievalBuffer = None\n\n\tdef sendPacket(self, packet):\n\t\ttempSLIPBuffer = bytearray() \n\t\ttempSLIPBuffer.append(SLIP_END) \n\t\tfor i in packet: \n\t\t\tif i == SLIP_END: \n\t\t\t\ttempSLIPBuffer.append(SLIP_ESC) \n\t\t\t\ttempSLIPBuffer.append(SLIP_ESC_END) \n\t\t\telif i == SLIP_ESC: \n\t\t\t\ttempSLIPBuffer.append(SLIP_ESC) \n\t\t\t\ttempSLIPBuffer.append(SLIP_ESC_ESC) \n\t\t\telse: \n\t\t\t\ttempSLIPBuffer.append(i) \n\t\ttempSLIPBuffer.append(SLIP_END)\n\t\tself.socket.send(bytes(tempSLIPBuffer))\n\n\tdef getPacket(self):\n\t\tif self.inPacketBuf.empty():\n\t\t\tself.retrieveData()\n\t\treturn self.inPacketBuf.get()\n\n\tdef dataWaiting(self):\n\t\treturn not self.inPacketBuf.empty()\n\n\tdef retrieveData(self):\n\t\tworkingBuf = self.workingRetrievalBuffer\n\t\twhile self.inPacketBuf.empty():\n\t\t\tnewData = self.socket.recv(SOCKET_BUF_SIZE)\n\t\t\tnewData = iter(newData)\n\t\t\tfor i in newData:\n\t\t\t\tif i == SLIP_END:\n\t\t\t\t\tif workingBuf is None:\n\t\t\t\t\t\tworkingBuf = bytearray()\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.inPacketBuf.put(bytes(workingBuf))\n\t\t\t\t\t\tworkingBuf = None\n\t\t\t\t\t\n\t\t\t\telif i == SLIP_ESC:\n\t\t\t\t\ti = newData.__next__()\n\t\t\t\t\tif i == SLIP_ESC_END:\n\t\t\t\t\t\tworkingBuf.append(SLIP_ESC)\n\t\t\t\t\telif i == SLIP_ESC_ESC:\n\t\t\t\t\t\tworkingBuf.append(SLIP_ESC)\n\t\t\t\t\telse:\n\t\t\t\t\t\traise(SLIPException(\"Unexpected byte %x following ESCAPE character\"%i))\n\t\t\t\telse:\n\t\t\t\t\tworkingBuf.append(i)\n\t\tself.workingRetrievalBuffer = workingBuf\n\t\t\t\t\t\n\nclass OSCDeviceTCP(OSCDevice):\n\tdef __init__(self, inPort=None, parallelMessages = False, addressFamily = socket.AF_INET):\n\t\tsuper().__init__(parallelMessages = parallelMessages)\n\t\tif inPort != None:\n\t\t\tself.targets = AddressTree()\n\t\t\tself.connectInTCP(inPort,addressFamily)\n\t\tself.sockets = {}\n\t\tself.decoders = {}\n\n\tdef connectInTCP(self, inPort, addressFamily):\n\t\tself.inSocket = socket.socket(addressFamily, socket.SOCK_STREAM)\n\t\tself.inSocket.settimeout(1)\n\t\tself.inSocket.bind((\"\",inPort))\n\t\tself.thread = Thread(target=self.listenTCPThread)\n\t\tself.thread.start()\n\n\tdef connectOutTCP(self, destIP, destPort, addressFamily = socket.AF_INET):\n\t\tif (destIP,destPort) in self.sockets:\n\t\t\treturn self.sockets[(destIP,destPort)]\n\t\toutSocket = socket.socket(addressFamily, socket.SOCK_STREAM)\n\t\toutSocket.settimeout(1)\n\t\toutSocket.connect((destIP,destPort))\n\t\tself.handleNewConnection((destIP,destPort),outSocket)\n\t\treturn outSocket\n\n\tdef closeOutTCP(self, destIP, destPort):\n\t\tif (destIP,destPort) in self.sockets:\n\t\t\tself.sockets[(destIP,destPort)].close()\n\t\t\tdel self.sockets[(destIP,destPort)]\n\n\tdef getSocketAddress(self, sock):\n\t\tfor k,v in self.sockets.items():\n\t\t\tif v == sock:\n\t\t\t\treturn k\n\n\n\tdef listenTCPThread(self):\n\t\t\"\"\" The main listening thread, this thread listens for new connections and sends them\n\t\t to handleNewConnection for filtering. If they pass muser (default is to auto-accept)\n\t\t then they can be added to the list of sockets to listen for data on. Because TCP\n\t\t is stream-oriented, data is handled differently than in UDP.\n\t\t\"\"\"\n\t\tself.inSocket.listen(10)\n\t\tallSockets = [self.inSocket]\n\t\twhile True:\n\t\t\treadSockets,_,errorSockets = select(allSockets,[],allSockets)\n\t\t\tfor sock in readSockets:\n\t\t\t\t#Handle new connecting socket\n\t\t\t\tif sock is self.inSocket:\n\t\t\t\t\tneonateSocket, addr = self.inSocket.accept()\n\t\t\t\t\tif self.handleNewConnection(addr, neonateSocket):\n\t\t\t\t\t\tallSockets = [self.inSocket]+list(self.sockets.values())\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdecoder = self.decoders[sock]\n\t\t\t\t\t\tdata = decoder.getPacket()\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tpacket = OSCDecoder(data).decode()\n\t\t\t\t\t\texcept OSCZeroDataError:\n\t\t\t\t\t\t\traise(socket.error)\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\traise(DecodingError(e))\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself.dispatchHandleMessage(packet, sock)\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\traise(HandlingError(e))\n\t\t\t\t\t\tif decoder.dataWaiting():\n\t\t\t\t\t\t\treadSockets.append(sock)\n\t\t\t\t\t# TODO: All of the below should be moved to some kind of status\n\t\t\t\t\t# log stream.\n\t\t\t\t\texcept socket.error:\n\t\t\t\t\t\tprint(\"Connection closed by peer\")\n\t\t\t\t\t\terrorSockets.append(sock)\n\t\t\t\t\texcept DecodingError:\n\t\t\t\t\t\tprint(\"Invalid message from (%s,%s)\"%self.getSocketAddress(sock))\n\t\t\t\t\t\terrorSockets.append(sock)\n\t\t\t\t\texcept HandlingError:\n\t\t\t\t\t\tprint(\"Error handling message %s\"%data)\n\t\t\t\t\t\terrorSockets.append(sock)\n\t\t\t#Handle disconnections\n\t\t\tfor sock in errorSockets:\n\t\t\t\tself.closeConnection(sock)\n\t\t\t\tallSockets = [self.inSocket]+list(self.sockets.values())\n\n\tdef handleNewConnection(self, addr, neonateSocket):\n\t\tself.sockets[addr] = neonateSocket\n\t\tself.decoders[neonateSocket] = SLIPEncoderDecoder(neonateSocket)\n\t\treturn True\n\n\tdef closeConnection(self, socket):\n\t\terr = self.getSocketAddress(socket)\n\t\tdel self.sockets[err]\n\t\tdel self.decoders[socket]\t\t\n\t\tsocket.close()\n\n\tdef sendto(self, thing, address):\n\t\t\"\"\" Send a message out to a specific address\n\t\t The connection to the address will be kept until it is manually closed\n\t\t\"\"\"\n\t\toutSocket = self.connectOutTCP(*address)\n\t\toutDecoder = self.decoders[outSocket]\n\t\toutDecoder.sendPacket(thing)\n\n\n\tdef dispatchHandleMessage(self, packet, sock):\n\t\tsource = self.getSocketAddress(sock)\n\t\tself.handleMessage(packet, source)\n\n\tdef close(self):\n\t\tsuper().close()\n\t\tfor i in self.sockets.items():\n\t\t\ti.close()\n\t\tself.inSocket.close()\n\ndef header(p):\n\tprint(\"\\n\")\n\tprint(p)\n\tprint(\"\".join([\"*\"]*len(p)))\n\tprint()\n\ndef testEcho(server, message,source):\n\tmessage = \"ECHO: \"+message\n\tserver << Message(message, address=\"/print\")\n\ndef testPrint(server, message, source):\n\tprint(source)\n\tprint(message)\n\ndef unitTests():\n\theader(\"Test the direct creation of various Atoms\")\n\tprint(Float(1.0))\n\tprint(Double(1.0))\n\tprint(Int(1))\n\tprint(Long(1))\n\tprint(Blob(b\"asdasd\"))\n\tprint(String(\"asdasd\"))\n\tprint(Array([\"asdasd\",\"mooop\"]))\n\tprint(TimeTag(datetime.datetime.now()))\n\n\theader(\"Test the direct creation of a message\")\n\tm = Message(\"/\")\n\tm.append(Float(1.0))\n\tm += [Double(1.0), Int(1), Long(1), Blob(b\"asdasd\"), String(\"asdasd\"),Array([\"asdasd\",\"mooop\"])]\n\tprint(m)\n\n\theader(\"Test the indirect creation of various Atoms\")\n\tprint(Atom(1.0))\n\tprint(Atom(1))\n\tprint(Atom(True))\n\tprint(Atom(False))\n\tprint(Atom(b\"asdasd\"))\n\tprint(Atom(\"asdasd\"))\n\tprint(Atom(datetime.datetime.now()))\n\n\theader(\"Test the indirect creation of a bundle\")\n\tb = Message(\"/unitTest\")\n\tb.append([1,2,3,4, True])\n\tb.append([1.0,[\"hello\"]])\n\tb = Bundle(Immediately(), b)\n\tprint(b)\n\n\t\n\theader(\"Test the binarization of a message\")\n\tprint(m.bin)\n\n\theader(\"Test the binarization of a bundle\")\n\tprint(b.bin)\n\n\theader(\"Test the manual de-binarization of a message\")\n\tmbd = OSCDecoder(m.bin)\n\tprint(mbd.decode())\n\n\theader(\"Test the manual de-binarization of a bundle\")\n\tbdb = OSCDecoder(b.bin)\n\tprint(bdb.decode())\n\n\theader(\"Test the address tree creation\")\n\tadt = AddressTree()\n\tadt[\"/test1/subtest1\"] = 1\n\tadt[\"/test1/subtest2\"] = 2\n\tadt[\"/test2/subtest1\"] = 3\n\tadt[\"/test2/subtest2\"] = 4\n\tadt[\"/test2/subtest3\"] = 5\n\tprint(adt)\n\n\theader(\"Test retrieving values from the address tree\")\n\tprint(adt[\"/test1/subtest1\"])\n\tprint(adt[\"/test?/subtest1\"])\n\tprint(adt[\"/test2/subtest*\"])\n\tprint(adt[\"/*/subtest{1,2}\"])\n\tprint(adt[\"/*/subtest8\"])\n\n\theader(\"Test setting up a server\")\n\toscServe = Socket(inPort=9001)\n\t#oscServe.registerDestination(\"localhost\", 9001)\n\t#oscServe[\"/echo\"] = testEcho\n\t#oscServe[\"/print\"] = testPrint\n\toscServe(\"localhost\",9013)[\"/group3/bool/a\"] << True\n\ttry:\n\t\twhile True:\n\t\t\tpass\n\texcept:\n\t\toscServe.close()\n","sub_path":"osc.py","file_name":"osc.py","file_ext":"py","file_size_in_byte":31873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"173728070","text":"from DatabasePool import DatabasePool\nfrom fakenews import fakenews\nfrom myHtmlClass import myHtmlClass\nfrom bson.objectid import ObjectId\nimport json\n\ndef get_dimension(paramenter_url):\n try:\n f = fakenews()\n m = myHtmlClass()\n\n dimension_text = m.prepare_text(paramenter_url)\n dimension_text = dimension_text[:5120]\n # print(f\"--->{dimension_text}<---\")\n dimension_language = f.check_language(dimension_text)\n dimension_sentiment = f.check_sentiment(dimension_text)\n dimension_key_words = f.check_key_words(dimension_text)\n return dimension_language, dimension_sentiment, dimension_key_words\n except:\n return 0\n\n\ndef open_database():\n try:\n d = DatabasePool()\n c = d.connect_mongo()\n except:\n return 0\n return c\n\n\ndef language_score(url_id):\n global new_list\n x = data_collection.find({\"url_id\": url_id})\n nl = []\n for i in x:\n ll = i[\"language\"][\"documents\"]\n new_list = [x[\"detectedLanguages\"] for x in ll]\n nl.append([x[\"score\"] for x in new_list[0]])\n return nl[0][0]\n\n\ndef sentiment_score(url_id):\n x = data_collection.find({\"url_id\": url_id})\n nl = []\n for i in x:\n ll = i[\"sentiment\"][\"documents\"]\n nl = [x[\"score\"] for x in ll]\n return nl[0]\n\n\ndef key_word_score(url_id):\n #print(\"url_id ---->\", url_id)\n x = data_collection.find({\"url_id\": url_id})\n entityTypeScore = []\n wikipediaScore = []\n\n for i in x:\n ll = i[\"key_word\"][\"documents\"]\n new_list = [x[\"entities\"] for x in ll]\n\n lkeyword = new_list[0]\n for i in range(len(lkeyword)):\n l = lkeyword[i]\n lm = dict(l[\"matches\"][0])\n\n try:\n wikipediaScore.append(lm[\"wikipediaScore\"])\n except:\n entityTypeScore.append(lm[\"entityTypeScore\"])\n\n return len(entityTypeScore), entityTypeScore, len(wikipediaScore), wikipediaScore\n\n\ndef log_classification(p_is_fake):\n if p_is_fake == 0:\n print(\"Document is true\")\n print(\"***\"*30)\n print(\"\")\n print(\"\")\n else:\n print(\"FAKE NEWS!!!\")\n print(\"***\"*30)\n print(\"\")\n print(\"\")\n\n\n# Set fakenews objectx\nf = fakenews()\n\n# Set database\nd = open_database()\ndatabase = d['fakenews']\n\n#Documents to be analyzed\n# if you need to training a text, inform is_fake parameter with the knowledge value\n# if you need to classify the text, pass is_fake parameter with blank value\n# 0 = not fake\n# 1 = is fake\n\n#documents = [\n# {\"url\": \"https://noticia-tv.com/entrevista-helen-sbt/?utm_source=taboola&utm_medium=PHYTO-2B-DESK-CP1&utm_campaign=editoraabril-exame\", \"is_fake\":\"1\"},\n#]\n\n\njson_file = open(\"/Users/arnaldo.pedroso/git/Monografia/news.json\", \"r\", encoding=\"utf-8\")\n\nnews = json.load(json_file)\n\nfor doc in news:\n url = doc[\"url\"]\n print(\"==*\"*30)\n print(f\"Working with url {url}\")\n print(\"==*\"*30)\n\n v_is_fake = doc[\"is_fake\"]\n\n # Define dictionary to be searched\n dict_url = {\"url\": url}\n\n # Set collections\n url_collection = database['url']\n data_collection = database['data_to_be_analyzed']\n\n # Reset variables\n vlanguage_score = 0.0\n vsentiment_score = 0.0\n\n d_url = url_collection.find(dict_url)\n if v_is_fake is not \"\":\n if url_collection.count_documents(dict_url) >0:\n try:\n return_is_fake = [x[\"is_fake\"] for x in d_url]\n except:\n print(\"Error - ignoring this url\")\n url_collection.delete_one({\"url\": url})\n continue\n\n log_classification(int(return_is_fake[0]))\n continue\n else:\n # Insert url\n url_id = url_collection.insert_one(dict_url).inserted_id\n\n # Get dimensions\n\n try:\n language, sentiment, key_word = get_dimension(url)\n except:\n url_collection.delete_one({\"url\": url})\n continue\n\n\n # Prepare data to be recorded\n dict_data = {\"url_id\": url_id, \"language\": language, \"sentiment\": sentiment, \"key_word\": key_word}\n\n # Inserting data_collection\n data_to_be_analyzed_id = data_collection.insert_one(dict_data).inserted_id\n\n # Determine score values\n vlanguage_score = float(language_score(url_id))\n vsentiment_score = float(sentiment_score(url_id))\n total_entityTypeScore, entityTypeScore, total_wikipediaScore, wikipediaScore = key_word_score(url_id)\n\n sum_entityTypeScore = float(sum(entityTypeScore))\n\n try:\n avg_entityTypeScore = float(sum_entityTypeScore / total_entityTypeScore)\n except ZeroDivisionError:\n avg_entityTypeScore = 0\n\n sum_wikipediaScore = float(sum(wikipediaScore))\n\n try:\n avg_wikipediaScore = float(sum_wikipediaScore / total_wikipediaScore)\n except ZeroDivisionError:\n avg_wikipediaScore = 0\n\n url_collection.update_one({\"url\": url}, {\"$set\":\n {\"language_score\": vlanguage_score,\n \"sentiment_score\": vsentiment_score,\n \"total_entityTypeScore\": total_entityTypeScore,\n \"total_wikipediaScore\": total_wikipediaScore,\n \"avg_entityTypeScore\": avg_entityTypeScore,\n \"avg_wikipediaScore\": avg_wikipediaScore,\n \"is_fake\": v_is_fake\n }\n })\n\n print(f\"URL: {url} has been inserted.\")\n print(f\"URL id# is {url_id}.\")\n print(f\"Data id# is {data_to_be_analyzed_id}.\")\n print(\"--\"*30)\n elif url_collection.count_documents(dict_url) > 0:\n try:\n return_is_fake = [x[\"is_fake\"] for x in d_url]\n except:\n print(\"Error - ignoring this url\")\n url_collection.delete_one({\"url\": url})\n continue\n log_classification(int(return_is_fake[0]))\n continue\n else:\n url_swap_collection = database['url_swap']\n\n #Insert url_swap\n url_id = url_swap_collection.insert_one(dict_url).inserted_id\n\n #Get dimensions\n language, sentiment, key_word = get_dimension(url)\n\n #Prepare data to be recorded\n dict_data = {\"url_id\": url_id, \"language\": language, \"sentiment\": sentiment, \"key_word\": key_word}\n\n #Insert data_collection_swap\n data_to_be_analyzed_id = data_collection.insert_one(dict_data).inserted_id\n\n #Determine score values\n vlanguage_score = float(language_score(url_id))\n\n vsentiment_score = float(sentiment_score(url_id))\n total_entityTypeScore, entityTypeScore, total_wikipediaScore, wikipediaScore = key_word_score(url_id)\n\n sum_entityTypeScore = float(sum(entityTypeScore))\n avg_entityTypeScore = float(sum_entityTypeScore / total_entityTypeScore)\n\n sum_wikipediaScore = float(sum(wikipediaScore))\n avg_wikipediaScore = float(sum_wikipediaScore / total_wikipediaScore)\n\n #Verify if the url is fake or not\n is_fake = f.classify_url([avg_entityTypeScore, avg_wikipediaScore, vlanguage_score, vsentiment_score, sum_entityTypeScore, sum_wikipediaScore])\n\n #Print classification of the url\n log_classification(int(is_fake[0]))\n\n #Remove swap registers\n url_swap_collection.delete_one({'_id': ObjectId(url_id)})\n data_collection.delete_one({'_id': ObjectId(data_to_be_analyzed_id)})\n\n #Inserting correct values\n url_id = url_collection.insert_one(dict_url).inserted_id\n url_collection.update_one({\"url\": url}, {\"$set\":\n {\"language_score\": vlanguage_score,\n \"sentiment_score\": vsentiment_score,\n \"total_entityTypeScore\": total_entityTypeScore,\n \"total_wikipediaScore\": total_wikipediaScore,\n \"avg_entityTypeScore\": avg_entityTypeScore,\n \"avg_wikipediaScore\": avg_wikipediaScore,\n \"is_fake\": is_fake[0]\n }\n })\n\n # Inserting data collection\n dict_data = {\"url_id\": url_id, \"language\": language, \"sentiment\": sentiment, \"key_word\": key_word}\n data_to_be_analyzed_id = data_collection.insert_one(dict_data).inserted_id\n#Finish\nexit(1)\n","sub_path":"FakeNews/algorithmFakeNews.py","file_name":"algorithmFakeNews.py","file_ext":"py","file_size_in_byte":9075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"155645856","text":"import argparse\n\nfrom model import Model\n\ndef main():\n # set up our command line arguments\n parser = argparse.ArgumentParser(description='Set arguments for training of pytorch image recognotion model')\n parser.add_argument('image_dir', type = str, help='path to image to run model on')\n parser.add_argument('checkpoint_dir', type = str, help='path to the model checkpoint')\n parser.add_argument('--top_k', type = int, default=5, help='return top k probabilities')\n parser.add_argument('--category_names', type = str, help='json file containing the conversion from classes to the real labels')\n parser.add_argument('--gpu', type = bool, default=False, help='Should pytorch use a gpu for better performance')\n \n # gets our arguments from the command line\n in_arg = parser.parse_args()\n \n # creates a Model class\n model = Model()\n \n # loads a checkpoint from specified path\n model.load_model(in_arg.checkpoint_dir)\n \n # sends our model to the gpu if requested\n model.use_gpu(in_arg.gpu)\n \n # Gets our top image prediction from our model\n probs, classes = model.predict(in_arg.image_dir, category_names_dir=in_arg.category_names, topk=in_arg.top_k)\n\n # prints out our data\n print('model probabilities: {}'.format(probs))\n print('model classes: {}'.format(classes))\n \n# Call to main function to run the program\nif __name__ == \"__main__\":\n main()","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584296153","text":"\"\"\"\nThis is the toy example problem in the SNOPT documentation.\n min x1\n s.t . x1**2 + 4x2**2 <= 4\n (x1-2)**2 + x2**2 <= 5\n x1 >=0\n\nWe define the function F(x):\n F(x) = [ x1 ]\n [ x1**2 + 4x2**2 ]\n [ (x1-2)**2 + x2**2 ]\nwith ObjRow = 1 to indicate the objective.\n\nThe Jacobian is:\n F'(x) = [ 1 0 ] [ 1 0 ] [ 0 0 ]\n [ 2x1 8x2 ] = [ 0 0 ] + [ 2x1 8x2 ]\n [ 2(x1-2) 2x2 ] [ 0 0 ] [ 2(x1-2) 2x2 ]\n linear(A) nonlinear (G)\n\n\"\"\"\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom optimize.snopt7 import SNOPT_solver\n\n\ndef sntoya_objF(status,x,needF,needG,cu,iu,ru):\n F = np.array([ x[1], # objective row\n x[0]**2 + 4.0*x[1]**2,\n (x[0] - 2.0)**2 + x[1]**2 ])\n return status, F\n\n\ndef sntoya_objFG(status,x,needF,needG,cu,iu,ru):\n F = np.array([ x[1], # objective row\n x[0]**2 + 4.0*x[1]**2,\n (x[0] - 2.0)**2 + x[1]**2 ])\n\n G = np.array([ 2*x[0], 8*x[1], 2*(x[0]-2), 2*x[1] ])\n return status, F, G\n\n\n\ninf = 1.0e20\n\nsnopt = SNOPT_solver()\n\nsnopt.setOption('Verbose',True)\nsnopt.setOption('Solution print',True)\nsnopt.setOption('Print file','sntoya.out')\n\n\n# Either dtype works, but the names for x and F have to be of\n# the correct length, else they are both ignored by SNOPT:\nxNames = np.array([ ' x0', ' x1' ])\nFNames = np.array([ ' F0', ' F1', ' F2' ],dtype='c')\n\nx0 = np.array([ 1.0, 1.0 ])\n\nxlow = np.array([ 0.0, -inf])\nxupp = np.array([ inf, inf])\n\nFlow = np.array([ -inf, -inf, -inf ])\nFupp = np.array([ inf, 4.0, 5.0 ])\n\nObjRow = 1\n\n# We first solve the problem without providing derivative info\nsnopt.snopta(name=' sntoyaF',x0=x0,xlow=xlow,xupp=xupp,\n Flow=Flow,Fupp=Fupp,ObjRow=ObjRow,\n usrfun=sntoya_objF,xnames=xNames,Fnames=FNames)\n\n# Now we set up the derivative structures...\n\n# A and G provide the linear and nonlinear components of\n# the Jacobian matrix, respectively. Here, G and A are given\n# as dense matrices.\n#\n# For the nonlinear components, enter any nonzero value to\n# indicate the location of the nonlinear deriatives (in this case, 2).\n# A must be properly defined with the correct derivative values.\n\nA = np.array([ [0, 1],\n [0, 0],\n [0, 0]])\n\nG = np.array([ [0, 0],\n [2, 2],\n [2, 2]])\n\n# Alternatively, A and G can be input in coordinate form via scipy's\n# coordinate matrix\n# A = sp.coo_matrix(A)\n# G = sp.coo_matrix(G)\n# or explicitly in coordinate form\n# iAfun = row indices of A\n# jAvar = col indices of A\n# A = matrix values of A\n#\n# iGfun = row indices of G\n# jGvar = col indices of G\n\nsnopt.snopta(name='sntoyaFG',usrfun=sntoya_objFG,x0=x0,xlow=xlow,xupp=xupp,\n Flow=Flow,Fupp=Fupp,ObjRow=ObjRow,A=A,G=G,xnames=xNames,Fnames=FNames)\n","sub_path":"examples/sntoya.py","file_name":"sntoya.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16705192","text":"import pandas as pd\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nimport re\nfrom numpy import array\n\ndef content_ratio(attr):\n return len(set(attr)) / len(attr)\n\n# for one attr\ndef content_histogram(attr_df, attr_name):\n return attr_df.groupby(attr_name).agg({attr_name:'count'})\n\ndef visualize_histograms_pair(attr1_name, attr1_histog_re, attr2_name, attr2_histog_re, resample_dimension):\n pos = list(range(0, resample_dimension))\n plt.plot(pos, attr1_histog_re, 'go-', pos, attr2_histog_re, '.-')\n plt.legend([attr1_name, attr2_name], loc='best')\n plt.show()\n\ndef feature_extractor(pair_of_attrs, pair_of_attr_names):\n attr1 = pair_of_attrs[0]\n # attr2 = pair_of_attrs[1]\n attr1_name = pair_of_attr_names[0]\n # attr2_name = pair_of_attr_names[1]\n attr1_df = pd.DataFrame({attr1_name: attr1})\n # attr2_df = pd.DataFrame({attr2_name: attr2})\n\n content_ratio1 = content_ratio(attr1)\n # content_ratio2 = content_ratio(attr2)\n\n # print(content_ratio1)\n # print(content_ratio2)\n\n # all attrs in table1\n tbl1_attrs = attr1_df.keys()\n # all attrs in table2\n # tbl2_attrs = attr2_df.keys()\n\n distributions1 = {}\n # distributions2 = {}\n for attr in tbl1_attrs:\n content_histogram_tbl1 = content_histogram(attr1_df, attr)\n distributions1[attr] = content_histogram_tbl1\n\n # for attr in tbl2_attrs:\n # content_histogram_tbl2 = content_histogram(attr2_df, attr)\n # distributions2[attr] = content_histogram_tbl2\n\n # table1\n attr1_histog = []\n for distr in distributions1:\n # print(distr)\n if distr == attr1_name:\n # distributions1[distr].sort_values(distr)\n for index, row in distributions1[distr].iterrows():\n # print(row)\n # for key in row.keys():\n attr1_histog.append(row[distr])\n\n # # table2\n # attr2_histog = []\n # for distr in distributions2:\n # # print(distr)\n # if distr == attr2_name:\n # # distributions2[distr].sort_values(distr)\n # for index, row in distributions2[distr].iterrows():\n # attr2_histog.append(row[distr])\n\n attr1_histog.sort()\n # attr2_histog.sort()\n\n # print(attr1_histog)\n # print(attr2_histog)\n\n # resample using fft\n resample_dimension = 20\n attr1_histog_re = signal.resample(attr1_histog, resample_dimension)\n # attr2_histog_re = signal.resample(attr2_histog, resample_dimension)\n\n # print(attr1_histog_re)\n # # print(attr2_histog_re)\n\n # visualize_histograms_pair(attr1_name, attr1_histog_re, attr2_name, attr2_histog_re, resample_dimension)\n\n # print(_get_col_dtype(attr1_df[attr1_name]))\n # print(_get_col_dtype(attr2_df[attr2_name]))\n\n average_cell_len1 = average_cell_len(attr1)\n # average_cell_len2 = average_cell_len(attr2)\n\n percentage_of_num1, percentage_of_alphabetic1 = percentage_of_num_alphabetic(attr1)\n # percentage_of_num2, percentage_of_alphabetic2 = percentage_of_num_alphabetic(attr2)\n\n attr1_features = [content_ratio1]\n attr1_features.extend(attr1_histog_re)\n attr1_features.append(average_cell_len1)\n attr1_features.append(percentage_of_num1)\n attr1_features.append(percentage_of_alphabetic1)\n\n # attr2_features = [content_ratio2]\n # attr2_features.extend(attr2_histog_re)\n # attr2_features.append(average_cell_len2)\n # attr2_features.append(percentage_of_num2)\n # attr2_features.append(percentage_of_alphabetic2)\n\n attr1_features_dict = ['attr_histogram']*resample_dimension\n attr1_features_dict = ['content_ratio', *attr1_features_dict, 'average_cell_len', 'percentage_of_num', 'percentage_of_alphabetic']\n\n return attr1_features, attr1_features_dict\n\n\ndef average_cell_len(cols):\n # cell is one string\n return sum([len(cell) for cell in cols])/len(cols)\n\ndef percentage_of_num_alphabetic(cols):\n total_nums = 0\n total_alphabets = 0\n total_chars = 0\n for cell in cols:\n total_nums += sum([len(s) for s in re.findall(r'-?\\d+\\.?\\d*', cell)])\n total_alphabets += sum (len(s) for s in re.findall(\"[a-zA-Z]+\", cell))\n total_chars += len(cell)\n return total_nums/total_chars, total_alphabets/total_chars\n\n# # tokenize cell\n# from nltk import word_tokenize\n\n# pandas infer data type https://stackoverflow.com/questions/35003138/python-pandas-inferring-column-datatypes\ndef _get_col_dtype(col):\n \"\"\"\n Infer datatype of a pandas column, process only if the column dtype is object.\n input: col: a pandas Series representing a df column.\n \"\"\"\n\n if col.dtype == \"object\":\n\n # try numeric\n try:\n col_new = pd.to_datetime(col.dropna().unique())\n return col_new.dtype\n except:\n try:\n col_new = pd.to_numeric(col.dropna().unique())\n return col_new.dtype\n except:\n try:\n col_new = pd.to_timedelta(col.dropna().unique())\n return col_new.dtype\n except:\n return \"object\"\n\n else:\n return col.dtype\n\n\n\n# attr from table1\nattr1 = ['a', 'a', 'b', 'c', 'd', '-1', 'a1a']\n# attr from table2\nattr2 = ['a', 'a', 'a', 'a', 'a', 'e', '2.0', 'a1a']\n# attr from table3\nattr3 = ['abcd', 'bd bd bd', 'op op as as', 'qwert']\n# attr from table4\nattr4 = ['a', 'a', 'b', 'c', 'd']\n# attr from table5\nattr5 = ['a2a', 'a', '4.0', 'a', 'd']\n\nattr1_name = 'attr1'\nattr2_name = 'attr2'\nattr3_name = 'attr3'\nattr4_name = 'attr4'\nattr5_name = 'attr5'\n\nattr1_features, attr1_features_dict = feature_extractor([attr1], [attr1_name])\nattr2_features, _ = feature_extractor([attr2], [attr2_name])\nattr3_features, _ = feature_extractor([attr3], [attr3_name])\nattr4_features, _ = feature_extractor([attr4], [attr4_name])\n\nx12 = array(attr2_features) - array(attr1_features)\nx13 = array(attr3_features) - array(attr1_features)\nx14 = array(attr4_features) - array(attr1_features)\nx23 = array(attr3_features) - array(attr2_features)\nx24 = array(attr4_features) - array(attr2_features)\nx34 = array(attr4_features) - array(attr3_features)\n\n# random forest classifier\nfrom sklearn.ensemble import RandomForestClassifier\n# from sklearn.datasets import make_classification\n\n# X, y = make_classification(n_samples=1000, n_features=4,\n# n_informative=2, n_redundant=0,\n# random_state=0, shuffle=False)\nX = [x12, x13, x14, x23, x24, x34]\ny = [True, False, True, False, True, False]\nclf = RandomForestClassifier(n_estimators=15, max_depth=2,\n random_state=0)\nclf.fit(X, y)\n\nprint(clf.feature_importances_)\n\nattr5_features, _ = feature_extractor([attr5], [attr5_name])\nx25 = array(attr5_features) - array(attr2_features)\n\nprint(clf.predict([x25]))","sub_path":"tutorial_data_distribution/data_distribution.py","file_name":"data_distribution.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"80169812","text":"# --------------------------------------------------------------------------\n# ----------------------- Rozpoznawanie Obrazow --------------------------\n# --------------------------------------------------------------------------\n# Zadanie 3: Regresja logistyczna\n# autorzy: A. Gonczarek, J. Kaczmar, S. Zareba\n# 2017\n# --------------------------------------------------------------------------\n\nimport numpy as np\nfrom sklearn.metrics import f1_score\n\ndef sigmoid(x):\n '''\n :param x: wektor wejsciowych wartosci Nx1\n :return: wektor wyjściowych wartości funkcji sigmoidalnej dla wejścia x, Nx1\n '''\n\n sigmoid_vector = 1/(1+np.exp(-x))\n return sigmoid_vector\n\n\ndef logistic_cost_function(w, x_train, y_train):\n '''\n :param w: parametry modelu Mx1\n :param x_train: ciag treningowy - wejscia NxM\n :param y_train: ciag treningowy - wyjscia Nx1\n :return: funkcja zwraca krotke (val, grad), gdzie val oznacza wartosc funkcji logistycznej, a grad jej gradient po w\n '''\n val=0\n grad = np.zeros((len(w),1))\n\n for i in range(len(y_train)):\n a = x_train[i,:]@w\n sig = sigmoid(a)\n part_of_grad = (sig - y_train[i]) * np.transpose(x_train[i, :])\n part_of_grad = np.reshape(part_of_grad,(len(w),1))\n value = (-(y_train[i]* np.log(sig) + (1 - y_train[i]) * np.log(1 - sig)))\n val = val + value\n grad = grad + part_of_grad\n\n grad = grad/len(y_train)\n val = float(val)/len(y_train)\n\n return val,grad\n\n\ndef gradient_descent(obj_fun, w0, epochs, eta):\n '''\n :param obj_fun: funkcja celu, ktora ma byc optymalizowana. Wywolanie val,grad = obj_fun(w).\n :param w0: punkt startowy Mx1\n :param epochs: liczba epok / iteracji algorytmu\n :param eta: krok uczenia\n :return: funkcja wykonuje optymalizacje metoda gradientu prostego dla funkcji obj_fun. Zwraca krotke (w,func_values),\n gdzie w oznacza znaleziony optymalny punkt w, a func_valus jest wektorem wartosci funkcji [epochs x 1] we wszystkich krokach algorytmu\n '''\n func_values = []\n\n w = w0\n\n for i in range(epochs):\n grad = obj_fun(w)[1]\n w = w + (eta * (-1) * grad)\n func_values.append(obj_fun(w)[0])\n\n func_values = np.array(func_values)\n func_values = np.reshape(func_values,(epochs,1))\n\n return w, func_values\n\ndef stochastic_gradient_descent(obj_fun, x_train, y_train, w0, epochs, eta, mini_batch):\n '''\n :param obj_fun: funkcja celu, ktora ma byc optymalizowana. Wywolanie val,grad = obj_fun(w,x,y), gdzie x,y oznaczaja podane\n podzbiory zbioru treningowego (mini-batche)\n :param x_train: dane treningowe wejsciowe NxM\n :param y_train: dane treningowe wyjsciowe Nx1\n :param w0: punkt startowy Mx1\n :param epochs: liczba epok\n :param eta: krok uczenia\n :param mini_batch: wielkosc mini-batcha\n :return: funkcja wykonuje optymalizacje metoda stochastycznego gradientu prostego dla funkcji obj_fun. Zwraca krotke (w,func_values),\n gdzie w oznacza znaleziony optymalny punkt w, a func_values jest wektorem wartosci funkcji [epochs x 1] we wszystkich krokach algorytmu. Wartosci\n funkcji do func_values sa wyliczane dla calego zbioru treningowego!\n '''\n w = w0\n M = x_train.shape[0]/mini_batch\n M=int(M)\n func_values = []\n\n for k in range(epochs):\n for m in range(M):\n x = x_train[0+m*mini_batch:(m+1)*mini_batch,:]\n y = y_train[0+m*mini_batch:(m+1)*mini_batch,:]\n grad = obj_fun(w,x,y)[1]\n w = w + eta*(-1)*grad\n func_values.append(obj_fun(w, x_train, y_train)[0])\n\n func_values = np.array(func_values)\n func_values = np.reshape(func_values,(epochs,1))\n\n return w, func_values\n\ndef regularized_logistic_cost_function(w, x_train, y_train, regularization_lambda):\n '''\n :param w: parametry modelu Mx1\n :param x_train: ciag treningowy - wejscia NxM\n :param y_train: ciag treningowy - wyjscia Nx1\n :param regularization_lambda: parametr regularyzacji\n :return: funkcja zwraca krotke (val, grad), gdzie val oznacza wartosc funkcji logistycznej z regularyzacja l2,\n a grad jej gradient po w\n '''\n\n val = logistic_cost_function(w,x_train,y_train)[0]\n val += (regularization_lambda / 2) * np.linalg.norm(w[1:], ord=2) ** 2\n grad = np.zeros((len(w), 1))\n\n for i in range(len(y_train)):\n a = x_train[i,:]@w\n sig = sigmoid(a)\n grad_w0 = (sig - y_train[i]) * np.transpose(x_train[i, 0])\n grad_w_rest = (sig - y_train[i]) * np.transpose(x_train[i, 1:])\n grad_w_rest = np.reshape(grad_w_rest,(grad_w_rest.shape[0],1))\n grad_w_rest += regularization_lambda*w[1:]\n grad_w = np.vstack((grad_w0,grad_w_rest))\n grad += grad_w\n\n grad /= len(y_train)\n\n return val,grad\n\n\ndef prediction(x, w, theta):\n '''\n :param x: macierz obserwacji NxM\n :param w: wektor parametrow modelu Mx1\n :param theta: prog klasyfikacji z przedzialu [0,1]\n :return: funkcja wylicza wektor y o wymiarach Nx1. Wektor zawiera wartosci etykiet ze zbioru {0,1} dla obserwacji z x\n bazujac na modelu z parametrami w oraz progu klasyfikacji theta\n '''\n y = np.zeros((x.shape[0],1))\n\n for n in range(x.shape[0]):\n if sigmoid(x[n,:]@w) >= theta:\n y[n] = 1\n\n return y\n\ndef f_measure(y_true, y_pred):\n '''\n :param y_true: wektor rzeczywistych etykiet Nx1\n :param y_pred: wektor etykiet przewidzianych przed model Nx1\n :return: funkcja wylicza wartosc miary F\n '''\n F = f1_score(y_true,y_pred,average ='binary')\n\n return F\n\n\ndef model_selection(x_train, y_train, x_val, y_val, w0, epochs, eta, mini_batch, lambdas, thetas):\n '''\n :param x_train: ciag treningowy wejsciowy NxM\n :param y_train: ciag treningowy wyjsciowy Nx1\n :param x_val: ciag walidacyjny wejsciowy Nval x M\n :param y_val: ciag walidacyjny wyjsciowy Nval x 1\n :param w0: wektor poczatkowych wartosci parametrow\n :param epochs: liczba epok dla SGD\n :param eta: krok uczenia\n :param mini_batch: wielkosc mini batcha\n :param lambdas: lista wartosci parametru regularyzacji lambda, ktore maja byc sprawdzone\n :param thetas: lista wartosci progow klasyfikacji theta, ktore maja byc sprawdzone\n :return: funckja wykonuje selekcje modelu. Zwraca krotke (regularization_lambda, theta, w, F), gdzie regularization_lambda\n to najlpszy parametr regularyzacji, theta to najlepszy prog klasyfikacji, a w to najlepszy wektor parametrow modelu.\n Dodatkowo funkcja zwraca macierz F, ktora zawiera wartosci miary F dla wszystkich par (lambda, theta). Do uczenia nalezy\n korzystac z algorytmu SGD oraz kryterium uczenia z regularyzacja l2.\n '''\n\n F_array = []\n w=w0\n for hparameter in lambdas:\n obj_fun = lambda w,x_train,y_train: regularized_logistic_cost_function(w,x_train,y_train,hparameter)\n w = stochastic_gradient_descent(obj_fun,x_train,y_train,w0,epochs,eta,mini_batch)[0]\n F_array_row = []\n for theta in thetas:\n y_pred = prediction(x_val, w,theta)\n F_array_row.append(f_measure(y_val,y_pred))\n w=w0\n F_array.append(F_array_row)\n\n\n F_array = np.array(F_array)\n HP_best = np.max(F_array)\n HP_indices = np.where(HP_best == F_array)\n regularization_lambda = lambdas[HP_indices[0][0]]\n theta = thetas[HP_indices[1][0]]\n obj_fun = lambda w, x_train, y_train: regularized_logistic_cost_function(w, x_train, y_train, regularization_lambda)\n w = stochastic_gradient_descent(obj_fun, x_train, y_train, w0, epochs, eta, mini_batch)[0]\n\n return regularization_lambda,theta,w,F_array","sub_path":"lab3_python/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":7616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"75049918","text":"#!/usr/bin/env python\n# Copyright 1983-2020 Keysight Technologies\nfrom __future__ import print_function\nimport argparse\nimport json\nimport os\nimport re\nimport shlex\nimport signal\nimport stat\nimport subprocess\nimport sys\nimport tempfile\n\n\ntry:\n from subprocess import STDOUT, check_output, CalledProcessError\nexcept ImportError: # pragma: no cover\n # python 2.6 doesn't include check_output\n # monkey patch it in!\n import subprocess\n STDOUT = subprocess.STDOUT\n\n def check_output(*popenargs, **kwargs):\n if 'stdout' in kwargs: # pragma: no cover\n raise ValueError('stdout argument not allowed, '\n 'it will be overridden.')\n process = subprocess.Popen(stdout=subprocess.PIPE,\n *popenargs, **kwargs)\n output, _ = process.communicate()\n retcode = process.poll()\n if retcode:\n cmd = kwargs.get(\"args\")\n if cmd is None:\n cmd = popenargs[0]\n raise subprocess.CalledProcessError(retcode, cmd,\n output=output)\n return output\n subprocess.check_output = check_output\n\n # overwrite CalledProcessError due to `output`\n # keyword not being available (in 2.6)\n class CalledProcessError(Exception):\n\n def __init__(self, returncode, cmd, output=None):\n self.returncode = returncode\n self.cmd = cmd\n self.output = output\n\n def __str__(self):\n return \"Command '%s' returned non-zero exit status %d\" % (\n self.cmd, self.returncode)\n subprocess.CalledProcessError = CalledProcessError\n\n\nclass SiteCluster(object):\n\n # SiteCluster version\n __version__ = ['core_1']\n\n def __init__(self, use_argv=True, ignore_user=True):\n '''\n Constructor\n '''\n if not use_argv:\n return\n\n self.ignore_user = ignore_user\n\n parser = argparse.ArgumentParser(\n description='site cluster',\n usage='''sitecluster []\n\nThe supported sitecluster commands are:\n api Returns the sitecluster api version, minimum version is 'core_1'.\n queues Returns a list with queues, one queue on each line.\n submit [] -- Submits a job to the site cluster.\n supported submit options:\n [--queue=] Queue on which the job should run (Optional).\n [--nodes=] Number of nodes to be reserved for the job (Optional).\n [--threads=] Number of threads per node requested for this job (Optional).\n [--memory=] Maximum amount of physical memory used by the job (Optional).\n [--jobname=] Name of the job (Optional).\n [--email=] List of email addresses to notify, format user[@host][,user[@host],...] (Optional).\n [--attime=] Time after which the job is eligible for execution, format [[[[CC]YY]MM]DD]hhmm[.SS] (Optional).\n [--endtime=] End time of the job, format [[[[CC]YY]MM]DD]hhmm[.SS] (Optional).\n [--after=] List of jobs to wait for, format ['j1'.j2] (Optional).\n [--startnode=] Number of node to run sub process directly (Optional).\n [--user=] Submit job as user with name (only available if allowed by system)\n [--project=] add a project/account name on submit when available (Optional).\n [--group=] add a group name for submit when available (Optional).\n [--customargs=] Custom submit arguments for the job. Repeated occurences append customargs content. (Optional)\n status ['-e','--add-exit-status'] Returns the status of the job with identifier on the cluster,\n supported states are 'PENDING', 'RUNNING', 'SUSPENDED', 'COMPLETED' and UNKNOWNID.\n Optional options -e and --exit adds an optional exit status as provided by the cluster system\n kill [ ...] Kills the jobs with the specied s.\n nodecount Returns the total number of nodes allocated to the job. Only usable within a job's environment.\n startnode Starts the command with arguments on node .\n behavior Returns default behavior specifications.\n''')\n parser.add_argument('command', choices=['api', 'queues', 'submit', 'status', 'kill', 'nodecount', 'startnode', 'behavior'],\n help='Subcommand to run')\n args = parser.parse_args(sys.argv[1:2])\n # use dispatch pattern to invoke method with same name\n getattr(self, args.command)()\n\n def api(self):\n '''\n Prints the site cluster api version.\n '''\n for version in SiteCluster.__version__:\n print(version)\n\n def queues(self):\n '''\n Prints the available queues.\n '''\n queues = self.getQueues()\n for queue in queues:\n print(queue)\n\n def submit(self):\n '''\n Submits a job to the cluster.\n '''\n parser = argparse.ArgumentParser(description='submit', usage='%(prog)s submit [options] -- cmdargs')\n parser.add_argument('--queue', help='Queue on which the job should run (Optional).')\n parser.add_argument('--nodes', type=int, metavar='', help='Number of nodes to be reserved for exclusive use by the job (Optional).')\n parser.add_argument('--threads', type=int, metavar='', help='Number of threads per node requested for this job (Optional).')\n parser.add_argument('--memory', help='Maximum amount of physical memory used by the job (Optional).')\n parser.add_argument('--jobname', help='Name of the job (Optional).')\n parser.add_argument('--email', help='List of email addresses to notify, format user[@host][,user[@host],...] (Optional).')\n parser.add_argument('--attime', help='Time after which the job is eligible for execution, format [[[[CC]YY]MM]DD]hhmm[.SS] (Optional).')\n parser.add_argument('--endtime', help='End time of the job, format [[[[CC]YY]MM]DD]hhmm[.SS] (Optional).')\n parser.add_argument('--after', help=\"List of jobs to wait for, format ['j1'.j2] (Optional).\")\n parser.add_argument('--project', help=\"Project/account setting for cluster system if available (Optional).\")\n parser.add_argument('--group', help=\"Groupname setting for cluster system if available (Optional).\")\n parser.add_argument('--customargs', action='append', help='Custom submit arguments for the job. (Optional).')\n parser.add_argument('--startnode', type=int, metavar='', help='Number of node to run sub process within a job just as with startnode command. (Optional).')\n parser.add_argument('--user', help='Defines the user name under which the job is to run on the execution system if allowed by workload system (Optional).')\n parser.add_argument('cmdargs', nargs=argparse.REMAINDER)\n if not sys.argv[2:]:\n parser.print_help()\n args = parser.parse_args(sys.argv[2:])\n cmdargs = None\n if len(args.cmdargs) > 1 and args.cmdargs[0] == '--':\n cmdargs = args.cmdargs[1:]\n if not hasattr(self, 'submitJob'):\n parser.print_help()\n else:\n print(self.submitJob(args, cmdargs))\n\n def status(self):\n '''\n Returns the status of a job.\n '''\n parser = argparse.ArgumentParser(description='status', usage='%(prog)s status [options] jobId')\n parser.add_argument('-e', '--add-exit-status', dest='addStatus', action='store_true', help='Return the job exit status when available after COMPLETED')\n parser.add_argument('jobId')\n if not sys.argv[2:]:\n parser.print_help()\n args = parser.parse_args(sys.argv[2:])\n if not hasattr(self, 'getJobStatus'):\n parser.print_help()\n else:\n print(self.getJobStatus(args.jobId, args.addStatus))\n\n def kill(self):\n '''\n Kills a job.\n '''\n parser = argparse.ArgumentParser(description='kill', usage='%(prog)s kill jobId [jobId ...]')\n parser.add_argument('jobId', nargs='+', help='Kills the jobs with the specied s')\n if not sys.argv[2:]:\n parser.print_help()\n args = parser.parse_args(sys.argv[2:])\n if not hasattr(self, 'killJob'):\n parser.print_help()\n else:\n print(self.killJob(args.jobId))\n\n def nodecount(self):\n print(self.getNodeCount())\n\n def startnode(self):\n self.startNode(sys.argv[2], sys.argv[3:])\n\n def behavior(self):\n behavior = {}\n\n ## qbehave mode:\n # behavior = {\n # 'alpha': {\n # 'command_argument_string': '',\n # 'allow_user_command_argument_string_suffix': True,\n # },\n # 'beta': {\n # 'mapping': [\n # {\n # 'memory': [0,5],\n # 'command_argument_string': '',\n # },\n # {\n # 'memory': [5,50],\n # 'command_argument_string': '',\n # }\n # # ...\n # ],\n # 'allow_user_command_argument_string_suffix': True,\n # },\n # 'omega': {\n # 'command_argument_string': '',\n # 'allow_user_command_argument_string_suffix': True,\n # },\n # }\n\n print(json.dumps(behavior))\n\nclass PBSSiteCluster(SiteCluster):\n\n def __init__(self, use_argv=True, ignore_user=True):\n SiteCluster.__init__(self, use_argv=use_argv, ignore_user=ignore_user)\n\n def getQueues(self):\n cmd = ['qstat', '-Q']\n reAnsw = r'([a-zA-Z0-9_\\.-]+)[ ]*([0-9]+).*'\n queueNames = []\n for s in [s.strip() for s in subprocess.check_output(cmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n queueNames.append(reMatch.group(1))\n return queueNames\n\n def submitJob(self, options, cmdargs):\n # sub job start within job\n if options.startnode:\n self.startNode(options.startnode, cmdargs)\n return str(int(os.environ['PBS_JOBID']))\n\n submitCmd = ['qsub', '-V', '-W', 'umask=022']\n # destination queue of the job\n if options.queue:\n submitCmd += ['-q', options.queue]\n # name of the job\n if options.jobname:\n submitCmd += ['-N', options.jobname]\n # resources\n resources = []\n if options.nodes:\n # number of nodes to be reserved for the job.\n resources += ['nodes=%d'% options.nodes]\n if options.threads:\n # the number of virtual processors/threads per node requested for this job\n resources += ['ppn=%d'% options.threads]\n if options.memory:\n # maximum amount of physical memory used by any single process of the job\n resources += ['pmem=%s'% options.memory]\n if resources:\n submitCmd += ['-l', ':'.join(resources)]\n # list of email addresses to notify\n if options.email:\n submitCmd += ['-M', options.email]\n # email is sent by default on following events:\n # a - when the job is aborted by the batch system.\n # b - when the job begins execution.\n # e - when the job terminates.\n submitCmd += ['-m', 'abe']\n # time after which the job is eligible for execution\n if options.attime:\n submitCmd += ['-a', options.attime]\n # time when the job should be finished\n if options.endtime:\n submitCmd += ['-dl', options.endtime]\n # dependency between other jobs\n if options.after:\n afterJobs = eval(options.after)\n if afterJobs != []:\n submitCmd += ['-W', 'depend=after:%s' % \":\".join(afterJobs)]\n # submit as specific user (typically only allowed for administrators)\n if not self.ignore_user and options.user:\n submitCmd += ['-u', options.user]\n # PBS has no project option using account option instead\n if options.project:\n submitCmd += ['-A', options.project]\n if options.group:\n submitCmd += ['-W', 'group_list=%s'% options.group]\n # custom arguments is an array need to decide how to process\n # TODO need to decide how to process arguments if duplicates are not allowed\n if options.customargs:\n customArgArray = []\n # just append when multiple customargs arguments existed\n for entry in options.customargs:\n customArgArray += shlex.split(entry, posix=False)\n submitCmd += customArgArray\n # the command to submit and its arguments\n submitCmd += cmdargs\n # perform the job submission\n res = ''\n reAnsw = r'(^\\d+\\.[\\w\\.\\-]+).*'\n for s in [s for s in subprocess.check_output(submitCmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n res = str(reMatch.group(1))\n return res\n\n def getJobStatus(self, idOnCluster, addStatus=False):\n cmd = ['qstat', '-f', idOnCluster]\n try:\n # stderr=subprocess.STDOUT redirection is needed for getting the \"Unknown Job Id\" in err.output\n output = [s for s in subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()]\n except CalledProcessError as err:\n print(err.output, file=sys.stderr)\n # PBS error code PBSE_UNKJOBID = 15001; PBSE_UNKJOBID mod 256 = 153\n if err.returncode == 153 or \"Unknown Job Id\" in err.output:\n return \"UNKNOWNID\"\n raise\n\n reAnsw = r'\\s+job_state\\s+=\\s+([BEHQRSTUWX])'\n rstate = ''\n for s in output:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n rstate = reMatch.group(1)\n break\n jobStatus = 'COMPLETED'\n if rstate == '':\n jobStatus = 'COMPLETED'\n elif rstate in 'QW':\n jobStatus = 'PENDING'\n elif rstate in 'BR':\n jobStatus = 'RUNNING'\n elif rstate in 'HTU':\n jobStatus = 'SUSPENDED'\n elif rstate == 'EX':\n jobStatus = 'COMPLETED'\n\n if addStatus and jobStatus == 'COMPLETED':\n exitStatus = '0'\n reAnsw = r'\\s+exit_status\\s+=\\s+([0-9]+)'\n for s in output:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n exitStatus = reMatch.group(1)\n break\n jobStatus += ' ' + exitStatus\n return jobStatus\n\n def killJob(self, idsOnCluster):\n try:\n output = subprocess.check_output(['qdel'] + [str(x) for x in idsOnCluster], stderr=subprocess.STDOUT, universal_newlines=True).splitlines()\n except CalledProcessError as e:\n output = e.output.splitlines()\n if output:\n for jobId in idsOnCluster:\n res = ''\n for l in output:\n if str(jobId) in l:\n res = l\n if not res:\n continue\n reAnsw = r'Request invalid for state of job.*COMPLETE\\s+{}'.format(jobId)\n reMatch = re.search(reAnsw, res)\n if reMatch:\n continue\n reAnsw = r'nonexistent job id'\n reMatch = re.search(reAnsw, res)\n if reMatch:\n continue\n return 1\n return 0\n\n def getNodeCount(self):\n return str(int(os.environ['PBS_NUM_NODES']))\n\n def startNode(self, num, cmdargs):\n subprocess.check_call(['pbsdsh', '-n', str(int(num))] + cmdargs)\n\nclass LSFSiteCluster(SiteCluster):\n\n def __init__(self, use_argv=True):\n SiteCluster.__init__(self, use_argv=use_argv)\n\n def getQueues(self):\n cmd = ['bqueues', '-w']\n reAnsw = r'([a-zA-Z0-9_-]+)[ ]*([0-9]+).*'\n queueNames = []\n for s in [s.strip() for s in subprocess.check_output(cmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n queueNames.append(reMatch.group(1))\n return queueNames\n\n def submitJob(self, options, cmdargs):\n # sub job start within job\n if options.startnode:\n self.startNode(options.startnode, cmdargs)\n return str(int(os.environ['PBS_JOBID']))\n\n submitCmd = ['bsub']\n # destination queue of the job\n if options.queue:\n submitCmd += ['-q', options.queue]\n # name of the job\n if options.jobname:\n submitCmd += ['-J', options.jobname]\n # resources\n if options.nodes:\n # number of hosts required to run the job\n submitCmd += ['-n', str(options.nodes)]\n if options.threads:\n ## limit of the number of concurrent threads to thread_limit for the whole job\n # submitCmd += ['-T', str(options.threads)]\n pass\n if options.memory:\n # per-process physical memory limit for all of the processes belonging to a job\n # specified in KB\n submitCmd += ['-M', str(options.memory)]\n # list of email addresses to notify\n if options.email:\n submitCmd += ['-u', options.email]\n # email is sent by default on following events:\n # -B - when the job is dispatched and begins execution..\n # -N - when the job finishes.\n submitCmd += ['-B', '-N']\n # time after which the job is eligible for execution\n if options.attime:\n submitCmd += ['-b', options.attime]\n # time when the job should be finished\n if options.endtime:\n submitCmd += ['-t', options.endtime]\n # dependency between other jobs\n if options.after:\n afterJobs = eval(options.after)\n if afterJobs != []:\n submitCmd += ['-w', '\\\"ended(' + '|'.join(afterJobs) + ')\\\"']\n # project options for submit\n if options.project:\n submitCmd += ['-P', options.project]\n # group option for submit\n if options.group:\n submitCmd += ['-G', options.group]\n # custom arguments is an array \n # TODO need to decide how to process arguments if duplicates are not allowed\n if options.customargs:\n customArgArray = []\n # just append when multiple customargs arguments existed\n for entry in options.customargs:\n customArgArray += shlex.split(entry, posix=False)\n submitCmd += customArgArray\n # the command to submit and its arguments\n if cmdargs and ' ' in cmdargs[0]:\n # LSF does not quote command correctly if containing spaces\n # execute as shell command with arguments instead\n submitCmd += ['/bin/bash']\n submitCmd += cmdargs\n # perform the job submission\n res = ''\n reAnsw = r'Job\\s+<([0-9]+)>.*'\n for s in [s for s in subprocess.check_output(submitCmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n res = str(reMatch.group(1))\n return res\n\n def getJobStatus(self, idOnCluster, addStatus=False):\n cmd = ['bjobs', '-a', idOnCluster]\n reAnsw = r'\\s*{}\\s+\\S+\\s+(\\w+)\\s+.*'.format(idOnCluster)\n reAnswUnk = r'Job\\s*<{}>\\s*is not found'.format(idOnCluster)\n rstate = ''\n reMatchUnk = None\n for s in [s for s in subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n rstate = reMatch.group(1)\n break\n reMatchUnk = re.match(reAnswUnk, s)\n if reMatchUnk:\n break\n jobStatus = 'COMPLETED'\n if rstate == 'EXIT' or reMatchUnk:\n jobStatus = 'COMPLETED'\n exitStatus = 0\n cmdhist = ['bhist', '-la', idOnCluster]\n reAnsw = r'.*: Exited with exit code\\s*(\\d+).*'\n answSucces = 'Done successfully'\n answUnk = 'No matching job found'\n try:\n output = [s for s in subprocess.check_output(cmdhist, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()]\n except CalledProcessError as err:\n # LSF error code is always 255 so just look for string\n if answUnk in err.output:\n return \"UNKNOWNID\"\n raise\n\n for s in output:\n if answSucces in s:\n exitStatus = 0\n break\n if answUnk in s:\n jobStatus = 'UNKNOWNID'\n break\n reMatch = re.match(reAnsw, s)\n if reMatch:\n exitStatus = reMatch.group(1)\n break\n if addStatus:\n jobStatus += ' ' + str(exitStatus)\n elif rstate == 'PEND':\n jobStatus = 'PENDING'\n elif rstate == 'RUN':\n jobStatus = 'RUNNING'\n elif rstate == 'SUSP':\n jobStatus = 'SUSPENDED'\n elif rstate == 'DONE':\n if addStatus:\n jobStatus = 'COMPLETED 0'\n else:\n jobStatus = 'COMPLETED'\n return jobStatus\n\n def killJob(self, idsOnCluster):\n cmd = ['bkill'] + [str(x) for x in idsOnCluster]\n try:\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()\n except CalledProcessError as e:\n output = e.output.splitlines()\n for jobId in idsOnCluster:\n res = ''\n for l in output:\n if str(jobId) in l:\n res = l\n break\n if not res:\n continue\n reAnsw = r'Job\\s+<{}>\\s+is being terminated'.format(jobId)\n reMatch = re.search(reAnsw, res)\n if reMatch:\n continue\n reAnsw = r'Job has already finished'\n reMatch = re.search(reAnsw, res)\n if reMatch:\n # job has already finished\n continue\n return 1\n return 0\n\n def __getLSBHosts(self):\n if 'LSB_MCPU_HOSTS' in os.environ:\n # host, slot number pairs\n return (True, os.environ['LSB_MCPU_HOSTS'].split(' '))\n else:\n # list with host names\n return (False, os.environ['LSB_HOSTS'].split(' '))\n\n def getNodeCount(self):\n isShortHostnameSlotFormat, slots = self.__getLSBHosts()\n if isShortHostnameSlotFormat:\n return sum([int(y) for x, y in enumerate(slots) if x%2])\n else:\n return len(slots)\n\n def startNode(self, num, cmdargs):\n isShortHostnameSlotFormat, slots = self.__getLSBHosts()\n if isShortHostnameSlotFormat:\n slots = sum([[slots[x]]*int(slots[x+1]) for x, _ in enumerate(slots) if x%2 != 1], [])\n subprocess.check_call(['blaunch', slots[int(num)]] + cmdargs)\n\nclass SunGridEngineSiteCluster(SiteCluster):\n\n def __init__(self, use_argv=True):\n SiteCluster.__init__(self, use_argv=use_argv)\n\n def getQueues(self):\n cmd = ['qconf', '-sql']\n reAnsw = r'([a-zA-Z0-9_\\.-]+)$'\n queueNames = []\n for s in [s.strip() for s in subprocess.check_output(cmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n queueNames.append(reMatch.group(1))\n return queueNames\n\n def submitJob(self, options, cmdargs):\n # sub job start within job\n if options.startnode:\n self.startNode(options.startnode, cmdargs)\n return str(int(os.environ['JOB_ID']))\n\n submitCmd = ['qsub', '-V']\n # destination queue of the job\n if options.queue:\n submitCmd += ['-q', options.queue]\n # name of the job\n if options.jobname:\n submitCmd += ['-N', options.jobname]\n # resources\n resources = []\n if options.nodes:\n # number of nodes to be reserved for the job.\n resources += ['nodes=%d'% options.nodes]\n if options.memory:\n # per-process maximum memory limit in bytes.\n resources += ['s_vmem=%s'% options.memory]\n if resources:\n submitCmd += ['-l', ':'.join(resources)]\n # list of email addresses to notify\n if options.email:\n submitCmd += ['-M', options.email]\n # email is sent by default on following events:\n # a - when the job is aborted by the batch system.\n # b - when the job begins execution.\n # e - when the job terminates.\n submitCmd += ['-m', 'abe']\n # time after which the job is eligible for execution\n if options.attime:\n submitCmd += ['-a', options.attime]\n # time when the job should be finished\n if options.endtime:\n submitCmd += ['-dl', options.endtime]\n # dependency between other jobs\n if options.after:\n afterJobs = eval(options.after)\n if afterJobs != []:\n submitCmd += ['-W', 'depend=after:%s' % \":\".join(afterJobs)]\n\n # project options for submit\n if options.project:\n submitCmd += ['-P', options.project]\n # group option for submit doesn't exist in SGE\n if options.group:\n submitCmd += ['-A', options.group]\n # custom arguments is an array \n # TODO need to decide how to process arguments if duplicates are not allowed\n if options.customargs:\n customArgArray = []\n # just append when multiple customargs arguments existed\n for entry in options.customargs:\n customArgArray += shlex.split(entry, posix=False)\n submitCmd += customArgArray\n # the command to submit and its arguments\n submitCmd += cmdargs\n # perform the job submission\n res = ''\n reAnsw = r'[Yy]our job[ ]+([0-9]+).*'\n for s in [s for s in subprocess.check_output(submitCmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n res = str(reMatch.group(1))\n return res\n\n def __getQacctStatus(self, idOnCluster):\n cmdhist = ['qacct', '-j', idOnCluster]\n answUnk = \"job id %s not found\" % idOnCluster\n try:\n output = [s for s in subprocess.check_output(cmdhist, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()]\n except CalledProcessError as err:\n # LSF error code is always 255 so just look for string\n if answUnk in err.output:\n return \"UNKNOWNID\"\n raise\n\n for field in output:\n if 'exit_status' in field:\n return field.strip().split()[1]\n return \"UNKNOWNID\" # not found\n\n def getJobStatus(self, idOnCluster, addStatus=False):\n cmd = ['qstat']\n reAnsw = r'\\s+{}\\s+[\\d\\.]+\\s+\\S+\\s+\\S+\\s+(\\S+)\\s+.*'.format(idOnCluster)\n rstate = ''\n for s in [s for s in subprocess.check_output(cmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n rstate = reMatch.group(1)\n break\n jobStatus = 'PENDING'\n if rstate == '':\n jobStatus = 'RUNNING'\n qacct_code = self.__getQacctStatus(str(idOnCluster))\n if qacct_code == \"UNKNOWNID\":\n return qacct_code\n if qacct_code == '0':\n if addStatus:\n jobStatus = 'COMPLETED 0'\n else:\n jobStatus = 'COMPLETED'\n else:\n if addStatus:\n jobStatus = 'COMPLETED ' + qacct_code # non-zero exit status\n else:\n jobStatus = 'COMPLETED'\n elif rstate == 'r':\n jobStatus = 'RUNNING'\n return jobStatus\n\n def killJob(self, idsOnCluster):\n cmd = ['qdel'] + [ str(x) for x in idsOnCluster ]\n try:\n output = subprocess.check_output(cmd, universal_newlines=True).splitlines()\n except CalledProcessError as e:\n output = e.output.splitlines()\n for jobId in idsOnCluster:\n res = ''\n for l in output:\n if str(jobId) in l:\n res = l\n break\n if not res:\n continue\n reAnsw = r'(has registered the job\\s+{}\\s+for deletion)'.format(jobId)\n reMatch = re.search(reAnsw, res)\n if reMatch:\n # job was already killed\n continue\n reAnsw = r'^(denied:)'\n reMatch = re.search(reAnsw, res)\n if reMatch:\n # job has already finished\n continue\n return 1\n return 0\n\n def __getPEHosts(self):\n if 'PE_HOSTFILE' in os.environ:\n # host, slot number pairs\n return os.environ['PE_HOSTFILE'].split(' ')\n return None\n\n def getNodeCount(self):\n slots = self.__getPEHosts()\n if slots:\n return sum([int(y) for x, y in enumerate(slots) if x%2])\n return 0\n\n def startNode(self, num, cmdargs):\n slots = self.__getPEHosts()\n if slots:\n slots = sum([[slots[x]]*int(slots[x+1]) for x, _ in enumerate(slots) if x%2 != 1], [])\n subprocess.check_call(['qrsh', '-inherit', slots[int(num)]] + cmdargs)\n\n\nclass SlurmSiteCluster(SiteCluster):\n def __init__(self, use_argv=True, ignore_user=True):\n SiteCluster.__init__(self, use_argv=use_argv, ignore_user=ignore_user)\n\n def getQueues(self):\n cmd = ['sinfo', '-s', '--noheader']\n reAnsw = r'\\s*([a-zA-Z0-9_\\.-]+)\\*?'\n queueNames = []\n for s in [s.strip() for s in subprocess.check_output(cmd, universal_newlines=True).splitlines()]:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n queueNames.append(reMatch.group(1))\n return queueNames\n\n def submitJob(self, options, cmdargs):\n # sub job start within job\n if hasattr(options, 'startnode') and options.startnode:\n self.startNode(options.startnode, cmdargs)\n return str(int(os.environ['PBS_JOBID']))\n\n submitCmd = ['sbatch', '-v'] #, '-W', 'umask=022']\n # destination queue of the job\n if options.queue:\n submitCmd += ['--partition', options.queue]\n # name of the job\n if options.jobname:\n submitCmd += ['--job-name', options.jobname]\n # resources\n resources = []\n if options.nodes:\n # number of nodes to be reserved for the job.\n resources += ['--nodes={:d}'.format(options.nodes)]\n if options.threads:\n # the number of virtual processors/threads per node requested for this job\n resources += ['--cpus-per-task={}'.format(options.threads)]\n if options.memory:\n # maximum amount of physical memory used by any single process of the job\n resources += ['--mem={}'.format(options.memory)]\n if resources:\n submitCmd += ['-l', ':'.join(resources)]\n # list of email addresses to notify\n if options.email:\n submitCmd += ['--mail-user', options.email]\n # email is sent by default on following events:\n # a - when the job is aborted by the batch system.\n # b - when the job begins execution.\n # e - when the job terminates.\n submitCmd += ['--mail-type', 'ALL']\n # time after which the job is eligible for execution\n if options.attime:\n submitCmd += ['--begin', options.attime]\n # time when the job should be finished\n if options.endtime:\n submitCmd += ['--deadline', options.endtime]\n # dependency between other jobs\n if options.after:\n afterJobs = eval(options.after)\n if afterJobs != []:\n submitCmd += ['--dependency=after:%s' % \":\".join(afterJobs)]\n\n # submit as specific user (typically only allowed for administrators)\n if not self.ignore_user and options.user:\n submitCmd += ['--uid', options.user]\n\n # custom arguments\n if options.customargs:\n for customargs in options.customargs:\n submitCmd += shlex.split(customargs, posix=False)\n\n # the command to submit and its arguments\n if cmdargs:\n submitCmd += cmdargs\n\n # perform the job submission\n for line in subprocess.check_output(submitCmd, universal_newlines=True).splitlines():\n reMatch = re.match(r'Submitted batch job\\s+([0-9]+).*', line.strip())\n if reMatch:\n return reMatch.group(1)\n return ''\n\n def getJobStatus(self, idOnCluster, addStatus=False):\n import re, subprocess\n cmd = ['squeue', '--noheader', '-j', idOnCluster, '--Format=statecompact', ]\n try:\n # stderr=subprocess.STDOUT redirection is needed for getting the \"Unknown Job Id\" in err.output\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()\n except CalledProcessError as err:\n print(err.output, file=sys.stderr)\n # TODO PBS CODES need to be updated for Slurm\n if err.returncode == 153 or \"Unknown Job Id\" in err.output:\n return \"UNKNOWNID\"\n raise\n\n reAnsw = r'\\s*statecompact\\s*:\\s*([ABCDEFGHILMNOPQRSTV]+)'\n rstate = ''\n for s in output:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n rstate = reMatch.group(1)\n break\n jobStatus = 'COMPLETED'\n exitStatus = '0'\n if rstate == '':\n jobStatus = 'COMPLETED'\n elif rstate in ['PD']:\n jobStatus = 'PENDING'\n elif rstate in ['R', 'SO', 'RS', 'CF', 'CG', 'SI', 'RQ'] :\n jobStatus = 'RUNNING'\n elif rstate in ['RH', 'RF', 'S', 'RD']:\n jobStatus = 'SUSPENDED'\n elif rstate == ['BF', 'CA', 'DL', 'F', 'NF', 'OOM', 'PR', 'TO', 'RQ', 'RV', 'SE', 'ST']:\n jobStatus = 'COMPLETED'\n #TODO refine for all possible error states\n exitStatus = 1\n\n if addStatus and jobStatus == 'COMPLETED':\n jobStatus += ' ' + exitStatus\n return jobStatus\n\n def killJob(self, idsOnCluster):\n cmd = ['scancel'] + idsOnCluster\n try:\n subprocess.check_output(cmd)\n except CalledProcessError:\n return 1\n return 0\n\n def getNodeCount(self):\n cmd = [\"sinfo\", \"-N\", \"-o\", \"%N\", \"--noheader\"]\n output = subprocess.check_output(cmd, universal_newlines=True)\n nodes = set(output.splitlines())\n return len(nodes)\n\n def startNode(self, num, cmdargs):\n # TODO check if this is correct way to do this\n subprocess.check_call(['srun', '-N1', str(int(num))] + cmdargs)\n\n\nclass ProcessSiteCluster(SiteCluster):\n \"\"\"Sitecluster uses normal process execution on local host\"\"\"\n\n def __init__(self, use_argv=True, ignore_user=True):\n SiteCluster.__init__(self, use_argv=use_argv, ignore_user=ignore_user)\n\n def getQueues(self):\n \"\"\"Return a dummy queue name: run_local_process\"\"\"\n return [\"run_local_process\"]\n\n def submitJob(self, options, cmdargs):\n \"\"\"Submit implementated as standard process launch: returning pid of new process\"\"\"\n dir=os.getcwd()\n with tempfile.NamedTemporaryFile(dir=dir) as out, tempfile.NamedTemporaryFile(dir=dir) as err:\n proc = subprocess.Popen(cmdargs, stdout=out, stderr=err, preexec_fn=os.setpgrp, close_fds=True)\n stdout_f = \"stdout.{}.txt\".format(proc.pid)\n os.link(out.name, stdout_f)\n stderr_f = \"stderr.{}.txt\".format(proc.pid)\n os.link(err.name, stderr_f)\n os.chmod(stdout_f, os.stat(stdout_f).st_mode | stat.S_IRGRP | stat.S_IROTH )\n os.chmod(stderr_f, os.stat(stderr_f).st_mode | stat.S_IRGRP | stat.S_IROTH )\n return proc.pid\n\n def getJobStatus(self, idOnCluster, addStatus=False):\n \"\"\"Return status of process exit state always 0 as we cannot know that for terminated process\"\"\"\n cmd = ['ps', '--no-headers', '-o', 'pid,state', '--pid', str(idOnCluster) ]\n try:\n # stderr=subprocess.STDOUT redirection is needed for getting the \"Unknown Job Id\" in err.output\n output = [s for s in subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True).splitlines()]\n except CalledProcessError as err:\n # process is terminated already\n output = err.output\n\n reAnsw = r'\\s*{}\\s*([DRSTtWXZ])'.format(idOnCluster)\n rstate = ''\n for s in output:\n reMatch = re.match(reAnsw, s)\n if reMatch:\n rstate = reMatch.group(1)\n break\n jobStatus = 'COMPLETED'\n exitStatus = '0'\n if rstate == '':\n jobStatus = 'COMPLETED'\n elif rstate in ['D', 'R', 'S'] :\n jobStatus = 'RUNNING'\n elif rstate in ['T', 't', 'Z']:\n jobStatus = 'SUSPENDED'\n elif rstate == ['X']:\n jobStatus = 'COMPLETED'\n exitStatus = 1\n\n if addStatus and jobStatus == 'COMPLETED':\n jobStatus += ' ' + exitStatus\n return jobStatus\n\n def killJob(self, idsOnCluster):\n \"\"\"Kill processes in idsOnCluster list by sending SIGKILL to each of them\"\"\"\n for id in idsOnCluster:\n os.kill(int(id), signal.SIGKILL)\n return 0\n\n def getNodeCount(self):\n \"\"\"Node count returns 1 as we only have local machine\"\"\"\n return 1\n\n def startNode(self, num, cmdargs):\n \"\"\"Starts a local process and return process pid\"\"\"\n # TODO check if this is correct way to do this\n proc = subprocess.Popen(cmdargs, preexec_fn=os.setpgrp, close_fds=True)\n return proc.pid\n\n\nif __name__ == '__main__':\n if 'SITE_CLUSTER_USE_PBS' in os.environ:\n PBSSiteCluster(ignore_user=True)\n elif 'SITE_CLUSTER_USE_LSF' in os.environ:\n LSFSiteCluster()\n elif 'SITE_CLUSTER_USE_SGE' in os.environ:\n SunGridEngineSiteCluster()\n elif 'SITE_CLUSTER_USE_SLURM' in os.environ:\n SlurmSiteCluster()\n elif 'SITE_CLUSTER_USE_SUBPROCESS' in os.environ:\n ProcessSiteCluster()\n else:\n print('ERROR: No sitecluster configuration enabled through a SITE_CLUSTER_USE_{PBS|LSF|SGE|SUBPROCESS} environment variable')\n SiteCluster()\n","sub_path":"Aws-Infra/simserv-cloud/aws-slurm-simserv/sitecluster.py","file_name":"sitecluster.py","file_ext":"py","file_size_in_byte":39792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"242288313","text":"\"\"\"\n맨 위층 7부터 시작해서 아래에 있는 수 중 하나를 선택하여 아래층으로 내려올 때, 이제까지 선택된 수의 합이 최대가 되는 경로를 구하는 프로그램을 작성하라. 아래층에 있는 수는 현재 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다.\n\n삼각형의 크기는 1 이상 500 이하이다. 삼각형을 이루고 있는 각 수는 모두 정수이며, 범위는 0 이상 9999 이하이다.\n\"\"\"\n\n# arr[i][j] : i,j 도착했을 때 최댓값\n# dp[i][j] : max(dp[i-1][j-1], dp[i-1][j]) + arr[i][j]\n\nimport sys\n\nn = int(input())\narr = [[0 for _ in range(n+1)] for i in range(n+1)]\ndp = [[0 for _ in range(n+1)] for i in range(n+1)]\n\nfor i in range(1, n+1):\n nums = list(map(int, sys.stdin.readline().split()))\n for j in range(1, i+1):\n arr[i][j] = nums[j-1]\n\nfor i in range(1, n+1):\n for j in range(1, i+1):\n dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + arr[i][j]\n\nprint(max(dp[-1]))","sub_path":"dp/1932.py","file_name":"1932.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521716604","text":"tree = {\n \"name\": \"chodidlo\",\n \"text\": \"Bolesť chodidla\"\n}\n\nareas = [\n {\n \"name\": \"circles-chodidlo-spredu\",\n \"x\": 62,\n \"y\": 545.0952,\n \"width\": 166,\n \"height\": 130,\n },\n {\n \"name\": \"backcircles-chodidlo-zozadu\",\n \"x\": 61.9602,\n \"y\": 545.2499,\n \"width\": 166,\n \"height\": 130,\n },\n]\n\ndiagnoses = [\n {\n \"id\": \"d1\",\n \"name\": \"Plantárna fasciitída\",\n \"svk\": \"zápal alebo stav po zápale šľachy na chodidle\"\n },\n {\n \"id\": \"d2\",\n \"name\": \"Syndróm tarzálneho tunela\",\n \"svk\": \"útlak holenného nervu v oblasti vnútorného členku\"\n },\n {\n \"id\": \"d3\",\n \"name\": \"Reumatoidná artritída\",\n \"svk\": \"Reuma - zápalové ochorenie kĺbov spôsobené nerovnováhou vlastného imunitného systému\"\n },\n {\n \"id\": \"d4\",\n \"name\": \"Mortonov neuróm\",\n \"svk\": \"tekutinová kolekcia alebo zhrubnuté tkanivo obvykle v oblasti medzi 3. a 4. Prstom nohy\"\n },\n {\n \"id\": \"d5\",\n \"name\": \"Dna\",\n \"svk\": \"arthritis uratica – ukladanie kyseliny močovej do kĺbov pri jej nadbytku\"\n },\n {\n \"id\": \"d6\",\n \"name\": \"Burzitída\",\n \"svk\": \"zápal váčku mažúceho kĺb\"\n },\n {\n \"id\": \"d7\",\n \"name\": \"Tendinopatia m. tibialis\",\n \"svk\": \"zápal alebo stav po zápale úponu vretenného svalu predkolenia\"\n },\n {\n \"id\": \"d8\",\n \"name\": \"Syndróm hrany holennej kosti\",\n \"svk\": \"\"\n }\n]\n\nquestions = [\n {\n \"id\": \"q1\",\n \"text\": \"...tŕpnutie v okolí vnútorného členku alebo necitlivosť v oblasti šľapy?\",\n \"prepend_id\": 2,\n \"color_id\": 1\n },\n {\n \"id\": \"q2\",\n \"text\": \"...alebo ste v minulosti trpeli bolesťou chrbta.\",\n \"prepend_id\": 5,\n \"color_id\": 2\n },\n {\n \"id\": \"q3\",\n \"text\": \"... vo Vašom chodidle (zvrchu nohy) prítomná tuhá hrčka? Najčastejšie je to oblasť medzi 4. a 5. \"\n \"palcom.\",\n \"prepend_id\": 4,\n \"color_id\": 1\n },\n {\n \"id\": \"q4\",\n \"text\": \"...je horšia ráno hneď po zobudení a neskôr počas dňa a pri zahriatí sa zmierňuje.\",\n \"prepend_id\": 1,\n \"color_id\": 2\n },\n {\n \"id\": \"q5\",\n \"text\": \"...uchopíte svoje chodidlo do dlane tak, že do nej vložíte svoj nárt a následne ho stlačíte, \"\n \"Vaša bolesť sa zhorší.\",\n \"prepend_id\": 3,\n \"color_id\": 3\n },\n {\n \"id\": \"q6\",\n \"text\": \"...sedíte alebo ležíte a potiahnete špičku nahor smerom k sebe, Vaša bolesť sa zhorší.\",\n \"prepend_id\": 3,\n \"color_id\": 1\n },\n {\n \"id\": \"q7\",\n \"text\": \"...je horšia ráno po zobudení, po zahriatí a počas celého dňa, a zmierňuje sa až večer.\",\n \"prepend_id\": 1,\n \"color_id\": 1\n }\n]\n\noptions = [\n {\n \"from\": \"a\",\n \"text\": \"Zospodu chodidla\",\n \"label\": \"chodidlo-zospodu\",\n \"side\": \"back\",\n \"to\": \"q1\",\n },\n {\n \"from\": \"a\",\n \"text\": \"Zvrchu chodidla\",\n \"label\": \"chodidlo-zvrchu\",\n \"side\": \"back\",\n \"to\": \"q3\",\n },\n {\n \"from\": \"a\",\n \"text\": \"Prstov\",\n \"label\": \"chodidlo-prsty\",\n \"side\": \"front\",\n \"to\": \"q7\",\n },\n {\n \"from\": \"a\",\n \"text\": \"Päty\",\n \"label\": \"chodidlo-pata\",\n \"side\": \"back\",\n \"to\": \"different_tree_question\",\n \"tree\": \"clenok\",\n \"option\": \"clenok-zozadu\",\n },\n {\n \"from\": \"q1\",\n \"text\": \"Áno\",\n \"to\": \"q2\",\n },\n {\n \"from\": \"q1\",\n \"text\": \"Nie\",\n \"to\": \"d1\",\n },\n # SH: tento strom nebude v soft launch-i\n # {\n # \"from\": \"q2\",\n # \"text\": \"Áno\",\n # \"to\": \"different_tree\",\n # \"tree\": \"driek\",\n # },\n {\n \"from\": \"q2\",\n \"text\": \"Nie\",\n \"to\": \"d2\",\n },\n {\n \"from\": \"q3\",\n \"text\": \"Áno\",\n \"to\": \"d4\",\n },\n {\n \"from\": \"q3\",\n \"text\": \"Nie\",\n \"to\": \"q4\",\n },\n {\n \"from\": \"q4\",\n \"text\": \"Áno (bolesť je poobede/večer miernejšia a zlepšuje sa po zahriatí)\",\n \"to\": \"d3\",\n },\n {\n \"from\": \"q4\",\n \"text\": \"Nie\",\n \"to\": \"q5\",\n },\n {\n \"from\": \"q5\",\n \"text\": \"Áno\",\n \"to\": \"d6\",\n },\n {\n \"from\": \"q5\",\n \"text\": \"Nie (je stále rovnaká)\",\n \"to\": \"q6\",\n },\n {\n \"from\": \"q6\",\n \"text\": \"Áno\",\n \"to\": \"d7\",\n },\n {\n \"from\": \"q6\",\n \"text\": \"Nie\",\n \"to\": \"d8\",\n },\n {\n \"from\": \"q7\",\n \"text\": \"Áno (k večeru a po zahriatí sa bolesť zmierňuje)\",\n \"to\": \"d3\",\n },\n {\n \"from\": \"q7\",\n \"text\": \"Nie (pohybom sa bolesť nemení alebo sa zhoršuje)\",\n \"to\": \"d5\",\n }\n]\n","sub_path":"backend/app/self_diagnostic_trees/chodidlo.py","file_name":"chodidlo.py","file_ext":"py","file_size_in_byte":5021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"73928541","text":"import os\nimport cv2\nimport numpy as np\nimport time\n\n\n# get how far we should move the slide block\ndef get_move_step(icon_path=None, background_path=None):\n\n if not os.path.exists(icon_path):\n raise Exception('icon path does not exist %s' % str(icon_path))\n\n if not os.path.exists(background_path):\n raise Exception('icon path does not exist %s' % str(background_path))\n\n img_icon = cv2.imread(icon_path, 0)\n w_icon, h_icon = img_icon.shape[::-1]\n\n # we need to remove the icon part from the original background\n img_background_original = cv2.imread(background_path)\n (h_bg, w_bg, d_bg) = img_background_original.shape\n img_background = img_background_original[:, w_icon:w_bg]\n # img_background = img_background_original\n\n # change the background to grey one.\n img_background_gray = cv2.cvtColor(img_background, cv2.COLOR_BGR2GRAY)\n res = cv2.matchTemplate(img_background_gray, img_icon, cv2.TM_CCOEFF_NORMED)\n\n # 使用二分法查找阈值的精确值\n run = 1\n L = 0\n R = 1\n while run < 20:\n run += 1\n threshold = (R + L) / 2\n # print(threshold)\n if threshold < 0:\n print('Error')\n return None\n loc = np.where(res >= threshold)\n # print(len(loc[1]))\n if len(loc[1]) > 1:\n L += (R - L) / 2\n elif len(loc[1]) == 1:\n print('目标区域起点x坐标为:%d' % (loc[1][0] + w_icon))\n return loc[1][0] + w_icon\n # break\n elif len(loc[1]) < 1:\n R -= (R - L) / 2\n if run == 20:\n print('failed to recognize the img %s' % icon_path)\n return\n for pt in zip(*loc[::-1]):\n cv2.rectangle(img_background, pt, (pt[0] + w_icon, pt[1] + h_icon), (7, 279, 151), 2)\n cv2.imshow('Dectected', img_background)\n # cv2.waitKey(0)\n time.sleep(2)\n cv2.destroyAllWindows()\n return loc[1][0] + w_icon\n\nif __name__ == '__main__':\n icon_path = \"icon.png\"\n background_path = \"bg.png\"\n\n x = get_move_step(icon_path, background_path)\n print(x)\n\n\n\n","sub_path":"滑动验证码破解(今日头条)/RegisterImgUtil.py","file_name":"RegisterImgUtil.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"250485473","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2017-2020 - Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\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\"\"\"Migrate project to the latest Renku version.\"\"\"\nimport click\n\nfrom renku.core.commands.migrate import migrate_project, migrate_project_no_commit\n\n\n@click.command()\n@click.option(\"--no-commit\", is_flag=True, hidden=True, help=\"Do not commit changes after the migration.\")\ndef migrate(no_commit):\n \"\"\"Migrate to latest Renku version.\"\"\"\n if no_commit:\n result = migrate_project_no_commit(progress_callback=click.secho)\n else:\n result = migrate_project(progress_callback=click.secho)\n\n if result:\n click.secho(\"OK\", fg=\"green\")\n else:\n click.secho(\"No migrations required.\")\n","sub_path":"renku/cli/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314423937","text":"# coding=utf-8\nimport sys\nimport time\nimport config\n\n# 将本地的包,添加进入模块搜索\nsys.path.append(\"./site-packages\")\n\nimport alfred_util\nfrom search_in_bookmark import ChromeBookMarkSearch, ChromeHistorySearch\n\n\ndef do_search(words):\n list = []\n start_time = time.time() * 1000\n list.append(ChromeBookMarkSearch().find(words))\n end_book_mark_time = time.time() * 1000\n list.append(ChromeHistorySearch().find(words))\n history_time = time.time() * 1000\n merged_result = alfred_util.merge_result(list)\n merged_time = time.time() * 1000\n default_search_item = alfred_util.get_default_search_item(words)\n if len(merged_result) <= 2:\n merged_result.append(default_search_item)\n else:\n merged_result.insert(2, default_search_item)\n end_time = time.time() * 1000\n if config.IS_DEBUG_MODE:\n print(\"book_mark={0},history={1},merged_time={2},end_time={3}\".format(\n end_book_mark_time - start_time,\n history_time - end_book_mark_time,\n merged_time - history_time,\n end_time - start_time\n ))\n return alfred_util.get_alfred_out(merged_result)\n\ndef do_main():\n word = sys.argv[1].lstrip().strip()\n # 按照空格分隔成List\n words = word.decode(\"utf-8\").split(\" \")\n # 搜索时候要去除List中的空元素,因为中间可能有多个连续的空格\n result = do_search(list(filter(lambda x: x != '', words)))\n if config.IS_DEBUG_MODE:\n sys.stdout.write(result.decode(\"unicode_escape\").encode(\"utf-8\"))\n else:\n sys.stdout.write(result)\n sys.stdout.flush()\n exit(0)\n\nif __name__ == \"__main__\":\n do_main()\n","sub_path":"AlfredChrome/alfred_main.py","file_name":"alfred_main.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"622879486","text":"# -*- coding: utf-8 -*-\r\nfrom flask import Flask\r\nfrom flask import render_template\r\nfrom flask import request\r\nfrom Network import BIT_Network\r\nfrom User import User_Info\r\n \r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n if request.method == 'GET':\r\n output = ''\r\n us_info = User_Info().getUserInfo()\r\n return render_template('index.html', us_info=us_info, info=output)\r\n else:\r\n true_flag = True\r\n usr = request.form.get(\"usr\", type = str, default = '')\r\n pwd = request.form.get(\"pwd\", type = str, default = '')\r\n us_info = (usr, pwd)\r\n if not (usr and pwd):\r\n output = 'Your user information is not complete!'\r\n return render_template('index.html', us_info=us_info, info=output)\r\n btn_method = request.form.get(\"method\", type = str, default = 'Login')\r\n if btn_method == 'Login':\r\n output = BIT_Network((usr, pwd)).login()\r\n else:\r\n type_logout = request.form.get(\"type_logout\", type = str, default = 'y')\r\n print(type_logout)\r\n output = BIT_Network((usr, pwd)).logout(type_logout)\r\n if 'Password is Error' in output:\r\n true_flag = False\r\n else:\r\n User_Info().saveUserInfo(us_info, true_flag)\r\n us_info = User_Info().getUserInfo()\r\n return render_template('index.html', us_info=us_info, info=output)\r\n \r\nif __name__ == '__main__':\r\n app.run(host='127.0.0.1', port='8000')\r\n","sub_path":"flasker.py","file_name":"flasker.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"24060798","text":"from data import CITIES, BUSINESSES, USERS, REVIEWS, TIPS, CHECKINS, get_reviews, get_business, get_userreviews\nimport ast\nimport pandas as pd\nimport sklearn.metrics.pairwise as pw\nimport numpy as np\nimport random\n\ndef get_attributes(city, business_id):\n\n \"\"\"\n Given a city name and a business id, return that business's atributes as a dict\n\n \"\"\"\n business = get_business(city, business_id)\n return business['attributes']\n\ndef new_atts(atts):\n\n \"\"\"\n Restructures the attributes into a more practical format\n\n \"\"\"\n must_dict = ['Ambience', 'GoodForMeal', 'BusinessParking', 'Music']\n L = []\n L2 = []\n copy = atts\n\n if atts!=None:\n for i in atts:\n if i in must_dict:\n L.append(atts[i])\n\n for i in must_dict:\n if i in copy:\n del copy[i]\n for i in L:\n i = ast.literal_eval(i)\n L2.append(i)\n\n\n for i in L2:\n if i!=None:\n for j in i:\n copy[j] = i[j]\n\n return copy\n\n else:\n l = {}\n return l\n\ndef get_cities():\n cities = []\n\n for i in BUSINESSES:\n cities.append(i)\n\n return cities\n\n\ndef all_revs(cities):\n\n revs = []\n\n for i in cities:\n r = get_reviews(i)\n for j in r:\n l = []\n l.append(j['user_id'])\n l.append(j['business_id'])\n l.append(j['stars'])\n revs.append(l)\n\n return revs\n\ndef b_c_pair(cities):\n\n b_c_pair = {}\n\n for i in cities:\n b = BUSINESSES[i]\n for j in b:\n b_c_pair[j['business_id']] = [i]\n\n return b_c_pair\n\n\ndef make_utility_matrix(cities):\n\n\n b_c_pair = {}\n\n for i in cities:\n b = BUSINESSES[i]\n for j in b:\n b_c_pair[j['business_id']] = [i]\n\n all_atts = set()\n\n for i in cities:\n for j in BUSINESSES[i]:\n b_id = j['business_id']\n ats = new_atts(get_attributes(i, b_id))\n for k in ats:\n all_atts.add(k)\n\n df = pd.DataFrame( columns=all_atts, index=b_c_pair.keys())\n\n for i in df.index:\n for j in df.columns:\n df.loc[i,j] = 0\n\n for i in df.index:\n a = new_atts(get_attributes(b_c_pair[i][0], i))\n if len(a) > 0:\n for j in a.keys():\n if a[j] == True or a[j] == 'free' or a[j] == 2 or a[j] == 'True':\n df.loc[i,j] = 1\n else:\n df.loc[i,j] = 0\n\n return df\n\ndef create_similarity_matrix_categories(matrix):\n np.seterr(divide='ignore', invalid='ignore')\n npu = matrix.values\n m1 = npu @ npu.T\n diag = np.diag(m1)\n m2 = m1 / diag\n m3 = np.minimum(m2, m2.T)\n return pd.DataFrame(m3, index = matrix.index, columns = matrix.index)\n\n\ndef sorted_similarity(s_matrix, business_id):\n\n df = s_matrix.loc[business_id].sort_values(ascending=False)\n\n return df\n\n\n\ndef top_5(df, n):\n\n top_5 = df.nlargest(n)\n\n return top_5\n\n\n\nu_matrix = make_utility_matrix(get_cities())\n\ns_matrix = create_similarity_matrix_categories(u_matrix)\n\nr = all_revs(get_cities())\n\ndf = pd.DataFrame(r, columns = ['user_id', 'business_id', 'rating'])\n\n\n\ndef pivot_ratings(df):\n \"\"\"Creates a utility matrix for user ratings for movies\n\n Arguments:\n df -- a dataFrame containing at least the columns 'movieId' and 'genres'\n\n Output:\n a matrix containing a rating in each cell. np.nan means that the user did not rate the movie\n \"\"\"\n return df.pivot(values='rating', columns='user_id', index='business_id')\n\ndef create_similarity_matrix_cosine(matrix):\n \"\"\"Creates a adjusted(/soft) cosine similarity matrix.\n\n Arguments:\n matrix -- a utility matrix\n\n Notes:\n Missing values are set to 0. This is technically not a 100% correct, but is more convenient\n for computation and does not have a big effect on the outcome.\n \"\"\"\n mc_matrix = matrix - matrix.mean(axis = 0)\n return pd.DataFrame(pw.cosine_similarity(mc_matrix.fillna(0)), index = matrix.index, columns = matrix.index)\n\ndef predict_ratings(similarity, utility, to_predict):\n \"\"\"Predicts the predicted rating for the input test data.\n\n Arguments:\n similarity -- a dataFrame that describes the similarity between items\n utility -- a dataFrame that contains a rating for each user (columns) and each movie (rows).\n If a user did not rate an item the value np.nan is assumed.\n to_predict -- A dataFrame containing at least the columns movieId and userId for which to do the predictions\n \"\"\"\n # copy input (don't overwrite)\n ratings_test_c = to_predict.copy()\n # apply prediction to each row\n ratings_test_c['predicted rating'] = to_predict.apply(lambda row: predict_ids(similarity, utility, row['user_id'], row['business_id']), axis=1)\n return ratings_test_c\n\n### Helper functions for predict_ratings_item_based ###\n\ndef predict_ids(similarity, utility, userId, itemId):\n # select right series from matrices and compute\n if userId in utility.columns and itemId in similarity.index:\n return predict_vectors(utility.loc[:,userId], similarity[itemId])\n return 0\n\ndef predict_vectors(user_ratings, similarities):\n # select only movies actually rated by user\n relevant_ratings = user_ratings.dropna()\n\n # select corresponding similairties\n similarities_s = similarities[relevant_ratings.index]\n\n # select neighborhood\n similarities_s = similarities_s[similarities_s > 0.0]\n relevant_ratings = relevant_ratings[similarities_s.index]\n\n # if there's nothing left return a prediction of 0\n norm = similarities_s.sum()\n if(norm == 0):\n return 0\n\n # compute a weighted average (i.e. neighborhood is all)\n return np.dot(relevant_ratings, similarities_s)/norm\n\ndef mse(predicted_ratings):\n \"\"\"Computes the mean square error between actual ratings and predicted ratings\n\n Arguments:\n predicted_ratings -- a dataFrame containing the columns rating and predicted rating\n \"\"\"\n diff = predicted_ratings['rating'] - predicted_ratings['predicted rating']\n return (diff**2).mean()\n\n\n# make copy\ncopy_test = df.copy()\n\n# make list wiht random numbers between 0.5 and 5.0\nrandoms = []\nfor i in range(len(copy_test['rating'])):\n randoms.append(round(random.uniform(0.5, 5.0),1))\n\n\n# make new column\ncopy_test['predicted rating'] = [2.0, 3.5, 3.0, 4.0, 3.0]\ndisplay(copy_test.head())\n\n# make mse\nmse_random = mse(copy_test)\n\n\nprint(f'mse for random prediction: {mse_random:.2f}')","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"31618569","text":"import pygame\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\n\n\n\npygame.init()\n\nsize = (700, 500)\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"My Game\")\n\nbackground_image = pygame.image.load(\"saturn_family1.bmp\").convert()\nplayer_image = pygame.image.load(\"player.bmp\").convert()\nplayer_image.set_colorkey(WHITE)\nclick_sound = pygame.mixer.Sound(\"laser5.ogg\").convert()\n\ndone = False\nclock = pygame.time.Clock()\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n elif event.type == pygame.MOUSEBUTTONDOWN:\n click_sound.play()\n \n # --- Game logic should go here\n player_position = pygame.mouse.get_pos()\n x = player_position[0]\n y = player_position[1]\n \n screen.blit(background_image, [0, 0])\n screen.blit(player_image, [x, y])\n \n # --- Drawing code should go here\n\n pygame.display.flip()\n clock.tick(60)\npygame.quit()","sub_path":"bitmap and sound.py","file_name":"bitmap and sound.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"445963755","text":"'''\n\nCARMEN RVP analysis v6.\nFor 192.192 IFCs only.\n\n'''\n\n# General modules\nimport sys\nimport logging\nimport time\nfrom os import path, makedirs\nfrom gooey import Gooey, GooeyParser\n\n# import submodules\nfrom parser import ArgParse\nfrom analysis import ReadData, ItemsToList, LabelInputs\nfrom plot import PlotHeatmap\nfrom hitcalling import HitCallingFoldThreshold, CheckOutliers, CheckEC, CheckNDC, CheckDM, CheckEx, ConsiderControls, getCtrlMean\n\n\n@Gooey(program_name='CARMEN RVP analysis',\n program_description = 'Analyze CARMEN RVP data from Fluidigm Biomark HD instrument.',\n tabbed_groups=True,\n language = 'english',\n image_dir = '../img/',\n clear_before_run = True,\n menu=[{\n 'name': 'About',\n 'items': [{\n 'type': 'AboutDialog',\n 'menuTitle': 'About',\n 'name': 'CARMEN RVP analysis Demo',\n 'description': 'An example description',\n 'version': '1.0.6',\n 'copyright': '2021',\n 'website': 'Github Link',\n 'license': 'MIT'\n }, {\n 'type': 'Link',\n 'menuTitle': 'Visit Our Webite',\n 'url': 'https://www.sabetilab.org/'\n }]\n }]\n )\n\n# these lines are for packaging with PyInstaller\nclass Unbuffered(object):\n def __init__(self, stream):\n self.stream = stream\n def write(self, data):\n self.stream.write(data)\n self.stream.flush()\n def writelines(self, datas):\n self.stream.writelines(datas)\n self.stream.flush()\n def __getattr__(self, attr):\n return getattr(self.stream, attr)\nsys.stdout = Unbuffered(sys.stdout)\n\n# Get the version:\nversion = {}\nwith open(path.join(path.abspath(path.dirname(__file__)), 'version.py')) as f: exec(f.read(), version)\n\n# A function to quit with an error:\ndef error(msg, exit_code=1):\n logging.error(msg)\n sys.exit(exit_code)\n\ndef main():\n \n # Define the user defaults:\n timestamp = time.strftime(\"%Y%m%d-%H%M%S\")\n defaults = {'verbosity': 'info', 'xname': timestamp, 'outdir': '', 'rawdata': '', 'layout': '',\\\n 'Ectrl': 'EC','NTCctrl': 'NTC','CPCctrl':'CPC','NDCctrl': 'NDC', 'DMctrl': 'no-crRNA','Wctrl': 'water',\\\n 'threshold': 1.8, 'timepoint': 't12', 'alsort': 'original','slsort': 'original'}\n \n args = ArgParse(defaults)\n \n # Check that the output directory exists, and make it if not:\n output_dir = path.expanduser(path.abspath(args.outdir))\n if not path.exists(output_dir):\n try:\n makedirs(output_dir)\n except: \n logging.basicConfig(level = logging.DEBUG)\n error('failed to create output directory {}'.format(output_dir))\n if not path.isdir(output_dir): \n logging.basicConfig(level = logging.DEBUG)\n error('specified output {} is not a directory'.format(output_dir)) \n # Build the output file prefix:\n output_prefix = path.join(args.outdir, args.xname)\n \n # Set up logging based on the verbosity level set by the command line arguments:\n logfilepath = '{}logfile.log'.format(output_prefix)\n logging.basicConfig(format='%(asctime)s, %(name)s %(levelname)s %(message)s',\n datefmt='%m-%d %H:%M',\n level = logging.DEBUG,\n filename= logfilepath,\n filemode= 'w')\n logging.getLogger('matplotlib').setLevel(logging.WARNING)\n # define a Handler which writes INFO messages or higher to the sys.stderr\n console = logging.StreamHandler()\n console.setLevel(args.verbosity.upper())\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(message)s')\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n \n logging.debug('Logfile is saved to {}'.format(logfilepath))\n logging.debug('output file prefix is {}'.format(output_prefix))\n \n # Check if everything is there\n for inputfile in [args.layout, args.rawdata]: \n if not path.exists(inputfile):\n error('specified file {} does not exist'.format(inputfile)) \n \n # Read in data\n logging.info(\"Reading in rawdata from {}\".format(args.rawdata))\n try:\n probe_df, ref_df, bkgdprobe_df, bkgdref_df = ReadData(args.rawdata)\n except:\n error(\"Reading the raw data from {} failed.\".format(args.rawdata))\n \n # Background subtraction\n probe_df = probe_df - bkgdprobe_df\n ref_df = ref_df - bkgdref_df\n # Normalization with ROX\n signal_df = probe_df/ref_df\n \n # Assign sample and assay names\n try:\n LabelInputs(signal_df, args.layout)\n logging.info(\"Assays and Samples have been labeled.\")\n except:\n error(\"Unable to label assays and samples. Please check the layout sheet.\")\n \n # Save signal dataframe to csv\n signal_df.to_csv(\"{}_signal.csv\".format(output_prefix)) \n logging.info(\"Normalized data saved to {}_signal.csv\".format(output_prefix))\n\n # Get median data for timepoint of interest\n x_med = signal_df.groupby(['assay', 'sample']).median()[args.toi].unstack()\n x_med.index.names=['']\n x_med.columns.names=['']\n median_df = x_med\n \n # Create a list of all assays and all samples\n a_list = ItemsToList(args.layout, 'assays', sort = args.alsort)\n s_list = ItemsToList(args.layout, 'samples', sort = args.slsort)\n \n ####################### Hit calling\n \n neg_ctrl_mean, neg_ctrl_std = getCtrlMean(median_df,args.ntcctrl,args)\n pos_ctrl_mean, pos_ctrl_std = getCtrlMean(median_df,args.cpcctrl,args)\n \n # Overall dynamic range of the assay --> turns whole assay invalid\n \"\"\"\n The NTC and CPC are the ground truth for the hit calling. Since the validation of CPC and NTC depends on their group mean and standard deviation respectively, they have to be distinctively different from each other. For the assay to be valid, the ratio of separation band to dynamic range has to be greater than 0.2. The dynamic range is defined as the difference of the NTC mean and CPC mean. The separation band is the range between the CPC mean subtracted by three standard deviations of the CPCs and the NTC mean plus three standard deviations of the NTCs. \n \"\"\"\n separation_band = (pos_ctrl_mean - 3*pos_ctrl_std) - (neg_ctrl_mean + 3* neg_ctrl_std)\n dynamic_range = abs(pos_ctrl_mean - neg_ctrl_mean)\n zfactor = separation_band/dynamic_range\n \n if zfactor > 0.2:\n logging.info('Z-Factor is {}'.format(zfactor))\n else:\n logging.error(\"Run invalid: the dynamic range of this assay is too low (Z-factor {}).\".format(zfactor))\n logging.debug(\"CPC mean = {} stdev = {}; NTC mean = {} stdev = {}\".format(pos_ctrl_mean, pos_ctrl_std,neg_ctrl_mean, neg_ctrl_std))\n PlotHeatmap(median_df, None, args.toi, a_list, s_list, output_prefix+'_LowDynamicRange')\n logging.warning(\"A heatmap has been generated nevertheless, but without hit calling.\")\n sys.exit()\n \n # Check for RT-PCR control outlier --> turns assay invalid\n NTC_outlier = CheckOutliers(median_df,args.ntcctrl,'negative') \n CPC_outlier, pass_cpc = CheckOutliers(median_df,args.cpcctrl,'positive')\n \n # perform hit calling on remaining samples\n hit_df, quanthit_df = HitCallingFoldThreshold(median_df,args.threshold,a_list,s_list,args.ntcctrl)\n quanthit_df.T.to_csv(\"{}_HitQuantification.csv\".format(output_prefix)) \n PlotHeatmap(median_df, hit_df, args.toi, a_list, s_list, output_prefix+'_initial_raw_hitcalling')\n \n # Extraction control should be negative for all targets and positive for RNAseP\n EC_outlier, pass_ec = CheckEC(hit_df,a_list,args.ectrl)\n \n if pass_ec or pass_cpc == False:\n hit_df = hit_df.applymap(lambda x: 'invalid')\n hit_df.T.to_csv(\"{}_hits.csv\".format(output_prefix))\n PlotHeatmap(median_df, hit_df, args.toi, a_list, s_list, output_prefix)\n logging.info(\"Heatmap with hits is saved as {}_heatmap_{}.png\".format(output_prefix, args.toi))\n sys.exit()\n \n # Negative Detection Control (NDC) for sample mastermix should be negative for all targets in W-det-NoMg\n NDC_outlier = CheckNDC(hit_df,a_list,args.ndcctrl)\n \n # Detection control for assay mastermix should be negative for all sample in no-crRNA assay\n DM_soutlier = CheckDM(hit_df,s_list,args.dmctrl) # this outlier list is with samples instead of assays\n \n # All samples should be positive for RNAseP or at least another sample\n Ex_soutlier = CheckEx(hit_df,s_list,a_list,args) # check if extraction for the sample was successfull\n \n # annotate samples that didn't pass the control\n hit_df = ConsiderControls(hit_df,a_list,s_list,args,NTC_outlier, CPC_outlier, EC_outlier, NDC_outlier, DM_soutlier, Ex_soutlier)\n \n hit_df.T.to_csv(\"{}_hits.csv\".format(output_prefix)) \n logging.warning(\"Hit calling data frame is generated and saved to {}_hits.csv.\".format(output_prefix))\n \n # Plot heatmap with overlayed hits\n PlotHeatmap(median_df, hit_df, args.toi, a_list, s_list, output_prefix)\n logging.info(\"Heatmap with hits is generated and saved as {}_heatmap_{}.\".format(output_prefix, args.toi))\n \n \n\n############### EXECUTE #################\n \nif __name__ == '__main__':\n main()\n\n","sub_path":"archive-expertversion/.ipynb_checkpoints/carmen_rvp_analysis-checkpoint.py","file_name":"carmen_rvp_analysis-checkpoint.py","file_ext":"py","file_size_in_byte":9469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"135686807","text":"class Solution:\n # @param {character[][]} grid\n # @return {integer}\n def numIslands(self, grid):\n if len(grid) == 0 or len(grid[0]) == 0:\n return 0\n def helper(grid, row, col):\n q = [(row,col)]\n grid[row][col] = '0'\n while len(q) > 0:\n (r,c) = q.pop(0)\n if r > 0 and grid[r-1][c] == '1':\n q.append((r-1,c))\n grid[r-1][c] = '0'\n if r < len(grid)-1 and grid[r+1][c] == '1':\n q.append((r+1,c))\n grid[r+1][c] = '0'\n if c > 0 and grid[r][c-1] == '1':\n q.append((r,c-1))\n grid[r][c-1] = '0'\n if c < len(grid[0])-1 and grid[r][c+1] == '1':\n q.append((r,c+1))\n grid[r][c+1] = '0'\n return\n ret = 0\n grid = [[e for e in r] for r in grid]\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == '1':\n ret += 1\n helper(grid, row, col)\n return ret","sub_path":"leetcode/number-of-islands.py","file_name":"number-of-islands.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"276833530","text":"import socket\n\n\nwhile True:\n socketserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socketserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n socketserver.bind(('127.0.0.1', 1315))\n socketserver.listen(10)\n q, v = socketserver.accept()\n q.send(b'Come and you love me')\n print(q.recv(1024))\n q.close()","sub_path":"wsgi/socket_s1.py","file_name":"socket_s1.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"439762951","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\n 3.1:\r\n 没有标签的可以让分类模型学习, 我们不可能学习得到一个分类器, 然后可以从数据本身学习到一些模式,\r\n 用户提出一个问题 然后返回给他最想要的答案.\r\n 计算一个帖子和其他帖子的相似度,然后得到���N个最相似的帖子。\r\n\r\n 通过聚类实现目的, 使相同的数据项 归类同一个簇中,\r\n 问题1 将文本进行相似度计算?\r\n 原始的文本用处不大,计算机又不认识, 至少现在不认识,\r\n 转化为数学形式, --- 词袋向量.\r\n #3.1.2 bag of words\r\n # features is words.\r\n # feature_value is one wordCnt in a doc.\r\n # strategy:\r\n # 1 transform doc to a vocab_Vec. (some important process)\r\n # 2 cluster\r\n # 3 confirm every doc in which cluster\r\n # 4\r\n\r\n'''\r\nimport numpy as np\r\nimport scipy as sp\r\nimport os\r\nimport math\r\nimport nltk\r\nimport sklearn.datasets\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\nMLCOMP_DIR = r\"C:\\Users\\people\\QtProject\\mlapps\\20news-18828\"\r\nmlcomp_data = sklearn.datasets.load_mlcomp(\"20news-18828\", mlcomp_root=MLCOMP_DIR)\r\n\r\n\r\n\r\n\r\n'''\r\n3.2\r\n 预处理,用相近的公共词语个数来衡量相似性\r\n 3.2.1 原始文本 -> 词袋向量\r\n 向量化处理器 : sklearn CounterVectorizer.\r\n 3.2.2 统计词语\r\n 将数据整体全部传入给 向量化处理器, 向量化处理器就会自动统计词语,\r\n 并得到 词袋特征 -- vocabBag.\r\n 通过向量化处理器 得到了文本的 词袋向量\r\n 计算距离.\r\n\r\n 3.2.3 归一化词频, 计算归一化距离\r\n 对自己进行归一化 这样好么?他这样收缩了长度减小词频影响,貌似应该并不好啊.\r\n 对于 其他非文本数据这样确实不好, 但是对于文本来说 词频影响比较小, 而更加关注于词语组合,\r\n 即 文本匹配 更注重内在意思 - 多个词相同越多越好, 而不是一个词出现的越多越好.\r\n 相同的词越多越好, 同一个相同的词 次数越多并不重要\r\n\r\n 3.2.4 删除不重要的词语\r\n stop_words = 'english' 文本中 很多词语 并不是为了表达意思 而是为了形容的这类词语\r\n 对文本意思并不重要 计算相似度时候 不需要.\r\n 不重要的词 没有意义。\r\n\r\n 3.2.5 词干处理 nltk\r\n 词语形式不同 实际意义实际相同, 通过抽取词干, 将不同形式的词语变为同一个词语\r\n\r\n 3.2.6 停用词兴奋剂\r\n 有些词 对特殊的文本 具有标记型, 军事文本 一般都会出现国家名字.\r\n 为这些特征性词语 提高权重.\r\n 而对于某些大众词(a subject example)等 减少权重,因为任何一个文本都有很大可能出现. 甚至直接标记为停用词.\r\n 词频-反转文档频率 (TF-IDF)\r\n 此时词袋向量的 特征值 并不是词的统计值, 而是一个词的TF-IDF值,\r\n 可以考虑认为是 词对于整个数据集的分类权重值.\r\n\r\n 3.2.7 成果和目标\r\n 文本预处理\r\n 1 文本切分\r\n 2 去掉stop_words 和\r\n 3 统计剩余词语\r\n 4 考虑整个语料集合, 从词频统计中计算每个词的 tf-idf值. 生成 以tf-idf为特征值的 词袋向量\r\n 此时 我们将充满噪音的文本转化为了简明的 分类特征的词袋向量数据集.\r\n 问题、缺点:\r\n 1 词语之间关联关系\r\n 2 not or yes 否定关系捕捉\r\n 3 拼写错误的词语 捕捉错误.\r\n\r\n\r\n'''\r\ndef test_counterVectorizer():\r\n content = [\"How to format my hard disk\",\r\n \"Hard disk format problems\"]\r\n vectorizer = CountVectorizer(min_df=1)\r\n\r\n X = vectorizer.fit_transform(content)\r\n vecNames = vectorizer.get_feature_names()\r\n\r\n data = X.toarray()\r\n print(data)\r\n\r\n# Eul\r\ndef dist_raw(v1, v2):\r\n delta = v1 - v2\r\n return sp.linalg.norm(delta.toarray())\r\n\r\n# norm Eul\r\ndef dist_norm(v1, v2):\r\n v1_norm = v1/sp.linalg.norm(v1.toarray())\r\n v2_norm = v2/sp.linalg.norm(v2.toarray())\r\n return dist_raw(v1_norm, v2_norm)\r\n\r\nenglish_stemmer = nltk.stem.SnowballStemmer('english')\r\nclass StemmedCounterVectorizer(CountVectorizer):\r\n def build_analyzer(self):\r\n analyzer = super(StemmedCounterVectorizer, self).build_analyzer()\r\n return lambda doc: (english_stemmer.stem(w) for w in analyzer(doc))\r\n\r\n# term 词 对 doc的重要性(权重) 在集合docset中.\r\ndef tfidf(term, doc, docset):\r\n tf = float(doc.count(term))/sum(doc.count(w) for w in set(doc))\r\n idf = float(len(docset))/(len([docTemp for docTemp in docset if term in docTemp]))\r\n idf = math.log(idf)\r\n return tf*idf\r\n\r\nclass StemmedTfidfVectorizer(TfidfVectorizer):\r\n def build_analyzer(self):\r\n analyzer = super(StemmedTfidfVectorizer, self).build_analyzer()\r\n return lambda doc: (english_stemmer.stem(w) for w in analyzer(doc))\r\n\r\ndef test_tfidf():\r\n a, abb, abc = ['a'], ['a', 'b', 'b'], ['a', 'b', 'c']\r\n D = [a, abb, abc]\r\n print(tfidf('a', a, D))\r\n print(tfidf('a', abb, D))\r\n print(tfidf('a', abc, D))\r\n print(tfidf('b', a, D))\r\n print(tfidf('b', abb, D))\r\n print(tfidf('b', abc, D))\r\n print(tfidf('c', a, D))\r\n print(tfidf('c', abb, D))\r\n print(tfidf('c', abc, D))\r\n\r\n\r\ndef loadData():\r\n DIR = \"../data/toy/\"\r\n posts = [open(os.path.join(DIR, f)).read() for f in os.listdir(DIR)]\r\n return posts\r\n\r\ndef vocabTransform(vectorizer, data_words):\r\n data_vocabVec = vectorizer.fit_transform(data_words)\r\n# print(data_vocabVec.shape)\r\n #get the vocabBag.\r\n vecNames = vectorizer.get_feature_names()\r\n# print(vecNames)\r\n return data_vocabVec\r\n\r\ndef calcNeareast(vectorizer, dataSet, dataSet_vocab, example, dist = dist_raw):\r\n best_doc = None\r\n best_dist = 999999\r\n best_i = None\r\n num_samples = len(dataSet)\r\n for i in range(0, num_samples):\r\n entry = dataSet[i]\r\n if entry == example:\r\n continue\r\n entry_vec = dataSet_vocab.getrow(i)\r\n example_vec = vectorizer.transform([example])\r\n d = dist(entry_vec, example_vec)\r\n print(\"============ Index: %d distance: %.2f \\n%s, \" %(i, d, entry))\r\n if d < best_dist:\r\n best_dist = d\r\n best_i = i\r\n best_doc = entry\r\n return best_i, best_dist, best_doc\r\n\r\n\r\n\r\ndef mlcomp():\r\n print(mlcomp_data.filenames)\r\n print(len(mlcomp_data.filenames))\r\n\r\ndef easyToUse():\r\n# vectorizer = CountVectorizer(min_df=1, stop_words = 'english')\r\n# vectorizer = StemmedCounterVectorizer(min_df=1, stop_words = 'english')\r\n vectorizer = StemmedTfidfVectorizer(min_df=1, stop_words = 'english', charest_error = 'ignore')\r\n data_words = loadData()\r\n data_vocabVec = vocabTransform(vectorizer, data_words)\r\n\r\n new_post = \"imaging databases\"\r\n new_post_vec = vectorizer.transform([new_post])\r\n print(new_post_vec.toarray())\r\n\r\n calcNeareast(vectorizer, data_words, data_vocabVec, new_post, dist=dist_norm)\r\n\r\nif __name__ == \"__main__\":\r\n mlcomp()\r\n","sub_path":"machine_system_design/1400OS_03_Codes/mycode/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"322311044","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///annotations.sqlite'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\nclass Genome(db.Model):\n\n\n __tablename__ = 'genomes'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n\n def __repr__(self):\n return '' % self.name\n\n\n\n# Annotations model:\nclass Annotations(db.Model):\n\n\n __tablename__ = 'annotations'\n\n trackid = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n chromosome = db.Column(db.Integer, nullable=True, unique=False)\n start = db.Column(db.Integer, nullable=True, unique=False)\n end = db.Column(db.Integer, nullable=True, unique=False)\n variant = db.Column(db.String, nullable=True, unique=False)\n confirmed = db.Column(db.String, default='No', unique=False)\n comment = db.Column(db.String, nullable=True, unique=False)\n trackgenome = db.Column(db.Integer, db.ForeignKey('genomes.id'), nullable=False)\n\n def __repr__(self):\n return '' % self.name\n\n\nclass Users(db.Model):\n\n\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(200), nullable=False)\n password = db.Column(db.String, nullable=False)\n\n def __repr__(self):\n return '' % self.name\n\n\nclass Technologies(db.Model):\n\n\n __tablename__ = 'technologies'\n\n id = db.Column(db.Integer, primary_key=True)\n technology = db.Column(db.String, nullable=False)\n\n def __repr__(self):\n return '' % self.name\n\n\nclass Detections(db.Model):\n\n\n __tablename__ = 'detections'\n\n id = db.Column(db.Integer, primary_key=True)\n detection_method = db.Column(db.String, nullable=False)\n\n def __repr__(self):\n return '' % self.name\n\n\nclass Annotated(db.Model):\n\n\n __tablename__ = 'annotated'\n\n id = db.Column(db.Integer, primary_key=True)\n trackannotation = db.Column(db.Integer, db.ForeignKey('annotations.trackid'), nullable=False)\n # trackuser = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n # tracktech = db.Column(db.Integer, db.ForeignKey('technologies.id'), nullable=False)\n # trackdetect = db.Column(db.Integer, db.ForeignKey('detections.id'), nullable=False)\n trackuser = db.Column(db.String, db.ForeignKey('users.name'), nullable=False)\n tracktech = db.Column(db.String, nullable=False)\n trackdetect = db.Column(db.String, nullable=False)\n\n\n # def __repr__(self):\n # return '' % self.name\n\n\n\n# user_choices = db.Table('users',\n# db.Column('annotations_trackid', db.Integer, db.ForeignKey('annotations.trackid'), primary_key=True),\n# db.Column('users_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)\n# )\n\n# class AnnotateUsers(db.Model):\n\n\n# __tablename__ = 'annotateusers'\n\n# id = db.Column(db.Integer, primary_key=True)\n# name = db.Column(db.String, default='Nobody', unique=False)\n# technology = db.Column(db.String, default='Nobody', unique=False)\n# detection_method = db.Column(db.String, default='Nobody', unique=False)\n# trackanno = db.Column(db.Integer, db.ForeignKey('annotations.trackid'), nullable=False)\n\n\n\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"436431936","text":"from flask import Flask,render_template, redirect, url_for, request\nfrom sense_hat import SenseHat \nimport sqlite3\napp = Flask(__name__)\nsense = SenseHat()\nname = \"yikers\"\n\n@app.route(\"/\")\ndef home_page():\n return render_template(\"name.html\")\n\n@app.route('/login',methods = ['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n user = request.form['nm']\n return redirect(url_for('text',name = user))\n else:\n user = request.args.get('nm')\n return redirect(url_for('text',name = user)) \n\n# Break this so I dont get brain cancer\n\n@app.route(\"/text/\") # Renders text html with /text\ndef text(name):\n return render_template(\"text.html\", name = name)\n\n@app.route('/text_recieved',methods = ['POST']) # Goes to this site to do something with text\ndef text_recieved():\n message = request.form['text']\n conn = sqlite3.connect('./static/data/senseDisplay.db')\n curs = conn.cursor()\n curs.execute(\"INSERT INTO messages (name, message) VALUES((?), (?))\",(name, message))\n\n conn.commit()\n conn.close()\n\n sense.show_message(message)\n return render_template(\"text_sent.html\", message = message)\n\n\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"Sensor_Hat_Project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365696333","text":"from inspect import signature\n\nimport requests\n\n\nclass APIError(Exception):\n \"\"\"An API Error Exception\"\"\"\n\n def __init__(self, status):\n self.status = status\n\n def __str__(self):\n return \"APIError: status={}\".format(self.status)\n\n\nclass api:\n\n def __init__(self, name):\n self.name = name\n\n # self.summoner()\n # self.context = None\n\n # def summoner(self):\n # print('called')\n # if self.action == 'movies':\n # self.get_movies()\n # if self.action == 'shows':\n # self.get_shows()\n # if self.action == 'search':\n # self.query_shows()\n\n def _url(self, path):\n return 'https://tv-v2.api-fetch.website' + path\n\n # def get_movies(self):\n # self.context = requests.get(self._url(self.movies_url))\n #\n # def get_shows(self):\n # self.context = requests.get(self._url(self.shows_url))\n #\n # def query_shows(self):\n # print(self._url(self.shows_url + '1?sort=name&order=1&keywords={}'.format(self.query)))\n # self.context = requests.get(self._url(self.shows_url + '/1?sort=name&order=1&keywords={}'.format(self.query)))\n # # print(self.context)\n\n def take_context(self):\n return self.context\n\n\nclass Movies(api):\n def __init__(self, page=None, sort=None, order=None, keywords=None, id=None, **kwargs):\n super(api, self).__init__(**kwargs)\n\n\n\nclass Shows(api):\n def __init__(self, page=None, sort=None, order=None, keywords=None, id=None, genre=None, **kwargs):\n super(api, self).__init__(**kwargs)\n self.url = self._url('/shows')\n self.query = {}\n if page:\n self.query['page'] = page\n if sort:\n self.query['sort'] = sort\n if order:\n self.query['order'] = order\n if id:\n self.query['id'] = id\n if id:\n self.query['genre'] = genre\n if keywords:\n self.query['keywords'] = str(keywords).replace(' ','%20')\n # self.get_shows()\n # self.bla()\n\n # def set_query(self):\n # if page:\n # self.query.append()\n def get_shows(self):\n self.context = requests.get(self.url)\n\n def get_search_shows(self):\n self.query_str = '/'\n if 'page' not in self.query:\n self.page = '1'\n self.query_str += self.page + '?'\n else:\n self.query_str = self.query_str + self.query['page'] + '?'\n\n for i in self.query:\n if i != 'id' and i != 'page':\n self.query_str = self.query_str + str(i) + '=' + str(self.query[i]) + '&'\n\n self._url_prepared = self.url + self.query_str[:-1]\n\n print(self._url_prepared)\n return requests.get(self._url_prepared)\n\n\n# def describe_task(task_id):\n# return requests.get(_url('/tasks/{:d}/'.format(task_id)))\n#\n# def add_task(summary, description=\"\"):\n# return requests.post(_url('/tasks/'), json={\n# 'summary': summary,\n# 'description': description,\n# })\n#\n# def task_done(task_id):\n# return requests.delete(_url('/tasks/{:d}/'.format(task_id)))\n#\n# def update_task(task_id, summary, description):\n# url = _url('/tasks/{:d}/'.format(task_id))\n# return requests.put(url, json={\n# 'summary': summary,\n# 'description': description,\n# })\n\n\n# resp = api('movie', 'movies').take_context()\n# if resp.status_code != 200:\n# raise APIError(resp.status_code)\n# # print(resp.headers)\n# # print(resp.content)\n# # print(resp.encoding)\n# # print(resp.url)\n# if 'application/json' in resp.headers['Content-Type']:\n# print(resp.headers.values())\n# print('json')\n# print('Got response: {}'.format(resp.json()))\n\n# pippp = Shows(genre='animation', order='1', sort='name').get_shows_page()\\\npippp = Shows(keywords='once upon a time', order='1', sort='name').get_search_shows()\n\nprint('Got response: {}'.format(pippp.json()))\n\n# resp = todo.get_tasks()\n# if resp.status_code != 200:\n# raise ApiError('Cannot fetch all tasks: {}'.format(resp.status_code))\n# for todo_item in resp.json():\n# print('{} {}'.format(todo_item['id'], todo_item['summary']))\n","sub_path":"Base_API/api_requests.py","file_name":"api_requests.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286543084","text":"\"\"\"\nClass that represents a single linked\nlist node that holds a single value\nand a reference to the next node in the list\n\"\"\"\n\n\nclass Node:\n def __init__(self, value=None, next_node=None):\n self.value = value\n self.next_node = next_node\n\n def __str__(self):\n return \"Value: {}\".format(self.value)\n\n def get_value(self):\n return self.value\n\n def get_next(self):\n return self.next_node\n\n def set_next(self, new_next):\n self.next_node = new_next\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def add_to_tail(self, value):\n node = Node(value)\n if self.head is None:\n self.head = node\n self.tail = self.head\n\n elif self.head.get_next is None:\n self.head.set_next(node)\n self.tail = self.head.get_next()\n else:\n self.tail.set_next(node)\n self.tail = self.tail.get_next()\n\n def remove_head(self):\n if self.head is not None:\n temp = self.head\n if self.head == self.tail:\n self.tail = None\n self.head = self.head.get_next()\n return temp.get_value()\n else:\n return None\n\n def contains(self, value):\n search = self.head\n while search is not None:\n if search.value == value:\n return True\n else:\n search = search.get_next()\n return False\n\n def get_max(self):\n search = self.head\n topVal = -10000\n if search is None:\n return None\n while search is not None:\n if search.value > topVal:\n topVal = search.value\n else:\n search = search.get_next()\n return topVal\n","sub_path":"linked_list/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353630748","text":"question = {\n \"number\": [35,36,40,44],\n \"number2\": [5,6,7,8],\n \"number3\": [9,10,11,12],\n}\ncount = 0\nques = 0\nprint(\"If x = 8, then what is value of 4(3+x) ??\")\nfs = question[\"number\"]\nfor i in range(len(fs)):\n print(i+1, fs[i], sep = \", \")\nans = int(input(\"Your choice: \"))\nif ans == 4:\n print(\":)) Bingo\")\n count += 1\n ques +=1\n \n print(\"Lional Messi wears some clothes ??\")\n for j in range(len(question[\"number3\"])):\n print(j+1, question[\"number3\"][j], sep = \", \")\n m = int(input(\"nhập số: \"))\n if m == 2:\n print(\"Bingo\")\n count += 1\n else:\n print(\"HiHi\")\n ques += 1\n print(\"Over\")\n \nelse: \n ques +=1\n print(\":(( Over\")\n print(\"You can countie...(Y/N) ??\")\n k = input(\"nhập : \")\n if k == \"Y\":\n print(\"Critino Ronaldo wears some clothes ??\") \n for i in range(len(question[\"number2\"])):\n print(i+1,question[\"number2\"][i], sep = \", \")\n \n n = int(input(\"nhập số : \")) \n if n == 3:\n print(\":)) Bingo\")\n count += 1\n ques += 1\n else:\n print(\"Nghỉ\")\n ques += 1\n \n else:\n print(\"End :))\")\nprint(count,\"/\",ques)\n\n\n","sub_path":"C4E26/Assignment4_2.py/quizfun.py","file_name":"quizfun.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"288569784","text":"__author__ = 'student'\nimport numpy as np\nvalues=[3, 4, 1, 2, 5, 6, 7, 8, 9, 10]\nfile_input = open('input.txt', 'r')\ndef get_percentile(values, bucket_number):\n a=[0.0]\n for i in range(1,bucket_number):\n a.append(np.percentile(values,i*100/(bucket_number)))\n return(a)\n\ndef get_percentile_number(value,percentiles):\n k=[]\n m=0\n for j in range (len(value)):\n for i in range(len(percentiles)-1):\n if percentiles[i]<=value[j] and value[j] < percentiles[i+1]:\n k.append(percentiles[i])\n m=1\n if m!=0:\n m=0\n elif value[j]