diff --git "a/402.jsonl" "b/402.jsonl"
new file mode 100644--- /dev/null
+++ "b/402.jsonl"
@@ -0,0 +1,629 @@
+{"seq_id":"460301343","text":"import importlib\n\nimport csvReader\nimport csv\nimport random\n\nselected_root_domain_values = list()\nstate_list = []\nfailed = False\nback_track_count = 0\nout = \"\"\n\n\ndef read_csv():\n \"\"\"\n The function reads the neighbor_state_dict from csv and sets state_domain_dict for the neighbor_state_dict read.\n :return: 2 dictionaries, one mapping state and its neighbours and the other\n mapping state and its state_domain_dict i.e valid assignable colors.\n \"\"\"\n global neighbor_state_dict, state_domain_dict\n neighbor_state_dict, state_domain_dict = csvReader.read_csv()\n global visited_node\n visited_node = set()\n global selected_dict\n selected_dict = dict()\n global selected_backtrack_node\n selected_backtrack_node = set()\n\n\ndef forward_checking_lcv(failed_index, state_domain_dict, neighbor_state_dict, is_backtrack=False, parent_domain_to_be_chosen=None):\n \"\"\"\n The function implements Forward Checking Algorithm to solve\n Map couloring problem\n :param failed_index:Start Index during backtracking process.\n :param state_domain_dict:Dictionary mapping states and their state_domain_dicts i.e List of legal colors available to be chosen.\n :param neighbor_state_dict: Dictionary mapping states and their neigbours\n :param is_backtrack: Flag to differentiate between backtracking process and the normal flow\n :param parent_domain_to_be_chosen: Parent Domain to be chosen once the algorithm reaches the root node and restarts the algorithm\n :return:\n \"\"\"\n global back_track_count\n global failed\n global out\n key = state_list[0]\n i = failed_index\n while i < len(state_list):\n\n previous_selected_parent_domain = None\n key = state_list[i]\n if len(state_domain_dict[key]) <= 0:\n back_track_count += 1\n out += key.lower() + \",\" + \"White\" + \"\\n\"\n failed = True\n failed_index = i\n break\n else:\n failed = False\n if key not in visited_node and len(state_domain_dict[key]) > 0:\n if is_backtrack and selected_dict.get(key, None) is not None:\n previous_selected_parent_domain = selected_dict.get(key).pop()\n if previous_selected_parent_domain in state_domain_dict[key]:\n state_domain_dict[key].remove(previous_selected_parent_domain)\n if len(selected_dict[key]) == 0:\n del selected_dict[key]\n if parent_domain_to_be_chosen is not None and key == state_list[0]:\n parent_domain = parent_domain_to_be_chosen\n previous_selected_parent_domain = selected_root_domain_values[-1]\n else:\n parent_domain = lcv(key, state_domain_dict, neighbor_state_dict, selected_dict)\n state_domain_dict[key].remove(parent_domain)\n selected_dict.setdefault(key, list()).append(parent_domain)\n visited_node.add(key)\n for neighbours in neighbor_state_dict[key]:\n if previous_selected_parent_domain is not None and previous_selected_parent_domain not in state_domain_dict[neighbours]:\n if neighbours in selected_dict.keys() and previous_selected_parent_domain not in selected_dict[neighbours]:\n state_domain_dict[neighbours].append(previous_selected_parent_domain)\n if parent_domain in state_domain_dict[neighbours] and neighbours not in list(visited_node):\n state_domain_dict[neighbours].remove(parent_domain)\n i += 1\n out += key.lower() + \",\" + parent_domain + \"\\n\"\n if failed:\n length = len(list(selected_backtrack_node))\n if length > 0:\n last_element = list(sorted(selected_backtrack_node))[0]\n failed_index = last_element - 1\n else:\n failed_index -= 1\n while len(state_domain_dict[state_list[failed_index]]) <= 1:\n failed_index -= 1\n selected_backtrack_node.add(failed_index)\n if failed_index > 0:\n visited_node.clear()\n forward_checking_lcv(failed_index, state_domain_dict, neighbor_state_dict, True, None)\n else:\n state_domain_dict_list = ['Red', 'Green', 'Blue', 'Yellow']\n previous_root_values = selected_dict[state_list[0]]\n selected_root_domain_values.extend(previous_root_values)\n for previous_domain in selected_root_domain_values:\n state_domain_dict_list.remove(previous_domain)\n if len(state_domain_dict_list) == 0:\n return\n read_csv()\n forward_checking_lcv(0, state_domain_dict, neighbor_state_dict, True, state_domain_dict_list[0])\n else:\n pass\n\n\ndef lcv(key_state, state_domain, neighbour_list, selected_dict):\n \"\"\"\n :param key: The state for which color have to be selected\n :param state_domain: Dictionary mapping states and their state_domain_dicts i.e List of legal colors available to be chosen.\n :param neighbour_list: Dictionary mapping states and their neigbours\n :return:\n \"\"\"\n num_neighbour_colors = 0\n color_dict = dict()\n for color in state_domain[key_state]:\n for neighbour in neighbour_list[key_state]:\n if neighbour not in selected_dict.keys():\n if color in state_domain[neighbour]:\n if len(state_domain[neighbour]) - 1 == 0:\n color_dict[color] = float(\"inf\")\n else:\n num_neighbour_colors += len(state_domain[neighbour]) - 1\n\n if color not in color_dict.keys():\n color_dict[color] = num_neighbour_colors\n\n return min(color_dict, key=lambda k: color_dict[k])\n\n\ndef main():\n importlib.reload(csvReader)\n read_csv()\n global state_list\n state_list = ['WA', 'OR', 'CA', 'NV', 'ID', 'MT', 'WY', 'UT', 'AZ', 'NM', 'CO', 'ND', 'SD', 'NE', 'KS', 'OK', 'TX', 'MN', 'IA', 'MO', 'AR', 'LA', 'MS', 'AL', 'FL', 'GA', 'SC', 'NC', 'TN', 'KY', 'VA', 'DE', 'MD', 'WV', 'OH', 'IN', 'IL', 'WI', 'MI', 'PA', 'NJ', 'CT', 'RI', 'NY', 'VT', 'NH', 'MA', 'ME', 'AK', 'HI', 'DC']\n forward_checking_lcv(0, state_domain_dict, neighbor_state_dict)\n print(\"Backtrack Count\", back_track_count)\n return out\n","sub_path":"Map-Coloring-Problem- Intelligent Systems/MapColoringBackend-master/ForwardChecking_LCV.py","file_name":"ForwardChecking_LCV.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"456516037","text":"# Run with TF 2.0+\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport tensorflow_datasets as tfds\nimport cv2\nfrom glob import glob\nimport numpy as np\n# Convert the model.\n\ninput_height = 992\ninput_width = 1504\nh_to_w_ratio = input_height /input_width\nnum_calibration_steps = 20\n\n\ndef representative_dataset_gen():\n sample_folder = glob('{}/*.*'.format('samples'))\n data = [load_test_data(sample_file) for sample_file in tqdm(sample_folder)]\n # data = tfds.load(data)\n\n for _ in range(num_calibration_steps):\n image = data.pop()\n yield [image]\n\n\ndef load_test_data(image_path):\n img = cv2.imread(image_path).astype(np.uint8)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = crop(img)\n img = preprocessing(img)\n img = np.expand_dims(img, axis=0)\n return img\n\ncrop_image = lambda img, x0, y0, w, h: img[y0:y0+h, x0:x0+w]\n\ndef crop(img):\n h, w = img.shape[:2]\n # if (h < input_height) or (w < input_width):\n # print(\"Error, please make sure the image is at least\" + str(input_width) + \"x\" + str(input_height))\n # return;\n if (h != input_height) or (w != input_width):\n if(h > w):\n print(\"Error, please make sure the image is in landscape mode\")\n return;\n else:\n crop_height = int(w * h_to_w_ratio)\n height_middle_point = int(h / 2)\n cropped_image = crop_image(img, 0, height_middle_point - int(crop_height / 2), w, crop_height)\n return cropped_image.astype(np.float32)\n else:\n return img\n \n\ndef preprocessing(img):\n img = cv2.resize(img, (input_width, input_height))\n print(input_width)\n print(input_height)\n return img/127.5 - 1.0\n\n\ndef save_images(images, image_path):\n # return imsave(inverse_transform(images), size, image_path)\n return imsave(inverse_transform(images.squeeze()).astype(np.uint8), image_path)\n\ndef inverse_transform(images):\n return (images+1.) / 2 * 255\n\n\ndef imsave(images, path):\n # return misc.imsave(path, images)\n return cv2.imwrite(path, cv2.cvtColor(images, cv2.COLOR_BGR2RGB))\n\n\nmodel = tf.saved_model.load('./')\nconcrete_func = model.signatures[\n tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n\n'''keep the ratio as close to 3/2 while being divisible by 32'''\nconcrete_func.inputs[0].set_shape([1, input_height, input_width, 3])\nconverter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\nconverter.representative_dataset = tf.lite.RepresentativeDataset(\n representative_dataset_gen)\ntflite_model = converter.convert()\nopen(\"./converted_model.tflite\",\"wb\").write(tflite_model)\n","sub_path":"models/TFLite/saved_model_to_tflite_int_quantized.py","file_name":"saved_model_to_tflite_int_quantized.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"125725262","text":"class Settings:\n \"\"\"A class to store all settings for Alien Invasion.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game's settings.\"\"\"\n # Screen settings\n self.screen_width = 1200\n self.screen_height = 800\n self.bg_colour = (30, 30, 14)\n\n self.ship_limit = 3\n self.ship_speed = 1.5\n\n self.bullet_speed = 1.5\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_colour = (60, 60, 60)\n self.bullets_allowed = 3\n\n self.alien_speed = 1\n self.fleet_drop_speed = 10\n # fleet_direction of 1 represents right; -1 represents left.\n self.fleet_direction = 1\n\n # How quickly the game speeds up\n self.speedup_scale = 1.1\n\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n \"\"\"Initialize settings that change throughout the game.\"\"\"\n self.ship_speed = 1.5\n self.bullet_speed = 3.0\n self.alien_speed = 1.0\n\n # fleet_direction of 1 represents right; -1 represents left.\n self.fleet_direction = 1\n\n # Scoring\n self.alien_points = 50\n\n def increase_speed(self):\n \"\"\"Increase speed settings.\"\"\"\n self.ship_speed *= self.speedup_scale\n self.bullet_speed *= self.speedup_scale\n self.alien_speed *= self.speedup_scale\n\n def _print_settings(self):\n print(f'Ship speed: {self.ship_speed} - Bullet speed: {self.bullet_speed} - Alien speed: {self.alien_speed}\\n')\n","sub_path":"alien_invasion/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"516223979","text":"'''\r\nfirst strip out the constant and coefficent, \r\nperform a simple simplication\r\nreturn as string \r\n'''\r\n\r\ndef parser(a):\r\n a_a = a.index('+')\r\n a_a_num = int(a[:a_a] )\r\n a_b_num = int(a[a_a+1:-1])\r\n \r\n return a_a_num, a_b_num\r\n\r\nclass Solution(object):\r\n \r\n def complexNumberMultiply(self, a, b):\r\n \"\"\"\r\n :type a: str\r\n :type b: str\r\n :rtype: str\r\n \"\"\"\r\n first_a, first_b = parser(a) \r\n second_a, second_b = parser(b) \r\n \r\n val_1 = first_a * second_a\r\n val_2 = (first_a * second_b) + (first_b * second_a) # i coefficent\r\n val_3 = first_b * second_b * -1 # i^2 coefficent \r\n return str(val_1 + val_3 )+ \"+\"+str(val_2) + \"i\"","sub_path":"LeetCode/ComplexNumberMultiply.py","file_name":"ComplexNumberMultiply.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"347970121","text":"## @ StitchIfwi.py\n# This is a python stitching script for Slim Bootloader TGL build\n#\n# Copyright (c) 2019 - 2022, Intel Corporation. All rights reserved.
\n# SPDX-License-Identifier: BSD-2-Clause-Patent\n#\n##\n\nimport sys\nimport os\nimport re\nimport imp\nimport struct\nimport argparse\nimport zipfile\nimport shutil\nimport glob\nimport shlex\nimport subprocess\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\nfrom ctypes import *\nfrom subprocess import call\nfrom StitchLoader import *\nfrom security_stitch_help import *\nsys.dont_write_bytecode = True\n\n\n# sign_bin_flag can be set to false to avoid signing process. Applicable for Btg profile 0\nsign_bin_flag = True\n\nsblopen_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))\nif not os.path.exists (sblopen_dir):\n sblopen_dir = os.getenv('SBL_SOURCE', '')\nif not os.path.exists (sblopen_dir):\n raise Exception(\"Please set env 'SBL_SOURCE' to SBL open source root folder\")\n\ndef gen_xml_file(stitch_dir, stitch_cfg_file, btg_profile, plt_params_list, platform, tpm):\n print (\"Generating xml file .........\")\n\n fit_tool = os.path.join (stitch_dir, 'Fit', 'fit')\n new_xml_file = os.path.join (stitch_dir, 'Temp', 'new.xml')\n updated_xml_file = os.path.join (stitch_dir, 'Temp', 'updated.xml')\n sku = stitch_cfg_file.get_platform_sku().get(platform)\n cmd = [fit_tool, '-sku', sku, '-save', new_xml_file, '-w', os.path.join (stitch_dir, 'Temp')]\n run_process (cmd)\n\n tree = ET.parse(new_xml_file)\n\n xml_change_list = stitch_cfg_file.get_xml_change_list (platform, plt_params_list)\n for each in xml_change_list:\n for xml_path, value in each:\n node = tree.find('%s' % xml_path)\n node.set('value', value)\n print (value)\n\n tree.write(updated_xml_file)\n\ndef replace_component (ifwi_src_path, flash_path, file_path, comp_alg, pri_key):\n print (\"Replacing components.......\")\n work_dir = os.getcwd()\n ifwi_bin = bytearray (get_file_data (ifwi_src_path))\n ifwi = IFWI_PARSER.parse_ifwi_binary (ifwi_bin)\n\n # assume a flash map path first\n comp_name = ''\n replace_comps = IFWI_PARSER.locate_components (ifwi, flash_path)\n if len(replace_comps) == 0:\n # assume a container path if not in flash map\n nodes = flash_path.split('/')\n comp_name = nodes[-1]\n flash_path = '/'.join(nodes[:-1])\n replace_comps = IFWI_PARSER.locate_components (ifwi, flash_path)\n\n if len(replace_comps) == 0:\n raise Exception (\"Could not locate component '%s' !\" % flash_path)\n\n if len(replace_comps) > 1:\n raise Exception (\"Multiple components were located for '%s' !\" % flash_path)\n\n replace_comp = replace_comps[0]\n if comp_name:\n # extract container image\n container_file = os.path.join(work_dir, 'CTN_%s.bin') % comp_name\n gen_file_from_object (container_file, ifwi_bin[replace_comp.offset:replace_comp.offset + replace_comp.length])\n comp_file = os.path.join(work_dir, file_path)\n\n if os.name == 'nt':\n tool_bin_dir = os.path.join(sblopen_dir, \"BaseTools\", \"Bin\", \"Win32\")\n else:\n tool_bin_dir = os.path.join(sblopen_dir, \"BaseTools\", \"BinWrappers\", \"PosixLike\")\n gen_container = os.path.join(sblopen_dir, \"BootloaderCorePkg\" , \"Tools\", \"GenContainer.py\")\n if not os.path.isabs(pri_key):\n pri_key = os.path.join (work_dir, pri_key)\n cmd_line = [sys.executable, gen_container, 'replace', '-i', container_file, '-o', container_file, '-n', comp_name,\n '-f', comp_file, '-c', comp_alg, '-k', pri_key, '-td', tool_bin_dir]\n run_process (cmd_line, True)\n comp_bin = bytearray (get_file_data (container_file))\n else:\n # replace directly in flash map\n comp_bin = bytearray (get_file_data (file_path))\n IFWI_PARSER.replace_component (ifwi_bin, comp_bin, flash_path)\n gen_file_from_object (ifwi_src_path, ifwi_bin)\n\ndef replace_components (ifwi_src_path, stitch_cfg_file):\n print (\"Replacing components.......\")\n replace_list = stitch_cfg_file.get_component_replace_list ()\n for flash_path, file_path, comp_alg, pri_key in replace_list:\n replace_component (ifwi_src_path, flash_path, file_path, comp_alg, pri_key)\n\ndef stitch (stitch_dir, stitch_cfg_file, sbl_file, btg_profile, plt_params_list, platform_data, platform, tpm, full_rdundant = True):\n temp_dir = os.path.abspath(os.path.join (stitch_dir, 'Temp'))\n if os.path.exists(temp_dir):\n shutil.rmtree(temp_dir, ignore_errors=True)\n shutil.copytree (os.path.join (stitch_dir, 'Input'), temp_dir)\n\n # Get bios region image ready\n sbl_image_ext = os.path.splitext(sbl_file)\n\n if sbl_image_ext[1] != \".zip\":\n print (\"\\nCopy SBL image %s for stitch\" % sbl_file)\n shutil.copy(sbl_file, os.path.join(temp_dir, \"SlimBootloader.bin\"))\n else:\n print (\"\\nUnpack files from zip file ...\")\n zf = zipfile.ZipFile(sbl_file, 'r', zipfile.ZIP_DEFLATED)\n zf.extractall(temp_dir)\n zf.close()\n\n if platform_data:\n fd = open(os.path.join(temp_dir, \"SlimBootloader.bin\"), \"rb\")\n input_data = bytearray(fd.read())\n fd.close()\n print (\"\\n Adding platform data to Slimbootloader ...\")\n data = add_platform_data(input_data, platform_data)\n fd = open(os.path.join(temp_dir, \"SlimBootloader.bin\"), \"wb\")\n fd.write(data)\n fd.close()\n\n print(\"Replace components in both partitions....\")\n replace_components (os.path.join(temp_dir, \"SlimBootloader.bin\"), stitch_cfg_file)\n\n # Generate xml\n gen_xml_file(stitch_dir, stitch_cfg_file, btg_profile, plt_params_list, platform, tpm)\n\n if sign_bin_flag:\n update_btGuard_manifests(stitch_dir, stitch_cfg_file, btg_profile, tpm)\n else:\n shutil.copy(os.path.join(temp_dir, \"SlimBootloader.bin\"), os.path.join(temp_dir, \"BiosRegion.bin\"))\n\n print (\"Run fit tool to generate ifwi.........\")\n run_process (['./Fit/fit', '-b', '-o', 'Temp/Ifwi.bin', '-f', os.path.join (temp_dir, 'updated.xml'),\n '-s', temp_dir, '-w', temp_dir, '-d', temp_dir])\n return 0\n\ndef get_para_list (plt_para):\n para_lst = dict()\n for idx, para in enumerate(plt_para):\n items = para.split(':')\n item_cnt = len(items)\n para_lst.update( {items[0] : None if (item_cnt == 1) else items[1].strip()})\n return para_lst\n\ndef main():\n hexstr = lambda x: int(x, 16)\n ap = argparse.ArgumentParser()\n ap.add_argument('-p', dest='platform', default = '', help='specify platform sku to stitch')\n ap.add_argument('-w', dest='work_dir', default = '', help='specify stitch workspace directory, CSME tools and ingredients should be here')\n ap.add_argument('-c', dest='config_file', type=str, required=True, help='specify the platform specific stitch config file')\n ap.add_argument('-s', dest='sbl_file', type=str, default='stitch_Components.zip', help='specify slim bootloader file or generate zip file')\n ap.add_argument('-b', dest='btg_profile', default = 'vm', choices=['legacy', 'vm', 'fve', 'fvme'], help='specify Boot Guard profile type')\n ap.add_argument('-d', dest='plat_data', type=hexstr, default=None, help='Specify a platform specific data (HEX, DWORD) for customization')\n ap.add_argument('-r', dest='remove', action = \"store_true\", default = False, help = \"delete temporary files after stitch\")\n ap.add_argument('-t', dest='tpm', default = 'ptt', choices=['ptt', 'dtpm', 'none'], help='specify TPM type')\n ap.add_argument('-o', dest='option', default = '', help = \"Platform specific stitch option. Format: '-o option1;option2;...' For each option its format is 'parameter:data'. Try -o help for more information\")\n ap.add_argument('-op', dest='outpath', default = '', help = \"Specify path to write output IFIW and signed bin files\")\n\n args = ap.parse_args()\n\n stitch_cfg_file = imp.load_source('StitchIfwiConfig', args.config_file)\n if args.work_dir == '':\n print (\"Please specify stitch work directory\")\n print ('%s' % stitch_cfg_file.extra_usage_txt)\n return 1\n\n sku_dict = stitch_cfg_file.get_platform_sku()\n if len (sku_dict) == 1 and args.platform == '':\n for sku in sku_dict:\n args.platform = sku\n print (\"No sku is given, set to default sku value %s\" % sku)\n if args.platform == '' or args.platform not in sku_dict:\n print (\"Invalid sku (%s), Please provide valid sku:\" % args.platform)\n for sku in sku_dict :\n print (\" %s - 'For %s'\" % (sku, sku_dict[sku]))\n return 1\n\n if args.btg_profile in [\"vm\",\"fvme\"] and args.tpm == \"none\":\n print (\"ERROR: Choose appropriate Tpm type for BootGuard profile 3 and 5\")\n return 1\n\n plt_params_list = get_para_list (args.option.split(';'))\n if not stitch_cfg_file.check_parameter(plt_params_list):\n exit (1)\n\n print (\"Executing stitch.......\")\n curr_dir = os.getcwd()\n sbl_file = os.path.abspath(os.path.join (curr_dir, args.sbl_file))\n\n work_dir = os.path.abspath (args.work_dir)\n os.chdir(work_dir)\n if stitch (work_dir, stitch_cfg_file, sbl_file, args.btg_profile, plt_params_list, args.plat_data, args.platform, args.tpm):\n raise Exception ('Stitching process failed !')\n os.chdir(curr_dir)\n\n generated_ifwi_file = os.path.join(work_dir, 'Temp', 'Ifwi.bin')\n ifwi_file_name = os.path.join(args.outpath,'sbl_ifwi_%s.bin' % (args.platform))\n shutil.copy(generated_ifwi_file, ifwi_file_name)\n\n generated_signed_sbl = os.path.join(work_dir, 'Temp', 'SlimBootloader.bin')\n sbl_file_name = os.path.join(args.outpath,'SlimBootloader_%s.bin' % (args.platform))\n shutil.copy(generated_signed_sbl, sbl_file_name)\n\n print (\"\\nIFWI Stitching completed successfully !\")\n print (\"Boot Guard Profile: %s\" % args.btg_profile.upper())\n print (\"IFWI image: %s\\n\" % ifwi_file_name)\n if args.remove:\n shutil.rmtree(os.path.join(work_dir, 'Temp'), ignore_errors=True)\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"Platform/TigerlakeBoardPkg/Script/StitchIfwi.py","file_name":"StitchIfwi.py","file_ext":"py","file_size_in_byte":10158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"549114584","text":"import os.path\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\nfrom django.core.files.base import ContentFile\nfrom django.dispatch import receiver\nimport taglib\nfrom mutagen import File\n\nclass Album(models.Model):\n\tname = models.CharField(max_length=64,default=\"\")\n\t\n\tdef get_absolute_url(self):\n\t\treturn reverse('album.detail', args=[str(self.id)])\n\nclass Artist(models.Model):\n\tname = models.CharField(max_length=64,default=\"\")\n\t\nclass Track(models.Model):\n\tTYPE_MP3 = \"audio/mpeg\"\n\tTYPE_OGG = \"audio/ogg\"\n\tFILE_TYPES = (\n\t\t(TYPE_MP3,\"mp3\"),\n\t\t(TYPE_OGG,\"ogg\"),\n\t)\n\tartwork = models.ImageField(upload_to='music/tracks')\n\ttitle = models.CharField(max_length=64,default=\"\")\n\talbum = models.ForeignKey(Album, on_delete=models.CASCADE, null = True)\n\tartist = models.CharField(max_length=64,default=\"\")\n\tgenre = models.CharField(max_length=64,default=\"\")\n\tname = models.CharField(max_length=50,default=\"\")\n\ttype = models.CharField(max_length=20, choices=FILE_TYPES)\n\tfile = models.FileField(upload_to='music/tracks')\n\t\n\tdef get_absolute_url(self):\n\t\treturn reverse('track.detail', args=[str(self.id)])\n\t\n\t\n\tdef updateMetadataSave(self):\n\t\tself.updateMetadata()\n\t\tself.save()\n\t\n\tdef setFieldFromTags(self,tags,tag_title,field_name):\n\t\tif tags.get(tag_title) != None:\n\t\t\tfield = ''\n\t\t\tfor tag_title in tags.get(tag_title):\n\t\t\t\tfield = getattr(self, field_name)\n\t\t\t\tfield = ''\n\t\t\t\tfield += tag_title + ' '\n\t\t\tsetattr(self, field_name, field)\n\n\tdef updateMetadata(self):\n\t\tsong = taglib.File(self.file.path)\t\t\n\t\tself.setFieldFromTags(song.tags,'TITLE','title')\n\t\tif song.tags.get('ALBUM') != None:\n\t\t\tfor album_name in song.tags.get('ALBUM'):\n\t\t\t\ttry:\n\t\t\t\t\talbum = Album.objects.get(name=album_name)\n\t\t\t\t\tself.album = album\n\t\t\t\texcept Album.DoesNotExist:\n\t\t\t\t\tnew_album = Album(name=album_name)\n\t\t\t\t\tnew_album.save()\n\t\t\t\t\tself.album = new_album\n\n\t\tself.setFieldFromTags(song.tags,'ARTIST','artist')\n\t\tself.setFieldFromTags(song.tags,'GENRE','genre')\n\t\tfile = File(self.file.path)\n\t\tif file.tags != None:\n\t\t\tfor tag in file.tags:\n\t\t\t\tif tag.startswith(\"APIC\"):\n\t\t\t\t\tartwork = file.tags[tag].data\n\t\t\t\t\tself.artwork.save('art.jpg',ContentFile(artwork))\n\t\t\t\t\tbreak\n\n\t\tfileName, fileExtension = os.path.splitext(self.file.name)\n\t\tif(fileExtension == '.mp3'):\n\t\t\tself.type = self.TYPE_MP3\n\t\telif(fileExtension == '.ogg'):\n\t\t\tself.type = self.TYPE_OGG\n","sub_path":"wolf_services/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"72166452","text":"from .scholix_v1 import api_v1\n\n\nlinks_from_datasource_parser = api_v1.parser()\nlinks_from_datasource_parser.add_argument('datasource', required=True,\n help=\"Filter Scholix relationships collected from a LinkProvider\")\nlinks_from_datasource_parser.add_argument('page', required=False, help=\"select page of result\")\n\nlinks_from_pid_parser = api_v1.parser()\nlinks_from_pid_parser.add_argument(\"pid\", required=True, help=\"persistent Identifier\")\nlinks_from_pid_parser.add_argument(\"pidType\", required=False, help=\"persistent Identifier Type\")\nlinks_from_pid_parser.add_argument(\"targetPidType\", required=False,\n help=\"typology target filter should be publication, dataset or unknown\")\nlinks_from_pid_parser.add_argument(\"datasourceTarget\", required=False,\n help=\"a datasource provenace filter of the target relation\")\nlinks_from_pid_parser.add_argument(\"page\", required=False, help=\"select page of result\")\n\nlinks_from_publisher_parser = api_v1.parser()\nlinks_from_pid_parser.add_argument(\"publisher\", required=True, help=\"publisher name\")\nlinks_from_publisher_parser.add_argument(\"page\", required=False, help=\"select page of result\")","sub_path":"apis/v1/parser_arguments.py","file_name":"parser_arguments.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"603850950","text":"# module for textadvzix\n\n\n# represents the user\nclass User:\n def __init__(self, name, x=0, y=0):\n self.name = name\n self.x = x\n self.y = y\n self.coords = str(x) + \"x\" + str(y)\n","sub_path":"User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"384601383","text":"\"\"\"\nBasic group long polling example.\n\nCaution: don't store credentials and settings in your git. Use env variables or config file\nWe set it here to simplify the example.\n\n\n\"\"\"\nfrom avkapi import VK\nfrom avkapi import types\nfrom avkapi.dispatcher import Dispatcher\nfrom avkapi.utils.executor import start_polling\n\n# Set your VK credentials.\nVK_ACCESS_TOKEN = '2e37d9dd8f06e2ccf8dae5'\nVK_GROUP_ID = 123456\n\n\n# Create vk instance\n# You can use it for simple calling VK API methods\nvk = VK(access_token=VK_ACCESS_TOKEN)\n\n# Create dispatcher instance\n# You need to use a dispatcher for handling incoming messages from your users\ndp = Dispatcher(vk)\n\n\n@dp.message_handler(content_types=types.MessageType.MESSAGE_NEW)\nasync def echo_handler(message: types.Message):\n \"\"\" Handler catches all incoming messages and sends back the same. \"\"\"\n # calling message.send method\n await vk.messages.send(message=message.text, peer_id=message.peer_id)\n\n\nasync def shutdown(_: Dispatcher):\n \"\"\" Graceful application shutdown. \"\"\"\n await vk.close()\n\n\nif __name__ == '__main__':\n start_polling(dp, group_id=VK_GROUP_ID, on_shutdown=shutdown)\n\n","sub_path":"examples/echo_bot_polling.py","file_name":"echo_bot_polling.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"213411493","text":"from django.conf.urls import include\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom django.urls import path\nfrom django.views.generic.base import RedirectView\nfrom drf_spectacular.views import (\n SpectacularAPIView,\n SpectacularRedocView,\n SpectacularSwaggerView,\n)\n\nfrom auth.views.authtoken import authtoken\nfrom rr.routers import router\nfrom rr.views.attribute import attribute_admin_list, attribute_list, attribute_view\nfrom rr.views.certificate import (\n certificate_admin_list,\n certificate_info,\n certificate_list,\n)\nfrom rr.views.contact import contact_list\nfrom rr.views.email import email_list\nfrom rr.views.endpoint import endpoint_list\nfrom rr.views.login import ShibbolethLoginView, logout_redirect\nfrom rr.views.metadata import metadata, metadata_import, metadata_management\nfrom rr.views.redirecturi import redirecturi_list\nfrom rr.views.serviceprovider import (\n BasicInformationUpdate,\n BasicInformationView,\n LdapServiceProviderCreate,\n LdapTechnicalInformationUpdate,\n OidcServiceProviderCreate,\n OidcTechnicalInformationUpdate,\n SAMLAdminList,\n SamlServiceProviderCreate,\n SamlTechnicalInformationUpdate,\n ServiceProviderDelete,\n ServiceProviderList,\n)\nfrom rr.views.sp_errors import sp_error\nfrom rr.views.spadmin import activate_key, admin_list\nfrom rr.views.statistics import statistics_list, statistics_summary_list\nfrom rr.views.testuser import testuser_attribute_data, testuser_list\nfrom rr.views.usergroup import usergroup_list\n\n# Overwrite default status handlers\nhandler400 = \"rr.views.handlers.bad_request\"\nhandler403 = \"rr.views.handlers.permission_denied\"\nhandler404 = \"rr.views.handlers.page_not_found\"\nhandler500 = \"rr.views.handlers.server_error\"\n\nurlpatterns = [\n path(\"api/v1/\", include(router.urls)),\n path(\"api/schema/\", SpectacularAPIView.as_view(), name=\"schema\"),\n path(\"api/schema/swagger/\", SpectacularSwaggerView.as_view(url_name=\"schema\"), name=\"swagger-ui\"),\n path(\"api/schema/redoc/\", SpectacularRedocView.as_view(url_name=\"schema\"), name=\"redoc\"),\n path(\"swagger/\", RedirectView.as_view(url=\"/api/schema/swagger/\")),\n path(\"admin_django/doc/\", include(\"django.contrib.admindocs.urls\")),\n path(\"admin_django/\", admin.site.urls),\n path(\"\", login_required(ServiceProviderList.as_view()), name=\"front-page\"),\n path(\"authtoken/\", authtoken, name=\"auth-token\"),\n path(\"login/\", LoginView.as_view(), name=\"login\"),\n path(\"login/shibboleth/\", ShibbolethLoginView.as_view(), name=\"shibboleth-login\"),\n path(\"logout/\", logout_redirect, name=\"logout\"),\n path(\n \"logout/local/\",\n LogoutView.as_view(template_name=\"registration/logout.html\", redirect_field_name=\"return\"),\n name=\"logout-local\",\n ),\n path(\"list/\", login_required(ServiceProviderList.as_view()), name=\"serviceprovider-list\"),\n path(\"admin//\", admin_list, name=\"admin-list\"),\n path(\"attribute//\", attribute_list, name=\"attribute-list\"),\n path(\"attribute/list/\", attribute_admin_list, name=\"attribute-admin-list\"),\n path(\"attribute/view//\", attribute_view, name=\"attribute-view\"),\n path(\"certificate//\", certificate_list, name=\"certificate-list\"),\n path(\"certificate/info//\", certificate_info, name=\"certificate-info\"),\n path(\"certificate/list/\", certificate_admin_list, name=\"certificate-admin-list\"),\n path(\"contact//\", contact_list, name=\"contact-list\"),\n path(\"endpoint//\", endpoint_list, name=\"endpoint-list\"),\n path(\"email/\", email_list, name=\"email-list\"),\n path(\"metadata/import/\", metadata_import, name=\"metadata-import\"),\n path(\"metadata/manage/saml/\", metadata_management, {\"service_type\": \"saml\"}, name=\"metadata-manage-saml\"),\n path(\"metadata/manage/ldap/\", metadata_management, {\"service_type\": \"ldap\"}, name=\"metadata-manage-ldap\"),\n path(\"metadata/manage/oidc/\", metadata_management, {\"service_type\": \"oidc\"}, name=\"metadata-manage-oidc\"),\n path(\"metadata//\", metadata, name=\"metadata-view\"),\n path(\"redirecturi//\", redirecturi_list, name=\"redirecturi-list\"),\n path(\n \"technical//\",\n login_required(SamlTechnicalInformationUpdate.as_view()),\n name=\"technical-update\",\n ),\n path(\n \"ldap//\",\n login_required(LdapTechnicalInformationUpdate.as_view()),\n name=\"ldap-technical-update\",\n ),\n path(\n \"oidc//\",\n login_required(OidcTechnicalInformationUpdate.as_view()),\n name=\"oidc-technical-update\",\n ),\n path(\n \"serviceprovider/add/saml/\",\n login_required(SamlServiceProviderCreate.as_view()),\n name=\"saml-serviceprovider-add\",\n ),\n path(\n \"serviceprovider/add/ldap/\",\n login_required(LdapServiceProviderCreate.as_view()),\n name=\"ldap-serviceprovider-add\",\n ),\n path(\n \"serviceprovider/add/oidc/\",\n login_required(OidcServiceProviderCreate.as_view()),\n name=\"oidc-serviceprovider-add\",\n ),\n path(\n \"serviceprovider/remove//\",\n login_required(ServiceProviderDelete.as_view()),\n name=\"serviceprovider-delete\",\n ),\n path(\n \"serviceprovider//\",\n login_required(BasicInformationUpdate.as_view()),\n name=\"basicinformation-update\",\n ),\n path(\"saml_admin_list/\", login_required(SAMLAdminList.as_view()), name=\"saml-admin-list\"),\n path(\"statistics/summary/\", statistics_summary_list, name=\"statistics-summary-list\"),\n path(\"statistics//\", statistics_list, name=\"statistics-list\"),\n path(\"summary//\", login_required(BasicInformationView.as_view()), name=\"summary-view\"),\n path(\"testuser//\", testuser_list, name=\"testuser-list\"),\n path(\"testuser/data//\", testuser_attribute_data, name=\"testuser-attribute-data\"),\n path(\"usergroup//\", usergroup_list, name=\"usergroup-list\"),\n path(\"invite/\", activate_key, name=\"invite-activate\"),\n path(\"invite//\", activate_key, name=\"invite-activate-key\"),\n path(\"error/\", sp_error, name=\"error\"),\n path(\"\", include(\"django.contrib.auth.urls\")),\n path(\"i18n/\", include(\"django.conf.urls.i18n\")),\n]\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"104987721","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/12/14 23:33\n# @Author : play4fun\n# @File : t1.py\n# @Software: PyCharm\n\n\"\"\"\nt1.py:\n\"\"\"\nfrom time import sleep\nfrom uf.wrapper.swift_api import SwiftAPI\nfrom uf.utils.log import *\n\nlogger_init(logging.VERBOSE)\n# logger_init(logging.DEBUG)\n# logger_init(logging.INFO)\n\nprint('setup swift ...')\n\n# swift = SwiftAPI(dev_port = '/dev/ttyACM0')\n# swift = SwiftAPI(filters = {'hwid': 'USB VID:PID=2341:0042'})\nswift = SwiftAPI() # default by filters: {'hwid': 'USB VID:PID=2341:0042'}\nprint('sleep 2 sec ...')\nsleep(2)\n\nprint('device info: ')\nprint(swift.get_device_info())\nsleep(2)\n# swift.reset()\nswift.set_position(x=300, wait=True)\nsleep(3)\nprint(swift.get_position())\nsleep(3)\nswift.set_position(y=0, wait=True)\nsleep(3)\n\n# swift.set_position(x=200,y=0, z=45, wait=True)\nswift.set_position(z=85, wait=True)\nsleep(2)\nfor x in range(0, 180,30):\n swift.set_wrist(angle=x, wait=True)\n sleep(0.2)\nswift.set_wrist(angle=90, wait=True)\nswift.set_buzzer()\nsleep(2)\nswift.set_position(x=300, y=0, z=110, wait=True)\n\n#\nswift.set_position(x=330, y=0, z=85, wait=True)\nsleep(2)\nfor x in range(0, 180,30):\n swift.set_wrist(angle=x, wait=True)\n sleep(0.2)\nswift.set_wrist(angle=90, wait=True)\nswift.set_buzzer()\nsleep(2)\n\nprint('finished')\ntry:\n while True:\n sleep(1)\nexcept KeyboardInterrupt as e:\n print('KeyboardInterrupt',e)\nfinally:\n swift.reset()\n","sub_path":"毛笔字/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"363828266","text":"import RPi.GPIO as GPIO\nimport time\nimport threading\n\n\n\nFL_TRIG = 20\nFL_ECHO = 11\nFC_TRIG = 26\nFC_ECHO = 8\nFR_TRIG = 21\nFR_ECHO = 7\n\nclass sonicSensor(object):\n \n def __init__(self,trig,echo):\n self.trig = trig\n self.echo = echo\n self.last_range = 0\n GPIO.setup(self.trig, GPIO.OUT)\n GPIO.setup(self.echo, GPIO.IN)\n GPIO.output(self.trig, False)\n \n def get_range(self):\n if(self.trig < 0 or self.echo < 0):\n return -1\n GPIO.output(self.trig, True)\n time.sleep(0.000001)\n GPIO.output(self.trig,False)\n trig_end = time.time()\n\n pulse_start = time.time()\n pulse_end = 0\n \n #Wait for first instance of echo. Time out after 0.001 seconds\n while GPIO.input(self.echo) == 0 and pulse_start-trig_end < 0.001:\n pulse_start = time.time()\n pulse_end = time.time()\n \n while GPIO.input(self.echo) == 1:\n pulse_end = time.time()\n\n \n pulse_duration = pulse_end-pulse_start\n distance = pulse_duration * 17000\n \n self.last_range = distance\n return round(distance,2)\n\nclass SensorArray(object):\n \n def __init__(self):\n GPIO.setmode(GPIO.BCM)\n self.FL = sonicSensor(FL_TRIG,FL_ECHO)\n self.FC = sonicSensor(FC_TRIG,FC_ECHO)\n self.FR = sonicSensor(FR_TRIG,FR_ECHO)\n self.is_on = False\n self.thread = threading.Thread(target = self.Fire)\n \n def Fire(self):\n while self.is_on:\n time.sleep(0.1)\n self.FC.get_range()\n time.sleep(0.1)\n self.FR.get_range()\n time.sleep(0.1)\n self.FL.get_range()\n \n def start(self):\n self.is_on = True\n self.thread.start()\n \n def stop(self):\n self.is_on = False\n","sub_path":"Classes/Sensors.py","file_name":"Sensors.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"193563117","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 26 09:37:34 2015\n\n@author: z1s\n\"\"\"\n\nimport sys\nsys.path.append('/home/z1s/PythonScripts')\nimport binfile_io as fio\nimport amgrid as grid\nfrom scipy.io import netcdf as nc\nimport numpy as np\nimport calendar\nimport matplotlib.pyplot as plt\n\nCp = 1004.64\nLe = 2.500e6\ng = 9.80\nRair = 287.04\nRad = 6371.0e3\n\nbasedir = '/archive/Zhaoyi.Shen/ulm_201510/'\noutdir = '/home/z1s/research/nonlinearity/analysis/npz/1yr/'\nexper = 'imr_t42_'\npert = ['control','2xCO2','m2c40w30','2xCO2+m2c40w30']\nperto = ['ctrl','CO2','m2c40w30','CO2+m2c40w30']\nplat = '/gfdl.ncrc3-default-prod/'\ndiag = 'atmos_level'\ndiago = 'var2d'\nvar = 't_surf'\nvaro = 'tsfc'\nnpert = np.size(pert)\n#npert = 1\nfor i in range(npert):\n atmdir = basedir+exper+pert[i]+plat+'pp/'+diag+'/'\n stafile = atmdir+diag+'.static.nc'\n fs = []\n fs.append(nc.netcdf_file(stafile,'r',mmap=True))\n bk = fs[-1].variables['bk'][:].astype(np.float64)\n pk = fs[-1].variables['pk'][:].astype(np.float64)\n lat = fs[-1].variables['lat'][:].astype(np.float64)\n lon = fs[-1].variables['lon'][:].astype(np.float64)\n phalf = fs[-1].variables['phalf'][:].astype(np.float64)\n zsurf = fs[-1].variables['zsurf'][:].astype(np.float64)\n fs[-1].close()\n nlat = np.size(lat)\n nlon = np.size(lon)\n nphalf = np.size(phalf)\n #%%\n filedir = atmdir+'ts/daily/1yr/'\n yr = np.arange(1,10,1)\n nyr = np.size(yr)\n data = np.zeros([nyr,nphalf-1,nlat])\n #tmpZon = np.zeros([nmon,nlev-1,nlat])\n #phalfZon = np.zeros([nmon,nlev,nlat])\n for yri in range(nyr):\n yrC = '000'+str(yr[yri])+'0101-'+'000'+str(yr[yri])+'1231.'\n filename = filedir+diag+'.'+yrC+var+'.nc'\n fs.append(nc.netcdf_file(filename,'r',mmap=True))\n #pfull = fs[-1].variables['pfull'][:].astype(np.float64)\n tmp = fs[-1].variables[var][:].astype(np.float64) #t,p,lat,lon\n #tmp[np.where(tmp<-999)] = np.nan\n tmp = np.mean(tmp,3)\n data[yri,:,:] = np.mean(tmp,0)\n fs[-1].close()\n #%%\n #outfile = outdir+'dim.'+perto[i]+'_sigma.npz'\n #fio.save(outfile,lat=lat,lon=lon,phalf=phalf,pfull=pfull)\n outfile = outdir+diago+'.'+perto[i]+'_sigma.npz'\n fio.save(outfile,**{varo:data})\n \n","sub_path":"driver/calc_var2d_ts_1yr.py","file_name":"calc_var2d_ts_1yr.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"17255222","text":"import sys\r\nsys.path.append(\"..\")\r\nclass CurrencyPair:\r\n\r\n @classmethod\r\n def get_all_currency_pairs(cls, market, account=None, user_id=None):\r\n market=str(market).lower()\r\n if market=='digifinex':\r\n from packages import digifinex as DIGIFINEX\r\n digifinex=DIGIFINEX.DigiFinex(account)\r\n tickers=digifinex.ticker()\r\n # 在digiFinex返回的tickers数据结构里,每个项的vol字段的值指的是base的成交量,而不是reference的成交量,所以首先要变成reference成交量\r\n currency_pairs={\r\n 'usdt':[],\r\n 'btc':[],\r\n 'usdt2':[],\r\n 'eth':[],\r\n 'dft':[]\r\n }\r\n # currency_pairs_in_reference_of_btc=[]\r\n # currency_pairs_in_reference_of_usdt = []\r\n # currency_pairs_in_reference_of_usdt2 = []\r\n # currency_pairs_in_reference_of_eth = []\r\n # currency_pairs_in_reference_of_dft = []\r\n for item in dict(tickers).keys():\r\n base=str(item).split('_')[1]\r\n reference=str(item).split('_')[0]\r\n currency_pair=CurrencyPair(base,reference)\r\n vol=tickers[item]['vol']*tickers[item]['last']\r\n currency_pairs[reference].append({\r\n 'currency_pair':currency_pair,\r\n 'vol':vol,\r\n 'reference':reference\r\n })\r\n # sorted(x, key=lambda x : x['name'], reverse=True)\r\n for item in currency_pairs.keys():\r\n currency_pairs[item]=sorted(currency_pairs[item], key=lambda x : x['vol'], reverse=True)\r\n if market=='aex':\r\n from packages import aex as AEX\r\n aex=AEX.AEX(account, user_id)\r\n tickers={}\r\n tickers['cny']=aex.ticker(CurrencyPair('all','cny'),True)\r\n tickers['usdt']=aex.ticker(CurrencyPair('all','usdt'),True)\r\n # 在digiFinex返回的tickers数据结构里,每个项的vol字段的值指的是base的成交量,而不是reference的成交量,所以首先要变成reference成交量\r\n _tickers={}\r\n for key1 in tickers.keys():\r\n for key2 in tickers[key1]:\r\n if key1+'_'+key2=='usdt_tusd' or key1+'_'+key2=='usdt_pax':\r\n continue\r\n _tickers[key1+'_'+key2]=tickers[key1][key2]['ticker']\r\n tickers=_tickers\r\n currency_pairs={\r\n 'usdt':[],\r\n 'cny':[]\r\n }\r\n for item in dict(tickers).keys():\r\n base=str(item).split('_')[1]\r\n reference=str(item).split('_')[0]\r\n currency_pair=CurrencyPair(base,reference)\r\n vol=tickers[item]['vol']*tickers[item]['last']\r\n currency_pairs[reference].append({\r\n 'currency_pair':currency_pair,\r\n 'vol':vol,\r\n 'reference':reference\r\n })\r\n # sorted(x, key=lambda x : x['name'], reverse=True)\r\n for item in currency_pairs.keys():\r\n currency_pairs[item]=sorted(currency_pairs[item], key=lambda x : x['vol'], reverse=True)\r\n return currency_pairs\r\n\r\n @classmethod\r\n def get_top_n_currency_pairs_adjusted_by_vol(cls,market, account=None, top_n=5, user_id=None):\r\n currency_pairs=CurrencyPair.get_all_currency_pairs(market,account, user_id)\r\n for item in currency_pairs.keys():\r\n currency_pairs[item]=currency_pairs[item][:top_n]\r\n return currency_pairs\r\n\r\n @classmethod\r\n def find_triangle_arbitragable_currency_pairs(cls,market, account=None, top_n=5, user_id=None):\r\n currency_pairs=CurrencyPair.get_top_n_currency_pairs_adjusted_by_vol(market,account,top_n, user_id)\r\n arbitragable_keypairs=[]\r\n _currency_pairs=[]\r\n for item in currency_pairs.keys():\r\n for item2 in currency_pairs[item]:\r\n _currency_pairs.append(item2['currency_pair'])\r\n for i in range(0,len(_currency_pairs)):\r\n cp1=_currency_pairs[i]\r\n for j in range(i+1,len(_currency_pairs)):\r\n cp2=_currency_pairs[j]\r\n for k in range(j+1,len(_currency_pairs)):\r\n cp3=_currency_pairs[k]\r\n currencies=[]\r\n currencies.append(cp1.base)\r\n currencies.append(cp1.reference)\r\n currencies.append(cp2.base)\r\n currencies.append(cp2.reference)\r\n currencies.append(cp3.base)\r\n currencies.append(cp3.reference)\r\n distinctive_currencies=list(set(currencies))\r\n if currencies.count(distinctive_currencies[0])==2 and currencies.count(distinctive_currencies[1])==2 and currencies.count(distinctive_currencies[2])==2:\r\n arbitragable_keypairs.append([cp1,cp2,cp3])\r\n\r\n a=1\r\n return arbitragable_keypairs\r\n\r\n\r\n def __init__(self,base='btc', reference='usdt'):\r\n self.base=base\r\n self.reference=reference\r\n\r\n def subtract(self, other):\r\n if other==self.base:\r\n return self.reference\r\n if other==self.reference:\r\n return self.base\r\n else:\r\n return None\r\n\r\n def equals(self, other):\r\n if self.base==other.base and self.reference==other.reference:\r\n return True\r\n else:\r\n return False\r\n\r\n def contains(self, currency):\r\n if self.base==currency or self.reference==currency:\r\n return True\r\n else:\r\n return False\r\n\r\n def toString(self):\r\n return self.base+'_'+self.reference\r\n\r\n def get_currency_pair(self):\r\n return self.base+'_'+self.reference\r\n\r\n def get_referencial_currencies(self, market):\r\n market=str(market).lower()\r\n if market==\"okex\":\r\n return [\"btc\",\"usdt\",\"eth\",\"bch\"]\r\n elif market==\"chbtc\" or market==\"zb\":\r\n pass\r\n elif market==\"???\":\r\n pass\r\n else:\r\n pass\r\n\r\n def get_referencial_currency(self, string):\r\n try:\r\n reference=str(string).split(\"_\")[1]\r\n except Exception as e:\r\n reference=None\r\n return reference\r\n\r\n def get_base_currency(self, string):\r\n try:\r\n reference=str(string).split(\"_\")[0]\r\n except Exception as e:\r\n reference=None\r\n return reference\r\n\r\nclass Currency:\r\n\r\n def __init__(self, name):\r\n self.name=name","sub_path":"packages/currency_pair.py","file_name":"currency_pair.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"258648862","text":"def expand_array(a):\n alphas = [x for x in a if x.isalpha()]\n nums = []\n\n x = 1\n\n while x < len(a):\n if a[x].isnumeric() and a[x - 1].isnumeric():\n nums[-1] += a[x]\n elif a[x].isnumeric():\n nums.append(a[x])\n\n x+=1\n\n print(\"\".join([alphas[i] * int(nums[i]) for i in range(len(alphas))]))\n\nexpand_array(\"a3b1c1d1e4f0g11\")","sub_path":"expand-array.py","file_name":"expand-array.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"583750359","text":"import logging\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom elasticsearch import Elasticsearch\n\nfrom shared.audit_log.models import AuditLogEntry\n\nES_STATUS_CREATED = \"created\"\nLOGGER = logging.getLogger(__name__)\n\n\ndef send_audit_log_to_elastic_search():\n if not (\n settings.ELASTICSEARCH_CLOUD_ID\n and settings.ELASTICSEARCH_API_ID\n and settings.ELASTICSEARCH_API_KEY\n ):\n LOGGER.warning(\n \"Trying to send audit log to Elasticsearch without proper configuration, process skipped\"\n )\n return\n es = Elasticsearch(\n cloud_id=settings.ELASTICSEARCH_CLOUD_ID,\n api_key=(settings.ELASTICSEARCH_API_ID, settings.ELASTICSEARCH_API_KEY),\n )\n entries = AuditLogEntry.objects.filter(is_sent=False).order_by(\"created_at\")\n\n for entry in entries:\n rs = es.index(\n index=settings.ELASTICSEARCH_APP_AUDIT_LOG_INDEX,\n id=entry.id,\n body=entry.message,\n )\n if rs.get(\"result\") == ES_STATUS_CREATED:\n entry.is_sent = True\n entry.save()\n\n\ndef clear_audit_log_entries(days_to_keep=30):\n # Only remove entries older than `X` days\n sent_entries = AuditLogEntry.objects.filter(\n is_sent=True, created_at__lte=(timezone.now() - timedelta(days=days_to_keep))\n )\n sent_entries.delete()\n","sub_path":"backend/shared/shared/audit_log/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"523853035","text":"from torch import optim, nn\n\nfrom ..models.model import Model\nfrom ..utils import tolist\nfrom ..losses import StochasticReconstructionLoss\n\n\nclass VAE(Model):\n \"\"\"\n Variational Autoencoder\n\n [Kingma+ 2013] Auto-Encoding Variational Bayes\n \"\"\"\n def __init__(self, encoder, decoder,\n other_distributions=[],\n regularizer=[],\n optimizer=optim.Adam,\n optimizer_params={}):\n\n # set distributions (for training)\n distributions = [encoder, decoder] + tolist(other_distributions)\n\n # set losses\n reconstruction =\\\n StochasticReconstructionLoss(encoder, decoder)\n loss = (reconstruction + regularizer).mean()\n\n super().__init__(loss, test_loss=loss,\n distributions=distributions,\n optimizer=optimizer, optimizer_params=optimizer_params)\n\n def train(self, train_x={}, **kwargs):\n return super().train(train_x, **kwargs)\n\n def test(self, test_x={}, **kwargs):\n return super().test(test_x, **kwargs)\n","sub_path":"pixyz/models/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"596490870","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom multiprocessing import Process, Queue, JoinableQueue, cpu_count\nimport sys\nimport os\n\nfrom ElProduction import ExclusiveElProduction, DynamicScaleFactors\nimport Util\n\n# compute all data points\nclass ExclusiveRunner:\n\t__qIn = JoinableQueue()\n\t__qOut = Queue()\n\tdef add(self,e):\n\t\t\"\"\"\n\t\tadds an element\n\t\t@param e element\n\t\t\"\"\"\n\t\tself.__qIn.put(e)\n\tdef run(self,nProcesses = cpu_count()):\n\t\t\"\"\"\n\t\tcomputes all elements\n\t\t@param nProcesses number of parallel threads\n\t\t\"\"\"\n\t\t# add EOF\n\t\tlenParams = self.__qIn.qsize()\n\t\tfor n in xrange(nProcesses):\n\t\t\tself.__qIn.put(None)\n\t\t# setup PDFs\n\t\tUtil.setupPDFs()\n\t\t# start processes\n\t\tthreadArgs = (self.__qIn, self.__qOut)\n\t\tprocesses = []\n\t\tfor j in xrange(nProcesses):\n\t\t\tprocesses.append(Process(target=_threadWorker, args=threadArgs))\n\t\t[p.start() for p in processes]\n\t\t# run\n\t\ttry:\n\t\t\tself.__qIn.join()\n\t\texcept KeyboardInterrupt:\n\t\t\t[p.terminate() for p in processes]\n\t\t\tprint\n\t\t\tUtil.pWarn(\"aborting at %d/%d\"%((lenParams-self.__qIn.qsize()),lenParams))\n\t\t\tself.__qIn.close()\n\t\tself.__qIn.close()\n\t\t# remap\n\t\tlOut = []\n\t\tfor j in xrange(lenParams):\n\t\t\tlOut.append(self.__qOut.get())\n\t\tself.__qOut.close()\n\t\treturn lOut\n\n# thread worker\ndef _threadWorker(qIn, qOut):\n\twhile True:\n\t\t# get\n\t\tp = qIn.get()\n\t\tif None == p: # EOF?\n\t\t\tqIn.task_done()\n\t\t\tbreak\n\t\t# setup\n\t\to = ExclusiveElProduction(*p[\"objArgs\"])\n\t\to.setPdf(*p[\"pdf\"])\n\t\to.setLambdaQCD(p[\"lambdaQCD\"])\n\t\tif p.has_key(\"mu2\"): o.setMu2 (DynamicScaleFactors(*p[\"mu2\"]))\n\t\tif p.has_key(\"muR2\"): o.setMuR2(DynamicScaleFactors(*p[\"muR2\"]))\n\t\tif p.has_key(\"muF2\"): o.setMuF2(DynamicScaleFactors(*p[\"muF2\"]))\n\t\tif p.has_key(\"bjorkenX\"): o.setBjorkenX(p[\"bjorkenX\"])\n\t\tif p.has_key(\"hadronicS\"): o.setHadronicS(p[\"hadronicS\"])\n\t\tif p.has_key(\"activatedHistograms\"):\n\t\t\tfor e in p[\"activatedHistograms\"]:\n\t\t\t\to.activateHistogram(*e)\n\t\tif p.has_key(\"calls\"): \t\to.MCparams.calls = p[\"calls\"]\n\t\tif p.has_key(\"iterations\"): \to.MCparams.iterations = p[\"iterations\"]\n\t\tif p.has_key(\"bins\"): \t\to.MCparams.bins = p[\"bins\"]\n\t\tif p.has_key(\"adaptChi2\"): \to.MCparams.adaptChi2 = p[\"adaptChi2\"]\n\t\tif p.has_key(\"verbosity\"): \to.MCparams.verbosity = p[\"verbosity\"]\n\t\t# run\n\t\tp[\"res\"] = o.F(p[\"orderFlag\"],p[\"channelFlag\"])\n\t\tqOut.put(p)\n\t\tqIn.task_done()\n\t\tif p.has_key(\"msg\"): Util.pSucc(p[\"msg\"])\n","sub_path":"py/ExclusiveRunner.py","file_name":"ExclusiveRunner.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"29747784","text":"#! /home/tony/anaconda3/bin/python\nimport subprocess\nimport os.path\nfrom pprint import pprint\nimport time\n\nbucketIn = 's3://ga-odc-eros-cog-west/'\nbucketOut = 's3://ga-odc-eros-archive-west/'\n\nhomeDir='/home/ubuntu'\n\nBigcnt=0\nBigtime1 = 0;\nBigtime0 = time.time()\n\n\ndef subprocess_cmd(command):\n process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)\n proc_stdout = process.communicate()[0].strip()\n stupidBytesObject = proc_stdout\n outStr = (stupidBytesObject.decode(\"utf-8\"))\n print(outStr)\n return(outStr)\n\ndef s3CopyFile(fromfile, tofile):\n\tprint (\"hello from s3CopyFile copying file \" + fromfile)\n\tinfile = \"'\" + bucketIn + fromfile + \"'\"\n\toutfile = \"'\" + bucketOut + tofile + \"'\"\n\tpushcmd = \"aws s3 cp %s %s\" % (infile, outfile)\n\tprint (pushcmd)\n\tsubprocess_cmd(pushcmd)\n\ndef mkFileName(filename, prefix, extension):\n a = filename.split('/')\n cell = a[0]\n file = a[1]\n dir = file.split('.xml')[0]\n file = dir + ext\n subdirs = \"%s/%s/%s/\" % (cell,dir,prefix)\n print (subdirs)\n root= 'exp/'\n fullDir=root + subdirs + file\n print (fullDir)\n return(fullDir)\n\ndef tarFileName(xmlFile, extension):\n file = xmlFile.split('.xml')[0] + extension\n return(file)\n\n\n# get the file list\n\nfileExtensions = ['.tif', '.xml']\n\n\ns3CopyFile(fromfile=\"AAlist.html\", tofile=\"AAlist.html\")\nmyfile = \"./cogxml.txt\"\n#myfile = \"./singlexml.txt\"\nwith open(myfile) as f:\n for line in f:\n line = line.rstrip()\n #print (line)\n a = line.split('h03v03/')\n id = 'h03v03/' + a[1]\n print (id)\n for ext in fileExtensions:\n pre = 'TIF'\n bucketFile = mkFileName(filename=id, prefix=pre, extension=ext)\n #print(\"bucketFile is %s\" % bucketFile)\n fromfile = id.split('.xml')[0] + ext\n s3CopyFile(fromfile=fromfile, tofile=bucketFile)\n Bigcnt = Bigcnt + 1\n print (\"BIGCNT = %d\" % Bigcnt)\n\nBigtime1 = time.time()\n\nelapsed = Bigtime1 - Bigtime0\n\nprint (\"TOTAL Bucket loading time for these files took %.2f seconds\" % elapsed)\n\n","sub_path":"00proj/python/buntar/cptiff.py","file_name":"cptiff.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"493029713","text":"from rest_framework import serializers\n\nfrom babies.models import Baby\nfrom parents.serializers import ParentSerializer\n\n\nclass BabySerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Baby\n fields = (\n 'id',\n 'first_name',\n 'last_name',\n 'age',\n 'parent'\n )","sub_path":"babies/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"473545428","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .tree import Tree, DeepCrawl\nfrom .observer import TreeNotifier\n\n\ndef tree(request):\n if request.POST:\n tree_notifier = TreeNotifier()\n for i in range(1, 5):\n tree_notifier.detach('Check' + str(i))\n for i in range(1, 5):\n if request.POST.get('Check' + str(i)) == 'on':\n tree_notifier.attach('Check' + str(i))\n answer = tree_notifier.createTree()\n # for i in answer['clients']:\n # print(i)\n return render(request, 'tree.html', answer)\n return render(request, 'tree.html', {})","sub_path":"tree/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"442454787","text":"import sys\nimport requests\nimport logging\n\nimport defaults\n\nlogging.basicConfig(filename='wikiware.log',level=logging.DEBUG)\n\nlogger = logging.getLogger('wikiware-fetcher')\n\nclass WikiwareFetch(object):\n \"\"\" Fetch content from Wikipedia \"\"\"\n\n def __init__(self):\n \"\"\" Mediawiki API query \"\"\"\n\n self.user_agent = {\n 'User-agent': 'python-request-{}'.format(sys.version.split()[0]),\n }\n\n self.headers = self.user_agent\n\n def fetch_api(self, title, format=\"json\"):\n \"\"\" dump Wikipedia article \"\"\"\n\n self.url = defaults.WIKIWARE_API_URL\n self.params = {\n 'titles': title,\n 'format': format,\n 'action': 'query',\n 'prop': 'revisions',\n 'rvprop': 'content',\n 'redirects': '',\n }\n\n r = requests.get(self.url, params=self.params, headers=self.headers)\n if r.status_code != requests.codes.ok:\n logger.error('Fetch Failed: Title={0}, Status={1}'.format(title, r.status_code))\n return ''\n\n text = r.json()\n try:\n pages = text['query']['pages']\n except:\n logger.error('No pages returned: Title={0}, Status={1}'.format(title, r.status_code))\n return ''\n revision = ''\n for page in pages:\n try:\n revision = pages[page]['revisions'][0]['*']\n except:\n pass\n break\n\n if not revision:\n logger.error('No revisions found: Title={0}, Status={1}'.format(title, r.status_code))\n return revision\n\n def fetch_en(self, title, printable=True):\n \"\"\" dump Wikipedia article in HTML \"\"\"\n\n self.url = defaults.WIKIWARE_EN_URL\n self.params = {\n 'title': title,\n 'printable': 'yes' if printable else 'no',\n }\n r = requests.get(self.url, params=self.params, headers=self.headers)\n return r.text\n\n\n\n\n\n\n\n","sub_path":"wikiware/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"631890242","text":"import sys\n\ndef get_page(url):\n try:\n import requests\n r = requests.get(url)\n return r.text\n except:\n return \"\"\n\ndef get_next_target(page):\n start_link = page.find('href=')\n if start_link == -1:\n return None, 0\n start_quote = page.find('\"', start_link)\n end_quote = page.find('\"', start_quote + 1)\n url = page[start_quote + 1:end_quote]\n return url, end_quote\n\ndef union(p, q):\n for e in q:\n if e not in p:\n p.append(e)\n\ndef get_all_links(page):\n links = []\n while True:\n url, endpos = get_next_target(page)\n if url:\n links.append(url)\n page = page[endpos:]\n else:\n break\n return links\n\ndef crawl_web(seed, max_depth):\n # seed : 一番最初の元となるページ\n # tocrawl : クロールするページ\n # crawled : クロールが終了したページ\n tocrawl = [seed]\n crawled = []\n next_depth = []\n depth = 0\n while tocrawl and depth <= max_depth:\n page = tocrawl.pop()\n if page not in crawled:\n union(next_depth, get_all_links(get_page(page)))\n crawled.append(page)\n if not tocrawl:\n tocrawl, next_depth = next_depth, []\n depth = depth + 1\n return crawled\n\nmax_depth = 1\nlinks = crawl_web(sys.stdin.read(), max_depth)\nfor x in links:\n print(x)\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"227920428","text":"from django.shortcuts import render, redirect as redir\nfrom django.utils.crypto import get_random_string\n\n\n\ndef index(request):\n if \"count\" not in request.session:\n request.session[\"count\"] = 0\n if \"random\" not in request.session:\n return redir(\"/random\")\n else:\n if request.method == \"GET\":\n return render(request, \"index.html\")\n if request.method == \"POST\":\n return redir(\"/random\")\n \n\ndef random(request):\n if request.method == \"GET\":\n request.session[\"random\"] = get_random_string(length=14)\n \n request.session[\"count\"] += 1\n return redir(\"/\")\n\ndef reset(request):\n if request.method ==\"GET\":\n request.session[\"count\"] = 0\n return redir(\"/\")","sub_path":"apps/rng_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"140824462","text":"gans = []\r\nfound = []\r\nex_time = []\r\navg_per_gen = []\r\n\r\ndef new_trial(f):\r\n global gans\r\n global found\r\n global ex_time\r\n f.readline()\r\n gans.append(int(f.readline()[5:]))\r\n val = f.readline()[7:][:-1]\r\n if val == \"True\":\r\n found.append(True)\r\n else:\r\n found.append(False)\r\n val = f.readline()[9:][:-2]\r\n ex_time.append(float(val))\r\n\r\nwith open(\"RESULT.txt\") as f:\r\n while f.read(1) != '':\r\n new_trial(f)\r\n while f.readline() != \"\\n\":\r\n pass\r\n\r\ngen_avg = 0\r\nfor val in gans:\r\n gen_avg += val\r\ngen_avg /= 20\r\n\r\ns_rate = 0\r\nfor val in found:\r\n if val:\r\n s_rate += 1\r\ns_rate *= 5\r\n\r\next_avg = 0\r\nfor val in ex_time:\r\n ext_avg += val\r\next_avg /= 20\r\n\r\nsum_till = int(round(gen_avg, 0))\r\nprint(sum_till)\r\n\r\nwith open(\"PRESULT.txt\", 'w') as f:\r\n f.write(\"AVERAGE NUMBER OF GENERATIONS: \" + str(gen_avg) + '\\n')\r\n f.write(\"AVERAGE EXECUTION TIME: \" + str(ext_avg) + \"s\\n\")\r\n f.write(\"SUCCES RATE: \" + str(s_rate) + \"%\\n\")","sub_path":"NEdata/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"103110952","text":"from django.urls import path, include\nfrom . import views\n\n\napp_name = 'home'\n\nurlpatterns = [\n path('', views.index, name='index'),\n # path('', views.IndexListView.as_view(), name='index'),\n path('details/', views.details, name='details'),\n path('register.html', views.UserFormView.as_view(), name='register'),\n path('login/', views.UserLoginView.as_view(), name='login'),\n path('login/', views.logout, name='logout'),\n]","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"565952562","text":"\"\"\"\ndoubly connected edge list \n\nrepresentation for network algorithms\n\"\"\"\n\n\n# example of edges from de berg fig 2.6\n\nimport pysal as ps\n\nimport networkx as nx\n\n\nclass Vertex:\n \"\"\" \"\"\"\n def __init__(self, coordinates, incident_edge):\n self.coordinates = coordinates\n incident_edge = incident_edge\n\nclass Face:\n \"\"\" \"\"\"\n def __init__(self, outer_component=None, inner_component=None):\n\n self.outer_component = outer_component\n self.inner_component = inner_component\n\nclass Half_Edge:\n \"\"\" \"\"\"\n def __init__(self, origin, twin, incident_face, Next, Prev):\n self.origin = origin\n self.twin = twin\n self.incident_face = incident_face\n self.Next = Next\n self.Prev = Prev\n\n\nclass DCEL:\n \"\"\"Doubly connected edge list\"\"\"\n def __init__(self, graph):\n\n edges = {}\n vertices = {}\n faces = {}\n half_edges = {}\n\n cycles = nx.cycle_basis(graph)\n fi = 0\n for cycle in cycles:\n n = len(cycle)\n for i in range(n-1):\n e = (cycle[i], cycle[i+1])\n if e not in edges:\n edges[e] = fi\n twin_a = e[0], e[1]\n twin_b = e[1], e[0]\n if twin_a not in half_edges:\n half_edges[twin_a] = fi\n if twin_b not in half_edges:\n half_edges[twin_b] = None\n e = cycle[n-1], cycle[0]\n if e not in edges:\n edges[e] = fi\n faces[fi] = e\n\n\n fi += 1\n\n self.edges = edges\n self.faces = faces\n self.half_edges = half_edges\n\n\nif __name__ == '__main__':\n\n\n p1 = [\n [1,12],\n [6,12],\n [11,11],\n [14,13],\n [19,14],\n [22,9],\n [20,5],\n [16,0],\n [11,2],\n [5,1],\n [0,7],\n [2,9],\n [1,12]]\n\n h1 = [\n [3,7],\n [5,5],\n [8,5],\n [5,8],\n [3,7]\n ]\n\n h2 = [\n [4,10],\n [5,8],\n [8,5],\n [9,8],\n [4,10]\n ]\n\n h3 = [\n [12,6],\n [15,4],\n [18,5],\n [19,7],\n [17,9],\n [14,9],\n [12,6]\n ]\n # note that h1 union h2 forms a single hole in p1\n\n faces = [p1, h1, h2, h3]\n G = nx.Graph()\n\n for face in faces:\n n = len(face)\n for i in range(n-1):\n G.add_edge(tuple(face[i]), tuple(face[i+1]))\n\n\n cycles = nx.cycle_basis(G)\n # len of cycles is equal to the number of faces (not including external face\n\n # find cycles that share a vertex\n node2cycle = {}\n multi_nodes = set()\n for i,cycle in enumerate(cycles):\n for node in cycle:\n if node in node2cycle:\n node2cycle[node].append(i)\n multi_nodes.add(node)\n else:\n node2cycle[node] = [i]\n\n \n\n # check if there are nodes belonging to multiple cycles\n if multi_nodes:\n \n # put nodes for each edge in lexicographic order\n edges = [ sorted(edge) for edge in G.edges()]\n\n\n","sub_path":"pysal/network/dcel.py","file_name":"dcel.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"225966633","text":"import numpy as np\n\n\nclass Matrix(np.ndarray):\n def __new__(cls, ndarray=None):\n if ndarray is None:\n ndarray = np.eye(4)\n obj = np.asanyarray(ndarray).view(cls)\n return obj\n\n def __repr__(self):\n return f\"Matrix({repr(self.tolist())})\"\n\n def __eq__(self, other):\n return np.allclose(self, other)\n\n def __matmul__(self, other):\n if isinstance(other, Matrix):\n return super().__matmul__(other).view(other.__class__)\n else:\n return super().__matmul__(other.T).T.view(other.__class__)\n\n @property\n def inv(self):\n return np.linalg.inv(self)\n\n @staticmethod\n def from_string(string):\n ndarray = np.array(\n [\n [float(xx) for xx in x.split(\"|\")[1:-1]]\n for x in string.strip().splitlines()\n ]\n )\n return Matrix(ndarray)\n\n\nclass Translation(Matrix):\n def __new__(cls, x, y, z):\n obj = super().__new__(cls)\n obj[:3, 3] = [x, y, z]\n return obj\n\n\nclass Scaling(Matrix):\n def __new__(cls, x, y, z):\n obj = super().__new__(cls, np.diag([x, y, z, 1]))\n return obj\n\n\nclass Rotation(Matrix):\n def __new__(cls, x, y, z):\n matrix = np.eye(4)\n\n if x:\n matrix_x = np.eye(4)\n matrix_x[1:3, 1:3] = [[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]]\n matrix = matrix_x @ matrix\n\n if y:\n matrix_y = np.eye(4)\n matrix_y[::2, ::2] = [[np.cos(y), np.sin(y)], [-np.sin(y), np.cos(y)]]\n matrix = matrix_y @ matrix\n\n if z:\n matrix_z = np.eye(4)\n matrix_z[:2, :2] = [[np.cos(z), -np.sin(z)], [np.sin(z), np.cos(z)]]\n matrix = matrix_z @ matrix\n\n obj = super().__new__(cls, matrix)\n return obj\n\n\nclass Shearing(Matrix):\n def __new__(cls, xy, xz, yx, yz, zx, zy):\n matrix = np.eye(4)\n matrix[:3, :3] = [[1, xy, xz], [yx, 1, yz], [zx, zy, 1]]\n obj = super().__new__(cls, matrix)\n return obj\n","sub_path":"src/matrix/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"177610563","text":"# add_job\n## solve model_start_time, model_end_time, model_restart variables.\n### handle nones\n## copy namelist from setup object to job\n## apply solved times/restart to job's namelists\n### namelist.hrldas: start, khour, kday, RESTART\n### hydro.namelist: HYDRO_RST\n## if restart: check that the restart is available\n## diff the setup namelists with the new one to ensure only certain fields are changed.\n\n\nimport datetime\nimport os\nimport re\nfrom wrfhydropy import *\n\nhome = os.path.expanduser(\"~/\")\nmodel_path = home + '/WRF_Hydro/'\nthe_model = WrfHydroModel(\n os.path.expanduser(model_path + '/wrf_hydro_nwm_public/trunk/NDHMS'),\n 'NWM'\n)\n\ndomain_path = '/Users/james/Downloads/croton_NY_domain/domain/croton_NY/'\nthe_domain = WrfHydroDomain(\n domain_top_dir=domain_path,\n model_version='v1.2.1',\n domain_config='NWM'\n)\n\nthe_setup = WrfHydroSetup(\n the_model,\n the_domain\n)\n\nsolve_model_start_end_times = job_tools.solve_model_start_end_times\n\n# #################################\n\n# All are 1 day and 2 hours.\ndef assert_start_end_soln(s,e):\n assert s == datetime.datetime(2011, 8, 26, 0, 0)\n assert e == datetime.datetime(2011, 9, 2, 0, 0)\n\n\ns, e = solve_model_start_end_times(None, None, the_setup)\nassert_start_end_soln(s, e)\n\nmodel_start_time = '2011-08-26 00'\nmodel_end_time = '2011-09-02 00'\ns, e = solve_model_start_end_times(model_start_time, model_end_time, the_setup)\nassert_start_end_soln(s, e)\n\nmodel_start_time = '2011-08-26 00:00'\nmodel_end_time = '2011-09-02 00'\ns, e = solve_model_start_end_times(model_start_time, model_end_time, the_setup)\nassert_start_end_soln(s, e)\n\nmodel_start_time = '2011-08-26 00:00'\nmodel_end_time = datetime.timedelta(days=7)\ns, e = solve_model_start_end_times(model_start_time, model_end_time, the_setup)\nassert_start_end_soln(s, e)\n\nmodel_start_time = '2011-08-26 00:00'\nmodel_end_time = {'hours': 24*7}\ns, e = solve_model_start_end_times(model_start_time, model_end_time, the_setup)\nassert_start_end_soln(s, e)\n\nmodel_start_time = '2011-08-26 00:00'\nmodel_end_time = {'days': 6, 'hours': 24}\ns, e = solve_model_start_end_times(model_start_time, model_end_time, the_setup)\nassert_start_end_soln(s, e)\n","sub_path":"wrfhydro/one_off_scripts/example_job_model_dates.py","file_name":"example_job_model_dates.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"45894558","text":"import xlwt\n\nwb=xlwt.Workbook()\nsht=wb.add_sheet('Sheet1',cell_overwrite_ok=True)\n\nborders=xlwt.Borders()\nborders.top=1\nborders.left=1\nborders.right=1\nborders.bottom=1\n\nalignment=xlwt.Alignment()\nalignment.horz=0x02\nalignment.vert=0x01\n\ntile_font=xlwt.Font()\ntile_font.bold=True\ntile_font.height=350\ntile_font.colour_index=10\n\nltile_font=xlwt.Font()\nltile_font.bold=True\n\ntile_font1=xlwt.Font()\ntile_font1.bold=True\ntile_font1.height=350\ntile_font1.colour_index=49\n\ntile_font2=xlwt.Font()\ntile_font2.bold=True\ntile_font2.height=350\ntile_font2.colour_index=17\n\n\ncell_style=xlwt.XFStyle()\ncell_style.alignment=alignment\ncell_style.borders=borders\n\nlittle_style=xlwt.XFStyle()\nlittle_style.alignment=alignment\nlittle_style.borders=borders\nlittle_style.font=ltile_font\n\nbig_title=xlwt.XFStyle()\nbig_title.font=tile_font\nbig_title.alignment=alignment\nbig_title.borders=borders\n\nsec_title=xlwt.XFStyle()\nsec_title.font=tile_font1\nsec_title.alignment=alignment\nsec_title.borders=borders\n\ntrd_title=xlwt.XFStyle()\ntrd_title.font=tile_font2\ntrd_title.alignment=alignment\ntrd_title.borders=borders\n\n\nsht.write_merge(0,0,0,3,\"标兵榜\",big_title)\nsht.write(1,0,\"支行\",little_style)\nsht.write(1,1,\"完成率\",little_style)\nsht.write(1,2,\"支行\",little_style)\nsht.write(1,3,\"完成率\",little_style)\n\nsht.write_merge(4,4,0,3,\"前有标兵后有追兵榜\",sec_title)\nsht.write(5,0,\"支行\",little_style)\nsht.write(5,1,\"完成率\",little_style)\nsht.write(5,2,\"支行\",little_style)\nsht.write(5,3,\"完成率\",little_style)\n\nsht.write_merge(9,9,0,3,\"追兵榜\",trd_title)\nsht.write(10,0,\"支行\",little_style)\nsht.write(10,1,\"完成率\",little_style)\nsht.write(10,2,\"支行\",little_style)\nsht.write(10,3,\"完成率\",little_style)\nrow_list=[['先行区', 0.12452830188679245], ['历城', 0.07045454545454545], ['济阳', 0.060909090909090906], ['平阴', 0.03495145631067961], ['开发区', 0.034375], ['商河', 0.03428571428571429], ['章丘', 0.01869918699186992], ['营业部', 0.01818181818181818], ['和平', 0.01598173515981735], ['银河', 0.014634146341463415], ['槐荫', 0.013488372093023256], ['天桥', 0.009583333333333333], ['长清', 0.009285714285714286], ['泺源', 0.008556149732620321], ['市中', 0.0084], ['历下', 0.004285714285714286]]\n\nfor i,city in enumerate(row_list):\n\tif i<4:\n\t\tif i<2:\n\t\t\tj=0\n\t\telse:\n\t\t\tj=2\n\t\tsht.write((2+i%2),j,city[0],cell_style)\n\t\tsht.write((2+i%2),j+1,city[1],cell_style)\n\t\tcontinue\n\tif i<10:\n\t\tif i<7:\n\t\t\tm=2\n\t\t\tj=0\n\t\telse:\n\t\t\tm=-1\n\t\t\tj=2\n\t\tsht.write((i+m),j,city[0],cell_style)\n\t\tsht.write((i+m),j+1,city[1],cell_style)\n\t\tcontinue\n\tif i<16:\n\t\tif i<13:\n\t\t\tj=0\n\t\t\tm=1\n\t\telse:\n\t\t\tm=-2\n\t\t\tj=2\n\t\tsht.write((i+m),j,city[0],cell_style)\n\t\tsht.write((i+m),j+1,city[1],cell_style)\n\t\tcontinue\n\n\n\nwb.save('a.xls')\n\n\n","sub_path":"python/xlwt_xls.py","file_name":"xlwt_xls.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"481922962","text":"def manhattan(point1, point2):\n return sum(abs(coord1 - coord2) for coord1, coord2 in zip(point1, point2))\n\n\ndef solve(filename):\n points = []\n with open(filename) as fp:\n for line in fp.readlines():\n pos, r = line.split(' ')\n r_num = int(r.lstrip('r='))\n pos_nums = pos.lstrip('pos=<').rstrip('>,').split(',')\n point = list(map(int, pos_nums))\n point.append(r_num)\n points.append(point)\n\n max_range = max(points, key=lambda x: x[3])\n \n in_range = 0\n for point in points:\n in_range += 1 if manhattan(point[:3], max_range[:3]) <= max_range[3] else 0\n \n return in_range\n\nassert solve('easy_input') == 7\nprint(solve('input'))\n","sub_path":"python/d23p1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"5837674","text":"# 客户端\n\n# 收发 同时进行 把这个客户端做成一个类\n\n\nimport socket\nimport threading\n\n\nclass Client():\n def __init__(self):\n # 1. 创建套接字\n self.sk = socket.socket()\n # 2. 去链接服务器\n self.sk.connect((\"192.168.40.153\",666))\n t1 = threading.Thread(target=self.recv) # 开启子线程执行发送消息\n t1.start()\n self.send()\n # 发送消息\n def send(self):\n while True:\n str1 = input(\"请输入:\")\n self.sk.send(str1.encode(\"utf8\"))\n print(\"发过去了\")\n\n # 接收消息\n def recv(self):\n while True:\n source = self.sk.recv(1024).decode(\"utf8\")\n print(source)\n print(\"接收消息了\")\n\n\nif __name__ == '__main__':\n Client()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"woniu_workspace/python/day09/聊天室3——1/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"597103991","text":"#print one message if the try block raises a NameError and another for other errors\n\ntry:\n a = 123\n if a==123:\n print(b)\n raise NameError(\"Name error\")\n if a >0:\n raise ValueError(\"Value error\")\nexcept NameError as ne:\n print(ne)\nexcept ValueError as ve:\n pritn(ve)\n","sub_path":"(III).py","file_name":"(III).py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"592266870","text":"from math import atan2, pi\n\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n if len(points) == 1:\n return 1\n \n lx, ly = location\n angles = []\n me = 0\n \n for px, py in points:\n if px == lx and py == ly:\n me += 1\n else:\n angles.append(atan2(py - ly, px - lx))\n\n angles.sort()\n angles.extend([x + (2.0 * pi) for x in angles])\n \n l, r = 0, 0\n res = 0\n angle = (2 * pi * angle) / 360.0\n while l < len(angles) and r < len(angles):\n while r < len(angles) and angles[r] - angles[l] <= angle:\n res = max(res, r - l + 1)\n r += 1\n l += 1\n \n return res + me","sub_path":"python/1610_Maximum_Number_of_Visible_Points.py","file_name":"1610_Maximum_Number_of_Visible_Points.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"113431685","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n------------------------ Libraries & Global variables -------------------------\n\"\"\"\nimport os\nimport scipy.io as sio\nimport numpy as np\nimport pandas as pd\nfrom global_path import DATA_DIR, STIMULI\n\n\"\"\"\n-------------------------------- Read file data -------------------------------\n\"\"\"\ndef read_mat_file(stimulus, patient_id, data_dir = DATA_DIR):\n save_file = 'Stimuli'+str(stimulus)+'__'+patient_id+'.mat'\n file_path = os.path.join(data_dir, save_file)\n vid_data = sio.loadmat(file_path)['vid_data']\n values = vid_data.item()\n field = vid_data.dtype.names\n dict_list = [(field[i], values[i]) for i in range(len(field))]\n dict_list.append(('id', patient_id))\n return dict(dict_list)\n\ndef read_MCHAT(data_dir = DATA_DIR):\n file_path = os.path.join(data_dir, 'questions.xlsx')\n df = pd.read_excel(file_path, index_col=None)\n ids = df['Individual'].values\n X = (df.values[:,2:22] == 'fail') + 0\n y = df['Asd'].values\n neg, pos, mid, unk = y=='no', y=='yes', y=='suspected', y=='unknown'\n y[pos], y[neg], y[mid], y[unk] = 1, -1, 0, np.nan\n mchat_scoring = df.values[:,22:]\n return ids, X, y, mchat_scoring\n\n\"\"\"\n------------------------- Split training and testing --------------------------\n\"\"\"\ndef split(data_dir = DATA_DIR, percentage = .3):\n # Read files\n ids, X, y, mchat_scoring = read_MCHAT(data_dir)\n pos, neg = ids[y==1], ids[y==-1]\n # Number to remove\n remove_pos = int(percentage * pos.shape[0])\n remove_neg = int(percentage * neg.shape[0])\n # Split ids\n test_pos = np.random.permutation(pos)[:remove_pos]\n test_neg = np.random.permutation(neg)[:remove_neg]\n # Write it in a file, this is not really the best way to do it\n test, test_y = list(), list()\n train, train_y = list(), list()\n for i in range(len(ids)):\n patient_id = ids[i]\n if patient_id in test_pos or patient_id in test_neg:\n test.append(patient_id)\n test_y.append(y[i])\n else: \n train.append(patient_id)\n train_y.append(y[i])\n test_tmp = np.transpose(np.vstack((test, test_y)))\n testFrame = pd.DataFrame(test_tmp, columns=['Id','Output'])\n train_tmp = np.transpose(np.vstack((train, train_y)))\n trainFrame = pd.DataFrame(train_tmp, columns=['Id','Output'])\n testFrame.to_csv(os.path.join(data_dir, 'test_ids.csv'), index=None)\n trainFrame.to_csv(os.path.join(data_dir, 'train_ids.csv'), index=None)\n\n\"\"\"\n--------------------------------- Access data ---------------------------------\n\"\"\"\ndef get_ids(data_dir = DATA_DIR):\n ids, _, labels, _ = read_MCHAT(data_dir=data_dir)\n return ids, labels\n\ndef keep_label(ids, labels, keep=\"good\", verbose = False):\n if keep == \"pos\":\n ind = labels==1\n elif keep == \"neg\":\n ind = labels==-1\n elif keep == \"good\":\n ind = np.logical_or(labels==-1, labels==1)\n if verbose:\n return ids[ind], labels[ind].astype(np.int), ind\n else:\n return ids[ind], labels[ind].astype(np.int)\n \ndef get_data(stimulus, patient_id, data_dir = DATA_DIR):\n dictionary = read_mat_file(stimulus, patient_id, data_dir = data_dir)\n detected = dictionary.get('face_detection').flatten() == 1\n timestamps = dictionary.get('timestamps').flatten()\n timestamps = timestamps[detected]\n landmarks = dictionary.get('original_landmarks')\n landmarks = landmarks[:, detected]\n # Correct potential overflow\n timestamps = timestamps.astype(np.float32)\n landmarks = landmarks.astype(np.float32)\n return landmarks, timestamps\n\n\"\"\"\n------------------------------- Access all data -------------------------------\n\"\"\" \ndef compute_all(features_extractor, ids):\n nb_ids, nb_stimulis = len(ids), len(STIMULI)\n values = np.zeros((nb_ids, nb_stimulis)).astype(np.dtype(object))\n ind = np.zeros(nb_ids)==0\n for i in range(nb_ids):\n patient_id = ids[i]\n for j in range(nb_stimulis):\n stimulus = STIMULI[j]\n try:\n landmarks, timestamps = get_data(stimulus, patient_id)\n features = features_extractor(landmarks, timestamps, stimulus)\n values[i,j] = features\n except FileNotFoundError:\n ind[i] = False\n print(\"Patient %s stimuli %d not found\" %(patient_id,stimulus))\n continue \n return values[ind,:], ind\n \ndef concatenate_all(values): \n all_val = np.hstack(values[:,0])\n for i in range(1,4):\n tmp = np.hstack(values[:,i])\n all_val = np.hstack((all_val, tmp))\n all_val[np.isnan(all_val)] = 0\n all_val[all_val==np.inf] = 0\n all_val[all_val==-np.inf] = 0\n return all_val\n\ndef homogenized_description(extractor, keep='good',\n homogenize=False, keep_norm='neg'):\n all_ids, all_labels = get_ids()\n ids, labels = keep_label(all_ids, all_labels, keep=keep)\n values, ind = compute_all(extractor, ids)\n ids, labels = ids[ind], labels[ind]\n \n if homogenize:\n _, _, ind = keep_label(ids, labels, keep=keep_norm, verbose=True)\n val = values[ind, :]\n all_values = concatenate_all(val)\n mean = np.expand_dims(np.mean(all_values, axis=1), axis=1)\n std = np.expand_dims(np.sqrt(np.var(all_values, axis=1)), axis=1)\n for i in range(values.shape[0]):\n for j in range(values.shape[1]):\n tmp = values[i,j] \n tmp -= mean\n tmp /= std\n tmp[np.isnan(tmp)] = 0\n values[i,j] = tmp\n return values, labels, ids","sub_path":"data_handling.py","file_name":"data_handling.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"427849803","text":"#!/usr/bin/env python3\n\nimport json\nimport argparse\nimport http.client\nimport sys\n\nfrom homekit import find_device_ip_and_port, SecureHttp, load_pairing, get_session_keys, HapStatusCodes\n\n\ndef setup_args_parser():\n parser = argparse.ArgumentParser(description='HomeKit perform app - performs operations on paired devices')\n parser.add_argument('-f', action='store', required=True, dest='file', help='File with the pairing data')\n parser.add_argument('-c', action='store', required=False, dest='characteristics')\n parser.add_argument('-v', action='store', required=False, dest='value')\n\n return parser\n\n\nif __name__ == '__main__':\n parser = setup_args_parser()\n args = parser.parse_args()\n\n pairing_data = load_pairing(args.file)\n if pairing_data is None:\n print('File {file} not found!'.format(file=args.file))\n sys.exit(-1)\n\n deviceId = pairing_data['AccessoryPairingID']\n\n connection_data = find_device_ip_and_port(deviceId)\n if connection_data is None:\n print('Device {id} not found'.format(id=deviceId))\n sys.exit(-1)\n\n conn = http.client.HTTPConnection(connection_data['ip'], port=connection_data['port'])\n pairing_data = load_pairing(args.file)\n\n controllerToAccessoryKey, accessoryToControllerKey = get_session_keys(conn, pairing_data)\n\n if not args.characteristics:\n parser.print_help()\n sys.exit(-1)\n if not args.value:\n parser.print_help()\n sys.exit(-1)\n\n tmp = args.characteristics.split('.')\n aid = int(tmp[0])\n iid = int(tmp[1])\n value = args.value\n\n sec_http = SecureHttp(conn.sock, accessoryToControllerKey, controllerToAccessoryKey)\n\n body = json.dumps({'characteristics': [{'aid': aid, 'iid': iid, 'value': value}]})\n print(body)\n response = sec_http.put('/characteristics', body)\n data = response.read().decode()\n if response.code != 204:\n data = json.loads(data)\n code = data['status']\n print('put_characteristics failed because: {reason} ({code})'.format(reason=HapStatusCodes[code], code=code))\n else:\n print('put_characteristics succeeded')\n\n conn.close()\n","sub_path":"homekit/put_characteristic.py","file_name":"put_characteristic.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"607608331","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom itertools import imap\nfrom collections import namedtuple\n\nfrom ..exceptions import DSLParsingLogicException\n\nVERSION = 'tosca_definitions_version'\nBASE_VERSION_PROFILE = 'tosca_aria_yaml'\n\n\nclass VersionNumber(namedtuple('VersionNumber', 'major, minor, micro')):\n def __new__(cls, major, minor, micro=0):\n return super(VersionNumber, cls).__new__(cls, major, minor, micro)\n\n def __repr__(self):\n return (\n '{cls.__name__}'\n '(major={self.major}, minor={self.minor}, micro={self.micro})'\n .format(cls=self.__class__, self=self))\n\n\nclass VersionStructure(namedtuple('VersionStructure', 'profile, number')):\n def __repr__(self):\n return (\n '{cls.__name__}(profile={self.profile}, number={self.number!r})'\n .format(cls=self.__class__, self=self))\n\n @property\n def name(self):\n return (\n '{self.profile}_{self.number.major}_'\n '{self.number.minor}_{self.number.micro}'.format(self=self))\n\n\nclass SupportedVersions(object):\n def __init__(self, database):\n self.database = database\n\n def __contains__(self, version):\n return any(imap(\n lambda supported_version: supported_version == version,\n self.versions()))\n\n @property\n def base_version(self):\n return next(iter(self.database[BASE_VERSION_PROFILE]))\n\n def versions(self):\n for version_structures in self.database.itervalues():\n for version_structure in version_structures:\n yield version_structure\n\n def create_version_structure(self, version_name):\n if not version_name:\n raise DSLParsingLogicException(\n 71, '{0} is missing or empty'.format(VERSION))\n\n if not isinstance(version_name, basestring):\n raise DSLParsingLogicException(\n 72, 'Invalid {0}: {1} is not a string'.format(\n VERSION, version_name))\n\n for prefix in self.database.iterkeys():\n if version_name.startswith(prefix):\n short_dsl_version = version_name[len(prefix) + 1:]\n break\n else:\n raise DSLParsingLogicException(\n 73, \"Invalid {0}: '{1}', expected a value following \"\n \"this format: '{2}'\".format(\n VERSION, version_name, self.base_version.name))\n\n if '_' not in short_dsl_version:\n raise DSLParsingLogicException(\n 73, \"Invalid {0}: '{1}', \"\n \"expected a value following this format: '{2}'\".format(\n VERSION, version_name, self.base_version.name))\n\n version_parts = short_dsl_version.split('_')\n if len(version_parts) == 2:\n major, minor = version_parts\n micro = '0'\n else:\n major, minor, micro = version_parts\n\n if not major.isdigit():\n raise DSLParsingLogicException(\n 74, \"Invalid {0}: '{1}', major version is '{2}' \"\n \"while expected to be a number\".format(\n VERSION, version_name, major))\n\n if not minor.isdigit():\n raise DSLParsingLogicException(\n 75, \"Invalid {0}: '{1}', minor version is '{2}' \"\n \"while expected to be a number\".format(\n VERSION, version_name, minor))\n\n if not micro.isdigit():\n raise DSLParsingLogicException(\n 76, \"Invalid {0}: '{1}', micro version is '{2}' \"\n \"while expected to be a number\".format(\n VERSION, version_name, micro))\n\n return VersionStructure(\n profile=prefix, # pylint: disable=undefined-loop-variable\n number=VersionNumber(int(major), int(minor), int(micro)))\n\n def validate_dsl_version(self, version_structure):\n if version_structure not in self:\n raise DSLParsingLogicException(\n 29,\n 'Unexpected tosca_definitions_version {0!r}; Currently '\n 'supported versions are: {1}'\n .format(version_structure, list(self.versions())))\n","sub_path":"aria/parser/dsl_supported_versions/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"134765852","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 29 09:50 2017\n\n@author: andrewalferman\n\"\"\"\n\nimport os as os\nimport numpy as np\nimport pyjacob as pyjacob\nimport matplotlib.pyplot as plt\n# import scipy as sci\n\n\ndef loadpasrdata(num):\n \"\"\"Load the initial conditions from the PaSR files.\"\"\"\n pasrarrays = []\n print('Loading data...')\n for i in range(num):\n filepath = os.path.join(os.getcwd(),\n 'pasr_out_h2-co_' +\n str(i) +\n '.npy')\n filearray = np.load(filepath)\n pasrarrays.append(filearray)\n return np.concatenate(pasrarrays, 1)\n\n\ndef rearrangepasr(Y, useN2):\n \"\"\"Rearrange the PaSR data so it works with pyJac.\"\"\"\n press_pos = 2\n temp_pos = 1\n arraylen = len(Y)\n\n Y_press = Y[press_pos]\n Y_temp = Y[temp_pos]\n Y_species = Y[3:arraylen]\n Ys = np.hstack((Y_temp, Y_species))\n\n # Put N2 to the last value of the mass species\n N2_pos = 9\n newarlen = len(Ys)\n Y_N2 = Ys[N2_pos]\n # Y_x = Ys[newarlen - 1]\n for i in range(N2_pos, newarlen - 1):\n Ys[i] = Ys[i + 1]\n Ys[newarlen - 1] = Y_N2\n if useN2:\n initcond = Ys\n else:\n initcond = Ys[:-1]\n return initcond, Y_press\n\n\n# Load the initial conditions from the PaSR files\npasr = loadpasrdata(1)\nnumparticles = len(pasr[0, :, 0])\nnumtsteps = len(pasr[:, 0, 0])\n\nfor i in pasr[469, 91, :]:\n print(i)\n\n\n\n# # All of the species names, after the data has been rearranged\n# speciesnames = ['H', 'H$_2$', 'O', 'OH', 'H$_2$O', 'O$_2$', 'HO$_2$',\n# 'H$_2$O$_2$', 'Ar', 'He', 'CO', 'CO$_2$', 'N$_2$']\n# # Keep in mind that the states also have temperature data\n#\n# states = np.empty((14, numtsteps*numparticles))\n#\n# # Rearrange all of the particles so that histograms can be made\n# count = 0\n# for i in range(numparticles):\n# for j in range(numtsteps):\n# particle, press = rearrangepasr(pasr[j, i, :], True)\n# for k in range(len(particle)):\n# states[k, count] = particle[k]\n# count += 1\n#\n# # Clear all previous figures and close them all\n# for i in range(15):\n# plt.figure(i)\n# plt.clf()\n# plt.close('all')\n#\n# # Make the histograms and plots\n# print('Plotting...')\n# for i in range(7):\n# plt.figure(i)\n# if i == 0:\n# title = 'Temperature'\n# else:\n# title = speciesnames[i-1]\n# print(title)\n# plt.hist(states[i, :100100], bins='auto')\n# plt.title(title)\n#\n# plt.show()\n","sub_path":"H2_CO/PaSR_Histogram.py","file_name":"PaSR_Histogram.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"528958179","text":"import os\nfrom datetime import datetime\n\n# 3rd Party Imports\nimport boto\nfrom boto.s3.key import Key\nfrom click import echo\n\nfrom .utils import temp_directory, zipdir\nfrom .local import local_restore\nfrom .mongo import dump_db\n\n\ndef get_s3_bucket(s3_settings):\n conn = boto.connect_s3(s3_settings['aws_access_key_id'], s3_settings['aws_secret_access_key'])\n bucket = conn.get_bucket(s3_settings['bucket_name'])\n return bucket\n\n\ndef generate_uniqueish_key(s3_settings, environment, name_prefix):\n bucket = get_s3_bucket(s3_settings)\n\n if name_prefix and name_prefix != '':\n name_base = name_prefix\n else:\n name_base = environment['db_name']\n\n name_attempt = \"{}__{}.dmp.zip\".format(name_base, datetime.utcnow().strftime(\"%Y_%m_%d\"))\n\n key = bucket.get_key(name_attempt)\n\n if not key:\n key = Key(bucket)\n key.key = name_attempt\n return key\n else:\n counter = 1\n while True:\n counter += 1\n name_attempt = \"{}__{}_{}.dmp.zip\".format(name_base,\n datetime.utcnow().strftime(\"%Y_%m_%d\"), counter)\n\n if bucket.get_key(name_attempt):\n continue\n else:\n key = Key(bucket)\n key.key = name_attempt\n return key\n\n\ndef backup_to_s3(environment, s3_settings, name, query_set_class):\n\n dump_path = dump_db(environment, QuerySet=query_set_class)\n zipf = zipdir(dump_path)\n\n key = generate_uniqueish_key(s3_settings, environment, name)\n\n bytes_written = key.set_contents_from_filename(zipf.filename)\n\n # 4) print out the name of the bucket\n echo(\"Wrote {} bytes to s3\".format(bytes_written))\n\n\ndef s3_restore(key, to_enviornment):\n\n with temp_directory() as temp_dir:\n zip_path = os.path.join(temp_dir, 'MongoDump.zip')\n key.get_contents_to_filename(zip_path)\n local_restore(zip_path, to_enviornment)\n\n\ndef s3_backups(s3_config):\n \"\"\" a dict of key.name: key\n \"\"\"\n bucket = get_s3_bucket(s3_config)\n\n buckets = {}\n for key in bucket.get_all_keys():\n buckets[key.name] = key\n\n return buckets\n","sub_path":"monarch/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"194333164","text":"import random as rd\nimport copy\n\n########### création ou chargement des tableaux #################\n\n\ndef creer_tableau(n):\n \"\"\" créer une liste de liste de taille nxn \"\"\"\n L = [[]for i in range(n-1)]\n L.append([0 for i in range(n-1)])\n L.append([\"*\" for i in range(n+1)])\n L.append([0 for i in range(n)])\n for i in range(n+2):\n if i != n and i != n+1:\n if i == 0:\n L[i].extend([0 for i in range(n-1)])\n elif 1 <= i <= n-2:\n L[i].append(0)\n L[i].extend([rd.randint(5, 9) for i in range(n-2)])\n L[i].extend([0, \"*\", 0])\n L_final = somme(L)\n return L_final\n\n\ndef creer_tableau_2():\n choix = input(\"taper 'nouveau' si vous souhaitez charger un nouveau tableau et taper 'charger' sinon : \")\n if choix == \"charger\":\n nom_fichier = input(\"entrer le nom du fichier (ne pas oublier .txt) : \")\n chargement = open(nom_fichier, \"r\")\n list_chargement = [(line.strip()).split() for line in chargement]\n chargement.close()\n afficher_tableau(list_chargement)\n elif choix == \"nouveau\":\n n = input(\"entrer la taille du tableau (un entier) : \")\n tableau = creer_tableau(int(n))\n afficher_tableau(tableau)\n\n\ndef somme(tab):\n for k in range(len(tab)-2):\n for i in range(len(tab)-2):\n tab[len(tab)-1][k] += tab[i][k]\n tab[k][len(tab)-1] += tab[k][i]\n return tab\n\n\n######### afficher sous forme de tableau ############################\n\n\ndef afficher_tableau(tab):\n \"\"\" affiche la liste de liste sous la forme d'un tableau \"\"\"\n for elem in tab:\n for i in range(len(elem)):\n if i != len(elem)-1:\n if (isinstance(elem[i], int)) and (elem[1] >= 10):\n print(elem[i], end=\" \")\n else:\n print(elem[i], end=\" \")\n else:\n print(elem[i])\n\n\n########## automate des tas de sable version sequentiel ##############\n\n\ndef etape_sequentiel(tab):\n changement = True\n tab_modif = copy.deepcopy(tab)\n\n tab_modif[len(tab)-1].clear()\n tab_modif[len(tab)-1] = [0 for i in range(len(tab)-2)]\n for i in range(len(tab)-3):\n tab_modif[i][len(tab)-1] = 0\n\n for i in range(1, len(tab)-3):\n for k in range(1, len(tab)-3):\n if tab_modif[i][k] >= 4:\n tab_modif[i][k] = tab[i][k] - 4\n tab_modif[i][k-1] += 1\n tab_modif[i][k+1] += 1\n tab_modif[i+1][k] += 1\n tab_modif[i-1][k] += 1\n\n changement = True\n return [tab_modif, changement]\n return [tab, False]\n\n\ndef automate_sequentiel(tab):\n res = etape_sequentiel(tab)\n while res[1]:\n res = etape_sequentiel(res[0])\n res_vrai = somme(res[0])\n return res_vrai\n\n\n####### automate des tas de sable version parallele ##########################\n\n\ndef etape_parallele(tab):\n changement = False\n tab_modif = copy.deepcopy(tab)\n\n tab_modif[len(tab)-1].clear()\n tab_modif[len(tab)-1] = [0 for i in range(len(tab)-2)]\n for i in range(len(tab)-3):\n tab_modif[i][len(tab)-1] = 0\n\n for i in range(1, len(tab)-3):\n for k in range(1, len(tab)-3):\n if tab_modif[i][k] >= 4: \n tab_modif[i][k] = tab_modif[i][k] - 4\n tab_modif[i][k-1] += 1\n tab_modif[i][k+1] += 1\n tab_modif[i+1][k] += 1\n tab_modif[i-1][k] += 1\n\n changement = True\n if changement:\n return [tab_modif, changement]\n else:\n return [tab, changement]\n\ndef automate_parallele1(tab):\n nom_fichier = input(\"entrer le nom du fichier (ne pas oublier .txt) \")\n res = etape_parallele(tab)\n while res[1]:\n res = etape_parallele(res[0])\n res_vrai = somme(res[0])\n Fichier = open(nom_fichier, 'w')\n for elem in res_vrai:\n txt = ' '.join([str(i) for i in elem])\n Fichier.write(txt + '\\n')\n Fichier.close()\n return res[0]\n\n\ndef automate_parallele(tab):\n res = etape_parallele(tab)\n while res[1]:\n res = etape_parallele(res[0])\n res_vrai = somme(res[0])\n return res_vrai\n\n\n############# commandes tests ###################\n\ntest = creer_tableau(4)\nafficher_tableau(test)\nprint(\"------------\")\ntest_para = automate_parallele(test)\nafficher_tableau(test_para)\nprint(\"--------------\")\ntest_seq = automate_sequentiel(test)\nafficher_tableau(test_seq)\n","sub_path":"exercises/in200 exercices/feuille_exos_3_bis.py","file_name":"feuille_exos_3_bis.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"332125791","text":"def solution(arr, m):\n ptr = -1\n while len(arr) > 1:\n for i in range(m):\n ptr += 1\n if ptr >= len(arr): # reach end\n ptr = 0\n\n p_num = arr.pop(ptr)\n print(p_num, arr)\n ptr = ptr - 1\n\n return arr[ptr]\n\n\nprint(solution(list(range(10)), 3))\n","sub_path":"solutions/array/62_Last_Digit_in_Circle.py","file_name":"62_Last_Digit_in_Circle.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"608225837","text":"import logging\nimport os\n\nfrom clowder.tomcat import ConfigurationException,\\\n NotAnInstance\nfrom clowder.tomcat import Instance\n\nclass Finder(object):\n def __init__(self, root=\"/opt/evive/apps/\"): #root=\"/opt/clowder\"):\n self._root = root\n self.logger = logging.getLogger(\"AppFinder\")\n\n def all(self):\n basenames = [x for x in os.listdir(self._root)\n if os.path.isdir(os.path.join(self._root, x))]\n app_instances = filter(lambda x: len(x) == 2, [tuple(x.split(\".\")) for x in basenames])\n apps = {}\n for base in app_instances:\n try:\n app = Instance(name=base[0], instance=base[1], root=self._root)\n apps[base] = app\n except (NotAnInstance,ConfigurationException) as e:\n self.logger.info(\"{message}\".format(message=e.message))\n return apps\n\n def find(self, name, instance=None):\n if instance:\n return {k:v for k,v in self.all().items() if k == (name, instance)}\n else:\n return {k:v for k,v in self.all().items() if k[0] == name}\n","sub_path":"clowder/tomcat/finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"210190451","text":"import unittest\nfrom datetime import date\n\n\nfrom domain.research.factories.research_daily_journal_factory import ResearchDailyJournalFactory\nfrom domain.research.factories.research_factory import GynecologicResearchFactory\nfrom domain.research.repositories.research_daily_journal_repository import ResearchDailyJournalRepository\nfrom usecases.new_research_usecase import NewResearchUseCase\nfrom usecases.utils import ResearchData\n\n\njournal_factory = ResearchDailyJournalFactory()\njournal_repository = ResearchDailyJournalRepository()\ntoday = date(2016, 5, 1)\nresearch_factory = GynecologicResearchFactory()\n\n\nclass TestSaveResearch(unittest.TestCase):\n\n def setUp(self):\n journal = journal_factory.journal(today)\n journal_repository.add_journal(journal)\n\n def test(self):\n expected = research_factory.new_research()\n expected.mark_cell_smear_adequate()\n research_data = ResearchData(\n cell_smear_quality='adequate',\n cell_smear_type='',\n epithelium_surface='',\n epithelium_basal='',\n epithelium_cylindrical='',\n leukocytes='',\n description=''\n )\n journal = journal_repository.find_journal_by_date(today)\n use_case = NewResearchUseCase(journal)\n use_case.execute(research_data)\n\n result = journal.find_by_index(0)\n\n self.assertEqual(expected, result)\n","sub_path":"source/test/test_usecase/test_save_research.py","file_name":"test_save_research.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"103921668","text":"if __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(prog='merge_bxcan.py', description='''\n Merge BrainXcan results from dMRI and T1.\n ''')\n parser.add_argument('--dmri', help='''\n Input S-BrainXcan result for dMRI IDPs.\n ''')\n parser.add_argument('--t1', help='''\n Input S-BrainXcan result for T1 IDPs.\n ''')\n parser.add_argument('--idp_meta_file', help='''\n A meta file for annotating IDPs.\n ''')\n parser.add_argument('--output', help='''\n Output table.\n ''')\n args = parser.parse_args()\n \n import logging, time, sys, os\n # configing util\n logging.basicConfig(\n level = logging.INFO, \n stream = sys.stderr, \n format = '%(asctime)s %(message)s',\n datefmt = '%Y-%m-%d %I:%M:%S %p'\n )\n import pandas as pd\n\n logging.info('Loading S-BrainXcan dMRI.')\n df1 = pd.read_csv(args.dmri)\n df1['modality'] = 'dMRI'\n logging.info('{} IDPs in total.'.format(df1.shape[0]))\n \n logging.info('Loading S-BrainXcan T1.')\n df2 = pd.read_csv(args.t1)\n df2['modality'] = 'T1'\n logging.info('{} IDPs in total.'.format(df2.shape[0]))\n \n logging.info('Loading the IDP meta file.')\n meta = pd.read_csv(args.idp_meta_file)\n \n logging.info('Saving outputs.')\n df = pd.concat([df1, df2], axis=0)\n df = pd.merge(df, meta.drop(columns=['t1_or_dmri', 'ukb_link']), on='IDP', how='left')\n df.fillna('NA', inplace=True)\n df.sort_values(by='pval').to_csv(args.output, index=False)\n \n logging.info('Done.')\n","sub_path":"brainxcan/snmk/merge_bxcan.py","file_name":"merge_bxcan.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"512123369","text":"def solution(weights, head2head):\n \n #인원수 n, 리스트 result, answer 선언\n n= len(weights)\n result,answer=[],[]\n \n #인원수 만큼 반복\n for i in range (n): \n #선수마다 이긴 횟수, 진 횟수 카운트\n win= head2head[i].count('W')\n lose= head2head[i].count('L')\n \n #조건2) 자신보다 무거운 복서를 이긴 횟수 변수 선언\n heavy_win= 0\n \n #win+lose가 0이면 모두 'N'인경우=> 승률 0으로 처리\n if (win+lose) == 0: \n win_rate= 0 \n else:\n #승률 계산\n win_rate= win / (win+lose)\n \n for j in range(n):\n #자기 자신과 싸운 경우인 인덱스는 제외\n if i == j: \n continue\n #이기고 + 자신보다 몸무게가 무거운 복서인 경우 체크\n if head2head[i][j]=='W' and weights[i] < weights[j]:\n heavy_win += 1\n \n #승률, 무거운 선수 이긴 횟수, 몸무게, 선수 번호 순으로 result에 저장\n result.append([-win_rate, -heavy_win, -weights[i],i+1])\n \n #정렬 후 순서대로 선수번호만 answer에 저장해 반환\n result.sort()\n answer = [x[-1] for x in result]\n return answer","sub_path":"6week/6week_kyk.py","file_name":"6week_kyk.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"409589674","text":"import pandas as pd\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\n\n# Load CSSV file from Datasets folder\ndf = pd.read_csv('../Datasets/Weather2014-15.csv')\n\n# Extrapolating the actual max temp per month\nnew_df = df.groupby('month', sort=False).agg(\n {'actual_max_temp': 'max'}).reset_index()\n\n# Preparing data\ndata = [go.Scatter(x=new_df['month'], y=new_df['actual_max_temp'], mode='lines',\n name='Record Max Temperature')]\n\n# Preparing layout\nlayout = go.Layout(title='The Actual Max Temperature of Each Month From 2014 To 2015',\n xaxis_title=\"Month\", yaxis_title=\"Temperature (F)\")\n\n# Plot the figure and saving in a html file\nfig = go.Figure(data=data, layout=layout)\npyo.plot(fig, filename='WeatherLineChart.html')","sub_path":"Plots/WeatherLineChart.py","file_name":"WeatherLineChart.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"122842692","text":"import os\nimport logging\nimport hydra\nfrom solver import main\nfrom omegaconf import OmegaConf, DictConfig\n\nlog = logging.getLogger(__name__)\n\n@hydra.main(config_path=\"conf\", config_name=\"default.yaml\")\ndef run_experiment(cfg: DictConfig) -> None:\n # print(OmegaConf.to_yaml(cfg))\n \n # read params\n p = cfg.solver.penalty\n nV = cfg.solver.num_vehicle\n num_fss = cfg.solver.first_solution_strategy.num_fss\n \n ds, td, tl = main(p, nV, num_fss)\n print(\"Dropped nodes :\", ds)\n print(\"Total distance :\", td)\n print(\"Total load :\", tl)\n\n log.info(\"Dropped nodes :{}\".format(ds))\n log.info(\"Total distance :{}\".format(td))\n log.info(\"Total load :{}\".format(tl))\n\nif __name__ == '__main__':\n run_experiment()","sub_path":"h_experiment.py","file_name":"h_experiment.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"430858855","text":"import re\nimport requests\nimport json #用于读取账号信息\nimport time #用于计时重新发送requests请求\nimport base64 #用于解密编码\nimport logging #用于日志控制\nimport os,sys\nfrom lxml import etree # 可以利用Xpath进行文本解析的库\n# 发送邮件的库\nimport smtplib\nfrom email.mime.text import MIMEText\n\n#账号 密码等信息 Actions部署\nid = os.environ[\"id\"]\npwd = os.environ[\"pwd\"]\n# 邮箱信息\nMAIL_USER = os.environ[\"MAIL_USER\"] #QQ邮箱账户\nMAIL_PWD = os.environ[\"MAIL_PWD\"] #QQ邮箱授权码\nMAIL_TO = os.environ[\"MAIL_TO\"] #QQ邮箱账户\n\n# 本地运行就直接填上相应信息,所有信息需要被双引号\"\"包裹\n# id = \"学号\"\n# pwd = \"密码\"\n# MAIL_USER = \"QQ邮箱账户\"\n# # 这里是授权码--不是账户密码\n# MAIL_PWD = \"邮箱授权码\"\n# MAIL_TO = \"QQ邮箱账户\"\n#账号和密码需要被双引号\"\"包裹\n# eg:\n# id = \"学号\"\n# pwd = \"密码\"\n\ndef sign_in(id, pwd):\n\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n r=\"\"\n\n #set logging format\n LOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\n DATE_FORMAT = \"%m/%d/%Y %H:%M:%S %p\"\n #create a log file at the work directory\n\n # 日志文件my.log会保存在该python文件所在目录当中\n logging.basicConfig(filename=curr_dir+'/my.log', level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)\n\n logging.info(\"===开始打卡===\")\n\n #login\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',\n 'referer':'https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/first0?fun2=a',\n 'Content-Type':'application/x-www-form-urlencoded'\n }\n form={\n \"uid\": id,\n \"upw\": pwd,\n \"smbtn\": \"进入健康状况上报平台\",\n \"hh28\": \"750\" #按照当前浏览器窗口大小计算\n }\n r = \"\"\n max_punch = 10\n curr_punch = 0 #if curr_punch > max_pubch then exit\n logging.info(\"准备进入打卡界面\")\n while True:\n try:\n logging.info(\"准备进入post请求\")\n r= requests.post(\"https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/login\",headers=headers,data=form,timeout=(200,200)) #response为账号密码对应的ptopid和sid信息,timeout=60(sec)\n logging.info(\"成功运行post请求\")\n except:\n logging.warning(\"请检查网络链接是否正常\")\n curr_punch+=1\n if curr_punch>max_punch:\n exit()\n time.sleep(120) #sleep 60 sec\n else:\n break\n text = r.text.encode(r.encoding).decode(r.apparent_encoding) #解决乱码问题\n r.close()\n del(r)\n #first6\n matchObj = re.search(r'ptopid=(\\w+)\\&sid=(\\w+)\\\"',text)\n try:\n ptopid = matchObj.group(1)\n sid = matchObj.group(2)\n except:\n logging.warning(\"请检查账号\"+id+\"和密码\"+pwd+\"是否正确,或检查是否有验证码\")\n exit()\n else:\n logging.info(\"账号密码正确\")\n headers= {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',\n 'referer':'https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/login'\n }\n curr_punch=0\n while True:\n try:\n r = requests.get(\"https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb?ptopid=\"+ptopid+\"&sid=\"+sid+\"&fun2=\") #response里含有jksb对应的params\n except:\n logging.error(\"get请求失败\")\n if curr_punch>max_punch:\n exit()\n curr_punch+=1\n time.sleep(120)\n else:\n break\n text = r.text.encode(r.encoding).decode(r.apparent_encoding) #解决乱码问题\n tree=etree.HTML(text)\n nodes = tree.xpath('//*[@id=\"bak_0\"]/div[7]/span')\n # 如果今日填报过就退出填报,直接返回msg\n if nodes[0].text == \"今日您已经填报过了\":\n return nodes[0].text\n r.close()\n del(r)\n #jksb?with_params\n matchObj = re.search(r'ptopid=(\\w+)\\&sid=(\\w+)\\&',text)\n ptopid = matchObj.group(1)\n sid = matchObj.group(2)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',\n 'referer':'https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/login'\n }\n curr_punch=0\n while True:\n try:\n r = requests.get(\"https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb?ptopid=\"+ptopid+\"&sid=\"+sid+\"&fun2=\",headers=headers) #response为jksb表单第一页\n except:\n logging.info(\"第二次get请求失败\")\n while curr_punch>max_punch:\n exit()\n curr_punch+=1\n time.sleep(120)\n else:\n break\n ptopid1 = ptopid\n sid1 = sid\n\n text = r.text.encode(r.encoding).decode(r.apparent_encoding) #解决乱码问题\n r.close()\n del(r)\n #DONE\n matchObj = re.search(r'name=\\\"ptopid\\\" value=\\\"(\\w+)\\\".+name=\\\"sid\\\" value=\\\"(\\w+)\\\".+',text)\n ptopid = matchObj.group(1)\n sid = matchObj.group(2)\n form = {\n \"day6\": \"b\",\n \"did\": \"1\",\n \"door\": \"\",\n \"men6\": \"a\",\n \"ptopid\": ptopid,\n \"sid\": sid\n }\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',\n 'Referer': 'https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb?ptopid='+ptopid1+'&sid='+sid1+'&fun2=',\n 'Content-Type':'application/x-www-form-urlencoded'\n }\n while True:\n try:\n r = requests.post(\"https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb\",headers=headers,data=form) #response为打卡的第二个表单\n except:\n while curr_punch>max_punch:\n exit()\n curr_punch+=1\n else:\n break\n text = r.text.encode(r.encoding).decode(r.apparent_encoding) #解决乱码问题\n r.close()\n del(r)\n #DONE\n matchObj = re.search(r'name=\\\"ptopid\\\" value=\\\"(\\w+)\\\".+name=\\\"sid\\\" value=\\\"(\\w+)\\\"',text)\n ptopid = matchObj.group(1)\n sid = matchObj.group(2)\n form = {\n \"myvs_1\": \"否\",\n \"myvs_2\": \"否\",\n \"myvs_3\": \"否\",\n \"myvs_4\": \"否\",\n \"myvs_5\": \"否\",\n \"myvs_6\": \"否\",\n \"myvs_7\": \"否\",\n \"myvs_8\": \"否\",\n \"myvs_9\": \"否\",\n \"myvs_10\": \"否\",\n \"myvs_11\": \"否\",\n \"myvs_12\": \"否\",\n \"myvs_13\": \"g\",\n \"myvs_13a\": \"41\",\n \"myvs_13b\": \"4101\",\n \"myvs_13c\": \"河南省.郑州市.金水区\",\n \"myvs_24\": \"否\",\n \"myvs_26\": \"2\",\n \"myvs_14b\": \"\", #该选项已弃用\n \"memo22\": \"[待定]\",\n \"did\": \"2\",\n \"door\": \"\",\n \"day6\": \"b\",\n \"men6\": \"a\",\n \"sheng6\": \"\",\n \"shi6\": \"\",\n \"fun3\": \"\",\n \"jingdu\": \"113.64\",\n \"weidu\": \"34.71\",\n \"ptopid\": ptopid,\n \"sid\": sid\n }\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',\n 'Referer':'https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb',\n 'Content-Type':'application/x-www-form-urlencoded'\n }\n while True:\n try:\n r = requests.post(\"https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/jksb\",data=form,headers=headers) #response为完成打卡页面\n except:\n while curr_punch>max_punch:\n exit()\n curr_punch+=1\n else:\n break\n text = r.text.encode(r.encoding).decode(r.apparent_encoding) #解决乱码问题\n r.close()\n del(r)\n # 对text文件进行解析\n tree=etree.HTML(text)\n # print(type(tree))\n nodes = tree.xpath('//*[@id=\"bak_0\"]/div[2]/div[2]/div[2]/div[2]')\n for _ in nodes:\n msg = _.text\n if(\"感谢你今日上报健康状况!\" in msg):\n logging.info(id+\":打卡成功\")\n print(id+\":打卡成功\")\n \n else:\n logging.info(id+\":打卡失败\")\n print(id+\":打卡失败\")\n \n return msg\n\n\n\n# 发送邮件的函数\ndef mail(mail_text, mail_to):\n # set the mail context\n msg = MIMEText(mail_text)\n\n # set the mail info\n msg['Subject'] = \"每日健康打卡通知\" #主题\n msg['From'] = MAIL_USER\n msg['To'] = mail_to\n\n # send the mail\n # 发送到QQ邮箱\n send = smtplib.SMTP_SSL(\"smtp.qq.com\", 465)\n send.login(MAIL_USER, MAIL_PWD)\n send.send_message(msg)\n # quit QQ EMail\n send.quit()\n\nif __name__ == '__main__':\n msg = sign_in(id=id, pwd=pwd)\n mail(msg,MAIL_TO)\n\n","sub_path":"jksb.py","file_name":"jksb.py","file_ext":"py","file_size_in_byte":8550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"463085884","text":"class WarpDest():\n ''' Warp Speed: \n One's based GALAXY navigation.\n Guaranteed SAFE placement.\n '''\n def __init__(self, sector=-1, warp=0):\n if sector > 64: sector = 64 # zOuter Limits =)\n if warp > 10: warp = 10\n if warp < 0: warp = 0\n self.warp = warp\n self.sector = sector\n\n @staticmethod\n def parse(dest, sep=','):\n '''\n Parse: sector-num, speed-float - None on error\n Example: 5,1.1 \n '''\n dest = str(dest)\n cols = dest.split(sep)\n if len(cols) == 2:\n try:\n sector = int(cols[0].strip())\n if sector < 1:\n sector = 1\n speed = float(cols[1].strip())\n if speed < 0: speed = 0.1\n if speed > 9: speed = 9.0\n return WarpDest(sector, speed)\n except:\n pass\n return None\n\n\nclass SubDest():\n ''' Sublight Navigation:\n Zero based, AREA placement.\n Caveat, User! ;-)\n '''\n def __init__(self, xpos=-1, ypos=-1):\n if xpos > 7: xpos = 7\n if ypos > 7: ypos = 7\n if xpos < 0: xpos = 0\n if ypos < 0: ypos = 0\n self.xpos = xpos\n self.ypos = ypos\n\n @staticmethod\n def parse(dest, sep=','):\n '''\n WARNING: USER 1's -> 0-BASED TRANSLATION HERE\n\n Parse: [a-h], ypos \n or \n #,# \n Return None on error\n Example: b,5 \n '''\n dest = str(dest)\n cols = dest.split(sep)\n if len(cols) == 2:\n try:\n alph = cols[0].strip().lower()[0]\n num = 0\n if alph.isalpha():\n num = ord(alph) - 96 # 'a' == 1\n else:\n num = int(alph)\n xpos = num\n ypos = int(cols[1].strip()[0])\n return SubDest(xpos-1, ypos-1)\n except:\n pass\n return None\n\n\nclass Dest(WarpDest, SubDest):\n\n def __init__(self):\n WarpDest.__init__(self)\n SubDest.__init__(self)\n\n def is_null(self):\n return self.xpos == 0 and \\\n self.sector == -1\n\n def clone(self):\n result = Dest()\n result.xpos = self.xpos\n result.ypos = self.ypos\n result.sector = self.sector\n result.warp = self.warp\n return result\n\n\nif __name__ == '__main__':\n test = Dest()\n assert(test.is_null() == True)\n test.xpos = test.ypos = 123\n test.sector = 22\n test.warp = 22\n assert(test.is_null() == False)\n clone = test.clone()\n assert(clone.sector == test.sector)\n assert(clone.warp == test.warp)\n assert(clone.xpos == test.xpos)\n assert(clone.ypos == test.ypos)\n\n","sub_path":"Points.py","file_name":"Points.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"47746744","text":"#-*- coding: utf-8 -*-\r\n\r\nimport time\r\nimport random\r\nimport datetime\r\nimport os\r\nimport sys\r\nimport socket\r\nimport csv\r\n\r\nfrom django.contrib import auth\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom django.core.paginator import Paginator\r\nfrom django.core.urlresolvers import reverse\r\nfrom django.db.models import Q\r\nfrom django.http.response import HttpResponse, JsonResponse\r\nfrom django.shortcuts import render_to_response, redirect\r\nfrom django.template.context_processors import csrf\r\n\r\nfrom .cleaner import phone_validator\r\nfrom .forms import ClientForm, StatisticSearch, RecordForm, UploadFileForm\r\nfrom .models import Clients, Statistics, Records\r\n\r\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\n\r\n# def originate(request):\r\n# if request.is_ajax():\r\n# id = request.GET['id']\r\n# user = request.user.username\r\n# model_base_name = user + '_base'\r\n# model_base = apps.get_model('inform', model_base_name)\r\n# model_stats_name = user + '_stats'\r\n# model_stats = apps.get_model('inform', model_stats_name)\r\n# client = model_base.objects.get(id=id)\r\n# name = client.name\r\n# phone = client.phone\r\n# record = client.record\r\n# am = Ami()\r\n# am.connect()\r\n# origin = am.originate('9' + phone, record, user)\r\n# am.disconnect()\r\n# if origin['Response'] == 'Success':\r\n# status = 'ANSWER'\r\n# else:\r\n# status = 'NOANSWER'\r\n# time_now = datetime.datetime.now().strftime('%H:%M')\r\n# date_now = datetime.datetime.now().strftime('%Y-%m-%d')\r\n# model_stats.objects.create(name=name, phone=phone, record=record, date=date_now, time=time_now, status=status)\r\n# model_base.objects.get(id=id).delete()\r\n# response_data = {\r\n# 'id': id,\r\n# 'name': name,\r\n# 'phone': phone,\r\n# 'record': record,\r\n# 'date': date_now,\r\n# 'time': time_now,\r\n# 'status': status,\r\n# }\r\n# return JsonResponse(response_data)\r\n\r\n\r\ndef parse_row(row, line, user):\r\n if len(row) is not 3:\r\n return {\r\n 'valid': False,\r\n 'message': u'Строка {}: Неверное количество данных для '\r\n u'загрузки'.format(line)\r\n }\r\n try:\r\n row[0].decode('utf-8')\r\n decoding = 'utf-8'\r\n except UnicodeDecodeError:\r\n decoding = 'cp1251'\r\n client_name = row[0].decode(decoding)\r\n client_phone = row[1].decode(decoding)\r\n client_record = row[2].decode(decoding)\r\n phone = phone_validator(client_phone)\r\n if not phone['valid']:\r\n return {\r\n 'valid': False,\r\n 'message': u'Строка {}: '\r\n u'Неверный формат номера телефона'.format(line)\r\n }\r\n records_list = Records.objects.filter(\r\n user=user\r\n ).values_list('title', flat=True)\r\n if client_record not in records_list:\r\n return {\r\n 'valid': False,\r\n 'message': u'Строка {}: Запись \"{}\" не найдена для текущего '\r\n u'пользователя'.format(line, client_record)\r\n }\r\n record = Records.objects.get(title=client_record)\r\n to_create = Clients(user=user, name=client_name,\r\n phone=client_phone, record=record)\r\n return {'valid': True, 'to_create': to_create}\r\n\r\n\r\ndef index(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n return redirect(reverse('inform:clients'))\r\n else:\r\n return redirect(reverse('inform:login'))\r\n\r\n\r\ndef clients(request):\r\n user = auth.get_user(request)\r\n context = {}\r\n context.update(csrf(request))\r\n message_success = ''\r\n message_error = ''\r\n\r\n if request.POST:\r\n if request.FILES:\r\n file_form = UploadFileForm(request.POST, request.FILES)\r\n if file_form.is_valid():\r\n upload_file = request.FILES['file']\r\n file = str(upload_file).split('.')\r\n file_type = file[-1]\r\n warnings = []\r\n to_create = []\r\n\r\n if file_type == 'txt':\r\n row_reader = upload_file.readlines()\r\n for line, row in enumerate(row_reader, 1):\r\n row = row.rstrip().split(';')\r\n row_valid = parse_row(row, line, user)\r\n if not row_valid['valid']:\r\n warnings.append(row_valid['message'])\r\n continue\r\n to_create.append(row_valid['to_create'])\r\n\r\n elif file_type == 'csv':\r\n row_reader = csv.reader(upload_file, delimiter=';')\r\n for line, row in enumerate(row_reader, 1):\r\n row_valid = parse_row(row, line, user)\r\n if not row_valid['valid']:\r\n warnings.append(row_valid['message'])\r\n continue\r\n to_create.append(row_valid['to_create'])\r\n success = len(to_create)\r\n message_success = u'Добавлено записей: {}'.format(success)\r\n message_warning = u'
'.join(warnings) or ''\r\n try:\r\n Clients.objects.bulk_create(to_create)\r\n except ValueError as e:\r\n message_error = e\r\n message_success = ''\r\n message_warning = ''\r\n context['message_success'] = message_success\r\n context['message_warning'] = message_warning\r\n context['message_error'] = message_error\r\n\r\n else:\r\n client_form = ClientForm(request.POST, user=user)\r\n if client_form.is_valid():\r\n user = user\r\n name = client_form.cleaned_data['name']\r\n phone = client_form.cleaned_data['phone']\r\n record = client_form.cleaned_data['record']\r\n client = Clients.objects.create(\r\n user=user, name=name, phone=phone, record=record)\r\n if client:\r\n context['message_success'] = u'Клиент добавлен в список обзвона'\r\n client_form = ClientForm()\r\n file_form = UploadFileForm()\r\n clients_all = Clients.objects.filter(user=user)\r\n clients_curr = Paginator(clients_all, 10)\r\n page_number = request.GET.get('pn') or 1\r\n context['user'] = user\r\n context['clients'] = clients_curr.page(page_number)\r\n context['client_form'] = client_form\r\n context['file_form'] = file_form\r\n return render_to_response('clients.html', context)\r\n\r\n\r\ndef records(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n context = {}\r\n context.update(csrf(request))\r\n if request.POST:\r\n record_form = RecordForm(request.POST, request.FILES)\r\n if record_form.is_valid():\r\n user = user\r\n title = record_form.cleaned_data['title']\r\n record = Records.objects.create(\r\n user=user, title=title, file=request.FILES['file'])\r\n if record:\r\n context['message_success'] = u'Сообщение добавлено'\r\n record_form = RecordForm()\r\n records = Records.objects.filter(user=user)\r\n context['record_form'] = record_form\r\n context['user'] = user\r\n context['records'] = records\r\n return render_to_response('records.html', context)\r\n else:\r\n return redirect(reverse('inform:index'))\r\n\r\n\r\ndef statistic(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n page_number = request.GET.get('pn') or 1\r\n context = {}\r\n context.update(csrf(request))\r\n statistic_form = StatisticSearch(request.POST or None)\r\n statistic_all = Statistics.objects.filter(user=user)\r\n statistic_curr = Paginator(statistic_all, 10)\r\n context['user'] = user\r\n context['statistics'] = statistic_curr.page(page_number)\r\n context['statistic_form'] = statistic_form\r\n return render_to_response('statistic.html', context)\r\n else:\r\n return redirect(reverse('inform:index'))\r\n\r\n\r\ndef export(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n myQuery = Q(user=user)\r\n statistic_filtered = Statistics.objects.filter(myQuery)\r\n response = HttpResponse(content_type='text/csv')\r\n writer = csv.writer(response, delimiter=';')\r\n writer.writerow([u'Имя клиента'.encode('cp1251'),\r\n u'Телефон'.encode('cp1251'),\r\n u'Сообщение'.encode('cp1251'),\r\n u'Дата звонка'.encode('cp1251'),\r\n u'Время звонка'.encode('cp1251'),\r\n u'Статус'.encode('cp1251')])\r\n for row in statistic_filtered:\r\n name = row.name.encode('cp1251')\r\n phone = row.phone\r\n record = row.record.encode('cp1251')\r\n date = row.date\r\n time = row.time\r\n status = row.status\r\n writer.writerow([name, phone, record, date, time, status])\r\n time_now = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')\r\n response['Content-Disposition'] = 'attachment; filename=\"' + time_now + '.csv\"'\r\n return response\r\n else:\r\n return redirect(reverse('inform:index'))\r\n\r\n\r\ndef remove_client(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n to_delete = request.GET.get('rm')\r\n if to_delete == 'all':\r\n Clients.objects.filter(user=user).delete()\r\n else:\r\n try:\r\n Clients.objects.get(id=to_delete).delete()\r\n except ObjectDoesNotExist:\r\n print('no object %s' % to_delete)\r\n pass\r\n return redirect(reverse('inform:clients'))\r\n else:\r\n return redirect(reverse('inform:index'))\r\n\r\n\r\ndef remove_record(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n to_delete = request.GET.get('rm')\r\n if to_delete == 'all':\r\n Records.objects.filter(user=user).delete()\r\n else:\r\n try:\r\n Records.objects.get(id=to_delete).delete()\r\n except ObjectDoesNotExist:\r\n print('no object %s' % to_delete)\r\n pass\r\n return redirect(reverse('inform:records'))\r\n else:\r\n return redirect(reverse('inform:index'))\r\n\r\n\r\ndef start_inform(request):\r\n user = auth.get_user(request)\r\n if user.is_authenticated():\r\n context = {}\r\n context.update(csrf(request))\r\n clients_all = Clients.objects.filter(user=user)\r\n context = {\r\n 'user': user,\r\n 'clients': clients_all,\r\n }\r\n return render_to_response('startinform.html', context)\r\n else:\r\n return redirect(reverse('inform:index'))\r\n","sub_path":"inform/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"98467668","text":"import os\nimport sqlite3\nimport unittest\n\nfrom mmvizutil.db.query import (\n Query,\n db_query_df,\n db_query_list,\n query_bar,\n query_scatter\n)\n\nfrom mmvizutil.db.sqlite import (\n query_box\n)\n\ndef db_sqlite_path(fname):\n cur_dir = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(cur_dir, fname)\n\nDB_FILE_PATH = db_sqlite_path(\"data/customer.db\")\n\n\ndef db_query_customer():\n\n query = Query()\n query.value = \"select income num_1, travel_spending num_2, state cat_1 from customer\"\n\n return query\n\n\nclass TestSqliteQuery(unittest.TestCase):\n\n def test_query_list(self):\n\n with sqlite3.connect(DB_FILE_PATH) as connection:\n result = db_query_list(connection, db_query_customer())\n print(result)\n\n def test_query_df(self):\n with sqlite3.connect(DB_FILE_PATH) as connection:\n result = db_query_df(connection, db_query_customer())\n print(result)\n\n def test_query_box_df(self):\n with sqlite3.connect(DB_FILE_PATH) as connection:\n result = db_query_df(connection, query_box(db_query_customer()))\n print(result)\n\n def test_query_bar_df(self):\n with sqlite3.connect(DB_FILE_PATH) as connection:\n result = db_query_df(connection, query_bar(db_query_customer()))\n print(result)\n\n def test_query_scatter_df(self):\n with sqlite3.connect(DB_FILE_PATH) as connection:\n result = db_query_df(connection, query_scatter(db_query_customer(), \"max\", \"avg\"))\n print(result)\n\n# def main():\n# result = db_sqlite_query_df(db_query_customer_income())\n# print(result)\n#\n# if __name__ == \"__main__\": main()","sub_path":"test/sqlite/test_db_query.py","file_name":"test_db_query.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"164556785","text":"#!/usr/bin/python3\nimport os, requests, json, lxml.html, subprocess, zipfile, shutil, re\n\nclass ExtensionManager():\n\n def __init__(self):\n self.extensions_local_path = os.getenv(\"HOME\") + \"/.local/share/gnome-shell/extensions/\"\n self.extensions_sys_path = \"/usr/share/gnome-shell/extensions/\"\n self.results = []\n self.installed = self.list_all_extensions()\n self.version = self.run_command(\"gnome-shell --version\").split()[2]\n \n def run_command(self, command):\n return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode() \n\n def list_all_extensions(self):\n installed_extensions = []\n uuids = self.list_user_extensions() + self.list_system_extensions()\n enabled_extensions = re.findall(r'\\'(.+?)\\'', self.run_command(\"gsettings get org.gnome.shell enabled-extensions\"))\n for uuid in uuids:\n extension_local_path = self.extensions_local_path + uuid\n extension_sys_path = self.extensions_sys_path + uuid\n\n extension_data = {\"uuid\": uuid, \"local\": self.extension_is_local(uuid)}\n if uuid in enabled_extensions:\n extension_data[\"enabled\"] = True\n else:\n extension_data[\"enabled\"] = False\n if extension_data[\"local\"] == True:\n metadata = open(extension_local_path + \"/metadata.json\", \"r\").read()\n else:\n metadata = open(extension_sys_path + \"/metadata.json\").read()\n metadata = json.loads(metadata)\n\n # Check for preferences\n if os.path.exists(extension_sys_path + \"/prefs.js\") or os.path.exists(extension_local_path + \"/prefs.js\"):\n extension_data[\"prefs\"] = True\n else:\n extension_data[\"prefs\"] = False\n\n extension_data[\"name\"] = metadata[\"name\"]\n installed_extensions.append(extension_data)\n return installed_extensions\n \n def extension_is_local(self, uuid):\n if uuid in self.list_user_extensions():\n return True\n else:\n return False\n\n def list_system_extensions(self):\n return os.listdir(self.extensions_sys_path)\n\n def list_user_extensions(self):\n try:\n return os.listdir(self.extensions_local_path)\n except FileNotFoundError:\n os.mkdir(self.extensions_local_path)\n return os.listdir(self.extensions_local_path)\n\n def search(self, query):\n try:\n response = self.get_request(\"https://extensions.gnome.org/extension-query/?page=1&search=\" + query)\n except:\n raise\n return \n self.results = json.loads(response.text)[\"extensions\"]\n\n def get_extensions(self, uuid):\n # Parse the extension webpage and get the json from the data-svm element\n url = \"https://extensions.gnome.org\" + self.results[self.get_index(uuid)][\"link\"]\n try:\n response = self.get_request(url)\n except:\n raise\n\n root = lxml.html.fromstring(response.text)\n content = root.xpath(\"/html/body/div[2]/div/div[2]/@data-svm\")[0]\n releases = json.loads(content)\n\n # Get matching version\n extension_id = \"\"\n\n # Iterate through the different releases and get the matching one for your gnome version and failsafe to the lastest release\n subversions = []\n for key, value in releases.items():\n subversions.append(float(key[2:]))\n\n if self.version.startswith(str(key)):\n extension_id = str(value[\"pk\"])\n \n # If the ID doesn't start with your current version, get the highest one\n if extension_id == \"\":\n\n # Use re to remove .0 from the float conversion above\n max_subversion = re.sub('\\.0$', '', str(max(subversions)))\n highest_version = \"3.\" + max_subversion\n extension_id = str(releases[highest_version][\"pk\"])\n\n # Download and install\n try:\n self.download(\"https://extensions.gnome.org/download-extension/\" + uuid + \".shell-extension.zip?version_tag=\" + extension_id, uuid)\n self.install(uuid)\n except:\n raise\n\n def get_index(self, uuid):\n for index, entry in enumerate(self.results):\n if entry[\"uuid\"] == uuid:\n return index\n \n def get_uuid(self, index):\n return self.results[index][\"uuid\"]\n\n def download(self, url, uuid):\n try:\n response = self.get_request(url)\n with open(self.get_zip_path(uuid), \"wb\") as file:\n file.write(response.content)\n print(\"Downloaded \" + uuid)\n except:\n raise\n\n def remove(self, uuid):\n install_path = self.extensions_local_path + uuid\n if os.path.isdir(install_path):\n print(\"Deleting \" + uuid)\n try:\n shutil.rmtree(install_path)\n except:\n raise\n self.installed = self.list_all_extensions()\n \n def get_image(self, uuid):\n url = \"https://extensions.gnome.org\" + self.results[self.get_index(uuid)][\"icon\"]\n if url == \"https://extensions.gnome.org/static/images/plugin.png\":\n return None\n try:\n response = self.get_request(url)\n return response.content\n except:\n raise\n \n def get_request(self, url):\n response = requests.get(url)\n if response == None:\n raise\n return\n return response\n \n def set_extension_status(self, uuid, status):\n self.run_command(\"gnome-extensions \" + status + \" \" + uuid)\n \n def get_zip_path(self, uuid):\n return \"/tmp/\" + uuid + \".zip\"\n\n def install(self, uuid):\n # Remove old extension \n self.remove(uuid)\n zip_path = self.get_zip_path(uuid)\n\n # Create new folder with matching uuid and extract to it\n install_path = self.extensions_local_path + uuid\n\n try:\n os.mkdir(install_path)\n with zipfile.ZipFile(zip_path,\"r\") as zip_ref:\n zip_ref.extractall(install_path)\n os.remove(zip_path)\n self.installed = self.list_all_extensions()\n print(\"Installed \" + uuid)\n \n except:\n raise\n\n\n\n","sub_path":"extensionmanager/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"549300844","text":"# _*_ coding: utf-8 _*_\r\nfrom Tkinter import* \r\n\r\nmaster = Tk() # 创建根窗口\r\n\r\nlistbox = Listbox(master) # 引入Listbox组件,创建消息窗口\r\nlistbox.pack() # 组块\r\n\r\nlistbox.insert(END, \"a list entry\") # 输出某值\r\n\r\nfor item in range(0,30): # 输出列表元素,与本次任务吻合\r\n\tlistbox.insert(END, item)\r\n\r\nmainloop() # 进入消息循环,否则无法显示界面\r\n\r\n","sub_path":"_src/om2py2w/2wex0/tk_listbox.py","file_name":"tk_listbox.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"204730767","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _ \nimport logging\n_logger = logging.getLogger(__name__)\n\nclass AccountInvoice(models.Model):\n\t_inherit = 'account.invoice'\n\n\t@api.multi\n\tdef get_bom_details_summary(self):\n\t\tif self.invoice_line_ids: \n\t\t\tproduct_bom_list = {}\n\t\t\tfor invoice_id in self.invoice_line_ids:\n\t\t\t\tbom_obj = self.env['mrp.bom'].search([('product_tmpl_id','=', invoice_id.product_id.product_tmpl_id.id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t ('company_id','=', self.company_id.id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t ('type','=', 'phantom')], limit=1)\n\t\t\t\tif bom_obj:\n\t\t\t\t\tquantity_converted = invoice_id.quantity / bom_obj.product_qty\n\t\t\t\t\tbom_ctr = 1\n\n\t\t\t\t\tfor line_id in bom_obj.bom_line_ids:\n\t\t\t\t\t\tif line_id.id != bom_obj.bom_line_ids.ids[0]:\n\n\t\t\t\t\t\t\tnames = str(line_id.product_id.id) + 'UOM' + str(line_id.product_uom_id.id)\n\t\t\t\t\t\t\tproduct_name = line_id.product_id.name\n\n\t\t\t\t\t\t\tif line_id.product_id.description_sale:\n\t\t\t\t\t\t\t\tproduct_name = line_id.product_id.description_sale\n\n\t\t\t\t\t\t\tif names not in product_bom_list:\n\t\t\t\t\t\t\t\tproduct_bom_list[names] = [\n\t\t\t\t\t\t\t\t\tproduct_name,\n\t\t\t\t\t\t\t\t\tline_id.product_uom_id,\n\t\t\t\t\t\t\t\t\tquantity_converted * line_id.product_qty]\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tproduct_bom_list[names][2] += (quantity_converted * line_id.product_qty)\n\t\t\t\t\t\t\tbom_ctr +=1\n\t\t\treturn product_bom_list\n\t\treturn False\n\n\n\nclass AccountInvoiceLine(models.Model):\n\t_inherit = 'account.invoice.line'\n\n\t@api.multi\n\tdef get_product_bom_details(self):\n\t\tself.ensure_one()\n\t\tbom_obj = self.env['mrp.bom'].search([('product_tmpl_id','=', self.product_id.product_tmpl_id.id),\n\t\t\t\t\t\t\t\t\t\t ('company_id','=', self.company_id.id),\n\t\t\t\t\t\t\t\t\t\t ('type','=', 'phantom')], limit=1)\n\t\tif bom_obj:\n\t\t\t#raise Warning(bom_obj.bom_line_ids[1:])\n\t\t\treturn bom_obj.bom_line_ids[0]\n\n\t\treturn False\n\n\n\n\n\n\n\n# class goodheart(models.Model):\n# _name = 'goodheart.goodheart'\n# name = fields.Char()\n# value = fields.Integer()\n# value2 = fields.Float(compute=\"_value_pc\", store=True)\n# description = fields.Text()\n#\n# @api.depends('value')\n# def _value_pc(self):\n# self.value2 = float(self.value) / 100\n","sub_path":"gh_shoot_so_coneland/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"88024018","text":"import re\n\n\ndef calculate():\n fo = open(\"data.txt\", \"r+\")\n lines = fo.readlines()\n total = 0\n grp = []\n for line in lines:\n line = line.strip()\n if line == \"\":\n total += group_sum(grp)\n grp = []\n else:\n grp.append(line)\n\n total += group_sum(grp)\n return total\n\ndef group_sum(lines):\n group_results = 0\n for line in lines:\n group_results |= person_binary(line)\n return sum(int(b) for b in \"{0:b}\".format(group_results))\n\ndef person_binary(answers):\n hash = 0\n for letter in answers:\n hash |= 2**order_number(letter)\n return hash\n\ndef order_number(letter):\n return ord(letter) - ord('a')\n","sub_path":"day06a/program_lib.py","file_name":"program_lib.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"516663146","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom rest_framework import permissions\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom picpay.search import *\n\nfrom .secrets import *\n\n__author__ = 'Roberto Morati '\n__copyright__ = ' Copyright (c) 2017'\n__version__ = '0.0.1'\n\n\nclass InfoSearchViewSet(APIView):\n \"\"\"\n title: Basic Info to start the Search\n\n * description: Return the informations that are necessary to use the service api.v1.search\"\n\n * retrieve: token to start the search\n \"\"\"\n permission_classes = (permissions.AllowAny,)\n\n def get(self, request, *args, **kw):\n\n infs = {}\n if 'data_search' in kw:\n infs = info_search(kw['data_search'])\n else:\n infs = info_search()\n\n if 'success' in infs:\n for key in list(request.session.keys()):\n del request.session[key]\n request.session.modified = True\n\n token = token_hex(6)\n request.session[token] = infs\n\n response = {}\n response['pages'] = infs['pages']\n response['total'] = infs['total']\n response['success'] = infs['success']\n response['token'] = token\n print(\"token : \" + str(response['token']))\n else:\n response = {}\n response['error'] = infs['error']\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass UserSearchViewSet(APIView):\n \"\"\"\n title: Search by users\n\n * description: Return the informations about users.\n\n * retrieve: users (id, username and fullname)\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n\n def get(self, request, *args, **kw):\n response = {}\n if 'token' in kw:\n if kw['token'] in request.session:\n if 'data_search' in kw:\n if not (kw['data_search'] == request.session[kw['token']]['data_search']):\n response['error'] = 'data_search invalid'\n else:\n response = search(data_search=kw['data_search'], info_search=request.session[kw['token']], page=(int(kw['page']) - 1))\n else:\n if not ('data_search' in kw):\n if request.session[kw['token']]['data_search'] is not None:\n response['error'] = 'data_search invalid'\n else:\n response = search(info_search=request.session[kw['token']], page=(int(kw['page']) - 1))\n else:\n response['error'] = 'invalid token'\n return Response(response, status=status.HTTP_200_OK)\n","sub_path":"api/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"275796404","text":"def resize_fs(module, filesystem, size):\n ' Resize LVM file system. '\n chfs_cmd = module.get_bin_path('chfs', True)\n if (not module.check_mode):\n (rc, chfs_out, err) = module.run_command(('%s -a size=\"%s\" %s' % (chfs_cmd, size, filesystem)))\n if (rc == 28):\n changed = False\n return (changed, chfs_out)\n elif (rc != 0):\n if re.findall('Maximum allocation for logical', err):\n changed = False\n return (changed, err)\n else:\n module.fail_json('Failed to run chfs.', rc=rc, err=err)\n else:\n if re.findall('The filesystem size is already', chfs_out):\n changed = False\n else:\n changed = True\n return (changed, chfs_out)\n else:\n changed = True\n msg = ''\n return (changed, msg)","sub_path":"Data Set/bug-fixing-3/75724bb7cabcdd78eed0ee3435b056e75db315ee--bug.py","file_name":"75724bb7cabcdd78eed0ee3435b056e75db315ee--bug.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"537033116","text":"#encoding=utf-8\nfrom django.shortcuts import render, render_to_response\n\n# Create your views here.\nfrom blogs.models import passage\n\n\ndef home(req):\n posts = []\n\n return render_to_response(\"pages/home.html\", {\"posts\":posts})\n\ndef example_home(req):\n posts = []\n\n raws = passage.objects.filter()[:10]\n for blograw in raws:\n if blograw.type == 1:\n standard_post = {}\n standard_post[\"id\"] = blograw.id\n standard_post[\"type\"] = blograw.type\n standard_post[\"title\"] = blograw.title\n standard_post[\"text\"] = blograw.text\n standard_post[\"time\"] = blograw.time\n standard_post[\"author\"] = blograw.author\n standard_post[\"href\"] = blograw.href\n standard_post[\"tags\"] = blograw.tags.split(\"|\")\n posts.append(standard_post)\n elif blograw.type == 2:\n gallary_post = {}\n gallary_post[\"id\"] = blograw.id\n gallary_post[\"imgs\"] = blograw.quote.split(\"|\")\n gallary_post[\"type\"] = 2\n gallary_post[\"title\"] = \"测试文章\"\n gallary_post[\"text\"] = blograw.text\n gallary_post[\"time\"] = blograw.time\n gallary_post[\"author\"] = blograw.author\n gallary_post[\"href\"] = blograw.href\n gallary_post[\"tags\"] = blograw.tags.split(\"|\")\n\n posts.append(gallary_post)\n elif blograw.type == 3:\n youtube_post = {}\n youtube_post[\"id\"] = blograw.id\n youtube_post[\"ylink\"] = blograw.link\n youtube_post[\"type\"] = 3\n youtube_post[\"title\"] = \"测试文章\"\n youtube_post[\"text\"] = blograw.text\n youtube_post[\"time\"] = blograw.time\n youtube_post[\"author\"] = blograw.author\n youtube_post[\"href\"] = blograw.href\n youtube_post[\"tags\"] = blograw.tags.split(\"|\")\n posts.append(youtube_post)\n elif blograw.type == 4:\n link_post = {}\n link_post[\"id\"] = blograw.id\n link_post[\"link\"] = \"http://www.wrapbootstrap.com/\"\n link_post[\"type\"] = 4\n link_post[\"title\"] = \"测试文章\"\n link_post[\"text\"] = blograw.text\n link_post[\"time\"] = blograw.time\n link_post[\"author\"] = blograw.author\n link_post[\"href\"] = blograw.href\n link_post[\"tags\"] = blograw.tags.split(\"|\")\n posts.append(link_post)\n elif blograw.type == 5:\n quote_post = {}\n quote_post[\"id\"] = blograw.id\n quote_post[\"quote\"] = blograw.quote\n quote_post[\"type\"] = 5\n quote_post[\"author\"] = blograw.author\n posts.append(quote_post)\n\n\n\n pages = [[1, \"\"], [2, \"\"], [3, \"\"]]\n current_page = 2\n tags = [[\"Java\", \"/tag/java\"], [\"Python\", \"/tag/python\"], [\"NLP\", \"/tag/nlp\"], [\"Machine Learning\", \"/tag/ml\"]]\n\n return render_to_response(\"pages/home.html\", {\"posts\":posts, \"pages\":pages, \"current_page\":current_page, \"tags\":tags})\n\n\ndef blog(req, bid=0):\n blograw = passage.objects.get(id=bid)\n post = {}\n if blograw.type == 1:\n post[\"id\"] = blograw.id\n post[\"type\"] = blograw.type\n post[\"title\"] = blograw.title\n post[\"text\"] = blograw.text\n post[\"time\"] = blograw.time\n post[\"author\"] = blograw.author\n post[\"href\"] = blograw.href\n post[\"tags\"] = blograw.tags.split(\"|\")\n elif blograw.type == 2:\n post[\"id\"] = blograw.id\n post[\"imgs\"] = blograw.quote.split(\"|\")\n post[\"type\"] = 2\n post[\"title\"] = \"测试文章\"\n post[\"text\"] = blograw.text\n post[\"time\"] = blograw.time\n post[\"author\"] = blograw.author\n post[\"href\"] = blograw.href\n post[\"tags\"] = blograw.tags.split(\"|\")\n elif blograw.type == 3:\n post[\"id\"] = blograw.id\n post[\"ylink\"] = blograw.link\n post[\"type\"] = 3\n post[\"title\"] = \"测试文章\"\n post[\"text\"] = blograw.text\n post[\"time\"] = blograw.time\n post[\"author\"] = blograw.author\n post[\"href\"] = blograw.href\n post[\"tags\"] = blograw.tags.split(\"|\")\n elif blograw.type == 4:\n post[\"id\"] = blograw.id\n post[\"link\"] = \"http://www.wrapbootstrap.com/\"\n post[\"type\"] = 4\n post[\"title\"] = \"测试文章\"\n post[\"text\"] = blograw.text\n post[\"time\"] = blograw.time\n post[\"author\"] = blograw.author\n post[\"href\"] = blograw.href\n post[\"tags\"] = blograw.tags.split(\"|\")\n elif blograw.type == 5:\n post[\"id\"] = blograw.id\n post[\"quote\"] = blograw.quote\n post[\"type\"] = 5\n post[\"author\"] = blograw.author\n\n return render_to_response(\"pages/blog.html\", {\"bid\":bid, \"post\":post})\n\ndef publish(req):\n return render_to_response(\"pages/publish.html\")\n\n# Create your views here.\ndef about(req):\n return render_to_response(\"pages/about.html\", {})\n\n# Create your views here.\ndef contact(req):\n return render_to_response(\"pages/about.html\", {})\n\n# Create your views here.\ndef works(req):\n return render_to_response(\"pages/about.html\", {})\n","sub_path":"blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"168269219","text":"import sf\nimport resourcemanager\n\nclass Menu (object):\n def __init__ (self, game, width = 50):\n self.game = game\n\n self.x = 0\n self.y = 0\n self.width = width\n \n self.font = resourcemanager.get('font.menu')\n \n self.entries = []\n self.selected_index = 0\n\n self.input = []\n \n def add_title (self, label, label_size=24):\n self.add_entry(None, label, label_size)\n\n def add_entry (self, widget, label=None, label_size=24):\n ''' append an entry to the menu\n None widgets will be treated as separators/titles '''\n \n if widget: widget.menu = self\n \n entry = {\n 'label': sf.Text(label, self.font, label_size) if label else None,\n 'widget': widget\n }\n \n self.entries.append(entry)\n \n this_index = self.entries.index(entry)\n \n if this_index > 0:\n # if previous entry is unselectable, make this one the selected one\n if self.entries[this_index-1]['widget'] == None:\n self.selected_index = this_index\n\n def change_selected(self, index):\n if not index == self.selected_index:\n self.selected_index = index\n resourcemanager.get(\"sound.menu_change\").play()\n \n def execute_action(self):\n \n resourcemanager.get(\"sound.menu_select\").play()\n \n entry = self.entries[self.selected_index]\n entry['callback'](entry['data']) if entry['data'] else entry['callback']()\n\n def update (self, input):\n mx, my = sf.Mouse.get_position(self.game.window)\n\n index_changed = False\n execute_action = False\n index = self.selected_index\n \n if input['up']:\n\n if index == 0:\n index = len(self.entries)-1\n else:\n index -= 1\n \n index_changed = True\n \n elif input['down']:\n \n if index == len(self.entries)-1:\n index = 0\n else:\n index += 1\n \n index_changed = True\n \n for i, entry in enumerate(self.entries):\n if entry['widget']:\n entry['widget'].dehilight()\n\n local_bounds = sf.FloatRect()\n \n if entry['widget']:\n local_bounds.left = entry['widget'].x\n local_bounds.top = entry['widget'].y\n local_bounds.height = entry['widget'].height\n\n if entry['label']:\n local_bounds.left = entry['label'].x\n local_bounds.top = entry['label'].y\n local_bounds.height = entry['label'].local_bounds.height\n \n local_bounds.width = self.width\n \n if local_bounds.contains(mx, my) and entry['widget']:\n index = i\n index_changed = True\n \n if sf.Mouse.is_button_pressed(sf.Mouse.LEFT):\n input['confirm'] = True\n\n if index_changed:\n if self.entries[index]['widget'] == None:\n self.selected_index = index\n self.update(input)\n return # avoid using invalid index because recursion\n\n self.change_selected(index)\n \n self.entries[self.selected_index]['widget'].hilight()\n self.entries[self.selected_index]['widget'].update(input)\n\n def render (self, target):\n offset = 0\n i = 0\n for i, entry in enumerate(self.entries):\n lh = 0\n if entry['label']:\n entry['label'].x = self.x\n entry['label'].y = self.y + offset\n \n if self.selected_index == i:\n entry['label'].color = sf.Color.CYAN\n else:\n entry['label'].color = sf.Color.WHITE\n \n target.draw(entry['label'])\n lh = entry['label'].local_bounds.height\n\n wh = 0\n if entry['widget']:\n entry['widget'].x = self.x\n if entry['label']: entry['widget'].x += entry['label'].local_bounds.width + 10\n\n entry['widget'].y = self.y + offset\n entry['widget'].render(target)\n \n wh = entry['widget'].height\n\n offset += max(lh, wh) + 2\n\nclass Widget (object):\n def __init__ (self):\n self.x = 0\n self.y = 0\n\n self.menu = None\n self.color = sf.Color.WHITE\n \n def dehilight (self):\n self.color = sf.Color.WHITE\n\n def hilight (self):\n self.color = sf.Color.CYAN\n\n def update (self, input):\n pass\n\n def render(self, target):\n pass\n\nclass Button (Widget):\n def __init__ (self, label_text, width=100, height=25, callback=None, data=None, text_size=24):\n super(Button, self).__init__()\n self.width = width\n self.height = height\n\n self.label_text = label_text\n self.label_text_size = text_size\n self.label = None\n \n self.connect(callback, data)\n\n def connect (self, callback, data=None):\n self.callback = callback\n self.data = data\n\n def activate (self):\n resourcemanager.get(\"sound.menu_select\").play()\n\n if self.callback:\n if self.data:\n self.callback(self.data)\n else:\n self.callback()\n\n def update (self, input):\n if input['confirm']:\n self.activate()\n\n def render (self, target):\n if self.label == None:\n self.label = sf.Text(self.label_text, self.menu.font, self.label_text_size)\n\n self.label.x = self.x\n self.label.y = self.y\n self.label.color = self.color\n\n target.draw(self.label)\n\nclass Slider (Widget):\n def __init__ (self, width=200):\n super(Slider, self).__init__()\n\n self.height = 25\n self.width = width\n\n self.x = 0\n self.y = 0\n\n self.slide = sf.RectangleShape((10, 10))\n self.slide.origin = (5, 5)\n\n self.value = 0\n self.grabbed = False\n \n def update (self, input):\n mx, my = sf.Mouse.get_position(self.menu.game.window)\n\n local_bounds = sf.FloatRect(\n self.x, self.y,\n self.width, self.height\n )\n\n if local_bounds.contains(mx ,my):\n if sf.Mouse.is_button_pressed(sf.Mouse.LEFT):\n self.grabbed = True\n\n if self.grabbed:\n if sf.Mouse.is_button_pressed(sf.Mouse.LEFT):\n self.value = ((mx - self.x) / float(self.width)) * 100\n else:\n self.grabbed = False\n\n if input['left']:\n self.value -= 1\n elif input['right']:\n self.value += 1\n\n # clamp within [0, 100]\n self.value = max(0, min(self.value, 100))\n\n def render (self, target):\n line = sf.RectangleShape((self.width,1))\n line.x = self.x\n line.y = self.y + self.height/1.5\n line.fill_color = self.color\n\n self.slide.x = self.x + self.width * (self.value/100.0)\n self.slide.y = line.y\n self.slide.fill_color = self.color\n\n target.draw(line)\n target.draw(self.slide) \n","sub_path":"lapsus/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"598142320","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Image Segmentation Using Python's PixelLib Package: \n# Last modified: July 13, 2021\n\n# ## Useful links / Citations:\n# https://towardsdatascience.com/custom-instance-segmentation-training-with-7-lines-of-code-ff340851e99b\n# https://pixellib.readthedocs.io/en/latest/custom_inference.html\n\n# ## Import PixelLib and load random training photo:\n# Shows a random training photo with handpicked mask polygon from LabelMe annotation.\n# Run cell multiple times to make sure your image annotations are showing up as expected.\n\n# In[1]:\n\n\nimport pixellib\nfrom pixellib.custom_train import instance_custom_training\n\nvis_img = instance_custom_training()\nvis_img.load_dataset(\"/Users/sebastianperezlopez/Desktop/PixelLabTesting/SeepageDatasetNEW.nosync\")\nvis_img.visualize_sample()\n\n\n# ## Train model\n# Load MaskRCNN model, load pre-trained coco weights, set batch size / epochs / data augmentation\n\n# In[3]:\n\n\nimport pixellib\nfrom pixellib.custom_train import instance_custom_training\n\ntrain_maskrcnn = instance_custom_training()\ntrain_maskrcnn.modelConfig(network_backbone = \"resnet101\", num_classes= 1, batch_size = 4)\ntrain_maskrcnn.load_pretrained_model(\"/Users/sebastianperezlopez/Desktop/PixelLabTesting/COCO Model.nosync/mask_rcnn_coco.h5\")\ntrain_maskrcnn.load_dataset(\"/Users/sebastianperezlopez/Desktop/PixelLabTesting/SeepageDatasetNEW.nosync\")\ntrain_maskrcnn.train_model(num_epochs = 4, augmentation=False, path_trained_models = \"/Users/sebastianperezlopez/Desktop/PixelLabTesting/mask_rcnn_models.nosync\")\n\n\n# ## Create segmentation mask on new image using trained model \n# Photo output showing predicted mask over original photo\n# \n# *Set extract_segmented_objects=True if you want a .jpg file with only the segmented part of your original showing. Will appear in the directory of your .ipynb file. \n\n# In[21]:\n\n\n# Save extracted object (what mask predicts) as a separate file\nimport pixellib\nfrom pixellib.instance import custom_segmentation\n\nsegment_image = custom_segmentation()\nsegment_image.inferConfig(num_classes= 1, class_names= [\"BG\", \"seepage\"])\nsegment_image.load_model('/Users/sebastianperezlopez/Desktop/PixelLabTesting/mask_rcnn_models.nosync/Epoch2_16July') # Put filename of .h5 that has weights you just trained\nsegment_image.segmentImage(\"/Users/sebastianperezlopez/Desktop/framefolder.nosync/raw frames/_frame16500.jpg\", show_bboxes=False, output_image_name=\"/Users/sebastianperezlopez/Desktop/framefolder.nosync/mask+image/_frame16500.jpg\", extract_segmented_objects=False, save_extracted_objects=True)\n\n\n\n# In[14]:\n\n\n# importing pyplot and image from matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\n \n# reading png image file\nim = img.imread('/Users/sebastianperezlopez/Desktop/5 epochs/seepageTEST5.jpg')\n \n# show image\nplt.imshow(im)\n\n\n# ## Create segmentation mask on single image using trained model for further image manipulation (no output)\n# No photo output here; instead, saving segmented mask in segmask variable\n\n# In[28]:\n\n\nimport pixellib\nfrom pixellib.instance import custom_segmentation\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\n\noriginalImage = '/Users/sebastianperezlopez/Desktop/framefolder.nosync/raw frames/_frame16500.jpg'\n\nsegment_image = custom_segmentation()\nsegment_image.inferConfig(num_classes= 1, class_names= [\"BG\", \"seepage\"])\nsegment_image.load_model('/Users/sebastianperezlopez/Desktop/PixelLabTesting/mask_rcnn_models.nosync/Epoch2_16July') # Put filename of .h5 that has weights you just trained\nsegmask, output = segment_image.segmentImage(originalImage, show_bboxes=True, extract_segmented_objects= True)\n\n\n\n# ## Isolate Mask\n\n# In[29]:\n\n\n#https://www.codespeedy.com/change-the-pixel-values-of-an-image-in-python/\n\nfrom PIL import Image\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport numpy\nfrom numpy import array\n\noutputMask = segmask['masks']\n\nimage = img.imread(originalImage)\n\nnewImage = Image.new('RGB', (image.shape[1],image.shape[0]), \"black\")\npixels = newImage.load()\n\nfor i in range(newImage.size[0]):\n for j in range(newImage.size[1]):\n if outputMask[j,i] == array([True]):\n pixels[i,j] = (255,255,255)\n if outputMask[j,i] == array([False]): \n pixels[i,j] = (0,0,0)\n \ndisplay(newImage)\n\nnewImage.save('/Users/sebastianperezlopez/Desktop/framefolder.nosync/segmented mask/_frame16500.jpg')\n\n#image.shape\n#outputMask.shape\n\n#for i in range(newImage.shape[0]):\n # for j in range(newImage.shape[1]):\n # if outputMask[i, j] == False:\n # newImage[i, j] = 0\n # else:\n # newImage[i, j] = 1\n\n\n# ## Isolate Masks' Upper Border\n\n# In[30]:\n\n\nfrom PIL import Image\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport numpy\nfrom numpy import array\n\noutputMask = segmask['masks']\n\nimage = img.imread(originalImage)\n\nnewImage = Image.new('RGB', (image.shape[1],image.shape[0]), \"black\")\npixels = newImage.load()\n\n# outputMask = mask\n# newImage = size of original image, all black. \n\n\nfor i in range(newImage.size[0]):\n j = 0\n while outputMask[j,i] == array([False]):\n j += 1\n #if j == 4677: \n if j == image.shape[0]: \n break\n if outputMask[j,i] == array([True]):\n pixels[i,j] = (255,255,255)\n pixels[i+1,j] = (255,255,255)\n pixels[i+2,j] = (255,255,255)\n pixels[i+3,j] = (255,255,255)\n pixels[i-1,j] = (255,255,255)\n pixels[i-2,j] = (255,255,255)\n pixels[i-3,j] = (255,255,255)\n break\n \n\ndisplay(newImage)\n\n\nnewImage.save('/Users/sebastianperezlopez/Desktop/framefolder.nosync/segmented border/_frame16500.jpg')\n\n\n# ## Analyze a video file and separate frames / run image segmentation on each frame.\n\n# In[ ]:\n\n\n# crop video to only tank (I found this was easiest to do on an iPhone...)\n# need cv2 (OpenCV)\n\n\n# In[18]:\n\n\nimport cv2\n\nvideo = cv2.VideoCapture(\"/Users/sebastianperezlopez/Desktop/framefolder.nosync/DSC_7166.mp4\")\ntotal_frames = video.get(cv2.CAP_PROP_FRAME_COUNT)\nprint(total_frames)\n\nfor i in range(0, 17784, 500):\n video.set(1, i)\n ret, still = video.read()\n cv2.imwrite(f'/Users/sebastianperezlopez/Desktop/framefolder.nosync/raw frames/_frame{i}.jpg', still)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"MaskRCNN.py","file_name":"MaskRCNN.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"389027471","text":"#!/usr/bin/python3\nclass Square():\n \"\"\"A class used to represent a square.\n\n Attributes:\n __size: A private int with size of Square.\n \"\"\"\n def __init__(self, size=0):\n \"\"\"Inits Square with size, pnly allowed type int > 0.\"\"\"\n try:\n if not type(size) == int:\n raise TypeError\n except TypeError as e:\n raise Exception(\"size must be an integer\") from e\n try:\n if (int(size) < 0):\n raise ValueError\n self.__size = size\n except ValueError as e:\n raise Exception(\"size must be >= 0\") from e\n","sub_path":"0x06-python-classes/2-square.py","file_name":"2-square.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"577773022","text":"#-*- coding: utf-8 -*-\nimport pprint, json, requests\n \nimport xml.etree.ElementTree\nfrom bs4 import BeautifulSoup\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n# Create your views here.\n\nserviceKey = \"sYYsbAStv5lTMH32zXdixfecuB3dMciY5lyOva1NYa0rQD2odfRg82LZn%2F3QBqa%2BerqaXm28HDph%2FcPI%2BQe7Tw%3D%3D\"\n# serviceKey = URLEncoder.encode(serviceKey, \"UTF-8\")\n\ndef health(request):\n return JsonResponse({})\n# serviceKey = URLEncoder.encode(serviceKey, \"UTF-8\");\n private\n pprint.pprint(request.body)\n if request.method == 'POST':\n # nugu_body = json.loads(request.body, encoding='utf-8')\n aItem = request.POST.get(\"a\")\n bItem = request.POST.get(\"b\")\n url = f\"http://apis.data.go.kr/1470000/DURPrdlstInfoService/getUsjntTabooInfoList?ServiceKey={serviceKey}&itemName={aItem}\"\n print(url)\n responses = requests.get(url)\n response = BeautifulSoup(responses.content, 'lxml-xml')\n pprint.pprint(response)\n \n # pprint.pprint(nugu_body)\n \n else:\n return render(request, 'pills/interaction.html')\n \ndef oldmanCare(request):\n global serviceKey # 서비스 인증키 불러오기 (전역변수)\n \n # 요청변수(Request Parameter)\n typeName = \"병용금기\" # DUR 유형\n ingrName = \"클로르디아제폭시드\" # DUR 성분\n \n # DUR 품목정보 API\n # 서비스요청 URL\n url = f'http://apis.data.go.kr/1470000/DURIrdntInfoService/getOdsnAtentInfoList?ServiceKey={serviceKey}&typeName={typeName}&ingrName={ingrName}&numOfRows=3&pageNo=1'\n responses = requests.get(url)\n response = BeautifulSoup(responses.content, 'lxml-xml')\n pprint.pprint(response)\n return render(request, 'pills/oldmanCare.html', {'response': response})\n ","sub_path":"pills/.~c9_invoke_tGgs7.py","file_name":".~c9_invoke_tGgs7.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"582453812","text":"\"\"\"Phabricator client classes.\"\"\"\n\nimport requests\n\n\nclass PhabricatorClient:\n \"\"\"Simple Phabricator client.\"\"\"\n\n PRIORITY_HIGH = 75\n\n STATUS_OPEN = 'open'\n\n def __init__(self, host, api_token):\n \"\"\"Create client for specified host and api token.\"\"\"\n self.host = host\n self.api_token = api_token\n\n def api_request(self, method, params):\n \"\"\"Make api request to Phabricator.\"\"\"\n params['api.token'] = self.api_token\n r = requests.get('https://{}/api/{}'.format(self.host, method),\n params=params)\n return r.json()['result']\n\n def get_task(self, task_id):\n \"\"\"Get task by id.\"\"\"\n result = self.api_request('maniphest.search', {\n 'constraints[ids][0]': task_id\n })['data']\n\n if len(result) > 0:\n result = result[0]\n else:\n return None\n\n return PhabricatorTask.fromApiResult(self, result)\n\n def get_user(self, user_phid):\n \"\"\"Get user by phid.\"\"\"\n result = self.api_request('user.search', {\n 'constraints[phids][0]': user_phid\n })['data'][0]\n\n user = PhabricatorUser(self)\n user.username = result['fields']['username']\n return user\n\n def find_tasks(self, priorities=[], statuses=[]):\n \"\"\"Find tasks.\"\"\"\n params = {}\n\n for i in range(0, len(priorities)):\n params['constraints[priorities][' + str(i) + ']'] = priorities\n for i in range(0, len(statuses)):\n params['constraints[statuses][' + str(i) + ']'] = statuses\n\n result = self.api_request('maniphest.search', params)['data']\n tasks = []\n for entry in result:\n tasks.append(PhabricatorTask.fromApiResult(self, entry))\n return tasks\n\n\nclass PhabricatorTask:\n \"\"\"Class representing Phabricator task.\"\"\"\n\n def __init__(self, client):\n \"\"\"Create instance for client.\"\"\"\n self.client = client\n\n @staticmethod\n def fromApiResult(client, entry):\n \"\"\"Create instance and fill it with data from api request result.\"\"\"\n task = PhabricatorTask(client)\n task.id = entry.get('id')\n fields = entry.get('fields', {})\n task.title = fields.get('name')\n task.ownerPHID = fields.get('ownerPHID')\n task.authorPHID = fields.get('authorPHID')\n task.priority = fields.get('priority', {}).get('name')\n task.status = fields.get('status', {}).get('name')\n task.dateModified = fields.get('dateModified')\n return task\n\n @property\n def author(self):\n \"\"\"Get task author.\"\"\"\n if self.authorPHID is None:\n return None\n\n if not hasattr(self, '_author'):\n self._author = self.client.get_user(self.authorPHID)\n return self._author\n\n @property\n def owner(self):\n \"\"\"Get task owner/assignee.\"\"\"\n if self.ownerPHID is None:\n return None\n\n if not hasattr(self, '_owner'):\n self._owner = self.client.get_user(self.ownerPHID)\n return self._owner\n\n @property\n def link(self):\n \"\"\"Get link to the task.\"\"\"\n return \"https://{}/T{}\".format(self.client.host, self.id)\n\n\nclass PhabricatorUser:\n \"\"\"Class representing Phabricator user.\"\"\"\n\n def __init__(self, client):\n \"\"\"Create instance for client.\"\"\"\n self.client = client\n","sub_path":"modules/utils/phabricator.py","file_name":"phabricator.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"167700519","text":"# 30个 斐波那契数列\ndef create_fibonacci_series(length):\n \"\"\"\n 输入长度\n :return: 输出数列\n \"\"\"\n list_fibonacci = [1, 1]\n while len(list_fibonacci) < length:\n number = list_fibonacci[- 1] + list_fibonacci[- 2]\n list_fibonacci.append(number)\n return list_fibonacci\n\n\nlist01 = create_fibonacci_series(10)\nprint(list01)\n\n\n# 打印100以内质数\ndef prime_number(start=1, end=0):\n return [number for number in range(start, end) if check_prime_number(number)]\n\n\ndef check_prime_number(number):\n for item in range(2, number):\n if number % item == 0:\n return False\n return True\n\n\nprint(prime_number())\n","sub_path":"python_study/base02/tarnar02.py","file_name":"tarnar02.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"541810800","text":"import os\nfrom PIL import Image\nimport boto3\nfrom boto3.s3.transfer import S3Transfer\nimport tempfile\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('images-from')\nclient = boto3.client('s3','ap-northeast-1')\ntransfer = S3Transfer(client)\ndir_imagesfrom = tempfile.TemporaryDirectory()\ndir_imagesto = tempfile.TemporaryDirectory()\nfor obj in bucket.objects.all():\n transfer.download_file('images-from',obj.key,dir_imagesfrom.name +'\\\\'+ obj.key)\nfor filename in os.listdir(dir_imagesfrom.name):\n img = Image.open(dir_imagesfrom.name+'\\\\'+filename)\n w, h = img.size\n img.thumbnail((w//2,h//2))\n img.save(dir_imagesto.name+'\\\\'+filename)\nfor filename in os.listdir(dir_imagesto.name):\n transfer.upload_file(dir_imagesto.name +'\\\\'+ filename,'images-to',filename)\n print('uploaded:',filename)\ndir_imagesfrom.cleanup()\ndir_imagesto.cleanup()\n\n\n\n","sub_path":"image_resize/resize_use_tempfile.py","file_name":"resize_use_tempfile.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"486935260","text":"from sinric import SinricPro, SinricProConstants\nimport asyncio\n\nAPP_KEY = ''\nAPP_SECRET = ''\nSWITCH_ID = ''\n\n\ndef power_state(device_id, state):\n print('device_id: {} state: {}'.format(device_id, state))\n return True, state\n\n\ncallbacks = {\n SinricProConstants.SET_POWER_STATE: power_state\n}\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n client = SinricPro(APP_KEY, [SWITCH_ID], callbacks,\n enable_log=False, restore_states=False, secret_key=APP_SECRET)\n loop.run_until_complete(client.connect())\n\n# To update the power state on server.\n# client.event_handler.raise_event(SWITCH_ID, SinricProConstants.SET_POWER_STATE, data = {SinricProConstants.STATE: SinricProConstants.POWER_STATE_ON })\n# client.event_handler.raise_event(SWITCH_ID, SinricProConstants.SET_POWER_STATE, data = {SinricProConstants.STATE: SinricProConstants.POWER_STATE_OFF })\n","sub_path":"examples/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"654026093","text":"from django.conf.urls import url\n\n\nfrom . import views\n\nurlpatterns = [\n url(r'^layouts/$', views.layouts, name='layouts'), \n url(r'^look/(?P[0-9]+)/$', views.look, name='look'), \n url(r'^rack_item/(?P[0-9]+)/$', views.rack_item, name='rack_item'), \n url(r'^look_item/(?P[0-9]+)/$', views.look_item, name='look_item'), \n url(r'^look_list/$', views.look_list, name='look_list'), \n url(r'^user_product_favorites/(?P[0-9]+)/$', views.user_product_favorites, name='user_product_favorites'), \n url(r'^user_product_favorite/(?P[0-9]+)/$', views.user_product_favorite, name='user_product_favorite'),\n url(r'^user_look_favorites/(?P[0-9]+)/$', views.user_look_favorites, name='user_look_favorites'), \n url(r'^user_look_favorite/(?P[0-9]+)/$', views.user_look_favorite, name='user_look_favorite'),\n url(r'^client_360/(?P[0-9]+)/$', views.client_360, name='client_360'),\n url(r'^styling_session_note/(?P[0-9]+)/$', views.styling_session_note, name='styling_session_note'),\n url(r'^styling_session_notes/(?P[0-9]+)/$', views.styling_session_notes, name='styling_session_notes'),\n url(r'^look_meta_tags/(?P[0-9]+)/$', views.look_meta_tags, name='look_meta_tags'),\n url(r'^style_occasions/$', views.style_occasions, name='style_occasions'), \n url(r'^style_type/$', views.style_type, name='style_type'), \n url(r'^update_look_position/(?P[0-9]+)/$', views.update_look_position, name='update_look_position'),\n url(r'^update_look_collage_image_data/(?P[0-9]+)/$', views.update_look_collage_image_data, name='update_look_collage_image_data'),\n url(r'^update_cropped_image_code/(?P[0-9]+)/$', views.update_cropped_image_code, name='update_cropped_image_code'),\n url(r'^get_allume_size/$', views.get_allume_size, name='get_allume_size'),\n url(r'^add_client_to_360/(?P[0-9]+)/$', views.add_client_to_360_api, name='add_client_to_360_api'),\n url(r'^add_look_to_session/(?P[0-9]+)/(?P[0-9]+)/$', views.add_look_to_session, name='add_look_to_session'),\n # sold out reporting\n url(r'^report_product_inventory_mismatch_from_anna/$', views.report_product_inventory_mismatch_from_anna, name='report_product_inventory_mismatch_from_anna'),\n url(r'^report_product_inventory_mismatch/$', views.report_product_inventory_mismatch, name='report_product_inventory_mismatch'),\n # download the look_copy report\n url(r'^look_copy_report/$', views.look_copy_report, name='look_copy_report'),\n\n]\n","sub_path":"shopping_tool_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"41345400","text":"import itertools\n\nmaze = {}\nstart = None\nlocations = []\n\nx, y = 0, 0\nfor line in open('input.txt'):\n\tfor x in range(len(line.rstrip())):\n\t\tmaze[x, y] = line[x]\n\t\tif line[x] == '0':\n\t\t\tstart = (x, y)\n\t\telif line[x] not in '#.':\n\t\t\tlocations.append((x, y))\n\n\ty += 1\n\n# BFS for shortest path\ndef getShortestPath(start, end):\n\tstates = {}\n\tsteps = 0\n\tpos = start\n\tqueue = [(pos, steps)]\n\n\twhile pos != end:\n\t\tpos, steps = queue.pop(0)\n\n\t\tif pos in states:\n\t\t\tcontinue\n\n\t\tstates[pos] = steps\n\n\t\tx, y = pos\n\n\t\tfor move in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:\n\t\t\tif maze[move] != '#':\n\t\t\t\tqueue.append((move, steps + 1))\n\n\treturn steps\n\ndistances = {}\n\nfor location in locations:\n\tdistances[start, location] = getShortestPath(start, location)\n\tdistances[location, start] = distances[start, location]\n\nfor pointA, pointB in itertools.combinations(locations, 2):\n\tlength = getShortestPath(pointA, pointB)\n\n\t# store the distance in both directions for easier lookups\n\tdistances[pointA, pointB], distances[pointB, pointA] = length, length\n\nleastSteps = float('inf')\nfor path in itertools.permutations(locations, len(locations)):\n\tpath = (start,) + path + (start,)\n\tsteps = 0\n\n\tfor i in range(len(path) - 1):\n\t\tsteps += distances[path[i], path[i + 1]]\n\n\tleastSteps = min(leastSteps, steps)\n\nprint(leastSteps)\n","sub_path":"2016/day24/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"522824726","text":"n = int(input(\"Введите количество билетов:\\n\"))\nfound = 0\nfor numcount in range (n):\n tick = str(input(\"Введите номер билета/билетов:\\n\"))\n if (tick[0] == 'a') and (tick[4] == '5') and (tick[5] == '5') and (tick[6] == '6') and (tick[7] == '6') and (tick[8] == '1'):\n print(tick, end = ' ')\n break\n else:\n found += 1\nif found == n:\n print(\"-1\", end = ' ')","sub_path":"practice/16/python/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"93479505","text":"#coding=utf-8\nfun={\n \"一\":1,\n \"二\":2,\n \"三\":3,\n \"四\":4,\n \"五\":5,\n \"六\":6,\n \"七\":7,\n \"八\":8,\n \"九\":9,\n \"十\":10,\n \"十一\":11,\n \"十二\":12,\n \"十三\":13,\n \"十四\":14,\n \"十五\":15,\n \"十六\":16,\n \"十七\":17,\n \"十八\":18,\n \"十九\":19,\n \"二十\":20,\n \"二十一\":21,\n \"二十二\":22,\n \"二十三\":23,\n \"二十四\":24,\n \"二十五\":25,\n \"二十六\":26,\n \"二十七\":27,\n \"二十八\":28,\n \"二十九\":29,\n \"三十\":30,\n \"三十一\":31,\n \"三十二\":32,\n \"三十三\":33\n}\n\nimport xlrd\n#打开一个workbook\nworkbook = xlrd.open_workbook('./test.xlsx')\n#抓取所有sheet页的名称\nworksheets = workbook.sheet_names()\n#print('worksheets is %s' %worksheets)\n#定位到sheet1\nworksheet1 = workbook.sheet_by_name(u'Sheet1')\n\"\"\"\n#通过索引顺序获取\nworksheet1 = workbook.sheets()[0]\n#或\nworksheet1 = workbook.sheet_by_index(0)\n\"\"\"\n\nimport xlwt\nworkbook2 = xlwt.Workbook() #注意Workbook的开头W要大写\nsheet1 = workbook2.add_sheet('sheet1',cell_overwrite_ok=True)\n\nnum_rows = worksheet1.nrows\nfor curr_row in range(num_rows):\n row = worksheet1.row_values(curr_row)\n for index in range(len(row)):\n if(curr_row!=0 and index==1):\n sheet1.write(curr_row,index,fun[row[index]])\n else:\n sheet1.write(curr_row,index,row[index])\n\n #print(row[0],fun[row[1]],row[2])\n\nworkbook2.save('./2.xls')","sub_path":"Python/excel/xls_xlrd_xlwt.py","file_name":"xls_xlrd_xlwt.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"128325138","text":"import json\nimport requests\nimport datetime\nfrom flask import *\nfrom flask_cors import CORS\nfrom reporter.make_result import make_result\nfrom reporter.config import config\nfrom reporter.utils import logger, handle_request_exceptions\nfrom tasks import epidemic_report\n\napp_name = 'epidemic'\napp = Flask(app_name)\nCORS(app, supports_credentials=True)\nhandle_request_exceptions(app)\n\n\ndef get_apis() -> dict:\n return {\n '/': {\n \"description\": 'Index and description of the Epidemic Report API',\n 'methods': ['GET'],\n 'args': {},\n 'rets': {\n 'apis': \"Lists of API urls and args\"\n }\n },\n '/report': {\n \"description\": 'HITsz疫情上报',\n 'methods': ['GET', 'POST'],\n 'args': {\n \"username\": {\n \"description\": 'HITsz SSO登录用户名(学号)',\n \"required\": True\n },\n \"password\": {\n \"defscription\": \"HITsz SSO登录密码\",\n \"required\": True\n },\n \"api_key\": {\n \"description\": \"Server酱的SCKEY\",\n \"required\": False\n }\n }\n }\n }\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return make_result(data={\n 'description': f'HItsz-daily-reporter API v{config.data.get(\"epidemic-report-version\", None)}',\n 'apis': get_apis()\n })\n\n\n@app.route('/report/', methods=['GET', 'POST'])\ndef report():\n if request.method == 'GET':\n args = request.args\n elif request.method == 'POST':\n try:\n args = request.json\n except json.decoder.JSONDecodeError:\n return make_result(400)\n else:\n return make_result(400)\n args = json.loads(json.dumps(args))\n required = ['username', 'password']\n for r in required:\n if r not in args:\n return make_result(400, message=f'Arg {r} is required')\n is_successful, msg = epidemic_report.main(args)\n if is_successful:\n txt = f\"疫情上报成功!{datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')}\"\n else:\n txt = f\"疫情上报失败,原因:{msg}{datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')}\"\n if 'api_key' in args and not is_successful:\n requests.get(f\"https://sc.ftqq.com/{args.api_key}.send?text={txt}\")\n return make_result(code=200 if is_successful else 403, message=txt)\n","sub_path":"api/tasks/app_epidemic_report.py","file_name":"app_epidemic_report.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"360808909","text":"# !usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport requests\nimport time\nfrom lxml import etree\n\ndef get_url_json(url, headers = None):\n res = False\n while res == False:\n time.sleep(0.3)\n try:\n response = requests.get(url, headers=headers)\n res = True\n return response.json()\n except:\n print('get_url_json err,err url =', url)\n res = False\n \n\ndef get_url_html(url):\n res = False\n while res == False:\n time.sleep(0.3)\n try:\n response = requests.get(url)\n if response.status_code == 500:\n return ''\n html = etree.HTML(response.text)\n res = True\n return html\n except:\n print('get_url_html err,err url =', url)\n res = False","sub_path":"common_fun.py","file_name":"common_fun.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"385285742","text":"from node import Node, BeaconBlock, MainChainBlock, ShardCollation\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport random, time\n\n\n## This methods creates an offset for plotting blocks of the main chain,\n# the beacon chain and all the shards\n# @param b Block to be plotted\ndef mkoffset(b):\n return random.randrange(5) + \\\n (0 if isinstance(b, MainChainBlock) else\n 5 if isinstance(b, BeaconBlock) else\n 5 + 5 * b.shard_id if isinstance(b, ShardCollation) else\n None)\n\n\n## This method plots the blockchain as seen from one of the notaries\n# @param n The notarie to plot its view of the chain\ndef plotChain(n):\n G=nx.Graph()\n fileName = \"results/chain-\" + str(n.id) + \".png\"\n for b in n.blocks.values():\n if b.number > 0:\n if isinstance(b, BeaconBlock):\n G.add_edge(b.hash, b.main_chain_ref, color='c')\n G.add_edge(b.hash, b.parent_hash, color='g')\n elif isinstance(b, MainChainBlock):\n G.add_edge(b.hash, b.parent_hash, color='b')\n elif isinstance(b, ShardCollation):\n G.add_edge(b.hash, b.beacon_ref, color='r')\n G.add_edge(b.hash, b.parent_hash, color='y')\n plt.clf()\n fig = plt.figure(figsize=(18,9))\n pos={b.hash: (b.ts + mkoffset(b), b.ts) for b in n.blocks.values()}\n edges = G.edges()\n colors = [G[u][v]['color'] for u,v in edges]\n nx.draw_networkx_nodes(G, pos, node_size=10, node_shape='o', node_color='0.75')\n nx.draw_networkx_edges(G, pos, width=2, edge_color=colors)\n plt.ylabel(\"Time (ticks)\")\n plt.savefig(fileName, bbox_inches=\"tight\")\n plt.close()\n\n\n## This method plots the peer to peer network of the blockchain being\n# simulated\n# @param peers The peer to peer network to plot\n# @param dir The directory where the figure should be saved\ndef plotNetwork(peers, dir):\n plt.clf()\n G=nx.Graph()\n fig = plt.figure(figsize=(18,9))\n for peer in peers:\n G.add_node(str(peer))\n for p in peers.get(peer):\n G.add_edge(str(peer), str(p.id))\n nx.draw(G, with_labels=True)\n plt.axis(\"off\")\n plt.savefig(dir+\"/network.png\", bbox_inches=\"tight\")\n\n\n","sub_path":"lshards/src/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"616531572","text":"# section04-1\n# requests scrapping - Session\n\nimport requests\n\n# Activate Session\ns = requests.session()\n\nr = s.get('https://www.google.com')\n\n# response data\nprint(r.text)\n\n# Status 200,201,404.......\nprint('Status Code : {}'.format(r.status_code))\n\n# check True, False\nprint('OK? : {}'.format(r.ok))\n\ns = requests.session()\n\n# cookie Return\n\nr1 = s.get(\"https://httpbin.org/cookies\", cookies={'name' : 'seo1'})\nprint(r1.text)\n\n# cookie Set\nr2 = s.get(\"https://httpbin.org/cookies/set\", cookies={'name' : 'seo2'})\nprint(r2.text)\n\n\n# User-agent\nurl = \"https://httpbin.org\"\nheaders = {'user-agent' : 'niceman_1.0.0_win10_ram16_home_chrome'}\n\n# header request\nr3 = s.get(url, headers=headers, cookies={'name' : 'seo1'})\n# print(r3.text)\n\n# Deactivate Session\ns.close()\n\n# with -> File, DB, HTTP\nwith requests.session() as s:\n r = s.get('https://www.google.com')\n # print(r.text)\n print(r.ok)\n\n\n\n","sub_path":"section04-1.py","file_name":"section04-1.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"507616798","text":"# Create a class the displays the Elevator art and navigation (list of commands)\n\nclass View():\n building_levels = 12\n building_width = 35\n\n def intro(self, position, people):\n print(\"\\n----- THE MIGHTY ELEVATOR -----\\n\")\n print(\"People in the elevator: {} (max. 5)\\nElevator position: {}\\n\".format(people, position))\n print(self.draw_top())\n print(self.draw_levels(position, people))\n print(self.draw_bottom())\n print(self.nav())\n print(\"\\nWhat would you like to do?\")\n\n def draw_top(self):\n top1 = \"\"\n for i in range(self.building_width):\n top1 += \"_\"\n top2 = \"'\"\n for j in range(1, self.building_width-1):\n top2 += \" \"\n top2 += \"'\"\n top3 = \" '\"\n for i in range(2, self.building_width-2):\n top3 += \"_\"\n top3 += \"'\"\n return top1 + \"\\n\" + top2 + \"\\n\" + top3\n\n def draw_levels(self, position, people):\n levels = \"\"\n for i in range(self.building_levels, 0, -1):\n if i == 1 and position != 1:\n levels += \" \"*2 + \"_\" + \"||_\"*2 + \"_\"*6 + \"||_\"*2 + \"_\"*6 + \"||_\"*2\n elif i == position and position != 1:\n levels += self.draw_elevator(position, people)\n elif i == position and position == 1:\n levels += self.draw_elevator(position, people)\n else:\n levels += \" \"*3 + \"|| \"*2 + \" \"*6 + \"|| \"*2 + \" \"*6 + \"|| \"*2 + \"\\n\"\n return levels\n\n def draw_bottom(self):\n line2 = \"'\"\n for j in range(1, self.building_width-1):\n line2 += \" \"\n line2 += \"'\"\n line3 = \"|\"\n for i in range(1, self.building_width-1):\n line3 += \"_\"\n line3 += \"|\"\n return line2 + \"\\n\" + line3\n\n def draw_elevator(self, position, people):\n elevator = \"\"\n if position != 1 and people == 0:\n elevator += \" \"*3 + \"|| \"*2 + \"[ ] \" + \"|| \"*2 + \" \"*6 + \"|| \"*2 + \"\\n\"\n elif position == 1 and people == 0:\n elevator += \" \"*2 + \"_\" + \"||_\"*2 + \"[___]_\" + \"||_\"*2 + \"_\"*6 + \"||_\"*2\n elif position != 1 and people > 0:\n elevator += \" \"*3 + \"|| \"*2 + \"[ X ] \" + \"|| \"*2 + \" \"*6 + \"|| \"*2 + \"\\n\"\n elif position == 1 and people > 0:\n elevator += \" \"*2 + \"_\" + \"||_\"*2 + \"[_X_]_\" + \"||_\"*2 + \"_\"*6 + \"||_\"*2\n return elevator\n\n def nav(self):\n return(\"\\n---- CONTROLS ----\\n\\nto X - enter a number to move to floor\\nin X - enter a number to add people to the elevator\\nout X - enter a number to remove people from the elevator\\nexit - exit the application\")\n\n def invalid_command(self):\n print(\"Please enter a valid command.\")\n print(\"\\nPress a button to refresh!\")\n user_error = input()\n\n#newele = View()\n#print(newele.draw_top())\n#print(newele.draw_levels(1, 1))\n#print(newele.draw_bottom())\n#print(newele.nav())\n","sub_path":"week-05/day-04/elevator/elevator_view.py","file_name":"elevator_view.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"511491581","text":"#!/usr/bin/env python3\n#coding: utf-8\n\nimport rospy\nfrom std_msgs.msg import String\nfrom nav_msgs.msg import Odometry\nfrom cmoon_msgs.msg import location\n\n\ndef callback(msg):\n rospy.loginfo('callback')\n ll=location()\n ll.location='living room'\n ll.x=1.0\n ll.y=2.0\n pub=rospy.Publisher('location',location,queue_size=10)\n pub.publish(ll)\n rospy.loginfo('location:{} x:{} y{}'.format(ll.location,ll.x,ll.y))\n\ndef main():\n rospy.init_node('test1')\n rospy.Subscriber('/odom',Odometry,callback)\n # pub=rospy.Publisher('location',location,queue_size=10)\n # ll=location()\n # ll.location='living room'\n # ll.x=1.0\n # ll.y=2.0\n # rate=rospy.Rate(1)\n # while not rospy.is_shutdown():\n # pub.publish(ll)\n # rospy.loginfo('location:{} x:{} y{}'.format(ll.location,ll.x,ll.y))\n # rate.sleep()\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n rospy.loginfo(\"Keyboard interrupt.\")","sub_path":"src/remake/src/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"372108632","text":"import os\nimport source\n\n\n# --- 3.4.1 Ensure TCP Wrappers is installed (Scored) ---#\n\ndef check_tcp_wrappers_is_installed():\n config = 'Ensure TCP Wrappers is installed (Scored)'\n\n command1 = 'rpm -q tcp_wrappers'\n command2 = 'rpm -q tcp_wrappers-libs'\n output = 'not installed'\n\n print('checking \"' + config + '\" ..... ')\n\n terminal_variable = os.popen(command1)\n terminal_output1 = terminal_variable.read()\n\n terminal_variable = os.popen(command2)\n terminal_output2 = terminal_variable.read()\n\n if output in terminal_output1 and output in terminal_output2:\n source.return_function(False, config)\n else:\n source.return_function(True, config)\n\n\n# --- 3.4.3 Ensure /etc/hosts.deny is configured (Scored) ---- #\n\ndef check_etc_hosts_deny_is_configured():\n config = '3.4.3 Ensure /etc/hosts.deny is configured (Scored)'\n command = 'cat /etc/hosts.deny'\n output = 'ALL: ALL'\n source.output_isIn_terminal_output(config, command, output)\n\n\n# ---- 3.4.4 Ensure permissions on /etc/hosts.allow are configured (Scored) ---#\n\ndef check_permissions_on_etc_hosts_allow_isConfigured():\n config = '3.4.4 Ensure permissions on /etc/hosts.allow are configured (Scored)'\n command = 'stat /etc/hosts.allow'\n output = 'Access:(0644/-rw-r--r--)Uid:(0/root)Gid:(0/root)'\n\n print('checking \"' + config + '\" ..... ')\n terminal_variable = os.popen(command)\n terminal_output = terminal_variable.read().replace(' ', '')\n\n if output in terminal_output:\n source.return_function(True, config)\n else:\n source.return_function(False, config)\n\n\n# ---- 3.4.4 Ensure permissions on /etc/hosts.deny are configured (Scored) ---#\n\ndef check_permissions_on_etc_hosts_deny_isConfigured():\n config = '3.4.5 Ensure permissions on /etc/hosts.deny are configured (Scored)'\n command = 'stat /etc/hosts.allow'\n output = 'Access:(0644/-rw-r--r--)Uid:(0/root)Gid:(0/root)'\n\n print('checking \"' + config + '\" ..... ')\n terminal_variable = os.popen(command)\n terminal_output = terminal_variable.read().replace(' ', '')\n\n if output in terminal_output:\n source.return_function(True, config)\n\n else:\n source.return_function(False, config)\n","sub_path":"networkConfiguration/tcpWrappers.py","file_name":"tcpWrappers.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"226834471","text":"\"\"\"\nconclusions.py\n\n* Copyright (c) 2006-2009, University of Colorado.\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 met:\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in the\n* documentation and/or other materials provided with the distribution.\n* * Neither the name of the University of Colorado nor the\n* names of its contributors may be used to endorse or promote products\n* derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF COLORADO ''AS IS'' AND ANY\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF COLORADO BE LIABLE FOR ANY\n* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\n#import confidence\nimport samples\n\n__ALL_SAMPLES = 0\n\ncurState = 0\n\nconclusions = [\"no process\", ]\nspecial = {\"outlier\":__ALL_SAMPLES}\n \ndef reset():\n \"\"\"\n Resets the conclusion state for starting up a new set of samples.\n Call this in between each thingymajig\n \"\"\"\n global curState\n curState = 0\n\ndef getConclusions():\n \"\"\"\n this function returns the list of conclusions that the engine should argue about. All\n parameters should be pre-entered.\n \"\"\"\n \n #can't do this with a list comprehension. Sigh.\n result = []\n for conclusion in conclusions:\n if conclusion in special:\n result.extend(__fillParams(conclusion))\n else:\n result.append(Conclusion(conclusion))\n \n return result\n\n \ndef __fillParams(conclusion):\n \"\"\"\n fills in parameters for conclusions and then returns the appropriate list of conclusion objects \n based on the type ID passed in.\n \"\"\"\n \n #conclusions should never be passed here anymore unless they're special ones\n \n if special[conclusion] == __ALL_SAMPLES:\n return [Conclusion(conclusion, [sample]) for sample in samples.sampleList]\n\nclass Conclusion:\n \"\"\"\n Contains the symbol (name) of a specific instance of a conclusion plus the list of arguments\n applicable to this specific conclusion (like outlier x).\n \n Also represents the same thing but with arguments filled in (like outlier 2)\n \"\"\"\n def __init__(self, name, paramList=None):\n self.name = name\n self.paramList = paramList\n if paramList is not None and len(paramList) == 0:\n self.paramList = None\n \n def __eq__(self, other):\n if isinstance(other, Conclusion):\n return self.name == other.name and \\\n (self.paramList is None and other.paramList is None or \\\n (self.paramList is not None and other.paramList is not None and\n len(self.paramList) == len(other.paramList)))\n else:\n return False\n \n def __repr__(self):\n st = self.name.title()\n if self.paramList is not None:\n st += ': ' + ', '.join([str(param) for param in self.paramList]) #+ ')'\n return st\n \n def buildEnv(self, filledConc):\n \"\"\"\n builds an initial environment from this conclusion and a filled version of the\n same conclusion (passed as a parameter). Initial environment values are also\n included in the result. Environments are dictionaries.\n \"\"\"\n \n if self.paramList is None and filledConc.paramList is None:\n return samples.initEnv.copy()\n \n if self.paramList is None or \\\n filledConc.paramList is None or \\\n len(filledConc.paramList) != len(self.paramList):\n raise ValueError(\"Attempt to use a rule with incorrect number of conclusion parameters\")\n \n env = dict(zip(self.paramList, filledConc.paramList))\n \n env.update(samples.initEnv)\n \n #if self.name == 'representative sample' or self.name == 'outlier':\n # print self, env\n return env\n \n \n\n \n","sub_path":"src/calvin/reasoning/conclusions.py","file_name":"conclusions.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"323259197","text":"# Copyright (c) str4d \n# See COPYING for details.\n\nimport unittest\n\nfrom parsley import makeGrammar, ParseError\n\nfrom txi2p.grammar import bobGrammarSource\n\n\nbobGrammar = makeGrammar(bobGrammarSource, {})\n\ndef stringParserFromRule(grammar, rule):\n def parseString(s):\n return getattr(grammar(s), rule)()\n return parseString\n\n\nclass TestBOBGrammar(unittest.TestCase):\n def _test(self, rule, data, expected):\n parse = stringParserFromRule(bobGrammar, rule)\n result = parse(data)\n self.assertEqual(result, expected)\n\n def test_BOB_clear(self):\n self._test('BOB_clear', 'OK cleared\\n', (True, 'cleared'))\n self._test('BOB_clear', 'ERROR tunnel is active\\n', (False, 'tunnel is active'))\n\n def test_BOB_getdest(self):\n self._test('BOB_getdest', 'OK spam\\n', (True, 'spam'))\n\n def test_BOB_getkeys(self):\n self._test('BOB_getkeys', 'OK spameggs\\n', (True, 'spameggs'))\n\n def test_BOB_list(self):\n spam = {\n 'nickname': 'spam',\n 'starting': False,\n 'running': True,\n 'stopping': False,\n 'keys': True,\n 'quiet': False,\n 'inport': '12345',\n 'inhost': 'localhost',\n 'outport': '23456',\n 'outhost': 'localhost'\n }\n eggs = {\n 'nickname': 'eggs',\n 'starting': False,\n 'running': False,\n 'stopping': False,\n 'keys': True,\n 'quiet': False,\n 'inport': 'not_set',\n 'inhost': 'localhost',\n 'outport': 'not_set',\n 'outhost': 'localhost'\n }\n\n self._test('BOB_list', 'OK Listing done\\n', (True, 'Listing done', []))\n self._test('BOB_list', 'DATA NICKNAME: spam STARTING: false RUNNING: true STOPPING: false KEYS: true QUIET: false INPORT: 12345 INHOST: localhost OUTPORT: 23456 OUTHOST: localhost\\nDATA NICKNAME: eggs STARTING: false RUNNING: false STOPPING: false KEYS: true QUIET: false INPORT: not_set INHOST: localhost OUTPORT: not_set OUTHOST: localhost\\nOK Listing done\\n', (True, 'Listing done', [spam, eggs]))\n self._test('BOB_list', 'ERROR ni!\\n', (False, 'ni!', []))\n","sub_path":"txi2p/test/test_grammar.py","file_name":"test_grammar.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"376555368","text":"import torch\nimport math\n\n\ndef estimate_entropies(qz_samples, qz_params, q_dist):\n \"\"\"Computes the term:\n E_{p(x)} E_{q(z|x)} [-log q(z)]\n and\n E_{p(x)} E_{q(z_j|x)} [-log q(z_j)]\n where q(z) = 1/N sum_n=1^N q(z|x_n).\n\n Assumes samples are from q(z|x) for *all* x in the dataset.\n Assumes that q(z|x) is factorial ie. q(z|x) = prod_j q(z_j|x).\n\n Computes numerically stable NLL:\n - log q(z) = log N - logsumexp_n=1^N log q(z|x_n)\n\n Inputs:\n -------\n qz_samples (K, S) Variable\n qz_params (N, K, nparams) Variable\n \"\"\"\n\n # Only take a sample subset of the samples\n qz_samples = qz_samples.index_select(1, Variable(torch.randperm(qz_samples.size(1))[:10000].cuda()))\n\n K, S = qz_samples.size()\n N, _, nparams = qz_params.size()\n assert(nparams == q_dist.nparams)\n assert(K == qz_params.size(1))\n\n marginal_entropies = torch.zeros(K).cuda()\n joint_entropy = torch.zeros(1).cuda()\n\n pbar = tqdm(total=S)\n k = 0\n while k < S:\n batch_size = min(10, S - k)\n logqz_i = q_dist.log_density(\n qz_samples.view(1, K, S).expand(N, K, S)[:, :, k:k + batch_size],\n qz_params.view(N, K, 1, nparams).expand(N, K, S, nparams)[:, :, k:k + batch_size])\n k += batch_size\n\n # computes - log q(z_i) summed over minibatch\n marginal_entropies += (math.log(N) - logsumexp(logqz_i, dim=0, keepdim=False).data).sum(1)\n # computes - log q(z) summed over minibatch\n logqz = logqz_i.sum(1) # (N, S)\n joint_entropy += (math.log(N) - logsumexp(logqz, dim=0, keepdim=False).data).sum(0)\n pbar.update(batch_size)\n pbar.close()\n\n marginal_entropies /= S\n joint_entropy /= S\n\n return marginal_entropies, joint_entropy\n\n\ndef elbo_decomposition(z_dim, nparams, dataset_loader):\n n = len(dataset_loader.dataset)\n S = 1\n\n print('Computing q(z|x) distributions.')\n # compute the marginal q(z_j|x_n) distributions\n qz_params = torch.Tensor(n, z_dim, nparams)\n\n n = 0\n logpx = 0\n\n for xs in dataset_loader:\n batch_sz = xs.size(0)\n xs = Variable(xs.view(batch_size, -1, 64, 64).cuda(), volatile=True)\n z_params = vae.encoder.forward(xs).view(batch_size, K, nparams)\n qz_params[n:n + batch_size] = z_params.data\n n += batch_size\n\n # estimate reconstruction term\n for _ in range(S):\n z = vae.q_dist.sample(params=z_params)\n x_params = vae.decoder.forward(z)\n logpx += vae.x_dist.log_density(xs, params=x_params).view(batch_size, -1).data.sum()\n\n logpx = logpx / (N * S)\n\n qz_params = Variable(qz_params.cuda(), volatile=True)\n\n print('Sampling from q(z).')\n # sample S times from each marginal q(z_j|x_n)\n qz_params_expanded = qz_params.view(N, K, 1, nparams).expand(N, K, S, nparams)\n qz_samples = vae.q_dist.sample(params=qz_params_expanded)\n qz_samples = qz_samples.transpose(0, 1).contiguous().view(K, N * S)\n\n print('Estimating entropies.')\n marginal_entropies, joint_entropy = estimate_entropies(qz_samples, qz_params, vae.q_dist)\n\n if hasattr(vae.q_dist, 'NLL'):\n nlogqz_condx = vae.q_dist.NLL(qz_params).mean(0)\n else:\n nlogqz_condx = - vae.q_dist.log_density(qz_samples,\n qz_params_expanded.transpose(0, 1).contiguous().view(K, N * S)).mean(1)\n\n if hasattr(vae.prior_dist, 'NLL'):\n pz_params = vae._get_prior_params(N * K).contiguous().view(N, K, -1)\n nlogpz = vae.prior_dist.NLL(pz_params, qz_params).mean(0)\n else:\n nlogpz = - vae.prior_dist.log_density(qz_samples.transpose(0, 1)).mean(0)\n\n # nlogqz_condx, nlogpz = analytical_NLL(qz_params, vae.q_dist, vae.prior_dist)\n nlogqz_condx = nlogqz_condx.data\n nlogpz = nlogpz.data\n\n # Independence term\n # KL(q(z)||prod_j q(z_j)) = log q(z) - sum_j log q(z_j)\n dependence = (- joint_entropy + marginal_entropies.sum())[0]\n\n # Information term\n # KL(q(z|x)||q(z)) = log q(z|x) - log q(z)\n information = (- nlogqz_condx.sum() + joint_entropy)[0]\n\n # Dimension-wise KL term\n # sum_j KL(q(z_j)||p(z_j)) = sum_j (log q(z_j) - log p(z_j))\n dimwise_kl = (- marginal_entropies + nlogpz).sum()\n\n # Compute sum of terms analytically\n # KL(q(z|x)||p(z)) = log q(z|x) - log p(z)\n analytical_cond_kl = (- nlogqz_condx + nlogpz).sum()\n\n print('Dependence: {}'.format(dependence))\n print('Information: {}'.format(information))\n print('Dimension-wise KL: {}'.format(dimwise_kl))\n print('Analytical E_p(x)[ KL(q(z|x)||p(z)) ]: {}'.format(analytical_cond_kl))\n print('Estimated ELBO: {}'.format(logpx - analytical_cond_kl))\n\n return logpx, dependence, information, dimwise_kl, analytical_cond_kl, marginal_entropies, joint_entropy\n\n\nif __name__ == '__main__':\n\n vae, dataset_loader = load_model_and_dataset(args.checkpt)\n logpx, dependence, information, dimwise_kl, analytical_cond_kl, marginal_entropies, joint_entropy = \\\n elbo_decomposition(vae, dataset_loader)\n torch.save({\n 'logpx': logpx,\n 'dependence': dependence,\n 'information': information,\n 'dimwise_kl': dimwise_kl,\n 'analytical_cond_kl': analytical_cond_kl,\n 'marginal_entropies': marginal_entropies,\n 'joint_entropy': joint_entropy\n }, os.path.join(args.save, 'elbo_decomposition.pth'))\n","sub_path":"elbo_evaluation.py","file_name":"elbo_evaluation.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"605747860","text":"#!usr/bin/python\nimport sys\nfrom os import path\nimport numpy as np\n\nfrom convolver import EyeCoord, GaborFunc, ImgToBinSpectrum, HammingDist, FitToRange255, LogGaborFunc\nfrom PIL import Image\nfrom multiprocessing import Pool\n\nimport cProfile\n\ndef get_data_dict(data_path, imgs_path):\n\tres_dict = dict()\n\twith open(data_path, 'r') as data_file:\n\t\ti = 0\n\t\tk = 0\n\t\tfor line in data_file:\n\t\t\tline_items = line.split()\n\t\t\timg_name = line_items[0]\n\t\t\tk += 1\n\t\t\tif path.exists(imgs_path + '/' + img_name):\n\t\t\t\ti += 1\n\t\t\t\tres_dict[img_name] = EyeCoord(\tx1=np.array([int(i) for i in line_items[6:8]]),\n\t\t\t\t\t\t\t\t\t\t\t\tr1=int(line_items[8]),\n\t\t\t\t\t\t\t\t\t\t\t\tx2=np.array([int(i) for i in line_items[11:13]]),\n\t\t\t\t\t\t\t\t\t\t\t\tr2=int(line_items[13]))\n\tprint(i, k)\n\treturn res_dict\n\n\ndef is_test_img(name):\n#\treturn 1\n\treturn int(name[:4]) in range(2001, 2151)\n\t#return 'R' in name and int(name[:4]) in range(2001, 2151)\n\t#return 'L' in name and int(name[:4]) in range(2001, 2151)\n\n\ndef ImageSpectrum(arg_tuple):\n\teye_name, eye_coord, imgs_path = arg_tuple\n\tspectr_size = (256, 64)\n\tsigma = 17\n\tT = 8\n\timg_path = imgs_path + '/' + eye_name\n\treturn ImgToBinSpectrum(img_path, eye_coord, spectr_size, LogGaborFunc, S=1/sigma, W=1/T)\n\t#return ImgToBinSpectrum(img_path, eye_coord, spectr_size, GaborFunc, S=1/sigma, W=1/T)\n\ndef HammDistMatrix(imgs_path, imgs_dict):\n\tdist_same = []\n\tdist_diff = []\n\t\n\timg_to_idx = dict()\n\tidx_to_img = dict()\n\tpool = Pool(4)\n\n\tfor idx, (eye_name, _) in enumerate(imgs_dict.items()):\n\t\timg_to_idx[eye_name] = idx\n\t\tidx_to_img[idx] = eye_name\n\n\targ_tuples = list(zip(imgs_dict.keys(), imgs_dict.values(), [imgs_path] * len(imgs_dict)))\n\n\tspectrums = pool.map(ImageSpectrum, arg_tuples)\n\n\tassert len(imgs_dict) == len(spectrums)\n\timg_to_spectrum = dict(zip(imgs_dict.keys(), spectrums))\n\n\tfor x in range(len(imgs_dict)):\n\t\tspectr_x = img_to_spectrum[idx_to_img[x]]\n\t\tfor y in range(x + 1, len(imgs_dict)):\n\t\t\tspectr_y = img_to_spectrum[idx_to_img[y]]\n\n\t\t\tdist = HammingDist(spectr_x, spectr_y)\n\t\t\tprint(dist)\n\t\t\t#Image.fromarray(FitToRange255(spectr_x).T, 'L').save('./tmp/spectr_' + idx_to_img[x])\n\t\t\tif idx_to_img[y][:5] == idx_to_img[x][:5]:\n\t\t\t\tdist_same.append(dist)\n\t\t\t\t#print('same', idx_to_img[y], idx_to_img[x], '->', dist)\n\t\t\telse:\n\t\t\t\tdist_diff.append(dist)\n\t\t\t\t#print('diff', idx_to_img[y], idx_to_img[x], '->', dist)\n\n\treturn dist_same, dist_diff\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) < 3:\n\t\tprint('Not enough args')\n\t\tsys.exit(1)\n\n\n#\ttry:\n\n\tdata_path = sys.argv[1]\n\timgs_path = sys.argv[2]\n\n\tdata_dict = get_data_dict(data_path, imgs_path)\n\tprint(len(data_dict))\n\ttest_set = dict((key,value) for key, value in data_dict.items() if is_test_img(key))\n\tprint(len(test_set))\n\n\t#cProfile.run('HammDistMatrix(imgs_path, dict(list(test_set.items())[:50]))')\n\tsame, diff = HammDistMatrix(imgs_path, test_set)\n\tf = open('same.txt', 'w')\n\tf.write(' '.join([str(int(j)) for j in same]))\n\tf.close()\n\tf = open('diff.txt', 'w')\n\tf.write(' '.join([str(i) for i in list(diff)]))\n\tf.close()\n\n#\texcept Exception as e:\n#\t\tprint(e)\n#\t\tsys.exit(1)","sub_path":"img_data.py","file_name":"img_data.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"205930412","text":"import pickle\nfrom helper.Reynolds import *\nfrom helper.MRSAnalytics import *\nfrom helper.Plotter import *\nfrom helper.Trainer import *\nfrom helper.DataGenerator import *\nfrom torch.distributions import *\nfrom mrsgym.Util import *\nimport os\nfrom matplotlib import pyplot as plt\n\n\n\ndef main():\n\t# Parameters\n\tN = 12\n\tD = 6\n\tK = 1\n\tCOMM_RANGE = 2.5\n\tdatapoints = 1000\n\tepisode_length = 200\n\theadless = True\n\tleader = True\n\t# File Paths\n\tdir_path = \"data\"\n\tevaldata_path = os.path.join(dir_path, \"%s_data.pt\")\n\ttry:\n\t\tos.mkdir(dir_path)\n\texcept FileExistsError:\n\t\tpass\n\t# Initialise Models\n\treynolds = Reynolds(N, D, 1, 3)\n\tmodels = {\"reynolds\": reynolds, \"random\": RandomController(OUT_DIM=3)} # we will compare reynolds flocking to a random model\n\t# Create Environment\n\tz = Uniform(low=2.0*torch.ones(N,1), high=5.0*torch.ones(N,1))\n\txy_normal = Normal(torch.zeros(N,2), 1.0)\n\tdist = CombinedDistribution([xy_normal, z], mixer='cat', dim=1) # create custom starting state distribution\n\tenv = gym.make('mrs-v0', state_fn=state_fn, update_fn=update_fn, N_AGENTS=N, START_POS=dist, K_HOPS=1, COMM_RANGE=COMM_RANGE, ACTION_TYPE='set_target_vel', HEADLESS=headless)\n\tstartpos = [env.generate_start_pos() for _ in range(int(datapoints/episode_length*2))]\n\tenv.START_POS = StartPosGenerator(startpos) # use the same starting state for each model\n\t# Generate and Analyse Data\n\tanalysers = {}\n\tfor name, model in models.items():\n\t\tprint(name)\n\t\tdata = Trainer(K=K)\n\t\tis_data_loaded = data.load_trainer(path=evaldata_path % name) # load simulation data if it exists\n\t\tif not is_data_loaded: # generate data if it does not exist\n\t\t\tdata.save_trainer_onexit(path=evaldata_path % name)\n\t\t\tsimulate(env=env, model=model, trainer=data, datapoints=datapoints, episode_length=episode_length, leader=leader)\n\t\tanalysers[name] = MRSAnalytics(data) # compute flocking metrics (separation, cohesion, leader dist)\n\t\tanalysers[name].name = name\n\t# Draw Plots\n\tplot_separation(*analysers.values())\n\tplot_cohesion(*analysers.values())\n\tplot_leader_dist(*analysers.values())\n\t# Show\n\tshow_plots()\n\n\n\ndef state_fn(quad):\n\treturn torch.cat([quad.get_pos(), quad.get_vel()])\n\ndef update_fn(env, action, **kwargs):\n\tfor i, agent in enumerate(env.agents):\n\t\tenv.add_line(start=[0.,0.,0.], end=action[i,:], parent=agent, name=\"line_%d\" % i, colour=[0.,0.,1.])\n\ndef simulate(env, model, leader=False, **kwargs):\n\tif leader:\n\t\tleader_action_policy = RandomAction()\n\t\taction_fn = leader_action_policy.action_fn\n\t\tenvironment = env.get_env()\n\t\tleader_agent = environment.agents[0]\n\t\tenvironment.set_colour(leader_agent, [1.,0.,0.])\n\telse:\n\t\taction_fn = lambda action, state: action\n\tenv.START_POS.reset()\n\tdata = generate_mrs(env, model=model, action_fn=action_fn, **kwargs)\n\treturn data\n\ndef plot_separation(*analysers):\n\tseparations = [analyser.separation().permute(0,2,1).reshape(analyser.N*analyser.num_episodes, analyser.episode_length) for analyser in analysers]\n\tnames = [analyser.name for analyser in analysers]\n\tplot_time_distribution(data=separations, labels=names, xlabel=\"Time Step\", ylabel=\"Separation from Nearest Neighbor\", title=\"\", ignorenan=True)\n\tfor name, separation in zip(names, separations):\n\t\tsep = separation.reshape(-1)\n\t\tmean = mean_ignorenan(sep.unsqueeze(1))[0]\n\t\tmedian = median_ignorenan(sep.unsqueeze(1))[0]\n\t\tstd = std_ignorenan(sep.unsqueeze(1))[0]\n\t\tprint(\"%s Separation: median=%g, mean=%g, std=%g\" % (name, median, mean, std))\n\ndef plot_cohesion(*analysers):\n\tcohesions = [analyser.cohesion() for analyser in analysers]\n\tnames = [analyser.name for analyser in analysers]\n\tplot_time_distribution(data=cohesions, labels=names, xlabel=\"Time Step\", ylabel=\"Diameter of Smallest Sphere that Contains all Agents\", title=\"\", ignorenan=True)\n\tfor name, cohesion in zip(names, cohesions):\n\t\tcoh = cohesion.reshape(-1)\n\t\tmean = mean_ignorenan(coh.unsqueeze(1))[0]\n\t\tmedian = median_ignorenan(coh.unsqueeze(1))[0]\n\t\tstd = std_ignorenan(coh.unsqueeze(1))[0]\n\t\tprint(\"%s Cohesion: median=%g, mean=%g, std=%g\" % (name, median, mean, std))\n\ndef plot_leader_dist(*analysers):\n\tdists = [analyser.dist_to_leader() for analyser in analysers]\n\tnames = [analyser.name for analyser in analysers]\n\tplot_time_distribution(data=dists, labels=names, xlabel=\"Time Step\", ylabel=\"Distance from the Center of the Swarm to the Leader\", title=\"\", ignorenan=True)\n\tfor name, dist in zip(names, dists):\n\t\tleader_dist = dist.reshape(-1)\n\t\tmean = mean_ignorenan(leader_dist.unsqueeze(1))[0]\n\t\tmedian = median_ignorenan(leader_dist.unsqueeze(1))[0]\n\t\tstd = std_ignorenan(leader_dist.unsqueeze(1))[0]\n\t\tprint(\"%s Leader Dist: median=%g, mean=%g, std=%g\" % (name, median, mean, std))\n\ndef loss_fn(output, target):\n\tloss = torch.nn.MSELoss()(output, target.double())\n\tloss_dict = {\"Loss\": loss}\n\treturn loss_dict\n\n# Generates an off-policy random action (used for creating a leader)\nclass RandomAction:\n\n\tdef __init__(self):\n\t\ttorch.manual_seed(0)\n\t\tself.target_vel = torch.zeros(3)\n\t\tself.sigma = 0.05\n\t\tself.maxspeed = 1.0\n\t\tself.dist = Normal(self.target_vel, self.sigma)\n\n\tdef action_fn(self, action, state):\n\t\t# Update target_vel\n\t\tself.dist = Normal(self.target_vel, self.sigma)\n\t\tself.target_vel = self.dist.sample()\n\t\tmag = self.target_vel.norm()\n\t\tself.target_vel *= self.maxspeed / max(mag, self.maxspeed)\n\t\t# Set Leader Velocity\n\t\taction[0,:] = self.target_vel\n\t\treturn action\n\n# Stores the starting states in simulation so they can be reused with other models for consistency\nclass StartPosGenerator:\n\n\tdef __init__(self, pos_list):\n\t\tself.pos_list = pos_list\n\t\tself.i = 0\n\n\tdef sample(self):\n\t\tstartpos = self.pos_list[self.i]\n\t\tself.i += 1\n\t\treturn startpos\n\n\tdef reset(self):\n\t\tself.i = 0\n\n# Random model\nclass RandomController:\n\n\tdef __init__(self, OUT_DIM):\n\t\tself.OUT_DIM = OUT_DIM\n\n\tdef forward(self, A, X):\n\t\tbatch, N, D, K = X.shape\n\t\treturn torch.randn(batch, N, self.OUT_DIM)\n\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"examples/simulating_data/analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"249747793","text":"\"\"\"MobileNet v2 models for Keras.\n# Reference\n- [Inverted Residuals and Linear Bottlenecks Mobile Networks for\n Classification, Detection and Segmentation]\n (https://arxiv.org/abs/1801.04381)\n\"\"\"\n\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input, Conv2D, GlobalAveragePooling2D, Dropout, Flatten\nfrom keras.layers import Activation, BatchNormalization, add, Reshape, Dense\nfrom keras.applications.mobilenet import relu6, DepthwiseConv2D\nfrom keras.utils.vis_utils import plot_model\nfrom keras.applications import mobilenet\n\nfrom keras import backend as K\n\n\ndef _conv_block(inputs, filters, kernel, strides):\n \"\"\"Convolution Block\n This function defines a 2D convolution operation with BN and relu6.\n # Arguments\n inputs: Tensor, input tensor of conv layer.\n filters: Integer, the dimensionality of the output space.\n kernel: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n # Returns\n Output tensor.\n \"\"\"\n\n channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n x = Conv2D(filters, kernel, padding='same', strides=strides)(inputs)\n x = BatchNormalization(axis=channel_axis)(x)\n return Activation(relu6)(x)\n\n\ndef _bottleneck(inputs, filters, kernel, t, s, r=False):\n \"\"\"Bottleneck\n This function defines a basic bottleneck structure.\n # Arguments\n inputs: Tensor, input tensor of conv layer.\n filters: Integer, the dimensionality of the output space.\n kernel: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n t: Integer, expansion factor.\n t is always applied to the input size.\n s: An integer or tuple/list of 2 integers,specifying the strides\n of the convolution along the width and height.Can be a single\n integer to specify the same value for all spatial dimensions.\n r: Boolean, Whether to use the residuals.\n # Returns\n Output tensor.\n \"\"\"\n\n channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n tchannel = K.int_shape(inputs)[channel_axis] * t\n\n x = _conv_block(inputs, tchannel, (1, 1), (1, 1))\n\n x = DepthwiseConv2D(kernel, strides=(s, s), depth_multiplier=1, padding='same')(x)\n x = BatchNormalization(axis=channel_axis)(x)\n x = Activation(relu6)(x)\n\n x = Conv2D(filters, (1, 1), strides=(1, 1), padding='same')(x)\n x = BatchNormalization(axis=channel_axis)(x)\n\n if r:\n x = add([x, inputs])\n return x\n\n\ndef _inverted_residual_block(inputs, filters, kernel, t, strides, n):\n \"\"\"Inverted Residual Block\n This function defines a sequence of 1 or more identical layers.\n # Arguments\n inputs: Tensor, input tensor of conv layer.\n filters: Integer, the dimensionality of the output space.\n kernel: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n t: Integer, expansion factor.\n t is always applied to the input size.\n s: An integer or tuple/list of 2 integers,specifying the strides\n of the convolution along the width and height.Can be a single\n integer to specify the same value for all spatial dimensions.\n n: Integer, layer repeat times.\n # Returns\n Output tensor.\n \"\"\"\n\n x = _bottleneck(inputs, filters, kernel, t, strides)\n\n for i in range(1, n):\n x = _bottleneck(x, filters, kernel, t, 1, True)\n\n return x\n\n\ndef MobileNetv2(input_shape, k):\n \"\"\"MobileNetv2\n This function defines a MobileNetv2 architectures.\n # Arguments\n input_shape: An integer or tuple/list of 3 integers, shape\n of input tensor.\n k: Integer, number of classes.\n # Returns\n MobileNetv2 model.\n \"\"\"\n\n # inputs = Input(shape=input_shape)\n # x = _conv_block(inputs, 32, (3, 3), strides=(2, 2))\n #\n # x = _inverted_residual_block(x, 16, (3, 3), t=1, strides=1, n=1)\n # x = _inverted_residual_block(x, 24, (3, 3), t=6, strides=2, n=2)\n # x = _inverted_residual_block(x, 32, (3, 3), t=6, strides=2, n=3)\n # x = _inverted_residual_block(x, 64, (3, 3), t=6, strides=2, n=4)\n # x = _inverted_residual_block(x, 96, (3, 3), t=6, strides=1, n=3)\n # x = _inverted_residual_block(x, 160, (3, 3), t=6, strides=2, n=3)\n # x = _inverted_residual_block(x, 320, (3, 3), t=6, strides=1, n=1)\n #\n # x = _conv_block(x, 1280, (1, 1), strides=(1, 1))\n # x = GlobalAveragePooling2D()(x)\n # x = Reshape((1, 1, 1280))(x)\n # x = Dropout(0.3, name='Dropout')(x)\n # x = Conv2D(k, (1, 1), padding='same')(x)\n #\n # x = Activation('softmax', name='softmax')(x)\n # output = Reshape((k,))(x)\n #\n # model = Model(inputs, output)\n # plot_model(model, to_file='images/MobileNetv2.png', show_shapes=True)\n\n # model = Sequential()\n # mob = mobilenet.MobileNet(input_shape=input_shape, alpha=1.0, depth_multiplier=1, dropout=1e-3, include_top=True,\n # weights='imagenet', input_tensor=None, pooling=None, classes=1000)\n # model.add(Dense(1000, input_shape=(26,)))\n # model.add(mob)\n #\n # model.layers.pop()\n # output = Reshape((26,))\n # # model.add(output)\n # # model2 = Model(model.input, output)\n # for i in model.layers:\n # print(i)\n\n # load vgg16 without dense layer and with theano dim ordering\n base_model = mobilenet.MobileNet(weights='imagenet', include_top=False, input_shape=(128, 128, 3))\n\n # number of classes in your dataset e.g. 20\n num_classes = 26\n\n x = Flatten()(base_model.output)\n predictions = Dense(num_classes, activation='softmax')(x)\n\n # create graph of your new model\n head_model = Model(input=base_model.input, output=predictions)\n\n model = head_model\n\n return model\n\n\nif __name__ == '__main__':\n MobileNetv2((224, 224, 3), 100)\n","sub_path":"mobilenet_v2.py","file_name":"mobilenet_v2.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"197675130","text":"import sys\nimport os\nimport csv\n\nsys.path.append(r\"C:\\Users\\estasney\\PycharmProjects\\FlaskAPIWeb\\mysite\")\n# sys.path.append(\"/home/estasney1/mysite\")\n\nfrom app_folder import create_app\nfrom app_folder.models import LinkedInRecord\n\nprint(\"Fetching Records\")\n\nsave_path = 'corpus.csv'\n\napp = create_app()\napp.app_context().push()\n\n\nprofiles = LinkedInRecord.query.all()\n\nwith open(save_path, 'w+', newline='', encoding='utf-8') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(['member_id', 'title', 'company', 'summary', 'skills'])\n\n for profile in profiles:\n member_id = profile.member_id\n profile_text = []\n profile_text.append(profile.summary)\n title = \"\"\n company = \"\"\n for job in profile.jobs:\n if job.index == 0:\n title = job.title\n company = job.companyName\n profile_text.append(job.summary)\n\n profile_text = list(filter(lambda x: x is not None and len(x) > 5, profile_text))\n if not profile_text:\n profile_text = \"\"\n else:\n profile_text = [x.replace(\"\\n\", \" \").replace(\"\\t\", \" \") for x in profile_text]\n profile_text = \"\\n\".join(profile_text)\n\n skills = profile.skills if profile.skills else \"\"\n\n writer.writerow([member_id, title, company, profile_text, skills])\n","sub_path":"scripts2/make_corpus.py","file_name":"make_corpus.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"37729672","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('products/', views.products, name='products'),\n path('create_product/', views.createProduct, name='create_product'),\n path('update_product/', views.updateProduct, name='update_product'),\n path('delete_product/', views.deleteProduct, name='delete_product'),\n path('custumer/', views.custumer, name='custumer'),\n path('create_order/', views.createOrder, name='create_order'),\n path('update_order/', views.updateOrder, name='update_order'),\n path('delete_order/', views.deleteOrder, name='delete_order'),\n path('login/', views.loginPage, name='login'),\n path('register/', views.registerPage, name='register'),\n path('logout/', views.logoutPage, name='logout'),\n path('user/', views.userPage, name='user-page'),\n path('account/', views.accountSetting, name='account-page'),\n]\n\n","sub_path":"Asyari/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"394597812","text":"import torch.nn as nn\r\nimport torch\r\nfrom torchsummary import summary\r\n\r\ndef _make_divisible(v, divisor, min_value=None):\r\n \"\"\"\r\n This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8\r\n It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\r\n :param v:\r\n :param divisor:\r\n :param min_value:\r\n :return:\r\n \"\"\"\r\n if min_value is None:\r\n min_value = divisor\r\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\r\n # Make sure that round down does not go down by more than 10%.\r\n if new_v < 0.9 * v:\r\n new_v += divisor\r\n return new_v\r\n\r\nclass DoubleConv(nn.Sequential):\r\n def __init__(self, in_ch, out_ch, norm_layer=None, activation_layer=None):\r\n super(DoubleConv, self).__init__(\r\n nn.Conv2d(in_ch , out_ch, kernel_size=1),\r\n norm_layer(out_ch),\r\n activation_layer(out_ch),\r\n nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1),\r\n norm_layer(out_ch),\r\n activation_layer(out_ch),\r\n nn.UpsamplingBilinear2d(scale_factor=2)\r\n )\r\n\r\nclass ConvBNReLU(nn.Sequential):\r\n def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1, norm_layer=None, activation_layer=None):\r\n padding = (kernel_size - 1) // 2\r\n super(ConvBNReLU, self).__init__(\r\n nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),\r\n norm_layer(out_planes),\r\n activation_layer(out_planes)\r\n )\r\n\r\nclass InvertedResidual(nn.Module):\r\n def __init__(self, inp, oup, stride, expand_ratio, norm_layer=None, activation_layer=None):\r\n super(InvertedResidual, self).__init__()\r\n self.stride = stride\r\n assert stride in [1, 2]\r\n\r\n hidden_dim = int(round(inp * expand_ratio))\r\n self.use_res_connect = self.stride == 1 and inp == oup\r\n\r\n layers = []\r\n if expand_ratio != 1:\r\n # pw\r\n layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer, activation_layer=activation_layer))\r\n layers.extend([\r\n # dw\r\n ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim, norm_layer=norm_layer, activation_layer=activation_layer),\r\n # pw-linear\r\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\r\n norm_layer(oup),\r\n ])\r\n self.conv = nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n if self.use_res_connect:\r\n return x + self.conv(x)\r\n else:\r\n return self.conv(x)\r\n\r\nclass LpNetResConcat(nn.Module):\r\n def __init__(self,\r\n input_size,\r\n joint_num,\r\n input_channel = 48,\r\n embedding_size = 2048,\r\n width_mult=1.0,\r\n round_nearest=8,\r\n block=None,\r\n norm_layer=None,\r\n activation_layer=None,\r\n inverted_residual_setting=None):\r\n\r\n super(LpNetResConcat, self).__init__()\r\n\r\n assert input_size[1] in [256]\r\n\r\n if block is None:\r\n block = InvertedResidual\r\n if norm_layer is None:\r\n norm_layer = nn.BatchNorm2d\r\n if activation_layer is None:\r\n activation_layer = nn.PReLU # PReLU does not have inplace True\r\n if inverted_residual_setting is None:\r\n inverted_residual_setting = [\r\n # t, c, n, s\r\n [1, 64, 1, 1], #[-1, 48, 256, 256]\r\n [6, 48, 2, 2], #[-1, 48, 128, 128]\r\n [6, 48, 3, 2], #[-1, 48, 64, 64]\r\n [6, 64, 4, 2], #[-1, 64, 32, 32]\r\n [6, 96, 3, 2], #[-1, 96, 16, 16]\r\n [6, 160, 3, 2], #[-1, 160, 8, 8]\r\n [6, 320, 1, 1], #[-1, 320, 8, 8]\r\n ]\r\n\r\n # building first layer\r\n inp_channel = [_make_divisible(input_channel * width_mult, round_nearest),\r\n _make_divisible(input_channel * width_mult, round_nearest) + inverted_residual_setting[0][1],\r\n inverted_residual_setting[0][1] + inverted_residual_setting[1][1],\r\n inverted_residual_setting[1][1] + inverted_residual_setting[2][1],\r\n inverted_residual_setting[2][1] + inverted_residual_setting[3][1],\r\n inverted_residual_setting[3][1] + inverted_residual_setting[4][1],\r\n inverted_residual_setting[4][1] + inverted_residual_setting[5][1],\r\n inverted_residual_setting[5][1] + inverted_residual_setting[6][1],\r\n inverted_residual_setting[6][1] + embedding_size,\r\n 256 + embedding_size,\r\n ]\r\n self.first_conv = ConvBNReLU(3, inp_channel[0], stride=1, norm_layer=norm_layer, activation_layer=activation_layer)\r\n\r\n inv_residual = []\r\n # building inverted residual blocks\r\n j = 0\r\n for t, c, n, s in inverted_residual_setting:\r\n output_channel = _make_divisible(c * width_mult, round_nearest)\r\n for i in range(n):\r\n stride = s if i == 0 else 1\r\n input_channel = inp_channel[j] if i == 0 else output_channel\r\n inv_residual.append(block(input_channel, output_channel, stride, expand_ratio=t, norm_layer=norm_layer, activation_layer=activation_layer))\r\n j += 1\r\n # make it nn.Sequential\r\n self.inv_residual = nn.Sequential(*inv_residual)\r\n\r\n self.last_conv = ConvBNReLU(inp_channel[j], embedding_size, kernel_size=1, norm_layer=norm_layer, activation_layer=activation_layer)\r\n\r\n self.deonv0 = DoubleConv(inp_channel[j+1], 256, norm_layer=norm_layer, activation_layer=activation_layer)\r\n self.deonv1 = DoubleConv(2304, 256, norm_layer=norm_layer, activation_layer=activation_layer)\r\n self.deonv2 = DoubleConv(512, 256, norm_layer=norm_layer, activation_layer=activation_layer)\r\n\r\n self.final_layer = nn.Conv2d(\r\n in_channels=256,\r\n out_channels= joint_num * 64,\r\n kernel_size=1,\r\n stride=1,\r\n padding=0\r\n )\r\n\r\n self.avgpool = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)\r\n self.upsample = nn.UpsamplingBilinear2d(scale_factor=2)\r\n\r\n def forward(self, x):\r\n x0 = self.first_conv(x)\r\n x1 = self.inv_residual[0:1](x0)\r\n x2 = self.inv_residual[1:3](torch.cat([x0, x1], dim=1))\r\n x0 = self.inv_residual[3:6](torch.cat([self.avgpool(x1), x2], dim=1))\r\n x1 = self.inv_residual[6:10](torch.cat([self.avgpool(x2), x0], dim=1))\r\n x2 = self.inv_residual[10:13](torch.cat([self.avgpool(x0), x1], dim=1))\r\n x0 = self.inv_residual[13:16](torch.cat([self.avgpool(x1), x2], dim=1))\r\n x1 = self.inv_residual[16:17](torch.cat([self.avgpool(x2), x0], dim=1))\r\n x2 = self.last_conv(torch.cat([x0, x1], dim=1))\r\n x0 = self.deonv0(torch.cat([x1, x2], dim=1))\r\n x1 = self.deonv1(torch.cat([self.upsample(x2), x0], dim=1))\r\n x2 = self.deonv2(torch.cat([self.upsample(x0), x1], dim=1))\r\n x0 = self.final_layer(x2)\r\n return x0\r\n\r\n def init_weights(self):\r\n for i in [self.deconv0, self.deconv1, self.deconv2]:\r\n for name, m in i.named_modules():\r\n if isinstance(m, nn.ConvTranspose2d):\r\n nn.init.normal_(m.weight, std=0.001)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.constant_(m.weight, 1)\r\n nn.init.constant_(m.bias, 0)\r\n for j in [self.first_conv, self.inv_residual, self.last_conv, self.final_layer]:\r\n for m in j.modules():\r\n if isinstance(m, nn.Conv2d):\r\n nn.init.normal_(m.weight, std=0.001)\r\n if hasattr(m, 'bias'):\r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n\r\nif __name__ == \"__main__\":\r\n model = LpNetResConcat((256, 256), 18)\r\n test_data = torch.rand(1, 3, 256, 256)\r\n test_outputs = model(test_data)\r\n # print(test_outputs.size())\r\n summary(model, (3, 256, 256))","sub_path":"common/backbone/lpnet_res_concat.py","file_name":"lpnet_res_concat.py","file_ext":"py","file_size_in_byte":8398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"466211351","text":"from flask import Flask, request, render_template_string\nfrom OCR import run_image\nimport json\n\napp = Flask(__name__)\n\n\ndef get_webpage():\n res = ''\n for line in open('html/index.html'):\n res += line\n return res\n\n\n@app.route('/languages')\ndef languages():\n config = json.load(open('config.json'))\n return ','.join(config.keys())\n\n\n@app.route('/', methods=[\"GET\", \"POST\"])\ndef index():\n config = json.load(open('config.json'))\n if request.method == 'GET':\n return render_template_string(get_webpage(), langs=config.keys())\n else:\n return run_image(request.files['img'], request.form['lang'])\n","sub_path":"Webserver.py","file_name":"Webserver.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"613754790","text":"from SnakeGameColors import *\nimport random\nimport pygame\nimport os\npygame.init()\npygame.mixer.init()\n\nclock = pygame.time.Clock()\nfont = pygame.font.SysFont(None, 30)\n\nscreen_width = 650\nscreen_height = 450\n\ngameWindow = pygame.display.set_mode((screen_width, screen_height))\npygame.display.set_caption(\"Snake Game\")\n\nstart_bg = pygame.image.load(\"start.jpg\")\nstart_bg = pygame.transform.scale(start_bg, (screen_width, screen_height)).convert_alpha()\n\ngame_bg = pygame.image.load(\"grass.png\")\ngame_bg = pygame.transform.scale(game_bg, (screen_width, screen_width)).convert_alpha()\n\nover_bg = pygame.image.load(\"over.jpg\")\nover_bg = pygame.transform.scale(over_bg, (screen_width, screen_height)).convert_alpha()\n\n\ndef start():\n exit_game = False\n pygame.mixer.music.load(\"intro.mp3\")\n pygame.mixer.music.play(-1)\n while not exit_game:\n gameWindow.fill(yellow)\n gameWindow.blit(start_bg, (0, 0))\n show_on_screen(\"Press Any Key to Start the Game......\", black, 160, 57)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n if event.type == pygame.KEYDOWN:\n game_loop()\n pygame.display.update()\n clock.tick(60)\n\n\ndef show_on_screen(text, color, x, y):\n screen_text = font.render(text, True, color)\n gameWindow.blit(screen_text, [x, y])\n\n\ndef grow_snake(base, color, ordinates, size):\n for x, y in ordinates:\n pygame.draw.rect(base, color, [x, y, size, size])\n\n\ndef game_loop():\n if not os.path.exists(\"high_score.txt\"):\n with open(\"high_score.txt\", \"w\") as hs:\n hs.write(\"0\")\n with open(\"high_score.txt\", \"r\") as hs:\n high_score = hs.read()\n\n pygame.mixer.music.load(\"bg.mp3\")\n pygame.mixer.music.play(-1)\n\n food_x = random.randint(20, screen_width - 20)\n food_y = random.randint(75, screen_height - 20)\n food_radius = 5\n velocity_x = 0\n velocity_y = 0\n snake_size = 10\n snake_y = 220\n snake_x = 320\n score = 0\n fps = 50\n\n snake_length = 1\n snake_list = []\n\n exit_game = False\n game_over = False\n\n while not exit_game:\n if game_over:\n gameWindow.fill(white)\n gameWindow.blit(game_bg, (0, 0))\n show_on_screen(\"Game Over!!! Press Return to Continue\", red, 130, 160)\n show_on_screen(\"Your Score : \" + str(score), red, 230, 180)\n show_on_screen(\"High Score : \" + str(high_score), red, 230, 200)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n game_over = False\n game_loop()\n\n else:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n velocity_y = -5\n velocity_x = 0\n if event.key == pygame.K_DOWN:\n velocity_x = 0\n velocity_y = 5\n if event.key == pygame.K_RIGHT:\n velocity_y = 0\n velocity_x = 5\n if event.key == pygame.K_LEFT:\n velocity_y = 0\n velocity_x = -5\n\n snake_x = snake_x + velocity_x\n snake_y = snake_y + velocity_y\n\n if abs(snake_x - food_x) < 5 and abs(snake_y - food_y) < 5:\n # pygame.mixer.music.load(\"food.mp3\")\n # pygame.mixer.music.play()\n score = score + 10\n snake_length = snake_length + 3\n food_x = random.randint(20, screen_width - 20)\n food_y = random.randint(50, screen_height - 20)\n # pygame.mixer.music.load(\"bg.mp3\")\n # pygame.mixer.music.play(-1)\n elif abs(food_x - snake_x) < 5 and abs(food_y - snake_y) < 5:\n # pygame.mixer.music.load(\"food.mp3\")\n # pygame.mixer.music.play()\n score = score + 10\n snake_length = snake_length + 3\n food_x = random.randint(20, screen_width - 20)\n food_y = random.randint(50, screen_height - 20)\n # pygame.mixer.music.load(\"bg.mp3\")\n # pygame.mixer.music.play(-1)\n\n gameWindow.fill(white)\n gameWindow.blit(game_bg, (0, 0))\n show_on_screen(\"Score : \" + str(score) + \" High Score : \" + str(high_score), purple, 10, 10)\n pygame.draw.line(gameWindow, brown, (0, 40), (screen_width, 40), 3)\n pygame.draw.circle(gameWindow, red, [food_x, food_y], food_radius)\n\n snake_head = list()\n snake_head.append(snake_x)\n snake_head.append(snake_y)\n snake_list.append(snake_head)\n\n if len(snake_list) > snake_length:\n del snake_list[0]\n\n if snake_head in snake_list[:-1]:\n pygame.mixer.music.load(\"over.mp3\")\n pygame.mixer.music.play()\n if int(high_score) <= score:\n with open(\"high_score.txt\", \"w\") as hs:\n hs.write(str(score))\n game_over = True\n\n if snake_x < 0 or snake_x > screen_width or snake_y < 40 or snake_y > screen_height:\n pygame.mixer.music.load(\"over.mp3\")\n pygame.mixer.music.play()\n if int(high_score) <= score:\n with open(\"high_score.txt\", \"w\") as hs:\n hs.write(str(score))\n game_over = True\n\n if int(high_score) < score:\n high_score = score\n\n grow_snake(gameWindow, black, snake_list, snake_size)\n pygame.display.update()\n clock.tick(fps)\n\n pygame.quit()\n quit()\n\n\nstart()\n","sub_path":"SnakeGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"220114523","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 13:31:41 2017\n\n@author: mmic\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Reading the excel file into python with necessary rows and columns\n\nr=pd.read_excel('C:\\\\Users\\\\mmic\\\\Documents\\\\Python Tutorial\\\\Python\\\\'+\n 'Bangladesh_Remittance_HIES2010.xlsx',sheetname=\"Sheet1\",\n index_col=None,na_values=['NA'],skiprows=7,\n parse_cols=\"A,F:G,J:M,P,U\")\n\n## Data cleaning\n\nr['Total_Remittance']=r['Total_money_sent']+r['Value of product sent']\n# Converting total remittance in USD\n# US-BDT exchange rate in 2010\nE=71.17\nr['Total_Remittance']=r['Total_Remittance']/E\n# Converting total stay in abroad in months\nr['Total_Stay']=r['Months spent in abroad']+12*r['Years Spent in abroad']\nr=r[r.Total_Remittance !=0]\n# Deleting the expatriates' information reported as living in Bangladesh \n#(0 is the coutry code for Banglades)\nr=r[r.Country_Code !=0]\n\n# Recoding the country code into country name\nr['Country'] = (r['Country_Code'].map({1:'Saudi Arabia',2:'Qatar',3:'Kuwait',\n 4:'Oman',5:'Malaysia',6:'Singapore',7:'Iraq',8:'Iran',9:'Libya',10:'UAE',\n 11:'Canada',12:'Australia',13:'UK',14:'USA',15:'South Korea',16:'Japan',\n 17:'Turkey',18:'Germany',19:'Sweden',20:'Russia',21:'Other European Countries',\n 23:'Brunei',24:'Mauritius',25:'South Africa',26:'Others'}))\n\n## Graph 1\nplt.style.use('ggplot')\nfig1, ax = plt.subplots()\ngroup_names = ['0 year', '1-5 years','6-10 years','11-12 years','13-16 years',\n '>16 years']\nr['categories'] = pd.cut(r['Level of Education'], bins=[-1,0,5,10,12,16,18], \n labels=['0 year', '1-5 years','6-10 years',\n '11-12 years','13-16 years', '>16 years'])\ncounts = r['categories'].value_counts(sort=False)\nplt.axis('equal')\nexplode = (0.2, 0.1,0.1,0.2,0.1,0.1)\ncolors = ['#c0d6e4','#6a6aa7','#40e0d0','#ee6363','#0071C6','#008DB8',]\ncounts.plot(kind='pie', fontsize=12,colors=colors,explode=explode,autopct='%.2f')\nplt.legend(labels=group_names,loc=2,bbox_to_anchor=(0.8,0.4))\nplt.ylabel('')\nplt.title('Graph-1: Level of Education of the expatriates (In Percentage)')\n# save graph 1\nfig1.savefig('Graph-1.png', transparent=False, dpi=90, bbox_inches=\"tight\")\n\n# Graph 2\nfig2, ax = plt.subplots()\nr.groupby('Country')['Total_Remittance'].sum().plot(kind='bar')\nplt.ylabel('Remittance Amount (USD)')\nplt.title('Graph-2: Remittance Inflow by the Location of Expatriates')\n# save graph 2\nfig2.savefig('Graph-2.png', transparent=False, dpi=90, bbox_inches=\"tight\")\n\n# Graph 3\nfig3, ax = plt.subplots()\nplt.scatter(r['Level of Education'], np.log(r['Total_Remittance']), alpha=0.15,\n marker='o')\nplt.plot(np.unique(r['Level of Education']),\n np.poly1d(np.polyfit(r['Level of Education'],\n np.log(r['Total_Remittance']), 1))\n (np.unique(r['Level of Education'])),color='Black', \n linestyle=\"--\", linewidth=2)\nplt.scatter(r['Level of Education'], np.log(r['Total_Remittance']), \n alpha=0.15, marker='o')\nplt.ylabel('Remittance (Log)')\nplt.xlabel('Level of Education (Years)')\nplt.title('Graph-3: Remittance and Level of Education')\n# save graph 3\nfig3.savefig('Graph-3.png', transparent=False, dpi=90, bbox_inches=\"tight\")","sub_path":"ProblemSets/ProblemSet5/PS5_Chowdhury.py","file_name":"PS5_Chowdhury.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"169670158","text":"import torch\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.metrics import log_loss\n\n# https://www.kaggle.com/c/rfcx-species-audio-detection/discussion/198418#1086063\ndef _one_sample_positive_class_precisions(scores, truth):\n num_classes = scores.shape[0]\n pos_class_indices = np.flatnonzero(truth > 0)\n\n if not len(pos_class_indices):\n return pos_class_indices, np.zeros(0)\n\n retrieved_classes = np.argsort(scores)[::-1]\n\n class_rankings = np.zeros(num_classes, dtype=np.int)\n class_rankings[retrieved_classes] = range(num_classes)\n\n retrieved_class_true = np.zeros(num_classes, dtype=np.bool)\n retrieved_class_true[class_rankings[pos_class_indices]] = True\n\n retrieved_cumulative_hits = np.cumsum(retrieved_class_true)\n\n precision_at_hits = (\n retrieved_cumulative_hits[class_rankings[pos_class_indices]] /\n (1 + class_rankings[pos_class_indices].astype(np.float)))\n return pos_class_indices, precision_at_hits\n\ndef lwlrap(truth, scores):\n assert truth.shape == scores.shape\n num_samples, num_classes = scores.shape\n precisions_for_samples_by_classes = np.zeros((num_samples, num_classes))\n for sample_num in range(num_samples):\n pos_class_indices, precision_at_hits = _one_sample_positive_class_precisions(scores[sample_num, :], truth[sample_num, :])\n precisions_for_samples_by_classes[sample_num, pos_class_indices] = precision_at_hits\n\n labels_per_class = np.sum(truth > 0, axis=0)\n weight_per_class = labels_per_class / float(np.sum(labels_per_class))\n\n per_class_lwlrap = (np.sum(precisions_for_samples_by_classes, axis=0) /\n np.maximum(1, labels_per_class))\n return per_class_lwlrap, weight_per_class\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\nclass MetricMeter(object):\n def __init__(self):\n self.reset()\n \n def reset(self):\n self.y_true = []\n self.y_pred = []\n \n def update(self, y_true, y_pred):\n self.y_true.extend(y_true.cpu().detach().numpy().tolist())\n self.y_pred.extend(torch.sigmoid(y_pred).cpu().detach().numpy().tolist())\n\n @property\n def avg(self):\n \n score_class, weight = lwlrap(np.array(self.y_true), np.array(self.y_pred))\n self.score = (score_class * weight).sum()\n\n return {\n \"lwlrap\" : self.score\n }\n","sub_path":"BASELINE/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"204760029","text":"\"\"\"A Python script to rewrite hashes in BUILD files.\"\"\"\n\nimport ast\n\n\n# These are templated in by Go. It's a bit hacky but is a way of avoiding\n# passing arbitrary arguments through Go / C calls.\nFILENAME = '__FILENAME__'\nTARGETS = {__TARGETS__}\nPLATFORM = '__PLATFORM__'\n\n\ndef is_a_target(node):\n \"\"\"Returns the name of a node if it's a target that we're interested in.\"\"\"\n if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):\n for keyword in node.value.keywords:\n if keyword.arg == 'name':\n if isinstance(keyword.value, ast.Str) and keyword.value.s in TARGETS:\n return keyword.value.s\n\n\ndef replace_hash(line, before, after):\n \"\"\"Rewrites a hash within one particular line. Returns updated line.\"\"\"\n quote = lambda s, q: q + s + q\n return line.replace(quote(before, '\"'), quote(after, '\"')).replace(quote(before, \"'\"), quote(after, \"'\"))\n\n\nwith _open(FILENAME) as f:\n lines = f.readlines()\n tree = ast.parse(''.join(lines), filename=FILENAME)\n\nfor node in ast.iter_child_nodes(tree):\n name = is_a_target(node)\n if name:\n for keyword in node.value.keywords:\n if keyword.arg == 'hashes' and isinstance(keyword.value, ast.List):\n # lineno - 1 because lines in the ast are 1-indexed\n candidates = {dep.s: dep.lineno - 1 for dep in keyword.value.elts\n if isinstance(dep, ast.Str)}\n # Filter by any leading platform (i.e. linux_amd64: abcdef12345).\n platform_candidates = {k: v for k, v in candidates.items() if PLATFORM in k}\n prefix = ''\n if len(platform_candidates) == 1:\n candidates = platform_candidates\n prefix = PLATFORM + ': '\n # Should really do something here about multiple hashes and working out which\n # is which...\n current, lineno = candidates.popitem()\n prefix, colon, _ = current.rpartition(':')\n if colon:\n colon += ' '\n lines[lineno] = replace_hash(lines[lineno], current, prefix + colon + TARGETS[name])\n elif keyword.arg == 'hash' and isinstance(keyword.value, ast.Str):\n lineno = keyword.value.lineno - 1\n current = keyword.value.s\n prefix = current[:current.find(':') + 2] if ': ' in current else ''\n lines[lineno] = replace_hash(lines[lineno], current, prefix + TARGETS[name])\n\n\nwith _open(FILENAME, 'w') as f:\n for line in lines:\n f.write(line)\n","sub_path":"src/hashes/hash_rewriter.py","file_name":"hash_rewriter.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"351405357","text":"from django.conf.urls import url\n\nfrom . import views\n\n\napp_name = 'projects'\nurlpatterns = [\n url(r'^(?P\\w+)/(?P\\w+)-(?P\\d+)$', views.worklogs, name='worklogs'),\n url(r'^(?P\\w+)/(?P\\w+)-(?P\\d+)/(?P\\d+)$', views.detail, name='detail'),\n # url(r'^(?P\\w+)/(?P\\w+)-(?P\\d+)/(?P\\d+)/edit$', views.edit_worklog, name='edit_worklog'),\n # url(r'^save$', views.save_worklog, name='save_worklog'),\n]\n","sub_path":"soloist/apps/projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"408573099","text":"# from .models import Question\n# from django.http import HttpResponse\n\nfrom django.shortcuts import render, get_object_or_404\nfrom .forms import PostForm\nfrom django.template import loader\nfrom django.utils import timezone\nfrom .models import Post\nfrom django.shortcuts import redirect\n\n# def index(request):\n\n # return HttpResponse(\"Hello, world. You're at the polls index.\")\n# def detail(request, question_id):\n # return HttpResponse(\"You're looking at question %s.\" % question_id)\n# def results(request, question_id):\n\n # response = \"You're looking at the results of question %s.\"\n # return HttpResponse(response % question_id)\n# def vote(request, question_id):\n # return HttpResponse(\"You're voting on question %s.\" % question_id)\n# def index(request):\n # latest_question_list = Question.objects.order_by('-pub_date')[:5]\n # template = loader.get_template('polls/index.html')\n # context = { 'latest_question_list': latest_question_list, }\n\n # return HttpResponse(template.render(context, request))\n\n#Post.objects.get(pk=pk)\n# ----------------------------------------//-------------------------------------------------------\n\n\ndef post_list(request):\n\n post = Post.objects.filter( published_date__lte=timezone.now()).order_by('published_date')\n return render(request, 'polls/postlist.html', {'post': post})\n\n# ----------------------------------------//-------------------------------------------------------\n\n\ndef post_detail(request, pk):\n \n post = get_object_or_404(Post, pk=pk)\n return render(request, 'polls/post_detail.html', {'post': post})\n\n# ----------------------------------------//-------------------------------------------------------\n\n\ndef post_new(request):\n\n\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'polls/post_edit.html', {'form': form})\n\n \n \n# ----------------------------------------//-------------------------------------------------------\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'polls/post_edit.html', {'form': form})\n","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"334188934","text":"# Copyright 2016 The Meson development team\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 .. import coredata, mesonlib, build\nimport sys\n\nclass I18nModule:\n\n def gettext(self, state, args, kwargs):\n if len(args) != 1:\n raise coredata.MesonException('Gettext requires one positional argument (package name).')\n packagename = args[0]\n languages = mesonlib.stringlistify(kwargs.get('languages', []))\n if len(languages) == 0:\n raise coredata.MesonException('List of languages empty.')\n datadirs = mesonlib.stringlistify(kwargs.get('data_dirs', []))\n extra_args = mesonlib.stringlistify(kwargs.get('args', []))\n\n pkg_arg = '--pkgname=' + packagename\n lang_arg = '--langs=' + '@@'.join(languages)\n datadirs = '--datadirs=' + ':'.join(datadirs) if datadirs else None\n extra_args = '--extra-args=' + '@@'.join(extra_args) if extra_args else None\n\n potargs = [state.environment.get_build_command(), '--internal', 'gettext', 'pot', pkg_arg]\n if datadirs:\n potargs.append(datadirs)\n if extra_args:\n potargs.append(extra_args)\n pottarget = build.RunTarget(packagename + '-pot', sys.executable, potargs, [], state.subdir)\n\n gmoargs = [state.environment.get_build_command(), '--internal', 'gettext', 'gen_gmo', lang_arg]\n gmotarget = build.RunTarget(packagename + '-gmo', sys.executable, gmoargs, [], state.subdir)\n\n updatepoargs = [state.environment.get_build_command(), '--internal', 'gettext', 'update_po', pkg_arg, lang_arg]\n if datadirs:\n updatepoargs.append(datadirs)\n if extra_args:\n updatepoargs.append(extra_args)\n updatepotarget = build.RunTarget(packagename + '-update-po', sys.executable, updatepoargs, [], state.subdir)\n\n installcmd = [sys.executable, state.environment.get_build_command(),\n '--internal', 'gettext', 'install',\n '--subdir=' + state.subdir,\n '--localedir=' + state.environment.coredata.get_builtin_option('localedir'),\n pkg_arg, lang_arg]\n iscript = build.InstallScript(installcmd)\n\n return [pottarget, gmotarget, iscript, updatepotarget]\n\ndef initialize():\n return I18nModule()\n","sub_path":"mesonbuild/modules/i18n.py","file_name":"i18n.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"614410186","text":"from sa.common import get_ms_ticker_names, find_small_cap_tickers\nfrom sa.tools.features import Features\nfrom sa.tools.returncalc import ReturnCalculator\nfrom sa.logger import LOGGER\n\nimport os\nimport numpy as np\n\nfrom sklearn.preprocessing import Imputer\n\nclass FeatureHelper():\n def __init__(self, session):\n self.dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'cache')\n self.file_path = os.path.join(self.dir_path, 'features.npz')\n self.sess = session\n self.ff = Features()\n\n def fetch_feature_data(self):\n if not os.path.isfile(self.file_path):\n self.generate_and_save_feature_data()\n\n npz = np.load(self.file_path)\n\n return tuple(npz[a] for a in ('train_data', 'train_targets', 'test_data', 'test_targets'))\n\n def fetch_binary_feature_data(self, p=None):\n train_data, train_targets, test_data, test_targets = self.fetch_feature_data()\n\n median = np.median(train_targets)\n print('meadian is ', median)\n train_targets = np.array([t >= median for t in train_targets])\n test_targets = np.array([t >= median for t in test_targets])\n\n return train_data, train_targets, test_data, test_targets\n\n def fetch_feature_tickers(self):\n npz = np.load(self.file_path)\n\n return npz['train_ticker_names'], npz['test_ticker_names']\n\n def screen_and_save_feature_data(self):\n train_ticker_names, test_ticker_names = self.fetch_feature_tickers()\n train_data, train_targets, test_data, test_targets = self.fetch_feature_data()\n\n tickers = set(find_small_cap_tickers(self.sess)) # finds ticker < 10m value\n train_rm_indexes = []\n for i, (ticker, target) in enumerate(zip(train_ticker_names, train_targets)):\n if target > 10 or ticker in tickers:\n train_rm_indexes.append(i)\n test_rm_indexes = []\n for i, (ticker, target) in enumerate(zip(test_ticker_names, test_targets)):\n if target > 10 or ticker in tickers:\n test_rm_indexes.append(i)\n\n train_ticker_names = np.delete(train_ticker_names, train_rm_indexes, axis=0)\n train_data = np.delete(train_data, train_rm_indexes, axis=0)\n train_targets = np.delete(train_targets, train_rm_indexes, axis=0)\n test_ticker_names = np.delete(test_ticker_names, test_rm_indexes, axis=0)\n test_data = np.delete(test_data, test_rm_indexes, axis=0)\n test_targets = np.delete(test_targets, test_rm_indexes, axis=0)\n\n LOGGER.info(\"Saving file at: {}\".format(self.file_path))\n\n np.savez(self.file_path,\n train_data = train_data, train_targets = train_targets,\n train_ticker_names = train_ticker_names, test_data = test_data,\n test_targets = test_targets, test_ticker_names = test_ticker_names)\n\n def fetch_feature_names(self):\n return self.ff.ms_key_stats_cols\n\n def generate_and_save_feature_data(self, independent=True):\n rc = ReturnCalculator()\n\n ticker_names = sorted(get_ms_ticker_names(self.sess, \"TSX\"))\n num_tickers = len(ticker_names)\n\n train_data, train_targets = [], []\n train_ticker_names = []\n test_data, test_targets = [], []\n test_ticker_names = []\n\n imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n\n for i, t in enumerate(ticker_names, 1):\n LOGGER.info(\"[{:d}/{:d}] Working on {}...\".format(i, num_tickers, t))\n\n dates = self.ff.ms_key_stats_date(self.sess, t)\n\n if len(dates) < 1:\n continue\n\n date_gap = dates[1] - dates[0] if len(dates) > 2 else timedelta(days=365)\n last_date = dates[-1]\n\n rows = self.ff.ms_key_stats_data(self.sess, t)\n\n if not independent:\n # Window sliding for time series\n empty_row = tuple((None,)) * len(rows[0])\n new_rows = []\n for i in range(len(rows)):\n first_part = rows[i-1] if i > 0 else empty_row\n second_part = rows[i]\n new_rows.append(first_part + second_part)\n rows = new_rows\n\n # Add the start date to the list of dates\n return_dates = [dates[0] - date_gap] + dates\n\n returns = rc.calculate_return_between_dates(t, return_dates)\n for row, date, ret in zip(rows, dates, returns):\n if ret is None: # if return date are out of range\n continue\n\n if date == last_date:\n test_data.append(row)\n test_targets.append(ret)\n test_ticker_names.append(t)\n else:\n train_data.append(row)\n train_targets.append(ret)\n train_ticker_names.append(t)\n\n # Convert the python lists to numpy arrays and fill missing values\n train_data = np.array(train_data, dtype=np.float)\n imp = imp.fit(train_data)\n\n train_ticker_names = np.array(train_ticker_names, dtype=np.str)\n train_data = imp.transform(train_data)\n train_targets = np.array(train_targets, dtype=np.float)\n test_ticker_names = np.array(test_ticker_names, dtype=np.str)\n test_data = imp.transform(np.array(test_data, dtype=np.float))\n test_targets = np.array(test_targets, dtype=np.float)\n\n if not os.path.exists(self.dir_path):\n os.makedirs(self.dir_path)\n\n LOGGER.info(\"Saving file at: {}\".format(self.file_path))\n\n np.savez(self.file_path,\n train_data = train_data, train_targets = train_targets,\n train_ticker_names = train_ticker_names, test_data = test_data,\n test_targets = test_targets, test_ticker_names = test_ticker_names)\n\n\nif __name__ == \"__main__\":\n from sa.database import Session\n\n sess = Session()\n fc = FeatureHelper(sess)\n fc.generate_and_save_feature_data(independent=False)\n fc.screen_and_save_feature_data()\n\n","sub_path":"src/bots/feature_helper.py","file_name":"feature_helper.py","file_ext":"py","file_size_in_byte":6080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"399040587","text":"from commom import cfg as ucasbus_cfg\nfrom crawl2.spider import *\nfrom crawl2.utils import *\nimport os, time, json\nimport numpy as np\nfrom tools import *\nimport threading\nfrom certcode.init import *\n\nname_re = re.compile(\n '你好,(.*?)', re.S)\n\nurlcode_re = re.compile('toUtf8(.*?);')\n\ndef keep_alive(eric):\n while True:\n time.sleep(np.random.randint(300, 500))\n if eric.finished:\n return\n ret = eric.check()\n if not ret:\n res, msg, data = auto_recognition_attemps(eric, attemps=5)\n if res == 0 and data[0] == eric.realname:\n pass\n else:\n eric._login = False\n\nclass Eric(object):\n def __init__(self, username):\n self.username = username\n self.page_limit = ucasbus_cfg.page_limit\n self._login = True\n self.cache = Cache(ucasbus_cfg.cache_path)\n self.route_list_cache = Cache(ucasbus_cfg.route_list_path)\n self.user_cache = Cache(\\\n os.path.join(ucasbus_cfg.users_path, username))\n self.spider = Spider(encoding='utf-8')\n self.load()\n self.finished = False\n self.keep_alive = threading.Thread(target=keep_alive, args=(self, ))\n # self.keep_alive.start()\n\n def finish(self):\n self.save()\n self.finished = True\n # self.keep_alive.join()\n\n def check(self):\n response = self.spider.get('http://payment.ucas.ac.cn/NetWorkUI/showPublic')\n if response:\n return self.realname in response.text\n return False\n\n def load(self):\n self.page = self.user_cache.load('page')\n if not isinstance(self.page, list):\n self.page = []\n self.lock = self.user_cache.load('lock')\n if self.lock == None or not isinstance(self.lock, bool):\n self.lock = False\n self.realname = self.user_cache.load('realname')\n if not self.realname:\n self.realname = 'Unknown'\n \n def query_remain(self, data):\n url = 'http://payment.ucas.ac.cn/NetWorkUI/queryRemainingSeats'\n response = self.spider.post(url, data)\n try:\n return '剩余 %s' % response.json()['returndata']['freeseat']\n except:\n return ''\n\n\n def save(self):\n self.user_cache.save(self.page, 'page')\n self.user_cache.save(self.lock, 'lock')\n self.user_cache.save(self.realname, 'realname')\n\n def del_page(self, page):\n if page >= 0 and page < len(self.page):\n self.page[page]['active'] = False\n return self.touch_page()\n\n def new_page(self):\n n = len(self.page)\n for i in range(n):\n if not self.page[i]['active']:\n self.page[i] = {'status': 1, 'active': True}\n return i\n if n >= self.page_limit:\n return -1\n self.page.append({'status': 1, 'active': True})\n return n\n\n def touch_page(self, page=-1):\n if page >= 0 and page < len(self.page) and \\\n self.page[page]['active']:\n return page\n for i in range(len(self.page)):\n if self.page[i]['active']:\n return i\n return self.new_page()\n\n def get_certcode(self, prefix=False):# {{{\n url = 'http://payment.ucas.ac.cn/NetWorkUI/authImage'\n name = hash_func('{}{}'.format(self.username, time.time()))+'.jpg'\n certcode_path = os.path.join(ucasbus_cfg.static_folder, name)\n response = self.spider.get(url)\n if not response:\n return ''\n with open(certcode_path, 'wb') as f:\n f.write(response.content)\n return certcode_path if prefix else name\n # }}}\n def login(self, certcode):# {{{\n msg = []\n url = 'http://payment.ucas.ac.cn/NetWorkUI/fontuserLogin'\n data = self.user_cache.load('login')\n data['checkCode'] = certcode\n response = self.spider.post(url, data=data)\n\n if not response:\n msg += ['[ERR] 登录失败,服务器未响应。']\n return 1, msg, None\n\n name = name_re.findall(response.text)\n if len(name) == 0:\n msg += ['[ERR] 登录失败,信息错误。']\n return 9, msg, None\n else:\n name = name[0]\n msg += ['[SUC] %s 成功登录!' % name]\n return 0, msg, [name]\n # }}}\n def get_route(self, date, cache):# {{{\n url = 'http://payment.ucas.ac.cn/NetWorkUI/queryBusByDate'\n route_list = self.route_list_cache.load(date)\n msg = []\n if not route_list or not cache:\n data = {\n 'bookingdate': date,\n 'factorycode': 'R001',\n }\n response = self.spider.post(url, data=data)\n if not response:\n msg += ['[ERR] 获取路线失败,服务器未响应。']\n return 1, msg, None\n try:\n data = response.json()\n except:\n msg += ['[ERR] 获取路线失败,返回结果无法 json 化。']\n return 3, msg, None\n try: \n route_list = data['routelist']\n except:\n msg += ['[ERR] 获取路线失败,未找到 routelist 。']\n msg += ['[ERR] json = {}'.format(data)]\n return 4, msg, None\n\n self.route_list_cache.save(route_list, date)\n return 0, msg, [route_list]\n # }}}\n def calc_time(self, *, \\\n delta=ucasbus_cfg.delta, timezone=8, debug=None):# {{{\n cur = time.time()\n if debug:\n return debug + cur\n t = 18 * 3600 + delta - (cur + timezone * 3600) % 86400\n if t < 0:\n t += 86400\n return int(t + cur)\n # }}}\n def check_realname(self, step, response):# {{{\n msg = []\n data = name_re.findall(response.text)\n if len(data) == 1 and data[0] == self.realname:\n return 0, msg\n else:\n names = json.dumps(data)\n msg += ['[ERR] #{}: \\'{}\\' 用户不匹配 {}'.format(step, names, self.realname)]\n return step * 10 + 2, msg\n # }}}\n def send_order(self, route, date):# {{{\n msg = []\n data = {\n 'routecode': route, # You need change\n 'payAmt': '6.00',\n 'bookingdate': date, # You need change\n 'payProjectId': '4', \n 'tel': self.user_cache.load('tel'),\n 'factorycode': 'R001',\n }\n url = 'http://payment.ucas.ac.cn/NetWorkUI/reservedBusCreateOrder'\n response = self.spider.post(url, data)\n\n if not response:\n msg += ['[ERR] #1: 服务器未响应。']\n return 11, msg, None\n try:\n information = response.json()\n except:\n msg += ['[ERR] #1: 返回结果无法 json 化。']\n return 13, msg, None\n\n try:\n ret = information['returncode']\n orderno = information['payOrderTrade']['orderno']\n msg += ['[SUC] #1: 获取订单号[{}], 订单信息:{}, {}, {}'.format(orderno, data['bookingdate'][0], data['routecode'][0], data['tel'])]\n return 0, msg, [orderno]\n except:\n msg += ['[ERR] #1: 未找到 returncode 或 payOrderTrade->orderno 字段!']\n msg += ['[ERR] #1: json={}'.format(information)]\n return 14, msg, None\n\n msg += ['[ERR] step #1: json={}'.format(information)]\n return 19, msg, None\n # }}}\n def send_orderno(self, orderno):# {{{\n msg = []\n data = {\n 'orderno': orderno,\n 'orderamt': '6.00',\n 'payType': '03',\n 'mess': '',\n 'start_limittxtime': '',\n 'end_limittxtime': '',\n }\n url = 'http://payment.ucas.ac.cn/NetWorkUI/onlinePay'\n response = self.spider.post(url, data=data)\n\n if not response:\n msg += ['[ERR] #2: 服务器未响应。']\n return 21, msg, None\n \n ret, log = self.check_realname(2, response)\n msg += log\n if ret != 0:\n return ret, msg, None\n # msg += ['[SUC] #2: 成功发送订单: {}!'.format(orderno)]\n return 0, msg, None\n # }}}\n def request_wechat_urlcode(self, orderno):# {{{\n msg = []\n url = 'http://payment.ucas.ac.cn/NetWorkUI/weixinPayAction?orderno=%s'%orderno\n response = self.spider.get(url)\n\n if not response:\n msg += ['[ERR] #3: 服务器未响应!']\n return 31, msg, None\n\n ret, log = self.check_realname(3, response)\n msg += log\n if ret != 0:\n return ret, msg, None\n\n try:\n urlcode = urlcode_re.findall(response.text)[0][2:-2]\n except:\n msg += ['[ERR] #3: urlcode 字段缺失!']\n return 35, msg, None\n msg += ['[SUC] #3: 成功获从订单[{}]中获取urlcode[{}]!'.format(orderno, urlcode)]\n return 0, msg, [urlcode]\n # }}}\n def get_ucas_qrcode(self, urlcode):# {{{\n msg = []\n data = {\n 'msgCode': 'SUCCESS',\n 'weixinMessage': '??',\n 'urlCode': urlcode,\n 'key': 'TkVUV09SS1BBWWtleQ==',\n }\n url = 'http://payment.ucas.ac.cn/NetWorkUI/weiXinQRCode?'\n for key, value in data.items():\n url = url + key + '=' + value + '&'\n response = self.spider.get(url)\n\n if not response:\n msg += ['[ERR] #4: 服务器未响应!']\n return 41, msg, None\n\n ret, log = self.check_realname(4, response)\n msg += log\n if ret != 0:\n return ret, msg, None\n\n text = response.text.replace('src=\"/NetWork', 'src=\"http://payment.ucas.ac.cn/NetWork')\n msg += ['[SUC] 成功生成二维码,根据urlcode[{}]!'.format(urlcode)]\n return 0, msg, [text]\n # }}}\n def buy(self, route, date):# {{{\n msg = ['[LOG] 开始购票。']\n '''\n send order\n '''\n ret, log, data = self.send_order(route, date)\n msg += log\n if ret != 0:\n return ret, msg, None\n orderno = data[0]\n\n\n ret, log, data = self.send_orderno(orderno)\n msg += log\n if ret != 0:\n return ret, msg, None\n\n \n ret, log, data = self.request_wechat_urlcode(orderno)\n msg += log\n if ret != 0:\n return ret, msg, None\n urlcode = data[0]\n\n ret, log, data = self.get_ucas_qrcode(urlcode)\n msg += log\n if ret != 0:\n return ret, msg, None\n html = data[0]\n\n return 0, msg, [urlcode]\n # }}}\n","sub_path":"eric.py","file_name":"eric.py","file_ext":"py","file_size_in_byte":10775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"219192539","text":"import time\nimport sys\ninput = sys.stdin.readline\n\nn, k = list(map(int, input().split()))\ndiv = 1000000007\n\ndef is_over(num):\n if(num >= div):\n return True\n return False\n\ndef get_div(num):\n return num % div\n\ndef get_process(num1, num2):\n if(is_over(num1)):\n num1 = get_div(num1)\n return num1 * num2\n\ndef get_result():\n up = n\n bottom = k\n for i in range(1, k):\n up = get_process(up, up-i)\n bottom = get_process(bottom, bottom-i)\n\n result = up//bottom\n if(is_over(result)):\n return get_div(result)\n\n return get_div(result)\n\ns = time.time()\nprint(get_result())\nprint(time.time() - s)","sub_path":"by date/2021.03.15/11401.py","file_name":"11401.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"289632259","text":"import os\nimport subprocess\nimport shlex\nimport sys\nimport time\nimport logging\nfrom watchdog.observers import Observer\nfrom watchdog.events import PatternMatchingEventHandler\nimport shutil\n\nDEVELOPMENT_DIR = \"/Users/Jamie/Google Drive/CS4/WebTech/development/html/\"\nPRODUCTION_DIR = \"/Users/Jamie/Google Drive/CS4/WebTech/\"\n\ndef errorBeep():\n # terminal alert\n print('\\a')\n # audible alert\n duration = 0.2 # second\n freq = 440 # Hz\n os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration, freq))\n\ndef successBeep():\n # terminal alert\n print('\\a')\n # audible alert\n duration = 0.05 # second\n freq0 = 600 # Hz\n freq1 = 650 # Hz\n os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration, freq0))\n os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration, freq1))\n\n\nclass vnuValidation(PatternMatchingEventHandler):\n\n def extractTargetPath(self, event):\n if event.event_type == 'moved':\n return event.dest_path\n else:\n return event.src_path\n\n def runValidation(self, event):\n target_file = os.path.split(self.extractTargetPath(event)) [1]\n\n\n # new stuff\n target_file_path = self.extractTargetPath(event)\n splits = target_file_path.split('/')\n mirror_file_path = '/'.join(splits[8:])\n # new stuff\n\n\n # run validation\n target_path = \"/Users/Jamie/Google\\ Drive/CS4/WebTech/development/html/\" + mirror_file_path\n arg_str = \"java -jar /Users/Jamie/Google\\ Drive/CS4/WebTech/validation/dist/vnu.jar \" + target_path\n args = shlex.split(arg_str)\n p_vnu = subprocess.run(args, stderr=subprocess.PIPE)\n console_output = p_vnu.stderr.decode('utf-8')\n\n if len(console_output) == 0:\n # HTML passed - copy to public dir\n source_path = DEVELOPMENT_DIR + mirror_file_path\n destination_path = PRODUCTION_DIR +mirror_file_path\n shutil.copyfile(source_path, destination_path)\n print(\"Pass: %s\" %(target_file), '\\n')\n successBeep()\n else:\n # HTML failed\n errorBeep()\n print(\"Error in: %s\" %(target_file),'\\n')\n print(console_output)\n\n\n def on_created(self, event):\n self.runValidation(event)\n\n\n def on_modified(self, event):\n self.runValidation(event)\n\n def on_moved(self, event):\n self.runValidation(event)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n path = sys.argv[1] if len(sys.argv) > 1 else DEVELOPMENT_DIR\n\n event_handler = vnuValidation(patterns=[\"*.html\"], ignore_patterns=[], ignore_directories=False)\n\n observer = Observer()\n observer.schedule(event_handler, path, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n","sub_path":"vnu_automater.py","file_name":"vnu_automater.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"495503408","text":"from flask import Flask, render_template, request\r\nimport os\r\nfrom PIL import Image\r\n\r\nfrom tensorflow.keras.models import load_model\r\nfrom tensorflow.keras.preprocessing import image\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\napp = Flask(__name__)\r\nimage_folder = os.path.join('static', 'images')\r\napp.config[\"UPLOAD_FOLDER\"] = image_folder\r\n\r\ndic = {0: 'acne-and-rosacea', 1: 'atopic-dermatitis', 2: 'eczema', 3: 'herpes-zoster', 4: 'lichen-planus', 5: 'nail-fungus', 6: 'other',7: 'psoriasis',8: 'tinea',9: 'urticaria'}\r\ndic1 = {0: 'static/data/0Mụn trứng cá/dinh nghia.PNG', 1: 'static/data/1Viêm da cơ địa/dinhnghia.PNG',\r\n 2: 'static/data/2Chàm/dinhnghia.PNG', 3: 'static/data/3Zona/dinhnghia.PNG',\r\n 4: 'static/data/4Lichen phẳng/dinhnghia.PNG', 5:'static/data/5Nấm móng/dinhnghia.PNG',\r\n 6: 'static/data/6Bệnh khác/dinhnghia.PNG', 7: 'static/data/7Vảy nến/dinhnghia.PNG',\r\n 8: 'static/data/8Nấm da đầu/dinhnghia.PNG', 9: 'static/data/9Mề đay/dinhnghia.PNG' }\r\n\r\ndic2 = {0: 'static/data/0Mụn trứng cá/tuvan.PNG', 1: 'static/data/1Viêm da cơ địa/tuvan.PNG',\r\n 2: 'static/data/2Chàm/tuvan.PNG', 3: 'static/data/3Zona/tuvan.PNG',\r\n 4: 'static/data/4Lichen phẳng/tuvan.PNG', 5:'static/data/5Nấm móng/tuvan.PNG',\r\n 6: 'static/data/6Bệnh khác/tuvan.PNG', 7: 'static/data/7Vảy nến/tuvan.PNG',\r\n 8: 'static/data/8Nấm da đầu/tuvan.PNG', 9: 'static/data/9Mề đay/tuvan.PNG' }\r\n\r\nmodel = load_model('resnet50.h5')\r\nmodel.make_predict_function()\r\n\r\n@app.route('/', methods=['GET'])\r\ndef home():\r\n return render_template('AIMed1.html')\r\n\r\n@app.route('/', methods=['POST'])\r\ndef predict():\r\n # predicting images\r\n imagefile = request.files['imagefile']\r\n image_path = 'static/images/' + imagefile.filename\r\n imagefile.save(image_path)\r\n\r\n img = image.load_img(image_path, target_size=(224, 224))\r\n x = image.img_to_array(img)/255.0\r\n x = np.expand_dims(x, axis=0)\r\n\r\n classes = model.predict(x)\r\n result = np.argmax((classes[0]))\r\n pic = os.path.join(app.config['UPLOAD_FOLDER'], imagefile.filename)\r\n print(classes[0])\r\n print(tf.nn.sigmoid(classes[0]))\r\n print(result)\r\n print(dic[result])\r\n\r\n contents = Image.open('{}'.format(dic2[result]))\r\n\r\n return render_template('AIMed1.html', user_image=pic,\r\n prediction_text='{}'.format(dic[result]),\r\n definition_image='{}'.format(dic1[result]),\r\n advice_image='{}'.format(dic2[result]))\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"212134976","text":"# -*- coding: utf-8 -*-\n\"\"\"Stochastic Gradient Descent\"\"\"\n\nimport numpy as np\nimport os\nimport sys\n\ncwd = os.getcwd()\nsys.path.append(cwd)\n\nfrom costs import *\n\n\ndef compute_stoch_gradient_mse(y, tx, w):\n \"\"\"Compute a stochastic gradient from just few examples n and their corresponding y_n labels.\"\"\"\n n, d = tx.shape\n\n e = y - tx.dot(w)\n\n return -tx.T.dot(e) / n\n\n\ndef batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):\n \"\"\"\n Generate a minibatch iterator for a dataset.\n Takes as input two iterables (here the output desired values 'y' and the input data 'tx')\n Outputs an iterator which gives mini-batches of `batch_size` matching elements from `y` and `tx`.\n Data can be randomly shuffled to avoid ordering in the original data messing with the randomness of the minibatches.\n Example of use :\n for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):\n \n \"\"\"\n data_size = len(y)\n\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_y = y[shuffle_indices]\n shuffled_tx = tx[shuffle_indices]\n else:\n shuffled_y = y\n shuffled_tx = tx\n for batch_num in range(num_batches):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n if start_index != end_index:\n yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n\n\ndef stochastic_gradient_descent_mse(y, tx, initial_w, batch_size, max_iters, gamma):\n \"\"\"Stochastic gradient descent algorithm.\"\"\"\n n,d = tx.shape\n\n ws = [initial_w]\n initial_loss = compute_loss_mse(y, tx, initial_w)\n losses = [initial_loss]\n\n w = initial_w\n n_iter = 0\n\n for batch_y, batch_tx in batch_iter(y, tx, batch_size, max_iters):\n # Compute gradient for current batch\n gradient = compute_stoch_gradient_mse(batch_y, batch_tx, w)\n\n # Update model parameters\n w = w - gamma * gradient\n\n # Compute new loss\n loss = compute_loss_mse(y, tx, initial_w)\n\n # Store w and loss\n ws.append(w)\n losses.append(loss)\n\n print(\"Stochastic GD({bi}/{ti}): loss={l}, w0={w0}, w1={w1}\".format(\n bi=n_iter, ti=max_iters - 1, l=loss, w0=w[0], w1=w[1]))\n\n n_iter += 1\n\n return losses, ws","sub_path":"labs/ex02/template/stochastic_gradient_descent.py","file_name":"stochastic_gradient_descent.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"81725380","text":"import wikipedia\nimport re\nimport os\nimport csv\n\nclass Wikipedia:\n\tdef __init__(self):\n\t\tpass\n\n\tdef search(self, query):\n\t\t''' Wikipedia search function '''\n\t\t# try catch faulty queries, or queries resulting in disambiguation errors. \n\t\tprint('Wikipedia search in progress ...')\n\t\ttry: \n\t\t\tobj = wikipedia.page(wikipedia.search(query)[0])\n\t\t\ttext = obj.content\n\t\t\ttext = text.split('. ')\n\t\t\ttext = [[' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", sentence).split())] for sentence in text]\n\t\t\treturn text\n\t\texcept:\n\t\t\tprint('query error - try a more specific query')\n\t\t\tprint('possible that a wikipedia page pertaining to this query does not exist.')\n\t\tprint('Wikipedia search completed \\n')\n\t\treturn text\n\n\tdef buildCsv(self, wikiText, filename):\n\t\tprint('Writing %s ...' % (filename + '_cleaned' + '.csv'))\n\t\tif not os.path.exists('../data/'):\n\t\t\tos.makedirs('../data/')\n\n\t\tif not os.path.exists('../data/' + filename + '_cleaned' + '.csv'):\n\t\t\tf = open('../data/' + filename + '_cleaned' + '.csv', 'w')\n\t\t\tf.close()\n\n\t\twith open('../data/' + filename + '_cleaned' + '.csv', 'w', newline='') as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerows(wikiText)\n\t\tprint('%s written to /data \\n' % (filename + '_cleaned' + '.csv'))","sub_path":"src/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"477005048","text":"import sys\nclass Solution(object):\n def maxProfit(self, k, prices):\n \"\"\"\n :type k: int\n :type prices: List[int]\n :rtype: int\n \"\"\"\n n = len(prices)\n if k == 0 or n == 0: return 0\n if k < n / 2:\n sells = [0] * k\n holds = [-sys.maxint] * k\n # print n, k\n for p in prices:\n for j in range(k-1,0,-1):\n sells[j] = max(sells[j], holds[j] + p)\n holds[j] = max(holds[j], sells[j-1] - p)\n sells[0] = max(sells[0], holds[0] + p)\n holds[0] = max(holds[0], -p)\n return sells[-1]\n else:\n profit = 0\n for i in range(1, n):\n if prices[i] > prices[i-1]:\n profit += prices[i] - prices[i-1]\n return profit\n \n \n ","sub_path":"python/leetcode/state_machine/188_Best_Time_to_Buy_and_Sell_Stock_IV.py","file_name":"188_Best_Time_to_Buy_and_Sell_Stock_IV.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"426133752","text":"from app import createapp\nimport unittest\nimport json\n\nfrom app.api.v1.models.officemodels import OFFICES\n\n\nclass RoutesBaseTest(unittest.TestCase):\n def setUp(self):\n self.app = createapp()\n self.client = self.app.test_client()\n self.office1 = {\n \"type\": \"Member of Paliament\",\n \"name\": \"MP Nairobi\"\n }\n self.erroroffice = {\n }\n # tear down test\n\n def tearDown(self):\n \"\"\"Final cleanup after tests run\"\"\"\n self.app.testing = False\n\n\nclass TestOfficesEndPoints(RoutesBaseTest):\n\n def test_view_all_offices(self):\n response = self.client.get(\"api/v1/offices\")\n self.assertEqual(response.status_code, 200)\n result = json.loads(response.data.decode('utf-8'))\n self.assertEqual(result[\"data\"], [{\n \"name\": \"dsd\",\n \"type\": \"trtr\",\n \"id\": 23\n }])\n self.assertEqual(result[\"status\"], 200)\n\n def test_view_specific_undefined_office(self):\n response = self.client.get(\"api/v1/offices/12\")\n result = json.loads(response.data.decode(\"utf-8\"))\n self.assertEqual(result[\"status\"], 404)\n\n def test_create_office(self):\n res = self.client.post(\"api/v1/offices\", data=json.dumps({\n \"name\": \"dsd\",\n \"type\": \"trtr\",\n \"id\": 23\n }), content_type=\"application/json\")\n result = json.loads(res.data.decode(\"utf-8\"))\n self.assertEqual(result[\"status\"], 201)\n self.assertEqual(result[\"data\"], [{'id': 23, 'name':\n 'dsd', 'type': 'trtr'}])\n\n def test_create_office_with_bad_request(self):\n res = self.client.post(\"api/v1/offices\", data=json.dumps({\n \"name\": \"dsd\",\n \"type\": \"trtr\"\n }), content_type=\"application/json\")\n result = json.loads(res.data.decode(\"utf-8\"))\n self.assertEqual(result[\"status\"], 400)\n self.assertEqual(result['error'], 'Must provide id, name and type')\n\n def test_edit_office_not_found(self):\n response = self.client.get(\"api/v1/offices\")\n self.assertEqual(response.status_code, 200)\n result = json.loads(response.data.decode('utf-8'))\n self.assertEqual(result[\"status\"], 200)\n self.assertEqual(result[\"data\"], [{'id': 23, 'name':\n 'dsd', 'type': 'trtr'}])\n","sub_path":"tests/test_office_routes.py","file_name":"test_office_routes.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"605214437","text":"r\"\"\"Test `lmp.util._dataset._preprocess_wiki_tokens`.\n\nUsage:\n python -m unittest test.lmp.util._dataset.test_preprocess_wiki_tokens\n\"\"\"\n\n# built-in modules\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport inspect\nimport math\nimport os\nimport unittest\n\n# self-made modules\n\nimport lmp.path\nimport lmp.util\n\n\n# pylint: disable=W0212\nclass TestPreprocessWikiTokens(unittest.TestCase):\n r\"\"\"Test case of `lmp.util._dataset._preprocess_news_collection`\"\"\"\n\n def test_signature(self):\n r\"\"\"Ensure signature consistency.\"\"\"\n msg = 'Inconsistent method signature.'\n self.assertEqual(\n inspect.signature(lmp.util._dataset._preprocess_wiki_tokens),\n inspect.Signature(\n parameters=[\n inspect.Parameter(\n name='split',\n kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,\n annotation=str,\n default=inspect.Parameter.empty\n )\n ],\n return_annotation=lmp.dataset.LanguageModelDataset\n ),\n msg=msg\n )\n\n def test_invaild_input_split(self):\n r\"\"\"Raise exception when input `split` is invalid.\"\"\"\n msg1 = (\n 'Must raise `TypeError` or `FileNotFoundError` when input `split` '\n 'is invaild.'\n )\n msg2 = 'Inconsistent error message.'\n examples = (\n False, True, 0, 1, -1, 0.0, 1.0, math.nan, -math.nan, math.inf,\n -math.inf, 0j, 1j, b'', (), [], {}, set(), object(), lambda x: x,\n type, None, NotImplemented, ..., 'NotExistFile'\n )\n\n for invaild_input in examples:\n with self.assertRaises(\n (FileNotFoundError, TypeError),\n msg=msg1\n ) as ctx_man:\n lmp.util._dataset._preprocess_wiki_tokens(invaild_input)\n\n if isinstance(ctx_man.exception, TypeError):\n self.assertEqual(\n ctx_man.exception.args[0],\n '`split` must be an instance of `str`.',\n msg=msg2\n )\n else:\n file_path = os.path.join(\n f'{lmp.path.DATA_PATH}',\n f'wiki.{invaild_input}.tokens'\n )\n self.assertEqual(\n ctx_man.exception.args[0],\n f'file {file_path} does not exist.',\n msg=msg2\n )\n\n def test_return_type(self):\n r\"\"\"Return `lmp.dataset.LanguageModelDataset`\"\"\"\n msg = 'Must return `lmp.dataset.LanguageModelDataset`.'\n split_parameter = ('train', 'valid', 'test')\n\n for split in split_parameter:\n dataset = lmp.util._dataset._preprocess_wiki_tokens(split)\n self.assertIsInstance(\n dataset,\n lmp.dataset.LanguageModelDataset,\n msg=msg\n )\n# pylint: enable=W0212\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/lmp/util/_dataset/test_preprocess_wiki_tokens.py","file_name":"test_preprocess_wiki_tokens.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"}
+{"seq_id":"459862798","text":"from feeds import Events_Feed, Topics_Feed, Posts_Feed\nfrom django.conf.urls.defaults import patterns, url\n\nevent_patterns = patterns('core.views',\n url(r'^$', 'event_list', name='event_list'),\n url(r'^join/?$', 'join_event'),\n url(r'^checkin$', 'checkin', name='event_checkin'),\n url(r'^(?P\\d+)$', 'event', name='event'),\n)\n\ntopic_patterns = patterns('core.views',\n url(r'^$', 'topic_list', name='topic_list'),\n url(r'^(?P\\d+)$', 'topic', name='topic'),\n url(r'^new/?$', 'submit_topic', name='submit_new_topic'),\n url(r'^(?P\\d+)/edit/?$', 'edit_topic', name='edit_topic'),\n url(r'^(?P\\d+)/vote$', 'vote'),\n url(r'^(?P\\d+)/votes$', 'votes_for_topic', name='vote_for_topic'),\n)\n\nfeed_patterns = patterns('core.views',\n url(r'^event/?$', Events_Feed(), name=\"feed_events\"),\n url(r'^topic/?$', Topics_Feed(), name=\"feed_topics\"),\n url(r'^post/?$', Posts_Feed(), name=\"feed_posts\"),\n)\n\npost_patterns = patterns('core.views',\n url(r'^$', 'list_post', name='list_post'),\n url(r'^(?P\\d+)$', 'view_post', name='view_post'),\n url(r'^(?P.*)$', 'view_post_by_name', name='view_post_by_name'),\n)\n\nwordpress_redirect_patterns = patterns('core.views',\n url(r'^(?P.*)$', 'redirect_wordpress_post', name='redirect_wordpress_post'),\n)\n\nabout_patterns = patterns('django.views.generic.simple',\n url(r'^/?$', 'direct_to_template', {'template': 'core/about.html', 'extra_context':{'tab':'about'}}, name=\"about\"),\n)\n","sub_path":"apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"80469178","text":"#sum function definition \n#Output: Sum first element with each element of seq = [0,1, 2, 3, 4] Sum= 10\ndef sum(seq):\n if not seq:\n return 0\n else:\n return seq[0] + sum(seq[1:])\n\n#Fold Right function definition. if the list seq ist empty the initial value will be init.\n#if list is not empty the funtion output will be: foldr f z (x:xs) = f x (foldr f z xs)\ndef foldr(func, init, seq):\n if not seq:\n return init\n else:\n return func(seq[0], foldr(func, init, seq[1:]))\n\n#Output Sum using the funktion foldr \ndef sum_with_foldr(seq):\n return foldr(lambda seqval, acc: seqval + acc, 0, seq)\n\n\n\n#------------------------------ Testing --------------------------------#\n\nimport unittest\n\n\nclass TestFold(unittest.TestCase):\n def test_sum(self):\n self.assertEqual(sum([0,1, 2, 3, 4]), 10)\n self.assertEqual(sum([12]), 12)\n self.assertEqual(sum([]), 0)\n\n self.assertEqual(sum_with_foldr([0, 1, 2, 3, 4]), 10)\n self.assertEqual(sum_with_foldr([12]), 12)\n self.assertEqual(sum_with_foldr([]), 0)\n\n \nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"fold_implementation.py","file_name":"fold_implementation.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"65548508","text":"import os\nimport re\nimport subprocess\nimport argparse\nimport pathlib\n\nparser = argparse.ArgumentParser()\nparser.add_argument('ipynb_path', type=str)\nargs = parser.parse_args()\n\n\n'''\nInput paths\n'''\nthis_script_dir: str = os.path.abspath(pathlib.Path(__file__).parent.resolve())\nipynb_file_name: str = os.path.basename(args.ipynb_path)\nconfig_script_path: str = os.path.join(this_script_dir, 'nbconvert_config.py')\n'''\nOutput paths\n'''\noutput_abs_dir: str = os.path.abspath(pathlib.Path(args.ipynb_path).parent.resolve()) # '/Users/Desktop/_posts/YYYY-MM-DD-post-name/'\noutput_relative_dir: str = '/'.join(args.ipynb_path.split('/')[:-1]) # '_posts/YYYY-MM-DD-post-name/'\noutput_image_abs_dir: str = os.path.abspath(os.path.join(output_abs_dir, 'markdown_images/')) # '/Users/Desktop/_posts/YYYY-MM-DD-post-name/markdown_images/'\noutput_image_relative_dir: str = os.path.join(output_relative_dir, 'markdown_images/') # '_posts/YYYY-MM-DD-post-name/markdown_images/'\nbase_file_name_with_date_prefix: str = ipynb_file_name.lower().replace(' ', '-').replace('.ipynb', '') # 'YYYY-MM-DD-post-name'\nbase_file_name: str = re.sub(r'^\\d{4}\\-\\d{2}\\-\\d{2}\\-', '', base_file_name_with_date_prefix) # 'YYYY-MM-DD-post-name' => 'post-name'\noutput_markdown_abs_path: str = os.path.join(output_abs_dir, base_file_name + '.md') # '/Users/Desktop/_posts/YYYY-MM-DD-post-name/post-name.md'\njekyll_markdown_abs_path: str = os.path.join(output_abs_dir, base_file_name_with_date_prefix + '.md') # '/Users/Desktop/_posts/YYYY-MM-DD-post-name/YYYY-MM-DD-post-name.md'\n\nprint(f\"Converting {ipynb_file_name} => {os.path.basename(jekyll_markdown_abs_path)}\")\nsubprocess.run([\"jupyter\", \"nbconvert\", args.ipynb_path, \"--to\", \"markdown\", \"--config\", config_script_path])\n\n# Clean up markdown\nwith open(output_markdown_abs_path, 'r') as fd:\n md = fd.read()\nmd_clean = md\n\n# HTML cleanup\n# Remove %s'\n ''\n '