diff --git "a/1145.jsonl" "b/1145.jsonl" new file mode 100644--- /dev/null +++ "b/1145.jsonl" @@ -0,0 +1,789 @@ +{"seq_id":"413937355","text":"from donor_models import donor\nfrom donor_models import donor_collection\nfrom donor_models import donor_methods\nfrom test_mailroom_oo import tests\n\ndef create_donor_data():\n d1 = donor(\"Mark Zuckerberg\")\n d1.new_donation(3245)\n d1.new_donation(48372)\n d2 = donor(\"Bill Gates\")\n d2.new_donation(43454)\n d2.new_donation(444)\n d2.new_donation(23444)\n a = donor_collection(d1.return_list())\n a.add_donor(d2.return_list())\n return a\n#initilize donor data as a\na = create_donor_data()\n#load initialized donor list\nb = a.donor_list\n#io for mailroom\nsentinal = True\nwhile sentinal == True:\n choice = input(\"1. Print Donor Report \\n2. Write Letters\\n3. Initiate unit tests\\n4. Close out\\n\"\"What would you like to do?: \")\n if choice == \"1\":\n a.report_writer()\n elif choice == \"2\":\n report_choice = input(\"1. Print single donor letter\\n2. Print all donor letters\\n\"\"What would you like to do?: \")\n if report_choice == \"1\":\n donor_methods.list_donors(b)\n donor_choice = input(\"Which donor would you like to choose? \")\n donor_methods.write_letter(donor_methods.search_list(b, donor_choice))\n elif report_choice == \"2\":\n for i in b:\n donor_methods.write_letter(i)\n elif choice == \"3\":\n tests()\n elif choice == \"4\":\n break\n\n","sub_path":"students/Tommy Aguilu/cli_main.py","file_name":"cli_main.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"328892195","text":"# This file is part of the bapsflib package, a Python toolkit for the\n# BaPSF group at UCLA.\n#\n# http://plasma.physics.ucla.edu/\n#\n# Copyright 2017-2018 Erik T. Everson and contributors\n#\n# License: Standard 3-clause BSD; see \"LICENSES/LICENSE.txt\" for full\n# license terms and contributor agreement.\n#\nimport h5py\n\nfrom .digi_template import hdfMap_digi_template\n\n\nclass hdfMap_digi_siscrate(hdfMap_digi_template):\n \"\"\"\n Mapping class for the 'SIS crate' digitizer.\n \"\"\"\n def __init__(self, digi_group):\n \"\"\"\n :param digi_group: the HDF5 digitizer group\n :type digi_group: :class:`h5py.Group`\n \"\"\"\n # initialize\n hdfMap_digi_template.__init__(self, digi_group)\n\n # populate self.configs\n self._build_configs()\n\n @property\n def shotnum_field(self):\n \"\"\"Field name for shot number column in header dataset\"\"\"\n return 'Shot number'\n\n @property\n def _predefined_adc(self):\n \"\"\"\n Predefined (known) adc's for digitizer 'SIS crate'\n\n (See\n :attr:`~.digi_template.hdfMap_digi_template._predefined_adc`\n of the base class for details)\n \"\"\"\n return ['SIS 3302', 'SIS 3305']\n\n def _build_configs(self):\n \"\"\"\n Populates :attr:`configs` dictionary\n\n (See :meth:`~.digi_template.hdfMap_digi_template._build_configs`\n and :attr:`~.digi_template.hdfMap_digi_template.configs`\n of the base class for details)\n \"\"\"\n # self.configs is initialized in the template\n\n # collect digi_group's dataset names and sub-group names\n subgroup_names = []\n dataset_names = []\n for key in self.group.keys():\n if isinstance(self.group[key], h5py.Dataset):\n dataset_names.append(key)\n if isinstance(self.group[key], h5py.Group):\n subgroup_names.append(key)\n\n # populate self.configs\n for name in subgroup_names:\n is_config, config_name = self._parse_config_name(name)\n if is_config:\n # initialize configuration name in the config dict\n self.configs[config_name] = {}\n\n # determine if config is active\n self.configs[config_name]['active'] = \\\n self._is_config_active(config_name, dataset_names)\n\n # assign active adc's to the configuration\n self.configs[config_name]['adc'] = \\\n self._find_config_adc(self.group[name])\n\n # add 'group name'\n self.configs[config_name]['group name'] = name\n\n # add 'group path'\n self.configs[config_name]['group path'] = \\\n self.group[name].name\n\n # add adc info\n for adc in self.configs[config_name]['adc']:\n self.configs[config_name][adc] = \\\n self._adc_info(adc, self.group[name])\n\n @staticmethod\n def _parse_config_name(name):\n \"\"\"\n Parses :code:`name` to determine the digitizer configuration\n name. A configuration group name follows the format:\n\n | `config_name`\n\n (See\n :meth:`~.digi_template.hdfMap_digi_template.parse_config_name`\n of the base class for details)\n \"\"\"\n return True, name\n\n @staticmethod\n def _is_config_active(config_name, dataset_names):\n \"\"\"\n Determines if :code:`config_name` is an active digitizer\n configuration.\n\n (See\n :meth:`~.digi_template.hdfMap_digi_template._is_config_active`\n of the base class for details)\n \"\"\"\n active = False\n\n # if config_name is in any dataset name then config_name is\n # active\n for name in dataset_names:\n if config_name in name:\n active = True\n break\n\n return active\n\n def _adc_info(self, adc_name, config_group):\n \"\"\"\n Gathers information on the adc configuration.\n\n (See :meth:`~.digi_template.hdfMap_digi_template._adc_info`\n of the base class for details)\n \"\"\"\n # digitizer 'Raw data + config/SIS crate' has two adc's,\n # SIS 3302 and SIS 3305\n # adc_info = ( int, # board\n # [int, ], # channels\n # {'bit': int, # bit resolution\n # 'sample rate': (float, 'unit'),\n # 'shot average (software)': int,\n # 'sample average (hardware)': int})\n adc_info = []\n\n # build adc_info\n if adc_name == 'SIS 3302':\n # for SIS 3302\n conns = self._find_adc_connections('SIS 3302',\n config_group)\n for conn in conns:\n # define 'bit' and 'sample rate'\n conn[2]['bit'] = 16\n conn[2]['sample rate'] = (100.0, 'MHz')\n\n # keys 'shot average (software)' and\n # 'sample average (hardware)' are added in\n # self.__find_crate_connections\n\n # append info\n adc_info.append(conn)\n elif adc_name == 'SIS 3305':\n # note: sample rate for 'SIS 3305' depends on how\n # diagnostics are connected to the DAQ. Thus, assignment is\n # left to method self.__find_crate_connections.\n conns = self._find_adc_connections('SIS 3305',\n config_group)\n for conn in conns:\n # define 'bit' and 'sample rate'\n # - sample rate is defined in __find_adc_connections\n conn[2]['bit'] = 10\n\n # keys 'shot average (software)' and\n # 'sample average (hardware)' are added in\n # self.__find_crate_connections\n\n # append info\n adc_info.append(conn)\n else:\n adc_info.append((None, [None],\n {'bit': None,\n 'sample rate': (None, 'MHz'),\n 'shot average (software)': None,\n 'sample average (hardware)': None}))\n\n return adc_info\n\n @staticmethod\n def _find_config_adc(config_group):\n \"\"\"\n Determines active adc's used in the digitizer configuration.\n\n (See\n :meth:`~.digi_template.hdfMap_digi_template._find_config_adc`\n of the base class for details)\n \"\"\"\n active_adc = []\n adc_types = list(config_group.attrs['SIS crate board types'])\n if 2 in adc_types:\n active_adc.append('SIS 3302')\n if 3 in adc_types:\n active_adc.append('SIS 3305')\n\n return active_adc\n\n def _find_adc_connections(self, adc_name, config_group):\n \"\"\"\n Determines active connections on the adc.\n\n (See\n :meth:`~.digi_template.hdfMap_digi_template._find_adc_connections`\n of the base class for details)\n \"\"\"\n # initialize conn, brd, and chs\n # conn = list of connections\n # brd = board number\n # chs = list of connect channels of board brd\n #\n conn = []\n brd = None\n chs = []\n cmode = (None, 'GHz')\n\n # Build a tuple relating the adc name (adc), adc slot number\n # (slot), associated data configuration unique identifier index\n # (index), and board number (brd)\n active_slots = config_group.attrs['SIS crate slot numbers']\n config_indices = config_group.attrs['SIS crate config indices']\n info_list = []\n for slot, index in zip(active_slots, config_indices):\n if slot != 3:\n brd, adc = self.slot_to_brd(slot)\n info_list.append((slot, index, brd, adc))\n\n # filter out calibration groups and only gather configuration\n # groups\n sis3302_gnames = []\n sis3305_gnames = []\n for key in config_group.keys():\n if 'configurations' in key:\n if '3302' in key:\n sis3302_gnames.append(key)\n elif '3305' in key:\n sis3305_gnames.append(key)\n\n # Determine connected (brd, ch) combinations\n # TODO: make this section more efficient\n if adc_name == 'SIS 3302':\n for name in sis3302_gnames:\n\n # Find board number\n config_index = int(name[-2])\n brd = None\n for slot, index, board, adc in info_list:\n if '3302' in adc and config_index == index:\n brd = board\n break\n\n # Find active channels\n chs = []\n for key in config_group[name].attrs:\n if 'Enable' in key:\n tf_str = config_group[name].attrs[key]\n if 'TRUE' in tf_str.decode('utf-8'):\n chs.append(int(key[-1]))\n\n # determine 'shot average (software)'\n if 'Shot averaging (software)' \\\n in config_group[name].attrs:\n shtave = config_group[name].attrs[\n 'Shot averaging (software)']\n if shtave == 0 or shtave == 1:\n shtave = None\n else:\n shtave = None\n\n # determine 'sample average (hardware)'\n # - the HDF5 attribute is the power to 2\n # - So, a hardware sample of 5 actually means the number\n # of points sampled is 2^5\n if 'Sample averaging (hardware)'\\\n in config_group[name].attrs:\n splave = config_group[name].attrs[\n 'Sample averaging (hardware)']\n if splave == 0:\n splave = None\n else:\n splave = 2 ** splave\n else:\n splave = None\n\n # build subconn tuple with connected board, channels\n # and acquisition parameters\n subconn = (brd, chs,\n {'bit': None,\n 'sample rate': (None, 'MHz'),\n 'shot average (software)': shtave,\n 'sample average (hardware)': splave})\n if brd is not None:\n # This counters a bazaar occurrence in the\n # 'SIS crate' configuration where there's more\n # configuration subgroups in config_group than there\n # are listed in\n # config_group.attrs['SIS crate config indices']\n conn.append(subconn)\n\n # reset values\n # brd = None\n # chs = []\n\n elif adc_name == 'SIS 3305':\n for name in sis3305_gnames:\n\n # Find board number\n config_index = int(name[-2])\n brd = None\n for slot, index, board, adc in info_list:\n if '3305' in adc and config_index == index:\n brd = board\n break\n\n # Find active channels and clock mode\n chs = []\n for key in config_group[name].attrs.keys():\n # channels\n if 'Enable' in key:\n if 'FPGA 1' in key:\n tf_str = config_group[name].attrs[key]\n if 'TRUE' in tf_str.decode('utf-8'):\n chs.append(int(key[-1]))\n elif 'FPGA 2' in key:\n tf_str = config_group[name].attrs[key]\n if 'TRUE' in tf_str.decode('utf-8'):\n chs.append(int(key[-1]) + 4)\n\n # clock mode\n # the clock state of 3305 is stored in the 'channel\n # mode' attribute. The values follow\n # 0 = 1.25 GHz\n # 1 = 2.5 GHz\n # 2 = 5.0 GHz\n cmodes = [(1.25, 'GHz'),\n (2.5, 'GHz'),\n (5.0, 'GHz')]\n if 'Channel mode' in key:\n cmode = cmodes[config_group[name].attrs[key]]\n\n # determine 'shot average (software)'\n if 'Shot averaging (software)' \\\n in config_group[name].attrs:\n shtave = config_group[name].attrs[\n 'Shot averaging (software)']\n if shtave == 0 or shtave == 1:\n shtave = None\n else:\n shtave = None\n\n # determine 'sample average (hardware)'\n # - SIS 3305 has no hardware sampling feature\n splave = None\n\n # build subconn tuple with connected board, channels\n # and acquisition parameters\n subconn = (brd, chs,\n {'bit': None,\n 'sample rate': cmode,\n 'shot average (software)': shtave,\n 'sample average (hardware)': splave})\n if brd is not None:\n conn.append(subconn)\n\n # reset values\n cmode = (None, 'GHz')\n\n return conn\n\n def construct_dataset_name(self, board, channel,\n config_name=None, adc=None,\n return_info=False, silent=False):\n \"\"\"\n Constructs the HDF5 dataset name based on inputs. The dataset\n name follows the format:\n\n | `config_name` [Slot `#`: SIS `####` FPGA `#` ch `#`]\n\n (See\n :meth:`~.digi_template.hdfMap_digi_template.construct_dataset_name`\n of the base class for details)\n \"\"\"\n # TODO: Replace Warnings with proper error handling\n\n # initiate warning string\n warn_str = ''\n\n # Condition config_name\n # - if config_name is not specified then the 'active' config\n # is sought out\n if config_name is None:\n found = 0\n for name in self.configs:\n if self.configs[name]['active'] is True:\n config_name = name\n found += 1\n\n if found == 1:\n warn_str = ('** Warning: config_name not specified, '\n 'assuming ' + config_name + '.')\n elif found >= 1:\n # raise Exception(\"Too many active digitizer \"\n # \"configurations detected. Currently \"\n # \"do not know how to handle.\")\n raise ValueError(\"There are multiple active digitizer\"\n \"configurations. User must specify\"\n \"config_name keyword.\")\n else:\n raise ValueError(\"No active digitizer configuration \"\n \"detected.\")\n elif config_name not in self.configs:\n # config_name must be a known configuration\n raise ValueError('Invalid configuration name given.')\n elif self.configs[config_name]['active'] is False:\n raise ValueError('Specified configuration name is not '\n 'active.')\n\n # Condition adc\n # - if adc is not specified then the slow adc '3302' is assumed\n # or, if 3305 is the only active adc, then it is assumed\n # - self.__config_crates() always adds 'SIS 3302' first. If\n # '3302' is not active then the list will only contain '3305'.\n if adc is None:\n adc = self.configs[config_name]['adc'][0]\n warn_str += ('\\n** Warning: No adc specified, so assuming '\n + adc + '.')\n elif adc not in self.configs[config_name]['adc']:\n raise ValueError(\n 'Specified adc ({}) is not in specified '.format(adc)\n + 'configuration ({}).'.format(config_name))\n\n # search if (board, channel) combo is connected\n bc_valid = False\n d_info = None\n for brd, chs, extras in self.configs[config_name][adc]:\n if board == brd:\n if channel in chs:\n bc_valid = True\n\n # save adc settings for return if requested\n d_info = extras\n d_info['adc'] = adc\n d_info['configuration name'] = config_name\n d_info['digitizer'] = self.info['group name']\n\n # (board, channel) combo must be active\n if bc_valid is False:\n raise ValueError('Specified (board, channel) is not valid')\n\n # checks passed, build dataset_name\n if '3302' in adc:\n slot = self.brd_to_slot(board, 'SIS 3302')\n dataset_name = '{0} [Slot {1}: SIS 3302 ch {2}]'.format(\n config_name, slot, channel)\n elif '3305' in adc:\n slot = self.brd_to_slot(board, 'SIS 3305')\n if channel in range(1, 5):\n fpga = 1\n ch = channel\n else:\n fpga = 2\n ch = channel - 4\n\n dataset_name = '{0} [Slot {1}: '.format(config_name, slot) \\\n + 'SIS 3305 FPGA {0} ch {1}]'.format(fpga,\n ch)\n else:\n raise ValueError('We have a problem! Somehow adc '\n + '({}) is not known.'.format(adc))\n\n # print warnings\n if not silent:\n print(warn_str)\n\n if return_info is True:\n return dataset_name, d_info\n else:\n return dataset_name\n\n def construct_header_dataset_name(self, board, channel, **kwargs):\n \"\"\"\"Name of header dataset\"\"\"\n # ensure return_info kwarg is always False\n kwargs['return_info'] = False\n\n # get dataset naem\n dset_name = self.construct_dataset_name(board, channel,\n **kwargs)\n # build and return header name\n dheader_name = dset_name + ' headers'\n return dheader_name\n\n @staticmethod\n def slot_to_brd(slot):\n \"\"\"\n Translates the 'SIS crate` slot number to the board number and\n adc.\n\n :param int slot: digitizer slot number\n :return: (board number, adc name)\n :rtype: (int, str)\n \"\"\"\n sb_map = {5: (1, 'SIS 3302'),\n 7: (2, 'SIS 3302'),\n 9: (3, 'SIS 3302'),\n 11: (4, 'SIS 3302'),\n 13: (1, 'SIS 3305'),\n 15: (2, 'SIS 3305')}\n return sb_map[slot]\n\n @staticmethod\n def brd_to_slot(brd, adc):\n \"\"\"\n Translates board number and adc name to the digitizer slot\n number.\n\n :param int brd: board number\n :param str adc: adc name\n :return: digitizer slot number\n :rtype: int\n \"\"\"\n bs_map = {(1, 'SIS 3302'): 5,\n (2, 'SIS 3302'): 7,\n (3, 'SIS 3302'): 9,\n (4, 'SIS 3302'): 11,\n (1, 'SIS 3305'): 13,\n (2, 'SIS 3305'): 15}\n return bs_map[(brd, adc)]\n","sub_path":"bapsflib/lapdhdf/map_digitizers/siscrate.py","file_name":"siscrate.py","file_ext":"py","file_size_in_byte":19665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"451185901","text":"import pandas as pd\nimport numpy as np\n\nfrom alf_common.Constants.UpdateActions import \\\n updateActions\nfrom alf_common.Constants.Sides import sides\nfrom proxent_utils.logger import BaseLogger\n\n\nclass TopExistsEnum:\n UNKNOWN = 0 # Only for the initial ambiguous updates\n EXISTS = 1 # Top Order Exists with some probability > 0\n DOES_NOT_EXIST = 2 # Top Order Does Not Exist\n\n\nclass AggressionState:\n LOCAL_MULTI = 1 # Aggression trade happens in local book with\n # multiple trade details\n IMP_MULTI = 2 # Aggression happens due to implied out trade with multiple\n # trade details\n LOCAL_REDUCE_TOP = 3 # Reduce the top quantity from the local book due to\n # an aggression in the local book\n IMP_REDUCE_TOP = 4 # Reduce the top quantity from the implied book due to\n # an aggression in the implied book\n NO_AGGRESSION = 0 # No aggression has happened. Top tracker is instantiated\n # with this state\n\n\nclass PrevBook:\n def __init__(self):\n self.cont = True # true if there is no trade updates between books\n self.qty = None # Quantity on the level\n self.numOrders = None # Num of orders on the level\n\n\n# Listens to tick and book updates\n# Figures out the bid/ask tracker\n# Processes the update through TopTracker api method update_digest\n\nclass ConsolidatedTopTracker:\n def __init__(self):\n self.bidTracker = TopTracker(sides['Bid'])\n self.askTracker = TopTracker(sides['Offer'])\n self.tradeActions = [updateActions['TradeSummary'],\n updateActions['TradeDetail']]\n\n def process_tick_and_book(self, tick, book, timestamp):\n level = tick[\"level\"]\n updateAction = tick[\"updateAction\"]\n side = tick[\"side\"]\n if updateAction == updateActions[\"TradeDetailAgg\"] or \\\n (updateAction not in self.tradeActions and level != 1):\n return []\n\n if updateAction in self.tradeActions:\n tradePrice = tick[\"price\"]\n if tradePrice == self.askTracker.top_price:\n tracker = self.askTracker\n elif tradePrice == self.bidTracker.top_price:\n tracker = self.bidTracker\n else:\n return []\n else:\n tracker = self.bidTracker if side == sides['Bid'] else \\\n self.askTracker\n\n return tracker.update_tick_and_book(\n updateAction, tick, book, timestamp)\n\n # Listens to ticks and book updates and processes them\n # argument info is the output of\n # inst.mergeLoadedBooksWithTrades(\n # bookType=\"Outright\", includeTicks=True).iterrows()\n def process_update(self, info):\n row = info[1]\n level = row.level\n\n # only level 1 and trade updates are relevant\n if level != 1 and level != 0:\n return []\n\n update_actions = row.updateAction\n side = row.side\n trade_price = row.tradePrice\n\n if update_actions == updateActions['TradeSummary'] \\\n or update_actions == updateActions['TradeDetail']:\n if trade_price == self.askTracker.top_price:\n tracker = self.askTracker\n elif trade_price == self.bidTracker.top_price:\n tracker = self.bidTracker\n else:\n return []\n else:\n tracker = self.bidTracker if side == sides['Bid'] else \\\n self.askTracker\n\n return tracker.update_digest(update_actions, info)\n\n def get_status(self, side):\n if side == sides['Bid']:\n return self.bidTracker.report_status()\n elif side == sides['Offer']:\n return self.askTracker.report_status()\n\n def get_simple_status_dict(self, side):\n if side == sides['Bid']:\n return self.bidTracker.report_simple_status_dict()\n elif side == sides['Offer']:\n return self.askTracker.report_simple_status_dict()\n\n\nclass TopTracker(BaseLogger):\n def __init__(self, side):\n self.top_exists = TopExistsEnum.UNKNOWN\n self.side = side\n self.previous_book = PrevBook()\n self._initialize_helper()\n\n def close_top(self, time):\n self.end_time = time\n self.top_exists = TopExistsEnum.DOES_NOT_EXIST\n rv = {\n \"creation_time\": self.create_time,\n \"end_time\": self.end_time,\n \"side\": self.side,\n \"top_price\": self.top_price,\n \"initial_quantity\": self.initial_quantity,\n \"quantity\": self.qty,\n \"potentially_cancelled\": self.potentially_cancelled,\n \"revised\": self.revised,\n \"self_match_protection\": np.nan\n }\n self._initialize_helper()\n return rv\n\n def _initialize_helper(self):\n self.create_time = None\n self.end_time = None\n self.potentially_cancelled = False\n self.initial_quantity = None\n self.qty = None\n self.top_price = None\n self.revised = False\n self.aggression_against_top = AggressionState.NO_AGGRESSION\n\n def report_status(self):\n \"\"\"\n if top order is known to exist or Unknown\n report a tuple of the following items:\n 1.time at which the top is created\n 2.the side (bid/ask) which the top order belongs to\n 3.the price at which the top order is created\n 4.the initial qty of the top order\n 5.the current estimated qty of the top order\n 6.whether there have been cancellation of the exact remaining size\n of the top order.\n 7.whether they have been order revision on the level (not necessarily\n the top order)\n\n \"\"\"\n if self.top_exists == TopExistsEnum.DOES_NOT_EXIST:\n return None\n else:\n return {\n \"creation_time\": self.create_time,\n \"side\": self.side,\n \"top_price\": self.top_price,\n \"initial_quantity\": self.initial_quantity,\n \"quantity\": self.qty,\n \"potentially_cancelled\": self.potentially_cancelled,\n \"revised\": self.revised\n }\n\n def report_simple_status_dict(self):\n rv = {\"status\": self.top_exists}\n if self.top_exists == TopExistsEnum.DOES_NOT_EXIST:\n return rv\n else:\n rv[\"price\"] = self.top_price\n rv[\"qty\"] = self.qty\n rv[\"potentiallyCancelled\"] = self.potentially_cancelled\n return rv\n\n def top_overshadow(self, time):\n if self.top_exists == TopExistsEnum.EXISTS:\n if self.qty > 0:\n self.qty = 0\n return self.close_top(time)\n\n def top_create(self, qty, price, time):\n self.create_time = time\n self.top_exists = TopExistsEnum.EXISTS\n self.qty = qty\n self.initial_quantity = qty\n self.top_price = price\n\n def price_changed_unexpectedly(self, price, time):\n if self.top_exists == TopExistsEnum.EXISTS and price != self.top_price:\n return True\n return False\n\n def check_cancels_and_revisions(self, currend_num_orders, current_quantity,\n previous_num_orders,\n previous_quantity, cont, time):\n ret = None\n if self.top_exists == TopExistsEnum.EXISTS:\n if currend_num_orders == previous_num_orders and cont:\n if currend_num_orders == 1:\n if current_quantity - previous_quantity > 0:\n self.qty = 0\n ret = self.close_top(time)\n else:\n self.qty += current_quantity - previous_quantity\n self.revised = True\n elif (currend_num_orders == previous_num_orders - 1) and \\\n (previous_quantity - current_quantity) == self.qty:\n self.potentially_cancelled = True\n return ret\n\n def level_wipe_out(self, last_l1_qty, time):\n if self.top_exists == TopExistsEnum.EXISTS:\n diff = self.qty - last_l1_qty\n if diff == 0 or self.qty == 0:\n self.qty = 0\n else:\n # Note! here qty is set to the diff for easier debugging.\n # This may sometimes lead to unexpected negative values in\n # (only) the output table\n \n self.logger.warn(\"Level WIPE OUT: \"\n \"Difference between the current estimated\"\n \"top quantity and quantity on the level is {}\"\n \"\".format(diff))\n self.qty = diff\n return self.close_top(time)\n\n def reduce_top(self, trade_quantity, time):\n if self.top_exists == TopExistsEnum.EXISTS:\n self.qty -= trade_quantity\n if self.qty <= 0:\n return self.close_top(time)\n\n def multi_end(self, trade_quantity, time):\n if self.top_exists == TopExistsEnum.EXISTS:\n diff = self.qty - trade_quantity\n if diff == 0:\n if self.potentially_cancelled == False:\n self.qty = 0\n return self.close_top(time)\n\n def update_digest(self, update_action, info):\n # assumes info is the output of\n # inst.mergeLoadedBooksWithTrades(\n # bookType=\"Outright\", includeTicks=True).iterrows()\n\n \"\"\"\n either return an empty list\n return a list of the following items:\n 1. topCreationTime\",\n 2. topEndTime\",\n 3. side(bid/ask) to which the top order belongs\n 4. price at which the top order is created\n 5. initial Qty of the top order\n 6. the final unaccounted qty of the top order\n (note that level_wipe_out returns the diff value)\n 7. whether the top order has been potentially cancelled\n 8. whether there have been order revision on the level\n (not necessarily the top)\n 9. the possibility of self match protection (placeholder. Not developed)\n\n \"\"\"\n time = info[0]\n row = info[1]\n size = row.qty\n price = row.price\n aggside = row.tradeAggSide\n trade_num_orders = row.tradeNumOrders\n tradeQty = row.tradeQty\n if self.side == sides['Bid']:\n qty = row.bidQty_1\n num_orders = row.bidOrders_1\n else:\n qty = row.askQty_1\n num_orders = row.askOrders_1\n\n return self._update(update_action, time, size, price, qty, num_orders,\n aggside, trade_num_orders, tradeQty)\n\n def update_tick_and_book(self, update_action, tick, book, timestamp):\n if self.side == sides['Bid']:\n qty = book[\"bidQty_1\"]\n num_orders = book[\"bidOrders_1\"]\n else:\n qty = book[\"askQty_1\"]\n num_orders = book[\"askOrders_1\"]\n\n return self._update(update_action, timestamp,\n tick[\"qty\"], tick[\"price\"], qty, num_orders,\n tick[\"side\"], tick[\"numOrders\"], tick[\"qty\"])\n\n def _update(self, update_action, time, size, price, qty, num_orders,\n aggside, trade_num_orders, trade_quantity):\n current_l1_qty = qty\n current_l1_orders = num_orders\n\n to_return = None\n\n if update_action == updateActions[\"New\"]:\n to_return = self.top_overshadow(time)\n self.top_create(size, price, time)\n\n elif update_action == updateActions[\"Change\"]:\n\n # Ideally this check_price_change should only return false.\n # All price changes should have already been accounted for by\n # other sub-routines\n if self.price_changed_unexpectedly(price, time):\n self.logger.warn(\"WARNING! price changed unexpectedly\")\n return self.close_top(time)\n\n if self.previous_book.qty != None:\n last_l1_qty = self.previous_book.qty\n last_l1_orders = self.previous_book.numOrders\n to_return = self.check_cancels_and_revisions(current_l1_orders,\n current_l1_qty,\n last_l1_orders,\n last_l1_qty,\n self.previous_book.cont,\n time)\n self.previous_book.cont = True\n\n elif update_action == updateActions[\"Delete\"]:\n to_return = self.level_wipe_out(self.previous_book.qty, time)\n\n elif update_action == updateActions[\"TradeSummary\"]:\n # Crucial: do not reduce the top here based merely on TradeSummary.\n # Implied-in screws everything\n\n if aggside == sides['Unknown']: # Product was implied out\n if trade_num_orders == 1:\n self.aggression_against_top = AggressionState.IMP_REDUCE_TOP\n elif trade_num_orders == 0:\n print(\" \" * 60),\n print(\"WARNING------------------------Butterfly here?\")\n else:\n self.aggression_against_top = AggressionState.IMP_MULTI\n\n else:\n if trade_num_orders > 2:\n self.aggression_against_top = AggressionState.LOCAL_MULTI\n\n elif trade_num_orders == 2:\n self.aggression_against_top = \\\n AggressionState.LOCAL_REDUCE_TOP\n else:\n\n # Trade was implied-in trade. trade_num_orders is 1\n pass\n\n elif update_action == updateActions[\"TradeDetail\"] \\\n and self.aggression_against_top != \\\n AggressionState.NO_AGGRESSION:\n\n if self.aggression_against_top == AggressionState.LOCAL_MULTI:\n to_return = self.multi_end(trade_quantity, time)\n\n elif self.aggression_against_top == \\\n AggressionState.LOCAL_REDUCE_TOP:\n to_return = self.reduce_top(trade_quantity, time)\n\n elif self.aggression_against_top == AggressionState.IMP_MULTI:\n to_return = self.multi_end(trade_quantity, time)\n\n elif self.aggression_against_top == AggressionState.IMP_REDUCE_TOP:\n to_return = self.reduce_top(trade_quantity, time)\n\n self.aggression_against_top = AggressionState.NO_AGGRESSION\n\n if pd.notnull(price): # means it is a book update\n self.previous_book.qty = current_l1_qty\n self.previous_book.numOrders = current_l1_orders\n else:\n self.previous_book.cont = False\n\n return to_return\n","sub_path":"TopTracker/TopTracker.py","file_name":"TopTracker.py","file_ext":"py","file_size_in_byte":14838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473750756","text":"from django import http\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views import View\n\nfrom apps.contents.utils import get_categories\nfrom apps.goods.models import SKU, GoodsCategory, GoodsVisitCount\nfrom apps.goods.utils import get_breadcrumb\nfrom utils.response_code import RETCODE\n\n'''\n分析商品列表页\n一个页面的需求分析,先从大的方向把流程搞清楚\n再把页面中动态展示的数据分析出来(需求)\n\n再把一些需求模块化\n\n把需求简单化\n\n\n以列表数据展示为例:\n\n一 把需求写下来 (前端需要收集什么 后端需要做什么)\n 前端需要必须收集分类id,排序字段和页码是可选的\n 后端就是根据需要查询数据\n \n\n二 把大体思路写下来(后端的大体思路)\n # 1.根据分类id,把所有数据都查询出来\n # 2.如果有排序字段,再排序\n # 3.如果有分页字段再分页\n \n \n\n三 把详细思路完善一下(纯后端)\n 1.根据分类id,把所有数据都查询出来\n 2.如果有排序字段,再排序\n 3.如果有分页字段再分页\n \n\n四 确定我们请求方式和路由\n\n GET list/(?P\\d+)/(?P\\d+)/?sort=排序方法\n\n\n'''\nimport logging\nlogger = logging.getLogger('django')\n\nclass ListView(View):\n\n def get(self,request,category_id,page_num):\n\n # 一.面包屑的实现\n # 我们需要根据当前的分类,来获取他的上级/下级信息\n # ① 获取当前的分类\n try:\n category = GoodsCategory.objects.get(id=category_id)\n except Exception as e:\n logger.error(e)\n return render(request,'list.html',context={'errmsg':'没有此分类'})\n\n # ② 获取他的上/下级信息\n # 如果是三级 有3个信息\n # 如果是二级 有2个信息\n # 如果是一级 有1个信息\n # 对面包屑进行封装抽取\n breadcrumb = get_breadcrumb(category)\n\n\n\n\n\n\n # 二.列表数据\n # 1.如果有排序字段,先排序\n sort = request.GET.get('sort')\n # sort = hot 人气,根据销量排序\n # sort = price 价格,根据价格排序\n # sort = default 默认,根据create_time(上架时间)排序\n if sort == 'hot':\n order_filed = 'sales'\n elif sort == 'price':\n order_filed = 'price'\n else:\n order_filed = 'create_time'\n sort = 'default'\n # 2.根据分类id, 把所有数据都查询出来\n skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(order_filed)\n\n\n # 3.如果有分页字段再分页\n try:\n page_num = int(page_num)\n except Exception as e:\n page_num = 0\n # 3.1导入分页类\n from django.core.paginator import Paginator\n try:\n # 3.2创建分页实例\n paginator = Paginator(skus,per_page=5)\n # 3.3获取分页数据\n page_skus = paginator.page(page_num)\n # 总页数\n total_page = paginator.num_pages\n except Exception as e:\n pass\n # 渲染页面\n context = {\n 'category': category, # 频道分类\n 'breadcrumb': breadcrumb, # 面包屑导航\n 'sort': sort, # 排序字段\n 'page_skus': page_skus, # 分页后数据\n 'total_page': total_page, # 总页数\n 'page_num': page_num, # 当前页码\n }\n\n return render(request,'list.html',context=context)\n\n\n'''\n# 热销排行页面的展示思路\n一 把需求写下来 (前端需要收集什么 后端需要做什么)\n 前端:需要把分类id传递给后端\n 后端:根据分类id查询数据\n \n\n二 把大体思路写下来(后端的大体思路)\n 1.获取分类id\n 2.查询是否有当前分类\n 3.根据分类去查询指定的数据,并进行排序,排序之后获取n条数据\n 4.ajax把列表对象转换为字典列表\n \n\n \n三 把详细思路完善一下(纯后端)\n # 1.获取分类id\n # 2.查询是否有当前分类\n # 3.根据分类去查询指定的数据,并进行排序,排序之后获取n条数据\n # 4.ajax把列表对象转换为字典列表\n \n\n四 确定我们请求方式和路由\n GET hot/cat_id/\n hot/?cat=xxxx\n \n'''\nclass HotView(View):\n\n def get(self,request,category_id):\n # 1.获取分类id\n # 2.查询是否有当前分类\n try:\n category = GoodsCategory.objects.get(id=category_id)\n except Exception as e:\n return http.JsonResponse({'code':RETCODE.NODATAERR,'errmag':'暂无此分类'})\n\n\n # 3.根据分类去查询指定的数据,并进行排序,排序之后获取n条数据\n skus = SKU.objects.filter(category=category,is_launched=True).order_by('-sales')[0:2]\n # 4.ajax把列表对象转换为字典列表\n skus_list = []\n for sku in skus:\n skus_list.append({\n 'id': sku.id,\n 'default_image_url': sku.default_image.url,\n 'name': sku.name,\n 'price': sku.price\n })\n return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','hot_skus':skus_list})\n\n\n\n'''\n搜索引擎的原理: 类似于新华字典的索引\n\n 我是中国人 --> 搜索引擎 --> 进行分词处理 --> (我,是,中国,中国人,国人)\n\n 我 --> 我是中国人 这条记录\n 中国 -->\n\n 我是中\n 国人\n\n全文检索(搜索) --> 借助于 搜索引擎 (进行分词处理) --> 建立搜索词 和 搜索结果的对应关系\n\n 我 (我,是,中国,中国人,国人) 我是中国人\n\n\n\n1. 我们的搜索不使用like,因为like 查询效率低, 多个字段查询不方便\n\n2. 我们搜索使用全文检索\n\n3. 全文检索 需要使用 搜索引擎\n\n4. 我们的搜索引擎使用 elasticsearch\n\n\n使用 elasticsearch 实现全文检索\n\n\n数据 haystack elasticsearch\n\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass DetailView(View):\n def get(self,request,sku_id):\n\n # 获取当前sku信息\n try:\n sku = SKU.objects.get(id=sku_id)\n except Exception as e:\n return render(request,'404.html')\n # 查询商品频道分类\n categories = get_categories()\n\n # 查询面包屑导航\n breadcrumb = get_breadcrumb(sku.category)\n\n\n # 构建当前商品的规格键\n sku_specs = sku.specs.order_by('spec_id')\n sku_key = []\n for spec in sku_specs:\n sku_key.append(spec.option.id)\n # 获取当前商品的所有SKU\n skus = sku.spu.sku_set.all()\n # 构建不同规格参数(选项)的sku字典\n spec_sku_map = {}\n for s in skus:\n # 获取sku的规格参数\n s_specs = s.specs.order_by('spec_id')\n # 用于形成规格参数-sku字典的键\n key = []\n for spec in s_specs:\n key.append(spec.option.id)\n # 向规格参数-sku字典添加记录\n spec_sku_map[tuple(key)] = s.id\n # 获取当前商品的规格信息\n goods_specs = sku.spu.specs.order_by('id')\n # 若当前sku的规格信息不完整,则不再继续\n if len(sku_key) < len(goods_specs):\n return\n for index, spec in enumerate(goods_specs):\n # 复制当前sku的规格键\n key = sku_key[:]\n # 该规格的选项\n spec_options = spec.options.all()\n for option in spec_options:\n # 在规格参数sku字典中查找符合当前规格的sku\n key[index] = option.id\n option.sku_id = spec_sku_map.get(tuple(key))\n spec.spec_options = spec_options\n\n\n # 渲染页面\n context = {\n 'categories': categories,\n 'breadcrumb': breadcrumb,\n 'sku': sku,\n 'specs': goods_specs,\n }\n\n return render(request,'detail.html',context)\n\n\n\n\"\"\"\n1.\n 当用户在列表页面/详情页面的时候,我们需要给后台发送一个统计访问量的请求\n 这个请求包含分类id就行\n \n 后台: \n 接收这个分类id,对他的统计个数+1\n \n2.后台要做什么\n 根据id,查询分类\n 再将当天的统计个数+1\n \n3.细化\n ① 获取分类id\n ② 根据分类id查询分类,判断分类是否存在\n ③ 我们以天为单位,如果当天没有统计数据,则应该新增统计数据\n 我们以天为单位,如果当天有统计数据,则应该更新统计数据\n ④ 返回响应\n4.请求方式和路由\n GET visit/?cat_id=xx\n detail/visit/(?P\\d+)/ \n\n\"\"\"\n\nclass VisitCategoryView(View):\n\n def get(self,request,category_id):\n # ① 获取分类id\n # ② 根据分类id查询分类,判断分类是否存在\n try:\n category = GoodsCategory.objects.get(id=category_id)\n except Exception as e:\n logger.error(e)\n return render(request,'404.html')\n\n # 我们需要查询当天的分类id记录\n # from datetime import datetime\n # now = datetime.now()\n # today_date = datetime.strptime(now,'%Y_%m-%d')\n\n from django.utils import timezone\n\n today = timezone.localdate()\n try:\n gvc = GoodsVisitCount.objects.get(date=today,category_id=category_id)\n\n except GoodsVisitCount.DoesNotExist:\n # 我们以天为单位,如果当天有统计数据,则应该更新统计数据\n GoodsVisitCount.objects.create(\n date=today,\n count=1,\n category_id=category_id\n )\n else:\n gvc.count += 1\n gvc.save()\n # ③ 我们以天为单位,如果当天没有统计数据,则应该新增统计数据\n\n # ④ 返回响应\n return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})\n\n","sub_path":"meiduo_mall/apps/goods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"492869778","text":"# Copyright 2014 DreamHost, LLC\n#\n# Author: DreamHost, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\n\"\"\"State machine for managing a router.\n\n\"\"\"\n\n# See state machine diagram and description:\n# https://docs.google.com/a/dreamhost.com/document/d/1Ed5wDqCHW-CUt67ufjOUq4uYj0ECS5PweHxoueUoYUI/edit # noqa\n\nimport collections\nimport itertools\nimport logging\n\nfrom akanda.rug.event import POLL, CREATE, READ, UPDATE, DELETE, REBUILD\nfrom akanda.rug import vm_manager\n\n\nclass State(object):\n\n def __init__(self, log):\n self.log = log\n\n @property\n def name(self):\n return self.__class__.__name__\n\n def __str__(self):\n return self.name\n\n def execute(self, action, vm, worker_context, queue):\n return action\n\n def transition(self, action, vm, worker_context):\n return self\n\n\nclass CalcAction(State):\n def execute(self, action, vm, worker_context, queue):\n if DELETE in queue:\n self.log.debug('shortcutting to delete')\n return DELETE\n\n while queue:\n self.log.debug(\n 'action = %s, len(queue) = %s, queue = %s',\n action,\n len(queue),\n list(itertools.islice(queue, 0, 60))\n )\n\n if action == UPDATE and queue[0] == CREATE:\n # upgrade to CREATE from UPDATE by taking the next\n # item from the queue\n self.log.debug('upgrading from update to create')\n action = queue.popleft()\n continue\n\n elif action == UPDATE and queue[0] == REBUILD:\n # upgrade to REBUILD from UPDATE by taking the next\n # item from the queue\n self.log.debug('upgrading from update to rebuild')\n action = queue.popleft()\n continue\n\n elif action == CREATE and queue[0] == UPDATE:\n # CREATE implies an UPDATE so eat the update event\n # without changing the action\n self.log.debug('merging create and update')\n queue.popleft()\n continue\n\n elif queue[0] == POLL:\n # Throw away a poll following any other action,\n # because a create or update will automatically handle\n # the poll and repeated polls are not needed.\n self.log.debug('discarding poll event following action %s',\n action)\n queue.popleft()\n continue\n\n elif action != POLL and action != queue[0]:\n # We are not polling and the next action is something\n # different from what we are doing, so just do the\n # current action.\n self.log.debug('done collapsing events')\n break\n\n self.log.debug('popping action from queue')\n action = queue.popleft()\n\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state == vm_manager.GONE:\n return StopVM(self.log)\n elif action == DELETE:\n return StopVM(self.log)\n elif action == REBUILD:\n return RebuildVM(self.log)\n elif vm.state == vm_manager.BOOTING:\n return CheckBoot(self.log)\n elif vm.state == vm_manager.DOWN:\n return CreateVM(self.log)\n else:\n return Alive(self.log)\n\n\nclass PushUpdate(State):\n \"\"\"Put an update instruction on the queue for the state machine.\n \"\"\"\n def execute(self, action, vm, worker_context, queue):\n # Put the action back on the front of the queue.\n queue.appendleft(UPDATE)\n\n def transition(self, action, vm, worker_context):\n return CalcAction(self.log)\n\n\nclass Alive(State):\n def execute(self, action, vm, worker_context, queue):\n vm.update_state(worker_context)\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state == vm_manager.GONE:\n return StopVM(self.log)\n elif vm.state == vm_manager.DOWN:\n return CreateVM(self.log)\n elif action == POLL and vm.state == vm_manager.CONFIGURED:\n return CalcAction(self.log)\n elif action == READ and vm.state == vm_manager.CONFIGURED:\n return ReadStats(self.log)\n else:\n return ConfigureVM(self.log)\n\n\nclass CreateVM(State):\n def execute(self, action, vm, worker_context, queue):\n vm.boot(worker_context)\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state == vm_manager.GONE:\n return StopVM(self.log)\n return CheckBoot(self.log)\n\n\nclass CheckBoot(State):\n def execute(self, action, vm, worker_context, queue):\n vm.check_boot(worker_context)\n # Put the action back on the front of the queue so that we can yield\n # and handle it in another state machine traversal (which will proceed\n # from CalcAction directly to CheckBoot).\n if vm.state != vm_manager.GONE:\n queue.appendleft(action)\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state == vm_manager.GONE:\n return StopVM(self.log)\n if vm.state == vm_manager.UP:\n return ConfigureVM(self.log)\n return CalcAction(self.log)\n\n\nclass StopVM(State):\n def execute(self, action, vm, worker_context, queue):\n vm.stop(worker_context)\n if vm.state == vm_manager.GONE:\n # Force the action to delete since the router isn't there\n # any more.\n return DELETE\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state not in (vm_manager.DOWN, vm_manager.GONE):\n return self\n if vm.state == vm_manager.GONE:\n return Exit(self.log)\n if action == DELETE:\n return Exit(self.log)\n return CreateVM(self.log)\n\n\nclass RebuildVM(State):\n def execute(self, action, vm, worker_context, queue):\n vm.stop(worker_context)\n if vm.state == vm_manager.GONE:\n # Force the action to delete since the router isn't there\n # any more.\n return DELETE\n # Re-create the VM\n return CREATE\n\n def transition(self, action, vm, worker_context):\n if vm.state not in (vm_manager.DOWN, vm_manager.GONE):\n return self\n if vm.state == vm_manager.GONE:\n return Exit(self.log)\n return CreateVM(self.log)\n\n\nclass Exit(State):\n pass\n\n\nclass ConfigureVM(State):\n def execute(self, action, vm, worker_context, queue):\n vm.configure(worker_context)\n if vm.state == vm_manager.CONFIGURED:\n if action == READ:\n return READ\n else:\n return POLL\n else:\n return action\n\n def transition(self, action, vm, worker_context):\n if vm.state in (vm_manager.RESTART, vm_manager.DOWN, vm_manager.GONE):\n return StopVM(self.log)\n if vm.state == vm_manager.UP:\n return PushUpdate(self.log)\n # Below here, assume vm.state == vm_manager.CONFIGURED\n if action == READ:\n return ReadStats(self.log)\n return CalcAction(self.log)\n\n\nclass ReadStats(State):\n def execute(self, action, vm, worker_context, queue, bandwidth_callback):\n stats = vm.read_stats()\n bandwidth_callback(stats)\n return POLL\n\n def transition(self, action, vm, worker_context):\n return CalcAction(self.log)\n\n\nclass Automaton(object):\n def __init__(self, router_id, tenant_id,\n delete_callback, bandwidth_callback,\n worker_context, queue_warning_threshold):\n \"\"\"\n :param router_id: UUID of the router being managed\n :type router_id: str\n :param tenant_id: UUID of the tenant being managed\n :type tenant_id: str\n :param delete_callback: Invoked when the Automaton decides\n the router should be deleted.\n :type delete_callback: callable\n :param bandwidth_callback: To be invoked when the Automaton\n needs to report how much bandwidth\n a router has used.\n :type bandwidth_callback: callable taking router_id and bandwidth\n info dict\n :param worker_context: a WorkerContext\n :type worker_context: WorkerContext\n :param queue_warning_threshold: Limit after which adding items\n to the queue triggers a warning.\n :type queue_warning_threshold: int\n \"\"\"\n self.router_id = router_id\n self.tenant_id = tenant_id\n self._delete_callback = delete_callback\n self._queue_warning_threshold = queue_warning_threshold\n self.deleted = False\n self.bandwidth_callback = bandwidth_callback\n self._queue = collections.deque()\n self.log = logging.getLogger(__name__ + '.' + router_id)\n\n self.state = CalcAction(self.log)\n self.action = POLL\n self.vm = vm_manager.VmManager(router_id, tenant_id, self.log,\n worker_context)\n\n def service_shutdown(self):\n \"Called when the parent process is being stopped\"\n\n def _do_delete(self):\n if self._delete_callback is not None:\n self.log.debug('calling delete callback')\n self._delete_callback()\n # Avoid calling the delete callback more than once.\n self._delete_callback = None\n # Remember that this router has been deleted\n self.deleted = True\n\n def update(self, worker_context):\n \"Called when the router config should be changed\"\n while self._queue:\n while True:\n if self.deleted:\n self.log.debug(\n 'skipping update because the router is being deleted'\n )\n return\n\n try:\n additional_args = ()\n\n if isinstance(self.state, ReadStats):\n additional_args = (self.bandwidth_callback,)\n\n self.log.debug('%s.execute(%s) vm.state=%s',\n self.state, self.action, self.vm.state)\n self.action = self.state.execute(\n self.action,\n self.vm,\n worker_context,\n self._queue,\n *additional_args\n )\n self.log.debug('%s.execute -> %s vm.state=%s',\n self.state, self.action, self.vm.state)\n except:\n self.log.exception(\n '%s.execute() failed for action: %s',\n self.state,\n self.action\n )\n\n old_state = self.state\n self.state = self.state.transition(\n self.action,\n self.vm,\n worker_context,\n )\n self.log.debug('%s.transition(%s) -> %s vm.state=%s',\n old_state, self.action, self.state,\n self.vm.state)\n\n # Yield control each time we stop to figure out what\n # to do next.\n if isinstance(self.state, CalcAction):\n return # yield\n\n # We have reached the exit state, so the router has\n # been deleted somehow.\n if isinstance(self.state, Exit):\n self._do_delete()\n return\n\n def send_message(self, message):\n \"Called when the worker put a message in the state machine queue\"\n if self.deleted:\n # Ignore any more incoming messages\n self.log.debug(\n 'deleted state machine, ignoring incoming message %s',\n message)\n return False\n self._queue.append(message.crud)\n queue_len = len(self._queue)\n if queue_len > self._queue_warning_threshold:\n logger = self.log.warning\n else:\n logger = self.log.debug\n logger('incoming message brings queue length to %s', queue_len)\n return True\n\n def has_more_work(self):\n \"Called to check if there are more messages in the state machine queue\"\n return (not self.deleted) and bool(self._queue)\n","sub_path":"akanda/rug/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":13167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"62678720","text":"# Most codes copied from https://github.com/jtauber/gtp\n\nimport re\nfrom src.reversi_zero.lib.pipe_helper import PipePair\n\n\ndef pre_engine(s):\n s = re.sub(\"[^\\t\\n -~]\", \"\", s)\n s = s.split(\"#\")[0]\n s = s.replace(\"\\t\", \" \")\n return s\n\n\ndef pre_controller(s):\n s = re.sub(\"[^\\t\\n -~]\", \"\", s)\n s = s.replace(\"\\t\", \" \")\n return s\n\n\ndef gtp_boolean(b):\n return \"true\" if b else \"false\"\n\n\ndef gtp_list(l):\n return \"\\n\".join(l)\n\n\ndef gtp_color(color):\n # an arbitrary choice amongst a number of possibilities\n return {BLACK: \"B\", WHITE: \"W\"}[color]\n\n\ndef gtp_vertex(vertex):\n if vertex == PASS:\n return \"pass\"\n elif vertex == RESIGN:\n return \"resign\"\n else:\n x, y = vertex\n return \"{}{}\".format(\"ABCDEFGHJKLMNOPQRSTYVWYZ\"[x - 1], y)\n\n\ndef gtp_move(color, vertex):\n return \" \".join([gtp_color(color), gtp_vertex(vertex)])\n\n\ndef parse_message(message):\n message = pre_engine(message).strip()\n first, rest = (message.split(\" \", 1) + [None])[:2]\n if first.isdigit():\n message_id = int(first)\n if rest is not None:\n command, arguments = (rest.split(\" \", 1) + [None])[:2]\n else:\n command, arguments = None, None\n else:\n message_id = None\n command, arguments = first, rest\n\n return message_id, command, arguments\n\n\nWHITE = -1\nBLACK = +1\nEMPTY = 0\n\nPASS = (0, 0)\nRESIGN = \"resign\"\n\n\ndef parse_color(color):\n if color.lower() in [\"b\", \"black\"]:\n return BLACK\n elif color.lower() in [\"w\", \"white\"]:\n return WHITE\n else:\n return False\n\n\ndef parse_vertex(vertex_string):\n if vertex_string is None:\n return False\n elif vertex_string.lower() == \"pass\":\n return PASS\n elif len(vertex_string) > 1:\n x = \"abcdefghjklmnopqrstuvwxyz\".find(vertex_string[0].lower()) + 1\n if x == 0:\n return False\n if vertex_string[1:].isdigit():\n y = int(vertex_string[1:])\n else:\n return False\n else:\n return False\n return (x, y)\n\n\ndef parse_move(move_string):\n color_string, vertex_string = (move_string.split(\" \") + [None])[:2]\n color = parse_color(color_string)\n if color is False:\n return False\n vertex = parse_vertex(vertex_string)\n if vertex is False:\n return False\n\n return color, vertex\n\n\nMIN_BOARD_SIZE = 7\nMAX_BOARD_SIZE = 19\n\n\ndef format_success(message_id, response=None):\n if response is None:\n response = \"\"\n else:\n response = \" {}\".format(response)\n if message_id:\n return \"={}{}\\n\".format(message_id, response)\n else:\n return \"={}\\n\".format(response)\n\n\ndef format_error(message_id, response):\n if response:\n response = \" {}\".format(response)\n if message_id:\n return \"?{}{}\\n\".format(message_id, response)\n else:\n return \"?{}\\n\".format(response)\n\n\nclass GTPServer(object):\n\n def __init__(self, game_obj, name=\"gtp (python library)\", version=\"0.2\"):\n\n self.size = 19\n self.komi = 6.5\n\n self._game = game_obj\n self._game.clear()\n\n self._name = name\n self._version = version\n\n self.disconnect = False\n\n self.known_commands = [\n field[4:] for field in dir(self) if field.startswith(\"cmd_\")]\n\n def cmd(self, message):\n message_id, command, arguments = parse_message(message)\n if command in self.known_commands:\n try:\n return format_success(\n message_id, getattr(self, \"cmd_\" + command)(arguments))\n except ValueError as exception:\n return format_error(message_id, exception.args[0])\n else:\n return format_error(message_id, \"unknown command\")\n\n def vertex_in_range(self, vertex):\n if vertex == PASS:\n return True\n if 1 <= vertex[0] <= self.size and 1 <= vertex[1] <= self.size:\n return True\n else:\n return False\n\n # commands\n\n def cmd_protocol_version(self, arguments):\n return 2\n\n def cmd_name(self, arguments):\n return self._name\n\n def cmd_version(self, arguments):\n return self._version\n\n def cmd_known_command(self, arguments):\n return gtp_boolean(arguments in self.known_commands)\n\n def cmd_list_commands(self, arguments):\n return gtp_list(self.known_commands)\n\n def cmd_quit(self, arguments):\n self.disconnect = True\n return 'Done'\n\n def cmd_boardsize(self, arguments):\n if arguments.isdigit():\n size = int(arguments)\n if MIN_BOARD_SIZE <= size <= MAX_BOARD_SIZE:\n self.size = size\n self._game.set_size(size)\n return 'Done'\n else:\n raise ValueError(\"unacceptable size\")\n else:\n raise ValueError(\"non digit size\")\n\n def cmd_clear_board(self, arguments):\n self._game.clear()\n return 'Done'\n\n def cmd_komi(self, arguments):\n try:\n komi = float(arguments)\n self.komi = komi\n self._game.set_komi(komi)\n except ValueError:\n raise ValueError(\"syntax error\")\n\n def cmd_play(self, arguments):\n move = parse_move(arguments)\n if move:\n color, vertex = move\n if self.vertex_in_range(vertex):\n if self._game.make_move(color, vertex):\n return 'Done'\n raise ValueError(\"illegal move\")\n\n def cmd_genmove(self, arguments):\n c = parse_color(arguments)\n if c:\n move = self._game.get_move(c)\n self._game.make_move(c, move)\n return gtp_vertex(move)\n else:\n raise ValueError(\"unknown player: {}\".format(arguments))\n\n def cmd_is_over(self, arguments):\n return self._game.is_over()\n\n def cmd_final_score(self, arguments):\n return self._game.final_score()\n\n\nclass GTPClient(object):\n\n def __init__(self, pipe_pair: PipePair):\n self.pipe_pair = pipe_pair\n\n def send(self, data):\n self.pipe_pair.open_write_block()\n self.pipe_pair.write(data.encode())\n self.pipe_pair.close_write()\n\n self.pipe_pair.open_read_nonblock()\n while True:\n data = self.pipe_pair.try_read_allow_empty()\n if data and len(data):\n result = data.decode().strip()\n if len(result) > 0:\n break\n self.pipe_pair.close_read()\n return result\n\n def name(self):\n self.send(\"name\")\n\n def version(self):\n self.send(\"version\")\n\n def boardsize(self, boardsize):\n self.send(\"boardsize {}\".format(boardsize))\n\n def komi(self, komi):\n self.send(\"komi {}\".format(komi))\n\n def clear_board(self):\n self.send(\"clear_board\")\n\n def genmove(self, color):\n message = self.send(\n \"genmove {}\".format(gtp_color(color)))\n assert message[0] == \"=\", message\n return parse_vertex(message[1:].strip())\n\n def showboard(self):\n self.send(\"showboard\")\n\n def play(self, color, vertex):\n self.send(\"play {}\".format(gtp_move(color, vertex)))\n\n def is_over(self):\n message = self.send(\"is_over\")\n assert message[0] == \"=\", message\n return message[1:].strip() == 'True'\n\n def final_score(self):\n message = self.send(\"final_score\")\n assert message[0] == \"=\", message\n score_string = message[1:].strip()\n assert score_string[0] == '('\n assert score_string[-1] == ')'\n score_string = score_string[1:-1]\n scores = score_string.split(',')\n assert len(scores) == 2\n return int(scores[0].strip()), int(scores[1].strip())\n","sub_path":"src/reversi_zero/lib/gtp.py","file_name":"gtp.py","file_ext":"py","file_size_in_byte":7764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"388974211","text":"from ._ffi import *\nfrom ctypes import *\nfrom wasmtime import Store, FuncType, Val, Trap, Extern\nimport sys\nimport traceback\n\ndll.wasm_func_new_with_env.restype = P_wasm_func_t\ndll.wasmtime_func_new_with_env.restype = P_wasm_func_t\ndll.wasm_func_type.restype = P_wasm_functype_t\ndll.wasm_func_param_arity.restype = c_size_t\ndll.wasm_func_result_arity.restype = c_size_t\ndll.wasm_func_call.restype = P_wasm_trap_t\ndll.wasm_func_as_extern.restype = P_wasm_extern_t\ndll.wasmtime_caller_export_get.restype = P_wasm_extern_t\n\n\nclass Func(object):\n # Creates a new func in `store` with the given `ty` which calls the closure\n # given\n #\n # The `func` is called with the parameters natively and they'll have native\n # Python values rather than being wrapped in `Val`. If `access_caller` is\n # set to `True` then the first argument given to `func` is an instance of\n # type `Caller` below.\n def __init__(self, store, ty, func, access_caller=False):\n if not isinstance(store, Store):\n raise TypeError(\"expected a Store\")\n if not isinstance(ty, FuncType):\n raise TypeError(\"expected a FuncType\")\n idx = FUNCTIONS.allocate((func, ty.params(), ty.results(), store))\n if access_caller:\n ptr = dll.wasmtime_func_new_with_env(\n store.__ptr__,\n ty.__ptr__,\n trampoline_with_caller,\n idx,\n finalize)\n else:\n ptr = dll.wasm_func_new_with_env(\n store.__ptr__, ty.__ptr__, trampoline, idx, finalize)\n if not ptr:\n FUNCTIONS.deallocate(idx)\n raise RuntimeError(\"failed to create func\")\n self.__ptr__ = ptr\n self.__owner__ = None\n\n @classmethod\n def __from_ptr__(cls, ptr, owner):\n ty = cls.__new__(cls)\n if not isinstance(ptr, P_wasm_func_t):\n raise TypeError(\"wrong pointer type\")\n ty.__ptr__ = ptr\n ty.__owner__ = owner\n return ty\n\n # Gets the type of this func as a `FuncType`\n def type(self):\n ptr = dll.wasm_func_type(self.__ptr__)\n return FuncType.__from_ptr__(ptr, None)\n\n # Returns the number of parameters this function expects\n def param_arity(self):\n return dll.wasm_func_param_arity(self.__ptr__)\n\n # Returns the number of results this function produces\n def result_arity(self):\n return dll.wasm_func_result_arity(self.__ptr__)\n\n # Calls this function with the given parameters\n #\n # Parameters can either be a `Val` or a native python value which can be\n # converted to a `Val` of the corresponding correct type\n #\n # Returns `None` if this func has 0 return types\n # Returns a single value if the func has 1 return type\n # Returns a list if the func has more than 1 return type\n def call(self, *params):\n return self(*params)\n\n def __call__(self, *params):\n ty = self.type()\n param_tys = ty.params()\n if len(param_tys) != len(params):\n raise TypeError(\"wrong number of parameters\")\n param_ffi = (wasm_val_t * len(params))()\n for i, param in enumerate(params):\n val = Val.__convert__(param_tys[i], param)\n param_ffi[i] = val.__raw__\n\n result_tys = ty.results()\n result_ffi = (wasm_val_t * len(result_tys))()\n\n trap = dll.wasm_func_call(self.__ptr__, param_ffi, result_ffi)\n if trap:\n raise Trap.__from_ptr__(trap)\n\n results = []\n for i in range(0, len(result_tys)):\n results.append(extract_val(Val(result_ffi[i])))\n if len(results) == 0:\n return None\n elif len(results) == 1:\n return results[0]\n else:\n return results\n\n # Returns this as an instance of `Extern`\n def as_extern(self):\n ptr = dll.wasm_func_as_extern(self.__ptr__)\n return Extern.__from_ptr__(ptr, self.__owner__ or self)\n\n def __del__(self):\n if hasattr(self, '__owner__') and self.__owner__ is None:\n dll.wasm_func_delete(self.__ptr__)\n\n\nclass Caller(object):\n def __init__(self, ptr):\n self.__ptr__ = ptr\n\n # Looks up an export with `name` on the calling module.\n #\n # May return `None` if the export isn't found, if it's not a memory (for\n # now), or if the caller has gone away and this `Caller` object has\n # persisted too long.\n def get_export(self, name):\n # First convert to a raw name so we can typecheck our argument\n name_raw = str_to_name(name)\n\n # Next see if we've been invalidated\n if not hasattr(self, '__ptr__'):\n return None\n\n # And if we're not invalidated we can perform the actual lookup\n ptr = dll.wasmtime_caller_export_get(self.__ptr__, byref(name_raw))\n if ptr:\n return Extern.__from_ptr__(ptr, None)\n else:\n return None\n\n\ndef extract_val(val):\n a = val.get()\n if a is not None:\n return a\n return val\n\n\n@CFUNCTYPE(c_size_t, c_size_t, POINTER(wasm_val_t), POINTER(wasm_val_t))\ndef trampoline(idx, params_ptr, results_ptr):\n return invoke(idx, params_ptr, results_ptr, [])\n\n\n@CFUNCTYPE(\n c_size_t,\n P_wasmtime_caller_t,\n c_size_t,\n POINTER(wasm_val_t),\n POINTER(wasm_val_t),\n)\ndef trampoline_with_caller(caller, idx, params_ptr, results_ptr):\n caller = Caller(caller)\n try:\n return invoke(idx, params_ptr, results_ptr, [caller])\n finally:\n delattr(caller, '__ptr__')\n\n\ndef invoke(idx, params_ptr, results_ptr, params):\n func, param_tys, result_tys, store = FUNCTIONS.get(idx)\n\n try:\n for i in range(0, len(param_tys)):\n params.append(extract_val(Val(params_ptr[i])))\n results = func(*params)\n if len(result_tys) == 0:\n if results is not None:\n raise RuntimeError(\n \"callback produced results when it shouldn't\")\n elif len(result_tys) == 1:\n val = Val.__convert__(result_tys[0], results)\n results_ptr[0] = val.__raw__\n else:\n if len(results) != len(result_tys):\n raise RuntimeError(\"callback produced wrong number of results\")\n for i, result in enumerate(results):\n val = Val.__convert__(result_tys[i], result)\n results_ptr[i] = val.__raw__\n except Exception:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n fmt = traceback.format_exception(exc_type, exc_value, exc_traceback)\n trap = Trap(store, \"\\n\".join(fmt))\n ptr = trap.__ptr__\n delattr(trap, '__ptr__')\n return cast(ptr, c_void_p).value\n\n return 0\n\n\n@CFUNCTYPE(None, c_size_t)\ndef finalize(idx):\n FUNCTIONS.deallocate(idx)\n pass\n\n\nclass Slab(object):\n def __init__(self):\n self.list = []\n self.next = 0\n\n def allocate(self, val):\n idx = self.next\n\n if len(self.list) == idx:\n self.list.append(None)\n self.next += 1\n else:\n self.next = self.list[idx]\n\n self.list[idx] = val\n return idx\n\n def get(self, idx):\n return self.list[idx]\n\n def deallocate(self, idx):\n self.list[idx] = self.next\n self.next = idx\n\n\nFUNCTIONS = Slab()\n","sub_path":"wasmtime/_func.py","file_name":"_func.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"534978672","text":"# !/home/imyin/python_env/newspaper_python3/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreate on 12/27/17 4:33 PM\n\n@auther: imyin\n\n@File: compare_cars\n\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nimport pandas as pd\n\nimport constants as cons\n\nfinally_path = ''\ncars_info_path = ''\nraw_dict = ''\ncars_dict = {file_name.split('.')[0]: pd.read_csv(cars_info_path + '/' + file_name) for file_name in\n os.listdir(cars_info_path)}\n\n\ndef raw_data(path):\n return pd.read_csv(raw_dict + '/' + path, encoding='utf-8', quotechar='&')\n\n\ndef compare_it(df):\n car_4s = []\n brand = []\n addrs = []\n tels = []\n for index, item in enumerate(df['name'].values):\n car_data = cars_dict[cons.province_dict[df.loc[index, 'province']]]\n name_list = [item.strip() for item in car_data['store_name']]\n for i, w in enumerate(name_list):\n if w in item:\n car_4s.append(w)\n brand.append(car_data.loc[i, 'main_brand'])\n addrs.append(car_data.loc[i, 'address'])\n tels.append(car_data.loc[i, 'phone'])\n break\n elif i == name_length - 1:\n car_4s.append('')\n brand.append('')\n addrs.append('')\n tels.append('')\n else:\n continue\n df['store_name'] = car_4s\n df['brand'] = brand\n df['addr'] = addrs\n df['tel'] = tels\n filter_not_null = df['store_name'] != ''\n df = df[filter_not_null]\n return df\n\n\ndef run(path):\n df = compare_it(raw_data(path))\n df.to_csv(finally_path + '/' + path, encoding='utf-8', index=False)\n print('{} finished.....'.format(path))\n\n\nif __name__ == '__main__':\n time1 = datetime.now()\n print('it is : {}'.format(time1))\n raw_file = os.listdir(raw_dict)\n\n pool = ThreadPool(16)\n results = pool.map(run, raw_file)\n pool.close()\n pool.join()\n time2 = datetime.now()\n print('It cost {} sec run it'.format(time2))\n","sub_path":"GD/compare_cars.py","file_name":"compare_cars.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"280015052","text":"import json\nfrom slots_tracker_server.charts import NUM_OF_CHARTS\n\n\n# Charts\ndef test_get_charts(client):\n rv = client.get('/charts/')\n r_data = json.loads(rv.get_data(as_text=True))\n assert isinstance(r_data, list)\n assert len(r_data) == NUM_OF_CHARTS\n","sub_path":"slots_tracker_server/tests/test_api_charts.py","file_name":"test_api_charts.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"363078407","text":"import re\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport itertools as it\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport statsmodels.stats.multitest as p_adjust\nfrom collections import Counter\nfrom pylab import text\nfrom scipy import stats\nfrom collections import deque\nfrom functools import reduce\nfrom matplotlib import colors\nfrom matplotlib.colors import LogNorm\nfrom heapq import nsmallest\nfrom Bio import SeqIO\nimport xlsxwriter\n\nall_mm = ['AG','AC','AT','CA','CG','CT','GA','GC','GT','TA','TG','TC']\n\n\ndef get_sites_list(df):\n \n sites = []\n for sample in list(set(df['sample_name'])):\n samples_df = df[df['sample_name'] == sample]\n row_gene_sites = []\n for i, row in samples_df.iterrows():\n for mm_type in eval(row['genomic_keys']):\n row_gene_sites = row_gene_sites + [row['gene_name']+';'+s for s in mm_type]\n sites = sites + list(set(row_gene_sites))\n return sites\n\n\ndef plot_editings_sites_repetitions(fig_path,names, sites, groups = [1,2,3,4,5,6,7,8,9,10]):\n col = ['b','g','salmon','y','m','tan','r','silver','yellow','crimson','teal','k','orange','brown','limegreen','navy','gold','c','olive']\n \n bars = []\n sites_counts = [list(Counter(s).values()) for s in sites]\n for s in sites_counts:\n b=[]\n for g in sorted(groups[:-1]):\n b.append(len([c for c in s if c==g]))\n b.append(len([c for c in s if c>=groups[-1]]))\n bars.append(b)\n \n # set width of bar\n barWidth = 0.2\n \n groups_labels = []\n for i in groups:\n if i < groups[-1]:\n groups_labels.append(str(i))\n groups_labels.append(str(groups[-1])+'<=')\n \n\n # Set position of bar on X axis\n rs = [np.arange(1,len(bars[0])+1)]\n r_temp = rs[0]\n for i in names[1:]:\n r_temp = [x + barWidth for x in r_temp]\n rs.append(np.array(r_temp))\n\n \n # Make the plot\n for i in range(len(bars)):\n plt.bar(list(rs[i]), bars[i], color=col[i], width=barWidth, edgecolor='white', label=names[i])\n \n # Add xticks on the middle of the group bars\n plt.xlabel('Repetitions', fontweight='bold')\n plt.ylabel('Sites', fontweight='bold')\n plt.xticks([g+0.2 for g in groups], groups_labels) \n plt.yticks(np.arange(0,20,5))\n plt.title('Discovered Editing Sites')\n \n # Create legend & Show graphic\n plt.legend()\n plt.savefig(fig_path)\n# plt.show()\n plt.close()\n\n\ndef scatter_discovered_peptides(df, name, path):\n color_markers = [('y', '+'), ('r', '*'), ('b', '>'), ('g', '<'), ('m', '^'), ('tan', 'D'), ('silver', '.'), ('yellow', 'o'), ('crimson', '<'), ('teal', '>'), ('k', 'D'), ('orange', '^'), ('brown', 'D'), ('limegreen', 'D'), ('navy', '^'), ('gold', 'o'), ('c', '.'), ('olive', '.')]\n \n tissues = Counter(list(df['tissue']))\n \n for i,t in enumerate(tissues.items()):\n print( t[0]+' '+str(t[1]))\n tissues_dfs = df[df['tissue']==t[0]]\n plt.scatter(list(tissues_dfs['total_peptides']),list(tissues_dfs['edited_peptides']), label = t[0]+' '+str(t[1]), color = color_markers[i][0], marker = color_markers[i][1])\n plt.legend(loc='center left', bbox_to_anchor=(0.8, 0.5))\n plt.title('Peptides for Samples - ' + name + ' proteom')\n plt.xlabel('total peptides')\n plt.savefig(path)\n plt.close()\n \n \nif __name__ == '__main__':\n \n quantification_methods = ['LFQ','LFQ+','unknown']\n filter_by_quantification = False\n \n\n \n \n# summ1 = 'E:/RNA_editing_Large_files/MQ/results_from_ag_finished.txt'\n# summ2 = 'E:/RNA_editing_Large_files/MQ/results_from_all_non_ag_finished.txt'\n# summ3 = 'E:/RNA_editing_Large_files/MQ/results_from_random_ag_finished.txt'\n# summ_files = [summ1,summ2,summ3]\n# \n# peps1 = 'E:/RNA_editing_Large_files/MQ/peptides_lists_from_ag_finished.txt'\n# peps2 = 'E:/RNA_editing_Large_files/MQ/peptides_lists_from_all_non_ag_finished.txt'\n# peps3 = 'E:/RNA_editing_Large_files/MQ/peptides_lists_from_random_ag_finished.txt'\n# peps_files = [peps1,peps2,peps3]\n# \n# names = ['AG','NonAG','randomAG']\n \n \n summ1 = 'E:/RNA_editing_Large_files/MQ/results_from_ag_finished.txt'\n summ2 = 'E:/RNA_editing_Large_files/MQ/results_from_all_non_ag_finished.txt'\n summ_files = [summ1,summ2]\n \n peps1 = 'E:/RNA_editing_Large_files/MQ/peptides_lists_from_ag_finished.txt'\n peps2 = 'E:/RNA_editing_Large_files/MQ/peptides_lists_from_all_non_ag_finished.txt'\n peps_files = [peps1,peps2]\n \n names = ['AG','NonAG']\n \n \n path = '/'.join(peps_files[0].split('/')[:-1]) + '/'\n \n anal_name = ''\n for n in names:\n anal_name = anal_name + '_' + n\n if filter_by_quantification:\n anal_name = anal_name[1:] + '_LFQ'\n else:\n anal_name = anal_name[1:] + '_all_quantifications'\n \n sys.stdout = open(path + anal_name + '.txt', 'w')\n \n\n \n peps_dfs_dict = {}\n writer = pd.ExcelWriter(path + 'peptides.xlsx', engine='xlsxwriter')\n for i,file in enumerate(peps_files):\n df = pd.read_csv(file,sep = '\\t', header = 0)\n for j, mm in enumerate(all_mm):\n df[mm+'sites'] = df.apply(lambda row: eval(row['genomic_keys'])[j], axis = 1)\n df.to_excel(writer, sheet_name = names[i])\n df['full_name'] = df.apply(lambda row: row['sample_name']+'_'+row['sub_name'], axis = 1)\n if filter_by_quantification:\n df = df[df['quantification'].isin(quantification_methods)]\n peps_dfs_dict.update({names[i]:df})\n writer.save()\n \n \n summaries_dfs_dict = {}\n writer = pd.ExcelWriter(path + 'sammaries.xlsx', engine='xlsxwriter')\n for i,file in enumerate(summ_files):\n df = pd.read_csv(file,sep = '\\t', header = 0)\n df.to_excel(writer, sheet_name = names[i])\n df['full_name'] = df.apply(lambda row: row['sample_name']+'_'+row['sub_name'], axis = 1)\n if filter_by_quantification:\n df = df[df['quantification'].isin(quantification_methods)]\n summaries_dfs_dict.update({names[i]:df})\n writer.save()\n \n samples_in_all = list(set.intersection(*map(set,[list(summaries_dfs_dict[n]['sample_name']) for n in names])))\n finshed_run_in_all_analyses = list(set.intersection(*map(set,[[str(i)+'_'+str(j) for i,j in zip(list(summaries_dfs_dict[n]['sample_name']),list(summaries_dfs_dict[n]['sub_name']))] for n in names])))\n for k,v in summaries_dfs_dict.items():\n summaries_dfs_dict[k] = v[v['full_name'].isin(finshed_run_in_all_analyses)]\n for k,v in peps_dfs_dict.items():\n peps_dfs_dict[k] = v[v['full_name'].isin(finshed_run_in_all_analyses)]\n \n \n \n print('\\nAnalysis for samples:')\n df = summaries_dfs_dict[names[0]]\n for s in samples_in_all:\n df_for_sample = df[df['sample_name'] == s]\n# tissue = list(df_for_sample['tissue'])[0]\n print(s)\n print('\\n')\n \n #list of sites (as a non-unique list) discovered in each file\n sites = [get_sites_list(peps_dfs_dict[n]) for n in names]\n tissues = list(set(summaries_dfs_dict[names[0]]['tissue']))\n \n plot_editings_sites_repetitions(path + anal_name + '.jpg', names, sites)\n \n for i, n in enumerate(names):\n path = '/'.join(summ_files[i].split('/')[:-1]) + '/peptides_for_samples_' + n + '.jpg' \n c = Counter(sites[i]).items()\n print('\\n\\n'+n+' Sites (' + str(len(c)) + '):')\n for key, val in Counter(sites[i]).items():\n# print(key)\n print(key+ ': ' + str(val))\n print('\\n')\n# scatter_discovered_peptides(summaries_dfs_dict[n], n, path)\n \n \n ","sub_path":"scripts/proteomics_simulator/OLD/20190322/proteomics_simulator/additional_modules/plot_maxquant_results_for_multiple_runs.py","file_name":"plot_maxquant_results_for_multiple_runs.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"588022759","text":"# -*- coding: utf-8 -*-\n\"\"\"\n店面就一轮,顺便问问有没有更好的思路,算是设计题目,第一问就是一堆人出去玩,吃饭或者什么的,有人先付钱,其他人欠着,最后求每个人的balance.\n比如 person A,B,C\nTransaction 1 is 12$, A pays for A,B,C.鏈枃鍘熷垱鑷�1point3acres璁哄潧\nTransaction 2 is 10$, B pays for A,B\n\n那么最后balance就是\nA: -3\nB: -1\nC: 4 (C需要给A,B各1元和3元)\n\n设计数据结构和打印出每个人的balance.\n\n第二问是打印出谁应该给谁多少钱,比如上例中,应该是\n\nC gives 1 to B\nC gives 3 to A\n\n第一问没什么好说的,第二问的时间复杂度是可以做到o(n)的,我想的是维持两个queue,一个是欠钱的,一个是收钱的,队首print,然后balance清零出队。不知道有没有更好的思路。\n\n#在这里快速回复#\npost_newreply\n\"\"\"\n\nfrom collections import defaultdict\n\n\nclass Solution:\n def get_balance(self, transations):\n balance_dct = defaultdict(int)\n for amount, payer, payees in transations:\n balance_dct[payer] -= amount\n amount_payee = float(amount) / len(payees)\n for payee in payees:\n balance_dct[payee] += amount_payee\n return balance_dct\n\n def get_due(self, balance_dct):\n if sum(balance_dct.values()) != 0:\n raise Exception('Not balance')\n debets = sorted([it for it in balance_dct.items() if it[1] > 0], key=lambda x: x[1])\n credit = sorted([it for it in balance_dct.items() if it[1] < 0], key=lambda x: -x[1])\n give_dct = defaultdict(list)\n while debets and credit:\n debet_user, debet_val = debets.pop()\n credit_user, credit_val = credit.pop()\n bal = debet_val + credit_val\n if bal > 0:\n debets.append((debet_user, bal))\n elif bal < 0:\n credit.append((credit_user, bal))\n\n give_dct[debet_user].append((credit_user, min(debet_val, -credit_val)))\n return give_dct\n","sub_path":"Practice/Interview/square/transaction_balance/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"537787245","text":"from enigma_machine import Enigma_machine\nfrom stecker_cable_enigma_logic import Stecker_cable_enigma_logic\nfrom stecker_cable_interface import Stecker_cable_interface\nfrom uhr_box_enigma_logic import Uhr_box_enigma_logic\nfrom uhr_box_interface import Uhr_box_interface\nfrom uhr_box import Uhr_box\nfrom three_rotor_group import Three_rotor_group\nfrom four_rotor_group import Four_rotor_group\nfrom three_rotor_interface import Three_rotor_interface\nfrom four_rotor_interface import Four_rotor_interface\nfrom enigma_interface import Enigma_interface\nfrom display_uhr_enigma import Display_uhr_enigma\nfrom display_stecker_enigma import Display_stecker_enigma\nfrom settings import*\n\nclass WEHRMACHT(Enigma_machine,\n\t\t\t\tEnigma_interface,\n\t\t\t\tThree_rotor_interface,\n\t\t\t\tDisplay_stecker_enigma,\n\t\t\t\tStecker_cable_enigma_logic,\n\t\t\t\tStecker_cable_interface):\n\n\tdef __init__(self):\n\n\t\tself._machine_type = \"WEHRMACHT\"\n\t\tself._rotor_group = Three_rotor_group(self._machine_type)\n\t\tsuper(WEHRMACHT, self).__init__()\n\n\nclass KRIEGSMARINE_M3(Enigma_machine,\n\t\t\t\t\t Enigma_interface,\n\t\t\t\t\t Three_rotor_interface,\n\t\t\t\t\t Display_stecker_enigma,\n\t\t\t\t\t Stecker_cable_enigma_logic,\n\t\t\t\t\t Stecker_cable_interface):\n\n\tdef __init__(self):\n\n\t\tself._machine_type = \"KRIEGSMARINE_M3\"\n\t\tself._rotor_group = Three_rotor_group(self._machine_type)\n\t\tsuper(KRIEGSMARINE_M3, self).__init__()\n\n\nclass KRIEGSMARINE_M4(Enigma_machine,\n\t\t\t\t\t Enigma_interface,\n\t\t\t\t\t Four_rotor_interface,\n\t\t\t\t\t Display_stecker_enigma,\n\t\t\t\t\t Stecker_cable_enigma_logic,\n\t\t\t\t\t Stecker_cable_interface):\n\n\tdef __init__(self):\n\n\t\tself._machine_type = \"KRIEGSMARINE_M4\"\n\t\tself._rotor_group = Four_rotor_group(self._machine_type)\n\t\tsuper(KRIEGSMARINE_M4, self).__init__()\n\n\nclass LUFTWAFFE(Enigma_machine,\n\t\t\t\tEnigma_interface,\n\t\t\t\tFour_rotor_interface,\n\t\t\t\tDisplay_uhr_enigma,\n\t\t\t\tUhr_box_enigma_logic,\n\t\t\t\tUhr_box_interface):\n\n\tdef __init__(self):\n\n\t\tself._machine_type = \"LUFTWAFFE\"\n\t\tself._rotor_group = Four_rotor_group(self._machine_type)\n\t\tself._uhr_box = Uhr_box()\n\t\tsuper(LUFTWAFFE, self).__init__()\n\n\nclass SWISS_K(Enigma_machine,\n\t\t\t Enigma_interface,\n\t\t\t Three_rotor_interface,\n\t\t\t Display_stecker_enigma,\n\t\t\t Stecker_cable_enigma_logic,\n\t\t\t Stecker_cable_interface):\n\n\tdef __init__(self):\n\n\t\tself._machine_type = \"SWISS_K\"\n\t\tself._rotor_group = Three_rotor_group(self._machine_type)\n\t\tsuper(SWISS_K, self).__init__()\n\n\nif __name__ == \"__main__\":\n\n\tdef select_machine():\n\n\t\twhile True:\n\t\t\tprint(\"ENIGMA MENU\\\n\t\t\t\t \\n\\nEnter a number for one of the following\\\n\t\t\t\t \\n1. WEHRMACHT\\\n\t\t\t\t \\n2. KRIEGSMARINE M3\\\n\t\t\t\t \\n3. KRIEGSMARINE M4\\\n\t\t\t\t \\n4. LUFTWAFFE\\\n\t\t\t\t \\n5. SWISS K\\\n\t\t\t\t \\n6. Quit\\n\")\n\n\t\t\tinpt = input()\n\n\t\t\tif inpt == '1':\n\t\t\t\tenigma = WEHRMACHT()\n\t\t\telif inpt == '2':\n\t\t\t\tenigma = KRIEGSMARINE_M3()\n\t\t\telif inpt == '3':\n\t\t\t\tenigma = KRIEGSMARINE_M4()\n\t\t\telif inpt == '4':\n\t\t\t\tenigma = LUFTWAFFE()\n\t\t\telif inpt == '5':\n\t\t\t\tenigma = SWISS_K()\n\t\t\telif inpt == '6':\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Invalid input! try again\")\n\t\t\t\tcontinue\n\n\t\t\tenigma.print_machine()\n\t\t\tenigma.menu()\n\n\tselect_machine()","sub_path":"enigma_machine_collection.py","file_name":"enigma_machine_collection.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425268268","text":"# --- Imports --- #\n\nimport sprites\n\n# --- Player Class --- #\n\nclass Player(object):\n \n animation_int = 0\n Animation_Walking_List = sprites.Player_Walking_List\n current = sprites.Player_Shooting_HG_List\n bullet = sprites.Bullet_List\n \n \n X = 640\n counter = 0\n Y = 530\n ground = 530\n direction = \"Right\"\n speed = 10\n grav_speed = 5\n jump_height = 150\n gravity_speed = 5\n health = 100\n max_health = 100\n weapon = \"Handgun\"\n weapon_dict = {0:\"Handgun\", 1:\"Shotgun\", 2:\"Sniper\", 3:\"Machine Gun\", 4:\"Submachine Gun\", 5:\"Assault Rifle\"}\n weapon_damage_dict = {\"Handgun\":35, \"Shotgun\":90, \"Sniper\":100, \"Machine Gun\":55, \"Submachine Gun\":45, \"Assault Rifle\":60}\n weapon_damage = 35\n weapon_int = 0\n damaged_counter = 0\n bullets_list = []\n bullet_X = 0\n bullet_Y = 0\n shot_counter = 0\n bullet_counter = 0\n bullet_speed = 30\n bullet_direction = \"Right\"\n bullet_dead = False\n\n damaged = False\n dead = False\n moving = False\n aiming = False\n shooting = False\n moving_up = False\n moving_down = False\n moving_right = False\n moving_left = False\n next_0 = True\n next_1 = False\n## next_2 = False\n\n def movement(self):\n\n if not self.dead:\n if self.moving_left:\n if self.X > 0:\n self.X -= self.speed\n if self.moving_right:\n if self.X < 1200:\n self.X += self.speed\n\n def animation(self): #Edit to include checks for gun type and walk whilst aiming, etc.\n \n self.counter += 1\n\n if self.counter == 5:\n if self.moving_right or self.moving_left:\n if self.aiming:\n if self.weapon == \"Handgun\":\n self.current = sprites.Player_Shooting_HG_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n self.next_1 = False\n self.next_0 = True\n## self.next_2 = True\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n elif self.weapon == \"Shotgun\":\n self.current = sprites.Player_Shooting_SG_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n self.next_1 = False\n self.next_0 = True\n## self.next_2 = True\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n elif self.weapon == \"Sniper\":\n self.current = sprites.Player_Shooting_SR_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n## self.next_2 = True\n self.next_0 = True\n self.next_1 = False\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n elif self.weapon == \"Machine Gun\":\n self.current = sprites.Player_Shooting_MG_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n## self.next_2 = True\n self.next_1 = False\n self.next_0 = True\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n elif self.weapon == \"Submachine Gun\":\n self.current = sprites.Player_Shooting_SMG_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n## self.next_2 = True\n self.next_1 = False\n self.next_0 = True\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n elif self.weapon == \"Assault Rifle\":\n self.current = sprites.Player_Shooting_AR_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n## self.next_2 = True\n self.next_1 = False\n self.next_0 = True\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n else:\n self.current = sprites.Player_Walking_List\n if self.next_0:\n self.animation_int = 0\n self.next_0 = False\n self.next_1 = True\n elif self.next_1:\n self.animation_int = 1\n## self.next_2 = True\n self.next_0 = True\n self.next_1 = False\n## elif self.next_2:\n## self.animation_int = 2\n## self.next_2 = False\n## self.next_0 = True\n else:\n if not self.aiming:\n self.current = sprites.Player_Walking_List\n self.animation_int = 0\n else:\n if self.weapon == \"Handgun\":\n self.current = sprites.Player_Shooting_HG_List\n self.animation_int = 0\n if self.weapon == \"Shotgun\":\n self.current = sprites.Player_Shooting_SG_List\n self.animation_int = 0\n if self.weapon == \"Sniper\":\n self.current = sprites.Player_Shooting_SR_List\n self.animation_int = 0\n if self.weapon == \"Machine Gun\":\n self.current = sprites.Player_Shooting_MG_List\n self.animation_int = 0\n if self.weapon == \"Submachine Gun\":\n self.current = sprites.Player_Shooting_SMG_List\n self.animation_int = 0\n if self.weapon == \"Assault Rifle\":\n self.current = sprites.Player_Shooting_AR_List\n self.animation_int = 0\n \n self.counter = 0\n \n def jump(self):\n if self.moving_up:\n if self.Y == self.ground:\n self.Y -= self.jump_height\n \n def gravity(self):\n if self.Y < self.ground:\n self.moving_down = True\n self.moving_up = False\n self.Y += self.grav_speed\n else:\n self.moving_down = False\n\n def regen(self):\n if not self.dead:\n self.health += 0.5\n\n def shot(self):\n\n self.shot_counter += 1\n \n if self.shooting and self.aiming:\n if self.bullet_counter == 0:\n self.bullets_list.append((self.X, self.Y))\n self.bullet_X = self.X\n self.bullet_Y = self.Y + 50\n self.bullet_direction = self.direction\n self.bullet_counter += 1\n self.bullet_dead = False\n \n if self.bullet_direction == \"Left\" and not self.bullet_dead:\n self.bullet_X -= self.bullet_speed\n elif self.bullet_direction == \"Right\" and not self.bullet_dead:\n self.bullet_X += self.bullet_speed\n\n if self.bullet_counter >= 1:\n if self.bullet_X <= 0 or self.bullet_X >= 1280:\n self.bullet_counter = 0\n self.shot_counter = 0\n del self.bullets_list[:]\n \n def change_weapon(self):\n self.weapon_int += 1\n if self.weapon_int > 5:\n self.weapon_int = 0\n self.weapon = self.weapon_dict.get(self.weapon_int)\n self.weapon_damage = self.weapon_damage_dict.get(self.weapon)\n\n def __main__(self):\n\n self.animation()\n self.movement()\n self.shot()\n self.jump()\n self.gravity()\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":9854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"193129252","text":"from django.db import models\n\n# Create your models here.\nclass Tour(models.Model):\n name = models.CharField(\"Nome\", max_length=50)\n date = models.DateField(\"Data\")\n full = models.BooleanField(\"Lotado\", default=False)\n city = models.CharField(\"Cidade\", max_length=50)\n capacity = models.PositiveIntegerField(\"Capacidade\")\n available = models.PositiveIntegerField(\"Disponíveis\")\n TOUR_TYPES = (\n (\"Natureza\", \"Natureza\"),\n (\"Cultural\", \"Cultural\"),\n (\"Aventura\", \"Aventura\"))\n tour_type = models.CharField(\"Tipo\", max_length=50, choices=TOUR_TYPES)\n meeting_point = models.CharField(\"Ponto de encontro\", max_length=50)\n","sub_path":"tours/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"40766903","text":"from tkinter import *\n\nroot = Tk()\n\nMODES = [\n (\"Pepperoni\",\"Perpperoni\"),\n (\"Cheese\",\"Cheese\"),\n (\"Mushroom\",\"Mushroom\"),\n (\"Onion\",\"Onion\")\n]\n\npizza = StringVar()\n#pizza.set(\"Pepperoni\")\n\n\nfor text,mode in MODES:\n Radiobutton(root,text=text,variable=pizza,value=mode).pack(anchor=W)\n\ndef clicked(value):\n mylabel=Label(root,text=value)\n mylabel.pack(anchor=W)\n\n\n\nmylabel=Label(root,text=pizza.get()).pack(anchor=W)\n\nmyButton=Button(root,text=\"Order\", command=lambda :clicked(pizza.get())).pack(anchor=W)\nroot.mainloop()","sub_path":"Tkinter/mutipleRadio.py","file_name":"mutipleRadio.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"21324386","text":"#! /usr/bin/python3\n#! -*- coding: utf-8 -*-\n\nimport csv\nfrom datetime import datetime\nfrom datetime import timedelta\nimport itertools\nimport pygal\nimport os\n\n\ndef load_data(*files):\n \"\"\"Load data from CSV files. Combine data from file in one list and\n sort by date.\"\"\"\n\n #TODO: Handle czech and english table header\n #TODO: Handle duplicit data\n fieldnames = [\n 'item',\n 'posting_date',\n 'amount',\n 'bank_account_detail',\n 'execution_date',\n 'variable_symbol',\n 'cancellation',\n 'counter_account_name',\n 'constant_symbol',\n 'specific_symbol',\n 'message_for_payee',\n 'message_for_me',\n 'transaction_reference_number',\n 'client_note',\n 'payment_reference',\n 'reason_for_non_execution',\n 'warning',\n ]\n\n data = []\n\n for file_name in files:\n\n with open(file_name, newline='',\n encoding='utf-8', errors='ignore') as f:\n\n reader = csv.DictReader(f, fieldnames)\n transactions = list(reader)[1:]\n data += transactions\n\n return sorted(data, key=lambda row: row['posting_date'])\n\n\ndef account_balance(data, initial_balance=0):\n \"\"\"Return a list of days and balances for each days.\"\"\"\n\n grouped = itertools.groupby(data, lambda row: row['posting_date'])\n days = []\n balance = initial_balance\n for group in grouped:\n group_key = group[0]\n group_iterator = group[1]\n\n amount_sum = sum([float(row['amount']) for row in group_iterator])\n date = datetime.strptime(group_key, '%Y/%m/%d')\n\n balance += amount_sum\n\n days.append((date, balance))\n\n return days\n\n\ndef create_chart(balance, output_file=None):\n \"\"\"Create a SVG file from account balance data.\"\"\"\n\n if output_file is None:\n if not os.path.isdir('charts'):\n os.mkdir('charts')\n\n output_file='charts/balance.svg'\n\n datetimeline = pygal.DateTimeLine(\n title='Account balance',\n show_legend=False,\n x_label_rotation=35, truncate_label=-1,\n x_value_formatter=lambda d: d.strftime('%Y/%m/%d')\n )\n\n datetimeline.add('Balance', balance)\n datetimeline.render_to_file(output_file)\n\n\nif __name__=='__main__':\n\n import sys\n argv = sys.argv\n files = argv[1:]\n\n #TODO: Load initial balance externaly\n initial_balance = 7999.75\n final_balance = 19224.27\n\n data = load_data(*files)\n balances = account_balance(data, initial_balance)\n\n create_chart(balances)\n","sub_path":"account_watcher.py","file_name":"account_watcher.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"615494291","text":"from pushbullet import Pushbullet # from pushbullet.py package\n\nclass pushbullet_connect(NebriOS):\n listens_to = ['pushbullet_connect']\n\n def check(self):\n return self.pushbullet_connect == True\n\n def action(self):\n # fill in the shared kvp in your instance\n pb_api = Pushbullet(shared.pb_api_key)\n notif_dict = self.notif_dict\n\n if notif_dict['type'] == 'note':\n note = pb_api.push_note(notif_dict['title'], notif_dict['note'])\n elif notif_dict['type'] == 'link':\n link = pb_api.push_link(notif_dict['title'], notif_dict['link'])\n elif notif_dict['type'] == 'list':\n pb_list = pb_api.push_list(notif_dict['title'], notif_dict['list'])\n elif notif_dict['type'] == 'address':\n address = pb_api.push_address(notif_dict['title'], notif_dict['address'])\n\n # Push Note\n # note = pb_api.push_note(\"This is the title\", \"This is the body\")\n\n # Push Address\n # address = \"\"\n # address = pb_api.push_address(\"home\", address)\n\n # Push List\n # to_buy = [\"milk\", \"bread\", \"cider\"]\n # to_buy_list = pb.push_list(\"Shopping list\", to_buy)\n","sub_path":"pushbullet.py","file_name":"pushbullet.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"330047880","text":"import pytest\nfrom selenium import webdriver\nimport allure\nimport logging\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\n@pytest.fixture()\ndef setUp():\n global driver\n driver = webdriver.Chrome(executable_path=\"/Users/aravindanathdm/Documents/Aravinda/chromedriver\")\n# After all the test case execution\n yield\n driver.close()\n\n\n@allure.step\ndef test_case_a(setUp):\n with allure.step(\"Amazon login\"):\n allure.title(\"Test case amzxon.com\")\n driver.get(\"https://www.amazon.in\")\n logger.info(\"User is on amazon.com\")\n logger.info(driver.current_url)\n logger.info(driver.get_cookies())\n allure.attach(driver.get_screenshot_as_png(),\"Success msg \",allure.attachment_type.PNG)\n\n\n@allure.step\ndef test_case_b(setUp):\n with allure.step(\"Facebook login\"):\n\n logger.info(\"User is entering URL\")\n driver.get(\"https://www.facebook.com\")\n allure.attach(driver.get_screenshot_as_png(), \"Sceenshot of this screen\", allure.attachment_type.PNG)\n logger.info(\"User is on \"+driver.current_url)\n\n# /Users/aravindanathdm/PycharmProjects/PythonSeleniumProject/allureReport/=/Users/aravindanathdm/Documents/class/Python Selenium/Reports\n\n# allureReport/StepsForAllureReport\n# /Users/aravindanathdm/Documents/class/Python Selenium/Reports\n\n# --vv --capture=fd --alluredir = /Users/aravindanathdm/Documents/class/Python Selenium/Reports\n\n\n# pytest test_allure.py --verbose --capture=fd --alluredir \"/demo/Users/aravindanathdm/Documents/class/Python Selenium/allureReport/demo/Reports\"\n\n\n","sub_path":"AllureReport/TCPkg/test_allure.py","file_name":"test_allure.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"29520786","text":"from django.test import TestCase\nfrom datetime import datetime\nfrom django.utils import timezone\nfrom main_site.models import Person, LabSession, Request, Topic, Question, RequestHandler, tempStoreUserLocationLink\n\nclass TestModels(TestCase):\n @classmethod\n def setUpTestData(self):\n person1 = Person.objects.create(username = 'hello')\n person2 = Person.objects.create(username = '')\n labsesh1 = LabSession.objects.create(lab_session = 'tootil1')\n request1 = Request.objects.create(lab_session = labsesh1, request_location = 'lf31')\n request2 = Request.objects.create(lab_session = labsesh1, request_location = 'lf31', request_start = timezone.now(), request_end = timezone.now())\n topic1 = Topic.objects.create(topic_text = 'randomtopic')\n Question.objects.create(request = request1, topic = topic1, question_text = 'what is life')\n RequestHandler.objects.create(person = person1, request = request1)\n tempStoreUserLocationLink.objects.create(person = person1, location = 'tootil0', lab_session = labsesh1)\n tempStoreUserLocationLink.objects.create(lab_session = labsesh1)\n tempStoreUserLocationLink.objects.create(person = person2, location = '', lab_session = labsesh1)\n##################### Person class #######################\n def test_person_username_max_length(self):\n user = Person.objects.get(id=1)\n max_length = user._meta.get_field('username').max_length\n self.assertEquals(max_length, 8)\n\n def test_person_username_label(self):\n user = Person.objects.get(id=1)\n field_label = user._meta.get_field('username').verbose_name\n self.assertEquals(field_label, 'username')\n\n def test_person_is_username(self):\n user = Person.objects.get(id=1)\n expected_object_name = user.username\n self.assertEquals(expected_object_name, str(user))\n\n##################### LabSession class #######################\n def test_LabSession_variables_max_length(self):\n user = LabSession.objects.get(id=1)\n max_length = user._meta.get_field('lab_session').max_length\n self.assertEquals(max_length, 30)\n\n\n def test_LabSession_labels(self):\n user = LabSession.objects.get(id=1)\n field_label1 = user._meta.get_field('lab_session').verbose_name\n self.assertEquals(field_label1, 'lab session')\n\n def test_LabSession_is_lab_session(self):\n user = LabSession.objects.get(id=1)\n expected_object_name = user.lab_session\n self.assertEquals(expected_object_name, str(user))\n \n##################### Request class #######################\n# check the on_delete thing\n def test_request_max_length(self):\n user = Request.objects.get(id=1)\n max_length = user._meta.get_field('request_location').max_length\n max_length1 = user._meta.get_field('status').max_length\n self.assertEquals(max_length, 30)\n self.assertEquals(max_length1, 20)\n\n def test_request_label(self):\n user = Request.objects.get(id=1)\n field_label = user._meta.get_field('request_location').verbose_name\n field_label1 = user._meta.get_field('status').verbose_name\n field_label2 = user._meta.get_field('lab_session').verbose_name\n field_label3 = user._meta.get_field('request_made').verbose_name\n field_label4 = user._meta.get_field('request_start').verbose_name\n field_label5 = user._meta.get_field('request_end').verbose_name\n self.assertEquals(field_label, 'request location')\n self.assertEquals(field_label1, 'status')\n self.assertEquals(field_label2, 'lab session')\n self.assertEquals(field_label3, 'request made')\n self.assertEquals(field_label4, 'request start')\n self.assertEquals(field_label5, 'request end')\n\n\n def test_request_is_lab_and_request(self):\n user = Request.objects.get(id=1)\n user1 = Request.objects.get(id=2)\n expected_object_name = str(user.lab_session) + ': ' + user.request_location + ' - made at ' + str(user.request_made)\n expected_object_name1 = str(user1.lab_session) + ': ' + user1.request_location + ' - made at ' + str(user1.request_made)\n expected_status = str(user.status)\n expected_request_start = user.request_start\n expected_request_end = user.request_end\n expected_request_made = user.request_made\n self.assertEquals(expected_object_name, str(user))\n self.assertEquals(expected_object_name1, str(user1))\n self.assertEquals(expected_status, 'Not started')\n self.assertEquals(expected_request_start, None)\n self.assertEquals(expected_request_end, None)\n # self.assertEquals(expected_request_made, timezone.now())\n\n\n##################### Topic class #######################\n def test_topic_text_max_length(self):\n user = Topic.objects.get(id=1)\n max_length = user._meta.get_field('topic_text').max_length\n self.assertEquals(max_length, 30)\n\n def test_topic_text_label(self):\n user = Topic.objects.get(id=1)\n field_label = user._meta.get_field('topic_text').verbose_name\n self.assertEquals(field_label, 'topic text')\n\n def test_topic_is_topic_text(self):\n user = Topic.objects.get(id=1)\n expected_object_name = user.topic_text\n self.assertEquals(expected_object_name, str(user))\n \n##################### Question class #######################\n# on_delete testing\n def test_question_max_length(self):\n user = Question.objects.get(id=1)\n max_length = user._meta.get_field('question_text').max_length\n self.assertEquals(max_length, 30)\n\n def test_question_label(self):\n user = Question.objects.get(id=1)\n field_label = user._meta.get_field('request').verbose_name\n field_label1 = user._meta.get_field('topic').verbose_name\n field_label2 = user._meta.get_field('question_text').verbose_name\n self.assertEquals(field_label, 'request')\n self.assertEquals(field_label1, 'topic')\n self.assertEquals(field_label2, 'question text')\n\n def test_question_is_topic_and_question(self):\n user = Question.objects.get(id=1)\n expected_object_name = str(user.topic) + ': ' + str(user.question_text)\n self.assertEquals(expected_object_name, str(user))\n \n##################### RequestHandler class #######################\n# on_delete testing\n def test_person_username_label(self):\n user = RequestHandler.objects.get(id=1)\n field_label = user._meta.get_field('person').verbose_name\n field_label1 = user._meta.get_field('request').verbose_name\n self.assertEquals(field_label, 'person')\n self.assertEquals(field_label1, 'request')\n\n def test_person_is_username(self):\n user = RequestHandler.objects.get(id=1)\n expected_object_name = str(user.person) + ' ' + str(user.request)\n self.assertEquals(expected_object_name, str(user))\n \n##################### tempStoreUserLocationLink class #######################\n# on_delete testing\n def test_tempStoreUserLocationLink_max_length(self):\n user = tempStoreUserLocationLink.objects.get(id=1)\n max_length = user._meta.get_field('location').max_length\n self.assertEquals(max_length, 30)\n\n def test_temp_label(self):\n user = tempStoreUserLocationLink.objects.get(id=1)\n field_label = user._meta.get_field('person').verbose_name\n field_label1 = user._meta.get_field('location').verbose_name\n field_label2 = user._meta.get_field('lab_session').verbose_name\n self.assertEquals(field_label, 'person')\n self.assertEquals(field_label1, 'location')\n self.assertEquals(field_label2, 'lab session')\n\n def test_temp_with_person_with_location(self):\n user = tempStoreUserLocationLink.objects.get(id=1)\n expected_object_name = str(user.person) + ' ' + str(user.lab_session)\n self.assertEquals(expected_object_name, str(user))\n\n def test_temp_null_person_and_null_location(self):\n user = tempStoreUserLocationLink.objects.get(id=2)\n expected_object_name = str(user.location) + ' ' + str(user.lab_session)\n self.assertEquals(expected_object_name, str(user))\n\n def test_temp_blank_person_and_blank_location(self):\n user = tempStoreUserLocationLink.objects.get(id=3)\n expected_object_name = str(user.person) + ' ' + str(user.lab_session)\n self.assertEquals(expected_object_name, str(user))","sub_path":"main_site/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":8514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"221116979","text":"from . import Thumbnail\nimport os, re\nimport StringIO\nimport logging #DEBUG\nfrom google.appengine.api import app_identity\nfrom google.appengine.ext import blobstore\nfrom google.appengine.api import urlfetch\nimport cloudstorage as gcs\nimport google.appengine.api.images as gimages\n\ndef post_data(url, payload):\n import json\n import requests\n data = json.dumps(payload)\n headers={ \"content-type\":\"application/json\"\n , \"datatype\":\"json\"\n }\n r = requests.post(url,data=data, headers=headers)\n if requests.codes.OK == r.status_code:\n pass\n else:\n pass #TODO: check all images with r.raise_for_status()\n\n\ndef _create_thumbnail_async_handle_results(rpc):\n \"\"\" does nothing \"\"\"\n pass\n #result = rpc.get_result()\n\ndef _create_thumbnail_async_callback(rpc):\n \"\"\" Use a helper function to define the scope of the callback. \"\"\"\n \"\"\" see: https://cloud.google.com/appengine/docs/python/urlfetch/asynchronousrequests#make_fetch_call\"\"\"\n return lambda: _create_thumbnail_async_handle_results(rpc)\n\nclass ThumbnailGAEasync(Thumbnail):\n \"\"\"makes Thumbnail work with GAE, extends flask.thumbnail\"\"\"\n _gs_bucket = None\n def __init__(self, app=None):\n super(self.__class__, self).__init__(app)\n self._rpcs = []\n\n # check if thumbnail already exists\n def _thumb_exists(self, thumb_url):\n #return False\n # TODO: use fast! and google intern file check\n if(len(thumb_url)>5):\n scheme = thumb_url[:5]\n if scheme in [\"http:\",\"https\"]:\n return self._url_exists(thumb_url)\n else :\n return self._gcs_file_exists(thumb_url)\n return False\n\n\n def _url_exists(self, url):\n ## google api compatible\n #from google.appengine.api import urlfetch\n #result = urlfetch.fetch(url)\n #if result.status_code == 200:\n # return True\n\n ## requests (faster than urlfetch?)\n try:\n r = requests.head(url)\n if requests.codes.OK == r.status_code: # this url repsonse is OK\n return True\n except Exception as e:\n logging.error(\"EXEPTION: flask.thumbnailsGAE._url_exists: error {}\".format(str(e)))\n return False\n\n # it's rather slow, but quite safe\n def _gcs_file_exists(self, url):\n try:\n from furl import furl\n from os import path\n thumb_gs_path = self._gs_path(url)\n stat = gcs.stat(thumb_gs_path)\n if stat.filename == thumb_gs_path:\n if stat.st_size > 0:\n f = furl(url)\n if stat.content_type.startswith(\"image/\"):\n import mimetypes\n if mimetypes.guess_type(url) == stat.content_type:\n return True\n return False\n except gcs.NotFoundError as e:\n logging.debug(\"flask.thumbnailsGAE._gcs_file_exists: url: '{}' not found\\nException: {}\".format(url, str(e)))\n return False\n logging.debug(\"flask.thumbnailsGAE._gcs_file_exists: url: '{}' return false\".format(url))\n return False\n\n def _store_thumb(self, thumb_url, thumb_pic, quality=100):\n try:\n thumb_filepath = self._gs_path(thumb_url)\n import mimetypes\n (content_type, content_encoding) = mimetypes.guess_type(thumb_url, strict=True)\n with gcs.open(thumb_filepath,\n 'w',\n content_type=content_type,\n options={'x-goog-acl': 'public-read'}) as thumb_gcs:\n fileext=content_type.split(\"/\")[-1]\n thumb_pic.save(thumb_gcs, fileext) # TODO save(thumb_gcs, fileext, QUALITY)\n except Exception as e:\n # TODO: better:\n # raise\n raise Exception(\"flask.thumbnailGAE._store_thumb: couldn't create thumbnail @ '{}'\\nError: {}\".format(thumb_url, str(e)))\n return thumb_url\n\n def _check_and_create(self, thumb_url, img_path, size, crop, bg, quality):\n \"\"\" makes async calls to create this thumbnails \"\"\"\n # TODO: do without const\n if self.app.config[\"LOCAL\"] is True:\n hostname = \"http://localhost:8080\"\n else:\n hostname = \"http://wwwjoeschroecker-pydev.appspot.com\"\n\n crop = crop or None\n bg = bg or None\n quality = quality if quality else 100\n thumb_name = thumb_url.split(\"/\")[-1:][0]\n\n url = \"/\".join((\"/storethumb/img\", thumb_name))\n\n data = { \"thumb_url\": thumb_url, \"img_path\":img_path, \"size\":size, \"crop\":crop, \"bg\":bg, \"quality\":quality }\n ## headers contains the necessary Content-Type and Content-Length\n ## datagen is a generator object that yields the encoded parameters\n ## possibly read image and send directly?\n #from poster.encode import multipart_encode\n #datagen, headers = multipart_encode({\"image1\": open(\"DSC0001.jpg\", \"rb\")})\n\n #TODO: use app engine moduls:\n #see: https://cloud.google.com/appengine/docs/python/modules/#Python_Background_threads\n #see: https://cloud.google.com/appengine/docs/python/modules/converting\n ### GAE Deferred (not possible, because can't pickle, maybe simpler storage method)\n import json\n from google.appengine.ext import deferred\n ## e.g. self.create_thumbnail(data['thumb_url'], data['img_path'], data['size'], data['crop'], data['bg'], data['quality'])\n deferred.defer(post_data, \"\".join((hostname,url)) , data)\n # ENABLE DEBUG post_data(\"\".join((hostname,url)), data)\n ## GAE Taskque ##\n #import json\n #data = json.dumps(data)\n\n ## use class Task()\n #from google.appengine.api.taskqueue import Task\n ## better using class Task.add_async\n #task = Task( url=url\n # , params={'thumbname': thumb_name} # adds ?paramname=value\n # , payload=data\n # , headers={\n # \"content-type\":\"application/json\"\n # , \"datatype\":\"json\"\n # }\n # , method=\"PUT\"\n # )\n #task.add_async()\n\n ## use taskqueue.add\n #from google.appengine.api import taskqueue\n #taskqueue.add( url=url\n # #, params={'thumbname': thumb_name}\n # , payload=data\n # , headers={\n # \"content-type\":\"application/json\"\n # , \"datatype\":\"json\"\n # }\n # , method=\"PUT\"\n # )\n\n ## RPC Style (still seems slow because of unhandled waits)##\n #url = \"/\".join((hostname, \"storethumb\", thumb_name))\n #rpc = urlfetch.create_rpc(deadline=1)\n #rpc.callback = _create_thumbnail_async_callback(rpc) # callback does nothing\n\n #import json\n #data = json.dumps(data)\n #urlfetch.make_fetch_call(rpc, url\n # , payload=data\n # , headers={\n # \"content-type\":\"application/json\"\n # , \"datatype\":\"json\"\n # }\n # , method=urlfetch.PUT\n # )\n\n #if self.app.config[\"LOCAL\"] is True:\n # rpc.wait() # the development server doesn't execute async calls in the background\n # return\n #else:\n # self._rpcs.append(rpc)\n\n return\n\n #def _clear_rpc_wait(self):\n # \"\"\" clears all waiting rpc, should be call after request received, eg. in create_thumbnail \"\"\"\n # for rpc in self._rpcs:\n # rpc.wait()\n\n\n def create_thumbnail(self, thumb_url, img_path, size, crop, bg, quality):\n if self._thumb_exists(thumb_url) is False:\n # get original image and transform to thumbail\n self._create_thumb(thumb_url, img_path, size, crop, bg, quality) # store thumbnail and return url\n return\n\n def get_serve_url(self, url):\n #TODO: serve \"pure\" gcs urls, see: http://stackoverflow.com/questions/22174903/how-to-serve-cloudstorage-files-using-app-engine-sdk\n gs_filepath = self._gs_path(url)\n # get_serving_url method => very slow\n # blob_key = blobstore.create_gs_key(\"/gs\" + gs_filepath)\n # return gimages.get_serving_url(blob_key)\n\n # TODO: serve better urls instade, served directly from gcs\n # example url: http://storage.googleapis.com/wwwjoeschroecker-pydev.appspot.com/img/frontpage-script_200x200_85.jpg\n\n #local\n if self.app.config[\"LOCAL\"] is True:\n servingurl = \"http://localhost:8080/_ah/gcs\"+gs_filepath\n else:\n servingurl = \"http://storage.googleapis.com/wwwjoeschroecker-pydev.appspot.com\"+url\n return servingurl\n\n def _gs_path(self, url):\n if self._gs_bucket is None:\n self._gs_bucket = app_identity.get_default_gcs_bucket_name()\n # gs_bucket = os.environ.get('BUCKET_NAME', gs_bucket)\n gs_bucket = self._gs_bucket\n gs_path = \"/\" + gs_bucket + url\n return gs_path\n\n def _build_thumbnail_url(self, img_url,*args):\n #TODO: maybe build url for blobstore image transformations\n # see: https://cloud.google.com/appengine/docs/python/images/#Python_Transforming_images_from_the_Blobstore\n return super(ThumbnailGAEasync, self)._build_thumbnail_url(img_url, *args)\n\n","sub_path":"flask_thumbnails/gae_async.py","file_name":"gae_async.py","file_ext":"py","file_size_in_byte":9672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"108983373","text":"import numpy as np\nimport cv2\nimport cvui\nimport os\nimport time\nfrom yolo import Yolo\nfrom configparser import ConfigParser\n\nsysPath = os.path.dirname(os.path.abspath(__file__))\n\nsettings_file = os.path.join(sysPath,\"settings.ini\")\n\n#Read config.ini file\nconfig_object = ConfigParser()\nconfig_object.read(settings_file)\n\nwin_config = config_object[\"Window\"]\nWINDOW_NAME = win_config[\"name\"]\nwin_width = int(win_config[\"width\"])\nwin_height = int(win_config[\"height\"])\n\nimage_config = config_object[\"Image\"]\nblink_every_n_frames = int(image_config[\"blink_frames\"])\nimg_alpha = [float(image_config[\"alpha\"])]\nimg_beta = [float(image_config[\"beta\"])]\nimg_gamma = [float(image_config[\"gamma\"])]\nthreshold_min = [int(image_config[\"threshold_min\"])]\nthreshold_max = [int(image_config[\"threshold_max\"])]\ncontour_area_min = [int(image_config[\"contour_area_min\"])]\ncontour_area_max = [int(image_config[\"contour_area_max\"])]\n\nyolo_config = config_object[\"YOLO\"]\nyolo_confidence = float(yolo_config[\"confidence\"])\nyolo_blob_resize = int(yolo_config[\"blob_resize\"])\nyolo_weight = yolo_config[\"weights\"]\nyolo_names = yolo_config[\"names\"]\nyolo_config = yolo_config[\"config\"]\n\n## constants that should be changed from params (future)\n\nlib_folder = \"lib\"\n\nsource_folder = \"sources\"\nsource_file_name = \"Skype_Video2.mp4\"\n\n## Window\n(win_W, win_H) = (win_width, win_height)\n\nvideoPath = os.path.join(sysPath, os.path.join(source_folder,source_file_name))\n\ncap = cv2.VideoCapture()\n\n# YOLO\nweights = os.path.join(sysPath, os.path.join(lib_folder,yolo_weight))\nconfig = os.path.join(sysPath, os.path.join(lib_folder,yolo_config))\nnames = os.path.join(sysPath, os.path.join(lib_folder,yolo_names))\n\nyo = Yolo(weights, config, names)\nyo.confidence = yolo_confidence\nyo.blobResize = yolo_blob_resize\n\n# cap/video state\nstates = {0: \"Ready for Stream\", 1: \"Streaming\", 2: \"Recognizing\"}\nstate = [states.get(0, \"\")]\n\n# recognition button states\nrecog_btn_states = {0: \"Start recognition\", 1: \"Stop recognition\"}\nrecog_btn_state = [recog_btn_states.get(0, \"\")]\n\n# recognizers state\nrecog_states = {0: \"Contours >\", 1: \"< YOLO\"}\nrecog_state = [recog_states.get(0, \"\")]\n\n# contour debug state\ncontour_states = {0: \"normal\", 1: \"thresholded\"}\ncontour_state = [contour_states.get(0, \"\")]\n\n# sub ui states\nsub_ui_states = {0: \"full screen\", 1: \"tuning\"}\nsub_ui_state = [sub_ui_states.get(0,\"\")]\n\nisBlink = [True]\nrecognize = [False]\n\n\n#\n# UI Positioning\n#\n\n# status position\nstat_l_x, stat_l_y = int(0.02 * win_W), int(0.01 * win_H)\nfps_l_x, fps_l_y = int(0.7 * win_W), int(0.01 * win_H)\n\n# capture frame position\ncap_fr1_x, cap_fr1_y, cap_fr1_w, cap_fr1_h = (\n int(0.016 * win_W),\n int(0.04 * win_H),\n int(0.48 * win_W),\n int(0.54 * win_H),\n)\ncap_fr2_x, cap_fr2_y, cap_fr2_w, cap_fr2_h = (\n int(0.51 * win_W),\n int(0.04 * win_H),\n int(0.48 * win_W),\n int(0.54 * win_H),\n)\n\n# action buttons\n(start_b_x, start_b_y, start_b_w, start_b_h) = (\n int(0.016 * win_W),\n int(0.66 * win_H),\n int(0.113 * win_W),\n int(0.113 * win_W),\n)\n(recog_b_x, recog_b_y, recog_b_w, recog_b_h) = (\n int(0.15 * win_W),\n int(0.66 * win_H),\n int(0.14 * win_W),\n int(0.113 * win_W),\n)\n(stop_all_b_x, stop_all_b_y, stop_all_b_w, stop_all_b_h) = (\n int(0.016 * win_W),\n int(0.83 * win_H),\n int(0.274 * win_W),\n int(0.16 * win_H),\n)\n(reset_crop_b_x, reset_crop_b_y, reset_crop_b_w, reset_crop_b_h) = (\n int(0.016 * win_W),\n int(0.586 * win_H),\n int(0.06 * win_W),\n int(0.06 * win_H),\n)\n\n\n# crop trackbars\n## frame_x\n(trb_X_x, trb_X_y, trb_X_w) = (\n int(0.078 * win_W),\n int(0.586 * win_H),\n int(0.195 * win_W),\n)\n## frame y\n(trb_Y_x, trb_Y_y, trb_Y_w) = (\n int(0.275 * win_W),\n int(0.586 * win_H),\n int(0.195 * win_W),\n)\n## frame width\n(trb_W_x, trb_W_y, trb_W_w) = (\n int(0.472 * win_W),\n int(0.586 * win_H),\n int(0.195 * win_W),\n)\n## frame height\n(trb_H_x, trb_H_y, trb_H_w) = (\n int(0.669 * win_W),\n int(0.586 * win_H),\n int(0.195 * win_W),\n)\n\n# recognizers setup region\n(recog_set_x, recog_set_y, recog_set_w, recog_set_h) = (\n int(0.3 * win_W),\n int(0.66 * win_H),\n int(0.33 * win_W),\n int(0.33 * win_H),\n)\n\n# recognizers setup toggle button - yolo/contour\n(recog_set_btn_x, recog_set_btn_y, recog_set_btn_w, recog_set_btn_h) = (\n int(0.305 * win_W),\n int(0.665 * win_H),\n int(0.32 * win_W),\n int(0.03 * win_H),\n)\n\n#resognizer contour normal/binary toggle button\n(cnt_state_btn_x, cnt_state_btn_y, cnt_state_btn_w, cnt_state_btn_h) = (\n int(0.88 * win_W),\n int(0.586 * win_H),\n int(0.1 * win_W),\n int(0.03 * win_H),\n)\n# recognizers trackbars\n## threshold min\n(trecog_thr_min_x, trecog_thr_min_y, trecog_thr_min_w) = (\n int(0.42 * win_W),\n int(0.7 * win_H),\n int(0.195 * win_W),\n)\n## threshold max\n(trecog_thr_max_x, trecog_thr_max_y, trecog_thr_max_w) = (\n int(0.42 * win_W),\n int(0.75 * win_H),\n int(0.195 * win_W),\n)\n## alpha\n(trecog_alpha_x, trecog_alpha_y, trecog_alpha_w) = (\n int(0.42 * win_W),\n int(0.8 * win_H),\n int(0.195 * win_W),\n)\n## beta\n(trecog_beta_x, trecog_beta_y, trecog_beta_w) = (\n int(0.42 * win_W),\n int(0.85 * win_H),\n int(0.195 * win_W),\n)\n## contour area min\n(trecog_area_min_x, trecog_area_min_y, trecog_area_min_w) = (\n int(0.42 * win_W),\n int(0.9 * win_H),\n int(0.195 * win_W),\n)\n## contour area max\n(trecog_area_max_x, trecog_area_max_y, trecog_area_max_w) = (\n int(0.42 * win_W),\n int(0.95 * win_H),\n int(0.195 * win_W),\n)\n\n\n# recognition result region\n(recog_res_x, recog_res_y, recog_res_w, recog_res_h) = (\n int(0.64 * win_W),\n int(0.66 * win_H),\n int(0.35 * win_W),\n int(0.33 * win_H),\n)\n\n# other\n(max_width, max_height) = (int(0.48 * win_W), int(0.54 * win_H))\n\ntr_vX = [0]\ntr_vY = [0]\ntr_vW = [cap_fr1_w]\ntr_vH = [cap_fr1_h]\n\n#\n# Helpers\n#\ndef setup():\n tr_vX[0] = 0\n tr_vY[0] = 0\n tr_vW[0] = cap_fr1_w\n tr_vH[0] = cap_fr1_h\n\ndef saveConfig():\n with open(settings_file, 'w') as configfile: # save\n config_object.write(configfile)\n\ndef scaleImageToMax(image, max_w, max_h):\n w = image.shape[1]\n h = image.shape[0]\n\n k_w = max_w / w\n k_max_h = h * k_w\n\n if k_max_h > max_h:\n k_h = max_h / h\n return cv2.resize(image, (int(k_h * w), int(k_h * h)))\n else:\n return cv2.resize(image, (int(k_w * w), int(k_w * h)))\n\ndef gammaCorrection(image, gamma):\n lookUpTable = np.empty((1, 256), np.uint8)\n for i in range(256):\n lookUpTable[0, i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)\n\n res = cv2.LUT(image, lookUpTable)\n return res\n\n\ndef toggleRecognizers():\n if recog_state[0] == recog_states.get(1, \"\"):\n recog_state[0] = recog_states.get(0, \"\")\n ## some controls for YOLO\n else:\n recog_state[0] = recog_states.get(1, \"\")\n\n\n# YOLO\ndef detectObjectsFrom(img, frame):\n yo.detectFrom(img)\n objects = yo.objects\n # print(\"[INFO] YOLO objects: {:}\".format(len(objects)))\n\n # Visualize detected on source image\n font = cv2.FONT_HERSHEY_PLAIN\n for obj in objects:\n label = obj.name + \" {:}\".format(objects.index(obj))\n textColor = (0, 0, 0)\n boxColor = (150, 180, 20)\n cv2.rectangle(\n img,\n (obj.x, obj.y),\n (obj.x + obj.width, obj.y + obj.height),\n boxColor,\n 1,\n )\n cv2.putText(img, label, (obj.x, obj.y - 5), font, 1, textColor, 2)\n\n obj_index = 0\n for obj in objects:\n label = (\n obj.name\n + \" {:}: \".format(objects.index(obj))\n + \"{:.6f} \".format(obj.confidence)\n + \"; x: \"\n + str((obj.x + obj.width) / 2)\n + \", y: \"\n + str((obj.y + obj.height) / 2)\n )\n cvui.text(frame, recog_res_x + 20, recog_res_y + obj_index * 20 + 20, label)\n obj_index += 1\n\n\n# Contours\ndef correctedImage(img, alpha, beta, gamma):\n corrected_img = gammaCorrection(img, gamma)\n converted_img = cv2.convertScaleAbs(corrected_img, alpha=alpha, beta=beta)\n\n gray = cv2.cvtColor(converted_img, cv2.COLOR_BGR2GRAY)\n _, threshold_img = cv2.threshold(\n gray, threshold_min[0], threshold_max[0], cv2.THRESH_BINARY\n )\n threshold_img = cv2.medianBlur(threshold_img, 5)\n threshold_img = cv2.medianBlur(threshold_img, 5)\n return threshold_img\n\ndef detectContoursFrom(img, frame, alpha, beta, gamma, area_min, area_max):\n threshold_img = correctedImage(img, alpha, beta, gamma)\n\n # Detect\n contours, _ = cv2.findContours(\n threshold_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE\n )\n cntrs_cnt = 0\n good_contours = []\n for cnt in contours:\n area = cv2.contourArea(cnt)\n print(\"area: {:}\".format(area))\n # Distinguish small and big\n\n if area_min < area < area_max:\n good_contours.append(cnt)\n cntrs_cnt += 1\n\n print(\"detect contours: {:}\".format(cntrs_cnt))\n\n obj_index = 0\n\n for cnt in good_contours:\n # draw minimum area box rotated\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect) ##\n box = np.int0(box)\n cv2.drawContours(img, [box], 0, (0, 0, 255), 2)\n ((rcx, rcy), (rw, rh), angle) = rect\n\n if rw < rh:\n angle = angle - 90\n\n print(\"bos: {:.4f}\".format(angle))\n # draw bounding contour box\n (x, y, w, h) = cv2.boundingRect(cnt)\n area = cv2.contourArea(cnt)\n # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n cv2.putText(\n img, \"{:}, {}\".format(obj_index, str(area)), (x, y), 1, 1, (0, 255, 0)\n )\n\n # setup and draw result label\n label = (\n \"{:}: \".format(obj_index)\n + \"; x: \"\n + str((x + w) / 2)\n + \", y: \"\n + str((y + h) / 2)\n + \", area: {:}\".format(cv2.contourArea(cnt))\n + \", deg: {:.1f}\".format(angle)\n )\n cvui.text(frame, recog_res_x + 10, recog_res_y + obj_index * 20 + 20, label)\n obj_index += 1\n\n\n#\n# Button actions\n#\n\n#### Stream\ndef startStream():\n cap.release()\n if not cap.isOpened():\n state[0] = states.get(1, \"None\")\n cap.open(videoPath) # (\"rtsp://admin:@192.168.1.234:554\")#\n cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)\n\n\ndef stopStream():\n state[0] = states.get(0, \"None\")\n recognize[0] = False\n cap.release()\n\n\ndef resetCrop():\n setup()\n\n\n#### Recognition\ndef startRecognize():\n state[0] = states.get(2, \"None\")\n recog_btn_state[0] = recog_btn_states.get(1, \"None\")\n recognize[0] = True\n\ndef stopRecognize():\n state[0] = states.get(1, \"None\")\n recog_btn_state[0] = recog_btn_states.get(0, \"None\")\n recognize[0] = False\n\ndef contourStateToggle():\n if contour_state[0] == contour_states.get(0,\"\"):\n contour_state[0] = contour_states.get(1,\"\")\n else:\n contour_state[0] = contour_states.get(0,\"\")\n setup()\n\n#### TODO\ndef stopAll():\n stopStream()\n\n\ndef cropTrackBars(frame, cv_sh_w, cv_sh_h):\n # reset crop button\n if cvui.button(\n frame, reset_crop_b_x, reset_crop_b_y, reset_crop_b_w, reset_crop_b_h, \"Reset\"\n ):\n resetCrop()\n # x\n cvui.text(frame, trb_X_x + int(0.1 * win_W), trb_X_y - int(0.002 * win_H), \"X\", 0.5)\n if cvui.trackbar(frame, trb_X_x, trb_X_y, trb_X_w, tr_vX, 0.0, cv_sh_w):\n cr_x = cv_sh_w - int(tr_vX[0])\n if cr_x < tr_vW[0]:\n tr_vW[0] = cr_x\n # y\n cvui.text(frame, trb_Y_x + int(0.1 * win_W), trb_Y_y - int(0.002 * win_H), \"Y\", 0.5)\n if cvui.trackbar(frame, trb_Y_x, trb_Y_y, trb_Y_w, tr_vY, 0.0, cv_sh_h):\n cr_y = cv_sh_h - int(tr_vY[0])\n if cr_y < tr_vH[0]:\n tr_vH[0] = cr_y\n # w\n cvui.text(\n frame, trb_W_x + int(0.08 * win_W), trb_W_y - int(0.002 * win_H), \"Width\", 0.5\n )\n cvui.trackbar(\n frame, trb_W_x, trb_W_y, trb_W_w, tr_vW, tr_vX[0], cv_sh_w - int(tr_vX[0])\n )\n # h\n cvui.text(\n frame, trb_H_x + int(0.08 * win_W), trb_H_y - int(0.002 * win_H), \"Height\", 0.5\n )\n cvui.trackbar(\n frame, trb_H_x, trb_H_y, trb_H_w, tr_vH, tr_vY[0], cv_sh_h - int(tr_vY[0])\n )\n\n\ndef contourTrackBars(frame):\n # threshold\n cvui.text(\n frame,\n trecog_thr_min_x - int(0.1 * win_W),\n trecog_thr_min_y + int(0.015 * win_H),\n \"Threshold min\",\n )\n cvui.trackbar(\n frame,\n trecog_thr_min_x,\n trecog_thr_min_y,\n trecog_thr_min_w,\n threshold_min,\n 1,\n threshold_max[0] - 1,\n )\n\n cvui.text(\n frame,\n trecog_thr_max_x - int(0.1 * win_W),\n trecog_thr_max_y + int(0.01 * win_H),\n \"Threshold max\",\n )\n cvui.trackbar(\n frame,\n trecog_thr_max_x,\n trecog_thr_max_y,\n trecog_thr_max_w,\n threshold_max,\n threshold_min[0],\n 255,\n )\n\n # image correction\n cvui.text(\n frame,\n trecog_alpha_x - int(0.1 * win_W),\n trecog_alpha_y + int(0.015 * win_H),\n \"Correct Alpha\",\n )\n cvui.trackbar(\n frame, trecog_alpha_x, trecog_alpha_y, trecog_alpha_w, img_alpha, 1.0, 3.0, 0.1\n )\n\n cvui.text(\n frame,\n trecog_beta_x - int(0.1 * win_W),\n trecog_beta_y + int(0.015 * win_H),\n \"Correct Beta\",\n )\n cvui.trackbar(frame, trecog_beta_x, trecog_beta_y, trecog_beta_w, img_beta, 1, 100)\n\n # area\n cvui.text(\n frame,\n trecog_area_min_x - int(0.1 * win_W),\n trecog_area_min_y + int(0.015 * win_H),\n \"Area min\",\n )\n cvui.trackbar(\n frame,\n trecog_area_min_x,\n trecog_area_min_y,\n trecog_area_min_w,\n contour_area_min,\n 1.0,\n contour_area_max[0] - 1,\n )\n\n cvui.text(\n frame,\n trecog_area_max_x - int(0.1 * win_W),\n trecog_area_max_y + int(0.015 * win_H),\n \"Area max\",\n )\n cvui.trackbar(\n frame,\n trecog_area_max_x,\n trecog_area_max_y,\n trecog_area_max_w,\n contour_area_max,\n contour_area_min[0],\n 20000,\n )\n\n\ndef main():\n frame = np.zeros((win_H, win_W, 3), np.uint8)\n cvui.init(WINDOW_NAME)\n fr = 0\n while True:\n frame[:] = (0, 0, 0)\n\n objects = []\n\n if cap.isOpened():\n # main stream image\n ret, cv_frame_orig = cap.read()\n\n if ret:\n # status message blink\n fr += 1\n if fr % blink_every_n_frames == 0:\n isBlink[0] = not isBlink[0]\n if isBlink[0]:\n cvui.text(frame, stat_l_x, stat_l_y, state[0])\n\n # original stream image\n cv_frame = scaleImageToMax(cv_frame_orig, max_width, max_height)\n cv_sh_h, cv_sh_w, _ = cv_frame.shape\n cv_sh_xx = cap_fr1_x + int((max_width - cv_sh_w) / 2)\n cv_sh_yy = cap_fr1_y + int((max_height - cv_sh_h) / 2)\n cvui.image(frame, cv_sh_xx, cv_sh_yy, cv_frame)\n cv_frame_h, cv_frame_w, _ = cv_frame.shape\n\n # cropped stream image\n crop_image = cv_frame[\n int(tr_vY[0]) : (int(tr_vH[0]) + int(tr_vY[0])),\n int(tr_vX[0]) : (int(tr_vW[0]) + int(tr_vX[0])),\n ]\n crop__scaled_image = scaleImageToMax(crop_image, max_width, max_height)\n cr_sh_h, cr_sh_w, _ = crop__scaled_image.shape\n cr_sh_xx = cap_fr2_x + int((max_width - cr_sh_w) / 2)\n cr_sh_yy = cap_fr2_y + int((max_height - cr_sh_h) / 2)\n\n # crop track bars\n cropTrackBars(frame, cv_sh_w, cv_sh_h)\n\n # zooming rect\n cvui.rect(\n frame,\n cv_sh_xx + int(tr_vX[0]),\n cv_sh_yy + int(tr_vY[0]),\n min(cv_sh_w, int(tr_vW[0])),\n min(cv_sh_h, int(tr_vH[0])),\n 0x00FF00,\n )\n\n ## Setup recognition UI\n # present toggle to switch 'YOLO' and 'filters'. Toggle will drop recognition - need manual start\n # 'filter' will have adjustable trackbars for threshold (2), alpha, beta, area_min, area_max = 6 ,\n if cvui.button(\n frame,\n recog_set_btn_x,\n recog_set_btn_y,\n recog_set_btn_w,\n recog_set_btn_h,\n recog_state[0],\n ):\n stopRecognize()\n toggleRecognizers()\n\n # recognition of objects and data presenting\n if recognize[0] == True:\n start = time.time()\n if recog_state[0] == recog_states.get(0, \"\"):\n detectContoursFrom(\n crop__scaled_image,\n frame,\n img_alpha[0],\n img_beta[0],\n img_gamma[0],\n contour_area_min[0],\n contour_area_max[0],\n )\n contourTrackBars(frame)\n\n else:\n detectObjectsFrom(crop__scaled_image, frame)\n end = time.time()\n cvui.text(frame, fps_l_x, fps_l_y, \"recognition time: {:5f} sec per frame\".format(end - start))\n\n\n # draw result\n if contour_state[0] == contour_states.get(0,\"\"):\n cvui.image(frame, cr_sh_xx, cr_sh_yy, crop__scaled_image)\n else:\n colored_grey = cv2.cvtColor(correctedImage(crop__scaled_image, img_alpha[0],\n img_beta[0],\n img_gamma[0]), cv2.COLOR_GRAY2BGR)\n cvui.image(frame, cr_sh_xx, cr_sh_yy, colored_grey)\n\n else:\n cap.release()\n else:\n cvui.text(frame, stat_l_x, stat_l_y, states.get(0, \"\"))\n\n ##\n ## Static UI\n ##\n\n # frame around image\n cvui.rect(frame, cap_fr1_x, cap_fr1_y, cap_fr1_w, cap_fr1_h, 0xFFFFFF)\n cvui.rect(frame, cap_fr2_x, cap_fr2_y, cap_fr2_w, cap_fr2_h, 0xFFFFFF)\n\n # start stream button\n if cvui.button(\n frame, start_b_x, start_b_y, start_b_w, start_b_h, \"Start stream\"\n ):\n startStream()\n\n # start recognition button\n if cvui.button(\n frame, recog_b_x, recog_b_y, recog_b_w, recog_b_h, recog_btn_state[0]\n ):\n if recognize[0] == True:\n stopRecognize()\n else:\n startRecognize()\n\n # stop all button\n if cvui.button(\n frame, stop_all_b_x, stop_all_b_y, stop_all_b_w, stop_all_b_h, \"STOP!\"\n ):\n stopAll()\n\n # recognizers setup region\n cvui.rect(frame, recog_set_x, recog_set_y, recog_set_w, recog_set_h, 0x008EDF)\n\n # contour toggle\n if recognize[0] == True:\n if recog_state[0] == recog_states.get(0,\"\"):\n if cvui.button(frame, cnt_state_btn_x, cnt_state_btn_y, cnt_state_btn_w, cnt_state_btn_h, contour_state[0]):\n contourStateToggle()\n\n # recognition result region\n cvui.rect(frame, recog_res_x, recog_res_y, recog_res_w, recog_res_h, 0xFFFF00)\n\n # update all ui\n cvui.update()\n\n # Show everything on the screen\n cv2.imshow(WINDOW_NAME, frame)\n\n # Check if ESC key was pressed\n if cv2.waitKey(20) == 27:\n stopStream()\n break\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"cvui/cvui_UI-bin_filter.py","file_name":"cvui_UI-bin_filter.py","file_ext":"py","file_size_in_byte":19799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"151289296","text":"\"\"\"\n\n The non-machine-learning game serving as background created by:\n\n Sample Breakout Game\n\n Sample Python/Pygame Programs\n Simpson College Computer Science\n http://programarcadegames.com/\n http://simpson.edu/computer-science/\n\n\n\n\"\"\"\n\n\nimport math\nimport pygame\nimport torch\ndevice = torch.device(\"cuda:0\")\ndtype = torch.float\n# Define some colors\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nblue = (0, 0, 255)\n\n# Size of break-out blocks\nblock_width = 23\nblock_height = 15\n\nclass Block(pygame.sprite.Sprite):\n \"\"\"This class represents each block that will get knocked out by the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n\n def __init__(self, color, x, y):\n \"\"\" Constructor. Pass in the color of the block,\n and its x and y position. \"\"\"\n\n # Call the parent class (Sprite) constructor\n super(Block, self).__init__()\n\n # Create the image of the block of appropriate size\n # The width and height are sent as a list for the first parameter.\n self.image = pygame.Surface([block_width, block_height])\n\n # Fill the image with the appropriate color\n self.image.fill(color)\n\n # Fetch the rectangle object that has the dimensions of the image\n self.rect = self.image.get_rect()\n\n # Move the top left of the rectangle to x,y.\n # This is where our block will appear..\n self.rect.x = x\n self.rect.y = y\n\n\nclass Ball(pygame.sprite.Sprite):\n \"\"\" This class represents the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n\n # Speed in pixels per cycle\n speed = 2.0\n\n # Floating point representation of where the ball is\n x = 0.0\n y = 180.0\n\n # Direction of ball (in degrees)\n direction = 200\n\n width = 10\n height = 10\n\n # Constructor. Pass in the color of the block, and its x and y position\n def __init__(self):\n # Call the parent class (Sprite) constructor\n super(Ball, self).__init__()\n\n # Create the image of the ball\n self.image = pygame.Surface([self.width, self.height])\n\n # Color the ball\n self.image.fill(white)\n\n # Get a rectangle object that shows where our image is\n self.rect = self.image.get_rect()\n\n # Get attributes for the height/width of the screen\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n # self.x = torch.rand(0, self.screenwidth - self.width)\n\n def bounce(self, diff):\n \"\"\" This function will bounce the ball\n off a horizontal surface (not a vertical one) \"\"\"\n\n self.direction = (180 - self.direction) % 360\n self.direction -= diff\n\n def read_pos(self):\n return self.rect.x\n\n def update(self):\n \"\"\" Update the position of the ball. \"\"\"\n # Sine and Cosine work in degrees, so we have to convert them\n direction_radians = math.radians(self.direction)\n\n # Change the position (x and y) according to the speed and direction\n self.x += self.speed * math.sin(direction_radians)\n self.y -= self.speed * math.cos(direction_radians)\n\n # Move the image to where our x and y are\n self.rect.x = self.x\n self.rect.y = self.y\n\n # Do we bounce off the top of the screen?\n if self.y <= 0:\n self.bounce(0)\n self.y = 1\n\n # Do we bounce off the left of the screen?\n if self.x <= 0:\n self.direction = (360 - self.direction) % 360\n self.x = 1\n\n # Do we bounce of the right side of the screen?\n if self.x > self.screenwidth - self.width:\n self.direction = (360 - self.direction) % 360\n self.x = self.screenwidth - self.width - 1\n\n # Did we fall off the bottom edge of the screen?\n if self.y > 600:\n return True\n else:\n return False\n\n\nclass Player(pygame.sprite.Sprite):\n \"\"\" This class represents the bar at the bottom that the\n player controls. \"\"\"\n\n def __init__(self):\n \"\"\" Constructor for Player. \"\"\"\n # Call the parent's constructor\n super(Player, self).__init__()\n\n self.width = 75\n self.height = 15\n self.image = pygame.Surface([self.width, self.height])\n self.image.fill((white))\n\n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n\n self.rect.x = 0\n self.rect.y = self.screenheight - self.height\n\n def update(self, decision):\n \"\"\" Update the player position. \"\"\"\n # Get where the mouse is\n # pos = pygame.mouse.get_pos()\n # Set the left side of the player bar to the mouse position\n\n # self.rect.x = pos[0]\n if decision[0][0] == 1:\n self.rect.x -= 3\n if decision[0][1] == 1:\n pass\n if decision[0][2] == 1:\n self.rect.x += 3\n\n # Make sure we don't push the player paddle\n\n # off the right side of the screen\n if self.rect.x > self.screenwidth - self.width:\n self.rect.x = self.screenwidth - self.width\n if self.rect.x < 0:\n self.rect.x = 0\n def read_pos(self):\n return self.rect.x\n\n\nclass Network:\n\n def __init__(self):\n\n self.D_in, self.H1, self.H2, self.D_out = 4, 100, 100, 3\n self.learning_rate = 1e-6\n\n # Declaring weighs tensors\n self.w1 = torch.randn(self.D_in, self.H1, device=device, dtype=dtype)\n self.w2 = torch.randn(self.H1, self.H2, device=device, dtype=dtype)\n self.w3 = torch.randn(self.H2, self.D_out, device=device, dtype=dtype)\n\n def forward(self, input_arr):\n\n self.h1 = input_arr.mm(self.w1)\n self.h1_relu = self.h1.clamp(min=0)\n self.h2 = self.h1_relu.mm(self.w2)\n self.h2_relu = self.h2.clamp(min=0)\n y_pred = self.h2_relu.mm(self.w3)\n predicted_move = y_pred\n temp = torch.argmax(y_pred[0])\n if temp == 0:\n predicted_move[0][0], predicted_move[0][1], predicted_move[0][2] = 1, 0, 0\n if temp == 1:\n predicted_move[0][0], predicted_move[0][1], predicted_move[0][2] = 0, 1, 0\n if temp == 2:\n predicted_move[0][0], predicted_move[0][1], predicted_move[0][2] = 0, 0, 1\n\n return predicted_move\n\n\n def train(self, err, input_arr):\n\n grad_y_pred = -err\n grad_w3 = self.h2_relu.t().mm(grad_y_pred)\n grad_h2_relu = grad_y_pred.mm(self.w3.t())\n grad_h2 = grad_h2_relu.clone()\n grad_h2[self.h2 < 0] = 0\n\n grad_w2 = self.h1_relu.t().mm(grad_h2)\n grad_h1_relu = grad_h2.mm(self.w2.t())\n grad_h1 = grad_h1_relu.clone()\n grad_h1[self.h1 < 0] = 0\n\n grad_w1 = input_arr.t().mm(grad_h1)\n\n # Update weights using gradient descent\n self.w1 -= self.learning_rate * grad_w1\n self.w2 -= self.learning_rate * grad_w2\n self.w3 -= self.learning_rate * grad_w3\n\n# Call this function so the Pygame library can initialize itself\npygame.init()\nexit_program = False\nepochs = 200\nepoch=0\nerr_log = torch.randn(1, 3, device=device, dtype=dtype)\n\nnetwork = Network()\nwhile not exit_program:\n epoch += 1\n if epoch == epochs:\n break\n # Create an 800x600 sized screen\n screen = pygame.display.set_mode([800, 600])\n\n # Set the title of the window\n pygame.display.set_caption('Breakout')\n\n # Enable this to make the mouse disappear when over our window\n pygame.mouse.set_visible(0)\n\n # This is a font we use to draw text on the screen (size 36)\n font = pygame.font.Font(None, 36)\n\n # Create a surface we can draw on\n background = pygame.Surface(screen.get_size())\n\n # Create sprite lists\n blocks = pygame.sprite.Group()\n balls = pygame.sprite.Group()\n allsprites = pygame.sprite.Group()\n\n # Create the player paddle object\n player = Player()\n allsprites.add(player)\n\n # Create the ball\n ball = Ball()\n allsprites.add(ball)\n balls.add(ball)\n\n # The top of the block (y position)\n top = 80\n\n # Number of blocks to create\n blockcount = 32\n\n # --- Create blocks\n\n # Five rows of blocks\n for row in range(5):\n # 32 columns of blocks\n for column in range(0, blockcount):\n # Create a block (color,x,y)\n block = Block(blue, column * (block_width + 2) + 1, top)\n blocks.add(block)\n allsprites.add(block)\n # Move the top of the next row down\n top += block_height + 2\n initial_blocks = len(blocks)\n # Clock to limit speed\n clock = pygame.time.Clock()\n\n # Is the game over?\n game_over = False\n\n # Initialization of network input\n input_array = torch.randn(1, 4, device=device, dtype=dtype)\n\n # Main program loop\n\n while not game_over:\n\n # Network input update\n input_array[0][0] = ball.x\n input_array[0][1] = ball.y\n input_array[0][2] = ball.direction\n input_array[0][3] = player.read_pos()\n\n # On regular computer game will be slower anyway\n clock.tick(1000)\n\n # Clear the screen\n screen.fill(black)\n\n # Process the events in the game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_program = True\n\n # Update the ball and player position as long\n # as the game is not over. In case game is over, check on which side of the player\n # has the ball touched the ground.\n if ball.update():\n if ball.read_pos() > player.read_pos():\n err_log[0][0], err_log[0][1], err_log[0][2] = 0, 0, 1\n else:\n err_log[0][0], err_log[0][1], err_log[0][2] = 1, 0, 0\n game_over = True\n player.update(network.forward(input_array))\n\n # If we are done, print game over\n\n if exit_program == True:\n break\n\n # See if the ball hits the player paddle\n if pygame.sprite.spritecollide(player, balls, False):\n # The 'diff' lets you try to bounce the ball left or right\n # depending where on the paddle you hit it\n diff = (player.rect.x + player.width / 2) - (ball.rect.x + ball.width / 2)\n\n # Set the ball's y position in case\n # we hit the ball on the edge of the paddle\n ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1\n ball.bounce(diff)\n\n # Check for collisions between the ball and the blocks\n deadblocks = pygame.sprite.spritecollide(ball, blocks, True)\n\n # If we actually hit a block, bounce the ball\n if len(deadblocks) > 0:\n ball.bounce(0)\n\n # Game ends if all the blocks are gone\n if len(blocks) == 0:\n game_over = True\n\n # Draw Everything\n allsprites.draw(screen)\n\n # Flip the screen and show what we've drawn\n pygame.display.flip()\n\n\n network.train(err_log, input_array)\n\n\npygame.quit()","sub_path":"game_script.py","file_name":"game_script.py","file_ext":"py","file_size_in_byte":11181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"27853751","text":"#Efrain Duarte Lopez\ndef readNumbersFromFile(x):\n f=open(x,\"r\")\n t=0\n n=0\n numbers=[]\n for line in f:\n a=int(line[0:len(line)])\n t=t+a\n n=n+1\n numbers.append(a)\n print (line)\n av=t/n\n sm=0\n for i in numbers:\n su=(i-av)**2\n sm=sm+su\n st=(sm/(n-1))**(0.5)\n print (\"the total of the values is: \",t)\n print (\"The number of values is: \",n)\n print (\"The average of the values is: \",av)\n print (\"the standard deviation of the values is: \",st)\n\nreadNumbersFromFile(\"numbers.txt\")\n","sub_path":"quiz11.py","file_name":"quiz11.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"318416298","text":"#operador ternário\n\nlogged_user = False\n\nif logged_user:\n msg = 'Logado'\nelse:\n msg = 'Necessário logar'\n\nprint(msg)\n\n###\nlogged_user = False\nmsg = 'Usuário logado' if logged_user else 'Usuário precisa logar'\nprint(msg)\n\n###\nidade = 18\nif idade >= 18:\n print('Pode entrar')\nelse:\n print('Não pode entrar')\n\nidade = input('Qual sua idade?')\n\ntry:\n idade = int(idade)\n maior = (idade >= 18)\n msg = 'Pode acessar' if maior else 'Não pode entrar'\n print(msg)\nexcept ValueError as err:\n print('Digite apenas números')\n pass","sub_path":"Lógica de programação/Aula39/aula39.py","file_name":"aula39.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"342052961","text":"# -*- Mode: Python -*-\n# vi:si:et:sw=4:sts=4:ts=4\nfrom twisted.internet import defer\n\nfrom feat import everything\nfrom feat.common import first\nfrom feat.test.integration import common\nfrom feat.common.text_helper import format_block\nfrom feat.agents.base import recipient, dbtools\nfrom feat.agents.common import host, raage\nfrom feat.interface.agent import Access, Address, Storage\n\n\ndef checkAllocation(test, agent, resources):\n _, allocated = agent.list_resource()\n for key in resources:\n test.assertEquals(allocated[key], resources[key], key)\n\n\ndef checkNoAllocated(test, a_id):\n test.assertEquals(a_id, None)\n\n\n@common.attr(timescale=0.1)\n@common.attr('slow')\nclass SingleHostAllocationSimulation(common.SimulationTest):\n\n timeout = 20\n\n @defer.inlineCallbacks\n def prolog(self):\n setup = format_block(\"\"\"\n load('feat.test.integration.resource')\n\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n\n host_desc = descriptor_factory('host_agent')\n req_desc = descriptor_factory('requesting_agent')\n\n host_medium = agency.start_agent(host_desc, hostdef=hostdef)\n host_agent = host_medium.get_agent()\n\n host_agent.wait_for_ready()\n host_agent.start_agent(req_desc)\n \"\"\")\n\n hostdef = host.HostDef()\n hostdef.resources = {\"host\": 1, \"epu\": 10}\n hostdef.categories = {\"access\": Access.private,\n \"address\": Address.dynamic,\n \"storage\": Storage.static}\n self.set_local(\"hostdef\", hostdef)\n\n yield self.process(setup)\n yield self.wait_for_idle(10)\n\n raage_medium = list(self.driver.iter_agents('raage_agent'))[0]\n self.raage_agent = raage_medium.get_agent()\n self.host_medium = self.get_local('host_medium')\n self.host_agent = self.get_local('host_agent')\n medium = yield self.driver.find_agent(self.get_local('req_desc'))\n self.req_agent = medium.get_agent()\n\n def testValidateProlog(self):\n self.assertEqual(1, self.count_agents('host_agent'))\n self.assertEqual(1, self.count_agents('shard_agent'))\n self.assertEqual(1, self.count_agents('raage_agent'))\n self.assertEqual(1, self.count_agents('requesting_agent'))\n\n @defer.inlineCallbacks\n def testFindHost(self):\n resources = {'host': 1}\n categories = {'access': Access.private,\n 'address': Address.none,\n 'storage': Storage.static}\n checkAllocation(self, self.host_agent, {'host': 0})\n self.info('starting test')\n allocation_id, irecipient = \\\n yield self.req_agent.request_resource(resources, categories)\n checkAllocation(self, self.host_agent, resources)\n self.assertEqual(recipient.IRecipient(self.host_medium), irecipient)\n\n @defer.inlineCallbacks\n def testNoHostFree(self):\n resources = {'host': 1}\n categories = {}\n allocation_id, irecipient = \\\n yield self.req_agent.request_resource(resources, categories)\n yield self.host_medium.wait_for_protocols_finish()\n checkAllocation(self, self.host_agent, resources)\n d = self.req_agent.request_resource(resources, categories)\n self.assertFailure(d, raage.AllocationFailedError)\n yield d\n\n @defer.inlineCallbacks\n def testBadResource(self):\n resources = {'beers': 999}\n categories = {}\n d = self.req_agent.request_resource(resources, categories)\n self.assertFailure(d, raage.AllocationFailedError)\n yield d\n\n @defer.inlineCallbacks\n def testBadCategory(self):\n resources = {'host': 1}\n categories = {'address': Address.fixed}\n d = self.req_agent.request_resource(resources, categories)\n self.assertFailure(d, raage.AllocationFailedError)\n yield d\n\n\n@common.attr(timescale=0.1)\n@common.attr('slow')\nclass MultiHostAllocationSimulation(common.SimulationTest):\n\n timeout = 20\n\n @defer.inlineCallbacks\n def prolog(self):\n setup = format_block(\"\"\"\n load('feat.test.integration.resource')\n host1_desc = descriptor_factory('host_agent')\n host2_desc = descriptor_factory('host_agent')\n host3_desc = descriptor_factory('host_agent')\n req_desc = descriptor_factory('requesting_agent')\n\n # First agency will eventually run Host, Shard, Raage and\n # Requesting agent\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(host1_desc, hostdef=hostdef)\n host = _.get_agent()\n\n wait_for_idle()\n host.start_agent(req_desc)\n\n # Second agency runs the host agent\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(host2_desc, hostdef=hostdef)\n wait_for_idle()\n\n # Third is like second\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(host3_desc, hostdef=hostdef)\n wait_for_idle()\n \"\"\")\n\n hostdef = host.HostDef()\n hostdef.resources = {\"host\": 1, \"epu\": 10}\n hostdef.categories = {\"access\": Access.private,\n \"address\": Address.dynamic,\n \"storage\": Storage.static}\n self.set_local(\"hostdef\", hostdef)\n\n yield self.process(setup)\n yield self.wait_for_idle(20)\n\n self.agents = [x.get_agent() \\\n for x in self.driver.iter_agents('host_agent')]\n req_medium = list(self.driver.iter_agents('requesting_agent'))[0]\n self.req_agent = req_medium.get_agent()\n\n @defer.inlineCallbacks\n def _waitToFinish(self, _=None):\n for x in self.driver.iter_agents():\n yield x._cancel_long_running_protocols()\n yield x.wait_for_protocols_finish()\n\n @defer.inlineCallbacks\n def _startAllocation(self, resources, categories, count, sequencial=True):\n d_list = list()\n for i in range(count):\n d = self.req_agent.request_resource(resources, categories)\n if sequencial:\n yield d\n else:\n d_list.append(d)\n if not sequencial:\n yield defer.DeferredList(d_list)\n\n def _checkAllocations(self, resources, count):\n for agent in self.agents:\n _, allocated = agent.list_resource()\n if all([allocated[name] == value \\\n for name, value in resources.iteritems()]):\n count -= 1\n self.assertEquals(count, 0)\n\n def testValidateProlog(self):\n self.assertEqual(1, self.count_agents('shard_agent'))\n self.assertEqual(1, self.count_agents('raage_agent'))\n self.assertEqual(1, self.count_agents('requesting_agent'))\n self.assertEqual(3, len(self.agents))\n\n @defer.inlineCallbacks\n def testAllocateOneHost(self):\n resources = {'host': 1}\n categories = {'access': Access.private}\n self._checkAllocations(resources, 0)\n yield self._startAllocation(resources, categories, 1)\n yield self._waitToFinish()\n self._checkAllocations(resources, 1)\n\n @defer.inlineCallbacks\n def testAllocateAllHostsSecuencially(self):\n resources = {'host': 1}\n categories = {'access': Access.private}\n self._checkAllocations(resources, 0)\n yield self._startAllocation(resources, categories, 1)\n yield self._waitToFinish()\n self._checkAllocations(resources, 1)\n\n yield self._startAllocation(resources, categories, 1)\n yield self._waitToFinish()\n self._checkAllocations(resources, 2)\n\n @defer.inlineCallbacks\n def testAllocateSomeHosts(self):\n resources = {'host': 1}\n categories = {'access': Access.private}\n self._checkAllocations(resources, 0)\n yield self._startAllocation(resources, categories, 2)\n yield self._waitToFinish()\n self._checkAllocations(resources, 2)\n\n @common.attr(timescale=0.5)\n @defer.inlineCallbacks\n def testAllocateAllHosts(self):\n resources = {'host': 1}\n categories = {'access': Access.private}\n self._checkAllocations(resources, 0)\n yield self._startAllocation(resources, categories,\n 3, sequencial=False)\n yield self._waitToFinish()\n self._checkAllocations(resources, 3)\n\n\n@common.attr(timescale=0.1)\n@common.attr('slow')\nclass ContractNestingSimulation(common.SimulationTest):\n\n timeout = 40\n\n def setUp(self):\n config = everything.shard_agent.ShardAgentConfiguration(\n doc_id = u'test-config',\n hosts_per_shard = 2)\n dbtools.initial_data(config)\n self.override_config('shard_agent', config)\n return common.SimulationTest.setUp(self)\n\n @defer.inlineCallbacks\n def prolog(self):\n setup = format_block(\"\"\"\n # Host 1 will run Raage, Host, Shard and Requesting agents\n load('feat.test.integration.resource')\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n host_desc = descriptor_factory('host_agent')\n req_desc = descriptor_factory('requesting_agent')\n agency.start_agent(host_desc, hostdef=hostdef1)\n host = _.get_agent()\n\n wait_for_idle()\n host.start_agent(req_desc)\n\n # Host 2 run only host agent\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(descriptor_factory('host_agent'), hostdef=hostdef1)\n wait_for_idle()\n\n # Host 3 will run Shard, Host and Raage\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(descriptor_factory('host_agent'), hostdef=hostdef2)\n wait_for_idle()\n\n # Host 4 will run only host agent\n agency = spawn_agency()\n agency.disable_protocol('setup-monitoring', 'Task')\n agency.start_agent(descriptor_factory('host_agent'), hostdef=hostdef2)\n \"\"\")\n\n # host definition in first shard (no space to allocate)\n hostdef1 = host.HostDef(resources=dict(host=0, epu=10, local=1))\n self.set_local(\"hostdef1\", hostdef1)\n\n # host definition in second shard (no space to allocate)\n hostdef2 = host.HostDef(resources=dict(host=1, epu=10))\n self.set_local(\"hostdef2\", hostdef2)\n\n yield self.process(setup)\n yield self.wait_for_idle(20)\n\n raage_mediums = self.driver.iter_agents('raage_agent')\n self.raage_agents = [x.get_agent() for x in raage_mediums]\n host_mediums = self.driver.iter_agents('host_agent')\n self.host_agents = [x.get_agent() for x in host_mediums]\n self.req_agent = first(\n self.driver.iter_agents('requesting_agent')).get_agent()\n\n def testValidateProlog(self):\n self.assertEqual(4, self.count_agents('host_agent'))\n self.assertEqual(2, self.count_agents('shard_agent'))\n self.assertEqual(2, self.count_agents('raage_agent'))\n\n @common.attr(timescale=0.2)\n @defer.inlineCallbacks\n def testRequestLocalResource(self):\n self.info(\"Starting test\")\n resources = dict(host=1)\n d = self.req_agent.request_local_resource(resources, {})\n self.assertFailure(d, raage.AllocationFailedError)\n yield d\n self.assert_allocated('host', 0)\n\n allocation_id, irecipient1 = \\\n yield self.req_agent.request_resource({'local': 1}, {})\n self.assert_allocated('local', 1)\n\n @common.attr(timescale=0.1)\n @defer.inlineCallbacks\n def testRequestFromOtherShard(self):\n self.info(\"Starting test\")\n resources = dict(host=1)\n allocation_id, irecipient1 = \\\n yield self.req_agent.request_resource(resources, {})\n self.assert_allocated('host', 1)\n\n allocation_id, irecipient2 = \\\n yield self.req_agent.request_resource(resources, {})\n self.assert_allocated('host', 2)\n\n shard2_hosts = map(recipient.IRecipient, self.host_agents[2:4])\n self.assertTrue(irecipient1 in shard2_hosts)\n self.assertTrue(irecipient2 in shard2_hosts)\n\n def assert_allocated(self, resource, expected):\n count = 0\n for agent in self.host_agents:\n _, allocated = agent.list_resource()\n count += allocated.get(resource, 0)\n self.assertEquals(expected, count,\n \"Expected %d allocated %s, found %d\" %\\\n (expected, resource, count, ))\n","sub_path":"src/feat/test/integration/test_simulation_raage.py","file_name":"test_simulation_raage.py","file_ext":"py","file_size_in_byte":12730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"33671258","text":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\nfrom matplotlib import pyplot as plt\nimport seaborn as sea\nimport squarify \nimport lightgbm as lgb\nimport gc\n\n\naisles = pd.read_csv('aisles.csv')\ndepartments = pd.read_csv('departments.csv')\npriors = pd.read_csv('order_products__prior.csv')\ntrain = pd.read_csv('order_products__train.csv')\norders = pd.read_csv('orders.csv')\nproducts = pd.read_csv('products.csv')\n\nprint(\"aisles\", aisles.shape, aisles.columns)\nprint(\"departments:\", departments.shape, departments.columns)\nprint(\"priors:\", priors.shape, priors.columns)\nprint(\"train:\", train.shape, train.columns)\nprint(\"orders:\", orders.shape, orders.columns)\nprint(\"products:\", products.shape, products.columns)\n\nbest50 = priors['product_id'].value_counts()[0:50].to_frame().reset_index()\n# print(best50)\n# print((products[products['product_id']==472565]['product_name'].iloc[0]))\nname = []\nfor id in best50['index']:\n name.append(products[products['product_id']==id]['product_name'].iloc[0])\n# print(name)\n# sea.barplot(best50['product_id'][0:7],name[0:7])\nsells = pd.DataFrame({\n 'Name': np.array(name)[0:8],\n \"Volume\": best50['product_id'][0:8]\n})\nplt.figure(figsize=(16,8))\npic = sea.barplot(x='Name', y='Volume', data=sells)\npic.set_xticklabels(pic.get_xticklabels(), rotation=90)\n\n\"\"\"# 賣最好的產品,列出販賣次數前幾高的產品\"\"\"\n\n\n\"\"\"# 統計training data中商品連續被再次購買的次數(連續兩次購買相同物品,reordered即會被設為1)\"\"\"\n\nplt.figure(figsize=(10,5))\nreordered = pd.DataFrame({\n 'Reorder':['1','0'],\n 'Times':train['reordered'].value_counts()\n})\nprint(reordered)\nsea.barplot(x='Reorder',y='Times',data=reordered)\n\n\"\"\"# 商品被再次購買的比率(每次購買中)\n\n# 統計Order_dow(一週中的哪一天購買)的數量,因資料沒有特別註明數字分別代表禮拜幾,只能找出第幾天最常購買\n\"\"\"\n\nOrder_dow = orders['order_dow'].value_counts().to_frame().reset_index()\nplt.figure(figsize=(10,5))\nsea.barplot(x='index',y='order_dow',data=Order_dow)\n\n\"\"\"# 統計兩次購買間間隔幾天\n可以看出一週內再次購買的機率相當高,而最後一天30天飆高可能是超過30天購買第二次都歸類在30天\n\"\"\"\n\ntwodays = orders['days_since_prior_order'].value_counts().to_frame().reset_index()\n# print(twodays)\nplt.figure(figsize=(15,5))\nsea.barplot(x='index',y='days_since_prior_order',data=twodays)\n\n\"\"\"# 統計每次購買的時間點(幾點鐘)\n可以看出白天(約7~19)購買的機率最高\n\"\"\"\n\nhours = orders['order_hour_of_day'].value_counts().to_frame().reset_index()\nplt.figure(figsize=(15,5))\nsea.barplot(x='index',y='order_hour_of_day',data=hours)\n\n\"\"\"# 因為資料量過大,記憶體有限,將資料型態由int64轉成int8和int32(根據數據大小)。\n## Ex:orders中order_dow為0~6,故轉成int8\n## 而orders中order_id最大為3421083,故轉成int32\n\n### 印出每筆column最大範圍,決定更改型態\n\"\"\"\n\nprint('priors:order_id', max(priors.order_id))\nprint('priors:product_id', max(priors.product_id))\nprint('priors:add_to_cart_order', max(priors.add_to_cart_order))\nprint('priors:reordered', max(priors.reordered))\nprint('orders:user_id', max(orders.user_id))\nprint('orders:order_number', max(orders.order_number))\nprint('orders:order_hour_of_day', max(orders.order_hour_of_day))\nprint('orders:days_since_prior_order', max(orders.days_since_prior_order[1:]))\nprint('products:aisle_id', max(products.aisle_id))\nprint('products:department_id', max(products.department_id))\n\norders.order_dow = orders.order_dow.astype(np.int8)\norders.order_hour_of_day = orders.order_hour_of_day.astype(np.int8)\norders.order_number = orders.order_number.astype(np.int16)\norders.order_id = orders.order_id.astype(np.int32)\norders.user_id = orders.user_id.astype(np.int32)\norders.days_since_prior_order = orders.days_since_prior_order.astype(np.float32)\n\nproducts.drop(['product_name'], axis=1, inplace=True)\nproducts.aisle_id = products.aisle_id.astype(np.int8)\nproducts.department_id = products.department_id.astype(np.int8)\nproducts.product_id = products.product_id.astype(np.int32)\n\ntrain.order_id = train.order_id.astype(np.int32)\ntrain.reordered = train.reordered.astype(np.int8)\ntrain.add_to_cart_order = train.add_to_cart_order.astype(np.int16)\n\npriors.order_id = priors.order_id.astype(np.int32)\npriors.add_to_cart_order = priors.add_to_cart_order.astype(np.int16)\npriors.reordered = priors.reordered.astype(np.int8)\npriors.product_id = priors.product_id.astype(np.int32)\n\n\"\"\"# 計算先前某項產品重複購買的頻率(rate = reorders/orders)\"\"\"\n\nprods = pd.DataFrame()\nprods['orders'] = priors.groupby(priors.product_id).size().astype(np.float32)\nprods['reorders'] = priors['reordered'].groupby(priors.product_id).sum().astype(np.float32)\nprods['reorder_rate'] = (prods.reorders / prods.orders).astype(np.float32)\nproducts = products.join(prods, on='product_id') #依照product_id來排序 並把prods加進products\nproducts.set_index('product_id', drop=False, inplace=True)\ndel prods\n\nprint('add order info to priors')\norders.set_index('order_id', inplace=True, drop=False)\npriors = priors.join(orders, on='order_id', rsuffix='_new')\npriors.drop('order_id_new', inplace=True, axis=1)\n\n\"\"\"# 創建一個新的DataFrame:user紀錄每個用戶以下資訊\n1. Total_item:總共買了幾樣產品\n2. all_products_id:全部買的產品的product_id\n3. total_different_item:總共買過哪些不同的產品\n4. average_days:平均幾天買一次\n5. average_times:平均在一天的何時購買\n6. number_orders:購買的次數\n7. average_buy:平均一次購買幾樣產品\n\"\"\"\n\nusr = pd.DataFrame()\nusr['average_days'] = orders.groupby('user_id')['days_since_prior_order'].mean().astype(np.float32)\nusr['average_times'] = orders.groupby('user_id')['order_hour_of_day'].mean().astype(np.float32)\nusr['most_dow'] = orders.groupby('user_id')['order_dow'].agg(lambda x:x.value_counts().index[0]).astype(np.int8) # 利用value_counts()找出出現最多次的dow\nusr['number_orders'] = orders.groupby('user_id').size().astype(np.int16)\n\nusers = pd.DataFrame()\nusers['total_items'] = priors.groupby('user_id').size().astype(np.int16) # 計算總共買了多少數量的物品\nusers['all_products_id'] = priors.groupby('user_id')['product_id'].apply(set) # 計算買了哪些物品\nusers['total_different_item'] = (users.all_products_id.map(len)).astype(np.int16) #計算不同物品的數量\n\nusers = users.join(usr)\ndel usr\nusers['average_buy'] = (users.total_items / users.number_orders).astype(np.float32)\ngc.collect()\nprint('user f', users.shape)\n\n\npriors['user_product'] = priors.product_id + priors.user_id * 100000\n\nd= dict()\nfor row in priors.itertuples():\n z = row.user_product\n if z not in d:\n d[z] = (1, (row.order_number, row.order_id), row.add_to_cart_order)\n else:\n d[z] = (d[z][0] + 1, max(d[z][1], (row.order_number, row.order_id)), d[z][2] + row.add_to_cart_order)\nd = pd.DataFrame.from_dict(d, orient='index')\nd.columns = ['number_orders', 'last_order_id', 'sum_pos_in_cart']\nd.number_orders = d.number_orders.astype(np.int16)\nd.last_order_id = d.last_order_id.map(lambda x: x[1]).astype(np.int32)\nd.sum_pos_in_cart = d.sum_pos_in_cart.astype(np.int16)\n\nuser_product = d\nprint('user X product f', len(user_product))\n\ndel priors\n\n\n\"\"\"# 切割train/test data,透過orders的eval_set column來區分\"\"\"\n\ntest_orders = orders[orders.eval_set == 'test']\ntrain_orders = orders[orders.eval_set == 'train']\n\ntrain.set_index(['order_id', 'product_id'], inplace=True, drop=False)\n\n\n\"\"\"# 模型\"\"\"\n\ndef features(selected_orders, labels_given=False):\n print('build candidate list')\n order_list = []\n product_list = []\n labels = []\n i=0\n for row in selected_orders.itertuples():\n i+=1\n if i%10000 == 0: print('order row',i)\n order_id = row.order_id\n user_id = row.user_id\n user_products = users.all_products_id[user_id]\n product_list += user_products\n order_list += [order_id] * len(user_products)\n if labels_given:\n labels += [(order_id, product) in train.index for product in user_products]\n \n df = pd.DataFrame({'order_id':order_list, 'product_id':product_list})\n df.order_id = df.order_id.astype(np.int32)\n df.product_id = df.product_id.astype(np.int32)\n labels = np.array(labels, dtype=np.int8)\n del order_list\n del product_list\n \n df['user_id'] = df.order_id.map(orders.user_id).astype(np.int32)\n df['user_total_orders'] = df.user_id.map(users.number_orders)\n df['user_total_items'] = df.user_id.map(users.total_items)\n df['total_distinct_items'] = df.user_id.map(users.total_different_item)\n df['user_average_days_between_orders'] = df.user_id.map(users.average_days)\n df['user_average_basket'] = df.user_id.map(users.average_buy)\n df['user_average_times'] = df.user_id.map(users.average_times) #\n df['user_most_dow'] = df.user_id.map(users.most_dow)\n \n df['order_hour_of_day'] = df.order_id.map(orders.order_hour_of_day)\n df['days_since_prior_order'] = df.order_id.map(orders.days_since_prior_order)\n df['days_since_ratio'] = df.days_since_prior_order / df.user_average_days_between_orders\n \n df['aisle_id'] = df.product_id.map(products.aisle_id).astype(np.int8)\n df['department_id'] = df.product_id.map(products.department_id).astype(np.int8)\n df['product_orders'] = df.product_id.map(products.orders).astype(np.float32)\n df['product_reorders'] = df.product_id.map(products.reorders).astype(np.float32)\n df['product_reorder_rate'] = df.product_id.map(products.reorder_rate)\n\n df['z'] = df.user_id * 100000 + df.product_id\n df.drop(['user_id'], axis=1, inplace=True)\n df['UP_orders'] = df.z.map(user_product.number_orders)\n df['UP_orders_ratio'] = (df.UP_orders / df.user_total_orders).astype(np.float32)\n df['UP_last_order_id'] = df.z.map(user_product.last_order_id)\n df['UP_average_pos_in_cart'] = (df.z.map(user_product.sum_pos_in_cart) / df.UP_orders).astype(np.float32)\n df['UP_reorder_rate'] = (df.UP_orders / df.user_total_orders).astype(np.float32)\n df['UP_orders_since_last'] = df.user_total_orders - df.UP_last_order_id.map(orders.order_number)\n df['UP_delta_hour_vs_last'] = abs(df.order_hour_of_day - \\\n df.UP_last_order_id.map(orders.order_hour_of_day)).map(lambda x: min(x, 24-x)).astype(np.int8)\n\n df.drop(['UP_last_order_id', 'z'], axis=1, inplace=True)\n\n gc.collect()\n return (df, labels)\n\ndf_train, labels = features(train_orders, labels_given=True)\n\nf_to_use = ['user_total_orders', 'user_total_items', 'total_distinct_items',\n 'user_average_days_between_orders', 'user_average_basket', 'user_average_times', 'user_most_dow',\n 'order_hour_of_day', 'days_since_prior_order', 'days_since_ratio',\n 'aisle_id', 'department_id', 'product_orders', 'product_reorders',\n 'product_reorder_rate', 'UP_orders', 'UP_orders_ratio',\n 'UP_average_pos_in_cart', 'UP_reorder_rate', 'UP_orders_since_last',\n 'UP_delta_hour_vs_last']\n\n\nprint('formating for lgb')\nd_train = lgb.Dataset(df_train[f_to_use],\n label=labels,\n categorical_feature=['aisle_id', 'department_id'])\ndel df_train\ngc.collect()\n\nparams = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metric': {'binary_logloss'},\n 'num_leaves': 96,\n 'feature_fraction': 0.9,\n 'bagging_fraction': 0.95,\n 'bagging_freq': 5\n}\nROUNDS = 98\n\nbst = lgb.train(params, d_train, ROUNDS)\nlgb.plot_importance(bst, figsize=(9,20))\ndel d_train\ngc.collect()\n\ndf_test, _ = features(test_orders)\npreds = bst.predict(df_test[f_to_use])\n\ndf_test['pred'] = preds\n\nTRESHOLD = 0.22 \n\nd = dict()\nfor row in df_test.itertuples():\n if row.pred > TRESHOLD:\n try:\n d[row.order_id] += ' ' + str(row.product_id)\n except:\n d[row.order_id] = str(row.product_id)\n\nfor order in test_orders.order_id:\n if order not in d:\n d[order] = 'None'\n\nsub = pd.DataFrame.from_dict(d, orient='index')\n\nsub.reset_index(inplace=True)\nsub.columns = ['order_id', 'products']\nsub.to_csv('submission.csv', index=False)","sub_path":"dsai_hw4.py","file_name":"dsai_hw4.py","file_ext":"py","file_size_in_byte":12715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"54246539","text":"\n# [link](https://linuxacademy.com/cp/exercises/view/id/712/module/168)\n\n\n# 5. Exercise: Interacting with External Commands\n# It’s not uncommon for a process to run on a server and listen to a port. Unfortunately, you sometimes don’t want that process to keep running, but all you know is the port that you want to free up.\n# write a script to make it easy to get rid of those pesky processes.\n# Write a script that does the following:\n# - Takes a port_number as its only argument.\n# - Calls out to lsof to determine if there is a process listening on that port.\n# - If there is a process, kill the process and inform the user.\n# - If there is no process, print that there was no process running on that port.\n\n# Python’s standard library comes with an HTTP server to start a server listening on a port 5500:\n# python -m http.server 5500\n\n# install lsof\n# sudo yum install -y lsof\n# lsof -n -i4TCP:PORT_NUMBER\n\n\nimport subprocess\nimport os\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser(description='kill the running process listening on a given port')\nparser.add_argument(\"-port\", \"-p\", help=\"prot number\")\n# args = parser.parse_args\nport = parser.parse_args().port\n\ntry:\n result = subprocess.run(\n ['lsof', '-n', \"-i4TCP:%s\" % port],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nexcept subprocess.CalledProcessError:\n print(f\"No process listening on port {port}\")\n exit(1)\nelse:\n listening = None\n for line in result.stdout.splitlines():\n if \"LISTEN\" in str(line):\n listening = line\n break\n\n if listening:\n # PID is the second column in the output\n pid = int(listening.split()[1])\n os.kill(pid, 9)\n print(f\"Killed process {pid}\")\n else:\n print(f\"No process listening on port {port}\")\n exit(1)\n\n\n","sub_path":"0.project/autoscript/5.kill_process_by_portnum.py","file_name":"5.kill_process_by_portnum.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"122770734","text":"import requests\nimport bs4\nimport datetime\nimport csv\n\n# TO DO:\n# Create the option to update all files at once\n\n\n# Final da URL de dados a serem buscados\n# # URL_END = '/HTML/10_ProducaoEolicaUsina.html' # (Endereço usado a partir de 16 de Maio de 2017)\n# # URL_END = '/HTML/09_ProducaoTermicaUsina.html' # (Endereço usado a partir de 16 de Maio de 2017)\n# # URL_END = '/HTML/08_ProducaoHidraulicaUsina.html' # (Endereço usado a partir de 16 de Maio de 2017)\n\n# # URL_END = '/HTML/09_ProducaoEolicaUsina.html' # (Endereço usado até 15 de Maio de 2017)\n# # URL_END = '/HTML/08_ProducaoTermicaUsina.html' # (Endereço usado até 15 de Maio de 2017)\n# # URL_END = '/HTML/07_ProducaoHidraulicaUsina.html' # (Endereço usado até 15 de Maio de 2017)\n\nmenu = {\n 'UHE': [r'.\\hist_hidraulicas.csv', r'/HTML/08_ProducaoHidraulicaUsina.html'],\n 'UTE': [r'.\\hist_termicas.csv', r'/HTML/09_ProducaoTermicaUsina.html'],\n 'EOL': [r'.\\hist_eolicas.csv', r'/HTML/10_ProducaoEolicaUsina.html']\n}\n\nwhile True:\n FILE_MENU = input('Escolha os dados a serem atualizados (UHE ou UTE ou EOL): ').upper()\n if FILE_MENU in menu.keys():\n # print('Você escolheu {}'.format(FILE_MENU))\n # print('Isso causa a arbertura do arquivo {} e do complemento {}'.format(menu[FILE_MENU][0], menu[FILE_MENU][1]))\n break\n else:\n continue\n\narquivo = menu[FILE_MENU][0]\nURL_END = menu[FILE_MENU][1]\nURL_BEGIN = 'http://www.ons.org.br/resultados_operacao/SDRO/Diario/'\n\n\ndef find_last_date_csv(path_to_file):\n # Abre o histórico de geração e procura a última data com dados de medição\n with open(path_to_file, newline='') as csvFile:\n csvReader = csv.reader(csvFile, delimiter=';')\n lastDate = list(csvReader)[-1][-0]\n lastDate = datetime.datetime.strptime(lastDate, \"%d/%m/%Y\")\n csvFile.close()\n return lastDate.date()\n\n\ndef find_last_date_ons_site():\n # Procura no site do ONS as medições mais recentes\n reqDate = requests.get('http://www.ons.org.br/resultados_operacao/SDRO/Diario/topo.htm')\n reqDate.encoding = 'utf8'\n soupDate = bs4.BeautifulSoup(reqDate.text, \"html.parser\")\n textDate = soupDate.find_all('option')\n textDate = textDate[1].get_text()\n textDate = datetime.datetime.strptime(textDate[-10:], '%d/%m/%Y')\n return textDate.date()\n\n\ndef generate_dates_url(d1, numDays):\n # Gerando datas para a url\n dates = []\n for i in range(1, numDays + 1):\n dates.append((d1 + datetime.timedelta(days=i)).strftime(\"%Y_%m_%d\"))\n return dates\n\n\ndef get_measurements(urlFull):\n res = requests.get(urlFull)\n n = datetime.datetime.strptime(date, \"%Y_%m_%d\").date().strftime(\"%d/%m/%Y\")\n if res.ok:\n res.encoding = 'utf8'\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n text = soup.find_all('tbody')\n # A função anterior retorna um arry com todas as tabelas do frame\n # queremos a que contem os dados das usinas, supõe-se que seja a\n # maior.\n text = max(text, key=len)\n text = text.find_all('tr')\n medicoes_dia = []\n for value in range(1, len(text) - 1):\n linha = text[value].get_text().strip().replace(' \\n\\n', ';').replace('\\n', ';')\n linha = linha.split(';')\n linha.insert(0, n)\n medicoes_dia.append(linha)\n else:\n print('/t ERRO: {1}, {2}: Dados de {0} com problemas.'.format(n, res.status_code, res.reason))\n\n return medicoes_dia\n\n\n# Entrada de datas específicas para testes\n# d1 = datetime.date(2017, 5, 16)\n# d2 = datetime.date(2017, 5, 31)\nd1 = find_last_date_csv(arquivo)\nd2 = find_last_date_ons_site()\n\nprint('\\n\\nA última data de medições no arquivo local é: {}'.format(d1))\nprint('A última data de medições no site do ONS é: {}\\n\\n'.format(d2))\n\nnumDays = (d2 - d1).days\ndates = generate_dates_url(d1, numDays)\n\nif (input('Importar útimas medições? (S/N) :').upper() == ('S')) and (numDays > 0):\n print('\\n\\n')\n with open(arquivo, 'a', newline='') as csvFile:\n csvWriter = csv.writer(csvFile, delimiter=';')\n\n for date in dates:\n urlFull = URL_BEGIN + date + URL_END\n csvWriter.writerows(get_measurements(urlFull))\n print('Dados de {} importados com sucesso'.format(date))\n\n csvFile.close()\n\nelse:\n print('Nenhum dado importado')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"285282209","text":"from time import sleep\nimport MySQLdb as mysql\n\n\ncredentials = {\n 'host': 'localhost',\n 'port': 3306,\n 'user': 'web',\n 'password': 'r3p3atp1z',\n 'connect_timeout': 1\n}\n\n\ndef main():\n print('*' * 80)\n\n try:\n # создаем соединение с сервером MySQL\n connection = mysql.connect(**credentials)\n except mysql.Error as e:\n # объект исключения хранит информацию в свойстве args, представленное\n # кортежем\n print(str.format('[#] error: {}', e))\n print(str.format('[#] error code: {}', e.args[0]))\n print(str.format('[#] error string: {}', e.args[1]))\n exit(1)\n\n ping_result = connection.ping()\n print(str.format('[*] ping result # 1: {}', ping_result))\n\n print(str.format(\n '[*] connected with MySQL server <{}:{}>',\n credentials['host'], credentials['port']\n ))\n\n print('-' * 80)\n # получаем курсор, который позволяет выполнять SQL инструкции\n cursor = connection.cursor()\n\n try:\n # выполняет SQL запрос на сервер\n cursor.execute('select version()')\n except mysql.Error as e:\n print(str.format('[#] {}: {}', e.args[0], e.args[1]))\n exit(2)\n\n print('-' * 80)\n # извлекаем результат выполнения SQL инструкции; результатом может\n # быть либо кортеж, либо None\n row = cursor.fetchone()\n\n if row is not None:\n print(str.format('[*] MySQL version: {}', row[0]))\n\n for i in range(10):\n print('-' * 80)\n sleep(0.3)\n\n try:\n connection.ping()\n print(str.format('[*] ping result # {}', i + 1))\n except mysql.Error as e:\n print(str.format(\n '[#] error # {}: <{}:{}>', i + 1, e.args[0], e.args[1]\n ))\n\n print('-' * 80)\n print('[!] close cursor')\n\n # закрываем курсор\n cursor.close()\n\n # закрываем соединение с MySQL сервером\n connection.close()\n\n print('-' * 80)\n print('[!] close connection')\n\n print('*' * 80)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"packages/database_packages/sql/mysql_packages/mysqlclient_package/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"65908896","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'byb'\n\n\"\"\"\n@version: python2.7\n@author: ‘byb‘\n@license: Apache Licence \n@contact: baiyibing@gmail.com\n@site: \n@software: PyCharm\n@file: api2.py\n@time: 2016/9/8 22:04\n\"\"\"\n\nfrom flask import Flask\nfrom flask_restful import reqparse, abort, Api, Resource\n\n# app = Flask(__name__)\n# api = Api(app)\n\nTODOS = {\n 'todo1': {'task': 'build an API'},\n 'todo2': {'task': '?????'},\n 'todo3': {'task': 'profit!'},\n}\n\n\ndef abort_if_todo_doesnt_exist(todo_id):\n if todo_id not in TODOS:\n abort(404, message=\"Todo {} doesn't exist\".format(todo_id))\n\n\nparser = reqparse.RequestParser()\n# 基本参数\nparser.add_argument('task')\n\n\n# 参数类型 type\n# 信息 help,在解析类型错误的时候,就会作为错误信息呈现出来;否则默认返回类型错误本身的错误。\n# parser.add_argument('task', type=str, help='Rate cannot be converted')\n# parser.add_argument('rate', type=int)\n\n# 必须的参数 required\n# curl 127.0.0.1:5000/todos -d task=hello -d rate=3 -X POST\n# parser.add_argument('rate', type=int, required=True)\n\n# 多个值&列表 append\n# curl 127.0.0.1:5000/todos -d task=hello -d task=hello2 -d task=hello4 -X POST\n# parser.add_argument('task', type=str, action='append')\n\n# 参数位置\n\n# # Look only in the POST body\n# parser.add_argument('name', type=int, location='form')\n#\n# # Look only in the querystring\n# parser.add_argument('PageSize', type=int, location='args')\n#\n# # From the request headers\n# parser.add_argument('User-Agent', type=str, location='headers')\n#\n# # From http cookies\n# parser.add_argument('session_id', type=str, location='cookies')\n#\n# # From file uploads\n# parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')\n\n# # 多个位置\n# parser.add_argument('text', location=['headers', 'values'])\n\n# Todo\n# shows a single todo item and lets you delete a todo item\nclass Todo(Resource):\n def get(self, todo_id):\n abort_if_todo_doesnt_exist(todo_id)\n return TODOS[todo_id]\n\n def delete(self, todo_id):\n abort_if_todo_doesnt_exist(todo_id)\n del TODOS[todo_id]\n return '', 204\n\n def put(self, todo_id):\n args = parser.parse_args()\n print(args)\n task = {'task': args['task']}\n TODOS[todo_id] = task\n return task, 201\n\n\n# TodoList\n# shows a list of all todos, and lets you POST to add new tasks\nclass TodoList(Resource):\n def get(self):\n return TODOS\n\n def post(self):\n args = parser.parse_args()\n todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1\n todo_id = 'todo%i' % todo_id\n TODOS[todo_id] = {'task': args['task']}\n return TODOS[todo_id], 201\n\n ##\n ## Actually setup the Api resource routing here\n ##\n # api.add_resource(TodoList, '/todos')\n # api.add_resource(Todo, '/todos/')\n #\n #\n # if __name__ == '__main__':\n # app.run(debug=True)\n","sub_path":"app/resources/api2.py","file_name":"api2.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"371117033","text":"\"\"\"This produces a GUI that allows users to switch between segmentation\n algorithms and alter the parameters manually using a slider. It shows two images,\n one with the original image with the resulting mask and one with the original image\n with the negative of the resulting mask.\"\"\"\nimport matplotlib.pylab as plt\nimport ipywidgets as widgets\nfrom IPython.display import display, clear_output\nfrom pathlib import Path\nfrom see import Segmentors\nimport imageio\n\n\ndef showtwo(img, img2):\n \"\"\"Show two images side by side.\"\"\"\n fig = plt.figure(figsize=(20, 20))\n my_ax = fig.add_subplot(1, 2, 1)\n my_ax.imshow(img)\n my_ax = fig.add_subplot(1, 2, 2)\n my_ax.imshow(img2)\n return fig\n\ndef showthree(img, img1, img2):\n \"\"\"Show three images side by side.\"\"\"\n fig = plt.figure(figsize=(20, 20))\n my_ax = fig.add_subplot(1, 3, 1)\n my_ax.imshow(img)\n my_ax = fig.add_subplot(1, 3, 2)\n my_ax.imshow(img1)\n my_ax = fig.add_subplot(1, 3, 3)\n my_ax.imshow(img2)\n return fig\n\ndef show_segment(img, mask):\n \"\"\"Show both options for segmenting using the current mask.\n\n Keyword arguments:\n img -- original image\n mask -- resulting mask from segmentor\n\n \"\"\"\n im1 = img.copy()\n im2 = img.copy()\n im1[mask > 0, :] = 0\n im2[mask == 0, :] = 0\n fig = showtwo(im1, im2)\n return fig\n\n\ndef pickimage(folder='Image_data/Examples/'):\n #def pickimage(\n\n directory = Path(folder)\n\n allfiles = sorted(directory.glob('*'))\n\n filelist = []\n masklist = []\n for file in allfiles:\n if file.suffix ==\".jpg\" or file.suffix ==\".jpeg\" or file.suffix ==\".JPEG\" or file.suffix ==\".png\":\n if not \"_GT\" in file.name:\n filelist.append(file)\n mask = directory.glob(f\"{file.stem}_GT*\")\n for m in mask:\n masklist.append(m)\n \n w = widgets.Dropdown(\n options=filelist,\n value=filelist[0],\n description='Choose image:',\n )\n\n def update(w):\n clear_output(wait=True) # Clear output for dynamic display\n display(w)\n w.img = imageio.imread(w.value)\n index = filelist.index(w.value)\n w.mask = imageio.imread(masklist[index])\n if len(w.mask.shape) > 2:\n w.mask = w.mask[:,:,0]\n fig = showtwo(w.img, w.mask)\n print(f\"import imageio\")\n print(f\"data.img = imageio.imread(\\'{w.value}\\')\")\n print(f\"data.mask = imageio.imread(\\'{masklist[index]}\\')\")\n \n def on_change(change):\n if change['type'] == 'change' and change['name'] == 'value':\n\n update(w)\n\n w.observe(on_change)\n update(w)\n return w\n\n\ndef picksegment(algorithms):\n w = widgets.Dropdown(\n options=algorithms,\n value=algorithms[0],\n description='Choose Algorithm:',\n )\n\n def on_change(change):\n if change['type'] == 'change' and change['name'] == 'value':\n clear_output(wait=True) # Clear output for dynamic display\n display(w)\n print(Segmentors.algorithmspace[change['new']].__doc__)\n print(f\"\\nsegmentor_name=\\'{w.value}\\'\")\n w.observe(on_change)\n\n display(w)\n print(Segmentors.algorithmspace[w.value].__doc__)\n print(f\"\\nalg.value=\\'{w.value}\\'\")\n return w\n\ndef segmentwidget(img, gmask, params=None, alg=None):\n \"\"\"Generate GUI. Produce slider for each parameter for the current segmentor.\n Show both options for the masked image.\n\n Keyword arguments:\n img -- original image\n gmask -- ground truth segmentation mask for the image\n params -- list of parameter options\n alg -- algorithm to search parameters over\n\n \"\"\"\n if params:\n if alg:\n params[0] = alg;\n seg = Segmentors.algoFromParams(params)\n else:\n if alg:\n algorithm_gen = Segmentors.algorithmspace[alg]\n seg = algorithm_gen()\n else:\n seg = Segmentors.segmentor()\n\n widg = dict()\n widglist = []\n\n for ppp, ind in zip(seg.paramindexes, range(len(seg.paramindexes))):\n thislist = eval(seg.params.ranges[ppp])\n name = ppp\n current_value = seg.params[ppp]\n if not current_value in thislist:\n #TODO: We should find the min distance between current_value and this list and use that instead.\n current_value = thislist[0]\n \n thiswidg = widgets.SelectionSlider(options=tuple(thislist),\n disabled=False,\n description=name,\n value=current_value,\n continuous_update=False,\n orientation='horizontal',\n readout=True\n )\n\n widglist.append(thiswidg)\n widg[ppp] = thiswidg\n\n# algorithms = list(Segmentors.algorithmspace.keys())\n# w = widgets.Dropdown(\n# options=algorithms,\n# value=algorithms[0],\n# description='Choose Algorithm:',\n# )\n \n\n \n def func(img=img, mask=gmask, **kwargs):\n \"\"\"Find mask and fitness for current algorithm. Show masked image.\"\"\"\n print(seg.params[\"algorithm\"])\n for k in kwargs:\n seg.params[k] = kwargs[k]\n mask = seg.evaluate(img)\n fit = Segmentors.FitnessFunction(mask, gmask)\n fig = showtwo(img, mask)\n # I like the idea of printing the sharepython but it should be below the figures. \n #print(seg.sharepython(img))\n# plt.title('Fitness Value: ' + str(fit[0]))\n\n \n layout = widgets.Layout(grid_template_columns='1fr 1fr 1fr')\n u_i = widgets.GridBox(widglist, layout=layout)\n out = widgets.interactive_output(func, widg)\n display(u_i, out)\n \n return seg.params\n","sub_path":"see/JupyterGUI.py","file_name":"JupyterGUI.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"53114630","text":"##############################################################################\n#\n# Copyright (c) 2007-2009 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\nimport zc.buildout.testing\nimport zc.buildout.tests\nfrom zope.testing import doctest\n\ndef setUp(test):\n zc.buildout.tests.easy_install_SetUp(test)\n zc.buildout.testing.install_develop('z3c.recipe.filetemplate', test)\n\ndef test_suite():\n return doctest.DocFileSuite(\n 'README.txt', 'tests.txt',\n setUp=setUp,\n tearDown=zc.buildout.testing.buildoutTearDown,\n optionflags=doctest.NORMALIZE_WHITESPACE,\n )\n","sub_path":"z3c.recipe.filetemplate/z3c/recipe/filetemplate/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"649807223","text":"def quick_sort(arr, left, right):\n\n\tif left < right:\n\n\t\t# Pivot\n\t\tpivot = right\n\n\t\t# Partition_idx for pivot\n\t\tpartition_index = partition(arr, pivot, left, right)\n\n\t\t# After initial partition, do the same for both left and right of arr\n\t\tquick_sort(arr, left, partition_index-1)\n\t\tquick_sort(arr, partition_index+1, right)\n\n\treturn arr\n\n\n\ndef partition(arr, pivot, left, right):\n\n\t# Pivot value: The value to compare with others\n\tpivot_value = arr[pivot]\n\t# Position where to insert value < pivot\n\tpartition_index = left\n\n\ti = left\n\twhile i < right:\n\t\tif arr[i] < pivot_value:\n\t\t\t# Make value in the right position\n\t\t\tarr = swap(arr, i, partition_index)\n\t\t\t# Increment position to insert value\n\t\t\tpartition_index += 1\n\t\ti += 1\n\n\t# Make pivot in the right position, after this, all pivot_left < pivot < pivot_right. \n\t# This is what we want.\n\tswap(arr, pivot, partition_index)\n\n\treturn partition_index\n\n\n\ndef swap(arr, a, b):\n\n\tif a != b:\n\t\tarr[a] += arr[b]\n\t\tarr[b] = arr[a] - arr[b]\n\t\tarr[a] -= arr[b]\n\treturn arr\n\n\n\nif __name__ == \"__main__\":\n\n\tarr = [9,8,7,6,5,4,3,2,1]\n\tarr1 = [99,111,222,31,56,1,0]\n\n\tprint(quick_sort(arr, 0, len(arr)-1))\n\tprint(quick_sort(arr1, 0, len(arr1)-1))","sub_path":"sorting/py-sorting/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"94935851","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\nname = 'imagefavs'\nversion = '0.0.1'\nauthor = 'Tetsuya Shioda'\nauthor_email = 'shioda.tetsuya@gmail.com'\ndescription = 'Favorite Image Downloader'\n\ninstall_requires = [\n 'requests_oauthlib',\n]\n\nsetup(\n name=name,\n version=version,\n description=description,\n author=author,\n author_email=author_email,\n packages=['imagefavs'],\n install_requires=install_requires,\n entry_points={\n 'console_scripts': [\n 'imfv=imagefavs.client:main'\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"27184761","text":"# coding=utf-8\nfrom celery import Celery\n\n# 创建celery应用对象\napp = Celery('tasks', # 模块名\n backend='redis://127.0.0.1:6379/1',\n broker='redis://127.0.0.1:6379/0')\n\n# 表示,下面的任务由app这个对象来进行管理\n@app.task\ndef my_task(a,b):\n print ('任务函数正在执行')\n return a+b\n\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"266987707","text":"#!/usr/bin/python3\n\nimport sys, getopt\nimport settings\nfrom pymongo import MongoClient\n\ndef main(argv):\n username = ''\n name = ''\n try:\n opts, args = getopt.getopt(argv,\"hu:n:\",[\"username=\",\"name=\"])\n except getopt.GetoptError:\n print ('add_admin.py -u -n ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('add_admin.py -u -n ')\n sys.exit()\n elif opt in (\"-u\", \"--username\"):\n username = arg\n elif opt in (\"-n\", \"--name\"):\n name = arg\n\n if len(username) == 0 or len(name) == 0:\n print ('add_admin.py -u -n ')\n sys.exit(2) \n\n try:\n client = MongoClient('mongodb://%s:%s@%s:%s' % (settings.MONGO_USERNAME, settings.MONGO_PASSWORD, settings.MONGO_HOST, settings.MONGO_PORT))\n except AttributeError:\n client = MongoClient('mongodb://%s:%s' % (settings.MONGO_HOST, settings.MONGO_PORT))\n db = client[settings.MONGO_DBNAME]\n\n whitelist = db.whitelist\n user = {\n \"username\": username,\n \"name\": name,\n \"active\": True\n }\n\n whitelist_id = whitelist.insert_one(user).inserted_id\n\n if whitelist_id:\n print('SUCCESS')\n else:\n print('ERROR')\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"add_admin.py","file_name":"add_admin.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"260448672","text":"import sys\n\ndef initialize():\n file_in = 'D:\\code jam\\input.in'\n file_out = 'D:\\code jam\\output.txt'\n \n try:\n data_in = open(file_in, 'r')\n except:\n print(\"Can't open file \\'\" + data_in +\"\\'\")\n sys.exit()\n \n try:\n data_out = open(file_out, 'w')\n except:\n print(\"Can't write to file \\'\" + data_out +\"\\'\")\n sys.exit()\n\n return(data_in, data_out)\n\ndef get_variables():\n\n line = data_in.readline().split(' ')\n\n H=int(line[0]) \n N=int(line[1])\n M=int(line[2])\n \n i=0\n C=[]\n while(icur_time and pos_time[i][j]0 and pos_time[x-1][y] > (cur_time + movement_speed) ):\n check_this(x,y,x-1,y,W,N,M,C,F,pos_time,cur_time,movement_speed) \n\n if(x+1 (cur_time + movement_speed) ):\n check_this(x,y,x+1,y,W,N,M,C,F,pos_time,cur_time,movement_speed) \n\n if(y>0 and pos_time[x][y-1] > (cur_time + movement_speed) ):\n check_this(x,y,x,y-1,W,N,M,C,F,pos_time,cur_time,movement_speed) \n\n if(y+1 (cur_time + movement_speed) ):\n check_this(x,y,x,y+1,W,N,M,C,F,pos_time,cur_time,movement_speed)\n \n return\n\ndef check_this(x1,y1,x2,y2,W,N,M,C,F,pos_time,cur_time,movement_speed):\n #Calculate how much time\n res=check_transition(x1,y1,x2,y2,0,C,F)\n if res:\n #check water and time\n if( W > C[x2][y2] - 50):\n #wait\n time_wait = -(C[x2][y2] - 50 - W)/10\n new_W=C[x2][y2] - 50\n\n if(new_W < F[x1][y1]+20):\n new_movement_speed=10\n else:\n new_movement_speed=1\n \n if( pos_time[x2][y2] > (cur_time + new_movement_speed + time_wait) ):\n pos_time[x2][y2]=cur_time + new_movement_speed + time_wait\n else:\n #move\n pos_time[x2][y2]=cur_time+movement_speed\n return;\n \n\ndef check_position(x,y,H,N,M,C,F,memory,pos_check_x,pos_check_y):\n if(x>0 and memory[x-1][y]==0):\n res=check_transition(x,y,x-1,y,H,C,F)\n if res:\n pos_check_x.append(x-1)\n pos_check_y.append(y)\n memory[x-1][y]=1\n \n if(x+10 and memory[x][y-1]==0):\n res=check_transition(x,y,x,y-1,H,C,F)\n if res:\n pos_check_x.append(x)\n pos_check_y.append(y-1)\n memory[x][y-1]=1\n \n if(y+1 C[x2][y2] - 50):\n return 0\n \n if(F[x1][y1] > C[x2][y2] - 50):\n return 0\n \n if(C[x2][y2] < F[x2][y2] + 50):\n return 0\n \n if(C[x1][y1] < F[x2][y2] + 50):\n return 0\n \n return 1;\n \n \n(data_in, data_out) = initialize()\nno_test_cases = int( data_in.readline() )\n\ni = 0\nwhile ( i < no_test_cases ):\n i+=1\n H,N,M,C,F = get_variables()\n if(i==99):\n j=i\n# help('str')\n result = calculate_result(H,N,M,C,F)\n print( 'Case #' + str(i) + ': ' + str(result) )\n data_out.write( 'Case #' + str(i) + ': ' + str(result) + '\\n' )\n \n\n\n","sub_path":"solutions_1485488_1/Python/nunocordeiro/2012_1B_2.py","file_name":"2012_1B_2.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"581886457","text":"import time\nimport unittest\n\nfrom cloud.aws import AsyncioBotocore\n\nfrom tests import BotocoreMixin\n\n\nclass DynamoMixin(BotocoreMixin):\n\n @classmethod\n async def setUpClass(cls):\n super().setUpClass()\n cls.client = AsyncioBotocore('dynamodb', **cls.kwargs)\n cls.table_name = 'pulsarcloud_%d' % int(time.time())\n await cls.create_table()\n\n @classmethod\n async def tearDownClass(cls):\n await cls.delete_table()\n await cls.sessions.close()\n\n @classmethod\n async def is_table_ready(cls, table_name):\n response = await cls.client.describe_table(\n TableName=table_name\n )\n return response['Table']['TableStatus'] == 'ACTIVE'\n\n @classmethod\n async def create_table(cls, table_name=None):\n table_name = table_name or cls.table_name\n table_kwargs = {\n 'TableName': table_name,\n 'AttributeDefinitions': [\n {\n 'AttributeName': 'testKey',\n 'AttributeType': 'S'\n }\n ],\n 'KeySchema': [\n {\n 'AttributeName': 'testKey',\n 'KeyType': 'HASH'\n }\n ],\n 'ProvisionedThroughput': {\n 'ReadCapacityUnits': 1,\n 'WriteCapacityUnits': 1\n }\n }\n response = await cls.client.create_table(**table_kwargs)\n while not await cls.is_table_ready(table_name):\n pass\n cls.assert_status(response)\n return table_name\n\n @classmethod\n async def delete_table(cls, table_name=None):\n await cls.client.delete_table(\n TableName=table_name or cls.table_name\n )\n\n @classmethod\n async def put_item(cls, key_string_value, **item):\n item['testKey'] = {\n 'S': key_string_value\n }\n response = await cls.client.put_item(\n TableName=cls.table_name,\n Item=item\n )\n cls.assert_status(response)\n\n\nclass DynamoTest(DynamoMixin, unittest.TestCase):\n\n async def test_get_item(self):\n test_key = 'testValue'\n await self.put_item(test_key, foo={'S': 't' * 2**13})\n response = await self.client.get_item(\n TableName=self.table_name,\n Key={\n 'testKey': {\n 'S': test_key\n }\n },\n )\n self.assert_status(response)\n self.assertEqual(response['Item']['testKey'], {'S': test_key})\n","sub_path":"tests/test_dynamodb.py","file_name":"test_dynamodb.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"128437583","text":"from sklearn.decomposition import PCA\n\n#\n# Housekeeping\n#\nimport os\nimport shutil\nimport sys\nimport time\n\n#\n# Math\n#\nimport numpy as np\nimport math\n\n#\n# Plotting\n#\nimport matplotlib as mpl\nimport matplotlib.pylab as plt\n\n#\n# Optimizer\n#\nimport DeepEM\n\nif len( sys.argv ) < 6:\n\tprint( \"Usage: python \" + sys.argv[ 0 ] + \" { save folder } { max index } { loss percentage } { random generator seed } { number of hours to run }\" )\n\tsys.exit( 1 )\n\nsave_folder = sys.argv[ 1 ]\nmax_index = float( sys.argv[ 2 ] )\nloss_percentage = float( sys.argv[ 3 ] )\nrandom_seed = int( sys.argv[ 4 ] )\nnumber_of_hours_to_run = float( sys.argv[ 5 ] )\nnumber_of_seconds_to_run = 60. * 60. * number_of_hours_to_run\n\nif ( max_index > 3.5 ):\n\tprint( \"This index is a bit too high for the simulation mesh\" )\n\n\nmesh_size_nm = 9\ndensity_coarsen_factor = 10\nmesh_size_m = mesh_size_nm * 1e-9\nlambda_um = 0.532\n# num_lambda_values = 1\nnum_layers = 2\n\ndevice_width_voxels = 120\ndevice_height_voxels = 120\ndevice_voxels_total = device_width_voxels * device_height_voxels\nfocal_length_voxels = 120\n\nmin_relative_permittivity = 1.0**2\n\nsingle_pass_transmittance = 1 - ( loss_percentage / 100. )\ndevice_height_m = device_height_voxels * mesh_size_nm * 1e-9\nlambda_m = lambda_um * 1e-6\nloss_index = -lambda_m * np.log( single_pass_transmittance ) / ( device_height_m * 2 * np.pi )\n\nreal_permittivity = max_index**2 - loss_index**2\nimag_permittivity = 2 * np.sqrt( real_permittivity ) * loss_index\nmax_relative_permittivity = real_permittivity + 1j * imag_permittivity\n\n\ndensities = []\nfocal_abs = []\nnum_before_saving = 500\n\n# num_to_load = 10 * num_before_saving\nnum_load_epochs = 10\n\nfor epoch_num in range( 0, num_load_epochs ):\n\tdensities += list( np.load( save_folder + \"/generated_densities_\" + str( epoch_num ) + \".npy\" ) )\n\tfocal_abs += list( np.abs( np.load( save_folder + \"/generated_focal_fields_\" + str( epoch_num ) + \".npy\" ) ) )\n\n\npca = PCA()\npca.fit_transform( focal_abs )\n\nn_components_variance_max = 120\nratio_variance = np.zeros( ratio_variance )\n\nfor n_idx in range( 0, n_components_variance_max ):\n\tratio_variance.append( pca.explained_variance_ratio_( n_idx ) )\n\nnp.save( save_folder + \"/ratio_variance.npy\" )\n\n\n# principalComponents = pca.fit_transform(x)\n# principalDf = pd.DataFrame(data = principalComponents\n# , columns = ['principal component 1', 'principal component 2'])\n","sub_path":"inverse_design/Landscape/pca_deep_em.py","file_name":"pca_deep_em.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"180778058","text":"import os\nimport tensorflow as tf\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncwd='C:\\\\Users\\\\Rivaille\\\\Desktop\\\\ROkinect\\\\dataset3\\\\feng\\\\feng_learn\\\\'\nclasses={'back','front', 'side'} #\nwriter= tf.python_io.TFRecordWriter(\"train.tfrecords\") #要生成的文件\n\nfor index,name in enumerate(classes):\n class_path=cwd+name+'\\\\'\n for img_name in os.listdir(class_path):\n img_path=class_path+img_name #每一个图片的地址\n\n img=Image.open(img_path)\n img= img.resize((64,128))\n\n img_raw=img.all_vectores[index]#将图片转化为二进制格式\n example = tf.train.Example(features=tf.train.Features(feature={\n \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),\n 'img_raw': tf.train.Feature(\n int64_list=tf.train.Int64List(value=[img].astype(\"int64\")))\n })) #example对象对label和image数据进行封装\n writer.write(example.SerializeToString()) #序列化为字符串\n\nwriter.close()","sub_path":"tf1/NN_tensorflow/makeTFrecord2.py","file_name":"makeTFrecord2.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"198185415","text":"from datetime import datetime\n\n\nclass LineItem():\n\n def __init__(self,\n item_number=\"\",\n description=\"\",\n unit_cost=0.0,\n sizes=None,\n created_date=datetime.now(),\n color=\"\",\n imprint_name=\"\",\n imprint_width=0.0,\n image_url=\"\"\n ):\n self.item_number = item_number\n self.description = description\n self.unit_cost = unit_cost\n self.sizes = {} if sizes is None else sizes\n self.created_date = created_date\n self.color = color\n self.imprint_name = imprint_name\n self.imprint_width = imprint_width\n self.image_url = image_url\n\n def __eq__(self, other):\n return self.item_number == other.item_number and self.description == other.description and self.unit_cost == other.unit_cost and self.color == other.color and self.imprint_name == other.imprint_name and self.image_url == other.image_url\n\n def to_dict(self):\n return {\n 'item_number': self.item_number,\n 'description': self.description,\n 'unit_cost': self.unit_cost,\n 'sizes': self.sizes,\n 'created_date': self.created_date,\n 'image_url': self.image_url,\n 'color': self.color,\n 'imprint_name': self.imprint_name,\n 'imprint_width': self.imprint_width\n }\n\n def total_cost(self):\n return self.unit_cost * sum([size for size in self.sizes.values()])\n","sub_path":"src/models/line_items/line_item.py","file_name":"line_item.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"246209924","text":"from __future__ import (absolute_import, division, print_function)\n\nfrom ansible.errors import AnsibleError\nfrom ansible.module_utils._text import to_text\nfrom ansible.plugins.action import ActionBase\n\n__metaclass__ = type\n\n\nclass ActionModule(ActionBase):\n\n def run(self, tmp=None, task_vars=None):\n if task_vars is None:\n task_vars = dict()\n result = super(ActionModule, self).run(tmp, task_vars)\n endpoint = self._task.args.get('endpoint', None)\n application_key = self._task.args.get('application_key', None)\n application_secret = self._task.args.get('application_secret', None)\n consumer_key = self._task.args.get('consumer_key', None)\n state = self._task.args.get('state', None)\n name = self._task.args.get('name', None)\n domain = self._task.args.get('domain', None)\n ip = self._task.args.get('ip', None)\n vrack = self._task.args.get('vrack', None)\n boot = self._task.args.get('boot', None)\n force_reboot = self._task.args.get('force_reboot', None)\n template = self._task.args.get('template', None)\n hostname = self._task.args.get('hostname', None)\n service = self._task.args.get('service', None)\n link_type = self._task.args.get('link_type', None)\n max_retry = self._task.args.get('max_retry', 10)\n sleep = self._task.args.get('sleep', 10)\n\n ssh_key_name = self._task.args.get('ssh_key_name', None)\n use_distrib_kernel = self._task.args.get('use_distrib_kernel', False)\n\n result['failed'] = True\n\n new_src = template\n\n credentials = ['endpoint', 'application_key', 'application_secret', 'consumer_key']\n credentials_in_args = [cred in self._task.args for cred in credentials]\n\n if name is None:\n result['msg'] = \"name is required\"\n elif service is None:\n result['msg'] = \"service is required\"\n elif any(credentials_in_args) and not all(credentials_in_args):\n result['msg'] = \"missing credentials. Either none or all the following (%s)\" % \", \".join(credentials)\n else:\n del result['failed']\n if result.get('failed'):\n return result\n\n if service == 'template':\n try:\n new_src = self._find_needle('files', template)\n except AnsibleError as e:\n result['failed'] = True\n result['msg'] = to_text(e)\n return result\n\n changed = False\n module_return = dict(changed=False)\n module_executed = False\n\n new_module_args = self._task.args.copy()\n new_module_args.update(\n dict(\n template=new_src\n )\n )\n module_return = self._execute_module(module_name='ovh', module_args=new_module_args, task_vars=task_vars)\n module_executed = True\n\n if module_return.get('failed'):\n result.update(module_return)\n return result\n if module_return.get('changed'):\n changed = True\n if module_executed:\n result.update(module_return)\n\n return result\n","sub_path":"plugins/action/ovh.py","file_name":"ovh.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"216534755","text":"# cell11\nwBus = 1.5\ncellGDS = Device('cell11')\n\n# sweep the ring width between groups of devices\n\ngpNum = 4\nfor k in range(gpNum):\n \n wRg = 1.9 + .1*k\n devLen = 9.8e3\n \n # taper length & taper width, width of bus -> width of taper\n lTp = 500\n wTp = .3\n \n # ring radius\n rRg = 200\n \n # horizontal and vertical dist. per device\n HD = 4*rRg\n VD = rRg\n devNum = 7 # num of MRR dev\n\n gapPeriod = .05\n \n # x-axis shift\n offset = devLen/2 - devNum*HD/2 + rRg*4\n # margin = 100\n\n D = Device(f'GP{k}')\n LB = Device(f'LB{k}')\n\n for i in range(devNum):\n gap = gapPeriod*i+0.1\n MRR = D << asymMRR(width_bus=wBus,\n width_rg=wRg,radius=rRg,\n gap=gap,\n lenL=i*HD+i*rRg,\n lenR=0,\n layer=WG_LAY).move((offset+HD*i,-VD*i))\n LB << pg.text(text=f'WRG {wRg}\\nGAP {1e3*gap:.0f}', layer=LB_LAY, justify='center').move((offset+HD*i,-VD*i))\n \n # tp port\n TPCL = D << pg.connector((lTp,rRg-VD*i), width=wBus)\n TPCR = D << pg.connector((devLen-lTp,rRg-VD*i), width=wBus)\n '''\n PTL = D << pg.connector((0,rRg-VD*i),width=wTp)\n PTR = D << pg.connector((devLen,rRg-VD*i),width=wTp)\n D << pr.route_basic(port1=TPCL.ports[2],port2=PTL.ports[1], layer=4)\n D << pr.route_basic(port1=TPCR.ports[1],port2=PTR.ports[2], layer=4)\n '''\n D << pg.taper(port=TPCL.ports[2],length=lTp,\n width1=wBus, width2=wTp, layer=TP_LAY)\n D << pg.taper(port=TPCR.ports[1],length=lTp,\n width1=wBus, width2=wTp, layer=TP_LAY)\n \n # MIDL = D << pg.connector((MRR.xmin-margin,(MRR.ymin+rRg)),width=wBus)\n RT1 = D << pr.route_manhattan(port1=TPCL.ports[1],port2=MRR.ports[2],\n bendType='circular',radius=rRg,layer=WG_LAY)\n RT2 = D << pr.route_manhattan(port1=TPCR.ports[2],port2=MRR.ports[1],\n bendType='circular',radius=rRg,layer=WG_LAY)\n\n markNum = 3\n markDist = 300\n markSize = 100\n markLeft = D << [pg.cross(length=100, width=20, layer=MK_LAY).move((i*markDist, -VD*devNum)) for i in range(markNum) ]\n markRight = D << [pg.cross(length=100, width=20, layer=MK_LAY).move((devLen-i*markDist, -VD*devNum)) for i in range(markNum) ]\n LB << pg.text(text=f'R {rRg:.0f}\\nWB {wBus:.2f}\\nWRG {wRg}\\nTPL {lTp}\\nTPW {wTp}', \n layer=LB_LAY, justify='right', size=20).move(TPCL.ports[1]).move((0,-rRg))\n LB << pg.text(text=f'R {rRg:.0f}\\nWB {wBus:.2f}\\nWRG {wRg}\\nTPL {lTp}\\nTPW {wTp}', \n layer=LB_LAY, justify='left', size=20).move(TPCR.ports[2]).move((0,-rRg))\n D << LB\n cellGDS << D.flatten().movey(VD*(devNum+2)*k)\n\nbar = mn.waveguide(length=devLen,width=wBus, layer=WG_LAY).move((0,-(devNum+1)*VD)) \n\nfor i in range(3):\n cellGDS << pg.copy(bar).movey(-i*VD-VD*2)\n\n\ncellGDS.move(-cellGDS.center)\n\ncellGDS << pg.basic_die(size=cellSize, text_size=100,\n street_length=500, \n street_width=20, text_location='S',\n die_name='cell 11',\n draw_bbox=False,\n layer=MK_LAY)\ncellGDS.flatten().write_gds('cell33.gds')","sub_path":"190924-NTT/cell/cell34.py","file_name":"cell34.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"458469321","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Boxplot configuration\nmedianprops = dict(linestyle='-', linewidth=2.5, color='firebrick')\nmeanpointprops = dict(marker='D', markeredgecolor='black',\n markerfacecolor='firebrick')\n\n# Data column indexes\nMINLAT = 0\nMAXLAT = 1\nMAXERROR = 2\nRMSE = 3\nRRMSE = 4\nEPS2 = 5\nEPS5 = 6\n\n# Reference values\n#ref_min_lat = 16.23 # LV\n#ref_max_lat = 50.37 # LV\nref_min_lat = 18.58 # RV\nref_max_lat = 67.25 # RV\n\n# Reading data\ndata_exp1 = np.genfromtxt(\"data/electric_data_RV_exp1.dat\")\ndata_exp2 = np.genfromtxt(\"data/electric_data_RV_exp2.dat\")\ndata_exp3 = np.genfromtxt(\"data/electric_data_RV_exp3.dat\")\n\n# Min. LAT\nmin_lat_box_plot_data = [ data_exp1[:,0], data_exp2[:,0], data_exp3[:,0] ]\nmin_lat_ref_value = [ref_min_lat, ref_min_lat, ref_min_lat]\n# Max. LAT\nmax_lat_box_plot_data = [ data_exp1[:,1], data_exp2[:,1], data_exp3[:,1] ]\nmax_lat_ref_value = [ref_max_lat, ref_max_lat, ref_max_lat]\n# Max. Error\nmax_error_box_plot_data = [ data_exp1[:,2], data_exp2[:,2], data_exp3[:,2] ]\n# RMSE\nrmse_box_plot_data = [ data_exp1[:,3], data_exp2[:,3], data_exp3[:,3] ]\n# RRMSE\nrrmse_box_plot_data = [ data_exp1[:,4], data_exp2[:,4], data_exp3[:,4] ]\n# eps < 2ms\neps2_box_plot_data = [ data_exp1[:,5], data_exp2[:,5], data_exp3[:,5] ]\n# eps < 5ms\neps5_box_plot_data = [ data_exp1[:,6], data_exp2[:,6], data_exp3[:,6] ]\n\nfig, axes = plt.subplots(nrows=3, ncols=3, figsize=(12, 12))\n# Min. LAT\naxes[0, 0].boxplot(min_lat_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[0, 0].scatter([1,2,3],min_lat_ref_value,s=200,c=\"red\",marker='D')\naxes[0, 0].set_title(\"Min.LAT\")\naxes[0, 0].set_ylabel(\"LAT (ms)\")\n#axes[0, 0].set_ylim([14,17])\n\n# Max. LAT\naxes[0, 1].boxplot(max_lat_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[0, 1].scatter([1,2,3],max_lat_ref_value,s=200,c=\"red\",marker='D')\naxes[0, 1].set_title(\"Max.LAT\")\naxes[0, 1].set_ylabel(\"LAT (ms)\")\n#axes[0, 1].set_ylim([40,60])\n\n# Max. Error\naxes[0, 2].boxplot(max_error_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[0, 2].set_title(\"Max.Error\")\naxes[0, 2].set_ylabel(\"LAT (ms)\")\n\n# RMSE\naxes[1, 0].boxplot(rmse_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[1, 0].set_title(\"RMSE\")\naxes[1, 0].set_ylabel(\"LAT (ms)\")\n\n# RRMSE\naxes[1, 1].boxplot(rrmse_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[1, 1].set_title(\"RRMSE\")\naxes[1, 1].set_ylabel(\"%\")\n\n# eps < 2ms\naxes[1, 2].boxplot(eps2_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[1, 2].set_title(r\"$\\epsilon$ < 2ms\")\naxes[1, 2].set_ylabel(\"%\")\n\n# eps < 5ms\naxes[2, 0].boxplot(eps5_box_plot_data, medianprops=medianprops, meanprops=meanpointprops, showmeans=False)\naxes[2, 0].set_title(r\"$\\epsilon$ < 5ms\")\naxes[2, 0].set_ylabel(\"%\")\n\naxes[2, 1].set_visible(False)\naxes[2, 2].set_visible(False)\n\nplt.setp(axes, xticks=[y + 1 for y in range(3)],\n xticklabels=['Exp1', 'Exp2', 'Exp3'])\nfig.suptitle(\"Right Ventricle - Electric Results\",fontsize=20)\nfig.subplots_adjust(hspace=0.3)\nplt.savefig(\"electric_results_RV.pdf\")\n#plt.show()","sub_path":"cco-project-3d-purkinje/scripts/Data-Reader/boxplot.py","file_name":"boxplot.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"194688057","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 31 15:24:31 2017\r\n\r\n@author: Manjit\r\n\"\"\"\r\n\r\nimport process_mjmag_data as mj\r\nimport ssx_py_utils_basic as ssxutil\r\n#import pickle\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\n#import matplotlib.gridspec as gds\r\nfrom matplotlib import animation\r\n\r\n\r\n\r\nshot = '013017r2'\r\n\r\n#time = time index [8192]\r\n#bdot = calibrated dB/dt data [3,25,8192]\r\n#timeb = time index for integrated data [8191]\r\n#b = integrated magnetic field data [3,25,8192]\r\n#bmod = modulus of b for doublets and triplets\r\n\r\ntime,bdot,timeb,b,bmod = mj.process_mjmag_data(shot)\r\n#create a new figure\r\nplt.close('all')\r\nfig = plt.figure(dpi = 300, facecolor = 'w', edgecolor = 'k')\r\n#fig.suptitle(date + 'r' + str(shot)+'\\n Right & left dotted lines indicate beginning & end of SFC, respectively', size = 10)\r\nax = plt.axes(xlim=(-4,30),ylim=(-500,500))\r\nax.axvline(x = 0, linestyle = 'dotted', color = 'black', linewidth = 2)\r\nax.axvline(x = 29.69, linestyle = 'dotted', color = 'black', linewidth = 2) \r\nfig.text(0.25,0.7, 'End of SFC', color = 'black',size = 10)\r\n#fig.text(1.5,0.4, 'Beginning of SFC', color = 'black', size = 10)\r\nax.set_ylabel('By (G)')\r\nax.set_xlabel('Position (cm)')\r\nfig.subplots_adjust(top=0.92, bottom=0.16, left = 0.15, right=0.96)\r\n\r\nt0 = 1700\r\ntf = 4500\r\nb = b[:,:,t0:tf]\r\nx = np.arange(20) * 1.5 - 2.86\r\nd, = ax.plot(x,b[0,0:20,0],'bo')\r\ns, = ax.plot(x,b[0,0:20,0],ls = 'dotted')\r\nax.set_title('Time = %.2f $\\mu s$' %(timeb[t0])) \r\n\r\ndef animate(i):\r\n d.set_data(x,b[0,0:20,i])\r\n \r\n s.set_data(x,b[0,0:20,i])\r\n ax.set_title('Time = %.2f $\\mu s$' %(timeb[t0 + i])) \r\n return d,s,\r\n \r\nanim = animation.FuncAnimation(fig,animate,frames = len(b[0,0,:]), interval = 20, blit = False)\r\nplt.show()\r\nwriter=animation.writers['ffmpeg'](fps=30)\r\nanim.save(shot+'_By.avi', writer=writer, dpi=600)\r\n\r\n","sub_path":"Animation_test.py","file_name":"Animation_test.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"495936495","text":"\n# in order to get ret working need to change make modification in imtuils VideoStream package\n\nfrom imutils.video import VideoStream\nimport cv2\n\nvs = VideoStream(src=0).start()\nwhile True:\n ret, frame = vs.read()\n if ret == True:\n cv2.imshow(\"Frame\", frame)\n else:\n print(\"Failed to get Frame\")\n key = cv2.waitKey(1) & 0xFF\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\ncv2.destroyAllWindows()\nvs.stop()","sub_path":"opencv_image_video/video_playback_using_videostream.py","file_name":"video_playback_using_videostream.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"393938232","text":"# Copyright (C) 2013 the Institute for Institutional Innovation by Data\n# Driven Design Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE MASSACHUSETTS INSTITUTE OF\n# TECHNOLOGY AND THE INSTITUTE FOR INSTITUTIONAL INNOVATION BY DATA\n# DRIVEN DESIGN INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# Except as contained in this notice, the names of the Institute for\n# Institutional Innovation by Data Driven Design Inc. shall not be used in\n# advertising or otherwise to promote the sale, use or other dealings\n# in this Software without prior written authorization from the\n# Institute for Institutional Innovation by Data Driven Design Inc.\n\nimport datetime\nimport json\n\nimport pytz\nimport requests\nfrom dateutil.parser import parse\nfrom constance import config\n\ndef is_access_token_valid(request):\n \"\"\"\n Validate the request's access token with the OpenID Connect server.\n\n This function looks for the access token first in the query string, then in\n the headers. Next, it passes the access token to the \"tokenscope\"\n endpoint. When it receives the response, it first checks the status code,\n followed by the response format, and followed finally by the token\n expiration date.\n\n :param request: HTTP request\n :type request: HttpRequest\n\n :returns: determination as to whether the access token is valid\n :rtype: bool\n \"\"\"\n access_token = request.GET.get('access_token', None)\n if not access_token:\n auth_header = request.META.get('HTTP_AUTHORIZATION', None)\n if not auth_header:\n return False\n try:\n access_token = auth_header.split()[1]\n except IndexError:\n return False\n r = requests.get(config.TOKENSCOPE_ENDPOINT,\n headers={'Authorization': 'Bearer ' + access_token})\n if r.status_code / 100 != 2: # 2xx success\n return False\n try:\n reply = json.loads(r.text)\n except ValueError:\n return False\n if 'expiration' in reply and 'user_id' in reply:\n expires = parse(reply['expiration'])\n now = datetime.datetime.now(pytz.utc) # \"aware\" datetime\n if expires > now:\n return True\n return False\n","sub_path":"oic_validation/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"596572833","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nfrom builtins import str, input, object\nfrom past.builtins import basestring\nfrom copy import copy\nfrom datetime import datetime, date, timedelta\nfrom dateutil.relativedelta import relativedelta # for doctest\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.application import MIMEApplication\nimport errno\nfrom functools import wraps\nimport imp\nimport inspect\nimport json\nimport logging\nimport os\nimport re\nimport shutil\nimport signal\nimport six\nimport smtplib\nfrom tempfile import mkdtemp\n\nfrom alembic.config import Config\nfrom alembic import command\nfrom alembic.migration import MigrationContext\n\nfrom contextlib import contextmanager\n\nfrom sqlalchemy import event, exc\nfrom sqlalchemy.pool import Pool\n\nimport numpy as np\nfrom croniter import croniter\n\nfrom airflow import settings\nfrom airflow import configuration\n\n\nclass AirflowException(Exception):\n pass\n\n\nclass AirflowSensorTimeout(Exception):\n pass\n\n\nclass TriggerRule(object):\n ALL_SUCCESS = 'all_success'\n ALL_FAILED = 'all_failed'\n ALL_DONE = 'all_done'\n ONE_SUCCESS = 'one_success'\n ONE_FAILED = 'one_failed'\n DUMMY = 'dummy'\n\n @classmethod\n def is_valid(cls, trigger_rule):\n return trigger_rule in cls.all_triggers()\n\n @classmethod\n def all_triggers(cls):\n return [getattr(cls, attr)\n for attr in dir(cls)\n if not attr.startswith(\"__\") and not callable(getattr(cls, attr))]\n\n\nclass State(object):\n \"\"\"\n Static class with task instance states constants and color method to\n avoid hardcoding.\n \"\"\"\n QUEUED = \"queued\"\n RUNNING = \"running\"\n SUCCESS = \"success\"\n SHUTDOWN = \"shutdown\" # External request to shut down\n FAILED = \"failed\"\n UP_FOR_RETRY = \"up_for_retry\"\n UPSTREAM_FAILED = \"upstream_failed\"\n SKIPPED = \"skipped\"\n\n state_color = {\n QUEUED: 'gray',\n RUNNING: 'lime',\n SUCCESS: 'green',\n SHUTDOWN: 'blue',\n FAILED: 'red',\n UP_FOR_RETRY: 'gold',\n UPSTREAM_FAILED: 'orange',\n SKIPPED: 'pink',\n }\n\n @classmethod\n def color(cls, state):\n if state in cls.state_color:\n return cls.state_color[state]\n else:\n return 'white'\n\n @classmethod\n def color_fg(cls, state):\n color = cls.color(state)\n if color in ['green', 'red']:\n return 'white'\n else:\n return 'black'\n\n @classmethod\n def runnable(cls):\n return [\n None, cls.FAILED, cls.UP_FOR_RETRY, cls.UPSTREAM_FAILED,\n cls.SKIPPED, cls.QUEUED]\n\n\ncron_presets = {\n '@hourly': '0 * * * *',\n '@daily': '0 0 * * *',\n '@weekly': '0 0 * * 0',\n '@monthly': '0 0 1 * *',\n '@yearly': '0 0 1 1 *',\n}\n\ndef provide_session(func):\n \"\"\"\n Function decorator that provides a session if it isn't provided.\n If you want to reuse a session or run the function as part of a\n database transaction, you pass it to the function, if not this wrapper\n will create one and close it for you.\n \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n needs_session = False\n if 'session' not in kwargs:\n needs_session = True\n session = settings.Session()\n kwargs['session'] = session\n result = func(*args, **kwargs)\n if needs_session:\n session.expunge_all()\n session.commit()\n session.close()\n return result\n return wrapper\n\n\ndef pessimistic_connection_handling():\n @event.listens_for(Pool, \"checkout\")\n def ping_connection(dbapi_connection, connection_record, connection_proxy):\n '''\n Disconnect Handling - Pessimistic, taken from:\n http://docs.sqlalchemy.org/en/rel_0_9/core/pooling.html\n '''\n cursor = dbapi_connection.cursor()\n try:\n cursor.execute(\"SELECT 1\")\n except:\n raise exc.DisconnectionError()\n cursor.close()\n\n@provide_session\ndef merge_conn(conn, session=None):\n from airflow import models\n C = models.Connection\n if not session.query(C).filter(C.conn_id == conn.conn_id).first():\n session.add(conn)\n session.commit()\n\n\ndef initdb():\n session = settings.Session()\n\n from airflow import models\n upgradedb()\n\n merge_conn(\n models.Connection(\n conn_id='airflow_db', conn_type='mysql',\n host='localhost', login='root', password='',\n schema='airflow'))\n merge_conn(\n models.Connection(\n conn_id='beeline_default', conn_type='beeline',\n host='localhost',\n schema='airflow'))\n merge_conn(\n models.Connection(\n conn_id='bigquery_default', conn_type='bigquery'))\n merge_conn(\n models.Connection(\n conn_id='local_mysql', conn_type='mysql',\n host='localhost', login='airflow', password='airflow',\n schema='airflow'))\n merge_conn(\n models.Connection(\n conn_id='presto_default', conn_type='presto',\n host='localhost',\n schema='hive', port=3400))\n merge_conn(\n models.Connection(\n conn_id='hive_cli_default', conn_type='hive_cli',\n schema='default',))\n merge_conn(\n models.Connection(\n conn_id='hiveserver2_default', conn_type='hiveserver2',\n host='localhost',\n schema='default', port=10000))\n merge_conn(\n models.Connection(\n conn_id='metastore_default', conn_type='hive_metastore',\n host='localhost',\n port=10001))\n merge_conn(\n models.Connection(\n conn_id='mysql_default', conn_type='mysql',\n login='root',\n host='localhost'))\n merge_conn(\n models.Connection(\n conn_id='postgres_default', conn_type='postgres',\n login='postgres',\n schema='airflow',\n host='localhost'))\n merge_conn(\n models.Connection(\n conn_id='sqlite_default', conn_type='sqlite',\n host='/tmp/sqlite_default.db'))\n merge_conn(\n models.Connection(\n conn_id='http_default', conn_type='http',\n host='https://www.google.com/'))\n merge_conn(\n models.Connection(\n conn_id='mssql_default', conn_type='mssql',\n host='localhost', port=1433))\n merge_conn(\n models.Connection(\n conn_id='vertica_default', conn_type='vertica',\n host='localhost', port=5433))\n merge_conn(\n models.Connection(\n conn_id='webhdfs_default', conn_type='hdfs',\n host='localhost', port=50070))\n merge_conn(\n models.Connection(\n conn_id='ssh_default', conn_type='ssh',\n host='localhost'))\n\n # Known event types\n KET = models.KnownEventType\n if not session.query(KET).filter(KET.know_event_type == 'Holiday').first():\n session.add(KET(know_event_type='Holiday'))\n if not session.query(KET).filter(KET.know_event_type == 'Outage').first():\n session.add(KET(know_event_type='Outage'))\n if not session.query(KET).filter(\n KET.know_event_type == 'Natural Disaster').first():\n session.add(KET(know_event_type='Natural Disaster'))\n if not session.query(KET).filter(\n KET.know_event_type == 'Marketing Campaign').first():\n session.add(KET(know_event_type='Marketing Campaign'))\n session.commit()\n\n models.DagBag(sync_to_db=True)\n\n Chart = models.Chart\n chart_label = \"Airflow task instance by type\"\n chart = session.query(Chart).filter(Chart.label == chart_label).first()\n if not chart:\n chart = Chart(\n label=chart_label,\n conn_id='airflow_db',\n chart_type='bar',\n x_is_date=False,\n sql=(\n \"SELECT state, COUNT(1) as number \"\n \"FROM task_instance \"\n \"WHERE dag_id LIKE 'example%' \"\n \"GROUP BY state\"),\n )\n session.add(chart)\n\n\ndef upgradedb():\n logging.info(\"Creating tables\")\n package_dir = os.path.abspath(os.path.dirname(__file__))\n directory = os.path.join(package_dir, 'migrations')\n config = Config(os.path.join(package_dir, 'alembic.ini'))\n config.set_main_option('script_location', directory)\n config.set_main_option('sqlalchemy.url',\n configuration.get('core', 'SQL_ALCHEMY_CONN'))\n command.upgrade(config, 'heads')\n\n\ndef resetdb():\n '''\n Clear out the database\n '''\n from airflow import models\n\n logging.info(\"Dropping tables that exist\")\n models.Base.metadata.drop_all(settings.engine)\n mc = MigrationContext.configure(settings.engine)\n if mc._version.exists(settings.engine):\n mc._version.drop(settings.engine)\n initdb()\n\n\ndef validate_key(k, max_length=250):\n if not isinstance(k, basestring):\n raise TypeError(\"The key has to be a string\")\n elif len(k) > max_length:\n raise AirflowException(\n \"The key has to be less than {0} characters\".format(max_length))\n elif not re.match(r'^[A-Za-z0-9_\\-\\.]+$', k):\n raise AirflowException(\n \"The key ({k}) has to be made of alphanumeric characters, dashes, \"\n \"dots and underscores exclusively\".format(**locals()))\n else:\n return True\n\n\ndef date_range(\n start_date,\n end_date=None,\n num=None,\n delta=None):\n \"\"\"\n Get a set of dates as a list based on a start, end and delta, delta\n can be something that can be added to ``datetime.datetime``\n or a cron expression as a ``str``\n\n :param start_date: anchor date to start the series from\n :type start_date: datetime.datetime\n :param end_date: right boundary for the date range\n :type end_date: datetime.datetime\n :param num: alternatively to end_date, you can specify the number of\n number of entries you want in the range. This number can be negative,\n output will always be sorted regardless\n :type num: int\n\n >>> date_range(datetime(2016, 1, 1), datetime(2016, 1, 3), delta=timedelta(1))\n [datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 1, 2, 0, 0), datetime.datetime(2016, 1, 3, 0, 0)]\n >>> date_range(datetime(2016, 1, 1), datetime(2016, 1, 3), delta='0 0 * * *')\n [datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 1, 2, 0, 0), datetime.datetime(2016, 1, 3, 0, 0)]\n >>> date_range(datetime(2016, 1, 1), datetime(2016, 3, 3), delta=\"0 0 0 * *\")\n [datetime.datetime(2016, 1, 1, 0, 0), datetime.datetime(2016, 2, 1, 0, 0), datetime.datetime(2016, 3, 1, 0, 0)]\n \"\"\"\n if not delta:\n return []\n if end_date and start_date > end_date:\n raise Exception(\"Wait. start_date needs to be before end_date\")\n if end_date and num:\n raise Exception(\"Wait. Either specify end_date OR num\")\n if not end_date and not num:\n end_date = datetime.now()\n\n delta_iscron = False\n if isinstance(delta, six.string_types):\n delta_iscron = True\n cron = croniter(delta, start_date)\n elif isinstance(delta, timedelta):\n delta = abs(delta)\n l = []\n if end_date:\n while start_date <= end_date:\n l.append(start_date)\n if delta_iscron:\n start_date = cron.get_next(datetime)\n else:\n start_date += delta\n else:\n for i in range(abs(num)):\n l.append(start_date)\n if delta_iscron:\n if num > 0:\n start_date = cron.get_next(datetime)\n else:\n start_date = cron.get_prev(datetime)\n else:\n if num > 0:\n start_date += delta\n else:\n start_date -= delta\n return sorted(l)\n\n\ndef json_ser(obj):\n \"\"\"\n json serializer that deals with dates\n usage: json.dumps(object, default=utils.json_ser)\n \"\"\"\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n\n\ndef alchemy_to_dict(obj):\n \"\"\"\n Transforms a SQLAlchemy model instance into a dictionary\n \"\"\"\n if not obj:\n return None\n d = {}\n for c in obj.__table__.columns:\n value = getattr(obj, c.name)\n if type(value) == datetime:\n value = value.isoformat()\n d[c.name] = value\n return d\n\n\ndef readfile(filepath):\n f = open(filepath)\n content = f.read()\n f.close()\n return content\n\n\ndef apply_defaults(func):\n \"\"\"\n Function decorator that Looks for an argument named \"default_args\", and\n fills the unspecified arguments from it.\n\n Since python2.* isn't clear about which arguments are missing when\n calling a function, and that this can be quite confusing with multi-level\n inheritance and argument defaults, this decorator also alerts with\n specific information about the missing arguments.\n \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n if len(args) > 1:\n raise AirflowException(\n \"Use keyword arguments when initializing operators\")\n dag_args = {}\n dag_params = {}\n if 'dag' in kwargs and kwargs['dag']:\n dag = kwargs['dag']\n dag_args = copy(dag.default_args) or {}\n dag_params = copy(dag.params) or {}\n\n params = {}\n if 'params' in kwargs:\n params = kwargs['params']\n dag_params.update(params)\n\n default_args = {}\n if 'default_args' in kwargs:\n default_args = kwargs['default_args']\n if 'params' in default_args:\n dag_params.update(default_args['params'])\n del default_args['params']\n\n dag_args.update(default_args)\n default_args = dag_args\n arg_spec = inspect.getargspec(func)\n num_defaults = len(arg_spec.defaults) if arg_spec.defaults else 0\n non_optional_args = arg_spec.args[:-num_defaults]\n if 'self' in non_optional_args:\n non_optional_args.remove('self')\n for arg in func.__code__.co_varnames:\n if arg in default_args and arg not in kwargs:\n kwargs[arg] = default_args[arg]\n missing_args = list(set(non_optional_args) - set(kwargs))\n if missing_args:\n msg = \"Argument {0} is required\".format(missing_args)\n raise AirflowException(msg)\n\n kwargs['params'] = dag_params\n\n result = func(*args, **kwargs)\n return result\n return wrapper\n\nif 'BUILDING_AIRFLOW_DOCS' in os.environ:\n # Monkey patch hook to get good function headers while building docs\n apply_defaults = lambda x: x\n\ndef ask_yesno(question):\n yes = set(['yes', 'y'])\n no = set(['no', 'n'])\n\n done = False\n print(question)\n while not done:\n choice = input().lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n print(\"Please respond by yes or no.\")\n\n\ndef send_email(to, subject, html_content, files=None, dryrun=False):\n \"\"\"\n Send an email with html content\n\n >>> send_email('test@example.com', 'foo', 'Foo bar', ['/dev/null'], dryrun=True)\n \"\"\"\n SMTP_MAIL_FROM = configuration.get('smtp', 'SMTP_MAIL_FROM')\n\n if isinstance(to, basestring):\n if ',' in to:\n to = to.split(',')\n elif ';' in to:\n to = to.split(';')\n else:\n to = [to]\n\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject\n msg['From'] = SMTP_MAIL_FROM\n msg['To'] = \", \".join(to)\n mime_text = MIMEText(html_content, 'html')\n msg.attach(mime_text)\n\n for fname in files or []:\n basename = os.path.basename(fname)\n with open(fname, \"rb\") as f:\n msg.attach(MIMEApplication(\n f.read(),\n Content_Disposition='attachment; filename=\"%s\"' % basename,\n Name=basename\n ))\n\n send_MIME_email(SMTP_MAIL_FROM, to, msg, dryrun)\n\n\ndef send_MIME_email(e_from, e_to, mime_msg, dryrun=False):\n SMTP_HOST = configuration.get('smtp', 'SMTP_HOST')\n SMTP_PORT = configuration.getint('smtp', 'SMTP_PORT')\n SMTP_USER = configuration.get('smtp', 'SMTP_USER')\n SMTP_PASSWORD = configuration.get('smtp', 'SMTP_PASSWORD')\n SMTP_STARTTLS = configuration.getboolean('smtp', 'SMTP_STARTTLS')\n SMTP_SSL = configuration.getboolean('smtp', 'SMTP_SSL')\n\n if not dryrun:\n s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)\n if SMTP_STARTTLS:\n s.starttls()\n if SMTP_USER and SMTP_PASSWORD:\n s.login(SMTP_USER, SMTP_PASSWORD)\n logging.info(\"Sent an alert email to \" + str(e_to))\n s.sendmail(e_from, e_to, mime_msg.as_string())\n s.quit()\n\n\ndef import_module_attrs(parent_module_globals, module_attrs_dict):\n '''\n Attempts to import a set of modules and specified attributes in the\n form of a dictionary. The attributes are copied in the parent module's\n namespace. The function returns a list of attributes names that can be\n affected to __all__.\n\n This is used in the context of ``operators`` and ``hooks`` and\n silence the import errors for when libraries are missing. It makes\n for a clean package abstracting the underlying modules and only\n brings functional operators to those namespaces.\n '''\n imported_attrs = []\n for mod, attrs in list(module_attrs_dict.items()):\n try:\n path = os.path.realpath(parent_module_globals['__file__'])\n folder = os.path.dirname(path)\n f, filename, description = imp.find_module(mod, [folder])\n module = imp.load_module(mod, f, filename, description)\n for attr in attrs:\n parent_module_globals[attr] = getattr(module, attr)\n imported_attrs += [attr]\n except Exception as err:\n logging.debug(\"Error importing module {mod}: {err}\".format(\n mod=mod, err=err))\n return imported_attrs\n\n\ndef is_in(obj, l):\n \"\"\"\n Checks whether an object is one of the item in the list.\n This is different from ``in`` because ``in`` uses __cmp__ when\n present. Here we change based on the object itself\n \"\"\"\n for item in l:\n if item is obj:\n return True\n return False\n\n\n@contextmanager\ndef TemporaryDirectory(suffix='', prefix=None, dir=None):\n name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)\n try:\n yield name\n finally:\n try:\n shutil.rmtree(name)\n except OSError as e:\n # ENOENT - no such file or directory\n if e.errno != errno.ENOENT:\n raise e\n\n\nclass AirflowTaskTimeout(Exception):\n pass\n\n\nclass timeout(object):\n \"\"\"\n To be used in a ``with`` block and timeout its content.\n \"\"\"\n def __init__(self, seconds=1, error_message='Timeout'):\n self.seconds = seconds\n self.error_message = error_message\n\n def handle_timeout(self, signum, frame):\n logging.error(\"Process timed out\")\n raise AirflowTaskTimeout(self.error_message)\n\n def __enter__(self):\n try:\n signal.signal(signal.SIGALRM, self.handle_timeout)\n signal.alarm(self.seconds)\n except ValueError as e:\n logging.warning(\"timeout can't be used in the current context\")\n logging.exception(e)\n\n def __exit__(self, type, value, traceback):\n try:\n signal.alarm(0)\n except ValueError as e:\n logging.warning(\"timeout can't be used in the current context\")\n logging.exception(e)\n\n\ndef is_container(obj):\n \"\"\"\n Test if an object is a container (iterable) but not a string\n \"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, basestring)\n\n\ndef as_tuple(obj):\n \"\"\"\n If obj is a container, returns obj as a tuple.\n Otherwise, returns a tuple containing obj.\n \"\"\"\n if is_container(obj):\n return tuple(obj)\n else:\n return tuple([obj])\n\n\ndef round_time(dt, delta, start_date=datetime.min):\n \"\"\"\n Returns the datetime of the form start_date + i * delta\n which is closest to dt for any non-negative integer i.\n\n Note that delta may be a datetime.timedelta or a dateutil.relativedelta\n\n >>> round_time(datetime(2015, 1, 1, 6), timedelta(days=1))\n datetime.datetime(2015, 1, 1, 0, 0)\n >>> round_time(datetime(2015, 1, 2), relativedelta(months=1))\n datetime.datetime(2015, 1, 1, 0, 0)\n >>> round_time(datetime(2015, 9, 16, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0))\n datetime.datetime(2015, 9, 16, 0, 0)\n >>> round_time(datetime(2015, 9, 15, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0))\n datetime.datetime(2015, 9, 15, 0, 0)\n >>> round_time(datetime(2015, 9, 14, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0))\n datetime.datetime(2015, 9, 14, 0, 0)\n >>> round_time(datetime(2015, 9, 13, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0))\n datetime.datetime(2015, 9, 14, 0, 0)\n \"\"\"\n\n if isinstance(delta, six.string_types):\n # It's cron based, so it's easy\n cron = croniter(delta, start_date)\n prev = cron.get_prev(datetime)\n if prev == start_date:\n return start_date\n else:\n return prev\n\n # Ignore the microseconds of dt\n dt -= timedelta(microseconds = dt.microsecond)\n\n # We are looking for a datetime in the form start_date + i * delta\n # which is as close as possible to dt. Since delta could be a relative\n # delta we don't know it's exact length in seconds so we cannot rely on\n # division to find i. Instead we employ a binary search algorithm, first\n # finding an upper and lower limit and then disecting the interval until\n # we have found the closest match.\n\n # We first search an upper limit for i for which start_date + upper * delta\n # exceeds dt.\n upper = 1\n while start_date + upper*delta < dt:\n # To speed up finding an upper limit we grow this exponentially by a\n # factor of 2\n upper *= 2\n\n # Since upper is the first value for which start_date + upper * delta\n # exceeds dt, upper // 2 is below dt and therefore forms a lower limited\n # for the i we are looking for\n lower = upper // 2\n\n # We now continue to intersect the interval between\n # start_date + lower * delta and start_date + upper * delta\n # until we find the closest value\n while True:\n # Invariant: start + lower * delta < dt <= start + upper * delta\n # If start_date + (lower + 1)*delta exceeds dt, then either lower or\n # lower+1 has to be the solution we are searching for\n if start_date + (lower + 1)*delta >= dt:\n # Check if start_date + (lower + 1)*delta or\n # start_date + lower*delta is closer to dt and return the solution\n if (\n (start_date + (lower + 1) * delta) - dt <=\n dt - (start_date + lower * delta)):\n return start_date + (lower + 1)*delta\n else:\n return start_date + lower * delta\n\n # We intersect the interval and either replace the lower or upper\n # limit with the candidate\n candidate = lower + (upper - lower) // 2\n if start_date + candidate*delta >= dt:\n upper = candidate\n else:\n lower = candidate\n\n # in the special case when start_date > dt the search for upper will\n # immediately stop for upper == 1 which results in lower = upper // 2 = 0\n # and this function returns start_date.\n\n\ndef chain(*tasks):\n \"\"\"\n Given a number of tasks, builds a dependency chain.\n\n chain(task_1, task_2, task_3, task_4)\n\n is equivalent to\n\n task_1.set_downstream(task_2)\n task_2.set_downstream(task_3)\n task_3.set_downstream(task_4)\n \"\"\"\n for up_task, down_task in zip(tasks[:-1], tasks[1:]):\n up_task.set_downstream(down_task)\n\n\nclass AirflowJsonEncoder(json.JSONEncoder):\n def default(self, obj):\n # convert dates and numpy objects in a json serializable format\n if isinstance(obj, datetime):\n return obj.strftime('%Y-%m-%dT%H:%M:%SZ')\n elif isinstance(obj, date):\n return obj.strftime('%Y-%m-%d')\n elif type(obj) in [np.int_, np.intc, np.intp, np.int8, np.int16,\n np.int32, np.int64, np.uint8, np.uint16,\n np.uint32, np.uint64]:\n return int(obj)\n elif type(obj) in [np.bool_]:\n return bool(obj)\n elif type(obj) in [np.float_, np.float16, np.float32, np.float64,\n np.complex_, np.complex64, np.complex128]:\n return float(obj)\n\n # Let the base class default method raise the TypeError\n return json.JSONEncoder.default(self, obj)\n\n\nclass LoggingMixin(object):\n \"\"\"\n Convenience super-class to have a logger configured with the class name\n \"\"\"\n\n @property\n def logger(self):\n try:\n return self._logger\n except AttributeError:\n self._logger = logging.root.getChild(self.__class__.__module__ + '.' +self.__class__.__name__)\n return self._logger\n\n","sub_path":"airflow/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":25489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"80677376","text":"\"\"\"\ntracking.py\n\nPerson detection and tracking.\n\"\"\"\n\nimport logging\nfrom multiprocessing import Process\n\nfrom .cv import get_centroids\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import cv2\nexcept ImportError:\n logger.warning(\"Could not import cv2, continuing with no tracking\")\n cv2 = None\n\n\ndef start_tracking(shared_dict):\n logger.info(\"Tracking starting up\")\n while True:\n shared_dict['centroids'] = get_centroids()\n\n\nclass Tracking:\n def __init__(self, shared_dict):\n self.process = Process(\n target=start_tracking, args=(shared_dict,))\n self.process.daemon = True\n self.process.start()\n self.data = shared_dict\n\n def stop(self):\n self.process.terminate()\n self.process.join()\n\n def __del__(self):\n self.stop()\n","sub_path":"control/thegrid/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"529155519","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: Gillett Hernandez\n# @Date: 2016-07-02 12:52:02\n# @Last Modified by: Gillett Hernandez\n# @Last Modified time: 2017-08-10 13:35:54\n\n# MARK SLOW - 4s\n\nfrom euler_funcs import timed\nimport itertools\n\n@timed\ndef main():\n\n def join(*ns):\n return int(\"\".join([str(n) for n in ns]))\n\n s = set([])\n for p in itertools.permutations([1, 2, 3, 4, 5, 6, 7, 8, 9]):\n if join(*p[:2])*join(*p[2:5]) == join(*p[5:]):\n s.add(join(*p[5:]))\n if p[0]*join(*p[1:5]) == join(*p[5:]):\n s.add(join(*p[5:]))\n print(sum(list(s)))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/problem_32.py","file_name":"problem_32.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"425017296","text":"#!/usr/bin/env python\r\n\r\n__author__ = \"Juan Biondi\"\r\n__credits__ = [\"Juan Biondi\"]\r\n__version__ = \"0.1\"\r\n__maintainer__ = \"Juan Biondi\"\r\n\r\n__status__ = \"Development\"\r\n\r\n\"\"\"\r\nImport Modules needed for this script.\r\n\"\"\"\r\nimport qrcode\r\nimport os\r\n\r\n\"\"\"\r\nDeclare functions for the code.\r\n\"\"\"\r\nclass GenerateQR(object):\r\n \"\"\"\r\n Global class to have it more like OOP\r\n \"\"\"\r\n \r\n def __init__(self, FileName):\r\n \"\"\"\r\n Init function to have the variables in the class\r\n \"\"\"\r\n self.FileName=FileName\r\n\r\n def create_images(self):\r\n \"\"\"\r\n This function will generate 50 .png images with a string data replacing last character on the\r\n string in order to have a uniques QR codes and names.\r\n \r\n Just have to declare a String variable with the name. It has to be longer that 3 characters.\r\n \"\"\"\r\n \r\n\r\n for i in range(1,51):\r\n FinalFileName = self.FileName[:-len(str(i))] + str(i)\r\n qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, )\r\n qr.add_data(FinalFileName)\r\n qr.make(fit=True)\r\n img = qr.make_image()\r\n with open('%s.png'%FinalFileName, 'wb') as f:\r\n img.save(f)\r\n\r\n \r\n \r\n\"\"\"\r\nCall the function(s) to be used on the final code.\r\n\"\"\"\r\n\r\n\r\n\r\nName = \"P01 V05 S0000000\"\r\nQR=GenerateQR(Name)\r\nQR.create_images()\r\n\r\n","sub_path":"Test/Multiple_QRcodes.py","file_name":"Multiple_QRcodes.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"75862635","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 24 15:16:00 2019\n\n@author: ASUS\n\"\"\"\n\nimport pandas as pd\nfrom datetime import date, timedelta, datetime\nimport time\nfrom pymongo import MongoClient\n\n\ndef perdelta(start, end, delta):\n curr = start\n while curr < end:\n yield curr\n curr += delta\ndef date_populater():\n days = []\n for result in perdelta(date(1993, 1, 1), date(1998, 12, 20), timedelta(days=1)):\n days.append(result);\n return(days);\n \n \n \n \n \ndef accounts_importer():\n with open('trans.csv','r') as csv_file:\n lines = csv_file.readlines()\n accounts = [];\n for line in lines:\n data = line.split(';')\n accounts.append(data[1])\n del accounts[0]\n finalAccounts=[];\n for i in accounts:\n if i not in finalAccounts:\n finalAccounts.append(i)\n return(finalAccounts)\n \n \n\n\n\ndef data_frame_initielizer():\n \n \n accounts = accounts_importer()\n days = date_populater()\n zero_init =[]\n for i in range(len(accounts)):\n zero_init.append(0)\n \n data = {}\n \n for k in days:\n data[k]=zero_init\n \n df = pd.DataFrame(data,index=accounts)\n return(df)\n\n\n\n\ndef data_frame_populater():\n \n \n start = time.time()\n \n df = data_frame_initielizer()\n accounts_id = []\n dates = []\n balance = []\n initdates = []\n with open('trans.csv','r') as csv_file:\n lines = csv_file.readlines()\n for line in lines:\n data = line.split(';')\n accounts_id.append(data[1])\n initdates.append(data[2])\n balance.append(data[6])\n del initdates[0]\n del balance[0]\n del accounts_id[0]\n \n for i in initdates:\n dates.append(datetime.strptime(i, '%y%m%d').date())\n \n # populate the dataframe with true values from history of transactions\n print(len(dates))\n for i, d in enumerate(dates):\n b = balance[i]\n c = accounts_id[i]\n df.loc[c,d] = b\n if(i > 10000):\n break\n \n \n # populate the rest of the dataframe with recent values for zeros members\n \n \n for i in range(len(df.index)):\n for j in range(1,365):\n if (df.iloc[i,j]==0):\n df.iloc[i,j]=df.iloc[i,j-1]\n \n \n \n \n \n \n #populating MongoDB\n \n \n client = MongoClient('localhost',27017) # Remember your uri string\n col = client['pfe']['balance_history_test']\n df.columns = df.columns.astype(str)\n data = df.to_dict(orient='records') # Here's our added param..\n col.insert_many(data)\n \n \n \n \n \n \n \n \n end = time.time()\n print (end-start , \" : seconds \") \n print(\"-----------------------------------------\") \n print (\"Done with success\") \n print(df)\n\n \n\ndata_frame_populater()","sub_path":"data/testif.py","file_name":"testif.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"328210157","text":"###############################################################################\n# Project Euler Problem 3\n# Smallest multiple\n# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n###############################################################################\n\ndef smallest_divisible_by(n):\n factorization = []\n factorizations = [prime_factors(i) for i in range(n)]\n for i in range(n):\n if factorization == []:\n factorization = factorizations[i]\n else:\n union = []\n [union.extend([n] * max(factorization.count(n), factorizations[i].count(n))) for n in range(min(\n min(factorization), min(factorizations[i])), max(max(factorization), max(factorizations[i]))+1)]\n factorization = union\n total = 1\n for i in factorization:\n total *= i\n return total\n\n\ndef prime_factors(n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n return factors\n\n\nprint(smallest_divisible_by(20))\n","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"385678565","text":"from pandevice.panorama import Panorama\n\nfrom lib.actions import BaseAction\n\n\nclass Commit(BaseAction):\n \"\"\"\n Commit a firewall\n \"\"\"\n def run(self, firewall, device_group, sync, sync_all, exception):\n\n device = self.get_pandevice(firewall)\n if device_group and not isinstance(device, Panorama):\n raise ValueError(\n '{} is not a Panorama and does not understand device_group!'.format(firewall)\n )\n\n if isinstance(device, Panorama):\n try:\n device.commit(sync=sync, exception=exception)\n device.commit_all(sync=sync,\n sync_all=sync_all,\n devicegroup=device_group,\n exception=exception)\n except Exception as e:\n return False, \"Commit on {} rasied exception: {}\".format(firewall, e)\n else:\n try:\n device.commit_all(sync=sync, exception=exception)\n except Exception as e:\n return False, \"Commit on {} rasied exception: {}\".format(firewall, e)\n\n if not sync:\n return True, \"Commit on {} successfully requested!\".format(firewall)\n\n return True, \"Commit on {} successfully completed!\".format(firewall)\n","sub_path":"actions/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"321333676","text":"import subprocess\nimport time\nimport sys\n\n\nclass run(object):\n\n def __init__(self, command):\n self.command = command\n self.pid = None\n\n def execute(self):\n self.proc = subprocess.Popen(self.command)\n self.pid = self.proc.pid\n\n def kill(self):\n if self.proc.poll() is None:\n print(\"Killing: \", self.command)\n print(\"Pid\", self.pid)\n subprocess.Popen(['kill', f\"{self.pid}\"])\n","sub_path":"cloudmesh/common/run/background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"550817244","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport unicodedata as ud\nlatin_letters= {}\n\ndef is_latin(uchr):\n try: return latin_letters[uchr]\n except KeyError:\n return latin_letters.setdefault(uchr, 'LATIN' in ud.name(uchr))\n\ndef only_roman_chars(unistr):\n return all(is_latin(uchr)\n for uchr in unistr\n if uchr.isalpha())\n\n\n# In[2]:\n\n\nimport string\ndef remove_strange_character(input_str):\n s1 = u'ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚÝàáâãèéêìíòóôõùúýĂăĐÐđĨĩŨũƠơƯưẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹßñä'\n s0 = u'AAAAEEEIIOOOOUUYaaaaeeeiioooouuyAaDDdIiUuOoUuAaAaAaAaAaAaAaAaAaAaAaAaEeEeEeEeEeEeEeEeIiIiOoOoOoOoOoOoOoOoOoOoOoOoUuUuUuUuUuUuUuYyYyYyYybna'\n s = ''\n for c in input_str:\n if c in s1:\n s += s0[s1.index(c)]\n elif c in string.punctuation or c.isdigit() or c == \" \":\n s += c\n elif c.isalpha() and only_roman_chars(c):\n s += c\n return s\n\n\n# In[3]:\n\n\ndef remove_accents(input_str):\n s1 = u'ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚÝàáâãèéêìíòóôõùúýĂăĐđĨĩŨũƠơƯưẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹßñä'\n s0 = u'AAAAEEEIIOOOOUUYaaaaeeeiioooouuyAaDdIiUuOoUuAaAaAaAaAaAaAaAaAaAaAaAaEeEeEeEeEeEeEeEeIiIiOoOoOoOoOoOoOoOoOoOoOoOoUuUuUuUuUuUuUuYyYyYyYybna'\n s = ''\n for c in input_str:\n if c in s1:\n s += s0[s1.index(c)]\n else:\n s += c\n return s\n\n\n# In[4]:\n\n\ndef remove_unword_character(inp):\n res = re.sub('[^A-Za-z]+', ' ', inp)\n while re.findall(\"\\s\\s\", res):\n res = re.sub('\\s\\s', '\\s', inp)\n return res.strip()\n\n\n# In[20]:\n\nimport re\ndef clean(word):\n word = remove_strange_character(word)\n s = \"\"\n single = \"\"\n for i in range(len(word)):\n if word[i] in string.punctuation:\n single = \"\"\n if len(single) > 1:\n s += \" \"\n else: \n try:\n a = word[i+2]\n if a.isalpha():\n s += \" \"\n except IndexError:\n pass\n elif word[i] == \" \":\n single = \"\"\n s += \" \"\n else:\n single += word[i]\n s += word[i]\n s = re.sub('[\\s]+', ' ', s)\n return s.strip()\n\n","sub_path":"education/CleanWord.py","file_name":"CleanWord.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"319127620","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport io\n\n\ndef can_be_float(value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef can_be_int(value):\n try:\n int(value)\n return True\n except ValueError:\n return False\n\n\ndef index_exists(list_to_check, index_to_check):\n try:\n list_to_check[index_to_check]\n return True\n except IndexError:\n return False\n\n\ndef are_floats(list_to_check):\n for item in list_to_check:\n if can_be_float(item) is True:\n pass\n else:\n return False\n return True\n\n\ndef plus_one(*args):\n variables = list()\n for i in args:\n variables.append(i + 1)\n return variables\n\n\ndef logwrite(logfilename, *args):\n form_string = unicode(args[0])\n for i in range(1, len(args), 1):\n form_string += '\\t'\n form_string += unicode(args[i])\n form_string += '\\n'\n with io.open(logfilename, 'a', encoding='utf-8') as logfile:\n logfile.write(form_string)\n\n\ndef is_ascii(string_to_check):\n try:\n string_to_check.decode('ascii')\n except UnicodeDecodeError:\n return False\n else:\n return True\n\n\ndef read_csv(csv_input_filename, columns_to_return):\n import csv\n with open(csv_input_filename, 'rt') as input_file:\n data = list(csv.reader(input_file, delimiter='\\t'))\n\n input_file.close()\n return tuple(map(list, zip(*data)))[:columns_to_return]\n\n\ndef write_csv(data, filename):\n import csv\n with open(filename, 'wb') as output_file:\n write = csv.writer(output_file)\n for row in data:\n write.writerow(row)\n\n output_file.close()\n\n\ndef generate_date_range(date_start, periods_count, period_size):\n import pandas\n if period_size == 'month':\n dates = pandas.date_range(date_start, periods=periods_count, freq='MS')\n elif period_size == 'hour':\n dates = pandas.date_range(date_start, periods=periods_count, freq='60 min')\n elif period_size == '15_min':\n dates = pandas.date_range(date_start, periods=periods_count, freq='15 min')\n elif period_size == 'year':\n dates = pandas.date_range(date_start, periods=periods_count, freq='AS')\n return dates\n\n\ndef draw(dates, x_size, y_size, title, y_axis_name, filename, *args):\n import os\n import matplotlib\n matplotlib.use('agg')\n import matplotlib.pyplot as plt\n plt.figure(figsize=(x_size, y_size))\n for data in args:\n plt.plot(dates, data)\n\n plt.title(title)\n plt.ylabel(y_axis_name)\n plt.xticks(rotation=25)\n plt.grid()\n plt.savefig(filename)\n os.system('gwenview %s' % filename)\n\n\ndef save_vars(filename, *args):\n import pickle\n vars_to_dump = list()\n\n with open(filename, 'w') as dumpfile:\n if len(args) == 1:\n pickle.dump(args[0], dumpfile)\n\n elif len(args) > 1:\n for i in args:\n vars_to_dump.append(i)\n pickle.dump(vars_to_dump, dumpfile)\n\n\ndef load_vars(filename):\n import pickle\n with open(filename) as dumpfile:\n variables_list = pickle.load(dumpfile)\n return variables_list\n","sub_path":"functions_all.py","file_name":"functions_all.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"585575275","text":"from googlesearch import search, get_page, filter_result, get_random_user_agent\n\n'''\n\tSearching a word via a query to Google Search Engine\n\t\n\t:param str word - the given word\n\t:param int stp - after how many result (index for last result) \n'''\n\n\ndef search_google(word, stp=5):\n\t# Search query\n\tquery = str(word)\n\n\tquery_result = search(query=query, tld='com', lang='en', num=5, start=0, stop=stp)\n\n\tresults = []\n\tfor res in query_result:\n\t\tres = filter_result(res)\n\t\thtml = get_page(res, get_random_user_agent())\n\n\t\tresults.append({'link': res, 'page': html})\n\n\treturn results\n\n\n\n\n\n","sub_path":"NLP/src/googleSearch.py","file_name":"googleSearch.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"541365680","text":"# ========================================================================\n# Copyright 2017 Emory University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========================================================================\n\n__author__ = 'Jinho D. Choi'\n\n# language\nLANGUAGE_ENGLISH = 'en'\n\n# input format\nINPUT_FORMAT_RAW = 'raw'\nINPUT_FORMAT_LINE = 'line'\n\n# sentiment analysis\nSENTIMENT_MOVIE = 'mov'\nSENTIMENT_TWITTER = 'twit'\nSENTIMENT_MOVIE_ATT = 'mov-att'\nSENTIMENT_TWITTER_ATT = 'twit-att'\n\n\nclass Configuration:\n def __init__(self,\n language=LANGUAGE_ENGLISH,\n input_format=INPUT_FORMAT_RAW,\n tokenize=True,\n segment=True,\n sentiment=()):\n self.language = language\n self.input_format = input_format\n self.tokenize = tokenize\n self.segment = segment\n self.sentiment = sentiment\n\n\ndef is_valid_input_format(format):\n return format in {INPUT_FORMAT_RAW, INPUT_FORMAT_LINE}\n\n\ndef is_valid_sentiment(sentiment):\n return sentiment in {SENTIMENT_MOVIE, SENTIMENT_TWITTER, SENTIMENT_MOVIE_ATT, SENTIMENT_TWITTER_ATT}","sub_path":"elit/util/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"620038150","text":"# crawling data from https://www.bestplaces.net/crime/zip-code/california/los_angeles/\n\n#Parse data using BeautifulSoup\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport re\nimport csv\n\ntable = []\ndata = open('orange_venturacountyzipcodes.txt', 'r')\nfor line in data:\n # print(line.rstrip())\n zip = re.findall('([0-9]+)', line)\n zip1 = zip[0]\n city = re.findall('\\((.*?)\\)', line)\n city1 = city[0].replace(' ', '_').lower()\n # print(zip[0], city1)\n try:\n url = 'https://www.bestplaces.net/crime/zip-code/california/' + str(city1) + '/' + str(zip1)\n html = urllib.request.urlopen(url).read()\n # print(html)\n soup = BeautifulSoup(html, 'html.parser')\n # print(soup)\n # print(tag)\n h5 = soup.find_all('h5')\n vio_sent = str(h5[0])\n # print(vio_sent)\n # print(type(vio_sent))\n vio_crime = re.findall('violent crime is ([0-9]+.[0-9])', vio_sent)\n\n prop_sent = str(h5[1])\n prop_crime = re.findall('property crime is ([0-9]+.[0-9])', prop_sent)\n result = [str(zip1), vio_crime[0], prop_crime[0]]\n table.append(result)\n print(result)\n except:\n result = [str(zip1), '0', '0']\n table.append(result)\n\n\nheader = ['zipcode', 'violent_crime_index', 'property_crime_index']\n# write into newfile:\nwith open('crime_by_zipcode_part2.csv', 'w') as csvwrite:\n writer = csv.writer(csvwrite, delimiter=',')\n writer.writerow(header)\n for i in table:\n writer.writerow(i)\n\ncsvwrite.close()\n","sub_path":"code/scraper/crimeindex.py","file_name":"crimeindex.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"147186289","text":"from django.contrib import admin\r\n\r\nfrom modeltranslation.admin import TranslationAdmin\r\nfrom sorl.thumbnail.admin import AdminImageMixin\r\nfrom mce_filebrowser.admin import MCEFilebrowserAdmin\r\n\r\nfrom main.models import Slider, Feedback\r\n\r\n\r\nclass SliderAdmin(AdminImageMixin, TranslationAdmin, MCEFilebrowserAdmin):\r\n class Media:\r\n\t js = (\r\n\t '/static/modeltranslation/js/force_jquery.js',\r\n\t 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js',\r\n\t '/static/modeltranslation/js/tabbed_translation_fields.js',\r\n\t )\r\n\t css = {\r\n\t 'screen': ('/static/modeltranslation/css/tabbed_translation_fields.css',),\r\n\t }\r\n fieldsets = [\r\n (None, {'fields': ['title','link', 'content', 'image']}),\r\n ]\r\n\r\n\r\nadmin.site.register(Feedback)\r\nadmin.site.register(Slider, SliderAdmin)","sub_path":"main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"342405501","text":"from nltk.corpus import semcor,wordnet\nfrom nltk.corpus.reader.wordnet import Lemma\n# WordNet synset_pos : 'a', 's', 'r', 'n', 'v'\n# ADJ,ADJ_SAT,ADV,NOUN,VERB\n\ndef LookUp(INPUT='said'): #return {SYNSET:SENT}\n SYNSET_SENT={}\n for s in semcor.tagged_sents(tag='both')[:333]:\n SENT=[]\n SYNSET=0\n for t in s:\n if t.height()==2: #Function Word or Punctuation\n POS=t.label()\n WORD=t[0]\n if POS==None:POS='None'\n SENT.append(WORD)\n elif t.height()==3: #Disambiguated Word\n POS=t[0].label()\n LEMMA=t.label()\n WORD=t[0][0]\n if not isinstance(LEMMA,str): #isinstance(LEMMA,Lemma):\n# print(WORD,LEMMA.name())\n if INPUT==LEMMA.name():#WORD:\n SYNSET=LEMMA.synset()#.name()\n SENT.append(WORD)\n else: #t.height()==4: #Named Entity\n WORD='_'.join(t[0][0])\n SENT.append(WORD)\n if SYNSET:SYNSET_SENT[SYNSET]=' '.join(SENT)#[:99]\n return SYNSET_SENT\n\n#ookUp(INPUT='say')\nfor SYNSET,SENT in LookUp(INPUT='say').items():print(SYNSET,SYNSET.definition()[:22],SENT[:22])\n","sub_path":"semcor3_tagged_sents.py","file_name":"semcor3_tagged_sents.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359693260","text":"# -*- coding:utf-8 -*-\nimport bs4, requests\ndef search_meteo(text):\n response = requests.post('http://meteo.ua/ua/search-forecast-by-city-name', data = {'name': text})\n b = bs4.BeautifulSoup(response.text, \"html.parser\")\n p3 = b.select('.main_cont p a')\n hrefs = p3[0]['href']\n print(hrefs)\n\n\n\n\n\n\nif __name__ == '__main__':\n search_meteo('київ')\n\n\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315333686","text":"import os\nimport logging\n\nimport numpy as np\nimport dicom\nfrom skimage import measure, morphology, segmentation, filters\nfrom scipy import ndimage\nimport h5py\n\n\nfrom tools import filetools\n\n\nclass DicomToHdf(object):\n \"\"\"Data ingest from dicom format to HDF format.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize\n \"\"\"\n self.min_hu = -1024 # air\n self.max_hu = 400 # bone\n self.cube_length = 448\n\n def save_to_hdf(self, images, masks, spacing, filename):\n \"\"\"Save a rescaled and resampled version of this patient information to hdf5\n\n # Arguments\n filename: The hdf file to store information\n \"\"\"\n filetools.rm_rf(filename)\n filetools.mkdir_p(os.path.dirname(filename))\n with h5py.File(filename, 'w') as f:\n f.create_dataset('images', data=images,\n dtype='int16', compression=\"gzip\")\n f.create_dataset('masks', data=masks, dtype='int8', compression=\"gzip\")\n f.create_dataset('spacing', data=spacing, compression=\"gzip\")\n\n def resample_spacing(self, images, slices, new_spacing=[1, 1, 1]):\n \"\"\"Resample the volume so that the physical distance between two consecutive\n pixels in the 3d volume of images is 1mm\n\n # Arguments\n images: 3d Numpy array of scan\n slices: the original dicom scan (necessary for thickness and pixel spacing)\n binarize: if true, will threshold to binary values\n\n # Returns\n rescaled_volume: resampled 3d Numpy array of images\n \"\"\"\n # current spacing\n spacing = map(float, ([slices[0].SliceThickness] + slices[0].PixelSpacing))\n spacing = np.array(list(spacing))\n # target spacing\n resizer = spacing / new_spacing\n new_shape = np.round(images.shape * resizer)\n resize_factor = new_shape / images.shape\n new_spacing = spacing / resize_factor\n rescaled_images = ndimage.interpolation.zoom(\n images, resize_factor, mode='nearest')\n # if hu is less than air, set it to air; if greater than bone, set it to\n # bone\n rescaled_images[rescaled_images < self.min_hu] = self.min_hu\n rescaled_images[rescaled_images > self.max_hu] = self.max_hu\n return rescaled_images, new_spacing\n\n def load_slices(self, patient_path):\n \"\"\"Read dicom files\n\n # Arguments\n patient_path: The full path of the patient files with the folder conventions as in\n Data Science Bowl 2017 input dataset\n\n # Returns\n Array of dicom slices\n \"\"\"\n slices = [dicom.read_file(patient_path + '/' + s)\n for s in os.listdir(patient_path)]\n slices.sort(key=lambda x: int(x.ImagePositionPatient[2]))\n try:\n slice_thickness = np.abs(slices[0].ImagePositionPatient[\n 2] - slices[1].ImagePositionPatient[2])\n except:\n slice_thickness = np.abs(\n slices[0].SliceLocation - slices[1].SliceLocation)\n for s in slices:\n s.SliceThickness = slice_thickness\n return slices\n\n def get_pixels_hu(self, slices):\n \"\"\"Get pixels in Hounsfield Units. From wikipedia:\n HU: air -1000, lung -500, fat -100 to -50, water 0\n\n # Arguments\n slices: The scan slices from the dicom file\n\n # Returns\n 3d Numpy array with each value representing a pixel in HU\n \"\"\"\n images = np.stack([s.pixel_array for s in slices])\n images = images.astype(np.int16)\n\n # Set outside-of-scan pixels to 0\n # The intercept is usually -1024, so air is approximately 0\n images[images == -2000] = 0\n\n # Convert to Hounsfield units (HU)\n for slice_number in range(len(slices)):\n intercept = slices[slice_number].RescaleIntercept\n slope = slices[slice_number].RescaleSlope\n if slope != 1:\n images[slice_number] = slope * images[slice_number].astype(np.float64)\n images[slice_number] = images[slice_number].astype(np.int16)\n images[slice_number] += np.int16(intercept)\n return np.array(images, dtype=np.int16)\n\n def get_lung_mask(self, image, hu_threshold):\n \"\"\"Get one or more blobs of binary segmentation of a 2d image based on\n hu threshold.\n\n # Arguments\n image: 2d Numpy array\n hu_threshold: the upper-bound for background\n\n # Returns\n 2d Numpy array with binary segmentation (tissue/no-tissue)\n \"\"\"\n # threshold and remove anything from the border\n binary_image = image < hu_threshold\n border_cleared_image = segmentation.clear_border(binary_image)\n # find the largest blobs - if more than 2 present, combine them\n labels = measure.label(border_cleared_image)\n areas = sorted([r.area for r in measure.regionprops(labels)])\n if len(areas) > 2:\n for region in measure.regionprops(labels):\n if region.area < areas[-2]:\n for coord in region.coords:\n labels[coord[0], coord[1]] = 0\n binary_image = labels > 0\n # erase 2mm of tissue (or whatever there is) from the boundary\n binary_image = morphology.binary_erosion(binary_image, morphology.disk(2))\n # keep 10mm of tissue (or whatever there is) around the boundary\n binary_image = morphology.binary_closing(binary_image, morphology.disk(10))\n # at this point, all we want are two big blobs - fill in holes in the mask\n binary_image = ndimage.binary_fill_holes(filters.roberts(binary_image))\n # zero is background so make foreground 1\n mask = binary_image != 0\n return mask\n\n def get_volume_mask(self, volume, hu_threshold=-400):\n \"\"\"Get the mask for each image in the volume stack\n\n # Arguments\n volume: 3d Numpy array with slice data\n\n # Returns\n masks: 3d Numpy array with stacked masks for each image slice\n \"\"\"\n return np.stack([self.get_lung_mask(img, hu_threshold) for img in volume])\n\n def get_masks_boundary_center(self, masks):\n # for creating boundaries, there must be more elegant solution, but for\n # now, this will do\n ax0_start = -1\n ax0_end = -1\n ax1_start = -1\n ax1_end = -1\n ax2_start = -1\n ax2_end = -1\n for i in range(np.shape(masks)[0]):\n mk = np.max(masks[i, :, :])\n if ax0_start == -1 and mk > 0:\n ax0_start = i\n if ax0_start != -1 and mk == 1:\n ax0_end = i\n for i in range(np.shape(masks)[1]):\n mk = np.max(masks[:, i, :])\n if ax1_start == -1 and mk > 0:\n ax1_start = i\n if ax1_start != -1 and mk == 1:\n ax1_end = i\n for i in range(np.shape(masks)[2]):\n mk = np.max(masks[:, :, i])\n if ax2_start == -1 and mk > 0:\n ax2_start = i\n if ax2_start != -1 and mk == 1:\n ax2_end = i\n bdr = np.int16(\n [[ax0_start, ax0_end], [ax1_start, ax1_end], [ax2_start, ax2_end]])\n # for finding center, we let scipy tell us\n vol = np.zeros(np.shape(masks))\n vol[bdr[0][0]:bdr[0][1], bdr[1][0]:bdr[1][1], bdr[2][0]:bdr[2][1]] = 1\n center = ndimage.measurements.center_of_mass(vol)\n center = np.int16(center)\n return bdr, center\n\n def standardize_to_cube(self, volume, center, empty_fill_value, new_cube_length = None):\n \"\"\"Create a cube and place volume such that the center of volume lines up\n with the center of the cube\n\n # Arguments\n volume: 3d Numpy array\n center: center of the volume\n empty_fill_value: value to put in cube prior to filling\n new_cube_length: length of new cube, defaults to cube size of 448\n \"\"\"\n if new_cube_length == None:\n new_cube_length = self.cube_length\n shift = new_cube_length / 2 - center\n vol_shp = np.int16(np.shape(volume))\n # get start/end of cube and volume\n cube_start = np.zeros(3, dtype=np.int16)\n vol_start = np.zeros(3, dtype=np.int16)\n cube_end = np.zeros(3, dtype=np.int16)\n vol_end = np.zeros(3, dtype=np.int16)\n for i in range(3):\n if shift[i] > 0:\n vol_start[i] = 0\n vol_end[i] = np.min([vol_shp[i], new_cube_length - shift[i]])\n else:\n vol_start[i] = -shift[i]\n vol_end[i] = np.min([vol_shp[i], new_cube_length + vol_start[i]])\n vol_len = vol_end[i] - vol_start[i]\n cube_start[i] = int((new_cube_length - vol_len)/2.0)\n cube_end[i] = cube_start[i] + vol_len\n\n # create new volume and copy data\n new_volume = np.full(\n (new_cube_length, new_cube_length, new_cube_length), empty_fill_value)\n new_volume[cube_start[0]:cube_end[0], cube_start[1]:cube_end[1], cube_start[2]:cube_end[\n 2]] = volume[vol_start[0]:vol_end[0], vol_start[1]:vol_end[1], vol_start[2]:vol_end[2]]\n return new_volume\n\n def rotate(self, volume, center, angle, empty_fill_value, axes=(2,1)):\n \"\"\"Rotate the volume one plane at a time to a given angle\n\n # Arguments\n volume: 3d Numpy array\n center: center of the volume\n angle: angle of rotation\n empty_fill_value: value to put in cube prior to filling\n axes: axis along which to rotate\n \"\"\"\n # pad so that when rotating no portion gets cut off\n pad_length = np.max(np.shape(volume))\n pad_length = np.int(pad_length * np.ceil(np.cbrt(3)))\n if pad_length % 2 != 0:\n pad_length += 1\n padded_image = self.standardize_to_cube(volume, center, self.min_hu, new_cube_length=pad_length)\n rotated_image = ndimage.interpolation.rotate(padded_image, angle, axes=axes, reshape=False)\n return rotated_image\n","sub_path":"datasets/dicom_to_hdf.py","file_name":"dicom_to_hdf.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"584546644","text":"\nschema = \"http://json-schema.org/draft-04/schema#\"\n\ndate = {\n \"type\": \"string\",\n \"pattern\": \"\\d{2}[-/]\\d{2}[-/]\\d{4}\",\n \"pattern\": \"\\d{4}[-/]\\d{2}[-/]\\d{2}\",\n}\n\ninteger = {\n \"type\": \"integer\",\n}\n\nnumber = {\n \"type\": \"number\"\n}\n\nstring = {\n \"type\": \"string\"\n}\n\narray = {\n \"type\": \"array\"\n}\n\nboolean = {\n \"type\": \"boolean\"\n}\n\nadd_remove = {\n \"type\": \"object\",\n \"properties\": {\n \"add\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"integer\",\n },\n },\n \"remove\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"integer\",\n },\n },\n },\n \"required\": [\n \"add\",\n \"remove\",\n ],\n}\n","sub_path":"sampleserve/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"265217896","text":"import requests\nimport os\nfrom auth.client import JWTAuth\nfrom report.client import ReportClient\nfrom datetime import datetime, timedelta\n\n# path to the adobe analytics service account private key\njwt = JWTAuth(\"C:/users/jschlons/keys/adobe_io_private.key\")\njwt.setIss(\"9D88879D5579828F7F000101@AdobeOrg\")\njwt.setSub(\"473A0AFF5C498D430A495E7C@techacct.adobe.com\")\njwt.setClientId(\"45ec3245e84d4d40978fd8da5eeefc3d\")\n# client secret is sensitive, better store it as an evnironment variable \njwt.setClientSecret(os.environ.get(\"ADOBE_CLIENT_SECRET\"))\njwt.setMetascopes(\"https://ims-na1.adobelogin.com/s/ent_analytics_bulk_ingest_sdk\")\njwt.setCompanyId(\"dhlcom1\")\n\n# setup connection and authenticate\ncon = requests.Session()\njwt.authenticate(con)\n\n# report client configuration\nclient = ReportClient(con, \"dhlcom1\")\n\n# select report from adobe analytics internal json request format\n# the respective json can be retrieved as described here:\n# https://helpx.adobe.com/analytics/kt/using/build-api2-requests-analysis-workspace-feature-video-use.html\nclient.fromJSON(\"C:/pythonprojects/powerbi/testjson.json\")\n\n# set date range here\n# use python datetime syntax for setting the start and end date\n# refer to: https://docs.python.org/3.7/library/datetime.html\nclient.setDateRange(datetime.now() - timedelta(days=5), datetime.now())\n\n# execute and retrieve pandas dataframe\ndf = client.execute()\nprint(df)","sub_path":"app/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"92946478","text":"from __future__ import print_function\nimport unittest\nfrom collections import OrderedDict\nimport numpy as np\nimport pytraj as pt\nfrom pytraj.utils import eq, aa_eq\n\nfrom pytraj.tools import flatten\nfrom pytraj import matrix\nfrom pytraj.compat import set\nfrom pytraj.parallel.base import _load_batch_pmap, worker_by_actlist\nfrom pytraj import c_commands\n\n\nclass TestNormalPmap(unittest.TestCase):\n\n def setUp(self):\n self.traj = pt.iterload(\"./data/Tc5b.x\", \"./data/Tc5b.top\")\n\n def test_raise(self):\n # if func is not support pmap\n self.assertRaises(ValueError, lambda: pt.pmap(pt.bfactors, self.traj))\n\n # run time: openmp vs pmap\n if 'OPENMP' in pt.compiled_info():\n self.assertRaises(RuntimeError,\n lambda: pt.pmap(pt.watershell, self.traj))\n\n # if traj is not TrajectoryIterator\n self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj[:]))\n\n # raise if a given method does not support pmap\n def need_to_raise(traj=self.traj):\n pt.pmap(2, pt.bfactors, traj)\n\n self.assertRaises(ValueError, lambda: need_to_raise())\n\n # raise if a traj is not TrajectoryIterator\n def need_to_raise_2(traj=self.traj):\n pt.pmap(pt.bfactors, traj[:], n_cores=2)\n\n # raise if turn off pmap by setting _is_parallelizable to False\n pt.radgyr._is_parallelizable = False\n self.assertRaises(ValueError, lambda: pt.pmap(pt.radgyr, self.traj))\n pt.radgyr._is_parallelizable = True\n\n def test_general(self):\n traj = pt.iterload(\"./data/Tc5b.x\", \"./data/Tc5b.top\")\n\n # with mask\n saved_data = pt.radgyr(traj, '@CA')\n data = pt.pmap(pt.radgyr, traj, '@CA')\n data = pt.tools.dict_to_ndarray(data)\n aa_eq(saved_data, data)\n\n # with a series of functions\n func_list = [pt.radgyr, pt.molsurf, pt.rmsd]\n ref = traj[-3]\n\n for n_cores in [2, 3]:\n for func in func_list:\n if func in [pt.rmsd, ]:\n pout = pt.tools.dict_to_ndarray(pt.pmap(func=func,\n traj=traj,\n ref=ref,\n n_cores=n_cores))\n serial_out = flatten(func(traj, ref=ref))\n else:\n pout = pt.tools.dict_to_ndarray(pt.pmap(n_cores=n_cores,\n func=func,\n traj=traj))\n serial_out = flatten(func(traj))\n aa_eq(pout[0], serial_out)\n\n # test worker\n # need to test this since coverages seems not recognize partial func\n from pytraj.parallel.multiprocessing_ import worker_byfunc\n data = worker_byfunc(rank=2, n_cores=8, func=pt.radgyr, traj=traj, args=(), kwd={'mask': '@CA'}, iter_options={})\n assert data[0] == 2, 'rank must be 2'\n assert data[2] == 1, 'n_frames for rank=2 should be 1 (only 10 frames in total)'\n\n def test_different_references(self):\n traj = self.traj\n func = pt.rmsd\n for i in range(0, 8, 2):\n ref = self.traj[i]\n for n_cores in [2, 3, ]:\n pout = pt.tools.dict_to_ndarray(pt.pmap(n_cores=n_cores,\n func=func,\n traj=traj,\n ref=ref))\n serial_out = flatten(func(traj, ref=ref))\n aa_eq(pout[0], serial_out)\n\n def test_iter_options(self):\n traj = pt.iterload(\"data/tz2.ortho.nc\", \"data/tz2.ortho.parm7\")\n t0 = traj[:].autoimage().rmsfit(ref=0)\n saved_avg = pt.mean_structure(t0)\n saved_radgyr = pt.radgyr(traj, '@CA')\n\n # perform autoimage, then rms fit to 1st frame, then compute mean structure\n iter_options = {'autoimage': True, 'rmsfit': 0}\n for n_cores in [2, 3]:\n avg = pt.pmap(pt.mean_structure,\n traj,\n iter_options=iter_options,\n n_cores=n_cores)\n aa_eq(saved_avg.xyz, avg.xyz)\n radgyr_ = pt.tools.dict_to_ndarray(pt.pmap(pt.radgyr,\n traj,\n iter_options={'mask':\n '@CA'}))\n aa_eq(radgyr_[0], saved_radgyr)\n\n\nclass TestParallelMapForMatrix(unittest.TestCase):\n\n def test_matrix_module(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n\n for n_cores in [2, 3]:\n for func in [matrix.dist, matrix.idea]:\n x = pt.pmap(func, traj, '@CA', n_cores=n_cores)\n aa_eq(x, func(traj, '@CA'))\n\n def test_ired_vector_and_matrix_pmap(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n h = traj.top.select('@H')\n n = h - 1\n nh = list(zip(n, h))\n\n exptected_vecs, exptected_mat = pt.ired_vector_and_matrix(traj, nh)\n for n_cores in [2, 3]:\n vecs, mat = pt.pmap(pt.ired_vector_and_matrix,\n traj,\n nh,\n n_cores=n_cores)\n aa_eq(exptected_vecs, vecs, decimal=7)\n aa_eq(exptected_mat, mat, decimal=7)\n\n def test_rotation_matrix_in_rmsd_calculation(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n saved_mat = pt.rotation_matrix(traj, ref=traj[3], mask='@CA')\n saved_rmsd = pt.rmsd(traj, ref=traj[3], mask='@CA')\n\n for n_cores in [2, 3]:\n out = pt.pmap(pt.rotation_matrix, traj, ref=traj[3], mask='@CA')\n out_with_rmsd = pt.pmap(pt.rotation_matrix,\n traj,\n ref=traj[3],\n mask='@CA',\n with_rmsd=True)\n mat = out[list(out.keys())[0]]\n mat2, rmsd_ = out_with_rmsd[list(out_with_rmsd.keys())[0]]\n aa_eq(saved_mat, mat)\n aa_eq(saved_mat, mat2)\n aa_eq(saved_rmsd, rmsd_)\n\n\nclass TestCpptrajCommandStyle(unittest.TestCase):\n\n def test_c_command_style(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n\n angle_ = pt.angle(traj, ':3 :4 :5')\n distance_ = pt.distance(traj, '@10 @20')\n\n data = pt.pmap(['angle :3 :4 :5', 'distance @10 @20'], traj, n_cores=2)\n assert isinstance(data, OrderedDict), 'must be OrderDict'\n arr = pt.tools.dict_to_ndarray(data)\n aa_eq(angle_, arr[0])\n aa_eq(distance_, arr[1])\n\n # as whole text, case 1\n data = pt.pmap('''angle :3 :4 :5\n distance @10 @20''',\n traj,\n n_cores=2)\n assert isinstance(data, OrderedDict), 'must be OrderDict'\n arr = pt.tools.dict_to_ndarray(data)\n aa_eq(angle_, arr[0])\n aa_eq(distance_, arr[1])\n\n def test_reference(self):\n traj = pt.iterload(\"./data/tz2.nc\", \"./data/tz2.parm7\")\n\n for n_cores in [2, 3]:\n # use 4-th Frame for reference\n data = pt.pmap(['rms @CA refindex 0'],\n traj,\n ref=traj[3],\n n_cores=n_cores)\n # another way to get reference\n data2 = pt.pmap(['rms @CA reference'],\n traj,\n ref=traj[3],\n n_cores=n_cores)\n # use int for ref\n data3 = pt.pmap(pt.rmsd,\n traj,\n ref=3,\n mask='@CA',\n n_cores=n_cores)\n # use int for ref: use cpptraj's commmand style\n data4 = pt.pmap(['rms @CA reference'],\n traj,\n ref=3,\n n_cores=n_cores)\n arr = pt.tools.dict_to_ndarray(data)[0]\n arr2 = pt.tools.dict_to_ndarray(data2)[0]\n arr3 = pt.tools.dict_to_ndarray(data3)[0]\n arr4 = pt.tools.dict_to_ndarray(data4)[0]\n aa_eq(arr, pt.rmsd(traj, ref=3, mask='@CA'))\n aa_eq(arr2, pt.rmsd(traj, ref=3, mask='@CA'))\n aa_eq(arr3, pt.rmsd(traj, ref=3, mask='@CA'))\n aa_eq(arr4, pt.rmsd(traj, ref=3, mask='@CA'))\n\n # use 4-th and 5-th Frame for reference\n data = pt.pmap(\n ['rms @CA refindex 0', 'rms @CB refindex 1'],\n traj,\n ref=[traj[3], traj[4]],\n n_cores=n_cores)\n arr = pt.tools.dict_to_ndarray(data)[0]\n aa_eq(arr, pt.rmsd(traj, '@CA', 3))\n\n arr1 = pt.tools.dict_to_ndarray(data)[1]\n aa_eq(arr1, pt.rmsd(traj, ref=4, mask='@CB'))\n\n # no ref\n data = pt.pmap(['radgyr', ], traj, n_cores=n_cores)\n arr = pt.tools.dict_to_ndarray(data)[0]\n aa_eq(arr, pt.radgyr(traj))\n\n\nclass TestParallelMapForAverageStructure(unittest.TestCase):\n\n def test_pmap_average_structure(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n saved_frame = pt.mean_structure(traj, '@CA')\n saved_xyz = saved_frame.xyz\n\n for n_cores in [2, 3, 4]:\n frame = pt.pmap(pt.mean_structure, traj, '@CA', n_cores=n_cores)\n aa_eq(frame.xyz, saved_xyz)\n\n\nclass TestLoadBathPmap(unittest.TestCase):\n\n def test_load_batch(self):\n '''just test ValueError\n '''\n self.assertRaises(\n ValueError,\n lambda: _load_batch_pmap(n_cores=4, lines=['autoimage'], traj=None, dtype='dict', root=0, mode='xyz', ref=None))\n\n\nclass TestFrameIndices(unittest.TestCase):\n\n def test_frame_indices(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n\n # frame_indices could be a list, range\n frame_indices_list = [[0, 8, 9, 3, 2, 5], range(6)]\n\n for frame_indices in frame_indices_list:\n for n_cores in [2, 3]:\n serial_out = pt.radgyr(traj,\n '@CA',\n frame_indices=frame_indices)\n parallel_out = pt.pmap(pt.radgyr,\n traj,\n '@CA',\n frame_indices=frame_indices)\n parallel_out_c_style = pt.pmap(\n ['radgyr @CA nomax'],\n traj,\n frame_indices=frame_indices)\n aa_eq(serial_out, pt.tools.dict_to_ndarray(parallel_out))\n aa_eq(serial_out,\n pt.tools.dict_to_ndarray(parallel_out_c_style))\n\n\nclass TestCheckValidCommand(unittest.TestCase):\n\n def test_check_valid_command(self):\n from pytraj.parallel.base import check_valid_command\n assert check_valid_command(['rms', ]) == (['rms refindex 0 '], True)\n assert check_valid_command(['distrmsd', ]) == (['distrmsd refindex 0 '], True)\n assert check_valid_command(['nativecontacts', ]) == (['nativecontacts refindex 0 '], True)\n assert check_valid_command(['nastruct', ]) == (['nastruct refindex 0 '], True)\n assert check_valid_command(['symmetricrmsd', ]) == (['symmetricrmsd refindex 0 '], True)\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n\n aa_eq(pt.tools.dict_to_ndarray(\n pt.pmap(['rmsd'], traj, ref=traj[3], n_cores=3)),\n pt.rmsd(traj, ref=traj[3]))\n\n # provide refindex\n aa_eq(pt.tools.dict_to_ndarray(\n pt.pmap(['rmsd refindex 0'], traj, ref=traj[3], n_cores=3)),\n pt.rmsd(traj, ref=traj[3]))\n\n aa_eq(pt.tools.dict_to_ndarray(\n pt.pmap(['rmsd refindex 0'], traj, ref=[traj[3], traj[0]], n_cores=3)),\n pt.rmsd(traj, ref=traj[3]))\n\n # if user does not provide reference, need to give it to them\n aa_eq(pt.tools.dict_to_ndarray(\n pt.pmap(['rmsd'], traj, n_cores=3)),\n pt.rmsd(traj, ref=traj[0]))\n\n # does not support matrix\n self.assertRaises(ValueError, lambda: pt.pmap(['matrix'], traj, n_cores=2))\n\n # do not accept any c analysis command\n for word in c_commands.analysis_commands:\n self.assertRaises(ValueError, lambda: pt.pmap(word, traj, n_cores=2))\n\n\nclass TestVolmap(unittest.TestCase):\n\n def test_volmap(self):\n traj = pt.iterload(\"data/tz2.ortho.nc\", \"data/tz2.ortho.parm7\")\n\n # raise if does not provide size\n self.assertRaises(AssertionError, lambda: pt.pmap(pt.volmap, traj, mask=':WAT@O',\n grid_spacing=(0.5, 0.5, 0.5),\n n_cores=2))\n\n mask = ':WAT@O'\n grid_spacing = (0.5, 0.5, 0.5)\n\n for n_cores in [1, 2, 3]:\n for size in [(20, 20, 20), (20, 40, 60)]:\n serial_out = pt.volmap(traj, mask=mask, grid_spacing=grid_spacing, size=size)\n parallel_out = pt.pmap(pt.volmap, traj, mask=mask, grid_spacing=grid_spacing,\n size=size, n_cores=n_cores)\n self.assertEqual(serial_out.shape, tuple(2 * x for x in size))\n aa_eq(serial_out, parallel_out)\n\n\nclass TestWorker(unittest.TestCase):\n\n def testworker_by_actlist(self):\n # just want to exercise all codes\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n for ref in [None, traj[0], [traj[0], traj[1]]]:\n data = worker_by_actlist(rank=3, n_cores=8, traj=traj, lines=['radgyr @CA', 'vector :3 :7'],\n ref=ref, kwd=dict())\n\n\ndef change_10_atoms(traj):\n for frame in traj:\n frame.xyz[:10] += 1.\n yield frame\n\n\nclass TestInserNewFunction(unittest.TestCase):\n\n def test_insert_new_function(self):\n traj = pt.iterload(\"data/tz2.nc\", \"data/tz2.parm7\")\n\n # create mutable Trajectory\n t0 = traj[:]\n for frame in t0:\n frame.xyz[:10] += 1.\n\n data_parallel = pt.pmap(pt.radgyr, traj, n_cores=2, apply=change_10_atoms)\n data_serial = pt.radgyr(t0)\n aa_eq(data_parallel['RoG_00000'], data_serial)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_pmap.py","file_name":"test_pmap.py","file_ext":"py","file_size_in_byte":14685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"341807432","text":"import numpy as np\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array, load_img\n\ntest_model = load_model('D:/.../CNN3/Databest_model_CNN4.h5')\nimg = load_img('D:/.../CNN4/test/RF1.jpg',False,target_size=(224,224))\nx = img_to_array(img)\nx = np.expand_dims(x, axis=0)\npreds = test_model.predict_classes(x)\nprob = test_model.predict_proba(x)\nprint(preds, prob)\n","sub_path":"Predict.py","file_name":"Predict.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"262861633","text":"def update_status_RN(propfile,targetnumber,targetname,status,visitdigit,visitN,filters,sheet_df,verbal=True):\n \"\"\"\n This function updates visits in the propfile given (targetnumber,targetname) with status R or N.\n For R (repeat) status, the target is already existed in the propfile, but we would like to change the total number of its visits (visitN) by keeping the visit number's first digit (visitdigit) and filter info (filters) the same.\n Arguments:\n - propfile = path to .prop file\n - targetnumber = str\n - targetname = str\n - status = str. It is in {'R','N'}\n - visitdigit = str, 36-base one digit (i.e., 0...Z)\n - visitN = int or str\n - filters = str. It must be a correct keyword to search for a template library (e.g., 'visits_G280'). Use TemplateHandler to facilitate this.\n - sheet_df = pandas.DataFrame of the observing sheet (i.e., Google sheet)\n - verbal = bool\n \"\"\"\n if verbal: print('Start update_status_RN({0},{1},{2},{3},{4},{5},{6},{7},{8}) ...\\n'.format(propfile,targetnumber,targetname,status,visitdigit,visitN,filters,'sheet_df',verbal))\n from rolling_snapshot_proposal_editor.find_targetname_in_visits import find_targetname_in_visits\n from rolling_snapshot_proposal_editor.remove_visit import remove_visit\n from rolling_snapshot_proposal_editor.templatehandler import TemplateHandler\n from rolling_snapshot_proposal_editor.add_visit import add_visit\n from rolling_snapshot_proposal_editor.get_available_visitnumber import get_available_visitnumber\n import numpy as np\n lineindex_visitnumber_targetname_list = find_targetname_in_visits(propfile)\n vn_list = []\n for i in lineindex_visitnumber_targetname_list:\n index,vn,tn = i\n if targetname==tn: vn_list.append(vn)\n if verbal: print('Target {0} {1} had {2} visits in the old proposal. It will be updated to {3} visits.\\n'.format(targetnumber,targetname,len(vn_list),visitN))\n niter = np.abs(len(vn_list) - int(visitN))\n if len(vn_list) > int(visitN):\n if verbal: print('Remove {0} visits from the old proposal.\\n'.format(niter))\n for i in np.arange(niter): remove_visit(propfile,propfile,vn_list[-1-i])\n elif len(vn_list) < int(visitN):\n if verbal: print('Add {0} visits from the old proposal.\\n'.format(niter))\n visitnumber_available = get_available_visitnumber(propfile,visitdigit,verbal)\n for i in np.arange(niter): \n visittemplate = TemplateHandler().templatedict[filters]\n visitnumber = visitnumber_available[i]\n add_visit(propfile=propfile,outname=propfile,visittemplate=visittemplate,visitnumber=visitnumber,targetname=targetname,line_index=None)\n print('Visit {0} added ... \\n'.format(visitnumber))\n if verbal: print('Finish update_status_RN.\\n')\n","sub_path":"build/lib/rolling_snapshot_proposal_editor/.ipynb_checkpoints/update_status_RN-checkpoint.py","file_name":"update_status_RN-checkpoint.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"112404385","text":"import os\n\nfrom flask import render_template, Blueprint, request, redirect, url_for\nfrom flask_login import login_required\nfrom werkzeug.utils import secure_filename\n\nfrom data_tools.wrappers.jobserver_control import start_job\nfrom data_tools.wrappers.sample_creation import create_sample_creation_workflow\nfrom data_tools.wrappers.sample_groups import get_sample_group, get_sample_groups, update_sample_group, \\\n delete_sample_group, \\\n create_sample_group\nfrom data_tools.wrappers.samples import get_sample, delete_sample\nfrom data_tools.template_models.entry_page import SampleGroupPageData\nfrom data_tools.template_models.form import SampleCreateFormData\nfrom data_tools.template_models.list_table import ListTableData\nfrom data_tools.util import AuthException\nfrom config.config import UPLOADDIR\nfrom helpers import handle_exception_browser, get_current_user, process_input_dict\n\nsample_groups = Blueprint('sample_groups', __name__, url_prefix='/sample_groups')\n\n\n@sample_groups.route('/', methods=['GET', 'POST'])\n@login_required\ndef render_sample_group_list():\n try:\n current_user = get_current_user()\n return render_template('pages/list.html',\n page_data=ListTableData(current_user, get_sample_groups(current_user), 'Sample Groups'))\n except Exception as e:\n return handle_exception_browser(e)\n\n\n@sample_groups.route('/', methods=['GET', 'POST', 'DELETE'])\n@login_required\ndef render_sample_group(sample_group_id=None):\n try:\n current_user = get_current_user()\n sample_group = get_sample_group(current_user, sample_group_id)\n if request.method == 'DELETE':\n samples_to_delete = [sample for sample in sample_group.samples if len(sample.sample_groups) < 2]\n delete_sample_group(current_user, sample_group)\n for sample in samples_to_delete:\n try:\n delete_sample(current_user, sample)\n except AuthException:\n pass\n return redirect(url_for('sample_groups.render_sample_group_list'))\n if request.method == 'POST':\n update_sample_group(current_user, sample_group, request.form)\n return render_template('pages/sample_group_entry.html',\n page_data=SampleGroupPageData(current_user, sample_group))\n except Exception as e:\n return handle_exception_browser(e)\n\n\n@sample_groups.route('/create', methods=['GET', 'POST'])\n@login_required\ndef render_upload_sample_group():\n try:\n current_user = get_current_user()\n if request.method == 'POST':\n files = request.files.getlist('files')\n filenames = [os.path.join(UPLOADDIR, secure_filename(file.filename)) for file in files]\n [file.save(filename) for file, filename in zip(files, filenames)]\n metadata = process_input_dict(request.form.to_dict(), True)\n workflow_data = create_sample_creation_workflow(current_user, filenames, metadata)\n metadata['samples'] = [get_sample(current_user, sample_id) for sample_id in workflow_data['output_ids']]\n sample_group = create_sample_group(current_user, metadata)\n job = start_job(workflow_data['workflow'], workflow_data['job'], current_user, 'upload')\n update_sample_group(current_user, sample_group, {'upload_job_id': job.id})\n return redirect(url_for('sample_groups.render_sample_group', sample_group_id=sample_group.id))\n return render_template('pages/create.html',\n page_data=SampleCreateFormData(current_user))\n except Exception as e:\n return handle_exception_browser(e)\n","sub_path":"omics/omics_dashboard/blueprints/browser/sample_groups.py","file_name":"sample_groups.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"423419525","text":"import bz2\nimport json\n\nfrom cmv.preprocessing.postPreprocessor import PostPreprocessor\n\nclass MetadataGenerator:\n def __init__(self, train_filename, val_filename, num_responses=2**32, extend=True,\n discourse=True, frames=True, sentiment=False):\n self.train_filename = train_filename\n self.val_filename = val_filename\n self.num_responses = num_responses\n self.extend = extend\n self.border = 'INTERMEDIATE_DISCUSSION'\n\n self.discourse = discourse\n self.frames = frames\n self.sentiment = sentiment\n \n self._data = None\n \n def _load_file(self, filename):\n pairs = []\n with bz2.BZ2File(filename) as f:\n for line in f:\n pairs.append(json.loads(line))\n return pairs\n\n @property\n def data(self):\n if self._data is not None:\n return self._data\n\n train = self._load_file(self.train_filename)\n val = self._load_file(self.val_filename)\n \n train_op, train_titles, train_pos, train_pos_indices, train_neg, train_neg_indices = self.processData(train)\n val_op, val_titles, val_pos, val_pos_indices, val_neg, val_neg_indices = self.processData(val)\n\n self._data = dict(train_op=train_op,\n train_titles=train_titles,\n train_pos=train_pos,\n train_pos_indices=train_pos_indices,\n train_neg=train_neg,\n train_neg_indices=train_neg_indices,\n val_op=val_op,\n val_titles=val_titles,\n val_pos=val_pos,\n val_pos_indices=val_pos_indices,\n val_neg=val_neg,\n val_neg_indices=val_neg_indices)\n \n return self._data\n \n def processData(self, pairs):\n op = []\n titles = []\n pos = []\n pos_indices = []\n neg = []\n neg_indices = []\n \n for pair_index,pair in enumerate(pairs):\n op.append(PostPreprocessor(pair['op_text'], op=True,\n discourse=False, frames=False).processedData)\n\n post = ''\n for comment_index,comment in enumerate(pair['negative']['comments'][:self.num_responses]):\n if self.extend:\n if comment_index > 0:\n post += '\\n' + self.border + '\\n'\n post += comment['body']\n else:\n neg.append(PostPreprocessor(comment['body'],\n discourse=self.discourse, frames=self.frames,\n sentiment=self.sentiment).processedData)\n neg_indices.append(pair_index)\n \n if self.extend:\n neg.append(PostPreprocessor(comment['body'],\n discourse=self.discourse, frames=self.frames,\n sentiment=self.sentiment).processedData)\n neg_indices.append(pair_index)\n \n post = ''\n for comment_index,comment in enumerate(pair['positive']['comments'][:self.num_responses]):\n if self.extend:\n if comment_index > 0:\n post += '\\n' + self.border + '\\n'\n post += comment['body']\n else:\n pos.append(PostPreprocessor(comment['body'],\n discourse=self.discourse, frames=self.frames,\n sentiment=self.sentiment).processedData)\n pos_indices.append(pair_index)\n\n if self.extend:\n pos.append(PostPreprocessor(comment['body'],\n discourse=self.discourse, frames=self.frames,\n sentiment=self.sentiment).processedData)\n pos_indices.append(pair_index)\n \n titles.append(PostPreprocessor(pair['op_title'], discourse=False, frames=False).processedData)\n \n return op, titles, pos, pos_indices, neg, neg_indices\n\n \n","sub_path":"cmv/preprocessing/metadataGenerator.py","file_name":"metadataGenerator.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"395340779","text":"# coding: utf-8\nimport argparse\nimport time\nimport math\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.optim import Adadelta,SGD\n\nimport data\nimport model\nfrom data import N_MAX_CHAR_SIZE\n\nparser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM Language Model')\nparser.add_argument('--data', type=str, default='./data/wikitext',\n help='location of the data corpus')\nparser.add_argument('--model', type=str, default='LSTM',\n help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU)')\nparser.add_argument('--emsize', type=int, default=200,\n help='size of word embeddings')\nparser.add_argument('--nhid', type=int, default=400,\n help='number of hidden units per layer')\nparser.add_argument('--nlayers', type=int, default=2,\n help='number of layers')\nparser.add_argument('--lr', type=float, default=20,\n help='initial learning rate')\nparser.add_argument('--clip', type=float, default=0.25,\n help='gradient clipping')\nparser.add_argument('--epochs', type=int, default=40,\n help='upper epoch limit')\nparser.add_argument('--batch_size', type=int, default=40, metavar='N',\n help='batch size')\nparser.add_argument('--bptt', type=int, default=35,\n help='sequence length')\nparser.add_argument('--dropout', type=float, default=0.2,\n help='dropout applied to layers (0 = no dropout)')\nparser.add_argument('--tied', action='store_true',\n help='tie the word embedding and softmax weights')\nparser.add_argument('--seed', type=int, default=1111,\n help='random seed')\nparser.add_argument('--cuda', action='store_true',\n help='use CUDA')\nparser.add_argument('--log-interval', type=int, default=200, metavar='N',\n help='report interval')\nparser.add_argument('--save', type=str, default='out/model.pt',\n help='path to save the final model')\nparser.add_argument('--load_corpus', type=int, default=0,\n help='Whether load old corpus')\nparser.add_argument('--load_save', type=int, default=0,\n help='Whether load old weight')\nargs = parser.parse_args()\n\n# Set the random seed manually for reproducibility.\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n if not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n else:\n torch.cuda.manual_seed(args.seed)\n\n###############################################################################\n# Load data\n###############################################################################\n\nif os.path.exists('out/corpus') and args.load_corpus:\n print('loading previous corpus')\n corpus = torch.load('out/corpus')\nelse:\n print('creating new corpus')\n corpus = data.Corpus(args.data)\n\nif not os.path.exists('out'):\n os.mkdir('out')\ntorch.save(corpus, 'out/corpus')\n\n# Starting from sequential data, batchify arranges the dataset into columns.\n# For instance, with the alphabet as the sequence and batch size 4, we'd get\n# ┌ a g m s ┐\n# │ b h n t │\n# │ c i o u │\n# │ d j p v │\n# │ e k q w │\n# └ f l r x ┘.\n# These columns are treated as independent by the model, which means that the\n# dependence of e. g. 'g' on 'f' can not be learned, but allows more efficient\n# batch processing.\n\ndef batchify(data, bsz):\n # Work out how cleanly we can divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n if args.cuda:\n data = data.cuda()\n return data\n\neval_batch_size = args.batch_size\ntrain_data = batchify(corpus.train, args.batch_size)\nval_data = batchify(corpus.valid, eval_batch_size)\ntest_data = batchify(corpus.test, eval_batch_size)\n\n###############################################################################\n# Build the model\n###############################################################################\n\nntokens = len(corpus.dictionary)\nncharsize = len(corpus.dictionary.idx2char)\nmodel = model.RNNModel(args.model, ntokens, ncharsize, N_MAX_CHAR_SIZE,\n args.emsize, args.nhid, args.nlayers, args.dropout, args.tied)\nif os.path.exists(args.save) and args.load_save:\n print('loading from old...')\n model.load_state_dict(torch.load(args.save))\nelse:\n print('starting new...')\nif args.cuda:\n model.cuda()\n\ncriterion = nn.CrossEntropyLoss()\n\n###############################################################################\n# Training code\n###############################################################################\n\ndef repackage_hidden(h):\n \"\"\"Wraps hidden states in new Variables, to detach them from their history.\"\"\"\n if type(h) == Variable:\n return Variable(h.data)\n else:\n return tuple(repackage_hidden(v) for v in h)\n\ndef get_word_char_vecs(words: torch.LongTensor) -> torch.LongTensor:\n tmp = []\n for word in words:\n char_vectors = torch.LongTensor(corpus.dictionary.get_word_char_vec(corpus.dictionary.idx2word[word]))+1\n tmp.append(char_vectors)\n return torch.cat(tmp).view(len(words), N_MAX_CHAR_SIZE)\n\n\n# get_batch subdivides the source data into chunks of length args.bptt.\n# If source is equal to the example output of the batchify function, with\n# a bptt-limit of 2, we'd get the following two Variables for i = 0:\n# ┌ a g m s ┐ ┌ b h n t ┐\n# └ b h n t ┘ └ c i o u ┘\n# Note that despite the name of the function, the subdivison of data is not\n# done along the batch dimension (i.e. dimension 1), since that was handled\n# by the batchify function. The chunks are along dimension 0, corresponding\n# to the seq_len dimension in the LSTM.\n\ndef get_batch(source, i, evaluation=False):\n seq_len = min(args.bptt, len(source) - 1 - i)\n source_words = source[i:i+seq_len]\n source_word_vectors = []\n for batch in source_words:\n source_word_vectors.append(get_word_char_vecs(batch))\n\n source_word_vector = torch.cat(source_word_vectors).view(len(source_words), -1,\n N_MAX_CHAR_SIZE)\n if args.cuda:\n source_word_vector = source_word_vector.cuda()\n data = (Variable(source_words, volatile=evaluation), Variable(source_word_vector, volatile=evaluation))\n #print('input=', data)\n target_char_vectors = []\n for batch in source[i+1:i+1+seq_len]:\n target_char_vectors.append(get_word_char_vecs(batch))\n target_char_vectors = torch.cat(target_char_vectors).view(seq_len, -1, N_MAX_CHAR_SIZE)\n target = Variable(source[i+1:i+1+seq_len].view(-1))\n #print('expected target=', target)\n return data, target\n\ndef calculate_single_loss(output_embedding, targets):\n target_word_idx_vec, target_char_vectors = targets\n target_embedding_value = model.get_word_embedding(target_word_idx_vec, target_char_vectors)\n target_embedding = Variable(target_embedding_value.data, volatile=True)\n return criterion(output_embedding, target_embedding)\n\ndef calculate_loss(output: torch.Tensor, targets):\n return criterion(output.view(-1, ntokens), targets)\n\n #loss = calculate_single_loss(output_embedding, targets)\n # (batch, bqtt), (batch, bqtt, N_MAX_CHAR_SIZE)\n #for i in range(5):\n # random_batch_idx = random.randint(0, data_source.size(0) // args.bptt - 1) * args.bptt\n # _, rand_targets = get_batch(data_source, random_batch_idx)\n # loss -= calculate_single_loss(output_embedding, rand_targets)\n #return loss\n\n\ndef evaluate(data_source):\n # Turn on evaluation mode which disables dropout.\n model.eval()\n total_loss = 0\n ntokens = len(corpus.dictionary)\n hidden = model.init_hidden(eval_batch_size)\n for i in range(0, data_source.size(0) - 1, args.bptt):\n data, targets = get_batch(data_source, i, evaluation=True)\n output, hidden = model(data, hidden)\n cur_loss = calculate_loss(output, targets)\n total_loss += cur_loss.data[0]\n hidden = repackage_hidden(hidden)\n return total_loss / len(data_source)\n\n\ndef train():\n # Turn on training mode which enables dropout.\n total_loss = 0\n start_time = time.time()\n ntokens = len(corpus.dictionary)\n hidden = model.init_hidden(args.batch_size)\n for batch, i in enumerate(range(0, train_data.size(0) - 1, args.bptt)):\n model.train()\n data, targets = get_batch(train_data, i)\n # Starting each batch, we detach the hidden state from how it was previously produced.\n # If we didn't, the model would try backpropagating all the way to start of the dataset.\n hidden = repackage_hidden(hidden)\n model.zero_grad()\n output, hidden = model(data, hidden)\n\n #confidence, output_max = torch.max(output.view(-1, ntokens), dim=1)\n #print('output_max=', output_max)\n #print('confidence=', confidence)\n loss = calculate_loss(output, targets)\n loss.backward()\n\n # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n # torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)\n for p in model.parameters():\n p.data.add_(-lr, p.grad.data)\n\n total_loss += loss.data[0]\n print(' || cur loss= ', loss.data[0] / args.bptt / args.batch_size)\n\n if batch % args.log_interval == 0 and batch > 0:\n cur_loss = total_loss / args.log_interval / args.bptt / args.batch_size\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:8f} | ppl {:8f}'.format(\n epoch, batch, len(train_data) // args.bptt, lr,\n elapsed * 1000 / args.log_interval, cur_loss, math.pow(2, cur_loss)))\n total_loss = 0\n start_time = time.time()\n if batch / args.log_interval % 5 == 0:\n print('saving check point...')\n torch.save(model.state_dict(), 'out/checkpoint.t7')\n if batch / args.log_interval % 10 == 0:\n val_loss = evaluate(val_data)\n print('-' * 89)\n print('|| valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(val_loss, math.pow(2, val_loss)))\n print('-' * 89)\n\n# Loop over epochs.\nlr = args.lr\nbest_val_loss = None\n\n# At any point you can hit Ctrl + C to break out of training early.\ntry:\n for epoch in range(1, args.epochs+1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.pow(2, val_loss)))\n print('-' * 89)\n # Save the model if the validation loss is the best we've seen so far.\n if not best_val_loss or val_loss < best_val_loss:\n torch.save(model.state_dict(), args.save)\n best_val_loss = val_loss\n else:\n # Anneal the learning rate if no improvement has been seen in the validation dataset.\n lr /= 4.0\nexcept KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early')\n print('dumping weights...')\n torch.save(model.state_dict(), args.save)\n\n# Load the best saved model.\nmodel.load_state_dict(torch.load(args.save))\n\n# Run on test data.\ntest_loss = evaluate(test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"509401609","text":"#From pg. 81 of Self-Taught Programmer\n\nlists = []\nrap = [\"Kayne West\", \"Jay Z\", \"Eminem\", \"Nas\"]\n\nrock = [\"Bob Dylan\", \"The Beatles\", \"Led Zeppelin\"]\n\ndjs = [\"Zeds Dead\", \"Tiesto\"]\n\nlists.append(rap)\nlists.append(rock)\nlists.append(djs)\n\n#print(lists)\n\nrap = lists[0]\n#print(rap)\nrap.append(\"Kendrick Lamar\")\n#print(rap)\n#print(lists)\n","sub_path":"ContainersInContainers.py","file_name":"ContainersInContainers.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"268239000","text":"import re\nfrom Framework.screen.Navigation import move_to_overview\nfrom Framework.screen.OVillage import get_village_name\nfrom Framework.screen.Profile import get_capital\nfrom Framework.utility.Constants import Server, get_XPATH, get_projectLogger\nfrom Framework.utility.SeleniumWebScraper import SWS\n\n\n# Project constants\nlogger = get_projectLogger()\nXPATH = get_XPATH()\n\n\ndef get_server(sws: SWS):\n \"\"\"\n Gets the current server.\n\n Parameters:\n - sws (SWS): Selenium Web Scraper.\n\n Returns:\n - Current server if operation is successful, None otherwise.\n \"\"\"\n ret = None\n serverURL = None\n try:\n serverURL = re.match(r'(.*)\\/(.*)', sws.getCurrentUrl()).group(1) + '/'\n except AttributeError as err:\n logger.error(f'In get_server: Regex failed to extract server: {err}')\n if serverURL:\n for server in Server:\n if server.value == serverURL:\n ret = server\n break\n else:\n logger.error(f'In get_server: Unknown server {serverURL}')\n return ret\n\n\ndef in_capital(sws: SWS):\n \"\"\"\n Checks if the current village is capital.\n \n Parameters:\n - sws (SWS): Selenium Web Scraper.\n\n Returns:\n - True if current village is capital, False otherwise.\n \"\"\"\n ret = False\n capital = get_capital(sws)\n if capital:\n villageName = get_village_name(sws)\n if villageName:\n if capital == villageName:\n ret = True\n else:\n logger.info('In in_capital: Currently not in capital')\n else:\n logger.error('In in_capital: get_village_name() failed')\n else:\n logger.error('In in_capital: get_capital() failed')\n return ret\n\n\ndef return_stable(func):\n \"\"\"\n Will run func and attempt to return to overview.\n\n Parameters:\n - func (Function): Function to call.\n \"\"\"\n def wrapper(*args, **kwargs):\n sws = None\n for arg in args:\n if isinstance(arg, SWS):\n sws = arg\n break\n else:\n logger.err(f'In return_stable: Failed to get SWS from {func}`s args')\n if sws:\n ret = func(*args, **kwargs)\n if not move_to_overview(sws):\n if isinstance(ret, bool):\n ret = False\n else:\n ret = None\n logger.error(f'In {func}: move_to_overview failed')\n return ret\n return wrapper\n","sub_path":"Framework/screen/General.py","file_name":"General.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"591062780","text":"'''\nРеализовать склонение слова «процент» для чисел до 20.\nНапример, задаем число 5 — получаем «5 процентов»,\nзадаем число 2 — получаем «2 процента». Вывести все склонения для проверки.\n'''\npercent = int(input(\"Введите количество процентов: \"))\nwhile percent < 0: #100 < percent or percent < 0:\n percent = int(input(\"Введите количество процентов: \"))\n\n\nif (percent % 10 == 2 or percent % 10 == 3 or percent % 10 == 4) and percent % 100 // 10 != 1:\n print(f'{percent} процента')\nelif percent % 10 == 1 and percent % 100 // 10 != 1:\n print(f'{percent} процент')\nelse:\n print(f'{percent} процентов')\n","sub_path":"dz/igor_pavlov_less1_dz3.py","file_name":"igor_pavlov_less1_dz3.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"305769777","text":"from collections import namedtuple\nfrom struct import unpack, unpack_from, calcsize\nimport zlib\n\nCPKEntry = namedtuple(\"CPKEntry\", \"name, data\")\n\ndef get_data(resource):\n\timport os.path\n\tparts = resource.split('/')\n\tparts.insert(0, os.path.dirname(__file__))\n\tresource_name = os.path.join(*parts)\n\treturn __loader__.get_data(resource_name)\n\nstrings = frozenset(get_data(\"strings.txt\").split(b\"\\n\"))\n\ndef eld_hash(name):\n\taccum = 0\n\tfor i in name:\n\t\tif i == 0: break\n\t\ta = (i ^ 0x80) - 128 + 16 * accum\n\t\ta &= 0xffffffff\n\t\tb = a & 0xF0000000\n\t\tif b:\n\t\t\ta ^= b >> 24\n\t\taccum = ~b & a\n\treturn accum\n\ndef parse_cpk(data):\n\tif data[0:4] != b\"DCPK\":\n\t\traise Exception(\"CPK magic wrong\", data[0:4])\n\n\tnum_files, header_bytes, payload_bytes = unpack_from(\" SentinelBoxClient:\n\n if not oauth:\n oauth = self.configure_standard_box_auth(box_jwt_auth)\n\n super().__init__(oauth, **kwargs)\n self.auth_enterprise_id = self.auth._enterprise_id\n self.auth_client_id = self.auth._client_id\n self.rate_limiter = (\n sentinel_http_client.RateLimiter(rate_limit, rate_period)\n if rate_limited\n else None\n )\n\n def __repr__(self) -> AnyStr:\n return f\"\"\n\n @staticmethod\n def configure_standard_box_auth(\n box_jwt_auth: dict,\n ) -> boxsdk.JWTAuth:\n oauth = boxsdk.JWTAuth.from_settings_dictionary(\n box_jwt_auth\n )\n oauth.authenticate_instance()\n\n return oauth\n\n def make_request(\n self, method: AnyStr, url: AnyStr, **kwargs\n ) -> boxsdk.network.default_network.DefaultNetworkResponse:\n \"\"\"\n Base class override to rate limit requests\n \"\"\"\n if self.rate_limiter:\n with self.rate_limiter:\n resp = super().make_request(method, url, **kwargs)\n else:\n resp = super().make_request(method, url, **kwargs)\n\n return resp\n","sub_path":"file_server_box_sync/box_client.py","file_name":"box_client.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"618315669","text":"from django.shortcuts import render,redirect\nfrom django.http import JsonResponse,HttpResponseRedirect\nimport time,random\nfrom .models import Wheel,nav,Mustbuy,Shop,MainShow,FoodTypes,Goods,User,Cart\nfrom django.conf import settings\nimport os\nfrom django.contrib.auth import logout\n\n# Create your views here.\ndef home(request):\n wheelsList=Wheel.objects.all()\n navList=nav.objects.all()\n mustbuyList=Mustbuy.objects.all()\n shopList=Shop.objects.all()\n shop1=shopList[0]\n shop2 = shopList[1:3]\n shop3 = shopList[3:7]\n shop4 = shopList[7:11]\n mainList=MainShow.objects.all()\n\n return render(request, 'axf/home.html',{\"title\":\"主页\",\"wheelsList\":wheelsList,\"navList\":navList,\"mustbuyList\":mustbuyList,\"shop1\":shop1,\"shop2\":shop2,\"shop3\":shop3,\"shop4\":shop4,\"mainList\":mainList})\n\ndef market(request,categoryid,cid,sortid):\n leftSlider=FoodTypes.objects.all()\n if cid == '0':\n productList=Goods.objects.filter(categoryid=categoryid)\n else:\n productList = Goods.objects.filter(categoryid=categoryid,childcid=cid)\n group=leftSlider.get(typeid=categoryid)\n childList=[]\n childnames=group.childtypenames\n arr1=childnames.split(\"#\")\n for str in arr1:\n arr2=str.split(\":\")\n obj={\"childName\":arr2[0],\"childId\":arr2[1]}\n childList.append(obj)\n if sortid==\"1\":\n productList=productList.order_by(\"productnum\")\n elif sortid==\"2\":\n pass\n elif sortid==\"3\":\n pass\n cartlist=[]\n usertoken = request.session.get(\"token\")\n if usertoken:\n user = User.objects.get(userToken=usertoken)\n cartlist=Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n for p in productList:\n for c in cartlist:\n if p.productid==c.productid:\n p.num=c.productnum\n\n return render(request, \"axf/market.html\",{\"title\":\"闪送超市\",\"leftSlider\":leftSlider,\"productList\":productList,\"childList\":childList,\"categoryid\":categoryid,\"cid\":cid})\n\ndef cart(request):\n usertoken=request.session.get(\"token\")\n if usertoken:\n user=User.objects.get(userToken=usertoken)\n cartslist=Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n\n return render(request, 'axf/cart.html', {\"title\": \"购物车\", \"cartslist\": cartslist})\n else:\n return render(request,'axf/cart.html',{\"title\":\"购物车\"})\n\ndef mine(request):\n username=request.session.get(\"username\",\"未登录\")\n return render(request,'axf/mine.html',{\"title\":\"我的\",\"username\":username})\n#注册\ndef register(request):\n if request.method==\"POST\":\n userAccount = request.POST.get(\"userAccount\")\n userPasswd = request.POST.get(\"userPasswd\")\n userName = request.POST.get(\"userName\")\n userPhone = request.POST.get(\"userPhone\")\n userAdderss = request.POST.get(\"userAdderss\")\n userRank = 0\n Token=time.time() + random.randrange(1, 100000)\n userToken =str(Token)\n f=request.FILES[\"userImg\"]\n userImg=os.path.join(settings.MDEIA_ROOT,userAccount+\".png\")\n with open (userImg,\"wb\") as fp:\n for date in f.chunks():\n fp.write(date)\n\n user=User.createuser(userAccount,userPasswd,userName,userPhone,userAdderss,userImg,userRank,userToken)\n user.save()\n request.session[\"username\"] = userName\n request.session[\"token\"] = userToken\n return redirect(\"/mine/\")\n else:\n return render(request,'axf/register.html',)\n\n#检查用户明是否可用\ndef checkuserid(request):\n userid=request.POST.get(\"userid\")\n try:\n user=User.objects.get(userAccount=userid)\n return JsonResponse({\"data\":\"改用户已经被注册\",\"status\":\"error\"})\n except User.DoesNotExist as e:\n return JsonResponse({\"data\":\"可以注册\",\"status\":\"success\"})\n\n#退出登陆\ndef quit(request):\n logout(request)\n return redirect(\"/mine/\")\n\n#登陆\nfrom .forms.login import LoginForm\nfrom django.http import HttpResponse\ndef login(request):\n if request.method == \"POST\":\n f = LoginForm(request.POST)\n if f.is_valid():\n # 信息格式没多大问题,验证账号和密码的正确性\n nameid = f.cleaned_data[\"username\"]\n pswd = f.cleaned_data[\"passwd\"]\n try:\n user = User.objects.get(userAccount = nameid)\n if user.userPasswd != pswd:\n return redirect('/login/')\n except User.DoesNotExist as e:\n return redirect('/login/')\n\n #登陆成功\n token = time.time() + random.randrange(1, 100000)\n user.userToken = str(token)\n user.save()\n request.session[\"username\"] = user.userName\n request.session[\"token\"] = user.userToken\n return redirect('/mine/')\n else:\n return render(request, 'axf/login.html', {\"title\": \"登陆\", \"form\": f,\"error\":f.errors})\n else:\n f = LoginForm()\n return render(request, 'axf/login.html', {\"title\": \"登陆\",\"form\":f})\n\ndef changecart(request,flag):\n #检查是否登陆\n usertoken =request.session.get(\"token\")\n if usertoken==None:\n return JsonResponse({\"data\":\"-1\",\"status\":\"error\"})\n user = User.objects.get(userToken=usertoken)\n productid = request.POST.get(\"productid\")\n product = Goods.objects.filter(productid=productid)\n product=product.first()\n if flag=='0':\n if product.storenums ==0:\n return JsonResponse({\"data\":\"-2\",\"status\":\"error\"})\n carts=Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n c=None\n if carts.count()==0:\n c=Cart.createcart(user.userAccount,productid,1,product.price,True,product.productimg,product.productlongname,False)\n c.save()\n else:\n try:\n c=carts.get(productid=productid)\n c.productnum+=1\n c.productprice = \"%.2f\" % (float(product.price) * c.productnum)\n c.save()\n except Cart.DoesNotExist as e:\n c = Cart.createcart(user.userAccount, productid, 1, product.price, True, product.productimg,product.productlongname, False)\n c.save()\n product.storenums-=1\n product.save()\n return JsonResponse({\"data\":c.productnum, \"price\":c.productprice,\"status\":\"success\"})\n if flag=='1':\n\n carts=Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n try:\n c=carts.get(productid=productid)\n c.productnum -= 1\n if c.productnum == 0:\n c.delete()\n return JsonResponse({\"data\": c.productnum, \"price\": c.productprice, \"status\": \"success\"})\n else:\n c.productprice = \"%.2f\" % (float(product.price) * c.productnum)\n c.save()\n product.storenums += 1\n product.save()\n return JsonResponse({\"data\": c.productnum, \"price\": c.productprice, \"status\": \"success\"})\n except Cart.DoesNotExist as e:\n return JsonResponse({\"data\": \"-2\", \"status\": \"error\"})\n\n if flag==\"3\":\n carts = Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n c = carts.get(productid=productid)\n c.isChose = not c.isChose\n c.save()\n str = \"\"\n if c.isChose:\n str = \"√\"\n return JsonResponse({\"data\": str, \"status\": \"success\"})\n if flag == \"4\":\n carts = Cart.objects.filter(userAccount=user.userAccount,orderid=\"0\")\n for c in carts:\n c.isChose = True\n c.save()\n str = \"√\"\n return JsonResponse({\"data\": str, \"status\": \"success\"})\n if flag==\"5\":\n carts = Cart.objects.filter(userAccount=user.userAccount,isChose=True,orderid=\"0\")\n orderid=user.userAccount+time.strftime(\"%Y%m%d%H%M%S\", time.localtime())\n # orderid=str(order)\n productList=[]\n for cart in carts:\n productList.append(cart.productid)\n cart.orderid=orderid\n cart.save()\n good=Goods.objects.filter(productid=cart.productid)\n good=good.first()\n good.productnum+=1\n good.save()\n return JsonResponse({\"data\":orderid,\"status\":\"success\",\"productList\":productList})\n\ndef order(request):\n usertoken = request.session.get(\"token\")\n if usertoken == None:\n return HttpResponseRedirect(\"/login/\")\n\n return render(request,\"axf/order.html\")\n\n\n\n\n\n\n\n","sub_path":"axf/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"373602356","text":"#%matplotlib inline\n#%config InlineBackend.figure_format = 'retina'\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, transforms, models\nfrom torch.optim import lr_scheduler\nimport matplotlib.pyplot as plt\nimport time\nimport copy\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, precision_recall_fscore_support, auc, precision_recall_curve\nimport sys\nimport os\nfrom collections import Counter\nimport math\nimport random\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport pandas\nimport scipy\nfrom prg import prg\n\ntransforms_ = transforms.Compose(\n [\n transforms.Resize((255)),\n #transforms.Resize((227,227)),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225]\n )\n ]\n)\n\none_shot_examples = {\n 'badminton': '/evaluation_dataset/one_shot_data/event_img/badminton/Easy_Mid_badminton_98.jpg',\n 'bocce': '/evaluation_dataset/one_shot_data/event_img/bocce/Medium_Mid_bocce_78.jpg',\n 'croquet': '/evaluation_dataset/one_shot_data/event_img/croquet/Easy_Mid_croquet_2.jpg',\n 'polo': '/evaluation_dataset/one_shot_data/event_img/polo/Easy_Mid_polo_96.jpg',\n 'RockClimbing': '/evaluation_dataset/one_shot_data/event_img/RockClimbing/Easy_Mid_RockClimbing_90.jpg',\n 'rowing': '/evaluation_dataset/one_shot_data/event_img/rowing/Easy_Mid_Rowing_5.jpg',\n 'sailing': '/evaluation_dataset/one_shot_data/event_img/sailing/Easy_Mid_sailing_83.jpg',\n 'snowboarding': '/evaluation_dataset/one_shot_data/event_img/snowboarding/Easy_Mid_snowboarding_33.jpg'\n}\n\n# A simple hook class that returns the input and output of a layer during forward/backward pass\nclass Hook():\n def __init__(self, module, backward=False):\n if backward==False:\n self.hook = module.register_forward_hook(self.hook_fn)\n else:\n self.hook = module.register_backward_hook(self.hook_fn)\n def hook_fn(self, module, input, output):\n self.input = input\n self.output = output\n def close(self):\n self.hook.remove()\n\nclass ImageFoldersWithPaths(datasets.ImageFolder):\n def __getitem__(self, index):\n original_tuple = super(ImageFoldersWithPaths, self).__getitem__(index)\n path = self.imgs[index][0]\n tuple_with_path = (original_tuple + (path,))\n return tuple_with_path\n\ndef accuracy(y_truth, y_pred):\n '''\n Returns accuracy score \n\n y_truth - list of true labels same size as y_pred\n y_pred - list of predicted labels same size as y_truth\n '''\n return float(sum([x==y for x, y in zip(y_truth, y_pred)]))/len(y_truth)\n\n\ndef load_data(datadir, is_valid_file_func= lambda x:True):\n '''\n Returns a pytorch Dataloader\n\n datadir - directory where each sub directory contains images for a specific class\n is_valid_file_func - function that takes in a file_path and determines if is a valid file for loading with a Dataset object\n '''\n data = datasets.ImageFolder(\n root=datadir,\n transform=transforms_,\n is_valid_file=is_valid_file_func \n )\n \n dataloader = torch.utils.data.DataLoader(\n data,\n batch_size=1024,\n num_workers=10,\n pin_memory=True\n )\n return dataloader\n\ndef load_data_with_paths(datadir, is_valid_file_func= lambda x:True):\n '''\n Returns a pytorch Dataloader, at each iteraction the dataloader returns:(feature_activations, labels, paths)\n\n datadir - directory where each sub directory contains images for a specific class\n is_valid_file_func - function that takes in a file_path and determines if is a valid file for loading with a Dataset object\n '''\n data = ImageFoldersWithPaths(\n root=datadir,\n transform=transforms_,\n is_valid_file=is_valid_file_func \n )\n \n dataloader = torch.utils.data.DataLoader(\n data,\n batch_size=1024,\n num_workers=10,\n pin_memory=True\n )\n return dataloader\n\ndef evaluate(W, data):\n '''\n Returns label predictions and softmax scores after applying weight matrix (W) to data\n W - class X weights matrix\n data - example X features\n '''\n return np.argmax(\n np.matmul(\n W,\n data.transpose()\n ),\n 0\n )\n\ndef oneshot_update(K, train_features, novel_features):\n '''\n Builds a new linear classifier based on original train_features and novel features. A new weight matrix (W) is returned\n\n K - matrix of labels for train features [n_classes, n_train_features] where 1 indicates class label\n train_features - example X features\n novel_features - features for one class [examples, features]\n '''\n features = np.hstack([train_features, novel_features])\n\n num_samples = train_features.shape[1] + novel_features.shape[1]\n\n num_classes = train_features.shape[1] + 1\n\n K_prime = np.zeros((num_classes,num_samples))\n K_prime[0:K.shape[0], 0:K.shape[1]] = K\n for i in range(train_features.shape[1], num_samples):\n K_prime[num_classes - 1,i] = 1\n\n W = np.matmul( K_prime, np.linalg.pinv(features) )\n\n return W \n\n\ndef get_features(device, model, test_dataloader):\n '''\n Gets pre-classification features from a resnet model. Returns true_classnames (determined by test_dataloader), labels, activation features.\n\n device - pytorch device\n model - pytorch model\n test_dataloader - pytorch dataloader\n '''\n truth_classnames = test_dataloader.dataset.classes\n avgPoolF = Hook(model.avgpool)\n features_arr = []\n labels_arr = []\n with torch.no_grad():\n for i, (inputs, labels) in enumerate(test_dataloader):\n inputs = inputs.to(device)\n outputs = model(inputs)\n print(avgPoolF.output.shape)\n avgPoolF_npy = avgPoolF.output.detach().cpu().reshape( labels.size()[0], -1).numpy()\n features_arr.append(avgPoolF_npy)\n labels_arr.append(labels.detach().cpu().numpy())\n \n features = np.vstack(features_arr)\n labels = np.hstack(labels_arr)\n return truth_classnames, labels, features\n\ndef get_features_with_paths(device, model, test_dataloader):\n '''\n Gets pre-classification features from a resnet model. Returns true_classnames (determined by test_dataloader), labels, activation features, image_path.\n\n device - pytorch device\n model - pytorch model\n test_dataloader - pytorch dataloader\n '''\n truth_classnames = test_dataloader.dataset.classes\n avgPoolF = Hook(model.avgpool)\n features_arr = []\n labels_arr = []\n image_paths = []\n with torch.no_grad():\n for i, (inputs, labels, paths) in enumerate(test_dataloader):\n inputs = inputs.to(device)\n outputs = model(inputs)\n print(avgPoolF.output.shape)\n avgPoolF_npy = avgPoolF.output.detach().cpu().reshape( labels.size()[0], -1).numpy()\n features_arr.append(avgPoolF_npy)\n labels_arr.append(labels.detach().cpu().numpy())\n image_paths += paths\n\n features = np.vstack(features_arr)\n labels = np.hstack(labels_arr)\n return truth_classnames, labels, features, image_paths\n\npreextracted_data_path = '/export/u10/jfaschin_ad/places_features.npz'\n\nmodel_path = '/export/u10/users/jfaschin/places.365.resnet18.pth'\n\ndef image_loader(image_name):\n \"\"\"load image, returns cuda tensor\"\"\"\n image = Image.open(image_name)\n image = transforms_(image).float()\n image = Variable(image, requires_grad=True)\n image = image.unsqueeze(0) #this is for VGG, may not be needed for ResNet\n return image.cuda() #assumes that you're using GPU\n\n\ndef compute_statistics(W_new, gt_label, new_labels, new_classes_features, original_labels, original_features):\n '''\n Computes classification related statistics based on the supplied W_new weight matrix.\n\n Arguments:\n W_new - linear classifier\n gt_label - integer label for the new class\n new_labels - labels for unseen classes\n new_classes_features - examples X features for unseen classes\n original_labels - labels for original training set\n original_features - examples X features for original training set\n\n Returns:\n acc_on_whole_set - accuracy on the new_class images + original training set images\n p_new - precision on new class\n r_new - recall on new class\n f1_new - F1 on new class\n acc_on_new_class - accuracy on the new_class\n pg - precision gain on new class\n rg - recall gain on new class\n '''\n y_pred = evaluate(W_new, new_classes_features)\n y_pred_arr = np.array(y_pred)\n\n y_pred_original = evaluate(W_new, original_features)\n\n #Y_pred_total = np.vstack((Y_pred_original, Y_pred[new_labels==gt_label,:]))\n\n N_original = len(y_pred_original)\n N_new = sum(new_labels == gt_label)\n\n y_pred_total_arr = np.concatenate((np.array(y_pred_original), y_pred_arr[new_labels == gt_label]))\n\n y_truth_total_arr = np.concatenate((original_labels, np.array([365] * N_new)))\n\n v = y_truth_total_arr == 365\n # np.set_printoptions(threshold=sys.maxsize)\n # prg_curve = prg.create_prg_curve(y_truth_total_arr == 365, Y_pred_total[:,365])\n # pr_xx, re_xx, _ = precision_recall_curve(y_truth_total_arr,\n # Y_pred_total[:,365],pos_label=365 )\n #plt.plot(re_xx, pr_xx)\n\n #print(prg_curve['recall_gain'])\n #print( prg_curve['precision_gain'])\n #plt.plot(prg_curve['recall_gain'], prg_curve['precision_gain'])\n #auprg = prg.calc_auprg(prg_curve)\n #print(auprg)\n \n tp = float(sum(y_pred_total_arr[-N_new:] == [365]*N_new))\n fp = float(sum(y_pred_total_arr[:N_original] == [365]*N_original))\n tn = float(sum(y_pred_total_arr[:N_original] != [365]*N_original))\n fn = float(sum(y_pred_total_arr[-N_new:] != [365]*N_new))\n '''\n print(f'tp:{tp}')\n print(f'fp:{fp}')\n print(f'tn:{tn}')\n print(f'fN:{fn}')\n\n\n tpr = tp / (tp + fn)\n fpr = fp / (fp + tn) \n '''\n pg = prg.precision_gain(tp, fn, fp, tn)\n rg = prg.recall_gain(tp, fn, fp, tn)\n\n acc_on_whole_set = accuracy(y_truth_total_arr, y_pred_total_arr)\n precision, recall, f1, _ = precision_recall_fscore_support(\n y_truth_total_arr,\n y_pred_total_arr,\n labels=range(366),\n zero_division=0\n )\n p_new = precision[365]\n r_new = recall[365]\n f1_new = f1[365]\n acc_on_new_class = accuracy(y_truth_total_arr == 365, y_pred_total_arr == 365)\n\n return acc_on_whole_set, p_new, r_new, f1_new, acc_on_new_class, pg, rg\n # return acc_on_whole_set, p_new, r_new, f1_new, acc_on_new_class, tpr, fpr\n\n\ndef main():\n experiment_name = '11232020.codecleanup'\n\n # Load up pretrained model\n num_classes = 365\n model = models.resnet18(num_classes=num_classes)\n model.load_state_dict(torch.load(model_path)['state_dict'])\n model.eval()\n\n device = torch.device(\n \"cuda\" if torch.cuda.is_available() \n else \"cpu\"\n )\n\n model.to(device)\n\n # Recover the weight matrix for the output layer to initialize one-shot detection\n W = model.fc.weight.detach().cpu().numpy()\n b = model.fc.bias.detach().cpu().numpy()\n\n # Compute the pseudo-inverse to recover features necessary for the one-shot update\n prior_features = np.linalg.pinv(W)\n\n # Load pre-extracted activation features for both the original places validation set and the images from new_classes\n preextracted_data = np.load(preextracted_data_path)\n \n original_classnames = preextracted_data['original_classnames']\n original_labels = preextracted_data['original_labels']\n original_features = preextracted_data['original_feature']\n\n new_classnames = preextracted_data['new_classnames']\n new_classes_labels = preextracted_data['new_classes_labels']\n new_classes_features = preextracted_data['new_classes_features']\n\n # Setting up data frames for analysis\n df = pandas.DataFrame(\n columns=[\n 'new_class',\n 'mod',\n 'value',\n 'filter',\n 'acc_on_all_classes',\n 'acc_on_new_class',\n 'p_new',\n 'r_new',\n 'f1_new'\n ]\n )\n df_summary = pandas.DataFrame(\n columns=[\n 'new_class',\n 'filter',\n 'aupg',\n 'aupr'\n ]\n )\n\n for new_class, example_path in one_shot_examples.items():\n print(new_class)\n \n # Loading up the oneshot example image for that class\n training_image_path = example_path\n\n training_image = image_loader(training_image_path)\n\n avgPoolF = Hook(model.avgpool)\n\n # Recovering the activations\n output = model(training_image)\n\n avgPoolF_npy = avgPoolF.output.detach().cpu().numpy()\n #active_srt = [y for _, y in sorted(zip(avgPoolF_npy[0,:,:,0], range(512)),reverse=True)]\n #print(active_srt[:20])\n\n # Determine new weight matrix W_new for linear classification\n W_new = oneshot_update( np.eye(365), prior_features, avgPoolF_npy[0,:,:,0])\n\n # Rescale W_new\n scale_factor_sum = 0\n for x in range(365):\n numerator = np.sqrt(np.mean(np.square(W_new[x, :])))\n denomonator = np.sqrt(np.mean(np.square(W_new[365, :])))\n scale_factor_sum += numerator/denomonator\n scale_factor = scale_factor_sum / 365\n W_new[365, :] *= scale_factor\n\n # Save new weight matrix for further investigation\n np.savez(f'{new_class}_w_new.{experiment_name}', W_new)\n \n # Predict using new weight matrix\n y_pred, _ = evaluate(W_new, new_classes_features)\n \n # Determine the index assigned to the new class amongst the other new classes\n gt_label = list(new_classnames).index(new_class)\n \n # Create numpy arrays for easier syntax\n y_truth_arr = np.array(new_classes_labels)\n y_pred_arr = np.array(y_pred)\n\n # Count number of false negatives from the new class\n misclassified = np.logical_and(y_truth_arr == gt_label, y_pred_arr < 365)\n\n print(f'Number of false negatives for new class: {sum(misclassified)}')\n \n # Print out which of the original classes, examples of the new class are confused with\n print(f'Confused classes:')\n print(f'-----------------')\n for class_name, count in Counter([original_classnames[x] for x in y_pred_arr[misclassified]]).most_common():\n print(f'{class_name}:{count}')\n print(f'-----------------')\n \n # Print out the number from the new class that are correct\n n_correct = sum(np.logical_and(y_truth_arr == gt_label, y_pred_arr == 365))\n print(n_correct)\n W_new_base = np.copy(W_new)\n\n top_positive_weights = []\n top_negative_weights = []\n\n new_class_most_positive_filters = [x for _, x in sorted(zip(W_new[365, :], range(512)), reverse=True)][:20]\n new_class_most_negative_filters = [x for _, x in sorted(zip(W_new[365, :], range(512)))][:20]\n\n filters_to_try = new_class_most_positive_filters + new_class_most_negative_filters\n \n for filter_index in filters_to_try:\n pg_l = []\n rg_l = []\n p_l = []\n r_l = []\n for magnitude in range(-5, 6, 2):\n W_new = np.copy(W_new_base)\n\n # Set the weight value to be the highest weight value or lowest weight value for the weight vector depending on the sign of the original weight value for that filter\n weight_value = W_new[365, new_class_most_positive_filters[0]] if W_new[365, filter_index] > 0 else W_new[365, new_class_most_negative_filters[0]]\n W_new[365, filter_index] = magnitude * weight_value\n # W_new[365, filter_index] = magnitude * W_new[365, filter_index]\n tic = time.perf_counter()\n\n # Compute statistics based on the modified W_new matrix\n acc_on_whole_set, p_new, r_new, f1_new, acc_on_new_class, pg, rg = compute_statistics(W_new, gt_label, y_truth_arr, new_classes_features, original_labels, original_features)\n print(f'pg:{pg} rg:{rg}')\n pg_l.append(pg)\n rg_l.append(rg)\n p_l.append(p_new)\n r_l.append(r_new)\n toc = time.perf_counter()\n print(f'Stats time: {toc-tic:.2f}')\n df = df.append(\n {\n 'new_class': new_class, \n 'mod': 'multiply',\n 'filter': filter_index,\n 'value': magnitude,\n 'acc_on_all_classes': acc_on_whole_set,\n 'acc_on_new_class': acc_on_new_class,\n 'p_new': p_new,\n 'r_new': r_new,\n 'f1_new': f1_new\n },\n ignore_index=True\n )\n # print(acc_on_whole_set)\n # print(f'Precision on new class: {p_new}')\n # print(f'Recall on new class: {r_new}')\n # print(f'F1 on new class: {f1_new}')\n # print(f'Accuracy on new class: {acc_on_new_class}')\n # print(df)\n sorted_pr_l = sorted(zip(r_l, p_l))\n p_l = [x for _, x in sorted_pr_l]\n r_l = [y for y, _ in sorted_pr_l]\n\n sorted_prg_l = sorted(zip(rg_l, pg_l))\n pg_l = [x for _, x in sorted_prg_l]\n rg_l = [y for y, _ in sorted_prg_l]\n df_summary = df_summary.append(\n {\n 'new_class': new_class,\n 'filter': filter_index,\n 'aupg': prg.calc_auprg(\n {\n 'precision_gain': pg_l,\n 'recall_gain': rg_l\n }\n ),\n 'aupr': auc(r_l, p_l)\n },\n ignore_index=True\n )\n print('WRITE SUMMARY')\n df_summary.to_pickle(f\"./results.summary.{experiment_name}.pkl\")\n\n df.to_pickle(f\"./results.{experiment_name}.pkl\")\n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"utilitiesService/service/one_shot/oneshot_places365.py","file_name":"oneshot_places365.py","file_ext":"py","file_size_in_byte":18573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"531589946","text":"\"\"\"Dungeon World Type\"\"\"\n\nimport roguemoose.libtcodpy as libtcod\nfrom roguemoose.NaiveDungeon import NaiveDungeon\nfrom roguemoose.Tile import Tile\nfrom roguemoose.Player import Player\n\nclass Dungeon(object): #should extend a world object\n \"\"\"Holder for Dungeon Generation Types\"\"\"\n def __init__(self, **kwargs):\n self.width = kwargs.get('width', 100)\n self.height = kwargs.get('height', 100)\n\n self.map = [\n [\n Tile(blocked=True) for _ in range(self.height)\n ]\n for _ in range(self.width)\n ]\n\n self.entities = []\n\n self.player = Player(self)\n\n self.entities.append(self.player)\n\n self.generator = NaiveDungeon(self)\n self.generator.generate()\n self.generator.populate()\n\n self.player.set_position(*self.generator.start)\n\n def handle_input(self, key, mouse):\n \"\"\"Handle input for objects in dungeon\"\"\"\n for entity in self.entities:\n if entity.has_component('Input'):\n entity.Input.handle_key(key)\n entity.Input.handle_mouse(mouse)\n\n def draw(self, width, height):\n \"\"\"Draw the dungeon starting with the player\"\"\"\n window = libtcod.console_new(width, height)\n\n x_offset = self.player.Position.x_position - (width / 2)\n y_offset = self.player.Position.y_position - (height / 2)\n\n x_offset = min(max(0, x_offset), self.width - width)\n y_offset = min(max(0, y_offset), self.height - height)\n\n (x_position, y_position) = (\n self.player.Position.x_position,\n self.player.Position.y_position\n )\n\n self.explore_map((x_position, y_position))\n\n self.draw_map(window, (x_offset, y_offset), (width, height))\n\n self.draw_entities_from(\n window,\n (x_position, y_position),\n (x_offset, y_offset)\n )\n\n return window\n\n def draw_entities_from(self, window, position, offset):\n (x_position, y_position) = position\n (x_offset, y_offset) = offset\n for entity in self.entities:\n if (\n entity.has_component('Renderable')\n and entity.has_component('Position')\n ):\n if entity.Renderable.visible:\n libtcod.console_put_char(\n window,\n entity.Position.x_position - x_offset,\n entity.Position.y_position - y_offset,\n entity.Renderable.character,\n libtcod.BKGND_NONE\n )\n\n def draw_map(self, window, offset, dimensions):\n (width, height) = dimensions\n (x_offset, y_offset) = offset\n\n for y_position in range(y_offset, y_offset + height):\n for x_position in range(x_offset, x_offset + width):\n tile = self.map[x_position][y_position]\n if tile.explored:\n libtcod.console_set_char_background(\n window,\n x_position - x_offset, y_position - y_offset,\n tile.color,\n libtcod.BKGND_SET\n )\n\n def explore_map(self, position):\n (x_position, y_position) = position\n\n distance = 10\n\n for pos in range(-distance, distance):\n points = [\n (x_position + pos, y_position - distance),\n (x_position + pos, y_position + distance),\n (x_position + distance, y_position + pos),\n (x_position - distance, y_position + pos)\n ]\n\n for point in points:\n position_list = self.bresenham(position, point)\n\n for index in range(len(position_list)):\n (tile_x_position, tile_y_position) = position_list[index]\n\n tile = self.get_tile(tile_x_position, tile_y_position)\n if tile:\n tile.explored = True\n\n if tile.block_sight:\n break\n\n @staticmethod\n def bresenham(source, destination):\n (x_1, y_1) = source\n (x_2, y_2) = destination\n\n points = []\n is_steep = abs(y_2 - y_1) > abs(x_2 - x_1)\n\n if is_steep:\n x_1, y_1 = y_1, x_1\n x_2, y_2 = y_2, x_2\n\n is_reversed = False\n\n if x_1 > x_2:\n x_1, x_2 = x_2, x_1\n y_1, y_2 = y_2, y_1\n is_reversed = True\n\n delta_x = x_2 - x_1\n delta_y = abs(y_2 - y_1)\n\n error = int(delta_x / 2)\n\n y_result = y_1\n\n y_step = None\n\n if y_1 < y_2:\n y_step = 1\n else:\n y_step = -1\n\n for x_result in range(x_1, x_2 + 1):\n if is_steep:\n points.append((y_result, x_result))\n else:\n points.append((x_result, y_result))\n\n error -= delta_y\n\n if error < 0:\n y_result += y_step\n error += delta_x\n\n if is_reversed:\n points.reverse()\n\n return points\n\n def generate_lightmap(self):\n for entity in self.entities:\n if (\n entity.has_component(\"Position\") and\n entity.has_component(\"Light\")\n ):\n self.propogate_light(\n (entity.Position.x_position, entity.Position.y_position),\n entity.Light.color\n )\n\n def propogate_light(self, position, color):\n (x_position, y_position) = position\n\n distance = 1\n light_level = None\n\n light_level = self.attenuate_light(\n color,\n position,\n position\n )\n\n while light_level > 0:\n light_level = 0\n for pos in range(-distance, distance):\n points = [\n (x_position + pos, y_position - distance),\n (x_position + pos, y_position + distance),\n (x_position + distance, y_position + pos),\n (x_position - distance, y_position + pos)\n ]\n for point in points:\n light_level = max(light_level,\n self.attenuate_light(color, position, point)\n )\n distance += 1\n\n def attenuate_light(self, color, source, tile_position):\n (tile_x_position, tile_y_position) = tile_position\n\n tile = self.get_tile(tile_x_position, tile_y_position)\n\n attenuation = 3\n\n if tile:\n distance_squared = self.distance_squared(\n source, tile_position\n ) * attenuation\n\n light = libtcod.Color(\n max(0, color.r * (255 - distance_squared) / 255),\n max(0, color.g * (255 - distance_squared) / 255),\n max(0, color.b * (255 - distance_squared) / 255),\n )\n\n tile.illumination.r = max(tile.light_map.r, light.r)\n tile.illumination.g = max(tile.light_map.g, light.g)\n tile.illumination.b = max(tile.light_map.b, light.b)\n\n return max(light.r, light.g, light.b)\n else:\n return 0\n\n @staticmethod\n def distance_squared(source, destination):\n (x_1, y_1) = source\n (x_2, y_2) = destination\n\n x_size = max(x_1, x_2) - min(x_1, x_2)\n y_size = max(y_1, y_2) - min(y_1, y_2)\n\n return (x_size ** 2) + (y_size ** 2)\n\n def get_tile(self, x_position, y_position):\n if (\n x_position > 0 and\n x_position < self.width and\n y_position > 0 and\n y_position < self.height\n ):\n return self.map[x_position][y_position]\n\n def tile_open(self, x_position, y_position):\n if self.map[x_position][y_position].blocked:\n return False\n\n for entity in self.entities:\n if (\n entity.has_component(\"Position\") and\n entity.has_component(\"Fighter\") and\n entity.Position.x_position == x_position and\n entity.Position.y_position == y_position and\n entity.Fighter.blocks\n ):\n return False\n\n return True\n\n def tile_can_attack(self, x_position, y_position):\n for entity in self.entities:\n if(\n entity.has_component(\"Position\") and\n entity.has_component(\"Fighter\") and\n entity.Position.x_position == x_position and\n entity.Position.y_position == y_position and\n entity.Fighter.blocks\n ):\n return entity\n\n def update(self):\n \"\"\"Update the dungeon\"\"\"\n if self.player.moved:\n self.player.moved = False\n for entity in self.entities:\n entity.update()\n\n for entity in self.entities:\n if (entity.off_target()):\n other = self.tile_can_attack(entity.Position.x_target, entity.Position.y_target)\n\n if other:\n entity.Fighter.attack(other.Fighter)\n\n if self.tile_open(entity.Position.x_target, entity.Position.y_target):\n entity.Position.x_position = entity.Position.x_target\n entity.Position.y_position = entity.Position.y_target\n\n self.generate_lightmap()\n","sub_path":"roguemoose/Dungeon.py","file_name":"Dungeon.py","file_ext":"py","file_size_in_byte":9501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"468624321","text":"\"\"\"\nhttps://leetcode.com/problems/linked-list-cycle-ii/\nLC142 Linked List Cycle II\nMedium\n\nGiven a linked list, return the node where the cycle begins. If there is no cycle, return null.\n\nTo represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.\n\nNote: Do not modify the linked list.\n\"\"\"\n\nfrom typing import *\nfrom A01_ListNode import *\n\n\nclass Solution_A:\n\n def detectCycle(self, head: ListNode) -> ListNode:\n \"\"\"\n Time O(N), Space O(N), use set to search existing node\n ListNode instance is hashable, this method search at O(1), and will not break down the original linked list\n \"\"\"\n ss = set()\n while head:\n if head.next in ss:\n return head.next\n else:\n ss.add(head)\n head = head.next\n return None\n\n\nif __name__ == \"__main__\":\n # Use is instead of == to avoid max recursion when comparing cycling linked list\n testCase = Solution_A()\n\n L1 = genNode([3, 2, 0, 4])\n L1.next.next.next.next = L1.next\n # 3 2 0 4\n # a b c d\n # d->b\n assert testCase.detectCycle(L1) is L1.next, \"Example 1\"\n\n L2 = genNode([1, 2])\n L2.next.next = L2\n # 1 2\n # a b\n # b->a\n assert testCase.detectCycle(L2) is L2, \"Example 2\"\n\n L3 = genNode([1])\n assert not testCase.detectCycle(L3), \"Edge 1, no cycle\"\n\n print(\"All passed\")\n","sub_path":"LeetCode/LC142_linked_list_cycle_ii.py","file_name":"LC142_linked_list_cycle_ii.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"363079664","text":"from ListNode import ListNode\n\n\nclass OrderedList:\n def __init__(self):\n self.head = None\n\n def __str__(self):\n current = self.head\n printed_list = []\n\n if current is None:\n return str(printed_list)\n\n while current is not None:\n printed_list.append(current.get_data())\n current = current.get_next()\n\n return str(printed_list)\n\n def is_empty(self):\n return self.head is None\n\n def add(self, item):\n prev = None\n current = self.head\n found = False\n\n while current is not None and not found:\n if current.get_data() > item:\n found = True\n else:\n prev = current\n current = current.get_next()\n\n new_node = ListNode(item)\n if prev is None:\n new_node.set_next(current)\n self.head = new_node\n else:\n prev.set_next(new_node)\n new_node.set_next(current)\n\n def size(self):\n cnt = 0\n current_node = self.head\n\n while current_node is not None:\n cnt += 1\n current_node = current_node.get_next()\n\n return cnt\n\n def search(self, item):\n current_node = self.head\n found = False\n stop = False\n\n while current_node is not None and not found and not stop:\n if current_node.get_data() > item:\n stop = True\n\n if current_node.get_data() == item:\n found = True\n\n if current_node.get_data() < item:\n current_node = current_node.get_next()\n\n return found\n\n def remove_item(self, item):\n previous = None\n current = self.head\n found = False\n\n while current is not None and not found:\n if current.get_data() == item:\n found = True\n else:\n previous = current\n current = current.get_next()\n\n if previous is None:\n self.head = current.get_next()\n else:\n previous.set_next(current.get_next())\n\n def index(self, item):\n cnt = -1\n current = self.head\n found = False\n\n while current is not None and not found:\n cnt += 1\n\n if current.get_data() == item:\n found = True\n else:\n current = current.get_next()\n\n return cnt\n\n def pop(self, index=None):\n current = self.head\n previous = current.get_next()\n found = False\n cnt = 0\n\n while current.get_next() is not None and not found:\n if index is not None:\n cnt += 1\n\n if index == cnt:\n found = True\n\n previous = current\n current = current.get_next()\n\n if current.get_next() is None:\n previous.set_next(None)\n else:\n previous.set_next(current.get_next())\n\n return current\n\nmy_list = OrderedList()\nprint(my_list)\nprint(my_list.head)\nmy_list.add(6)\n\nmy_list.add(31)\nprint(my_list)\n\nmy_list.add(17)\nmy_list.add(77)\nmy_list.add(93)\nmy_list.add(26)\nmy_list.add(54)\nprint(my_list)\nprint('Should be 7', my_list.size())\n\nprint('Should be True', my_list.search(17))\nprint('Should be False', my_list.search(18))\n","sub_path":"linear-structs/OrderedList.py","file_name":"OrderedList.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"401143855","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 28 08:46:13 2020\n\n@author: Acr\n\"\"\"\nfrom pynput import mouse\nimport threading\nfrom time import sleep\n\ndef on_click(x, y, button, pressed):\n \n if button == mouse.Button.right: \n print('{} at {}'.format('Pressed Right Click' if pressed else 'Released Right Click', (x, y)))\n\ndef printit():\n threading.Timer(1.0, printit).start()\n #print (\"Hello, World!\")\n \n listener = mouse.Listener(on_click=on_click)\n\n listener.start()\n listener.join()\n\nprintit()\n","sub_path":"robot/detect_xy.py","file_name":"detect_xy.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"403858323","text":"\"\"\"\r\nAuthors: Kovid, Tharun, Vishal, Anh, Dhriti, Rinku\r\nLast Edited By: Kovid\r\nLast Edited On: 9/22/2019\r\nClass Description: Class to Extract Features from images\r\n\"\"\"\r\n# Import statements\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nimport glob\r\nimport numpy as np\r\nfrom scipy.stats import skew\r\nfrom PostgresDB import PostgresDB\r\nimport tqdm\r\nimport os\r\nimport cv2\r\nfrom skimage import feature\r\nfrom skimage.transform import downscale_local_mean\r\nfrom scipy.linalg import svd\r\nfrom scipy.sparse.linalg import svds\r\n# import time\r\nimport math\r\nimport joblib\r\n\r\n# Task 3 4 5\r\nimport csv\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nimport os\r\n\r\nDATABASE_NAME = 'mwdb'\r\nTABLE_NAME = 'images_demo'\r\nPASSWORD = \"password\"\r\n# dirpath='/home/anhnguyen/ASU/CSE-515/Project/Phase 1/Project - Phase 2/Data/testset1/'\r\n# ext='*.jpg'\r\ncsvFile = \"HandInfo.csv\"\r\n\r\n\r\n\r\n\r\nclass imageProcess:\r\n def __init__(self, dirpath, ext='*.jpg'):\r\n self.dirpath = dirpath\r\n self.ext = ext\r\n\r\n # Method to fetch images as pixels\r\n def fetchImagesAsPix(self, filename):\r\n image = cv2.imread(filename)\r\n size = image.shape\r\n img_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)\r\n return img_yuv, size\r\n\r\n # Method to calculate the moments\r\n def calMommets(self, calc):\r\n calc = np.array([x for y in calc for x in y])\r\n mean = np.mean(calc, axis=0)\r\n sd = np.std(calc, axis=0)\r\n skw = skew(calc, axis=0)\r\n mom = [mean.tolist(), sd.tolist(), skw.tolist()]\r\n mom = [x for y in mom for x in y]\r\n return mom\r\n\r\n # Method to split image into 100*100 blocks\r\n def imageMoments(self, image, size, x=100, y=100):\r\n momments = []\r\n for idx1 in range(0, size[0], x):\r\n for idx2 in range(0, size[1], y):\r\n window = image[idx1:idx1 + x, idx2:idx2 + y]\r\n momments.append(self.calMommets(window.tolist()))\r\n return momments\r\n\r\n # Function to calculate the N SIFT feature vectors for each image\r\n def sift_features(self, filepath):\r\n img = cv2.imread(filepath)\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n kp, des = sift.detectAndCompute(gray, None)\r\n return des\r\n\r\n # Function to Calculate the HOG of an image\r\n def hog_process(self, filename):\r\n image = cv2.imread(filename)\r\n img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n dsimg = downscale_local_mean(img, (10, 10))\r\n (H, hogImage) = feature.hog(dsimg, orientations=9, pixels_per_cell=(8, 8),\r\n cells_per_block=(2, 2), block_norm=\"L2-Hys\",\r\n visualize=True)\r\n return H\r\n\r\n # Function to calculate the local binary pattern of the window\r\n def calculate_lbp(self, curr_window):\r\n eps = 1e-7\r\n hist = []\r\n # Initializing LBP settings - radius and number of points\r\n radius = 3\r\n num_of_points = 8 * radius\r\n # Checking for uniform patterns\r\n window_lbp = feature.local_binary_pattern(curr_window, num_of_points, radius, method='uniform')\r\n # Generating the histogram\r\n (histogram, temp) = np.histogram(window_lbp.ravel(),\r\n bins=np.arange(0, num_of_points + 3),\r\n range=(0, num_of_points + 2))\r\n # Typecasting histogram type to float\r\n histogram = histogram.astype('float')\r\n # Normalizing the histogram such that sum = 1\r\n histogram /= (histogram.sum() + eps)\r\n hist.append(histogram)\r\n return hist\r\n\r\n # Function to pre-process images into grayscale and form windows of 100X100 to be fed to calculate_lbp\r\n def lbp_preprocess(self, filename):\r\n local_binary_pattern = []\r\n # Converting the BGR image to Grayscale\r\n img = cv2.imread(filename)\r\n gray = cv2.cvtColor(img, cv2.cv2.COLOR_BGR2GRAY)\r\n for i in range(0, gray.shape[0], 100):\r\n j = 0\r\n while j < gray.shape[1]:\r\n current_window = gray[i:i + 99, j:j + 99]\r\n temp_lbp = self.calculate_lbp(current_window)\r\n local_binary_pattern.extend(temp_lbp)\r\n j = j + 100\r\n\r\n local_binary_pattern = [x for y in local_binary_pattern for x in y]\r\n local_binary_pattern = np.asarray(local_binary_pattern, dtype=float).tolist()\r\n\r\n return local_binary_pattern\r\n\r\n \"\"\"\r\n Method to Save feature data to Postgres Database\r\n 1. Sift: imagedata_s(imageid, data)\r\n 2. Moments: imagedata_m(imageid, data)\r\n 3. Hog: imagedata_h(imageid, data)\r\n 4. LBP: imagedata_l(imageid, data) \r\n \"\"\"\r\n def dbSave(self, conn, model):\r\n # Count the number of files in the directory\r\n filecnt = len(glob.glob(self.dirpath + self.ext))\r\n pbar = tqdm.tqdm(total=filecnt)\r\n # Read images from the directory\r\n for filename in glob.glob(self.dirpath + self.ext):\r\n if model == 'm':\r\n pixels, size = self.fetchImagesAsPix(filename)\r\n momments = self.imageMoments(pixels, size)\r\n # Convert to string to insert into DB as an array\r\n values_st = str(np.asarray(momments).tolist())\r\n # values_st = str(momments).replace('[', '{')\r\n # values_st = values_st.replace(']', '}')\r\n dbname = 'imagedata_m'\r\n elif model == 's':\r\n des = self.sift_features(filename)\r\n values_st = str(np.asarray(des).tolist())\r\n # values_st = str(des.tolist()).replace('[', '{')\r\n # values_st = values_st.replace(']', '}')\r\n dbname = 'imagedata_s'\r\n elif model == 'h':\r\n h_val = self.hog_process(filename)\r\n values_st = str(np.asarray(h_val).tolist())\r\n # values_st = str(h_val.tolist()).replace('[', '{')\r\n # values_st = values_st.replace(']', '}')\r\n dbname = 'imagedata_h'\r\n elif model == 'l':\r\n lbp_val = self.lbp_preprocess(filename)\r\n values_st = str(np.asarray(lbp_val).tolist())\r\n # values_st = str(lbp_val.tolist()).replace('[', '{')\r\n # values_st = values_st.replace(']', '}')\r\n dbname = 'imagedata_l'\r\n else:\r\n print('Incorrect value for Model provided')\r\n exit()\r\n sql = \"CREATE TABLE IF NOT EXISTS {db} (imageid TEXT NOT NULL, imagedata TEXT, PRIMARY KEY (imageid))\".format(db=dbname)\r\n cur = conn.cursor()\r\n cur.execute(sql)\r\n name = os.path.basename(filename)\r\n name = os.path.splitext(name)[0]\r\n # create a cursor\r\n sql = \"SELECT {field} FROM {db} WHERE {field} = '{condition}';\".format(field=\"imageid\",db=dbname,condition=name)\r\n # print(\"SQL Check Exist - HOG: \", sql)\r\n cur.execute(sql)\r\n\r\n # cur.execute(sql)\r\n if cur.fetchone() is None:\r\n print(\"Insert\")\r\n # print(\"Not Exist HOG - Insert\")\r\n sql = \"INSERT INTO {db} VALUES('{x}', '{y}');\".format(x=name,y=values_st, db=dbname)\r\n else:\r\n print(\"Update\")\r\n # print(\"Exist HOG - Update\")\r\n # column = \"HOG\"\r\n \r\n sql = \"UPDATE {db} SET imagedata ='{y}' WHERE IMAGEID = '{id}'\".format(y=values_st, db=dbname, id=name)\r\n \r\n cur.execute(sql)\r\n conn.commit()\r\n # close cursor\r\n cur.close()\r\n pbar.update(1)\r\n\r\n # Method to fetch data from Database\r\n def dbFetch(self, conn, dbname, condition = \"\"):\r\n # Create cursor\r\n cur = conn.cursor()\r\n # if model == 's':\r\n # dbname = 'imagedata_sift'\r\n # elif model == 'm':\r\n # dbname = 'imagedata_moments'\r\n # elif model == 'h':\r\n # dbname = 'imagedata_hog'\r\n # elif model == 'l':\r\n # dbname = 'imagedata_lbp'\r\n # dbname = 'imagedata_' + model\r\n # if condition:\r\n # dbname += \"_\" + technique\r\n sql = \"SELECT * FROM {db} {condition}\".format(db=dbname, condition=condition)\r\n # print (sql)\r\n # print(\"before\")\r\n cur.execute(sql)\r\n # print(\"here\")\r\n recs = cur.fetchall()\r\n return recs\r\n\r\n # Method to access the database\r\n def dbProcess(self, password, process='s', model='s', host='localhost',\r\n database='mwdb', user='postgres', port=5432, dbase = 'imagedata_l'):\r\n # Connect to the database\r\n db = PostgresDB(password=PASSWORD, host=host,\r\n database=DATABASE_NAME, user=user, port=port)\r\n conn = db.connect()\r\n if process == 's':\r\n self.dbSave(conn, model)\r\n print('Data saved successfully to the Database!')\r\n elif process == 'f':\r\n recs = self.dbFetch(conn,dbase)\r\n recs_flt = []\r\n # Flatten the data structure and \r\n for rec in recs:\r\n recs_flt.append((rec[0],np.asarray(eval(rec[1]))))\r\n # if model == 'm':\r\n # print(recs)\r\n # for rec in recs:\r\n # recs_flt.append(np.asarray(eval(rec[1])))\r\n # recs_flt.append((rec[0], [float(x) for y in rec[1] for x in y]))\r\n # elif model == 's':\r\n # for rec in recs:\r\n # recs_flt.append((rec[0], [[float(x) for x in y] for y in rec[1]]))\r\n # elif model == 'l' or model == 'h':\r\n # for rec in recs:\r\n # recs_flt.append((rec[0], [float(x) for x in rec[1]]))\r\n return recs_flt\r\n\r\n # Method to calculate the Cosine Similarity\r\n def cosine_sim(self, vec1, vec2):\r\n dot_product = np.dot(vec1, vec2)\r\n norm_a = np.linalg.norm(vec1)\r\n norm_b = np.linalg.norm(vec2)\r\n cos = 1 - dot_product / (norm_a * norm_b)\r\n return cos\r\n # return 1 - spatial.distance.cosine(vec1, vec2)\r\n\r\n # method to calculate Manhattan distance\r\n def man_dist(self, vec1, vec2):\r\n dist = [abs(x - y) for x,y in zip(vec1, vec2)]\r\n return sum(dist)\r\n\r\n # Calculate the L2 distance\r\n def l2Dist(self, d1, d2):\r\n d1 = np.array(d1, dtype=np.float32)\r\n d2 = np.array(d2, dtype=np.float32)\r\n dist = cv2.norm(d1, d2, cv2.NORM_L2)\r\n return dist\r\n\r\n # Calculate the Euclidean distance\r\n def euclidean_distance(self, imageA, imageB):\r\n # d=math.sqrt(np.sum([((a-b) ** 2) for (a,b) in zip(imageA,imageB)]))\r\n # return d\r\n return np.sqrt(np.sum((imageA - imageB) ** 2, axis=0))\r\n\r\n # Calculate the vector matches\r\n def knnMatch(self, d1, d2, k=2):\r\n distances = []\r\n for d in d1:\r\n dis = sorted([self.l2Dist(d, x) for x in d2])\r\n distances.append(dis[0:k])\r\n return distances\r\n\r\n # Method to calculate Similarity for SIFT vectors\r\n def sift_sim(self, d1, d2):\r\n matches = self.knnMatch(d1, d2, k=2)\r\n good = []\r\n all = []\r\n d1 = np.array(d1, dtype=np.float32)\r\n for m, n in matches:\r\n all.append(m)\r\n if m < 0.8 * n:\r\n good.append(m)\r\n return len(good) / d1.shape[0]\r\n\r\n # Method to calculate Similarity\r\n def SimCalc(self, img, recs, imgmodel='m', k=5):\r\n # Calculate the Similarity matrix for Moments model\r\n rec_dict = dict((x, y) for x, y in recs)\r\n img_vec = rec_dict[img]\r\n if imgmodel == 'm':\r\n sim_matrix = sorted([(rec[0], self.cosine_sim(img_vec, rec[1])) for rec in recs\r\n if rec[0] != img], key=lambda x: x[1])\r\n if imgmodel == 's':\r\n sim_matrix = sorted([(rec[0], self.sift_sim(img_vec, rec[1])) for rec in recs\r\n if rec[0] != img], key=lambda x: x[1], reverse=True)\r\n return sim_matrix[0:k]\r\n\r\n\r\n def queryImageNotLabel(self, image_data, feature, technique, label):\r\n print(\"Not Same Label\")\r\n # cursor.execute(\"SELECT * FROM imagedata_{0}_{1} WHERE imageid = '{2}'\".format(feature,technique,image))\r\n # image_data = cursor.fetchall()\r\n # print(image_data)\r\n image_data = np.asarray(eval(image_data[0][1]))\r\n path = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep + 'Models' +os.sep)\r\n\r\n model = joblib.load(path + os.sep + \"{0}_{1}_{2}.joblib\".format(feature, technique, label))\r\n latent = np.asarray(model.components_)\r\n \r\n if feature == 's':\r\n kmeans = joblib.load(path + os.sep + 'kmeans_{0}_{1}.joblib'.format(latent.shape[1], label))\r\n histo = np.zeros(latent.shape[1])\r\n nkp = np.size(image_data)\r\n for d in image_data:\r\n idx = kmeans.predict([d])\r\n histo[idx] += 1/nkp\r\n print(np.asarray((model.components_)).shape)\r\n image_data = np.asarray(histo).dot(latent.T)\r\n return image_data\r\n \r\n def similarity (self, feature, technique, dbase, k, image, label = \"\"):\r\n db = PostgresDB(password = \"mynhandepg\", database = \"mwdb\")\r\n conn = db.connect()\r\n if conn is None:\r\n print(\"Can not connect to database\")\r\n exit()\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT * FROM \" + dbase)\r\n data = cursor.fetchall()\r\n image_id = [rec[0] for rec in data]\r\n similarity = {}\r\n if image in image_id:\r\n image_index = image_id.index(image)\r\n print(image_index)\r\n image_data = np.asarray(eval(data[image_index][1]))\r\n else:\r\n print(\"Not Same Label\")\r\n dbase = 'imagedata_' + feature\r\n label = label.replace(\" \", \"_\")\r\n image_data = self.dbFetch(conn,dbase, \"WHERE imageid = '{0}'\".format(image))\r\n image_data = self.queryImageNotLabel(image_data, feature, technique, label)\r\n similarity[image] = self.euclidean_distance(image_data,image_data)\r\n \r\n # print (image_id)\r\n for i in range(len(image_id)):\r\n image_cmp = np.asarray(eval(data[i][1]))\r\n # if self.metrics:\r\n # # similarity[row[0]] = 1- self.cosine_similarity(image, result)\r\n # similarity[image_id[i]] = 1 - st.pearsonr(image,image_cmp)[0]\r\n # # similarity[row[0]] = mean_squared_error(image,result)\r\n # # similarity[row[0]] = 0 - self.psnr(image,result)\r\n # else:\r\n similarity[image_id[i]] = self.euclidean_distance(image_data,image_cmp)\r\n similarity = sorted(similarity.items(), key = lambda x : x[1], reverse=False)\r\n print(similarity)\r\n self.dispImages(similarity,feature, technique, 11, k)\r\n\r\n # Method to display images\r\n def dispImages(self, similarity, feature, technique, no_images, k):\r\n columns = 4\r\n rows = no_images // columns\r\n if no_images % columns != 0:\r\n rows += 1\r\n ax = []\r\n fig=plt.figure(figsize=(30, 20))\r\n fig.canvas.set_window_title('Task 3 - Images Similarity')\r\n fig.suptitle(str(no_images - 1) + ' Similar Images of ' + similarity[0][0] + ' based on ' + feature + \", \"+ str(k) + \" latent semantics and \" + technique)\r\n # plt.title(str(no_images - 1) + ' Similar Images of ' + similarity[0][0] + ' based on ' + type,y=-0.01)\r\n plt.axis('off')\r\n # fig.title(str(k) + 'Similar Images of ' + similarity[0][0] + ' based on ' + type)\r\n f= open(\"../Outputs/task3_result.txt\",\"w+\")\r\n f.write(\"Task 2 - Matching Score \" + str(no_images) + \" images with \" + similarity[0][0] + ' based on ' + feature + \", \"+ str(k) + \" latent semantics and \" + technique + \":\\n\")\r\n for i in range(no_images):\r\n f.write(similarity[i][0] + \": \" + str(similarity[i][1]) + \"\\n\")\r\n img = mpimg.imread(self.dirpath + self.ext.replace('*', similarity[i][0]))\r\n # create subplot and append to ax\r\n ax.append( fig.add_subplot(rows, columns, i+1))\r\n if i == 0:\r\n ax[-1].set_title(\"Given Image: \" +similarity[i][0] ) # set title\r\n else:\r\n ax[-1].set_title(\"Image \"+str(i) + \": \" +similarity[i][0] ) # set title\r\n ax[-1].axis('off')\r\n plt.imshow(img)\r\n plt.savefig('../Outputs/task3_result.png')\r\n f.close()\r\n plt.show()\r\n plt.close()\r\n\r\n # Method to write to a file\r\n def writeFile(self, content, path):\r\n with open(path, 'w+') as file:\r\n file.write(str(content))\r\n\r\n # Convert list to string\r\n def list2string(self, lst):\r\n values_st = str(lst).replace('[[', '(')\r\n values_st = values_st.replace('[', '(')\r\n values_st = values_st.replace(']]', ']')\r\n values_st = values_st.replace(']', ')')\r\n return values_st\r\n \r\n def createInsertMeta(self, conn):\r\n # Read the metadata file\r\n metafile = self.readMetaData()\r\n # Create cursor\r\n cur = conn.cursor()\r\n # Create the meta table\r\n sqlc = \"CREATE TABLE IF NOT EXISTS \" \\\r\n \"img_meta(subjectid TEXT, image_id TEXT, gender TEXT, aspect TEXT, orient TEXT, accessories TEXT)\"\r\n cur.execute(sqlc)\r\n conn.commit()\r\n # Insert the meta data into the database table\r\n values_st = self.list2string(metafile)\r\n sqli = \"INSERT INTO img_meta VALUES {x}\".format(x=values_st)\r\n cur.execute(sqli)\r\n conn.commit()\r\n print('Meta Data saved into Database!')\r\n cur.close()\r\n \r\n \r\n def readMetaData(self):\r\n with open(self.dirpath + csvFile, 'r') as file:\r\n csv_reader = csv.reader(file)\r\n meta_file = []\r\n for idx, row in enumerate(csv_reader):\r\n if idx == 0:\r\n continue\r\n sub_id = row[0]\r\n id = row[7].split('.')[0]\r\n gender = row[2]\r\n orientation = row[6].split(' ')\r\n accessories = row[4]\r\n meta_file.append([sub_id, id, gender, orientation[0], orientation[1], accessories])\r\n return meta_file\r\n\r\n def CSV(self, label = \"\"):\r\n label = label.lower()\r\n if label in (\"dorsal\", \"palmar\", \"left\", \"right\"):\r\n index = \"aspectOfHand\"\r\n elif label in (\"male\", \"female\"):\r\n index = \"gender\"\r\n elif label in (\"with accessories\", \"without accessories\"):\r\n index = \"accessories\"\r\n else:\r\n index = \"\"\r\n\r\n with open(self.dirpath + csvFile, 'r', newline='') as f:\r\n reader = csv.reader(f, delimiter=',')\r\n # next(cr) gets the header row (row[0])\r\n header = next(reader)\r\n i = header.index(index)\r\n id = header.index(\"imageName\")\r\n # print(i,index)\r\n # list comprehension through remaining cr iterables\r\n if index in (\"aspectOfHand\", \"gender\"):\r\n filteredImage = [row[id][:len(row[id]) - 4] for row in reader if row[i].find(label) != -1]\r\n elif label == \"with accessories\":\r\n filteredImage = [row[id][:len(row[id]) - 4] for row in reader if int(row[i]) == 0]\r\n elif label == \"without accessories\":\r\n filteredImage = [row[id][:len(row[id]) - 4] for row in reader if int(row[i]) == 1]\r\n # else:\r\n # return data, header\r\n # print (filteredImage)\r\n return filteredImage\r\n\r\n # def plotImage(self, data, path):\r\n # for i,k in enumerate(data):\r\n # print(i, k[0])\r\n # # break\r\n\r\n\r\n\r\ndef cosine_similarity(imageA, imageB):\r\n # print(imageA)\r\n # print(imageB)\r\n return np.dot(imageA, imageB)/(np.sqrt(np.sum(imageA ** 2, axis=0))*np.sqrt(np.sum(imageB ** 2, axis=0)))\r\n\r\n","sub_path":"imageProcess.py","file_name":"imageProcess.py","file_ext":"py","file_size_in_byte":20282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"413329143","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# pylint: disable=missing-docstring, line-too-long, bare-except, invalid-name\n\nimport re\nimport locale\n\nimport sys\nimport getopt\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util import Retry\n\nimport pywikibot\nfrom pywikibot import pagegenerators as pg\n\n\ndef requests_retry_session(\n retries=5,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n session=None,\n):\n session = session or requests.Session()\n retry = Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist,\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n\nwikidata_site = pywikibot.Site('wikidata', 'wikidata')\nrepo = wikidata_site.data_repository()\n\ndiocese = False\ndioid = False\nposition = False\n\n\ndef create_claim_pit(year):\n cal_model = None\n if year < 1584:\n cal_model = 'http://www.wikidata.org/entity/Q1985786'\n\n my_wbtime = pywikibot.WbTime(year=year,\n month=1, day=1,\n precision=9, before=0, after=0,\n timezone=0, calendarmodel=cal_model)\n\n claim = pywikibot.Claim(repo, 'P585')\n claim.setTarget(my_wbtime)\n return claim\n\n\ndef main(argv):\n opts, args = getopt.getopt(argv, \"hd:i:\", [\"diocese=\", 'id='])\n ret = {}\n for opt, arg in opts:\n if opt == '-h':\n print('check_bishopstart_on_chorg.py -d -i ')\n sys.exit()\n elif opt in (\"-d\", \"--diocese\"):\n diocese = arg\n if diocese.isnumeric():\n diocese = 'Q' + diocese\n ret['diocese'] = diocese\n elif opt in (\"-i\", \"--id\"):\n dioid = arg\n ret['dioid'] = dioid\n return ret\n\n\nif __name__ == \"__main__\":\n mainret = main(sys.argv[1:])\n if 'diocese' in mainret:\n diocese = mainret['diocese']\n if 'dioid' in mainret:\n dioid = mainret['dioid']\n\n\nif diocese == False and dioid == False:\n print('!! NO DIOCESE GIVEN. I quit.')\n\nitemdetails = False\ntarget_page = False\n\nif diocese:\n target_page = pywikibot.ItemPage(repo, diocese)\n itemdetails = target_page.get(get_redirect=True)\n list_currentdioids = itemdetails['claims']['P1866']\n if len(list_currentdioids) == 1:\n diocese = target_page.id\n print('-- Diocese found: https://www.wikidata.org/wiki/{}'.format(diocese))\n dioid = list_currentdioids[0].getTarget()\n else:\n print('! Length of P1866 (Claim for Catholic Hierarchy diocese ID) !=1')\n exit()\nelif not diocese and dioid:\n SPARQL = \"SELECT ?item WHERE { ?item wdt:P1866 \\\"\" + dioid + \"\\\". }\"\n my_generator = pg.WikidataSPARQLPageGenerator(SPARQL, site=wikidata_site)\n my_generator = list(my_generator)\n if len(my_generator) != 1:\n print('!!!- Found {} Results for DioId=\"' + dioid + '\" that works only with an exact match.'.format(len(my_generator)))\n exit()\n else:\n target_page = my_generator[0]\n itemdetails = target_page.get(get_redirect=True)\n list_currentdioids = itemdetails['claims']['P1866']\n if len(list_currentdioids) == 1:\n diocese = target_page.id\n print('-- Diocese found: https://www.wikidata.org/wiki/{}'.format(diocese))\n else:\n print('! Length of P1866 (Claim for Catholic Hierarchy diocese ID) !=1')\n\nchorgurl = 'http://www.catholic-hierarchy.org/diocese/d' + dioid + '.html'\n\n\ntry:\n r = requests_retry_session().get(chorgurl)\nexcept:\n print('!!! Could not request url:' + chorgurl)\n exit()\n\nif r.status_code != 200:\n print('### ERROR ON http-call for : ' + chorgurl)\nif r.status_code == 200:\n print('>> Catholic-Hierarchy-DioId: ' + dioid)\n print('-- URL: ' + chorgurl)\n\n\nbytes_regex = str.encode('

Statistics<\\/a><\\/h2>

\\n()')\nstat_table = re.findall(bytes_regex, r.content)\n\nif stat_table:\n print('--- Stat-Table found.')\nelse:\n print('!!- Stat-Table not found.')\n exit()\n\nif not itemdetails:\n print('!!- Could not load WD-Item')\n exit()\n\nbytes_regex = str.encode('(.*<\\/th>)<\\/tr>')\nstat_html_headlines = re.findall(bytes_regex, stat_table[0])\n\nif not stat_html_headlines:\n print('!!- No Headlines found')\n exit()\n\n\nbytes_regex = str.encode('([\\w ]+)<\\/th>')\nlist_headlines = re.findall(bytes_regex, stat_html_headlines[0])\n\nif not list_headlines:\n print('!!- No Plaintext Headlines found')\n exit()\n\n# print(list_headlines)\n\nyearpos = False\nmemberpos = False\n\n\ntry:\n yearpos = list_headlines.index(str.encode('Year'))\nexcept:\n print('!-- Year-Column not found')\n exit()\n\ntry:\n memberpos = list_headlines.index(str.encode('Catholics'))\nexcept:\n print('!-- Catholics-Column not found')\n exit()\n\nbytes_regex = str.encode(']*>(.*)<\\/tr>')\nstat_html_rows = re.findall(bytes_regex, stat_table[0])\n\na_yearstat_ch = {}\n\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\nfor html_row in stat_html_rows:\n bytes_regex = str.encode('.*<\\/th>')\n stat_th_in = re.findall(bytes_regex, html_row)\n if stat_th_in:\n continue\n\n bytes_regex = str.encode('([^<]*)')\n td_in = re.findall(bytes_regex, html_row)\n if not len(td_in) == len(list_headlines):\n continue\n\n try:\n my_year = int(td_in[yearpos])\n my_members = int(locale.atoi(td_in[memberpos].decode('utf-8')))\n if my_members == 0:\n continue\n a_yearstat_ch[str(my_year)] = my_members\n except:\n continue\n\n\ntry:\n known_stats = itemdetails['claims']['P2124']\nexcept KeyError:\n known_stats = []\n\n\na_yearstat_wd = {}\nfor known_stat in known_stats:\n trgt_number = known_stat.getTarget()\n print(trgt_number)\n a_qualis = known_stat.qualifiers\n if 'P585' not in a_qualis:\n print('-- Point in time unknown. I skip that one')\n continue\n\n my_year = a_qualis['P585'][0].getTarget().year\n my_members = trgt_number.amount\n a_yearstat_wd[str(my_year)] = int(my_members)\n\na_todo_stat = {}\n\nfor key in a_yearstat_ch.keys():\n if key not in a_yearstat_wd:\n a_todo_stat[key] = a_yearstat_ch[key]\n\n\nfor key in a_todo_stat:\n claim_membernumber = pywikibot.Claim(repo, 'P2124')\n amount_membernumber = pywikibot.WbQuantity(a_todo_stat[key], site=wikidata_site)\n claim_membernumber.setTarget(amount_membernumber)\n quali_pit = create_claim_pit(int(key))\n claim_membernumber.addQualifier(quali_pit)\n\n source_claim = pywikibot.Claim(repo, 'P1866')\n source_claim.setTarget(dioid)\n claim_membernumber.addSources([source_claim])\n target_page.addClaim(claim_membernumber, summary='added member amount')\n\nprint('Done!')\n","sub_path":"set_memberstats.py","file_name":"set_memberstats.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"59947457","text":"import Zero\nimport Events\nimport Property\nimport VectorMath\nimport Action\nimport random\n\nVec3 = VectorMath.Vec3\nVec2 = VectorMath.Vec2\n\nclass MainMenu:\n DebugMode = Property.Bool(default=False)\n TestButton = None\n StartGame = None\n Options = None\n Credits = None\n \n selection = []\n selectID = 0\n menuPoint = None\n menuPointerShift = Vec2(-3.5, 0)\n Timer = 0\n \n def Initialize(self, initializer):\n Zero.Connect(self.Space, Events.LevelStarted, self.onLevelStart)\n Zero.Connect(self.Space, \"myGamepadEvent\", self.onButtonDown)\n Zero.Connect(self.Space, Events.LogicUpdate, self.onUpdate)\n \n #self.selection = []\n #self.menuPoint = self.Space.CreateAtPosition(\"MenuPointer\", self.menuPointerShift + self.selection[0].Transform.Translation)\n \n def onButtonDown(self, Event):\n if(Event.Button == Zero.Buttons.DpadLeft):\n self.selectID -= 1\n \n if self.selectID < 0:\n self.selectID = 0\n else:\n self.Owner.SoundEmitter.Play()\n \n self.updateCursor()\n #endif\n if(Event.Button == Zero.Buttons.DpadRight):\n self.selectID += 1\n \n if self.selectID > len(self.selection)-1:\n self.selectID = len(self.selection)-1\n else:\n self.Owner.SoundEmitter.Play()\n \n self.updateCursor()\n #endif\n if(Event.Button == Zero.Buttons.A or Event.Button == Zero.Buttons.Start):\n #self.selection[self.selectID].SpriteText.Text = \"DURR\"\n self.selection[self.selectID].ButtonLogic.Do()\n if(Event.Button == Zero.Buttons.B):\n #self.selection[self.selectID].SpriteText.Text = \"NURR\"\n pass\n \n def onLevelStart(self, Event):\n print(\"onlevelstart\")\n self.selection = []\n self.selectID = 0\n \n self.selection.append(self.Space.FindObjectByName(\"TestButton\"))\n self.selection.append(self.Space.FindObjectByName(\"TestButton2\"))\n #self.selection.append(self.Space.FindObjectByName(\"TestButton3\"))\n #self.selection.append(self.Space.FindObjectByName(\"TestButton4\"))\n \n self.menuPoint = self.Space.CreateAtPosition(\"MenuPointer\", self.menuPointerShift + self.selection[0].Transform.Translation)\n #self.menuPoint = self.Space.Create(\"MenuPointer\")\n self.menuPoint.Sprite.Visible = True\n \n def setCursorPosition(self, pos):\n seq = Action.Sequence(self.menuPoint)\n me = self.menuPoint.Transform\n Action.Property(seq, me, property=\"Translation\",end=pos,duration=0.5,ease=Action.Ease.Linear)\n #self.menuPoint.Transform.Translation = pos\n \n def updateCursor(self):\n if self.DebugMode:\n print(self.selectID)\n self.setCursorPosition(self.menuPointerShift + self.selection[self.selectID].Transform.Translation)\n \n def onUpdate(self, Event):\n self.Timer += Event.Dt\n \n if self.Timer > 0.1:\n self.Timer = 0\n return\n \n if(self.Owner.Sprinkler):\n #watervel = Vec3( 2*random.uniform(-0.5, 0.5), 0.8, 0 )\n random.seed(self.Space.TimeSpace.CurrentTime)\n \n watervel = self.menuPoint.Transform.Translation - self.Owner.Transform.Translation\n watervel *= 0.5\n self.Owner.Sprinkler.ShootStick(watervel.normalized())\n \n watervel = Vec3(random.uniform(-1.0, 2.0), 1.5, 0 )\n self.Owner.Sprinkler.shootUnlimited(watervel)\n\nZero.RegisterComponent(\"MainMenu\", MainMenu)","sub_path":"Spritz/Content/MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"294131576","text":"import sys\n\nimport pytest\n\n\ndef test_ipython(testdir):\n \"\"\"Test integration when used with IPython.\n\n - `up` used to crash due to conflicting `hidden_frames` attribute/method.\n \"\"\"\n pytest.importorskip(\"IPython\")\n child = testdir.spawn(\n \"{} -m IPython --colors=nocolor --simple-prompt\".format(\n sys.executable,\n )\n )\n child.sendline(\"%debug raise ValueError('my_value_error')\")\n child.sendline(\"up\")\n child.expect_exact(\"\\r\\nipdb> \")\n child.sendline(\"c\")\n child.expect_exact(\"\\r\\nValueError: my_value_error\\r\\n\")\n child.expect_exact(\"\\r\\nIn [2]: \")\n child.sendeof()\n child.sendline(\"y\")\n assert child.wait() == 0\n","sub_path":"testing/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"309328971","text":"'''\nThis script simulates one risk combat between one\nattacker and one defender. It conducts 100k simulated\ncombats to compute probability of attacker wining\nand the estimated number of armies remaining for each side\nafter combat.\n\n=== Risk RULES ===\nAttacker Dice = min(Armies - 1, 3\nDefender Dice = min(Armies, 2)\n\n1. Sort each set of dice from low to high and pair between Attacker / Defender\n2. Compare each die roll to it's opponents pair.\n3. Defender wins if it's Dice roll is equal or greater than attacker roll\n4. Subtract armies from each side based on how many die rolls won / lost\n\n=== USAGE ===\npython odds.py attacker_armies defender_armies\n\n\n=== EXAMPLE ===\npython odds.py 8 3\nOdds: 91.0% Attacker Rem: 5.7 Defender Rem: 0.2\n'''\n\nimport random\n\n\ndef do_roll(a, d):\n a = min(a - 1, 3)\n d = min(d, 2)\n dice_to_keep = min(a, d)\n a_dice = sorted([random.randint(1,6) for i in range(a)])[-dice_to_keep:]\n d_dice = sorted([random.randint(1,6) for i in range(d)])[-dice_to_keep:]\n a_wins = sum([d_dice[i] < a_dice[i] for i in range(dice_to_keep)])\n d_wins = sum([d_dice[i] >= a_dice[i] for i in range(dice_to_keep)])\n return -d_wins, -a_wins\n\n\ndef do_combat(a, d):\n while a > 1 and d > 0:\n a_loss, d_loss = do_roll(a, d)\n a += a_loss\n d += d_loss\n return a, d\n\n\ndef multi_odds(a, d, n=100000):\n a_wins = 0\n a_left_sum = 0\n d_left_sum = 0\n a_left = a\n for i in range(n):\n a_left = a\n for mi, m in enumerate(d):\n a_left, d_left = do_combat(a_left, m)\n if a_left == 1 or (mi + 1) == len(d):\n #print a_left, mi, d_left\n a_left_sum += a_left\n d_left_sum += d_left + (sum(d[mi + 1:]) if (mi + 1) < len(d) else 0)\n if (mi + 1) == len(d) and d_left == 0:\n a_wins += 1\n break\n a_left -= 1\n return a_wins / float(n), a_left_sum / float(n), d_left_sum / float(n)\n\n\n\ndef odds(a, d, n=100000):\n a_wins = 0\n a_left_sum = 0\n d_left_sum = 0\n for i in range(n):\n a_final, d_final = do_combat(a, d)\n a_left_sum += a_final\n d_left_sum += d_final\n if a_final > d_final:\n a_wins += 1\n return a_wins / float(n), a_left_sum / float(n), d_left_sum / float(n)\n\ndef sim_3v2(n=5000):\n def sim():\n attacker = [random.randint(1,6) for i in range(3)]\n defender = [random.randint(1,6) for i in range(22)]\n attacker.sort()\n attacker = attacker[1:]\n a_loss = 0\n d_loss = 0\n if attacker[0] > defender[0]:\n d_loss += 1\n else:\n a_loss += 1\n if attacker[1] > defender[1]:\n d_loss += 1\n else:\n a_loss += 1\n return a_loss, d_loss\n a_total = 0\n d_total = 0\n for i in range(n):\n a,d = sim()\n a_total += a\n d_total += d\n print('Attacker Avg loss: %2.2f' % (a_total / float(n)))\n print('Defender Avg loss: %2.2f' % (d_total / float(n)))\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 3:\n print('USAGE: python odds.py attacker_armies defender_army[ies]')\n print('EXAMPLE: python odds.py 15 11')\n print(' : python odds.py 15 7 3 1')\n sys.exit()\n a = sys.argv[1]\n d = sys.argv[2:]\n a = int(a)\n d = [int(x) for x in d]\n o, al, dl = 0.0, 0.0, 0.0\n if len(d) == 1:\n o, al, dl = odds(a, d[0])\n else:\n o, al, dl = multi_odds(a, d)\n print('Odds: %2.1f%% Attacker Rem: %2.1f Defender Rem: %2.1f' % (o * 100, al, dl))\n","sub_path":"odds.py","file_name":"odds.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"351688131","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\nimport numpy as np\nimport pytest\n\nimport mindspore.context as context\nimport mindspore.nn as nn\nfrom mindspore import Tensor, Parameter\nimport mindspore.common.dtype as mstype\nimport mindspore.ops as ops\n\ncontext.set_context(mode=context.GRAPH_MODE, device_target=\"GPU\")\n\nfunc_map = {\n \"update\": ops.ScatterNdUpdate,\n \"add\": ops.ScatterNdAdd,\n \"sub\": ops.ScatterNdSub,\n \"mul\": ops.ScatterNdMul,\n \"div\": ops.ScatterNdDiv,\n \"max\": ops.ScatterNdMax,\n \"min\": ops.ScatterNdMin,\n}\n\nnp_func_map = {\n \"update\": lambda a, b: b,\n \"add\": lambda a, b: a + b,\n \"sub\": lambda a, b: a - b,\n \"mul\": lambda a, b: a * b,\n \"div\": lambda a, b: a / b,\n \"max\": np.maximum,\n \"min\": np.minimum,\n}\n\n\nclass TestScatterNdFuncNet(nn.Cell):\n def __init__(self, func, lock, inputx, indices, updates):\n super(TestScatterNdFuncNet, self).__init__()\n\n self.scatter_func = func_map[func](use_locking=lock)\n self.inputx = Parameter(inputx, name=\"inputx\")\n self.indices = Parameter(indices, name=\"indices\")\n self.updates = Parameter(updates, name=\"updates\")\n\n def construct(self):\n out = self.scatter_func(self.inputx, self.indices, self.updates)\n return out\n\n\ndef scatter_nd_func_np(func, inputx, indices, updates):\n result = inputx.asnumpy().copy()\n updates_np = updates.asnumpy()\n\n f = np_func_map[func]\n\n for idx, _ in np.ndenumerate(np.zeros(indices.shape[:-1])):\n out_index = indices[idx]\n result[out_index] = f(result[out_index], updates_np[idx])\n\n return result\n\n\ndef compare_scatter_nd_func(func, lock, inputx, indices, updates):\n output = TestScatterNdFuncNet(func, lock, inputx, indices, updates)()\n expected = scatter_nd_func_np(func, inputx, indices, updates)\n np.testing.assert_array_almost_equal(output.asnumpy(), expected)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\n@pytest.mark.parametrize('func', ['update', 'add', 'sub', 'div', 'mul', 'max', 'min'])\n@pytest.mark.parametrize('data_type',\n [mstype.uint8, mstype.int8, mstype.int16, mstype.int32, mstype.float16, mstype.float32,\n mstype.float64])\n@pytest.mark.parametrize('index_type', [mstype.int32])\ndef test_scatter_nd_func_small(lock, func, data_type, index_type):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for small input of ScatterNd* like functions\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), data_type)\n indices = Tensor(np.array([[0, 0], [1, 1]]), index_type)\n updates = Tensor(np.array([1.0, 2.2]), data_type)\n\n compare_scatter_nd_func(func, lock, inputx, indices, updates)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\ndef test_scatter_nd_func_small_update(lock):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for bool input of ScatterNdUpdate\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.array([True, False, True, False, True, True, False, True]), mstype.bool_)\n indices = Tensor(np.array([[False], [True], [False], [True]]), mstype.int32)\n updates = Tensor(np.array([9, 10, 11, 12]), mstype.bool_)\n\n compare_scatter_nd_func(\"update\", lock, inputx, indices, updates)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\n@pytest.mark.parametrize('func', ['update', 'add', 'sub', 'div', 'mul', 'max', 'min'])\n@pytest.mark.parametrize('data_type',\n [mstype.uint8, mstype.int8, mstype.int16, mstype.int32, mstype.float16, mstype.float32,\n mstype.float64])\n@pytest.mark.parametrize('index_type', [mstype.int32])\ndef test_scatter_nd_func_small_int(lock, func, data_type, index_type):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for int input of ScatterNd* like functions\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), data_type)\n indices = Tensor(np.array([[4], [3], [1], [7]]), index_type)\n updates = Tensor(np.array([9, 10, 11, 12]), data_type)\n\n compare_scatter_nd_func(func, lock, inputx, indices, updates)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\n@pytest.mark.parametrize('func', ['update', 'add', 'sub', 'div', 'mul', 'max', 'min'])\n@pytest.mark.parametrize('data_type',\n [mstype.uint8, mstype.int8, mstype.int16, mstype.int32, mstype.float16, mstype.float32,\n mstype.float64])\n@pytest.mark.parametrize('index_type', [mstype.int32])\ndef test_scatter_nd_func_small_negative(lock, func, data_type, index_type):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for negative input of ScatterNd* like functions\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.array([-1, -2, -3, -4, -5, -6, -7, -8]), data_type)\n indices = Tensor(np.array([[4], [3], [1], [7]]), index_type)\n updates = Tensor(np.array([9, -10, 11, -12]), data_type)\n\n compare_scatter_nd_func(func, lock, inputx, indices, updates)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\n@pytest.mark.parametrize('func', ['update', 'add', 'sub', 'div', 'mul', 'max', 'min'])\n@pytest.mark.parametrize('data_type',\n [mstype.uint8, mstype.int8, mstype.int16, mstype.int32, mstype.float16, mstype.float32,\n mstype.float64])\n@pytest.mark.parametrize('index_type', [mstype.int32])\ndef test_scatter_nd_func_multi_dims(lock, func, data_type, index_type):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for multi-dims input of ScatterNd* like functions\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.zeros((4, 4, 4)), data_type)\n indices = Tensor(np.array([[0], [2]]), index_type)\n updates = Tensor(\n np.array(\n [\n [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n ]\n ),\n data_type,\n )\n\n compare_scatter_nd_func(func, lock, inputx, indices, updates)\n\n\n@pytest.mark.level0\n@pytest.mark.platform_x86_gpu_training\n@pytest.mark.env_onecard\n@pytest.mark.parametrize('lock', [True, False])\n@pytest.mark.parametrize('func', ['update', 'add', 'sub', 'div', 'mul', 'max', 'min'])\n@pytest.mark.parametrize('data_type',\n [mstype.uint8, mstype.int8, mstype.int16, mstype.int32, mstype.float16, mstype.float32,\n mstype.float64])\n@pytest.mark.parametrize('index_type', [mstype.int32])\ndef test_scatter_nd_func_one_value(lock, func, data_type, index_type):\n \"\"\"\n Feature: ALL To ALL\n Description: test cases for one value modification of ScatterNd* like functions\n Expectation: the result match to numpy implementation\n \"\"\"\n inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), data_type)\n indices = Tensor(np.array([[0, 1]]), index_type)\n updates = Tensor(np.array([1.0]), data_type)\n\n compare_scatter_nd_func(func, lock, inputx, indices, updates)\n","sub_path":"tests/st/ops/gpu/test_scatter_nd_func_op.py","file_name":"test_scatter_nd_func_op.py","file_ext":"py","file_size_in_byte":8196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"28990444","text":"# Python implementation using the multiprocessing module\n#\nfrom __future__ import division\nimport collections, resource\nimport os, sys, glob\nimport scipy\nfrom scipy.interpolate import RectBivariateSpline\nimport numpy as np\nfrom astropy import units as u\nfrom astropy import constants as const\nfrom astropy.cosmology import LambdaCDM\nimport pandas as pd\nimport h5py, pickle, pandas\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nsys.path.insert(0, '/cosma5/data/dp004/dc-beck3/lib/')\nimport read_hdf5\nsys.path.insert(0, '/cosma5/data/dp004/dc-beck3/StrongLensing/LensingAnalysis/lib/')\nimport lm_cfuncs as cf\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning, append=1)\nos.system(\"taskset -p 0xff %d\" % os.getpid())\nsys.settrace\n\n\ndef define_unit(simunit, hfname):\n exp = np.floor(np.log10(np.abs(simunit))).astype(int)\n if exp == 21: # simulation in [kpc]\n if hfname == 'Rockstar':\n unit = 'Mpc'\n elif hfname == 'Subfind':\n unit = 'kpc'\n elif exp == 23: #simulation in [Mpc]\n if hfname == 'Rockstar':\n unit = 'Mpc'\n elif hfname == 'Subfind':\n unit = 'kpc'\n else:\n raise Exception('Dont know this unit ->', unit)\n return unit\n\n\ndef source_selection(src_id, src_z, src_pos, halo_id):\n \"\"\"\n Find redshift of sources which are likely to be multiple imaged\n Input:\n src_id[np.array(int)] - LightCone-IDs of sources\n src_z[np.array(float)] - redshift of sources\n halo_id[int] - ID of subhalo acting as lens\n Output:\n zs[int] - redshift of source\n \"\"\"\n src_indx = np.where(src_id == halo_id)[0]\n dist = np.sqrt(src_pos[src_indx, 1]**2 + src_pos[src_indx, 2]**2)\n src_min = np.argsort(dist)\n #indx = np.argmin(dist)\n #indx = np.argmax(src_z[src_indx])\n start = 0\n end = 2\n if len(src_indx) > end:\n return src_z[src_indx[src_min[start:end]]], src_min[start:end], src_pos[src_indx[src_min[start:end]]] # indx\n else:\n return src_z[src_indx[src_min[:]]], src_min[:], src_pos[src_indx[src_min[:]]]\n\n\n\ndef sigma_crit(zLens, zSource, cosmo):\n Ds = cosmo.angular_diameter_distance(zSource)\n Dl = cosmo.angular_diameter_distance(zLens)\n Dls = cosmo.angular_diameter_distance_z1z2(zLens, zSource)\n sig_crit = (const.c**2/(4*np.pi*const.G))*Ds/(Dl*Dls)\n return sig_crit\n\n\ndef area(vs):\n \"\"\"\n Use Green's theorem to compute the area enclosed by the given contour.\n \"\"\"\n a = 0\n x0, y0 = vs[0]\n for [x1, y1] in vs[1:]:\n dy = y1 - y0\n a += x0*dy\n x0 = x1\n y0 = y1\n return a\n\n\ndef cal_lensing_signals(kap, bzz, ncc, coord):\n dsx_arc = bzz/ncc\n # deflection maps\n alpha1, alpha2 = cf.call_cal_alphas(kap, bzz, ncc)\n \n #TODO: map to finer grid\n alpha1_spline = RectBivariateSpline(coord, coord, alpha1)\n alpha2_spline = RectBivariateSpline(coord, coord, alpha2)\n lencoord = len(coord)\n centre_coord = np.linspace(coord[int(lencoord/3)],\n coord[int(2*lencoord/3)],\n 256)\n coord = np.concatenate((coord[:int(lencoord/3)],\n centre_coord,\n coord[int(2*lencoord/3+1):]))\n alpha1 = alpha1_spline(coord, coord)\n alpha2 = alpha2_spline(coord, coord)\n \n # shear maps\n al11 = 1 - np.gradient(alpha1, coord, axis=0)\n al12 = - np.gradient(alpha1, coord, axis=1)\n al21 = - np.gradient(alpha2, coord, axis=0)\n al22 = 1 - np.gradient(alpha2, coord, axis=1)\n \n detA = al11*al22 - al12*al21 # = (1-kappa0-shear0)*(1-kappa0+shear0)\n \n kappa0 = 1 - 0.5*(al11 + al22)\n shear1 = 0.5*(al11 - al22)\n shear2 = 0.5*(al21 + al12)\n shear0 = (shear1**2 + shear2**2)**0.5\n \n # magnification maps\n mu = 1/detA # = 1.0/((1.0-kappa0)**2.0-shear1*shear1-shear2*shear2)\n lambda_t = 1 - kappa0 - shear0 # tangential eigenvalue, page 115\n \n # lensing potential\n phi = cf.call_cal_phi(kap, bzz, ncc)\n\n return alpha1, alpha2, mu, phi, detA, lambda_t, coord\n\n\ndef einstein_radii(lp1, lp2, sp1, sp2 ,detA, lambda_t, cosmo, ax, method):\n \"\"\"\n Calculate Critical Curves, Caustics, and Einstein Radii\n Input:\n lp1,lp2[float] : lensing plane x,y-coordinates\n sp1,sp2[float] : source plane x,y-coordinates\n\n \"\"\"\n crit_curve = ax.contour(lp1, lp2, detA,\n levels=(0,), colors='r',\n linewidths=1.5, zorder=200)\n Ncrit = len(crit_curve.allsegs[0])\n crit_curve = crit_curve.allsegs[0]\n tan_crit_curve = ax.contour(lp1, lp2,\n lambda_t, levels=(0,), colors='r',\n linewidths=1.5, zorder=200)\n NumTCC = len(tan_crit_curve.allsegs[0])\n if NumTCC> 0:\n # Find tangential critical curve on which to base Rein\n len_tan_crit = np.zeros(NumTCC)\n for i in range(NumTCC):\n len_tan_crit[i] = len(tan_crit_curve.allsegs[0][i])\n tan_crit_curve = tan_crit_curve.allsegs[0][len_tan_crit.argmax()]\n \n # Einstein Radius\n if method == 'eqv':\n Rein = np.sqrt(np.abs(area(tan_crit_curve))/np.pi) #[arcsec]\n if method == 'med':\n dist = np.sqrt(tan_crit_curve[:, 0]**2 + tan_crit_curve[:, 1]**2)\n Rein = np.median(dist) #[arcsec]\n \n # Caustics\n for pp in range(len(tan_crit_curve)):\n c1, c2 = (cf.call_mapping_triangles([tan_crit_curve[pp, 0],\n tan_crit_curve[pp, 1]],\n sp1, sp2, lp1, lp2))\n if pp == 0:\n caustic1 = c1\n caustic2 = c2\n else:\n caustic1 = np.hstack((caustic1, c1))\n caustic2 = np.hstack((caustic2, c2))\n caustic = np.array([caustic1, caustic2]).T\n\n else:\n tan_crit_curve = np.array([])\n caustic = np.array([])\n Rein = 0\n return NumTCC, tan_crit_curve, caustic, Rein\n\n\ndef einstein_radii_proper(kappa, dsx_arc, cosmo):\n \"\"\"\n kappa:\n convergence map\n dsx_arc: [float]\n pixel size in arcsec\n \"\"\"\n #_radius = 0\n #while _kappa_enclosed < 1:\n return\n\ndef mpc2arc(SrcPosSky):\n # Source position [arcsec]\n x = SrcPosSky[0]*u.Mpc\n y = SrcPosSky[1]*u.Mpc\n z = SrcPosSky[2]*u.Mpc\n if (y == 0.) and (z == 0.):\n beta1 = 1e-3\n beta2 = 1e-3\n else:\n beta1 = ((y/x)*u.rad).to_value('arcsec')\n beta2 = ((z/x)*u.rad).to_value('arcsec')\n beta = [beta1, beta2]\n return beta\n\n\ndef timedelay_magnification(mu_map, phi_map, dsx_arc, Ncells, lp1, lp2,\n alpha1, alpha2, beta, zs, zl, cosmo):\n \"\"\"\n Input:\n mu_map: 2D magnification map\n phi_map: 2D potential map\n dsx_arc: cell size in arcsec\n Ncells: number of cells\n lp1, lp2: lens place grid coordinates\n alpha1, alpha2: 2D deflection map\n SrcPosSky: source position in Mpc\n zs: source redshift\n zl: lens redshift\n\n Output:\n len(mu): number of multiple images of supernova\n delta_t: Time it takes for photon to cover distance source-observer\n mu: luminosity magnification of source\n \"\"\"\n # Mapping light rays from image plane to source plan\n [sp1, sp2] = [lp1 - alpha1, lp2 - alpha2] #[arcsec]\n\n theta1, theta2 = cf.call_mapping_triangles([beta[0], beta[1]], \n lp1, lp2, sp1, sp2)\n # calculate magnifications of lensed Supernovae\n mu = cf.call_inverse_cic_single(mu_map, 0.0, 0.0, theta1, theta2, dsx_arc)\n # calculate time delays of lensed Supernovae in Days\n prts = cf.call_inverse_cic_single(phi_map, 0.0, 0.0, theta1, theta2, dsx_arc)\n Kc = ((1.0+zl)/const.c.to('Mpc/s') * \\\n (cosmo.angular_diameter_distance(zl) * \\\n cosmo.angular_diameter_distance(zs) / \\\n (cosmo.angular_diameter_distance(zs) - \\\n cosmo.angular_diameter_distance(zl)))).to('sday').value\n delta_t = Kc*(0.5*((theta1 - beta[0])**2.0 + \\\n (theta2 - beta[1])**2.0) - prts)/cf.apr**2\n theta = np.array([theta1, theta2]).T\n return len(mu), delta_t, mu, theta\n","sub_path":"LensingAnalysis/lib/lenstools.py","file_name":"lenstools.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"98570078","text":"# -*- coding: utf-8 -*-\n\n# 自选股分析监控\n# 对自选股进行分组:上升通道,下降通道,低价股,绩优股,筹码集中\n# 对不同组的股票按需进行监控 均线,极值点,\n\nimport pandas as pd\nimport numpy as np\nimport pandas as pd\nfrom docx.shared import Cm\n\nfrom analysis_util.output_document import Doc\nfrom analysis_util.plot_k_line import save_k_line\nfrom selected_stock_analysis.stock_classification import get_up_trend_stocks\n\n\ndef output_doc(df, file_path):\n # doc文档\n doc = Doc()\n for line in df.values:\n print(line)\n doc.add_heading(','.join(line))\n symbol = line[0]\n\n # 画出其最近100天,300天,1000天日线图\n save_k_line(symbol, 100, './resources/kline100.png')\n save_k_line(symbol, 300, './resources/kline300.png')\n save_k_line(symbol, 1000, './resources/kline1000.png')\n doc.add_picture('./resources/kline100.png', width=Cm(10))\n doc.add_picture('./resources/kline300.png', width=Cm(10))\n doc.add_picture('./resources/kline1000.png', width=Cm(10))\n\n # 保存文档\n doc.save(file_path)\n\n\nif __name__ == '__main__':\n # 获取股票池\n # file = 'stock_pool2023.txt'\n file = '自选股.csv'\n\n path = './classification/'\n\n # 先进行自选股分组\n # 上升通道股票\n get_up_trend_stocks(file)\n\n # 超短线上升通道\n df = pd.read_csv(path + '超短线上升通道%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '超短线上升通道%s.docx' % (file.split('.')[0]))\n\n # 短线上升通道\n df = pd.read_csv(path + '短线上升通道%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '短线上升通道%s.docx' % (file.split('.')[0]))\n\n # 中线上升通道\n df = pd.read_csv(path + '中线上升通道%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '中线上升通道%s.docx' % (file.split('.')[0]))\n\n # 中长线上升通道\n df = pd.read_csv(path + '中长线上升通道%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '中长线上升通道%s.docx' % (file.split('.')[0]))\n\n # 长线上升通道\n df = pd.read_csv(path + '长线上升通道%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '长线上升通道%s.docx' % (file.split('.')[0]))\n\n # 中期反弹\n df = pd.read_csv(path + '中期反弹%s.csv' % (file.split('.')[0]), dtype={'symbol': np.str})\n # 输出到文档\n output_doc(df, path + '中期反弹%s.docx' % (file.split('.')[0]))\n","sub_path":"selected_stock_analysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"653062634","text":"# -*- coding=utf-8 -*-\nimport attr\nimport os\nimport pip_shims\n\n\n@attr.s\nclass VCSRepository(object):\n url = attr.ib()\n name = attr.ib()\n checkout_directory = attr.ib()\n vcs_type = attr.ib()\n subdirectory = attr.ib(default=None)\n commit_sha = attr.ib(default=None)\n ref = attr.ib(default=None)\n repo_instance = attr.ib()\n\n @repo_instance.default\n def get_repo_instance(self):\n from pip_shims import VcsSupport\n VCS_SUPPORT = VcsSupport()\n backend = VCS_SUPPORT._registry.get(self.vcs_type)\n return backend(url=self.url)\n\n @property\n def is_local(self):\n url = self.url\n if '+' in url:\n url = url.split('+')[1]\n return url.startswith(\"file\")\n\n def obtain(self):\n if (os.path.exists(self.checkout_directory) and not\n self.repo_instance.is_repository_directory(self.checkout_directory)):\n self.repo_instance.unpack(self.checkout_directory)\n elif not os.path.exists(self.checkout_directory):\n self.repo_instance.obtain(self.checkout_directory)\n else:\n if self.ref:\n self.checkout_ref(self.ref)\n if not self.commit_sha:\n self.commit_sha = self.get_commit_hash()\n\n def checkout_ref(self, ref):\n if not self.repo_instance.is_commit_id_equal(\n self.checkout_directory, self.get_commit_hash()\n ) and not self.repo_instance.is_commit_id_equal(self.checkout_directory, ref):\n if not self.is_local:\n self.update(ref)\n\n def update(self, ref):\n target_ref = self.repo_instance.make_rev_options(ref)\n if pip_shims.parse_version(pip_shims.pip_version) > pip_shims.parse_version(\"18.0\"):\n self.repo_instance.update(self.checkout_directory, self.url, target_ref)\n else:\n self.repo_instance.update(self.checkout_directory, target_ref)\n self.commit_sha = self.get_commit_hash()\n\n def get_commit_hash(self, ref=None):\n return self.repo_instance.get_revision(self.checkout_directory)\n","sub_path":"weatherenv/Lib/site-packages/pipenv/vendor/requirementslib/models/vcs.py","file_name":"vcs.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"408674122","text":"import socket\nimport sys\nimport Classifier_general\nimport Classifier_ecoc_svm\n\nimport Classify_utils\n\nHOST = '192.168.0.104'\nPORT = 8888\n\nfolds = Classify_utils.eight_labels()\nclassifier = Classifier_ecoc_svm.SVM()\nClassifier_general.classify(folds, classifier)\nprediction = Classifier_general.predict_one_sample(\"You are a stupid bitch\", classifier)\nprint(prediction)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint('socket created')\n\n# Bind socket to Host and Port\ntry:\n s.bind((HOST, PORT))\nexcept socket.error as err:\n print('Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1])\n sys.exit()\n\nprint('Socket Bind Success!')\n\n\n# listen(): This method sets up and start TCP listener.\ns.listen(10)\nprint('Socket is now listening')\n\n\nwhile 1:\n conn, addr = s.accept()\n print('Connect with ' + addr[0] + ':' + str(addr[1]))\n data = conn.recv(64)\n print(data)\n data = str(Classifier_general.predict_one_sample(str(data), classifier))\n print(\"sending: \" + str(data))\n conn.send(data.encode())\n conn.close()\ns.close()\n\n","sub_path":"Classifier_Belgian_Dataset/Classification_Server.py","file_name":"Classification_Server.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"296221189","text":"from models import Books\nfrom app import db\nimport csv\n\n\ndef insert_into_table(file_name):\n with open(file_name) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n next(reader, None)\n for isbn, title, author, year in reader:\n item = Books(isbn, title, author, year)\n db.session.add(item)\n db.session.commit()\n\n\nif __name__ == '__main__':\n book_csv = \"../books.cv\"\n insert_into_table(book_csv)\n","sub_path":"app/inserts.py","file_name":"inserts.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"534868162","text":"#1、\ndef count_1(A,B):\n if A>B:\n A,B = B,A\n C = A*B\n while A!=0:\n R= B%A\n B=A\n A=R\n return (B,int(C/B))\nprint(count_1(20,30))\n\n#2、\ndef count_2(words):\n num_number = char_number = space_number = other_number = 0\n for char in words:\n if char.isdigit():\n num_number += 1\n elif char.isalpha():\n char_number += 1\n elif char == ' ':\n space_number += 1\n else:\n other_number += 1\n print(\"数字个数:%d, 字母个数:%d, 空格个数:%d, 其他字符:%d\" % (num_number,char_number,space_number,other_number))\ncount_2(input(\"请输入字符串:\"))\n","sub_path":"homework7/Group12/hw_1720400.py","file_name":"hw_1720400.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"303125986","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 19 17:59:49 2021\n\n@author: 0014CR744\n\"\"\"\n\nclass Search():\n def name(productList): \n productName = str(input(\"Enter Product Name : \"))\n searchList = list(filter(lambda i: i.get(\"name\") == productName,productList))\n return searchList\n \n def displayBrand(searchList):\n try:\n if(len(searchList) == 0):\n raise ValueError()\n else:\n for i in range(0,len(searchList)):\n print(f\"Brand : { searchList[i]['brand']} | Price : { searchList[i]['price']}\")\n \n except ValueError:\n print(\"Product not available\")","sub_path":"CaseStudy_With_Cart/search_prod_name.py","file_name":"search_prod_name.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"129367856","text":"\"\"\" Player module\nThis is a template/example class for your player.\nThis is the only file you should modify.\nThe logic of your hockey robot will be implemented in this class.\nPlease implement the interface next_move().\nThe only restrictions here are:\n - to implement a class constructor with the args: paddle_pos, goal_side\n - set self.my_display_name with your team's name, max. 15 characters\n - to implement the function next_move(self, current_state),\n returnin the next position of your paddle\n\"\"\"\n\nimport copy\nimport utils\nimport random as r\n\nclass Player:\n def __init__(self, paddle_pos, goal_side):\n\n # set your team's name, max. 15 chars\n self.my_display_name = \"Random\"\n\n # these belong to my solution,\n # you may erase or change them in yours\n self.future_size = 30\n self.my_goal = goal_side\n self.my_goal_center = {}\n self.opponent_goal_center = {}\n self.my_paddle_pos = paddle_pos\n self.up= False;\n\n\n def next_move(self, current_state):\n \"\"\" Function that computes the next move of your paddle\n Implement your algorithm here. This will be the only function\n used by the GameCore. Be aware of abiding all the game rules.\n Returns:\n dict: coordinates of next position of your paddle.\n \"\"\"\n\n # update my paddle pos\n # I need to do this because GameCore moves my paddle randomly\n self.my_paddle_pos = current_state['paddle1_pos'] if self.my_goal == 'left' \\\n else current_state['paddle2_pos']\n\n \n \n # computing both goal centers\n self.my_goal_top = {'x': 100 if self.my_goal == 'left' else 800,\n 'y': (current_state['board_shape'][0]/2)+((current_state['board_shape'][0]*0.45)/2)}\n self.my_goal_down = {'x': 100 if self.my_goal == 'left' else 800,\n 'y': (current_state['board_shape'][0]/2)-((current_state['board_shape'][0]*0.45)/2)}\n \n\n\n # estimate an aiming position\n if(self.up):\n target_pos = self.my_goal_down\n self.up= False\n else: \n target_pos = self.my_goal_top\n self.up= True\n # move to target position, taking into account the max. paddle speed\n \n if target_pos != self.my_paddle_pos:\n \n direction_vector = {'x': target_pos['x'] - self.my_paddle_pos['x'],\n 'y': target_pos['y'] - self.my_paddle_pos['y']}\n \n direction_vector = {k: v / utils.vector_l2norm(direction_vector)\n for k, v in direction_vector.items()}\n \n movement_dist = min(current_state['paddle_max_speed'] * current_state['delta_t'],\n utils.distance_between_points(target_pos, self.my_paddle_pos))\n direction_vector = {k: v * movement_dist\n for k, v in direction_vector.items()}\n \n new_paddle_pos = {'x': self.my_paddle_pos['x'] + direction_vector['x'],\n 'y': self.my_paddle_pos['y'] + direction_vector['y']}\n \n \n # check if computed new position in inside board limits\n if utils.is_inside_goal_area_paddle(new_paddle_pos, current_state) is False and \\\n utils.is_out_of_boundaries_paddle(new_paddle_pos, current_state) is None:\n self.my_paddle_pos = new_paddle_pos \n return self.my_paddle_pos\n\n\n","sub_path":"ai-airhockey/Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"601394306","text":"#!/usr/bin/env python3\n\n\n\ndef count_words(filename):\n \"\"\"Sum of strings in file\"\"\"\n try:\n with open(filename) as f_obj:\n contents = f_obj.read()\n except FileNotFoundError:\n msg=\"Sorry, the file \"+filename+\" does not exist.\"\n print(msg)\n else:\n words=contents.split()\n num_words=len(words)\n print(\"The file \"+filename+\" has about \"+str(num_words)+\" words.\")\n\n\nfilenames=[\"alice.txt\",\"mobydick.txt\",\"War and peace.txt\"]\nfor filename in filenames:\n count_words(filename)","sub_path":"garbage/books/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"74866165","text":"\"\"\"\nSupport code that deals with packages compiled\nwith mypyc.\n\"\"\"\nimport ast\n\nimport modulegraph2\n\nfrom ._ast_tools import extract_ast_info\nfrom ._depinfo import DependencyInfo\nfrom ._nodes import BaseNode, ExtensionModule, Package\n\n# Mypyc compiles Python code in a package to extension\n# modules, but generally leaves the Python sources next\n# to those extension.\n#\n# Use this to update the dependency graph.\n#\n# A package compiled with mypy can be detected by\n# looking for a toplevel module whose name starts\n# with a hex string and ends with ``__mypyc``.\n#\n# The code tries to be careful and does not add\n# dependencies when it cannot find the python sources\n# corresponding to the extension module.\n\n\ndef mypyc_post_processing_hook(graph: \"modulegraph2.ModuleGraph\", node: BaseNode):\n # Look for extension modules, but standalone and\n # as the ``__init__`` for a package.\n if isinstance(node, Package):\n if not isinstance(node.init_module, ExtensionModule):\n return\n elif not isinstance(node, ExtensionModule):\n return\n\n # Only look at nodes with a distribution, uninstalled\n # modules don't have the information this hook needs.\n if node.distribution is None:\n return\n\n # This function will try to parse the source\n # file next to the node in the filesystem, that\n # requires knowing the filename for the node.\n if isinstance(node, Package):\n if node.init_module.filename is None: # pragma: no branch\n # This should never happen, a package that\n # was not loaded from something filesystem-like\n return # pragma: no cover\n else:\n source_filename = node.init_module.filename.parent / (\n node.init_module.filename.stem.split(\".\", 1)[0] + \".py\"\n )\n\n elif node.filename is None: # pragma: no branch\n # This should never happen: A installed distribution\n # but without a filesystem location.\n return # pragma: no cover\n else:\n source_filename = node.filename.parent / (\n node.filename.stem.split(\".\", 1)[0] + \".py\"\n )\n\n # Finally check that the distribution appears to\n # be compiled with mypyc.\n #\n # The name check can be made stricter if needed\n # by looking at the prefix as well.\n for nm in node.distribution.import_names:\n if nm.endswith(\"__mypyc\"):\n # Distribution is mypyc compiled\n helper_module = nm\n break\n else:\n # Distribution is not mypyc compiled\n return\n\n # Locate the source code that's next to the extension module.\n #\n # This code assumes that the extension module is in the filesystem,\n # which should be good enough in practice (AFAIK none of the major\n # platforms support loading extension modules from memory).\n if not source_filename.is_file():\n return\n\n # Add explicit dependency to the mypy helper extension module\n helper_node = graph.add_module(helper_module)\n graph.add_edge(node, helper_node, DependencyInfo(False, True, False, None))\n\n source_code = source_filename.read_bytes()\n\n try:\n ast_node = compile(\n source_code,\n str(source_filename),\n \"exec\",\n flags=ast.PyCF_ONLY_AST,\n dont_inherit=True,\n )\n except SyntaxError:\n return\n\n else:\n imports = list(extract_ast_info(ast_node))\n\n # And finally process the dependencies found in the source file.\n if imports:\n graph._process_import_list(node, imports)\n graph._run_stack()\n","sub_path":"modulegraph2/_mypyc_support.py","file_name":"_mypyc_support.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"52616368","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nimport random\nimport time\nimport pandas as pd\nfrom datetime import datetime\n\nFIELDS = [\"id\", \"condition\", \"mode\", \"run\", \"pressed_key\",\n \"pressed_correct_key\", \"reaction_time_in_sec\",\n \"time_waited_in_sec\", \"time_stamp\"]\n\n\nclass SpaceRecorder(QtWidgets.QWidget):\n\n def __init__(self, isDarkmode, id):\n super().__init__()\n self.id = id\n self.black = QtGui.QColor(0, 0, 0)\n self.white = QtGui.QColor(255, 255, 255)\n self.width = 1200\n self.height = 800\n self.minRectWidth = 40\n self.maxRectWidth = 200\n self.rectAppeared = False\n self.isDarkmode = isDarkmode\n self.initUI()\n self.timer = QtCore.QTimer()\n self.round = 1\n self.timerStarted = False\n self.color = self.white if self.isDarkmode else self.black\n self.df = pd.DataFrame(columns=FIELDS)\n self.circleAppeared = False\n self.timeWaited = 0\n self.timeWaitedFalse = 0\n\n def showRect(self):\n self.update()\n self.timerStarted = False\n\n def initUI(self):\n # set the text property of the widget we are inheriting\n self.setGeometry(100, 100, self.width, self.height)\n self.setWindowTitle('Darkmode vs Lightmode Test 2')\n # widget should accept focus by click and tab key\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n self.__setBackgroundColor()\n self.show()\n\n def keyPressEvent(self, ev):\n if ev.key() == QtCore.Qt.Key_Space:\n if self.round <= 20:\n if not self.timerStarted:\n self.__modeOne()\n\n def paintEvent(self, event):\n if not self.timerStarted:\n self.__paintRectOrText(event)\n\n def drawText(self, event, qp):\n if self.rectAppeared:\n self.rectAppeared = False\n elif self.circleAppeared:\n self.circleAppeared = False\n qp.setPen(self.color)\n qp.setFont(QtGui.QFont('Decorative', 32))\n if self.round == 1:\n self.text = \"\"\"Press 'Space' to start. \\nPress 'Space'\n only if a RECTANGLE appears\"\"\"\n if self.round > 1:\n self.text = f'Press \"Space\" to start round {str(self.round)}'\n if self.round == 21:\n self.text = \"You have finished the first test. \\nThank you!\"\n self.df = self.df.to_csv(\n f'/home/erik/assignments/assignment-03-bs/test2_{self.id}.csv',\n index=False)\n qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)\n\n def drawRect(self, event, qp):\n randNum = random.randint(0, 1)\n qp.setBrush(self.color)\n rect = self.__getRandomRect()\n if randNum == 0:\n qp.drawRect(rect)\n self.rectAppeared = True\n else:\n qp.drawEllipse(rect)\n self.circleAppeared = True\n self.timer.singleShot(3000, lambda: self.__drawAgain())\n\n def __getRandomRect(self):\n xPos = random.randint(0, self.width - self.maxRectWidth)\n yPos = random.randint(0, self.height - self.maxRectWidth)\n height = random.randint(self.minRectWidth, self.maxRectWidth)\n return QtCore.QRect(xPos, yPos, height, height)\n\n def __drawAgain(self):\n self.circleAppeared = False\n self.update()\n\n def __setColorScheme(self):\n if self.round == 10:\n self.__changeColorTheme()\n\n def __changeColorTheme(self):\n self.isDarkmode = not self.isDarkmode\n self.color = self.white if self.isDarkmode else self.black\n self.__setBackgroundColor()\n\n def __setBackgroundColor(self):\n if self.isDarkmode:\n self.setStyleSheet('background-color: black')\n else:\n self.setStyleSheet('background-color: white')\n\n def __modeOne(self):\n if not self.rectAppeared and not self.circleAppeared:\n self.timerStarted = True\n self.update()\n self.timeWaited = random.randint(1, 6)\n self.timer.singleShot(self.timeWaited*1000,\n lambda: self.showRect())\n else:\n # catch reation time here\n self.__addRow()\n self.__setColorScheme()\n self.round += 1\n self.update()\n\n def __paintRectOrText(self, event):\n if not self.rectAppeared and not self.circleAppeared:\n qp = QtGui.QPainter()\n qp.begin(self)\n self.drawRect(event, qp)\n qp.end()\n self.startTime = time.time()\n else:\n qp = QtGui.QPainter()\n qp.begin(self)\n self.drawText(event, qp)\n qp.end()\n\n def __addRow(self):\n condition = \"dark\" if self.isDarkmode else \"light\"\n reactionTime = time.time() - self.startTime\n timeStamp = datetime.now()\n run = self.round if self.round <= 10 else self.round-10\n d = {\n 'id': self.id,\n 'condition': condition,\n 'mode': 2,\n 'run': run,\n 'pressed_key': 'space',\n 'pressed_correct_key': True if self.rectAppeared else False,\n 'reaction_time_in_sec': reactionTime,\n 'time_waited_in_sec': self.timeWaited,\n 'time_stamp': timeStamp\n }\n print(d)\n self.df = self.df.append(d, ignore_index=True)\n\n\ndef main():\n isDarkmode = False\n if len(sys.argv) == 3:\n if sys.argv[1] in ('True', 'False'):\n if sys.argv[1] == 'True':\n isDarkmode = True\n else:\n print(\"Argument has to be 'True' or 'False'\")\n sys.exit()\n else:\n print(\"\"\"Set second argument to 'True'\n to start with dark mode or 'False' to start\n with light mode and third argument should be the participantID\"\"\")\n sys.exit()\n app = QtWidgets.QApplication(sys.argv)\n # variable is never used, class automatically\n # registers itself for Qt main loop:\n space = SpaceRecorder(isDarkmode, sys.argv[2])\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"reaction_test2.py","file_name":"reaction_test2.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"43127439","text":"import os, sys\nimport datetime\nimport time\nfrom schainpy.controller import Project\n\ndesc = \"USRP_test\"\nfilename = \"USRP_processing.xml\"\ncontrollerObj = Project()\ncontrollerObj.setup(id = '191', name='Test_USRP', description=desc)\n\n############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############\n######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################\npath = '/home/alex/Downloads/test_rawdata'\nfigpath = '/home/alex/Downloads'\n################# RANGO DE PLOTEO######################################\ndBmin = '30'\ndBmax = '60'\nxmin = '0'\nxmax ='24'\nymin = '0'\nymax = '600'\n########################FECHA##########################################\nstr = datetime.date.today()\ntoday = str.strftime(\"%Y/%m/%d\")\nstr2 = str - datetime.timedelta(days=1)\nyesterday = str2.strftime(\"%Y/%m/%d\")\n######################## UNIDAD DE LECTURA#############################\nreadUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader',\n path=path,\n startDate=\"2020/01/01\", #\"2020/01/01\",#today,\n endDate= \"2020/12/01\", #\"2020/12/30\",#today,\n startTime='00:00:00',\n endTime='23:59:59',\n delay=0,\n #set=0,\n online=0,\n walk=1)\n\nopObj11 = readUnitConfObj.addOperation(name='printInfo')\n#opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')\n#######################################################################\n################ OPERACIONES DOMINIO DEL TIEMPO########################\n#######################################################################\n\nprocUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())\n'''\nopObj11 = procUnitConfObjA.addOperation(name='PulsePairVoltage', optype='other')\nopObj11.addParameter(name='n', value='256', format='int')\nopObj11.addParameter(name='removeDC', value=1, format='int')\n'''\n'''\ntype=\"power\"\nopObj10 = procUnitConfObjA.addOperation(name='ScopePlot', optype='external')\n#opObj10.addParameter(name='id', value='12')\nopObj10.addParameter(name='wintitle', value=type )\nopObj10.addParameter(name='type', value=type)\n106 32\n102 64\n99 128\n99 256s\n'''\n'''\ntype=\"WeatherPower\"\nopObj10 = procUnitConfObjA.addOperation(name='PulsepairPowerPlot', optype='external')\n#opObj10.addParameter(name='id', value='12')\nopObj10.addParameter(name='wintitle', value=type )\n\nopObj11 = procUnitConfObjA.addOperation(name='PulsepairVelocityPlot', optype='other')\nopObj11.addParameter(name='xmax', value=8)\n'''\n\ncontrollerObj.start()\n","sub_path":"schainpy/scripts/test_sim0005.py","file_name":"test_sim0005.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"35799655","text":"from teambuzz import view, AdminController, Controller\nfrom models import User, Project, Group\nfrom google.appengine.ext import db\nimport logging\n\nclass Index(AdminController):\n errors = {\n '1': ('success', 'Recalculation complete'),\n }\n\n @view('/admin/index.html')\n def get(self):\n return {}\n\nclass Stats(AdminController):\n @view('/admin/stats.html')\n def get(self):\n stats = {}\n stats['volunteers'] = {}\n stats['volunteers']['count'] = 0\n stats['volunteers']['count_has_group'] = 0\n stats['volunteers']['count_no_group'] = 0\n stats['volunteers']['count_has_project'] = 0\n stats['volunteers']['count_no_project'] = 0\n users = User.all()\n for user in users:\n stats['volunteers']['count'] += 1\n if user.group == None:\n stats['volunteers']['count_no_group'] += 1\n else:\n stats['volunteers']['count_has_group'] += 1\n if user.project == None:\n stats['volunteers']['count_no_project'] += 1\n else:\n stats['volunteers']['count_has_project'] += 1\n stats['groups'] = {}\n stats['groups']['count'] = Group.all().count()\n stats['groups']['total_spots'] = sum(map(lambda group: group.slots, Group.all()))\n stats['groups']['spots_taken'] = sum(map(lambda group: group.spots_taken, Group.all()))\n stats['groups']['unused_spots'] = sum(map(lambda group: group.spots_taken, Group.all()))\n stats['projects'] = {}\n stats['projects']['count'] = Project.all().count()\n stats['projects']['total_spots'] = sum(map(lambda project: project.max_volunteers, Project.all()))\n stats['projects']['spots_taken'] = sum(map(lambda project: project.spots_taken, Project.all()))\n stats['projects']['unused_spots'] = stats['projects']['total_spots'] - stats['projects']['spots_taken']\n return stats\n\nclass Init(Controller):\n def makeBasicUser(self, username):\n email = username + \"@gatech.edu\"\n password = username\n user = User.create(username, email, password)\n return user\n\n def get(self):\n \"\"\" init the datastore with some test data.\n\n assumes the datastore is clear.\n \"\"\"\n # a basic check to make sure the datastore is clear\n if Greek.all().count() > 0:\n return\n\n # Create a project\n kitten = Project()\n kitten.name = \"Kitten Rescue\"\n kitten.max_volunteers = 3\n kitten.location = \"All around Atlanta.\"\n kitten.type_of_work = \"Outdoor\"\n kitten.description = \"We will save kittens from trees all over Atlanta.\"\n kitten.put()\n\n soup = Project()\n soup.name = \"Soup Making\"\n soup.max_volunteers = 5\n soup.description = \"You will make delicious soup.\"\n soup.put()\n\n huge = Project()\n huge.name = \"Huge Project\"\n huge.max_volunteers = 20\n huge.description = \"This is a darn huge project. With 20 people what CAN'T we do?\"\n huge.put()\n\n # Make a user with a pending PC app\n u = self.makeBasicUser(\"pending\")\n pc_app = PCApplication(response=\"Here is the sample responses to the questions\")\n pc_app.put()\n u.pc_application = pc_app\n u.put()\n\n # Put a user in the kitten project\n u = self.makeBasicUser(\"kitten\")\n u.project = kitten\n u.put()\n\n # Create a PC for the soup project\n u = self.makeBasicUser(\"souppc\")\n u.project = soup\n u.is_pc = True\n u.put()\n\n # Make a group for the HUGE project\n knights_group = Group(name=\"Knights who say Ni!\", password=\"shrubbery\", project=huge, slots=5)\n knights_group.put()\n\n leader = self.makeBasicUser(\"leader\")\n leader.joinGroup(knights_group)\n leader.is_group_leader = True\n leader.is_pc = True\n leader.put()\n\n knights = [\"lancelot\", \"gawain\", \"gallahad\", \"mordred\"]\n for knight in knights:\n k = self.makeBasicUser(knight)\n k.joinGroup(knights_group)\n k.put()\n\n # Make a full project\n full = Project(name=\"Full Project\",\n max_volunteers = 5,\n description = \"This was full so quickly...\")\n full.put()\n\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n for j in range(5):\n u = self.makeBasicUser(alphabet[j])\n u.project = full\n u.put()\n\n # Init the Greek Affliations\n for g_name in GREEK_AFFS:\n g = Greek(name=g_name)\n g.put()\n\n # Add the possible phases\n phases = [\n [\"pc_apps\", datetime.date(2014,9,5), datetime.date(2014,10,18)],\n [\"group_create\", datetime.date(2014,9,19), datetime.date(2014,10,9)],\n [\"group_join\", datetime.date(2014,9,26), datetime.date(2014,10,9)],\n [\"group_registration\", datetime.date(2014,9,19), datetime.date(2014,10,9)],\n [\"individual_registration\", datetime.date(2014,10,10), datetime.date(2014,10,21)]\n ]\n for phase_args in phases:\n phase = Phase(name=phase_args[0], start_date=phase_args[1], end_date=phase_args[2])\n phase.put()\n\n # Add a group that users can join\n nice_group = Group(name=\"A nice group for nice people\", password=\"nice!\", project=huge, slots=5)\n nice_group.put()\n\n # Make a user that has no project\n lonely_user = self.makeBasicUser(\"lonely\")\n lonely_user.put()\n\n return \"done\"\n\nclass Recalculate(Controller):\n @view(None)\n def get(self):\n # fix any references to non-existance objects\n users = User.all()\n for user in users:\n try:\n project = user.project\n except db.ReferencePropertyResolveError as e:\n logging.info('Resolving property resolve error on user.project for {}\\'s project {}'.format(user.key(), user._project))\n user.project = None\n user.put()\n\n try:\n group = user.group\n except db.ReferencePropertyResolveError as e:\n user.group = None\n user.put()\n\n groups = Group.all()\n for group in groups:\n try:\n project = group.project\n except db.ReferencePropertyResolveError as e:\n group.project = None\n group.put()\n\n projects = Project.all()\n for project in projects:\n volunteers = project.volunteers.filter('group =', None)\n num_volunteers = volunteers.count()\n groups = project.groups\n num_group_volunteers = sum([group.slots for group in groups])\n spots = num_volunteers + num_group_volunteers\n project.setSpotsTaken(spots, True)\n\n groups = Group.all()\n for group in groups:\n members = group.members\n num_members = members.count()\n group.spots_taken = num_members\n group.put()\n\n return self.redirect('/admin', {'error': '1'})\n","sub_path":"controllers/admin/Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":7178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225666634","text":"# Library inmport\nimport time\nimport requests\nfrom selenium.webdriver import Chrome, ChromeOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\nfrom selenium.webdriver.remote import file_detector\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n# deep Lに突っ込む\ndef translate(text):\n driver = webdriver.Chrome(ChromeDriverManager().install())\n\n driver.get(\"https://www.deepl.com/ja/translator\")\n time.sleep(3)\n\n driver.find_element_by_xpath(\"//*[@id='dl_translator']/div[5]/div[3]/div[1]/div[2]/div[1]/textarea\").send_keys(text)\n time.sleep(10)\n\n after = driver.find_element_by_xpath(\"//*[@id='dl_translator']/div[5]/div[3]/div[3]/div[3]/div[1]/textarea\").get_attribute('value')\n driver.quit()\n \n return after\n\n\n\n# main処理\ndef main():\n # 必要情報の入力\n search_keyword = input('Enter word:>>>')\n pages = input('Enter number how many pages do you want to get>>>')\n if pages.isdecimal()==False:\n print('Error...input number. execution is terminated.')\n exit()\n file_name = input('Enter file name>>>')\n\n # 初期設定\n col = ['title', 'link', 'publisher', 'abstract', 'abstract_ja']\n df = pd.DataFrame([], columns=col)\n page = 0\n\n # driverを起動、Google Chromeを使うこと\n driver = webdriver.Chrome(ChromeDriverManager().install())\n # Webサイトを開く\n driver.get(\"https://scholar.google.com/\")\n time.sleep(3)\n # 検索窓に入力\n driver.find_element_by_name(\"q\").send_keys(search_keyword)\n # 検索ボタンクリック\n driver.find_element_by_name(\"btnG\").click()\n time.sleep(3)\n \n # 繰り返し処理\n while page < int(pages):\n current_url = driver.current_url\n html = requests.get(current_url)\n soup = BeautifulSoup(html.text, \"lxml\")\n articles = soup.find_all(class_=\"gs_rt\")\n abst11 = soup.find_all(class_=\"gs_rs\")\n\n for article, abst in zip(articles, abst11):\n try:\n title = article.text\n link = article.find_all(\"a\")[0].get('href')\n publisher = link[8:link.find(\"/\", 8)]\n abst1 = abst.text.replace('\\n', ' ')\n # translate with deepL\n abst1_ja = translate(abst1)\n\n element = pd.Series([title, link, publisher, abst1, abst1_ja], index = col)\n df = df.append(element, ignore_index=True)\n except:\n pass\n \n # 次のページへ\n driver.find_element_by_xpath(\"//*[@id='gs_n']/center/table/tbody/tr/td[12]/a\").click()\n time.sleep(3)\n page += 1\n df.to_csv(file_name+'.csv')\n\nif __name__ == '__main__':\n main()\n","sub_path":"Article getter.py","file_name":"Article getter.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"240530182","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Header\nfrom geometry_msgs.msg import PolygonStamped, Point32, PointStamped\nimport tf \n\ndef main():\n '''uthai_control Publisher'''\n tf_listen = tf.TransformListener()\n pub_ssp = rospy.Publisher('uthai/spp', PolygonStamped, queue_size=3)\n pub_com = rospy.Publisher('uthai/com', PointStamped, queue_size=3)\n rospy.init_node('uthai_control')\n rate = rospy.Rate(10) # 10hz\n\n spp_msg = PolygonStamped()\n # spp_msg.header = Header()\n spp_msg.header.frame_id = \"r_foot_ft_link\"\n com_msg = PointStamped()\n # com_msg.header = Header()\n com_msg.header.frame_id = \"base_footprint\"\n flag = 1\n while not rospy.is_shutdown():\n \n spp_msg.header.stamp = rospy.Time.now()\n com_msg.header.stamp = rospy.Time.now()\n spp_msg.polygon.points.append(Point32(0.07, 0.07, 0))\n spp_msg.polygon.points.append(Point32(0.07, -0.07, 0))\n spp_msg.polygon.points.append(Point32(-0.07, -0.07, 0))\n spp_msg.polygon.points.append(Point32(-0.07, 0.07, 0))\n \n if flag:\n com_msg.point.x += 0.005\n else:\n com_msg.point.x -= 0.005\n if com_msg.point.x > 0.1:\n flag = 0\n elif com_msg.point.x < -0.1:\n flag = 1\n \n # rospy.loginfo(spp_msg)\n # (trans,rot) = tf_listen.lookupTransformFull('/r_foot_ft_link','/base_footprint')\n (trans,rot) = tf_listen.lookupTransform('/r_foot_ft_link','/l_foot_ft_link', rospy.Time(0))\n # rospy.loginfo(trans)\n rospy.loginfo(rot)\n # rospy.loginfo(com_msg)\n pub_ssp.publish(spp_msg)\n pub_com.publish(com_msg)\n rate.sleep()\n\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"uthai_control/src/uthai_control_pub.py","file_name":"uthai_control_pub.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"155709280","text":"from django.conf.urls.defaults import url, patterns\n\nurlpatterns = patterns('blog.views',\n url(r'^init$', 'init', name='init'),\n\n url(r'^$', 'index', name='index'),\n url(r'^(?P\\d+)$', 'index', name='index'),\n url(r'^login$', 'login', name='login'),\n url(r'^profile$', 'profile', name='profile'),\n url(r'^dashboard$', 'dashboard', name='dashboard'),\n url(r'^dashboard/(?P\\d+)$', 'dashboard', name='dashboard'),\n url(r'^new$', 'new_post', name='new_post'),\n url(r'^edit/(?P\\d+)$', 'edit_post', name='edit_post'),\n url(r'^delete/(?P\\d+)$', 'delete_post', name='delete_post'),\n url(r'^logout$', 'logout', name='logout'),\n)\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"539835176","text":"from source.UpdateData.saveLC5 import *\r\nfrom utility import threadpool\r\n\r\n\r\ndef updateLC5Data(lc5Dir):\r\n for folder in lc5Dir:\r\n files = os.listdir(folder)\r\n affectedRows = 0\r\n for filename in files:\r\n affectedRows += saveLC5(folder, filename)\r\n print (\"All together %d rows inserted.\" % (affectedRows))\r\n\r\ndef createLC5DataRequests(lc5Dir):\r\n args = []\r\n for folder in lc5Dir:\r\n files = os.listdir(folder)\r\n for filename in files:\r\n args.append(tuple([[folder, filename], {}]))\r\n requests = threadpool.makeRequests(saveLC5, args)\r\n return requests\r\n","sub_path":"source/UpdateData/LC5Data.py","file_name":"LC5Data.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"606957922","text":"def read4(buf):\n # ref\n for i in range(4):\n buf[i] = 'a'\n return 4\n\n\nclass Solution0:\n def __init__(self):\n self.buffer = [''] * 4\n self.offset = 0\n self.bufsize = 0\n\n def readn_multiple(self, buf, n):\n read_bytes = 0\n\n eof = False\n while not eof and read_bytes < n:\n if self.bufsize > 0:\n real_read = self.bufsize if read_bytes + self.bufsize < n else n - read_bytes\n buf.extend(self.buffer[self.offset:self.offset + self.bufsize])\n self.bufsize -= real_read\n self.offset += real_read\n read_bytes += real_read\n else:\n _read = read4(self.buffer)\n self.offset = 0\n self.bufsize = _read\n if not _read:\n eof = False\n\n return read_bytes\n\n\nclass Solution:\n def __init__(self):\n self.buffer = [''] * 4\n self.offset = 0\n self.bufsize = 0\n\n def read(self, buf, n):\n readbytes = 0\n eof = False\n while not eof and readbytes < n:\n sz = self.bufsize if self.bufsize > 0 else read4(self.buffer)\n if self.bufsize == 0 and sz < 4:\n eof = True\n _bytes = min(n - readbytes, sz)\n buf.extend(self.buffer[self.offset:self.offset + _bytes])\n self.offset = (self.offset + _bytes) % 4\n self.bufsize -= _bytes\n readbytes += _bytes\n\n return readbytes\n","sub_path":"Python/readn_multiple.py","file_name":"readn_multiple.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"639032370","text":"from model import Location\nfrom flask_restful import Resource, abort\nfrom util import require_permission, get_request_data\n\nclass SpecLocationController(Resource):\n def get(self, location_id):\n require_permission(3)\n try:\n data = Location.objects(id = location_id)[0]\n except:\n abort(404)\n return data.json()\n\n def put(self, location_id):\n require_permission(3)\n try:\n data = Location.objects(id = location_id)[0]\n except:\n abort(404)\n name = get_request_data(\"name\", required = False)\n note = get_request_data(\"note\", required = False)\n if name != None:\n data.name = name\n if note != None:\n data.note = note\n data.save()\n return data.json()\n \n\n def delete(self, location_id):\n require_permission(3)\n try:\n data = Location.objects(id = location_id)[0]\n data.delete()\n except:\n abort(404)\n return {\n \"result\": \"Ok\"\n }\n\n\n\nclass GenLocationController(Resource):\n def post(self):\n require_permission(3)\n name = get_request_data(\"name\")\n note = get_request_data(\"note\", required = False)\n loc = Location(name = name, note = note)\n loc.save()\n return loc.json()\n \n def get(self):\n require_permission(3)\n data = Location.objects()\n return {\n \"result\": [i.json() for i in data]\n }","sub_path":"controller/locationController.py","file_name":"locationController.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315220577","text":"# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup # sudo pip install beautifulsoup4\nfrom selenium import webdriver # sudo pip install selenium\nfrom selenium.webdriver.common.keys import Keys\nimport xlrd # sudo pip install xlrd\nimport xlwt # sudo pip install xlwt\nimport time\nimport os.path\nimport math\n\npathOfExcelTemplate = raw_input(\"Enter the file path of the excel sheet with the DNA Sequences:\\n\") # file path of\n# excel template that user made (contains all sequences)\ntype(pathOfExcelTemplate)\n\nnumberOfSequences = input(\"Enter number of sequences in excel sheet:\\n\") # asking for the number of sequences\n# that need to be read\ntype(numberOfSequences)\n\nnumberOfCycles = int(math.ceil(numberOfSequences/199.0)) # IDT can only read 200 sequences at a time.\n# Finding the number of loops that need to be performed to read the requested number of sequences\n# Converting input to integer and rounding integer up to account for remainder\n\nstyle0 = xlwt.easyxf('font: name Times New Roman, color-index black, bold on', num_format_str='#,##0.00')\n# setting style for excel sheet output\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\nCONFIG_PATH = os.path.join(ROOT_DIR, 'chromedriver') # creating a universal path for the chrome driver\n\ndriver = webdriver.Chrome(executable_path=CONFIG_PATH) # driver is assigned to the chrome driver\ndriver.get(\"https://www.idtdna.com/pages/products/custom-dna-rna/dna-oligos/custom-dna-oligos\") # open website link\ntime.sleep(3) # waiting for website to load, adjust based on internet speed...\n\nbuttonCookies = driver.find_element_by_xpath(\"//a[@class='cc-btn cc-dismiss']\").click() # close cookies dialog\n\ndriver.execute_script(\"window.scrollTo(0, 200)\") # scroll page down to get access to button\ntime.sleep(1) # wait for scroll to complete\nbuttonOrderNow = driver.find_element_by_xpath(\"//a[@class='btn btn_org']\").click() # press order now button\ntime.sleep(4) # wait for page to load\n\nsequencesNumberInTemplate = 1 # Sequence number that is being read from the excel template\n\nworkBookOutput = xlwt.Workbook() # creating workbook for output\nsheetWrite = workBookOutput.add_sheet('Sheet 1') # creating sheet in workbook, naming it 'Sheet 1'\n\n# making headers for the output excel file, using style0\nsheetWrite.write(0, 0, \"GC (%)\", style0)\nsheetWrite.write(0, 1, \"Tm\", style0)\nsheetWrite.write(0, 2, \"DeltaG (kcal/mole)\", style0)\n# end making headers\n\n# counters for variables being scraped\ncounterGC = 1 # glucose cytosine percent\ncounterTM = 1 # melting temperature\ncounterDG = 1 # delta G\n# end counter declarations\n\nfor j in range(0, numberOfCycles): # number of loops needed since IDT only takes 200 sequences at a time\n # finding and pressing blue bulk input button\n bulkInputButton = driver.find_element_by_xpath(\"//button[@class='btn btn-info btn-sm btn-block']\").click()\n time.sleep(2) # waiting for animation to end\n\n textArea = driver.find_element_by_xpath(\n \"//textarea[starts-with(@placeholder, '----------N')][@class='form-control']\")\n textArea.send_keys(Keys.TAB) # activating field by sending a tab\n textArea.clear() # clearing input field\n\n selectorItem = driver.find_element_by_id('delimiter') # defining selector\n for option in selectorItem.find_elements_by_tag_name('option'): # iterating through options in selector\n if option.text == 'Comma':\n option.click() # pressing selector that corresponds to 'Comma' when found\n break\n\n excelTemplateFile = xlrd.open_workbook(pathOfExcelTemplate) # accessing user inputted excel template of sequences\n sheet = excelTemplateFile.sheet_by_index(0) # accessing sheet 1 of excel file\n numberOfEntries = 0 # number of sequences inputted into text area\n maxLimit = 199*(j+1) # max sequence number that can be inputted in this iteration\n while sequencesNumberInTemplate < maxLimit:\n if sequencesNumberInTemplate <= numberOfSequences:\n cells = sheet.row_slice(rowx=sequencesNumberInTemplate, start_colx=1, end_colx=4)\n textArea.send_keys(sequencesNumberInTemplate, \",\")\n for cell in cells:\n textArea.send_keys(cell.value, \",\")\n textArea.send_keys(\"\\n\")\n sequencesNumberInTemplate = sequencesNumberInTemplate + 1\n numberOfEntries = numberOfEntries + 1\n else:\n break\n\n updateSequencesButton = driver.find_element_by_xpath(\"//button[@class='btn btn-primary']\").click()\n time.sleep(2)\n\n if numberOfEntries > 99: # confirm button only shows when greater than 99 entries inputted\n confirmContinueUpdateButton = driver.find_element_by_id('modal-question-component-primary-btn').click()\n\n print(\"loading... please wait approx 25 seconds...\")\n time.sleep(25)\n\n print(\"Sequences successfully imported into IDT! Looping again... wait for 'Done!' to close this program\")\n\n page = driver.page_source # getting page from web driver\n\n htmlOfThePage = BeautifulSoup(page, \"html.parser\") # html of the page\n\n # scraping GC and adding to excel sheet\n for node in htmlOfThePage.find_all(\"span\", {\"data-bind\": \"text: OligoCalcDetails.GC() + '%'\"}):\n for child in node.children:\n sheetWrite.write(counterGC, 0, child)\n counterGC = counterGC + 1\n\n # scraping melting temperature and adding to excel sheet\n for node in htmlOfThePage.find_all(\"span\", {\"data-bind\": \"text: OligoCalcDetails.TM() + 'ºC'\"}):\n for child in node.children:\n sheetWrite.write(counterTM, 1, child)\n counterTM = counterTM + 1\n\n # scraping DeltaG and adding to excel sheet\n for node in htmlOfThePage.find_all(\"span\", {\"data-bind\": \"text: OligoCalcDetails.DeltaG() + ' kcal/mole'\"}):\n for child in node.children:\n sheetWrite.write(counterDG, 2, child)\n counterDG = counterDG + 1\n\ndriver.close() # close website\nworkBookOutput.save('Scraper_IDT_GC_TM_DG.xls') # saving output into excel sheet\nprint('Done! saved as: Scraper_IDT_GC_TM_DG.xls')\n\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"433901585","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 30 10:54:21 2017\r\n\r\n@author: ishort\r\n\"\"\"\r\n\r\n#plotting:\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\n#%matplotlib inline\r\nimport pylab\r\n\r\nfrom functools import reduce\r\nimport subprocess\r\nimport os\r\nimport sys\r\n\r\n#General file for printing ad hoc quantities\r\n#dbgHandle = open(\"debug.out\", 'w')\r\n\r\nthisOS = \"unknown\" #default\r\nmyOS= \"\"\r\n#returns 'posix' form unix-like OSes and 'nt' for Windows??\r\nthisOS = os.name\r\nprint(\"\")\r\nprint(\"Running on OS: \", thisOS)\r\nprint(\"\")\r\n\r\nabsPath0 = \"./\" #default\r\n\r\nif thisOS == \"nt\": \r\n #windows\r\n absPath0 = subprocess.check_output(\"cd\", shell=True) \r\n backSpace = 2\r\nelif thisOS == \"posix\":\r\n absPath0 = subprocess.check_output(\"pwd\", shell=True)\r\n backSpace = 1\r\n \r\nabsPath0 = bytes.decode(absPath0)\r\n\r\n#remove OS_dependent trailing characters 'r\\n'\r\nnCharsPath = len(absPath0)\r\nnCharsPath -= backSpace\r\nabsPath0 = absPath0[0: nCharsPath]\r\n\r\nslashIndex = absPath0.find('\\\\') #The first backslash is the escape character!\r\nwhile slashIndex != -1:\r\n #python strings are immutable:\r\n absPathCopy = absPath0[0: slashIndex]\r\n absPathCopy += '/'\r\n absPathCopy += absPath0[slashIndex+1: len(absPath0)]\r\n absPath0 = absPathCopy\r\n #print(absPathCopy, absPath0)\r\n slashIndex = absPath0.find('\\\\')\r\n \r\nabsPath = absPath0 + '/'\r\n\r\n\r\n#Now get the synthetic spectrum pre-computed with ChromaStarPy\r\nmodelPath = absPath + \"Outputs/\"\r\n#outPath = absPath + \"Outputs/\"\r\n\r\n\r\nproject = \"Project\"\r\nrunVers = \"RunGas\"\r\nteff = 3600.0\r\nlogg = 1.0\r\nlog10ZScale = 0.0 \r\nlambdaStart = 695.0 \r\nlambdaStop = 700.0 \r\nfileStem = project + \"-\"\\\r\n + str(round(teff, 7)) + \"-\" + str(round(logg, 3)) + \"-\" + str(round(log10ZScale, 3))\\\r\n + \"-\" + str(round(lambdaStart, 5)) + \"-\" + str(round(lambdaStop, 5))\\\r\n + \"-\" + runVers \r\ninFile = modelPath + fileStem + \".ppress.txt\"\r\n\r\n\r\n#whichSpec = \"Ca+\"\r\n#whichSpec = [\"C\", \"N\", \"O\", \"Na\", \"Mg\", \"Si\", \"S\", \"K\", \"Ca\", \"Fe\"]\r\n#colrSpec = [\"black\", \"brown\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\", \"gray\"]\r\n#whichIon = [\"Na+\", \"Mg+\", \"Si+\", \"S+\", \"K+\", \"Ca+\", \"Fe+\"]\r\n#colrIon = [\"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\", \"gray\"]\r\nwhichSpec = [\"H2\", \"C2\", \"O2\", \"N2\", \"CO\", \"OH\", \"CN\", \"TiO\", \"CaH\", \"CaO\"]\r\ncolrSpec = [\"black\", \"brown\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\", \"gray\"]\r\nwhichIon = [\"H2+\", \"H2O\", \"CaOH\"]\r\ncolrIon = [\"black\", \"brown\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\", \"gray\"]\r\nthisSpec = 0 #default initialization (H)\r\n\r\nnumSampleDepths = 48 \r\n#numSampleDepths = 2 #debug\r\nnumSpecies = 105\r\n#numSpecies = 3 #debug\r\n\r\n#numStr = fields[0].strip() #first field is number of following records\r\n#num = int(numStr)\r\nspecies = [0.0 for i in range(numSpecies)]\r\nlogTau = [0.0 for i in range(numSampleDepths)]\r\nlogTkin = [0.0 for i in range(numSampleDepths)]\r\nlogPGas = [0.0 for i in range(numSampleDepths)]\r\nlogPe = [0.0 for i in range(numSampleDepths)]\r\nlogPP = [ [ 0.0 for j in range(numSpecies) ] for i in range(numSampleDepths)]\r\n\r\n\r\nfileTeff = 0.0\r\nfileLogg = 0.0\r\nfileLogZ = 0.0\r\n\r\n\r\nwith open(inFile, 'r') as inputHandle: \r\n \r\n #Expects number of records on first lines, then white space delimited columns of\r\n #wavelengths in nm and continuum rectified fluxes\r\n inLine = inputHandle.readline() #line of header\r\n print(inLine)\r\n fields = inLine.split()\r\n fileTeff = float(fields[1].strip())\r\n fileLogg = float(fields[3].strip())\r\n fileZ = float(fields[5].strip())\r\n if ( (fileTeff != teff) or\r\n (fileLogg != logg) or\r\n (fileLogZ != log10ZScale) ):\r\n print(\" \")\r\n print(\" !!!!!!!!!!!!!!!!!!!!!!\")\r\n print(\" \")\r\n print(\"Mismatch between input file name and stellar paramters in input file!\")\r\n print(\" \")\r\n print(\" !!!!!!!!!!!!!!!!!!!!!!\")\r\n print(\" \") \r\n\r\n#Header line \r\n inLine = inputHandle.readline()\r\n print(inLine)\r\n \r\n \r\n #Get the synthetic spectrum\r\n for i in range(numSampleDepths):\r\n #Begin reading data - each depthwise record is two lines:\r\n #line 1 has depth and environmental paramters\r\n #line 2 has specieswise partial pressures\r\n inLine1 = inputHandle.readline()\r\n #print(inLine1)\r\n fields = inLine1.split()\r\n logTau[i] = float(fields[1].strip())\r\n logTkin[i] = float(fields[3].strip())\r\n logPGas[i] = float(fields[6].strip())\r\n logPe[i] = float(fields[9].strip()) \r\n #Relative to total gas pressure for plot:\r\n logPe[i] = logPe[i] - logPGas[i]\r\n \r\n inLine2 = inputHandle.readline()\r\n #print(inLine2)\r\n fields = inLine2.split()\r\n for j in range(numSpecies):\r\n species[j] = fields[2*j].strip()\r\n #if (species[j] == whichSpec):\r\n # thisSpec = j\r\n logPP[i][j] = float(fields[(2*j) + 1].strip())\r\n #Relative to total gas pressure for plot:\r\n logPP[i][j] = logPP[i][j] - logPGas[i]\r\n #print(\"j \", j, \" 2*j \", 2*j, \" 2*j+1 \", (2*j)+1, \" species \", species[j], \" pp \", logPP[i][j])\r\n \r\n \r\n#plot some partial pressures \r\n#plt.title('Synthetic spectrum')\r\nplt.figure()\r\nplt.subplot(1, 1, 1) \r\n#plt.ylabel(r'$\\log P$ dynes cm$^{\\rm -2}$', fontsize=14)\r\nplt.ylabel(r'$\\log_{10} (P/P_{\\rm H})$', fontsize=14)\r\nplt.xlabel(r'$\\log_{10}\\tau_{\\rm Ros}$') \r\nxMin = min(logTau)\r\nxMax = max(logTau)\r\npylab.xlim(xMin, xMax)\r\npylab.ylim(-12.0, 0.0) \r\n#thisSpec = 3\r\ncolr = 0\r\n\r\nfor wS in whichSpec:\r\n \r\n for i in range(numSpecies):\r\n if (species[i] == wS):\r\n thisSpec = i\r\n print(\"Species: \", species[thisSpec])\r\n\r\n #print(\"At plot:\")\r\n #print (\"logPP \", [logPP[i][0] for i in range(numSampleDepths)]) \r\n # skip first depth point [i=0] - upper boundary condition:\r\n pylab.plot( [logTau[i] for i in range(1, numSampleDepths)],\\\r\n [logPP[i][thisSpec] for i in range(1, numSampleDepths)],\\\r\n color=colrSpec[colr], linewidth=2)\r\n pylab.text(logTau[4], logPP[4][thisSpec], species[thisSpec],\\\r\n color=colrSpec[colr], fontsize=13, weight='bold')\r\n colr+=1\r\n \r\n#pylab.plot(logTau, logPe, 'o', color='black')\r\n#pylab.text(logTau[numSampleDepths-3], logPe[numSampleDepths-3], 'Pe',\\\r\n# color='black', fontsize=13, weight='bold')\r\n\r\ncolr = 0 \r\nfor wI in whichIon:\r\n \r\n for i in range(numSpecies):\r\n if (species[i] == wI):\r\n thisSpec = i\r\n print(\"Species: \", species[thisSpec])\r\n \r\n pylab.plot([logTau[i] for i in range(1, numSampleDepths)],\\\r\n [logPP[i][thisSpec] for i in range(1, numSampleDepths)],\\\r\n '--', color=colrIon[colr], linewidth=2)\r\n pylab.text(logTau[numSampleDepths-8], logPP[numSampleDepths-8][thisSpec],\\\r\n species[thisSpec], color=colrIon[colr], fontsize=13, weight='bold')\r\n colr+=1\r\n\r\n#Save as encapsulated postscript (eps) for LaTex\r\nepsName = fileStem + \"Mols.eps\"\r\nplt.savefig(epsName, format='eps', dpi=1000)","sub_path":"PPressPlotMols.py","file_name":"PPressPlotMols.py","file_ext":"py","file_size_in_byte":7157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"566864705","text":"#!/usr/bin/env python\n#-*-coding:utf-8\n\n### Reference ###\n# Author information: Xiaodi Yang, China Agricultural University, email: xiao_di_yang@163.com.\n# Cititation: Yamg,X. et al. (2021) Transfer learning via multi-scale convolutional neural layers for human-virus protein-protein interaction prediction. Bioinformatics.\n# Part of the code was modified from https://github.com/muhaochen/seq_ppi and the corresponding reference is: \n# Chen,M. et al. (2019) Multifaceted protein-protein interaction prediction based on Siamese residual RCNN. Bioinformatics, 35, i305–i314.\n\nfrom __future__ import division\nimport time\nfrom numpy.random import seed\nseed(2066)\nfrom tensorflow import set_random_seed\nset_random_seed(2066)\n\nstart=time.ctime()\nimport os, sys\nif '../embeddings' not in sys.path:\n sys.path.append('../embeddings')\n\nfrom seq2pssm import s2p\n\nimport keras\n\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Activation, Dropout, merge\nfrom keras.layers.merge import concatenate\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.pooling import MaxPooling1D, GlobalMaxPooling1D\nfrom keras.optimizers import Adam\n\nimport numpy as np\nfrom numpy import linalg as LA\nimport scipy\nimport sklearn\nfrom sklearn.metrics import roc_auc_score, average_precision_score\n\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\n\n# Set GPU memory fraction\ngpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.80)\nsession=tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\nKTF.set_session(session)\n\n\n\n# Parameter setting\nid1_index = 0\nid2_index = 1\nlabel_index = 2\n\ntest_file, test_id2seq_file, train_virus, test_virus, batch_size, hidden_dim, dense_dim, n_epochs = sys.argv[1:]\nn_epochs = int(n_epochs)\n\nseq_size = 2000\n# batch_size = 64\n# hidden_dim = 64\n# dense_dim = 512\n# n_epochs = 100\nlr = 0.0001\nkernel_size = 3\npooling_size = 2\n\nid2seqindex = {}\nseqs = []\nseqindex = 0\nprint(test_id2seq_file)\nfor line in open(test_id2seq_file):\n line = line.strip().split('\\t')\n id2seqindex[line[0]] = seqindex\n seqs.append(line[1])\n seqindex += 1\n\nfrom tqdm import tqdm\nseq2p = s2p()\nindex2id1,index2id2={},{}\nraw_data = []\nid_array = []\nseq_array = []\nid2index = {}\nindex = 0\nfor line in tqdm(open(test_file)):\n line = line.strip().split('\\t')\n if line[id1_index] not in id2index:\n id2index[line[id1_index]] = index\n index += 1\n id_array.append(line[id1_index])\n seq_array.append(seqs[id2seqindex[line[id1_index]]])\n id1=line[id1_index]\n line[id1_index] = id2index[line[id1_index]]\n index1=line[id1_index]\n index2id1[index1]=id1\n if line[id2_index] not in id2index:\n id2index[line[id2_index]] = index\n index += 1\n id_array.append(line[id2_index])\n seq_array.append(seqs[id2seqindex[line[id2_index]]])\n id2=line[id2_index]\n line[id2_index] = id2index[line[id2_index]]\n index2=line[id2_index]\n index2id2[index2]=id2\n raw_data.append(line)\nprint(len(raw_data))\n\ndim = 20\nseq_tensor = np.array([seq2p.pssm_normalized(id, line, seq_size) for id, line in zip(tqdm(id_array),tqdm(seq_array))], dtype='int32')\ndel id_array\ndel seq_array\n\nseq_index1 = np.array([line[id1_index] for line in tqdm(raw_data)])\nseq_index2 = np.array([line[id2_index] for line in tqdm(raw_data)])\n\nclass_map = {'0':1,'1':0}\nclass_labels = np.zeros((len(raw_data), 2))\nfor i in range(len(raw_data)):\n class_labels[i][class_map[raw_data[i][label_index]]] = 1.\nprint(class_labels)\n\nfrom sklearn.model_selection import KFold, StratifiedKFold, ShuffleSplit\nkf = StratifiedKFold(n_splits=5, random_state=2066, shuffle=True)\ntrain_test = []\nprint(class_labels[:,0])\nfor train, test in kf.split(class_labels[:,0],class_labels[:,0]):\n print(np.sum(class_labels[train], 0)[0],np.sum(class_labels[train], 0)[1])\n train_test.append((train, test))\n\nprint (len(train_test))\n\n# initialization\nn_model = 0\nn_hit = 0\nn_total = 0\nn_pos = 0\nn_true_pos = 0\nn_false_pos = 0\nn_true_neg = 0\nn_false_neg = 0\n\nfrom keras.utils import plot_model\nfrom collections import Counter\nfrom keras.models import load_model\n\ntrain_file='../results/'+train_virus+'_cnnpssm.txt'\nfor train, test in train_test:\n n_model+=1\n # Load model of train dataset\n merge_model=load_model(train_file+str(n_model)+'.h5')\n print(seq_index1[train][0])\n print(merge_model.get_weights()[0][0][0])\n print(class_labels[train][:,0])\n # Set class weight for samples\n counter = Counter(class_labels[train][:,0])\n majority = max(counter.values())\n class_weight = {cls: float(majority / count) for cls, count in counter.items()}\n print(class_weight)\n # Test the model\n pred = merge_model.predict([seq_tensor[seq_index1[test]], seq_tensor[seq_index2[test]]])\n # Output prediction scores (Format: 'label\\tscore_t\\tscore_f\\tid1\\tid2\\n')\n w = open(test_virus+'_'+train_virus+'_cross_viral_test_score'+str(n_model),'w')\n for i in range(len(class_labels[test])):\n n_total += 1\n w.write(str(class_labels[test][i][0])+'\\t'+str(pred[i][0])+'\\t'+str(pred[i][1])+'\\t'+str(index2id1[seq_index1[test][i]])+'\\t'+str(index2id2[seq_index2[test][i]])+'\\n')\n if np.argmax(class_labels[test][i]) == np.argmax(pred[i]):\n n_hit += 1\n if class_labels[test][i][0] > 0.:\n n_pos += 1.\n if pred[i][0] > pred[i][1]:\n n_true_pos += 1\n else:\n n_false_neg += 1\n else:\n if pred[i][0] > pred[i][1]:\n n_false_pos += 1\n else:\n n_true_neg += 1\n w.close()\n\n# Calculate metrics\naccuracy = n_hit / n_total\nprec = n_true_pos / (n_true_pos + n_false_pos)\nrecall = n_true_pos / n_pos\nspec = n_true_neg / (n_true_neg + n_false_pos)\nf1 = 2. * prec * recall / (prec + recall)\nprint (accuracy, prec, recall, f1)\n\nresult_file = '../results/'+test_virus+'_'+train_virus+'_cross_viral_test.txt'\nbasename = test_virus+'_'+train_virus+'_cross_viral_test_score'\nos.system('cat '+basename+'1 '+basename+'2 '+basename+'3 '+basename+'4 '+basename+'5 > '+ result_file)\ndata=np.genfromtxt(result_file, dtype=str)\ny = data[:,0]\nx = data[:,1]\ny = y.astype(float)\nx = x.astype(float)\nauc = roc_auc_score(y,x)\nauprc = average_precision_score(y,x)\n\nend=time.ctime()\nw = open('../Run_result.txt','a')\nif os.popen(\"grep $'Source' ../Run_result.txt\").read():pass\nelse:w.write('Source\\tTarget\\tMethod\\tBatch_size\\tSequence_size\\tn_epochs\\tlearning_rate\\tAUC\\tAUPRC\\tAccuracy\\tPrecision\\tRecall\\tSpecificity\\tF1\\tStart\\tEnd\\n')\nw.write('Human-' + train_virus + '\\tHuman-' + test_virus + '\\tCross viral test\\t' + str(batch_size) + '\\t' + str(seq_size) + '\\t' + str(n_epochs) + '\\t' + str(lr) + '\\t%.3f'%auc + '\\t%.3f'%auprc + '\\t%.3f'%accuracy + '\\t%.3f'%prec + '\\t%.3f'%recall + '\\t%.3f'%spec + '\\t%.3f'%f1 + '\\t'+str(start) + '\\t' + str(end) + '\\n')\n","sub_path":"script/cnnpssm_cross_viruses.py","file_name":"cnnpssm_cross_viruses.py","file_ext":"py","file_size_in_byte":6872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"469635720","text":"## 2. The Empirical Probability ##\n\nheads = 56\ntotal_times = 100\np_tail = (total_times - heads) / total_times\n#Six died die 200 times\nsix = 28\ntimes = 200\np_six = six / times\n\np_odd = 102/times\n\nprint(p_tail)\nprint(p_six)\nprint(p_odd)\n\n## 3. Probability as Relative Frequency ##\n\np_heads_1 = (300 - 162) / 300\npercentage_1 = p_heads_1 * 100\n\np_heads_2 = (5000 - 2450) / 5000\npercentage_2 = p_heads_2 * 100\n\n## 4. Repeating an Experiment ##\n\n# INITIAL CODE\nfrom numpy.random import seed, randint\n\nseed(1)\n\ndef coin_toss():\n if randint(0,2) == 1:\n return 'HEAD'\n else:\n return 'TAIL'\n \nprobabilities = []\nheads = 0\n\nfor n in range(1, 10001):\n outcome = coin_toss()\n if (outcome == 'HEAD'):\n heads += 1\n current_probability = heads / n\n probabilities.append(current_probability)\n \n# Uncomment above and complete code from here\n\n## 5. The True Probability Value ##\n\nlife_inserance = 87\nlife_car_inserance = 40\nhouse_inserance = 63\none_type = 160\ntotal = 200 \np_l = 87 / 200\n\np_l_and_c = 40 / 200\n\np_h = house_inserance / total \n\np_no = (total - one_type) / total\n\n\n\n## 6. The Theoretical Probability ##\n\np_5 = 1/6\n\np_ht = (1/2) * (1/2)\n\np_tt = (1/2) * (1/2)\n\n## 7. Events vs. Outcomes ##\n\np_even = 3/6\n\np_odd_no_3 = 2 / 6\n\np_odd_greater_5 = 0\n\n\n## 8. A Biased Die ##\n\np_blue = 10 / 100\np_red = 90 / 100","sub_path":"Probability/fundamentals/Estimating Probabilities-377.py","file_name":"Estimating Probabilities-377.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"382495900","text":"\ndef minHeightBSTHelper(array):\n return minHeightBST(array, BST(None))\n\n\n# array, BST, startIdx, endIdx\n# [ 1, 2, 5, 7, 10, 13, 14, 15, 22]\n\n# insert middleIdx value to BST\n# recursivly call minHeightBSTHelper(array, BST, startIdx, midIdx - 1)\n# recursivly call minHeightBstHelper(array, BST, midIdx, endIdx)\n\ndef minHeightBST(array):\n return minHeightBSTHelper(array, 0, len(array) - 1)\n\n# get middleIdx\n# get middleValue\n# create BST with middle value\n# create BST.left with left array\n# create BST.right with right array\n\n\ndef minHeightBSTHelper(array, startIdx, endIdx):\n if endIdx < startIdx:\n return None\n\n middleIdx = (startIdx + endIdx) // 2\n bst = BST(array[middleIdx])\n\n bst.left = minHeightBSTHelper(array, startIdx, middleIdx - 1)\n bst.right = minHeightBSTHelper(array, middleIdx + 1, endIdx)\n\n return bst\n\n\ndef printBST(bst):\n if bst is None:\n return\n\n printBST(bst.left)\n print(bst.value)\n printBST(bst.right)\n\n\nclass BST:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if value < self.value:\n if self.left is None:\n self.left = BST(value)\n else:\n self.left.insert(value)\n else:\n if self.right is None:\n self.right = BST(value)\n else:\n self.right.insert(value)\n\n\nbst = minHeightBST([1, 2, 5, 7, 10, 13, 14, 15, 22])\nprintBST(bst)\n","sub_path":"minHeightBST.py","file_name":"minHeightBST.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"458336437","text":"import sys\nfrom PyQt5 import QtWidgets\nfrom core import Client, ServerInterchange\nfrom ui import GuiChatroomWindow, GuiMainWindow\n\n\nclass MainWindow2(QtWidgets.QMainWindow, GuiChatroomWindow):\n def __init__(self, parent=None):\n super(MainWindow2, self).__init__(parent)\n chatroom_name = self.listWidget.selectedIndexes()[0].data()\n nickname = self.lineEdit.text()\n joined_chatroom = ServerInterchange.join_chat(chatroom_name, nickname, client.rcv.port)\n self.setup_chatroom_ui(self.window, joined_chatroom, client, chatroom_name, nickname)\n self.pushButton_2.clicked.connect(self.openFirst)\n self.pushButton_2.clicked.connect(self.hide)\n\n def openFirst(self):\n self.FW = MainWindow()\n self.FW.show()\n\n\nclass MainWindow(QtWidgets.QMainWindow, GuiMainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.setup_ui(self)\n self.pushButton.clicked.connect(self.openSecond)\n self.pushButton.clicked.connect(self.hide)\n\n def openSecond(self):\n self.SW = MainWindow2()\n self.SW.show()\n\n\nif __name__ == \"__main__\":\n client = Client()\n client.start()\n\n rooms = ServerInterchange.list_rooms()\n\n app = QtWidgets.QApplication(sys.argv)\n main_window = QtWidgets.QMainWindow()\n ui = GuiMainWindow()\n ui.setup_ui(main_window, rooms)\n main_window.show()\n app.exec_()\n","sub_path":"client/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"573351702","text":"import os\nimport requests\nimport hashlib\nimport pymongo\nfrom retry import retry\n\ntoken = 'F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB'\ndata = {\n 'token': token,\n}\nurl = 'http://open.fangjia.com/files/upload'\n\n\n# def eachFile(filepath):\n# pathDir = os.listdir(filepath)\n# for allDir in pathDir:\n# print(allDir)\n# child = os.path.join('%s\\%s' % (filepath, allDir))\n# files = {'file': open(child, 'rb')}\n# reslut = requests.post(url=url, files=files, data=data)\n# print(reslut.text)\n# break\n\n\ndef get_collection_object(host, port, db_name, collection_name):\n client = pymongo.MongoClient(host, port)\n db = client[db_name]\n collection = db[collection_name]\n return collection\n\n\nm = get_collection_object('192.168.0.235', 27017, 'image_test', 'image_test')\n\n\n@retry(tries=3)\ndef retry_(result):\n try:\n print(1 / 0)\n link = result.json()['result']['link']\n return link\n except Exception as e:\n print('重试一次-----------------------------------')\n raise\n\n\ndef start():\n for i in m.find():\n image_list = i['image_list']\n _id = i['_id']\n img_list = []\n for i in image_list:\n img = i['img']\n m1 = hashlib.md5()\n m1.update(img.encode('utf-8'))\n md5_url = m1.hexdigest()\n file_path = 'D:\\\\imagesss\\\\' + md5_url + '.png'\n try:\n files = {'file': open(file_path, 'rb')}\n result = requests.post(url=url, files=files, data=data)\n link = retry_(result)\n\n i['link'] = link\n img_list.append(i)\n\n except Exception as e:\n print('没有图片')\n\n print(img_list)\n m.update({'_id': _id}, {'$set': {'image_list': img_list}})\n\n\nif __name__ == '__main__':\n start()\n","sub_path":"hilder_other/community_image/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"17714346","text":"from .load import load_quests\nfrom .artifacts import write_dicts_artifact\n\ndef update_quests(mhdata, item_updater):\n quests = load_quests()\n\n # Internal helper to add a prefix to \"unk\" fields\n def prefix_unk_fields(basename, d):\n result = {}\n for key, value in d.items():\n if key.startswith('unk'):\n key = basename + '_' + key\n result[key] = value\n return result\n\n quest_artifact_entries = []\n quest_reward_artifact_entries = []\n test = set()\n for quest in quests:\n header_fields = prefix_unk_fields('header', quest.header.as_dict())\n objective_fields = prefix_unk_fields('objective', quest.objective.as_dict())\n\n if quest.name['en'] in test:\n print(quest.name['en'] + \" is a dupe\")\n test.add(quest.name['en'])\n\n quest_artifact_entries.append({\n 'name_en': quest.name['en'],\n **header_fields,\n **objective_fields\n })\n\n for idx, rem in enumerate(quest.reward_data_list):\n first = True\n for (item_id, qty, chance) in rem.iter_items():\n item_name, _ = item_updater.name_and_description_for(item_id)\n if first and not rem.drop_mechanic:\n quest_reward_artifact_entries.append({\n 'name_en': quest.name['en'],\n 'reward_idx': idx,\n 'signature?': rem.signature,\n 'signatureExt?': rem.signatureExt,\n 'drop_mechanic': rem.drop_mechanic,\n 'item_name': item_name['en'],\n 'qty': qty,\n 'chance': 100\n })\n\n quest_reward_artifact_entries.append({\n 'name_en': quest.name['en'],\n 'reward_idx': idx,\n 'signature?': rem.signature,\n 'signatureExt?': rem.signatureExt,\n 'drop_mechanic': rem.drop_mechanic,\n 'item_name': item_name['en'],\n 'qty': qty,\n 'chance': chance\n })\n first = False\n\n write_dicts_artifact('quest_raw_data.csv', quest_artifact_entries)\n write_dicts_artifact('quest_raw_rewards.csv', quest_reward_artifact_entries)","sub_path":"mhdata/merge/binary/quests.py","file_name":"quests.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"472075050","text":"import pandas as pd\nimport pymysql.cursors\n\n\ndef df_builder(sql, cursor):\n cursor.execute(sql)\n result = cursor.fetchall()\n return pd.DataFrame.from_dict(result)\n\n\n# Connect to the database\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='87iu0080A',\n db='lab',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\ntry:\n with connection.cursor() as cursor:\n\n df_user = df_builder(\"select * from user\", cursor)\n df_blog = df_builder(\"select * from blog\", cursor)\n df_post = df_builder(\"select * from post\", cursor)\n\n print(\" ------------------------ \")\n postByBlog = df_post[df_post.blog_id == 1]\n print(\" ------------------------ \")\n blogByUser = df_user[df_user.user_id == 1]\n print(\" ------------------------ \")\n result = pd.merge(postByBlog, blogByUser, how='left',\n on='blog_id', indicator=True)\n print(result[['user_id', 'blog_id', 'post_id', 'title', 'content']])\n\n\nfinally:\n connection.close()\n","sub_path":"src/Pandas and Numpy and Scipy/Pandas_with_DB.py","file_name":"Pandas_with_DB.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"516021355","text":"def specialMultiple(x):\n '''\n # read from stdin\n n = int(input())\n for i in range(n):\n x = int(input().strip())\n '''\n\n for l in range(1, 1000):\n for a in range(1, l + 1):\n b = l - a\n p = int('4' * a + '0' * b)\n if p % x == 0:\n return 2 * a + b\n\n return 0\n\ndef specialMultiple2(x):\n '''\n # read from stdin\n n = int(input())\n for i in range(n):\n x = int(input().strip())\n '''\n\n # count 2 & 5\n c2 = c5 = 0\n while x % 2 == 0:\n x = x // 2 # Do not use x /= 2, this is integer division, not float division. Having x as float will mess up the % calculation later\n c2 += 1\n \n while x % 5 == 0:\n x = x // 5\n c5 += 1\n\n b = max(c5, c2 - 2)\n\n found = False\n for a in range(1, 10000):\n if int('1' * a) % x == 0:\n found = True\n break\n\n print(x, a, b)\n return 2 * a + b if found else 0\n\ntests = [\n #38, 46, 54\n #1, 2, 3, 4, 5, 6, 7, 8, 9\n #, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20\n #, 80, 81\n #10 ** 10 - 7\n]\n\ntests += [i for i in range(1, 100)]\n\nfor t in tests:\n print(specialMultiple2(t), '<--', t)\n #res1 = specialMultiple(t)\n #res2 = specialMultiple2(t)\n #print(res1 == res2, res1, res2, '<--', t)\n\n","sub_path":"2018/hr_SpecialMultiple.py","file_name":"hr_SpecialMultiple.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"386532488","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.\n# All rights reserved.\n#\n# SPDX-License-Identifier: BSD-3-Clause\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#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# We kindly request you to use one or more of the following phrases to refer to\n# foxBMS in your hardware, software, documentation or advertising materials:\n#\n# - \"This product uses parts of foxBMS®\"\n# - \"This product includes parts of foxBMS®\"\n# - \"This product is derived from foxBMS®\"\n\n\"\"\"Template for Python scripts\"\"\"\n\nimport logging\nimport argparse\n\n\ndef main():\n \"\"\"This script does this and that\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-v\",\n \"--verbosity\",\n dest=\"verbosity\",\n action=\"count\",\n default=0,\n help=\"set verbosity level\",\n )\n args = parser.parse_args()\n\n if args.verbosity == 1:\n logging.basicConfig(level=logging.INFO)\n elif args.verbosity > 1:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.ERROR)\n logging.debug(args)\n\n with open(\"multiplexed_cellVoltages_for_sym_file.txt\", \"w\") as f:\n # create .sym file messages for 54 * 4 cell voltages\n for i in range(0, 54):\n f.write(\"[foxBMS_CellVoltage]\\n\")\n if i == 0:\n f.write(\"ID=240h\\n\")\n f.write(\"DLC=8\\n\")\n f.write(\n \"Mux=mux_cellVoltage_\"\n + str(i * 4)\n + \"_\"\n + str((i * 4) + 3)\n + \" 0,8 \"\n + hex(i)[2:].upper()\n + \"h -m\\n\"\n )\n f.write(\"Var=cellVoltage_\" + str(i * 4) + \"_invalidFlag unsigned 11,1 -m\\n\")\n f.write(\n \"Var=cellVoltage_\"\n + str((i * 4) + 1)\n + \"_invalidFlag unsigned 10,1 -m\\n\"\n )\n f.write(\n \"Var=cellVoltage_\" + str((i * 4) + 2) + \"_invalidFlag unsigned 9,1 -m\\n\"\n )\n f.write(\n \"Var=cellVoltage_\" + str((i * 4) + 3) + \"_invalidFlag unsigned 8,1 -m\\n\"\n )\n f.write(\"Var=cellVoltage_\" + str(i * 4) + \" unsigned 12,13 -m /u:mV\\n\")\n f.write(\n \"Var=cell_voltage_\" + str((i * 4) + 1) + \" unsigned 25,13 -m /u:mV\\n\"\n )\n f.write(\n \"Var=cell_voltage_\" + str((i * 4) + 2) + \" unsigned 38,13 -m /u:mV\\n\"\n )\n f.write(\n \"Var=cell_voltage_\" + str((i * 4) + 3) + \" unsigned 51,13 -m /u:mV\\n\"\n )\n f.write(\"\\n\")\n\n with open(\"multiplexed_cellTemperatures_for_sym_file.txt\", \"w\") as f:\n # create .sym file messages for 30 * 6 cell temperatures\n for i in range(0, 30):\n f.write(\"[foxBMS_CellTemperature]\\n\")\n if i == 0:\n f.write(\"ID=250h\\n\")\n f.write(\"DLC=8\\n\")\n f.write(\n \"Mux=mux_cellTemperature_\"\n + str(i * 6)\n + \"_\"\n + str((i * 6) + 5)\n + \" 0,8 \"\n + hex(i)[2:].upper()\n + \"h -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\" + str(i * 6) + \"_invalidFlag unsigned 15,1 -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\"\n + str((i * 6) + 1)\n + \"_invalidFlag unsigned 14,1 -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\"\n + str((i * 6) + 2)\n + \"_invalidFlag unsigned 13,1 -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\"\n + str((i * 6) + 3)\n + \"_invalidFlag unsigned 12,1 -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\"\n + str((i * 6) + 4)\n + \"_invalidFlag unsigned 11,1 -m\\n\"\n )\n f.write(\n \"Var=cellTemperature_\"\n + str((i * 6) + 5)\n + \"_invalidFlag unsigned 10,1 -m\\n\"\n )\n f.write(\"Var=cellTemperature_\" + str(i * 6) + \" signed 16,8 -m /u:degC\\n\")\n f.write(\n \"Var=cellTemperature_\" + str((i * 6) + 1) + \" signed 24,8 -m /u:degC\\n\"\n )\n f.write(\n \"Var=cellTemperature_\" + str((i * 6) + 2) + \" signed 32,8 -m /u:degC\\n\"\n )\n f.write(\n \"Var=cellTemperature_\" + str((i * 6) + 3) + \" signed 40,8 -m /u:degC\\n\"\n )\n f.write(\n \"Var=cellTemperature_\" + str((i * 6) + 4) + \" signed 48,8 -m /u:degC\\n\"\n )\n f.write(\n \"Var=cellTemperature_\" + str((i * 6) + 5) + \" signed 56,8 -m /u:degC\\n\"\n )\n f.write(\"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/dbc/symbol_creator.py","file_name":"symbol_creator.py","file_ext":"py","file_size_in_byte":6379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"304403426","text":"import urllib.request as urllib2\nimport pytest\nimport numpy as np\n\nfrom hqbot import answerbot\n\nSIMPLIFY_QUES_DATA = [\n # question, clean_question, neg\n (\n \"Which of these countries is NOT in Scandinavia?\",\n \"countries scandinavia?\",\n True),\n (\n \"The hottest multiplayer video game this year was designed by which famous gamer?\",\n \"hottest multiplayer video game year was designed famous gamer?\",\n False\n ),\n (\n \"Which of these state names is NOT a Native American word or phrase?\",\n \"state names native american word or phrase?\",\n True\n ),\n (\n \"Which pathogen is identifed by abnormally folded, \\\n transmissible proteins causing rare and fatal diseases?\",\n \"pathogen identifed abnormally folded, transmissible proteins causing rare fatal diseases?\",\n False\n )\n]\n\n\ndef test_screen_grab():\n assert isinstance(answerbot.screen_grab(save=False, location=None), np.ndarray)\n\n with pytest.raises(TypeError):\n answerbot.screen_grab(save=False, location=5)\n\n\ndef test_preprocess_img():\n img = answerbot.screen_grab(save=False, location=None)\n assert isinstance(answerbot.preprocess_img(img), np.ndarray)\n\n\ndef test_preprocess_img_exception():\n with pytest.raises(TypeError):\n answerbot.preprocess_img(img=None)\n\n\ndef test_read_screen():\n assert isinstance(answerbot.read_screen(), str)\n\n\ndef test_parse_question():\n question, options = answerbot.parse_question(save=False)\n assert isinstance(question, str)\n assert isinstance(options, list)\n\n\n@pytest.mark.parametrize(\"question,clean_question,neg\", SIMPLIFY_QUES_DATA)\ndef test_simplify_ques(question, clean_question, neg):\n processed_question, actual_neg = answerbot.simplify_ques(question, debug=True)\n assert processed_question == clean_question and actual_neg == neg\n\n with pytest.raises(TypeError):\n answerbot.simplify_ques(question=[])\n\n\n@pytest.mark.parametrize(\"link\", [\n \"https://wikipedia.org/\",\n \"https://en.wikipedia.org/wiki/HQ_Trivia\",\n \"https://google.com/\"\n])\ndef test_get_page(link):\n assert isinstance(answerbot.get_page(link), bytes)\n\n with pytest.raises((urllib2.URLError, urllib2.HTTPError, ValueError)):\n answerbot.get_page(\"4584\")\n","sub_path":"tests/test_answerbot.py","file_name":"test_answerbot.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"122520795","text":"import json\nimport numpy as np\nimport openml\nimport openmlcontrib\nimport os\nimport pandas as pd\nimport pickle\n\n\ndef get_dataframe_from_openml(task_id, flow_id, num_runs, relevant_parameters, evaluation_measure, cache_directory):\n if 'y' in relevant_parameters:\n raise ValueError()\n\n try:\n os.makedirs(cache_directory + '/' + str(flow_id) + '/' + str(task_id))\n except FileExistsError:\n pass\n\n # grab num_runs random evaluations\n evaluations_cache_path = cache_directory + '/' + str(flow_id) + '/' + str(task_id) + '/evaluations_%d.pkl' % num_runs\n setups_cache_path = cache_directory + '/' + str(flow_id) + '/' + str(task_id) + '/setups_%d.pkl' % num_runs\n if not os.path.isfile(evaluations_cache_path) or not os.path.isfile(setups_cache_path):\n evaluations = openml.evaluations.list_evaluations(evaluation_measure, size=num_runs, task=[task_id], flow=[flow_id])\n if len(evaluations) == 0:\n raise ValueError('No evaluations for this task. ')\n\n with open(evaluations_cache_path, 'wb') as fp:\n pickle.dump(evaluations, fp)\n\n # setups\n setup_ids = []\n for run_id, evaluation in evaluations.items():\n setup_ids.append(evaluation.setup_id)\n setups = openmlcontrib.setups.obtain_setups_by_ids(setup_ids=setup_ids)\n\n with open(setups_cache_path, 'wb') as fp:\n pickle.dump(setups, fp)\n\n with open(evaluations_cache_path, 'rb') as fp:\n evaluations = pickle.load(fp)\n with open(setups_cache_path, 'rb') as fp:\n setups = pickle.load(fp)\n\n setup_parameters = {}\n\n for setup_id, setup in setups.items():\n hyperparameters = {}\n for pid, hyperparameter in setup.parameters.items():\n name = hyperparameter.parameter_name\n value = hyperparameter.value\n if name not in relevant_parameters.keys():\n continue\n\n if name in hyperparameters:\n # duplicate parameter name, this can happen due to subflows.\n # when this happens, we need to fix\n raise ValueError('Duplicate hyperparameter:', name, 'Values:', value, hyperparameters[name])\n hyperparameters[name] = value\n setup_parameters[setup_id] = hyperparameters\n if len(hyperparameters) != len(relevant_parameters):\n raise ValueError('Obtained parameters not complete. Setup id %d missing: %s' %(setup_id, str(relevant_parameters.keys() - hyperparameters.keys())))\n\n all_columns = list(relevant_parameters)\n all_columns.append('y')\n dataframe = pd.DataFrame(columns=all_columns)\n\n for run_id, evaluation in evaluations.items():\n currentXy = {}\n legalConfig = True\n for idx, param in enumerate(relevant_parameters):\n value = json.loads(setup_parameters[evaluation.setup_id][param])\n if relevant_parameters[param] == 'numeric':\n if not (isinstance(value, int) or isinstance(value, float)):\n legalConfig = False\n\n currentXy[param] = value\n\n currentXy['y'] = evaluation.value\n\n if legalConfig:\n dataframe = dataframe.append(currentXy, ignore_index=True)\n else:\n # sometimes, a numeric param can contain string values. keep these out?\n print('skipping', currentXy)\n\n all_numeric_columns = list(['y'])\n for parameter, datatype in relevant_parameters.items():\n if datatype == 'numeric':\n all_numeric_columns.append(parameter)\n\n dataframe[all_numeric_columns] = dataframe[all_numeric_columns].apply(pd.to_numeric)\n\n if dataframe.shape[0] > num_runs:\n raise ValueError()\n if dataframe.shape[1] != len(relevant_parameters) + 1: # plus 1 for y data\n raise ValueError()\n\n dataframe = dataframe.reindex(sorted(dataframe.columns), axis=1)\n\n return dataframe\n\n\ndef get_X_y_from_openml(task_id, flow_id, num_runs, relevant_parameters, cache_directory):\n\n dataframe = get_dataframe_from_openml(task_id, flow_id, num_runs, relevant_parameters, cache_directory)\n\n categorical_columns = set(dataframe.columns) - set(dataframe._get_numeric_data().columns)\n categorical_indices = {dataframe.columns.get_loc(col_name) for col_name in categorical_columns}\n\n y = np.array(dataframe['y'], dtype=np.float)\n\n dataframe.drop('y', 1, inplace=True)\n return dataframe.as_matrix(), y, dataframe.columns.values, categorical_indices\n","sub_path":"activetesting/utils/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"266054070","text":"# pick percentage% randomly from a fasta file\n\n#\n\n\nimport sys\n\nimport random\n\nfilename = sys.argv[1]\n\noutname1 = sys.argv[2]\n\nnum = int(sys.argv[3]) # percentage to pick randomly\n\nf2 = open(filename,'r')\nf1 = open(outname1,'w')\n\n\nlist_seq=[]\nlist_name=[]\n\nfor line in f2:\n if line[0] == '>':\n list_name.append(line)\n else:\n list_seq.append(line)\n \n \n\n if len(list_seq)==100:\n #print num\n \n r=random.sample(xrange(100),num)\n #print r \n for i in r:\n f1.write('>' +list_name[i])\n f1.write(list_seq[i])\n list_seq=[]\n list_name = []\n","sub_path":"1_2009Dec_GPGC/Script/adina/pick_fasta_randomly_no_screed.py","file_name":"pick_fasta_randomly_no_screed.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"280873234","text":"from turtle import Turtle\nALIGNMENT = \"center\"\nFONT1 = (\"Courier\", 60, \"normal\")\nFONT2 = (\"Courier\", 20, \"normal\")\n\n\nclass Scoreboard(Turtle):\n\n def __init__(self):\n super().__init__()\n self.color(\"white\")\n self.penup()\n self.hideturtle()\n self.l_score = 0\n self.r_score = 0\n self.update_scoreboard()\n\n def update_scoreboard(self):\n self.clear()\n self.goto(-100, 220)\n self.write(self.l_score, align=ALIGNMENT, font=FONT1)\n self.goto(0, 220)\n self.write(\"::\", align=ALIGNMENT, font=FONT1)\n self.goto(100, 220)\n self.write(self.r_score, align=ALIGNMENT, font=FONT1)\n\n def l_point(self):\n self.l_score += 1\n self.update_scoreboard()\n\n def r_point(self):\n self.r_score += 1\n self.update_scoreboard()\n\n def game_over(self):\n self.goto(0, 80)\n self.write(\"GAME OVER\", align=ALIGNMENT, font=FONT2)\n self.goto(0, 0)\n if self.l_score > self.r_score:\n self.write(f\"Left Player has won\", align=ALIGNMENT, font=FONT2)\n else:\n self.write(f\"Right Player has won\", align=ALIGNMENT, font=FONT2)\n","sub_path":"Ping Pong Game/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"407715786","text":"#-*- coding:utf-8 -*-\n\nimport codecs\nimport operator\n\ndef ansi2utf8(src_filename):\n convenc(src_filename, 'cp949', 'utf8')\n\ndef ansi2utf8_tofile(src_filename, des_filename):\n convenc_tofile(src_filename, 'ansi', des_filename, 'utf8')\n\ndef convenc_tofile(src_filename, src_encoding, des_filename, des_encoding):\n with codecs.open(src_filename, 'r', encoding=src_encoding) as file:\n lines = file.read()\n\n with codecs.open(des_filename, 'w', encoding=des_encoding) as file:\n file.write(lines)\n\n return des_filename\n\ndef convenc(src_filename, src_encoding, des_encoding):\n with codecs.open(src_filename, 'r', encoding=src_encoding) as file:\n lines = file.read()\n\n return lines.decode(src_encoding).encode(des_encoding) \n\n\ndef parse2db(filename):\n with codecs.open(filename,'r',encoding='utf8') as f:\n rows = f.readlines()[3:]\n errors = []\n for row in rows:\n #?문자 발생시 구분기호로 변경\n row = row.replace('?','|')\n data = [x.strip() for x in row.split('|')][1:-1]\n if len(data) == 20:\n #수량 이상 시 이상표시\n try:\n data[8] = int(data[8])\n except ValueError:\n data[8] = '9999'\n errors.append(data)\n \n querySet = item.objects.filter(no = data[0])\n if querySet.exists() == False:\n db = item(no = data[0],\n group = data[1],\n name = data[2],\n description = data[3],\n slot = data[4],\n oldNo = data[5],\n groupText = data[6],\n safetyAmount = data[7],\n amount = data[8],\n buyAmount = data[9],\n totalAmount = data[10],\n itemType = data[11],\n BUn = data[12],\n price = float(data[13].replace(',','')),\n totalPrice = float(data[14].replace(',','')),\n Pe = data[15],\n Plnt = data[16],\n Sloc = data[17],\n itemGroup = data[18],\n itemUsage = data[19]\n )\n db.save()\n else:\n errors.append(data)\n\n return errors\n\ndef makedict(keys, values):\n dictdata = {}\n for num in range(0, len(values)):\n dictdata[keys[num]] = values[num]\n return dictdata\n\ndef parse(filename):\n with codecs.open(filename,'r',encoding='utf8') as f:\n rows = f.readlines()\n errors = []\n datas = []\n #keys = [x.strip() for x in rows[1].split('|')][1:-1]\n keys = [x.replace(\" \",\"\") for x in rows[1].split('|')][1:-1]\n for row in rows[3:]:\n #?문자 발생시 구분기호로 변경\n row = row.replace('?','|')\n data = [x.strip() for x in row.split('|')][1:-1]\n datas.append(makedict(keys, data))\n return datas\n\ndef getFailAmounts(lists):\n amounts = {}\n for item in lists[:-1]:\n try:\n amount = int(item['불량수량'])\n #print(amount)\n amounts[item['생산일']] = amounts[item['생산일']] + amount\n except KeyError:\n amounts[item['생산일']] = amount\n\n sorted_amounts = sorted(amounts.items(), key=operator.itemgetter(0))\n\n return sorted_amounts","sub_path":"qualview/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236154932","text":"# image blending\n\nimport cv2\nimport numpy\n\n\n# remember that size of both the images need to be same\nimg1 = cv2.imread('me.jpg')\nimg1 = cv2.resize(img1, (700, 500))\nimg2 = cv2.imread('PM.jpg')\nimg2 = cv2.resize(img2, (700, 500))\n\nval1 = cv2.add(img1, img2)\nval2 = cv2.addWeighted(img1, 0.7, img2, 0.7, 0)\n\ncv2.imshow('add_image1', val1)\ncv2.imshow('add_image2', val2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"adding_Images.py","file_name":"adding_Images.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"372249445","text":"#/usr/bin python\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\nstart='2020-10-21'\nend='2021-01-21'\n\ndatestart=datetime.datetime.strptime(start,'%Y-%m-%d')\ndateend=datetime.datetime.strptime(end,'%Y-%m-%d')\n\n#table_name=\"accounting_journal\"\ntable_name=['sub_ledger_entry','general_ledger_entry','application_journal','adjust_sub_ledger_entry','adjust_ledger_entry','accounting_journal_register','accounting_journal_entry','accounting_journal','adjust_journal_entry']\n\nfor table in table_name:\n start='2019-09-01'\n end='2022-02-01'\n\n datestart=datetime.datetime.strptime(start,'%Y-%m-%d')\n dateend=datetime.datetime.strptime(end,'%Y-%m-%d')\n\n # cteate default partition\n #print(\"CREATE TABLE {0}_default_partition PARTITION OF {0} DEFAULT;\".format(table))\n\n # cteate min partition\n print(\"CREATE TABLE {0}_p201909_before PARTITION OF {0} FOR VALUES FROM (MINVALUE) TO ('2019-09-01 00:00:00'::timestamp);;\".format(table))\n\n # create dayliy partition\n while datestart=[0,0,0]).all(axis=1)\n cubs = cubs[val,:]\n # get voxel idx\n v = cubs[:,0] + nx*(cubs[:,1] + ny*cubs[:,2])\n # check if is cube (therefore inside the domain)\n val[val] = (self.propeiko.vox2cub_view[v] >= 0)\n bcs += val\n\n return bcs\n\n def get_mass_matrix(self,lumped=True):\n\n if lumped:\n dim = self.get_dim()\n return self.get_voxel_volume() * self.bcs / (2**dim)\n else:\n raise NotImplementedError\n\n def convert_to_function(self,Yval,fill_value=np.nan):\n\n sfun = np.empty_like(self.propeiko.get_dtime())\n sfun.fill(fill_value)\n sfun.ravel()[self.propeiko.nod2ver_view] = Yval\n return sfun\n\n def save_function_igb(self,fname,Yval):\n\n sfun = self.convert_to_function(Yval)\n igb_write(sfun,fname)\n\n def get_number_of_points(self):\n return self.propeiko.mesh.nnod\n\n def get_voxel_volume(self):\n\n hx = self.propeiko.mesh.hx\n hy = self.propeiko.mesh.hy\n hz = self.propeiko.mesh.hz\n\n if self.force2d:\n hx = hx if self.propeiko.mesh.nx > 1 else 1.0\n hy = hy if self.propeiko.mesh.ny > 1 else 1.0\n hz = hz if self.propeiko.mesh.nz > 1 else 1.0\n\n return hx*hy*hz\n\n def get_dim(self):\n # dimension of the problem\n # we always solve in 3D, but if in one direction the\n # number of voxels is 1, then is lower dimentional\n d = sum(getattr(self.propeiko.mesh,s) > 1 for s in [\"nx\",\"ny\",\"nz\"])\n if self.force2d:\n return d\n else:\n return 3\n\n def get_point(self,idx):\n return self.get_points(idx)[0]\n\n def point_to_node(self,x,y,z):\n nx = self.propeiko.mesh.nx + 1\n ny = self.propeiko.mesh.ny + 1\n v = x + nx*(y + ny*z)\n idx = self.propeiko.ver2nod_view[v]\n return idx\n\n def get_points(self,idx=None):\n nx = self.propeiko.mesh.nx + 1\n ny = self.propeiko.mesh.ny + 1\n\n idx = idx or slice(None)\n v = self.propeiko.nod2ver_view[idx]\n x = v % nx\n y = (v // nx) % ny\n z = v // (nx*ny)\n\n return np.c_[x,y,z]\n\n def __call__(self,xyz):\n\n if self.backend == \"euclidean\":\n pts = self.get_points()\n dtime = self.propeiko.mesh.hx * np.linalg.norm(pts - xyz,axis=1)\n\n elif self.backend == \"fmm\":\n raise NotImplementedError\n\n else:\n self.propeiko.set_pacingsite(0,*xyz,0.0)\n self.propeiko.run_dtime()\n nod2ver = self.propeiko.nod2ver_view\n dtime_full = self.propeiko.get_dtime()\n dtime = np.ascontiguousarray(dtime_full.ravel()[nod2ver])\n\n return dtime\n\ndef create_cube():\n pass\n\n\ndef create_hollow_square(prefix,N=50,xsize=0.05,ysize=0.4):\n cfun = lambda x,y,z: 1-np.logical_and(np.abs(x-0.5) dict:\n result = dict()\n\n for query_group in query_groups:\n query = query_group.split('=')\n\n if len(query) == 1:\n result[query[0]] = None\n continue\n\n result[query[0]] = query[1]\n\n return result\n\n\ndef _parse_url_with_top_domain(url, top_domain):\n regex = r\"^(?:(?P[\\w\\d]+)(?:\\:\\/\\/))?\" \\\n r\"(?P\" \\\n r\"(?P(?:www)?)(?:\\.?)\" \\\n r\"(?:(?:[\\w\\d-]+|\\.)*?)?\" \\\n r\")(?:\\.?)\" \\\n r\"(?P[^./]+(?=\\.))\\.\" \\\n r\"(?P\" + re.escape(top_domain) + r\"(?![^/?#]))\" \\\n r\"(?P\" \\\n r\"(?P

\\/(?:[^/\\r\\n]+(?:/))+)?\" \\\n r\"(?:\\/?)(?P[^?#\\r\\n]+)?\" \\\n r\")?\" \\\n r\"(?:\\#(?P[^#?\\r\\n]*))?\" \\\n r\"(?:\\?(?P.*(?=$)))*$\"\n\n dict_data = {\n 'protocol': None,\n 'www': None,\n 'sub_domain': None,\n 'domain': None,\n 'top_domain': None,\n 'path': None,\n 'dir': None,\n 'file': None,\n 'fragment': None,\n 'query': None,\n }\n\n match = re.search(regex, url)\n\n dict_data['protocol'] = match.group('protocol') if match.group('protocol') else None\n dict_data['www'] = match.group('www') if match.group('www') else None\n dict_data['sub_domain'] = match.group('sub_domain') if match.group('sub_domain') else None\n dict_data['domain'] = match.group('domain')\n dict_data['top_domain'] = top_domain\n dict_data['path'] = match.group('path') if match.group('path') else None\n dict_data['dir'] = match.group('dir') if match.group('dir') else None\n dict_data['file'] = match.group('file') if match.group('file') else None\n dict_data['fragment'] = match.group('fragment') if match.group('fragment') else None\n\n query = match.group('query') if match.group('query') else None\n\n if query is not None:\n query_groups = query.split('&')\n query = _split_query_group(query_groups)\n dict_data['query'] = query\n\n return dict_data\n\n\ndef _parse_url_with_public_suffix(url):\n public_suffix = PublicSuffixList.get_list()\n public_suffix.sort()\n\n domain_regex = r\"(?:^|\\/)(?P[^:/#?]+)(?:[/#?]|$)\"\n match = re.search(domain_regex, url)\n domain = match.group('domain')\n domain_parts = domain.split('.')\n\n top_domain = None\n\n for i in range(len(domain_parts)):\n tail_gram = domain_parts[i:len(domain_parts)]\n tail_gram = '.'.join(tail_gram)\n\n if tail_gram in public_suffix:\n top_domain = tail_gram\n break\n\n data = _parse_url_with_top_domain(url, top_domain)\n\n return data\n\n\ndef get_base_url(url: str) -> str:\n url = get_url(url)\n protocol = str(url.protocol) + '://' if url.protocol is not None else 'http://'\n www = 'www.' if url.www is not None else ''\n sub_domain = str(url.sub_domain) + '.' if url.sub_domain is not None and url.sub_domain != 'www.' else ''\n return protocol + www + sub_domain + url.domain + '.' + url.top_domain\n\n\ndef get_url(url: str) -> UrlObject:\n data = _parse_url_with_public_suffix(url)\n\n object_data = UrlObject(\n protocol=data['protocol'],\n www=data['www'],\n sub_domain=data['sub_domain'],\n domain=data['domain'],\n top_domain=data['top_domain'],\n path=data['path'],\n dir=data['dir'],\n file=data['file'],\n fragment=data['fragment'],\n query=data['query'],\n )\n\n return object_data\n\n\ndef parse_url(url: str) -> dict:\n warnings.warn(\n \"parse_url is deprecated, use get_url instead\",\n DeprecationWarning\n )\n\n data = get_url(url)\n return data._asdict()\n","sub_path":"url_parser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"308524263","text":"import os, json, requests\nimport pandas as pd\nimport numpy as np\nimport jieba\nimport keras\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras import backend as K\nfrom flask import Flask, request\napp = Flask(__name__)\n\ntf_serving_api = \"http://127.0.0.1:8501/v1/models/VarietyPredictionZh:predict\"\nbase_dir=\"/Users/wxf/Documents/GitHub/FL-WINE-PROJECT/\"\n\njieba_dict_file = base_dir + \"dataset/jieba-dict/dict.txt\"\njieba.load_userdict(jieba_dict_file)\n\ndata = pd.read_csv(base_dir + \"dataset/wine-review/winemag-data-130k-v2-zh-resampled.csv\")\nall_description = data['desc_zh_cut'][:]\n\nencoder = LabelEncoder()\nencoder.fit(data['variety'][:])\n\nvocab_size = 12000 # 词袋数量\ntokenize = keras.preprocessing.text.Tokenizer(num_words=vocab_size, char_level=False)\ntokenize.fit_on_texts(all_description)\n\nmax_seq_length = 170\n\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n # if request.method == \"POST\":\n # request param\n desc = request.values.get(\"desc\", \"\")\n desc = jieba_cut(desc)\n price = float(request.values.get(\"price\", \"0.0\"))\n print(desc, price, type(desc), type(price))\n\n desc = pd.Series([desc])\n price = pd.Series([price])\n\n description_bow_test = tokenize.texts_to_matrix(desc)\n test_embed = tokenize.texts_to_sequences(desc)\n test_embed = keras.preprocessing.sequence.pad_sequences(test_embed, maxlen=max_seq_length, padding=\"post\")\n\n res = get_predicted(description_bow_test, price, test_embed)\n rindex = np.argmax(res)\n variety_predicted = encoder.inverse_transform(rindex)\n K.clear_session()\n return _ret(data={\"variety_predicted\": variety_predicted})\n\ndef get_predicted(description_bow_test, price, test_embed):\n # print(description_bow_test.shape, price.shape, test_embed.shape)\n description_bow_test = description_bow_test.flatten()\n # print(description_bow_test.shape)\n # price = price.values.reshape(1, 1)\n test_embed = test_embed.flatten()\n\n payload = {\n \"instances\": [{\"input_bow\": description_bow_test.tolist(),\n \"input_price\": price.tolist(),\n \"input_embed\": test_embed.tolist()}]\n }\n\n # print(payload)\n r = requests.post(tf_serving_api, json=payload)\n print(r.text)\n rdict = json.loads(r.content.decode(\"utf-8\"))\n return rdict[\"predictions\"]\n\ndef jieba_cut(input):\n res = jieba.cut(input, cut_all=False, HMM=True)\n res = \" \".join(res)\n return res\n\ndef _ret(msg=\"\", errcode=0, data={}):\n ret = {\n \"msg\": msg,\n \"code\": errcode,\n \"data\": data\n }\n return json.dumps(ret)\n","sub_path":"VarietyPredictionTFServingUwsgi.py","file_name":"VarietyPredictionTFServingUwsgi.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"456067429","text":"##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: Hang Zhang\n## Email: zhanghang0704@gmail.com\n## Copyright (c) 2020\n##\n## LICENSE file in the root directory of this source tree \n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\"\"\"ResNeSt models\"\"\"\n\nimport torch\nfrom resnet_new import ResNet, Bottleneck\n#from .resnet_new import ResNet, Bottleneck\nimport torch.nn as nn\nfrom Config import *\nfrom Weight import Weight\nimport mmd\n\n__all__ = ['resnest50', 'resnest101', 'resnest200', 'resnest269']\nfrom build import RESNEST_MODELS_REGISTRY\n\n_url_format = 'https://github.com/zhanghang1989/ResNeSt/releases/download/weights_step1/{}-{}.pth'\n\n_model_sha256 = {name: checksum for checksum, name in [\n ('528c19ca', 'resnest50'),\n ('22405ba7', 'resnest101'),\n ('75117900', 'resnest200'),\n ('0cc87c48', 'resnest269'),\n ]}\n\ndef short_hash(name):\n if name not in _model_sha256:\n raise ValueError('Pretrained model for {name} is not available.'.format(name=name))\n return _model_sha256[name][:8]\n\nresnest_model_urls = {name: _url_format.format(name, short_hash(name)) for\n name in _model_sha256.keys()\n}\n\nclass DSAN(nn.Module):\n # 实例化DSAN时,执行此操作。\n def __init__(self, num_classes=10):\n super(DSAN, self).__init__()\n # 输入参数为true表示加载利用ImageNet预训练好的resnet50模型\n\t\t# 之前此处调用的参数一直为true,即是用训练好的域训练模型,后续可以尝试使用没有预训练的模型进行试验。\n self.feature_layers = resnest50(False)\n self.num_classes = num_classes\n if bottle_neck:\n self.bottle = nn.Linear(2048, 256)\n self.cls_fc = nn.Linear(256, num_classes)\n else:\n self.cls_fc = nn.Linear(2048, num_classes)\n\n #当把DSAN当作一个方法来调用的时候,执行此操作。\n def forward(self, source, target, s_label):\n source = self.feature_layers(source)\n if bottle_neck:\n source = self.bottle(source)\n s_pred = self.cls_fc(source)\n if self.training ==True:\n target = self.feature_layers(target)\n if bottle_neck:\n target = self.bottle(target)\n t_label = self.cls_fc(target)\n #原始的lmmd\n loss = mmd.lmmd(source, target, s_label, torch.nn.functional.softmax(t_label, dim=1),num_classes = self.num_classes)\n #混合核lmmd\n #loss = mklmmd.mix_poly_rbf(source, target, s_label, torch.nn.functional.softmax(t_label, dim=1))\n else:\n loss = 0\n return s_pred, loss\n\n@RESNEST_MODELS_REGISTRY.register()\ndef resnest50(pretrained=False, root='~/.encoding/models', **kwargs):\n model = ResNet(Bottleneck, [3, 4, 6, 3],\n radix=2, groups=1, bottleneck_width=64,\n deep_stem=True, stem_width=32, avg_down=True,\n avd=True, avd_first=False, **kwargs)\n if pretrained:\n model.load_state_dict(torch.hub.load_state_dict_from_url(\n resnest_model_urls['resnest50'], progress=True, check_hash=True))\n return model\n\n@RESNEST_MODELS_REGISTRY.register()\ndef resnest101(pretrained=False, root='~/.encoding/models', **kwargs):\n model = ResNet(Bottleneck, [3, 4, 23, 3],\n radix=2, groups=1, bottleneck_width=64,\n deep_stem=True, stem_width=64, avg_down=True,\n avd=True, avd_first=False, **kwargs)\n if pretrained:\n model.load_state_dict(torch.hub.load_state_dict_from_url(\n resnest_model_urls['resnest101'], progress=True, check_hash=True))\n return model\n\n@RESNEST_MODELS_REGISTRY.register()\ndef resnest200(pretrained=False, root='~/.encoding/models', **kwargs):\n model = ResNet(Bottleneck, [3, 24, 36, 3],\n radix=2, groups=1, bottleneck_width=64,\n deep_stem=True, stem_width=64, avg_down=True,\n avd=True, avd_first=False, **kwargs)\n if pretrained:\n model.load_state_dict(torch.hub.load_state_dict_from_url(\n resnest_model_urls['resnest200'], progress=True, check_hash=True))\n return model\n\n@RESNEST_MODELS_REGISTRY.register()\ndef resnest269(pretrained=False, root='~/.encoding/models', **kwargs):\n model = ResNet(Bottleneck, [3, 30, 48, 8],\n radix=2, groups=1, bottleneck_width=64,\n deep_stem=True, stem_width=64, avg_down=True,\n avd=True, avd_first=False, **kwargs)\n if pretrained:\n model.load_state_dict(torch.hub.load_state_dict_from_url(\n resnest_model_urls['resnest269'], progress=True, check_hash=True))\n return model\n","sub_path":"20210623resnest+matrix/resnest.py","file_name":"resnest.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"269992604","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport sys\nfrom pathlib import Path\n\nimport qlib\nimport fire\nimport pandas as pd\nimport ruamel.yaml as yaml\nfrom qlib.utils import init_instance_by_config, flatten_dict\nfrom qlib.workflow import R\nfrom qlib.workflow.record_temp import SignalRecord\n\n\n# worflow handler function\ndef workflow(config_path, experiment_name=\"workflow\"):\n with open(config_path) as fp:\n config = yaml.load(fp, Loader=yaml.Loader)\n\n provider_uri = config.get(\"provider_uri\")\n region = config.get(\"region\")\n qlib.init(provider_uri=provider_uri, region=region)\n\n # model initiaiton\n model = init_instance_by_config(config.get(\"task\")[\"model\"])\n dataset = init_instance_by_config(config.get(\"task\")[\"dataset\"])\n\n # start exp\n with R.start(experiment_name=experiment_name):\n # train model\n R.log_params(**flatten_dict(config.get(\"task\")))\n model.fit(dataset)\n recorder = R.get_recorder()\n\n # generate records: prediction, backtest, and analysis\n for record in config.get(\"task\")[\"record\"]:\n if record[\"class\"] == SignalRecord.__name__:\n srconf = {\"model\": model, \"dataset\": dataset, \"recorder\": recorder}\n record[\"kwargs\"].update(srconf)\n sr = init_instance_by_config(record)\n sr.generate()\n else:\n rconf = {\"recorder\": recorder}\n record[\"kwargs\"].update(rconf)\n ar = init_instance_by_config(record)\n ar.generate()\n\n\n# function to run worklflow by config\ndef run():\n fire.Fire(workflow)\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"qlib/workflow/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"319440659","text":"import sys\r\n\r\ndef get_label(y):\r\n label = ''\r\n for uni_int in y.split('-'):\r\n label += chr(int(uni_int))\r\n return label\r\n\r\ndef main():\r\n file_name = sys.argv[1]\r\n correct = 0\r\n total = 0\r\n with open(file_name, 'r') as inp:\r\n for line in inp:\r\n total += 1\r\n y, pred = line.strip().split(',', 1)\r\n y = get_label(y.split('.')[0].strip()).replace(' ', '')\r\n if y == pred.strip():\r\n correct += 1\r\n print('correct', correct)\r\n print('total', total)\r\n print('ratio', correct / total)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"estimate_accuracy.py","file_name":"estimate_accuracy.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"649184258","text":"from sklearn import metrics\nimport pandas as pd\nimport numpy as np\nfrom gerador_modelo import get_model\n\nmodel, X_train, X_test, y_train, y_test = get_model(['temp_max', 'chuva', 'fds'])\nmodel_2, X2_train, X2_test, y2_train, y2_test = get_model(['temp_media', 'chuva', 'fds'])\n\n# Obtendo coeficiente de determinação (R²)\n# Medida resumida que diz o quanto a linha de regressão se ajusta aos dados. È um valor entre 0 e 1.\n# Quanto mais próximo de 1, melhor\nprint(f'R² Temp. Máxima = {model.score(X_train, y_train).round(2)}')\nprint(f'R² Temp. Média = {model_2.score(X2_train, y2_train).round(2)}\\n')\n\n# Gerando previsões\ny_preview = model.predict(X_test)\ny2_preview = model_2.predict(X2_test)\n\n# Obtendo R² da previsão\nR2 = metrics.r2_score(y_test, y_preview).round(2)\nR2_2 = metrics.r2_score(y2_test, y2_preview).round(2)\nprint('R² da previsão:')\nprint(f'R² Temp. Máxima = {R2}')\nprint(f'R² Temp. Média = {R2_2}\\n')\n\n# Utilizando outras métricas de comparação\n# EQM = Erro quadrático médio\n# REQM = Raiz quadrática média\n\nEQM = metrics.mean_squared_error(y_test, y_preview)\nREQM = np.sqrt(EQM).round(2)\n\nEQM_2 = metrics.mean_squared_error(y2_test, y2_preview)\nREQM_2 = np.sqrt(EQM_2).round(2)\n\n# R² - Quanto mais próximo de 1, melhor (mais adequado ao modelo)\n# EQM e REQM, quando menor, melhor (menos erros)\nmetrics_temp_max = pd.DataFrame([EQM, REQM, R2], ['EQM', 'REQM', 'R²'], columns=['Métricas - Temp Máxima'])\nmetrics_temp_media = pd.DataFrame([EQM_2, REQM_2, R2_2], ['EQM', 'REQM', 'R²'], columns=['Métricas - Temp Média'])\n\nprint(pd.concat([metrics_temp_max, metrics_temp_media], axis=1))\nprint('\\n')\n\n# Visualizando os coeficientes da regressão\n# Intercepto: Mantendo as variáveis explicativas = 0, o efeito médio no consumo de cerveja seria 5951 litros\n# X1, X2, X3: Mantendo os outros coeficientes constantes, o acréscimo de 1 unidade em Xi gera uma variação média\n# no consumo de cerveja de X1 = 684 litros, X2 = -60 litros, X3 = 5401 litros\nindex = ['Intercepto', 'Temperatura Máxima', 'Chuva (mm)', 'Final de Semana']\ncoeficientes = pd.DataFrame(data=np.append(model.intercept_, model.coef_), index=index, columns=['Parâmetros'])\nprint(coeficientes)\n\n# Gerando previsão pontual\nX_input = X_test[0:1]\nprint(f'Consumo previsto: {model.predict(X_input)[0].round(2)} litros')\n\n# Simulando dados\ntemp_max = 40\nchuva = 0\nfds = 1\nX_input = [[temp_max, chuva, fds]]\nprint(f'Consumo previsto simulação: {model.predict(X_input)[0].round(2)} litros\\n')","sub_path":"comparando_modelos.py","file_name":"comparando_modelos.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"568059199","text":"#Query an application\n\nappObjectNames = AdminControl.queryNames('type=Application,cell=' + 'swfihs6dCell01' + ',node=' + 'swfihs6dNode01' + ',process=' + 'servertecca' + ',name=' + 'tecca_20131128' + ',*')\n\nlineSeparator = java.lang.System.getProperty('line.separator')\nappObjectName = appObjectNames.split(lineSeparator)[0]\nappObjectName = appObjectName.strip()\n\n# get application status\n\nif len(appObjectName) == 0:\n tprint(prefix + 'application ' + appName + ' is stopped')\nelse: \n tprint(prefix + 'application ' + appName + ' is started')\n\n\n\n#Query running servers\nrunning_servers = AdminControl.queryNames('WebSphere:type=Server,*')\nlineSeparator = java.lang.System.getProperty('line.separator')\nrunning_server0 = running_servers.split(lineSeparator)[0]\nrunning_server0 = running_server.strip()\nrunning_server1 = running_servers.split(lineSeparator)[1]\nrunning_server1 = running_server.strip()\n","sub_path":"WAS_Deployment_Automation/Query.py","file_name":"Query.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"129827056","text":"import network, machine, time, math\nimport ujson\n\nprint('Starting boot(try to store wifi).py')\n\n# ssid = 'KVN'\n# ssidpss = 'cccccccc'\nssid = ''\nssidpss = ''\n\ntry:\n # with open('config.txt') as config_file:\n # config_text = config_file.read()\n # config_parced = ujson.loads(config_text)\n # ssid = config_parced['ssid']\n # ssidpss = config_parced['ssidpss']\n file = open('config.txt')\n text = file.read()\n config_parced = ujson.loads(text)\n ssid = config_parced['ssid']\n print('DBG got SSID {}'.format(ssid))\n ssidpss = config_parced['ssidpss']\n print('DBG got ssidpss {}'.format(ssidpss))\n\nexcept:\n print('DBG error reading settings')\n\n\n# >>> file = open('config.txt')\n# >>> text = file.read()\n# >>> text\n# '{\"ssid\":\"KVN\",\"ssidpss\":\"cccccccc\",\"trick\":\"demo\"}'\n# >>> parced = ujson.loads(text)\n# >>> parced\n# {'ssid': 'KVN', 'ssidpss': 'cccccccc', 'trick': 'demo'}\n# >>> parced['ssid']\n\n\n# ssid = 't4m'\n# ssidpss = ''\n\ns_timeout = 200\nl_timeout = 2000\n\nnetworkpin = machine.Pin(2, machine.Pin.OUT)\nnetworkpin.on()\ntime.sleep_ms(s_timeout)\nnetworkpin.off()\ntime.sleep_ms(s_timeout)\nnetworkpin.on()\ntime.sleep_ms(s_timeout)\nnetworkpin.off()\ntime.sleep_ms(s_timeout)\nnetworkpin.on()\ntime.sleep_ms(s_timeout)\nnetworkpin.off()\ntime.sleep_ms(s_timeout)\nnetworkpin.on()\ntime.sleep_ms(s_timeout)\n\nsta_if = network.WLAN(network.STA_IF)\nap_if = network.WLAN(network.AP_IF)\n\nprint(ap_if.ifconfig())\nprint(ssid, ssidpss)\n\nsta_if.active(True)\nsta_if.connect(ssid, ssidpss)\n\ntime.sleep_ms(l_timeout)\ntime.sleep_ms(l_timeout) # 4 s\ntime.sleep_ms(l_timeout) # 6 S\n\nprint('AP:')\nprint(ap_if.ifconfig())\nprint('STATION:')\nprint(sta_if.ifconfig())\n\nnetworkpin.off()\n","sub_path":"demo-app/demo-app-010/boot(try to store wifi).py","file_name":"boot(try to store wifi).py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"255000560","text":"from __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport os\nimport sys\n\nimport tensorflow as tf\nimport numpy as np\nimport scipy.sparse as sp\nimport scipy.stats as stats\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.preprocessing import normalize\n\nfrom sklearn import manifold\nfrom scipy.special import expit\n\nfrom optimizer import OptimizerVAE\nfrom input_data import *\n\nfrom preprocessing import *\nfrom utils.visualizer import visualize_reconstruct, visualize_traverse, find_latent\nfrom utils.utils import LossesLogger\nfrom collections import defaultdict\nfrom utils.evaluation import generation_evaluation, disentangle_evaluation, reconstruct_evaluation\n\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 1.0\nconfig.gpu_options.allow_growth = True\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n \nflags.DEFINE_integer('spatial_conv_layers', 3, 'Number of spatial_conv_layers.')\nflags.DEFINE_list('s_channel', [10,10,20], 'Number of channles in spatial convolution.')\nflags.DEFINE_list('s_kernel_size', [5,5,5], 'size of kernel in each spatial conv layer.')\nflags.DEFINE_list('s_strides', [1,1,1], 'Number of strides in each spatial conv layer.')\nflags.DEFINE_integer('s_hidden_size', 100, 'length of the hidden layer of spatial.')\nflags.DEFINE_integer('s_latent_size', 100, 'length of the latent representation of spatial.')\n#graph encoder\nflags.DEFINE_integer('graph_conv_layers', 2, 'Number of graph_conv_layers.')\nflags.DEFINE_list('g_conv_hidden', [10,20], 'Number of strides in each spatial conv layer.')\nflags.DEFINE_integer('g_hidden_size', 100, 'length of the hidden layer of spatial.')\nflags.DEFINE_integer('g_latent_size', 100, 'length of the latent representation of graph.')\n#spatial graph encoder\nflags.DEFINE_integer('spatial_graph_conv_layers', 2, 'Number of spatial-graph_conv_layers.')\nflags.DEFINE_list('sg_conv_hidden', [[20,20,20],[50,50,50]], 'length of hidden size in each spatial-graph conv layer.')\nflags.DEFINE_integer('sg_hidden_size', 200, 'length of the hidden layer of spatial-graph.')\nflags.DEFINE_integer('sg_latent_size', 200, 'length of the latent representation of sptial graph.')\n#spatial decoder\nflags.DEFINE_integer('spatial_deconv_layers', 3, 'Number of spatial_deconv_layers.')\nflags.DEFINE_list('s_d_channel', [50,20,10], 'Number of channles in spatial deconvolution.')\nflags.DEFINE_list('s_d_kernel_size', [5,5,5], 'size of kernel in each spatial deconv layer.')\nflags.DEFINE_list('s_d_strides', [1,1,1], 'Number of strides in each spatial deconv layer.')\n#graph decoder\nflags.DEFINE_integer('graph_deconv_layers', 2, 'Number of graph_deconv_layers.')\nflags.DEFINE_list('n_d_channel', [50,20,10], 'Number of channles in node deconvolution.')\nflags.DEFINE_list('n_d_kernel_size', [5,5,5], 'size of kernel in each node deconv layer.')\nflags.DEFINE_list('n_d_strides', [1,1,1], 'Number of strides in each node deconv layer.')\nflags.DEFINE_integer('d_hidden_size', 20, 'length of the hidden layer of graph deconv.')\nflags.DEFINE_list('e_d_hidden', [50,20,10], 'Number of channles in sedge deconvolution.')\n\nflags.DEFINE_integer('node_h_size', 20, 'node latent size in decoder part.')\nflags.DEFINE_string('model_type', 'disentangled', 'base, disentangled, disentangled_C,NED-VAE-IP,beta-TCVAE, geoGCN, posGCN')\n\n#training paramters\nflags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')\nflags.DEFINE_integer('epochs', 2000, 'Number of epochs to train.')\nflags.DEFINE_float('dropout', 1, 'keep probability.')\nflags.DEFINE_integer('batch_size', 2, 'Number of samples in a batch.')\nflags.DEFINE_integer('decoder_batch_size',2, 'Number of samples in a batch.')\nflags.DEFINE_integer('sg_batch_size', 5, 'Number of samples in a batch.')\nflags.DEFINE_integer('sg_decoder_batch_size',5, 'Number of samples in a batch.')\nflags.DEFINE_string('dataset_path', '../dataset/', 'Number of samples in a batch.')\nflags.DEFINE_integer('num_feature', 1, 'Number of features.')\nflags.DEFINE_integer('spatial_dim', 2, 'The dimension of spatial information.')\nflags.DEFINE_integer('verbose', 1, 'Output all epoch data')\nflags.DEFINE_integer('test_count', 10, 'batch of tests')\nflags.DEFINE_string('model', 'feedback', 'Model string.')\nflags.DEFINE_integer('seeded', 1, 'Set numpy random seed')\nflags.DEFINE_integer('connected_split', 0, 'use split with training set always connected')\nflags.DEFINE_string('type', 'test_reconstruct', 'train or test')\nflags.DEFINE_integer('if_traverse', 1, 'varying the z to see the generated graphs')\nflags.DEFINE_integer('visualize_length', 5, 'varying the z to see the generated graphs')\nflags.DEFINE_string('dataset', 'synthetic2', 'synthetic1 or synthetic2')\n\nflags.DEFINE_float('C_max', 100, 'capacity parameter(C) of bottleneck channel')\nflags.DEFINE_float('C_stop_iter', 1e2, 'when to stop increasing the capacity')\nflags.DEFINE_float('gamma', 100, 'gamma parameter for KL-term in understanding beta-VAE')\nflags.DEFINE_float('C_step', 20, 'every c_step epoch the C changes')\n\nflags.DEFINE_integer('sampling_num', 10, 'sampling ten times')\n\nflags.DEFINE_integer('dim', None, 'dim for traverse')\nflags.DEFINE_string('group_type', None, 'group type for traverse')\n\nif FLAGS.model_type=='base':\n from model_joint import *\nelse:\n from model import *\n\ndef ZscoreNormalization(x, mean_, std_):\n \"\"\"Z-score normaliaztion\"\"\"\n x = (x - mean_) / std_\n return x\n\n\ndef main(beta, type_model):\n if 'vae_type' in list(flags.FLAGS):\n delattr(flags.FLAGS,'vae_type')\n flags.DEFINE_string('vae_type', type_model, 'local or global or local_global')\n\n if FLAGS.type =='test_disentangle':\n FLAGS.batch_size=FLAGS.visualize_length*(FLAGS.s_latent_size+FLAGS.g_latent_size+FLAGS.sg_latent_size)\n FLAGS.decoder_batch_size=FLAGS.batch_size\n if FLAGS.seeded:\n np.random.seed(1)\n\n # Load data\n if FLAGS.dataset == 'synthetic1':\n dataset_path=FLAGS.dataset_path+'spatial_network_correlated1/25'\n if True:\n feature,spatial, adj, rel, factor, adj_truth = load_data_syn(FLAGS.type, dataset_path)\n adj = adj.reshape(-1,adj.shape[-2],adj.shape[-1])\n print (adj.shape)\n else:\n feature,spatial, adj, rel, factor= load_data_syn(FLAGS.type, dataset_path)\n FLAGS.spatial_conv_layers=3\n FLAGS.s_channel=[10,10,20]\n FLAGS.s_kernel_size=[5,5,5]\n FLAGS.s_strides=[1,1,1]\n FLAGS.s_hidden_size=100\n FLAGS.s_latent_size=100\n #graph encoder\n FLAGS.graph_conv_layers= 2\n FLAGS.g_conv_hidden=[10,20]\n FLAGS.g_hidden_size=100\n FLAGS.g_latent_size=100\n #spatial graph encoder\n FLAGS.spatial_graph_conv_layers=2\n FLAGS.sg_conv_hidden=[[20,20,20],[50,50,50]]\n FLAGS.sg_hidden_size=500\n FLAGS.sg_latent_size=500\n #spatial decoder\n FLAGS.spatial_deconv_layers=3\n FLAGS.s_d_channel=[50,20,10]\n FLAGS.s_d_kernel_size=[5,5,5]\n FLAGS.s_d_strides=[1,1,1]\n #graph decoder\n FLAGS.graph_deconv_layers=2\n FLAGS.n_d_channel=[50,20,10]\n FLAGS.n_d_kernel_size=[5,5,5]\n FLAGS.n_d_strides=[1,1,1]\n FLAGS.d_hidden_size=20\n FLAGS.e_d_hidden=[50,20,10]\n FLAGS.node_h_size=50\n #training paramters\n FLAGS.learning_rate=0.001\n FLAGS.epochs=1000\n FLAGS.dropout=1\n FLAGS.batch_size=10\n FLAGS.decoder_batch_size=10\n FLAGS.sg_batch_size=10\n FLAGS.sg_decoder_batch_size=10\n elif FLAGS.dataset == 'synthetic2':\n dataset_path=FLAGS.dataset_path+'spatial_network_correlated2/25'\n if True:\n feature,spatial, adj, rel, factor, adj_truth = load_data_syn(FLAGS.type, dataset_path)\n adj = adj.reshape(-1,adj.shape[-2],adj.shape[-1])\n print (adj.shape)\n else:\n feature,spatial, adj, rel, factor= load_data_syn(FLAGS.type, dataset_path)\n FLAGS.spatial_conv_layers=3\n FLAGS.s_channel=[10,10,20]\n FLAGS.s_kernel_size=[5,5,5]\n FLAGS.s_strides=[1,1,1]\n FLAGS.s_hidden_size=100\n FLAGS.s_latent_size=100\n #graph encoder\n FLAGS.graph_conv_layers= 2\n FLAGS.g_conv_hidden=[10,20]\n FLAGS.g_hidden_size=100\n FLAGS.g_latent_size=100\n #spatial graph encoder\n FLAGS.spatial_graph_conv_layers=2\n FLAGS.sg_conv_hidden=[[20,20,20],[50,50,50]]\n FLAGS.sg_hidden_size=100\n FLAGS.sg_latent_size=100\n #spatial decoder\n FLAGS.spatial_deconv_layers=3\n FLAGS.s_d_channel=[50,20,10]\n FLAGS.s_d_kernel_size=[5,5,5]\n FLAGS.s_d_strides=[1,1,1]\n #graph decoder\n FLAGS.graph_deconv_layers=2\n FLAGS.n_d_channel=[50,20,10]\n FLAGS.n_d_kernel_size=[5,5,5]\n FLAGS.n_d_strides=[1,1,1]\n FLAGS.d_hidden_size=20\n FLAGS.e_d_hidden=[50,20,10]\n FLAGS.node_h_size=20\n #training paramters\n FLAGS.learning_rate=0.0008\n FLAGS.epochs=1000\n FLAGS.dropout=1\n FLAGS.batch_size=10\n FLAGS.decoder_batch_size=10\n FLAGS.sg_batch_size=10\n FLAGS.sg_decoder_batch_size=10\n elif FLAGS.dataset == 'protein':\n FLAGS.spatial_dim = 3\n dataset_path=FLAGS.dataset_path+'protein'\n feature,spatial, adj, rel, factor, adj_truth = load_data_protein(FLAGS.type, dataset_path)\n adj = adj.reshape(-1,adj.shape[-2],adj.shape[-1])\n FLAGS.sg_conv_hidden = [[10,10,10,10],[20,20,20,20]]\n FLAGS.sg_hidden_size=50\n FLAGS.sg_latent_size=50\n FLAGS.s_hidden_size=5\n FLAGS.s_latent_size=5 \n FLAGS.g_hidden_size=5\n FLAGS.g_latent_size=5 \n FLAGS.node_h_size=5 \n FLAGS.s_channel = [10,10,20]\n FLAGS.s_kernel_size=[5,5,5]\n FLAGS.batch_size=50\n FLAGS.decoder_batch_size=50\n FLAGS.sg_batch_size=50\n FLAGS.sg_decoder_batch_size=50\n elif FLAGS.dataset == 'mnist':\n FLAGS.spatial_dim = 3\n dataset_path=FLAGS.dataset_path+'3D_mesh'\n feature,spatial, adj, rel = load_data_mnist(FLAGS.type, dataset_path)\n FLAGS.sg_conv_hidden = [[20,20,20,20],[50,50,50,50]]\n\n num_nodes = adj.shape[1]\n\n num_features = FLAGS.num_feature\n pos_weight = float(adj.shape[0] *adj.shape[1] * adj.shape[1] - adj.sum()) / adj.sum()\n norm = adj.shape[0] *adj.shape[1] * adj.shape[1] / float((adj.shape[0] *adj.shape[1] * adj.shape[1] - adj.sum()) * 2)\n\n feature=feature.reshape([-1,num_nodes,num_features])\n rel=rel.reshape([-1,num_nodes,num_nodes,1])\n\n if True:\n placeholders = {\n 'features': tf.placeholder(tf.float32,[FLAGS.batch_size*FLAGS.sampling_num,num_nodes,num_features]),\n 'spatial': tf.placeholder(tf.float32,[FLAGS.batch_size*FLAGS.sampling_num,num_nodes,FLAGS.spatial_dim]),\n 'adj': tf.placeholder(tf.float32,[FLAGS.batch_size*FLAGS.sampling_num,adj.shape[1],adj.shape[2]]),\n 'adj_truth': tf.placeholder(tf.float32,[FLAGS.batch_size,adj.shape[1],adj.shape[2]]),\n 'feature_truth': tf.placeholder(tf.float32,[FLAGS.batch_size,num_nodes,num_features]),\n 'spatial_truth': tf.placeholder(tf.float32,[FLAGS.batch_size,num_nodes,FLAGS.spatial_dim]),\n 'rel_truth': tf.placeholder(tf.float32,[FLAGS.batch_size,adj.shape[1],adj.shape[2], 1]),\n 'rel': tf.placeholder(tf.float32,[FLAGS.batch_size*FLAGS.sampling_num,adj.shape[1],adj.shape[2], 1]),\n 'dropout': tf.placeholder_with_default(0., shape=()),\n 'global_iter': tf.placeholder_with_default(0., shape=()),\n }\n else:\n placeholders = {\n 'features': tf.placeholder(tf.float32,[FLAGS.batch_size,num_nodes,num_features]),\n 'spatial': tf.placeholder(tf.float32,[FLAGS.batch_size,num_nodes,FLAGS.spatial_dim]),\n 'adj': tf.placeholder(tf.float32,[FLAGS.batch_size,adj.shape[1],adj.shape[2]]),\n 'rel': tf.placeholder(tf.float32,[FLAGS.batch_size,adj.shape[1],adj.shape[2], 1]),\n 'dropout': tf.placeholder_with_default(0., shape=()),\n 'global_iter': tf.placeholder_with_default(0., shape=()),\n }\n\n if FLAGS.type != 'test_disentangle':\n model = SGCNModelVAE(placeholders, num_features, num_nodes)\n\n TRAIN_LOSSES_LOGFILE='./train_loss_'+FLAGS.dataset+'_'+FLAGS.model_type+'.txt'\n\n losses_logger = LossesLogger(os.path.join(TRAIN_LOSSES_LOGFILE))\n\n\n if FLAGS.type=='train':\n with tf.name_scope('optimizer'):\n opt = OptimizerVAE(preds_edge=model.generated_adj_prob,\n preds_node=model.generated_node_feat,\n preds_spatial=model.generated_spatial,\n labels_edge=placeholders['adj_truth'],\n labels_node=placeholders['feature_truth'],\n labels_spatial=placeholders['spatial_truth'],\n labels_rel=placeholders['rel_truth'],\n global_iter=placeholders['global_iter'],\n model=model, num_nodes=num_nodes,\n pos_weight=pos_weight,\n norm=norm,\n beta=beta)\n\n if FLAGS.type != 'test_disentangle':\n saver = tf.train.Saver()\n if FLAGS.type=='train':\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n # Train model\n feature_truth = feature \n spatial_truth = spatial \n rel_truth = rel\n feature = np.tile(feature, (FLAGS.sampling_num,1,1))\n spatial = np.tile(spatial, (FLAGS.sampling_num,1,1))\n rel = np.tile(rel, (FLAGS.sampling_num,1,1,1))\n for epoch in range(FLAGS.epochs):\n storer = defaultdict(list)\n batch_num=int(adj.shape[0]/(FLAGS.batch_size*FLAGS.sampling_num))\n check=[]\n epoch_time = time.time()\n for i in range(batch_num):\n adj_batch=adj[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n feature_batch=feature[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n spatial_batch=spatial[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n rel_batch=rel[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n adj_truth_batch=adj_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n feature_truth_batch=feature_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n spatial_truth_batch=spatial_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n rel_truth_batch=rel_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n\n t = time.time()\n # Construct feed dictionary\n feed_dict = construct_feed_dict_train(feature_batch, spatial_batch, adj_batch, rel_batch, adj_truth_batch, feature_truth_batch, spatial_truth_batch, rel_truth_batch, placeholders)\n feed_dict.update({placeholders['dropout']: FLAGS.dropout})\n feed_dict.update({placeholders['global_iter']: epoch})\n # Run single weight update\n outs = sess.run([opt.opt_op, opt.overall_loss, model.generated_adj], feed_dict=feed_dict)\n # Compute average loss\n overall_loss=outs[1]\n acc=sum(sum(sum(outs[2]==adj_truth_batch)))/(FLAGS.batch_size*num_nodes*num_nodes)\n storer['loss'].append(overall_loss[0])\n storer['spatial_loss'].append(overall_loss[1])\n storer['adj_loss'].append(overall_loss[2])\n storer['adj_acc'].append(acc)\n storer['node_loss'].append(overall_loss[3])\n if FLAGS.model_type in ['disentangled','disentangled_C','NED-VAE-IP','beta-TCVAE']:\n storer['graph_kl'].append(overall_loss[4])\n storer['spatial_kl'].append(overall_loss[5])\n storer['sg_kl'].append(overall_loss[6])\n else:\n storer['sg_kl'].append(overall_loss[4])\n check.append(outs[2])\n\n print(\"Epoch:\", '%04d' % (epoch + 1), \"loss=\", \"{:.5f}\".format(overall_loss[0]),\n \"time=\", \"{:.5f}\".format(time.time() - t))\n print (\"epoch time=\", \"{:.5f}\".format(time.time()-epoch_time))\n if epoch%100==0:\n save_path = saver.save(sess, \"/home/ydu6/generation_eff_latent_sg/src/tmp/\"+FLAGS.dataset+'_'+FLAGS.model_type+\"/model_dgt_global_\"+str(epoch)+\".ckpt\")\n losses_logger.log(epoch, storer)\n\n print(\"Optimization Finished!\")\n return np.array(check), adj\n\n def generate_new_train(feed_dic):\n feed_dict = feed_dic\n feed_dict.update({placeholders['dropout']: 1.0})\n z_s,z_sg,z_g, adj, spatial, node = sess.run([model.z_mean_s,model.z_mean_sg,model.z_mean_g, model.generated_adj, model.generated_spatial, model.generated_node_feat], feed_dict=feed_dict)\n return z_s,z_sg,z_g, adj, spatial, node\n\n def generate_new(feature_batch, spatial_batch, adj_batch,rel_batch):\n feed_dict = construct_feed_dict(feature_batch, spatial_batch, adj_batch, rel_batch, placeholders)\n feed_dict.update({placeholders['dropout']: 1.0})\n if FLAGS.model_type == \"base\":\n z_sg, adj, node, spatial = sess.run([model.z_mean_sg, model.generated_adj,model.generated_node_feat,model.generated_spatial], feed_dict=feed_dict)\n return z_sg, adj, spatial, node\n else:\n z_s,z_sg,z_g, adj, spatial, node = sess.run([model.z_mean_s,model.z_mean_sg,model.z_mean_g, model.generated_adj, model.generated_spatial, model.generated_node_feat], feed_dict=feed_dict)\n return z_s,z_sg,z_g, adj, spatial, node\n\n if FLAGS.type =='test_reconstruct':\n with tf.Session() as sess:\n saver.restore(sess, \"/home/ydu6/generation_eff_latent_sg/src/tmp/\"+FLAGS.dataset+'_'+FLAGS.model_type+\"/model_dgt_global_\"+str(480)+\".ckpt\")\n print(\"Model restored.\")\n generated_adj=[]\n generated_nodes=[]\n generated_spatial=[]\n batch_num=int(adj.shape[0]/(FLAGS.batch_size*FLAGS.sampling_num))\n feature_truth = feature \n spatial_truth = spatial \n rel_truth = rel\n feature = np.tile(feature, (FLAGS.sampling_num,1,1))\n spatial = np.tile(spatial, (FLAGS.sampling_num,1,1))\n rel = np.tile(rel, (FLAGS.sampling_num,1,1,1))\n #generated_adj_prob=[]\n z_s=[]\n z_sg=[]\n z_g=[]\n for i in range(batch_num):\n adj_batch=adj[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n feature_batch=feature[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n spatial_batch=spatial[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n rel_batch=rel[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n adj_truth_batch=adj_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n feature_truth_batch=feature_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n spatial_truth_batch=spatial_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n rel_truth_batch=rel_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n feed_dict = construct_feed_dict_train(feature_batch, spatial_batch, adj_batch, rel_batch, adj_truth_batch, feature_truth_batch, spatial_truth_batch, rel_truth_batch, placeholders)\n z_s_batch,z_sg_batch, z_g_batch, generated_adj_, generated_spatial_, generated_node_= generate_new_train(feed_dict)\n generated_adj.append(generated_adj_)\n generated_nodes.append(generated_node_)\n generated_spatial.append(generated_spatial_)\n z_s.append(z_s_batch.reshape((FLAGS.batch_size,-1)))\n z_sg.append(z_sg_batch.reshape((FLAGS.batch_size,FLAGS.sampling_num,-1)).mean(axis=1))\n z_g.append(z_g_batch.reshape((FLAGS.batch_size,-1)))\n\n\n if FLAGS.model_type == \"base\":\n np.save('./qualitative_evaluation/'+str(FLAGS.dataset)+\"/\"+FLAGS.vae_type+'_z_sg.npy',np.array(z_sg))\n else:\n np.save('./qualitative_evaluation/'+str(FLAGS.dataset)+\"/\"+FLAGS.vae_type+'_z_s.npy',np.array(z_s))\n np.save('./qualitative_evaluation/'+str(FLAGS.dataset)+\"/\"+FLAGS.vae_type+'_z_sg.npy',np.array(z_sg))\n np.save('./qualitative_evaluation/'+str(FLAGS.dataset)+\"/\"+FLAGS.vae_type+'_z_g.npy',np.array(z_g))\n print (len(z_s))\n print (z_s[0].shape)\n generated_adj=np.array(generated_adj).reshape(-1,num_nodes,num_nodes)\n generated_nodes=np.array(generated_nodes).reshape(-1,num_nodes,num_features)\n generated_spatial=np.array(generated_spatial).reshape(-1,num_nodes,FLAGS.spatial_dim)\n #visualize_reconstruct(5, adj_batch, feature_batch*120, spatial_batch*600, generated_adj, generated_nodes*120, generated_spatial*600)\n evaluate_results=reconstruct_evaluation(generated_adj,generated_nodes,generated_spatial, adj_truth, feature_truth, spatial_truth, FLAGS.dataset)\n disentangle_results=disentangle_evaluation(z_s, z_g, z_sg, factor, FLAGS.dataset)\n print (evaluate_results,disentangle_results)\n return disentangle_results\n\n if FLAGS.type =='test_generation':\n with tf.Session() as sess:\n saver.restore(sess, \"/home/ydu6/generation_eff_latent_sg/src/tmp/\"+FLAGS.dataset+'_'+FLAGS.model_type+\"/model_dgt_global_\"+str(480)+\".ckpt\")\n print(\"Model restored.\")\n generated_adj=[]\n generated_nodes=[]\n generated_spatial=[]\n batch_num=int(adj.shape[0]/(FLAGS.batch_size*FLAGS.sampling_num))\n feature_truth = feature \n spatial_truth = spatial \n rel_truth = rel\n feature = np.tile(feature, (FLAGS.sampling_num,1,1))\n spatial = np.tile(spatial, (FLAGS.sampling_num,1,1))\n rel = np.tile(rel, (FLAGS.sampling_num,1,1,1))\n z_s=[]\n z_sg=[]\n z_g=[]\n for i in range(batch_num):\n adj_batch=adj[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n feature_batch=feature[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n spatial_batch=spatial[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n rel_batch=rel[i*FLAGS.batch_size*FLAGS.sampling_num:i*FLAGS.batch_size*FLAGS.sampling_num+FLAGS.batch_size*FLAGS.sampling_num]\n adj_truth_batch=adj_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n feature_truth_batch=feature_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n spatial_truth_batch=spatial_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n rel_truth_batch=rel_truth[i*FLAGS.batch_size:i*FLAGS.batch_size+FLAGS.batch_size]\n feed_dict = construct_feed_dict_train(feature_batch, spatial_batch, adj_batch, rel_batch, adj_truth_batch, feature_truth_batch, spatial_truth_batch, rel_truth_batch, placeholders)\n z_s_batch,z_sg_batch, z_g_batch, generated_adj_, generated_spatial_, generated_node_= generate_new_train(feed_dict)\n generated_adj.append(generated_adj_)\n generated_nodes.append(generated_node_)\n generated_spatial.append(generated_spatial_)\n z_s.append(z_s_batch.reshape((FLAGS.batch_size,-1)))\n z_sg.append(z_sg_batch.reshape((FLAGS.batch_size,FLAGS.sampling_num,-1)).mean(axis=1))\n z_g.append(z_g_batch.reshape((FLAGS.batch_size,-1)))\n\n generated_adj=np.array(generated_adj).reshape(-1,num_nodes,num_nodes)\n generated_nodes=np.array(generated_nodes).reshape(-1,num_nodes,num_features)\n generated_spatial=np.array(generated_spatial).reshape(-1,num_nodes,FLAGS.spatial_dim)\n #visualize_reconstruct(5, adj_batch, feature_batch*120, spatial_batch*600, generated_adj, generated_nodes*120, generated_spatial*600)\n evaluate_results=generation_evaluation(generated_adj,generated_nodes,generated_spatial, adj, feature, spatial, FLAGS.dataset)\n print (evaluate_results)\n return evaluate_results\n\n\n\n if FLAGS.type== 'test_disentangle':\n with tf.Session() as sess:\n generated_adj=[]\n generated_nodes=[]\n generated_spatial=[]\n adj_batch=adj[:FLAGS.batch_size]\n feature_batch=feature[:FLAGS.batch_size]\n spatial_batch=spatial[:FLAGS.batch_size]\n rel_batch=rel[:FLAGS.batch_size]\n model = SGCNModelVAE(placeholders, num_features, num_nodes, group_type=FLAGS.group_type, dim=FLAGS.dim, dim_a=77, dim_b=48, dim_c=171)\n saver = tf.train.Saver()\n saver.restore(sess, \"/home/ydu6/generation/src/tmp/\"+FLAGS.dataset+'_'+FLAGS.model_type+\"/model_dgt_global_\"+str(300)+\".ckpt\")\n print(\"Model restored.\")\n\n z_s,z_sg, z_g, generated_adj, generated_spatial, generated_nodes = generate_new(feature_batch, spatial_batch, adj_batch, rel_batch)\n generated_adj=np.array(generated_adj).reshape([-1, num_nodes, num_nodes])\n generated_nodes=np.array(generated_nodes).reshape([-1, num_nodes, num_features])\n generated_spatial=np.array(generated_spatial).reshape([-1, num_nodes,FLAGS.spatial_dim])\n print (generated_adj.shape, generated_nodes.shape, generated_spatial.shape)\n min_n, max_n = np.min(generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2]*120), np.max(generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2]*120)\n generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2] = (generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2]*120-min_n)/(max_n-min_n)\n # print (np.min(generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2]),np.max(generated_nodes[FLAGS.visualize_length:FLAGS.visualize_length*2]))\n print (np.min(generated_spatial[:FLAGS.visualize_length]*600), np.max(generated_spatial[:FLAGS.visualize_length]*600))\n print (np.min(generated_spatial)*600, np.max(generated_spatial)*600)\n visualize_traverse(generated_adj, generated_nodes*120, generated_spatial*600,1,FLAGS.visualize_length,FLAGS.dataset)\n # print('spatial:'+str(a))\n # print('graph:'+str(b))\n # print('joint:'+str(c))\n\nif __name__ == '__main__':\n np_load_old = np.load\n np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)\n models=['disentangled'] #'posGCN','geoGCN','disentangled_C''NED-VAE-IP','beta-TCVAE','disentangled','base',,,,,,'InfoVAE',,, ,'HFVAE'],,,,'InfoVAE''FactorVAE''InfoVAE','DIP-VAE''FactorVAE','HFVAE'\n types= ['train','test_reconstruct','test_generation']\n generation_results={}\n reconstruct_results={}\n for type_ in types:\n FLAGS.type=type_\n for t in models:\n tf.reset_default_graph()\n FLAGS.model_type=t\n if FLAGS.type =='train':\n main(1,t)\n elif FLAGS.type =='test_reconstruct':\n reconstruct_result=main(1,t)\n reconstruct_results[t]=reconstruct_result\n elif FLAGS.type =='test_generation':\n generation_result=main(1,t)\n generation_results[t]=generation_result\n else:\n main(1,t)\n print(generation_results)\n print(reconstruct_results)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"37871919","text":"from pandas.tseries.holiday import USFederalHolidayCalendar\nimport numpy as np\nimport pandas as pd\nimport time\nimport os\n\ndef get_demand(data):\n cal = USFederalHolidayCalendar()\n holidays = cal.holidays(start='2018-01-01', end='2019-01-01')\n demand = np.load('demand.npy')\n date = pd.to_datetime(data['tpep_dropoff_datetime']).dt.date\n dayofweek = pd.to_datetime(data['tpep_dropoff_datetime']).dt.dayofweek\n hour = pd.to_datetime(data['tpep_dropoff_datetime']).dt.hour\n for index, row in data.iterrows():\n if date[index] in holidays:\n dtype = 2\n elif dayofweek[index] in [5, 6]:\n dtype = 1\n else:\n dtype = 0\n period = hour[index]//2\n orig = int(row[\"PULocationID\"]) - 1\n dest = int(row[\"DOLocationID\"]) - 1\n demand[dtype, period, orig, dest] += 1\n return demand\n\nos.chdir(\"/Users/Vince7/desktop/Didi_Project/experiment\")\ndemand = np.zeros((3, 12, 265, 265))\nnp.save('demand.npy', demand)\n\nfor filename in os.listdir():\n data = pd.read_csv(filename).dropna()\n demand = get_demand(data)\n np.save('demand.npy', demand)\n print(demand)\n","sub_path":"demand_simulation.py","file_name":"demand_simulation.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"211769595","text":"'''\n\tWARM-UP:\n\tWhat is the name, type and value of the following variables?\n\t1) name = \"Aaron Kaminsky\"\n\t2) age = 19\n\t3) is_counselor = True\n'''\nnum_1 = input(\"What is the first number you would like to add: \")\t#Recieve the first input\nnum_2 = input(\"What is the second number you would like to add: \")\t#Recieve the second input\n\nsum = num_1 + num_2\t#Addition\n\nprint( str(num_1) + \" + \" + str(num_2) + \" = \" + str(sum) )\t#Print Statement","sub_path":"Sci_Tech_Intro_to_Python/Demo2.py","file_name":"Demo2.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"602822620","text":"cities = {\n 'James Island': {'pop': \"50000\", 'country': \"USA\", 'fact': 'has a beach'},\n 'Charleston': {'pop': \"100000\", 'country': \"USA\", 'fact': 'hateful people'},\n}\n\nfor town, info in cities.items():\n print(\"\\n\" + town.title() + \":\")\n population = info['pop']\n country = info['country']\n fact = info['fact']\n\n print(\"\\t\" + \"Population: \" + population)\n print(\"\\t\" + \"Country: \" + country)\n print(\"\\t\" + \"Fact: \" + fact)","sub_path":"Chapter6/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"331584660","text":"import numpy as np\nimport numba\nfrom .fast_interp import interp1d\n\nclass FunctionGenerator(object):\n \"\"\"\n This class provides a simple way to construct a fast \"function evaluator\"\n For 1-D functions defined on an interval\n \"\"\"\n def __init__(self, f, a, b, tol=1e-10, n=1000, k=5):\n \"\"\"\n f: function to create evaluator for\n a: lower bound of evaluation interval\n b: upper bound of evaluation interval\n tol: accuracy to recreate function to\n n: number of points used in interpolations\n k: degree of polynomial used (1, 3, 5, or 7)\n \"\"\"\n self.f = f\n self.a = float(a)\n self.b = float(b)\n self.tol = tol\n self.n = n\n self.k = k\n self.lbs = []\n self.ubs = []\n self.hs = []\n self.fs = []\n self._fit(self.a, self.b)\n self.lbs = np.array(self.lbs)\n self.ubs = np.array(self.ubs)\n self.hs = np.array(self.hs)\n self.fs = np.row_stack(self.fs)\n def __call__(self, x, out=None):\n \"\"\"\n Evaluate function at input x\n \"\"\"\n if isinstance(x, np.ndarray):\n xr = x.ravel()\n outr = np.zeros_like(xr) if out is None else out.ravel()\n _evaluates[self.k](self.fs, xr, outr, self.lbs, self.ubs, self.hs, self.n)\n return outr.reshape(x.shape)\n else:\n return _evaluate1s[self.k](self.fs, x, self.lbs, self.ubs, self.hs, self.n)\n def _fit(self, a, b):\n x, h = np.linspace(a, b, self.n, retstep=True)\n interp = interp1d(a, b, h, self.f(x), self.k, c=True)\n check_x = x[:-1] + h/2.0\n check_f = self.f(check_x)\n estim_f = interp(check_x)\n reg = np.abs(check_f)\n reg[reg < 1] = 1.0\n err = np.abs((check_f-estim_f)/reg).max()\n if err < self.tol:\n self.lbs.append(a)\n self.ubs.append(b)\n self.fs.append(interp._f)\n self.hs.append(h)\n else:\n m = a + (b-a)/2\n self._fit(a, m)\n self._fit(m, b)\n\n@numba.njit\ndef _single_interp_1d_k1(f, x, a, h, n):\n xx = x - a\n ix = min(int(xx//h), n-2)\n ratx = xx/h - (ix+0.5)\n asx = np.empty(2)\n asx[0] = 0.5 - ratx\n asx[1] = 0.5 + ratx\n fout = 0.0\n for i in range(2):\n fout += f[ix+i]*asx[i]\n return fout\n@numba.njit\ndef _single_interp_1d_k3(f, x, a, h, n):\n xx = x - a\n ix = min(int(xx//h), n-2)\n ratx = xx/h - (ix+0.5)\n asx = np.empty(4)\n asx[0] = -1/16 + ratx*( 1/24 + ratx*( 1/4 - ratx/6))\n asx[1] = 9/16 + ratx*( -9/8 + ratx*(-1/4 + ratx/2))\n asx[2] = 9/16 + ratx*( 9/8 + ratx*(-1/4 - ratx/2))\n asx[3] = -1/16 + ratx*(-1/24 + ratx*( 1/4 + ratx/6))\n fout = 0.0\n for i in range(4):\n fout += f[ix+i]*asx[i]\n return fout\n@numba.njit\ndef _single_interp_1d_k5(f, x, a, h, n):\n xx = x - a\n ix = min(int(xx//h), n-2)\n ratx = xx/h - (ix+0.5)\n asx = np.empty(6)\n asx[0] = 3/256 + ratx*( -9/1920 + ratx*( -5/48/2 + ratx*( 1/8/6 + ratx*( 1/2/24 - 1/8/120*ratx))))\n asx[1] = -25/256 + ratx*( 125/1920 + ratx*( 39/48/2 + ratx*(-13/8/6 + ratx*(-3/2/24 + 5/8/120*ratx))))\n asx[2] = 150/256 + ratx*(-2250/1920 + ratx*(-34/48/2 + ratx*( 34/8/6 + ratx*( 2/2/24 - 10/8/120*ratx))))\n asx[3] = 150/256 + ratx*( 2250/1920 + ratx*(-34/48/2 + ratx*(-34/8/6 + ratx*( 2/2/24 + 10/8/120*ratx))))\n asx[4] = -25/256 + ratx*( -125/1920 + ratx*( 39/48/2 + ratx*( 13/8/6 + ratx*(-3/2/24 - 5/8/120*ratx))))\n asx[5] = 3/256 + ratx*( 9/1920 + ratx*( -5/48/2 + ratx*( -1/8/6 + ratx*( 1/2/24 + 1/8/120*ratx))))\n fout = 0.0\n for i in range(6):\n fout += f[ix+i]*asx[i]\n return fout\n@numba.njit\ndef _single_interp_1d_k7(f, x, a, h, n):\n xx = x - a\n ix = min(int(xx//h), n-2)\n ratx = xx/h - (ix+0.5)\n asx = np.empty(8)\n asx[0] = -5/2048 + ratx*( 75/107520 + ratx*( 259/11520/2 + ratx*( -37/1920/6 + ratx*( -7/48/24 + ratx*( 5/24/120 + ratx*( 1/2/720 - 1/5040*ratx))))))\n asx[1] = 49/2048 + ratx*( -1029/107520 + ratx*(-2495/11520/2 + ratx*( 499/1920/6 + ratx*( 59/48/24 + ratx*( -59/24/120 + ratx*(-5/2/720 + 7/5040*ratx))))))\n asx[2] = -245/2048 + ratx*( 8575/107520 + ratx*(11691/11520/2 + ratx*(-3897/1920/6 + ratx*(-135/48/24 + ratx*( 225/24/120 + ratx*( 9/2/720 - 21/5040*ratx))))))\n asx[3] = 1225/2048 + ratx*(-128625/107520 + ratx*(-9455/11520/2 + ratx*( 9455/1920/6 + ratx*( 83/48/24 + ratx*(-415/24/120 + ratx*(-5/2/720 + 35/5040*ratx))))))\n asx[4] = 1225/2048 + ratx*( 128625/107520 + ratx*(-9455/11520/2 + ratx*(-9455/1920/6 + ratx*( 83/48/24 + ratx*( 415/24/120 + ratx*(-5/2/720 - 35/5040*ratx))))))\n asx[5] = -245/2048 + ratx*( -8575/107520 + ratx*(11691/11520/2 + ratx*( 3897/1920/6 + ratx*(-135/48/24 + ratx*(-225/24/120 + ratx*( 9/2/720 + 21/5040*ratx))))))\n asx[6] = 49/2048 + ratx*( 1029/107520 + ratx*(-2495/11520/2 + ratx*( -499/1920/6 + ratx*( 59/48/24 + ratx*( 59/24/120 + ratx*(-5/2/720 - 7/5040*ratx))))))\n asx[7] = -5/2048 + ratx*( -75/107520 + ratx*( 259/11520/2 + ratx*( 37/1920/6 + ratx*( -7/48/24 + ratx*( -5/24/120 + ratx*( 1/2/720 + 1/5040*ratx))))))\n fout = 0.0\n for i in range(8):\n fout += f[ix+i]*asx[i]\n return fout\n\n@numba.njit\ndef _get_ind(x, ubs):\n ind = 0\n while(x > ubs[ind]):\n ind += 1\n return ind\n\n@numba.njit(fastmath=True)\ndef _evaluate1_1(fs, x, lbs, ubs, hs, n):\n ind = _get_ind(x, ubs)\n return _single_interp_1d_k1(fs[ind], x, lbs[ind], hs[ind], n)\n@numba.njit(fastmath=True)\ndef _evaluate1_3(fs, x, lbs, ubs, hs, n):\n ind = _get_ind(x, ubs)\n return _single_interp_1d_k3(fs[ind], x, lbs[ind], hs[ind], n)\n@numba.njit(fastmath=True)\ndef _evaluate1_5(fs, x, lbs, ubs, hs, n):\n ind = _get_ind(x, ubs)\n return _single_interp_1d_k5(fs[ind], x, lbs[ind], hs[ind], n)\n@numba.njit(fastmath=True)\ndef _evaluate1_7(fs, x, lbs, ubs, hs, n):\n ind = _get_ind(x, ubs)\n return _single_interp_1d_k7(fs[ind], x, lbs[ind], hs[ind], n)\n\n@numba.njit(parallel=True, fastmath=True)\ndef _evaluate_1(fs, xs, out, lbs, ubs, hs, n):\n m = xs.shape[0]\n for i in numba.prange(m):\n out[i] = _evaluate1_1(fs, xs[i], lbs, ubs, hs, n)\n@numba.njit(parallel=True, fastmath=True)\ndef _evaluate_3(fs, xs, out, lbs, ubs, hs, n):\n m = xs.shape[0]\n for i in numba.prange(m):\n out[i] = _evaluate1_3(fs, xs[i], lbs, ubs, hs, n)\n@numba.njit(parallel=True, fastmath=True)\ndef _evaluate_5(fs, xs, out, lbs, ubs, hs, n):\n m = xs.shape[0]\n fplop = np.empty((6, m), dtype=np.float64)\n asxs = np.empty((6, m), dtype=np.float64)\n ixs = np.empty(m, dtype=np.int32)\n ratxs = np.empty(m, dtype=np.float64)\n inds = np.empty(m, dtype=np.int32)\n for k in numba.prange(m):\n x = xs[k]\n ind = 0\n while(x > ubs[ind]):\n ind += 1\n a = lbs[ind]\n h = hs[ind]\n xx = x - a\n ix = min(int(xx//h), n-2)\n ratxs[k] = xx/h - (ix+0.5)\n ixs[k] = ix\n inds[k] = ind\n for k in numba.prange(m):\n ratx = ratxs[k]\n asxs[0, k] = 3/256 + ratx*( -9/1920 + ratx*( -5/48/2 + ratx*( 1/8/6 + ratx*( 1/2/24 - 1/8/120*ratx))))\n asxs[1, k] = -25/256 + ratx*( 125/1920 + ratx*( 39/48/2 + ratx*(-13/8/6 + ratx*(-3/2/24 + 5/8/120*ratx))))\n asxs[2, k] = 150/256 + ratx*(-2250/1920 + ratx*(-34/48/2 + ratx*( 34/8/6 + ratx*( 2/2/24 - 10/8/120*ratx))))\n asxs[3, k] = 150/256 + ratx*( 2250/1920 + ratx*(-34/48/2 + ratx*(-34/8/6 + ratx*( 2/2/24 + 10/8/120*ratx))))\n asxs[4, k] = -25/256 + ratx*( -125/1920 + ratx*( 39/48/2 + ratx*( 13/8/6 + ratx*(-3/2/24 - 5/8/120*ratx))))\n asxs[5, k] = 3/256 + ratx*( 9/1920 + ratx*( -5/48/2 + ratx*( -1/8/6 + ratx*( 1/2/24 + 1/8/120*ratx))))\n for k in numba.prange(m):\n ix = ixs[k]\n ind = inds[k]\n for i in range(6):\n fplop[i, k] = fs[ind, ix+i]\n for k in numba.prange(m):\n out[k] = 0.0\n for i in range(6):\n out[k] += fplop[i,k]*asxs[i,k]\n@numba.njit(parallel=True, fastmath=True)\ndef _evaluate_7(fs, xs, out, lbs, ubs, hs, n):\n m = xs.shape[0]\n for i in numba.prange(m):\n out[i] = _evaluate1_7(fs, xs[i], lbs, ubs, hs, n)\n\n_evaluate1s = [None, _evaluate1_1, None, _evaluate1_3, None, _evaluate1_5, None, _evaluate1_7]\n_evaluates = [None, _evaluate_1, None, _evaluate_3, None, _evaluate_5, None, _evaluate_7 ]\n\n","sub_path":"fast_interp/function_generator.py","file_name":"function_generator.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"522967016","text":"# Master in Computer Vision\n# Module 3 - Machine Learning\n\nclass Window:\n height = 0\n width = 0\n x = 0\n y = 0\n x1 = 0\n x2 = 0\n y1 = 0\n y2 = 0\n\n def __init__(self, in_x, in_y, in_h, in_w):\n self.height = in_h\n self.width = in_w\n self.x = in_x\n self.y = in_y\n self.x1 = in_x\n self.x2 = in_x + in_w\n self.y1 = in_y\n self.y2 = in_y + in_h\n \n # Returns true if the intersection of window_1 with window_2 is at least 50%\n def overlap(self, in_window):\n result = False\n if self.x1 <= in_window.x1 <= self.x2 and self.y1 <= in_window.y1 <= self.y2:\n intersection_x = min(self.x2,in_window.x2)-in_window.x1\n intersection_y = min(self.y2,in_window.y2)-in_window.y1\n if float(intersection_x*intersection_y)/float(self.width*self.height) > 0.5:\n result = True\n elif in_window.x1 <= self.x1 <= in_window.x2 and in_window.y1 <= self.y1 <= in_window.y2:\n intersection_x = min(self.x2,in_window.x2)-self.x1\n intersection_y = min(self.y2,in_window.y2)-self.y1\n if float(intersection_x*intersection_y)/float(self.width*self.height) > 0.5:\n result = True\n return result\n\n def __repr__(self):\n return str(self.x)+\" \"+str(self.y)+\" \"+str(self.height)+\" \"+str(self.width)\n\n def get_as_array(self):\n win = [self.x, self.y, self.height, self.width]\n return win\n","sub_path":"Simple Detection/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"244421493","text":"input_list = [] # two dimensional list\n\ntry:\n with open('out.csv', 'r') as file:\n for row in file:\n input_list.append(row.rstrip('\\n').split(','))\n file.close()\nexcept FileNotFoundError as ex:\n print(\"File Not Found\")\n\nprint(input_list)\n","sub_path":"ReadCSV.py","file_name":"ReadCSV.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"121510213","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 19 11:32:57 2019\r\n\r\n@author: Pedro Augusto\r\n\"\"\"\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef request(url):\r\n headers = {'User-Agent': 'Mozilla/5.0'}\r\n source = requests.get('https://old.reddit.com/r/' + url + '/', headers=headers)\r\n return source\r\n\r\n#%% Wrapper\r\nif __name__ == \"__main__\": \r\n input_ = input(\"Entre com os subreddits separados por ponto-e-vírgula: \")\r\n url = input_.split(';')\r\n #url = ['askreddit', 'worldnews', 'cats']\r\n \r\n for u in url:\r\n source = request(u)\r\n soup = BeautifulSoup(source.text, 'html.parser')\r\n \r\n#%% Navegação pelas tags \r\n subreddit = '/r/' + u\r\n upvotes, title, link, comments_link = [],[],[],[]\r\n \r\n for paragraph in soup.find_all('div', class_='score unvoted'):\r\n if paragraph.string != \"•\":\r\n upvotes.append(paragraph.get('title'))\r\n else:\r\n upvotes.append('0')\r\n \r\n for paragraph in soup.find_all('a', class_='title'):\r\n title.append(str(paragraph.text))\r\n if paragraph.get('href')[0] == '/':\r\n link.append('https://old.reddit.com' + paragraph.get('href'))\r\n else:\r\n link.append(paragraph.get('href'))\r\n \r\n for url in soup.find_all('a', class_={'bylink comments empty may-blank', 'bylink comments may-blank'}):\r\n comments_link.append(url.get('href'))\r\n \r\n if len(upvotes) == 0:\r\n print(\"Subreddit não encontrado: {0}\".format(subreddit))\r\n continue\r\n \r\n # Remove a thread referente à propagando, caso exista \r\n if len(comments_link) != len(link):\r\n upvotes.pop(0)\r\n title.pop(0)\r\n link.pop(0)\r\n\r\n#%% Desconsiderar as threads com menos de 5000 upvotes \r\n i, k = 0, 0\r\n j = len(upvotes) \r\n while k < j:\r\n if int(upvotes[i]) < 5000:\r\n upvotes.pop(i)\r\n title.pop(i)\r\n link.pop(i)\r\n comments_link.pop(i)\r\n else:\r\n i = i + 1 \r\n k = k + 1 \r\n \r\n if len(upvotes) == 0:\r\n print(\"Nenhuma thread relevante para o subreddit: {0}\".format(u))\r\n \r\n#%% Impressão das informações\r\n for i in range(0, len(upvotes)): \r\n print(\"Subreddit: {0}\".format(subreddit))\r\n print(\"Título da thread: {0}\".format(title[i]))\r\n print(\"Número de upvotes: {0}\".format(upvotes[i])) \r\n print(\"Link para os comentários da thread: {0}\".format(comments_link[i]))\r\n print(\"Link da thread: {0}\\n\".format(link[i]))\r\n \r\n print(\"\\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n\\n\")","sub_path":"crawlers/crawlers_idwall.py","file_name":"crawlers_idwall.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"630339659","text":"'''---------------------------------------------------------------------\nCashManagementHooksDefault module contains functions called by CashManagment. \nIt should never be edited. All functions in CashManagementHooksDefault can be \noverridden in a CashManagementHooks module. To do so, create a module called CashManagementHooks \n(or rename the CashManagementHooksDefault to CashManagementHooks) and copy the function \ndeclaration of the function you want to override into it. \n---------------------------------------------------------------------'''\n\ndef AdjustmentInitialAttributeValues(row):\n '''\n Used to set initial values in the Cash Transfer Instrument Definition when\n opened using \"Adjust Cash\" from the Portfolio sheet\n \n row: A acm.FSingleInstrumentAndTrades object\n return value: A dictionary where the Key is the FCashEntry attribute, and the value\n is the value to initially set on the source trade.\n '''\n return DefaultInitialAttrubuteValues(row)\n\ndef FXRateFixingInitialSourceAttributeValues(row):\n '''\n Used to set initial values in the Cash Transfer Instrument Definition when\n opened using \"Fix RPL Fx Rate\" from the Portfolio sheet\n \n row: A acm.FSingleInstrumentAndTrades object\n return value: A dictionary where the Key is the FCashDualCurrencyEntry attribute, and the value\n is the value to initially set on the source trade.\n '''\n return DefaultInitialAttrubuteValues(row)\n\ndef FXRateFixingInitialDestinationAttributeValues(row):\n '''\n Used to set initial values in the Cash Transfer Instrument Definition when\n opened using \"Fix RPL Fx Rate\" from the Portfolio sheet\n \n row: A acm.FSingleInstrumentAndTrades object\n return value: A dictionary where the Key is the FCashDualCurrencyEntry attribute, and the value\n is the value to initially set on the destination trade.\n '''\n return DefaultInitialAttrubuteValues(row)\n\ndef TransferInitialSourceAttributeValues(row):\n '''\n Used to set initial values in the Cash Transfer Instrument Definition when\n opened using \"Transfer RPL\" from the Portfolio sheet\n \n row: A acm.FSingleInstrumentAndTrades object\n return value: A dictionary where the Key is the FCashEntry attribute, and the value\n is the value to initially set on the source trade.\n '''\n return DefaultInitialAttrubuteValues(row)\n\ndef TransferInitialDestinationAttributeValues(row):\n '''\n Used to set initial values in the Cash Transfer Instrument Definition when\n opened using \"Transfer RPL\" from the Portfolio sheet\n \n row: A acm.FSingleInstrumentAndTrades object\n return value: A dictionary where the Key is the FCashEntry attribute, and the value\n is the value to initially set on the destination trade.\n '''\n return DefaultInitialAttrubuteValues(row)\n\ndef DefaultInitialAttrubuteValues(row):\n attributes = ['Counterparty',\n 'Portfolio',\n 'Acquirer',\n 'OptKey1',\n 'OptKey2',\n 'OptKey3',\n 'OptKey4']\n \n d = GetSharedTradeAttributesFromRow(row, attributes)\n \n return {'Counterparty' : d['Counterparty'],\n 'Trade.Portfolio' : d['Portfolio'],\n 'Trade.Acquirer' : d['Acquirer'],\n 'Trade.OptKey1' : d['OptKey1'],\n 'Trade.OptKey2' : d['OptKey2'],\n 'Trade.OptKey3' : d['OptKey3'],\n 'Trade.OptKey4' : d['OptKey4']}\n \ndef GetSharedTradeAttributesFromRow(row, attributes):\n '''\n attributes: A list of trade attributes\n return: A dictionary with the attributes as key, and value is the value of the trades attribute\n if all the trades on the row have the same value, otherwise None\n '''\n trades = row.Trades().AsArray()\n firstTrade = trades.First()\n \n d = dict()\n for att in attributes:\n d[att] = firstTrade.GetProperty(att)\n \n for t in trades:\n found = False\n for att, val in list(d.items()):\n if val and (t.GetProperty(att) == val):\n found = True\n else:\n d[att] = None\n \n if not found:\n break\n \n return d\n","sub_path":"Extensions/Instrument Definition/FPythonCode/CashManagementHooksDefault.py","file_name":"CashManagementHooksDefault.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"418960824","text":"import base64\nfrom django.http import JsonResponse\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout\nfrom django.shortcuts import render\nfrom django.db.models import Avg, Sum\nfrom django.core.files import File\nfrom .models import *\nfrom django.views.decorators.csrf import csrf_exempt\nimport json,os\n\n\ndef logout_view(req):\n ctx = {}\n logout(req)\n return render(req, 'ecosmart/index.tpl', ctx)\n\n# Create your views here.\ndef index(req):\n ctx = {}\n if req.method == 'POST':\n user = authenticate(username=req.POST['user'], password=req.POST['pwd'])\n if user is not None and user.is_active:\n login(req, user)\n if req.user.is_authenticated():\n return render(req, 'ecosmart/frontend.tpl', ctx)\n else:\n return render(req, 'ecosmart/index.tpl', ctx)\n\n\ndef api_trashcans(req):\n ctx = {}\n ctx['trashcans'] = [ { 'id': tc.id, 'address': tc.address, 'trash_type': tc.trash_type_id, 'max_kg': tc.max_kg } for tc in\n TrashCan.objects.all().order_by('trash_type') ]\n return JsonResponse(ctx, safe=False)\n\n\ndef api_trashcan(req, id=None):\n if req.method == 'GET':\n if id == None:\n return api_trashcans(req)\n tc = TrashCan.objects.get(id = id)\n return JsonResponse( { 'id': tc.id, 'address': tc.address, 'trash_type': tc.trash_type_id, 'max_kg': tc.max_kg } )\n\n\ndef api_hhsummary(req):\n if req.method != 'GET':\n return\n ctx = {}\n # get for current household, linked through currently logged in user\n tes = TrashEvent.objects.filter(household__householduser__user = req.user)\n\n ctx['events'] = [ { 'id': te.id, 'date': te.date, 'kg': te.kg, 'trash_can': te.trash_can_id, 'flags': te.flags } for te in tes ]\n ctx['tr_labels'] = [ format_date(ev['date']) for ev in ctx['events'] ]\n ctx['tr_values'] = [ ev['kg'] for ev in ctx['events'] ]\n\n ctx['trash_types'] = [ {'id': tt.id, 'name': tt.name, 'cost_kg': tt.cost_kg } for tt in TrashType.objects.all().order_by('name') ]\n ctx['tt_labels'] = [ tt['name'] for tt in ctx['trash_types'] ]\n ctx['tt_values'] = [ TrashEvent.objects.filter(trash_can__trash_type_id = tt['id']).aggregate(Sum('kg'))['kg__sum'] for tt in ctx['trash_types'] ]\n\n return JsonResponse(ctx, safe=False)\n\n\ndef api_rfid_known(req, rfid_code):\n try:\n hh = Household.objects.get(rfid_code = rfid_code)\n return JsonResponse({ 'ok': True, 'household_id': hh.id })\n except Household.DoesNotExist:\n return JsonResponse({ 'ok': False, 'message': 'Household.DoesNotExist' })\n\n\n\"\"\"\n trash_can = models.ForeignKey(TrashCan)\n date = models.DateTimeField(auto_now_add = True)\n kg = models.FloatField()\n household = models.ForeignKey(Household)\n trash_pic = models.FileField()\n flags = models.IntegerField(default=0)\n \"\"\"\n\n\n@csrf_exempt\ndef api_trash_event(req):\n # Data in POST body\n data = json.loads(req.body.decode('utf-8'))\n te = TrashEvent(trash_can_id = data['trash_can_id'], kg = data['kg'], household_id = data['household_id'])\n f = open('/tmp/pic.jpg', 'wb+')\n bd = base64.b64decode(data['trash_pic'])\n f.write(bd)\n f.seek(0, 0)\n te.trash_pic.save('trash.jpg', File(f))\n te.save()\n return JsonResponse({ 'ok': True, 'id': te.id })\n\n\ndef format_date(d):\n return d.strftime('%Y-%m-%d %H:%M')\n\n","sub_path":"web/ecosmart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"99602912","text":"# $Id: ftmgmt_fitsdatafile.py 41700 2016-04-19 19:23:55Z mgower $\n# $Rev:: 41700 $: # Revision of last commit.\n# $LastChangedBy:: mgower $: # Author of last commit.\n# $LastChangedDate:: 2016-04-19 14:23:55 #$: # Date of last commit.\n\n\"\"\"\nGeneric filetype management class used to do filetype specific tasks\n such as metadata and content ingestion\n\"\"\"\n\n__version__ = \"$Rev: 41700 $\"\n\nfrom filemgmt.ftmgmt_genfits import FtMgmtGenFits\n\nimport despymisc.miscutils as miscutils\nimport databaseapps.datafile_ingest_utils as dfiutils\n#import time\n\nclass FtMgmtFitsDatafile(FtMgmtGenFits):\n \"\"\" Class for managing a filetype whose contents can be read by datafile_ingest \"\"\"\n\n ######################################################################\n def __init__(self, filetype, dbh, config, filepat=None):\n \"\"\" Initialize object \"\"\"\n # config must have filetype_metadata and file_header_info\n super().__init__(filetype, dbh, config, filepat)\n\n [self.tablename, self.didatadefs] = self.dbh.get_datafile_metadata(filetype)\n\n ######################################################################\n def has_contents_ingested(self, listfullnames):\n \"\"\" Check if file has contents ingested \"\"\"\n #starttime = time.time()\n assert isinstance(listfullnames, list)\n\n results = {}\n for fname in listfullnames:\n filename = miscutils.parse_fullname(fname, miscutils.CU_PARSE_FILENAME)\n results[fname] = dfiutils.is_ingested(filename, self.tablename, self.dbh)\n return results\n\n ######################################################################\n def ingest_contents(self, listfullnames, **kwargs):\n \"\"\" Ingest certain content into a non-metadata table \"\"\"\n #starttime = time.time()\n assert isinstance(listfullnames, list)\n\n for fname in listfullnames:\n _ = dfiutils.datafile_ingest_main(self.dbh, self.filetype, fname,\n self.tablename, self.didatadefs)\n #if numrows == None or numrows == 0:\n # miscutils.fwdebug_print(\"WARN: 0 rows ingested from %s\" % fname)\n #elif miscutils.fwdebug_check(1, 'FTMGMT_DEBUG'):\n # miscutils.fwdebug_print(\"INFO: %s rows ingested from %s\" % (numrows, fname))\n","sub_path":"python/filemgmt/ftmgmt_fitsdatafile.py","file_name":"ftmgmt_fitsdatafile.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"355483941","text":"import logging\nimport torch.nn as nn\nfrom alphabet import Alphabet\nfrom options import opt\nimport norm_utils\nfrom data import build_pretrain_embedding, my_tokenize, load_data_fda\nfrom my_utils import random_embedding, freeze_net\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\nimport numpy as np\nimport torch.optim as optim\nimport time\nimport os\nfrom data_structure import Entity\nimport torch.nn.functional as functional\nimport math\nimport numpy as np\nfrom stopword import stop_word\n\nclass DotAttentionLayer(nn.Module):\n def __init__(self, hidden_size):\n super(DotAttentionLayer, self).__init__()\n self.hidden_size = hidden_size\n self.W = nn.Linear(hidden_size, 1, bias=False)\n\n def forward(self, input):\n \"\"\"\n input: (unpacked_padded_output: batch_size x seq_len x hidden_size, lengths: batch_size)\n \"\"\"\n inputs, lengths = input\n batch_size, max_len, _ = inputs.size()\n flat_input = inputs.contiguous().view(-1, self.hidden_size)\n logits = self.W(flat_input).view(batch_size, max_len)\n alphas = functional.softmax(logits, dim=1)\n\n # computing mask\n idxes = torch.arange(0, max_len, out=torch.LongTensor(max_len)).unsqueeze(0)\n if opt.gpu >= 0 and torch.cuda.is_available():\n idxes = idxes.cuda(opt.gpu)\n mask = (idxes= 0 and torch.cuda.is_available():\n self.word_embedding = self.word_embedding.cuda(self.gpu)\n self.attn = self.attn.cuda(self.gpu)\n self.linear = self.linear.cuda(self.gpu)\n\n\n def forward(self, x, lengths):\n # length = x.size(1)\n x = self.word_embedding(x)\n x = self.word_drop(x)\n\n x = self.attn((x, lengths))\n # x = x.unsqueeze_(1)\n # x = functional.avg_pool2d(x, (length, 1))\n # x = x.squeeze_(1).squeeze_(1)\n\n x = self.linear(x)\n\n return x\n\n def loss(self, y_pred, y_gold):\n\n return self.criterion(y_pred, y_gold)\n\n\n\n def normalize(self, y_pred):\n\n return functional.softmax(y_pred, dim=1)\n\n def process_one_doc(self, doc, entities, dictionary, dictionary_reverse, isMeddra_dict):\n\n if isMeddra_dict:\n Xs, Ys = generate_instances(entities, self.word_alphabet, self.dict_alphabet)\n else:\n Xs, Ys = generate_instances_ehr(entities, self.word_alphabet, self.dict_alphabet, dictionary_reverse)\n\n data_loader = DataLoader(MyDataset(Xs, Ys), opt.batch_size, shuffle=False, collate_fn=my_collate)\n data_iter = iter(data_loader)\n num_iter = len(data_loader)\n\n entity_start = 0\n\n for i in range(num_iter):\n\n x, lengths, _ = next(data_iter)\n\n y_pred = self.forward(x, lengths)\n\n y_pred = self.normalize(y_pred)\n\n values, indices = torch.max(y_pred, 1)\n\n actual_batch_size = lengths.size(0)\n\n for batch_idx in range(actual_batch_size):\n entity = entities[entity_start+batch_idx]\n norm_id = norm_utils.get_dict_name(self.dict_alphabet, indices[batch_idx].item())\n if isMeddra_dict:\n name = dictionary[norm_id]\n entity.norm_ids.append(norm_id)\n entity.norm_names.append(name)\n else:\n concept = dictionary[norm_id]\n entity.norm_ids.append(norm_id)\n entity.norm_names.append(concept.names)\n\n if opt.ensemble == 'sum':\n entity.norm_confidences.append(y_pred[batch_idx].detach().cpu().numpy())\n else:\n entity.norm_confidences.append(values[batch_idx].item())\n\n entity.neural_id = norm_id\n\n entity_start += actual_batch_size\n\n\n\n\nclass MyDataset(Dataset):\n\n def __init__(self, X, Y):\n self.X = X\n self.Y = Y\n\n assert len(self.X) == len(self.Y), 'X and Y have different lengths'\n\n def __len__(self):\n return len(self.Y)\n\n def __getitem__(self, idx):\n return (self.X[idx], self.Y[idx])\n\ndef generate_instances(entities, word_alphabet, dict_alphabet):\n Xs = []\n Ys = []\n\n for entity in entities:\n if len(entity.norm_ids) > 0:\n Y = norm_utils.get_dict_index(dict_alphabet, entity.norm_ids[0]) # use the first id to generate instance\n if Y >= 0 and Y < norm_utils.get_dict_size(dict_alphabet): # for tac, can be none or oov ID\n Ys.append(Y)\n else:\n continue\n else:\n Ys.append(0)\n\n\n tokens = my_tokenize(entity.name)\n word_ids = []\n for token in tokens:\n if token in stop_word:\n continue\n token = norm_utils.word_preprocess(token)\n word_id = word_alphabet.get_index(token)\n word_ids.append(word_id)\n\n Xs.append(word_ids)\n\n return Xs, Ys\n\ndef generate_instances_ehr(entities, word_alphabet, dict_alphabet, dictionary_reverse):\n Xs = []\n Ys = []\n\n for entity in entities:\n if len(entity.norm_ids) > 0:\n if entity.norm_ids[0] in dictionary_reverse:\n cui_list = dictionary_reverse[entity.norm_ids[0]]\n Y = norm_utils.get_dict_index(dict_alphabet, cui_list[0]) # use the first id to generate instance\n if Y >= 0 and Y < norm_utils.get_dict_size(dict_alphabet):\n Ys.append(Y)\n else:\n raise RuntimeError(\"entity {}, {}, cui not in dict_alphabet\".format(entity.id, entity.name))\n else:\n logging.debug(\"entity {}, {}, can't map to umls, ignored\".format(entity.id, entity.name))\n continue\n else:\n Ys.append(0)\n\n\n tokens = my_tokenize(entity.name)\n word_ids = []\n for token in tokens:\n if token in stop_word:\n continue\n token = norm_utils.word_preprocess(token)\n word_id = word_alphabet.get_index(token)\n word_ids.append(word_id)\n\n Xs.append(word_ids)\n\n return Xs, Ys\n\ndef my_collate(batch):\n x, y = zip(*batch)\n\n x, lengths, y = pad(x, y)\n\n if opt.gpu >= 0 and torch.cuda.is_available():\n x = x.cuda(opt.gpu)\n lengths = lengths.cuda(opt.gpu)\n y = y.cuda(opt.gpu)\n return x, lengths, y\n\ndef pad(x, y):\n tokens = x\n\n lengths = [len(row) for row in tokens]\n max_len = max(lengths)\n\n tokens = pad_sequence(tokens, max_len)\n lengths = torch.LongTensor(lengths)\n\n y = torch.LongTensor(y).view(-1)\n\n\n return tokens, lengths, y\n\n\ndef pad_sequence(x, max_len):\n\n padded_x = np.zeros((len(x), max_len), dtype=np.int)\n for i, row in enumerate(x):\n padded_x[i][:len(row)] = row\n\n padded_x = torch.LongTensor(padded_x)\n\n return padded_x\n\ndef generate_dict_instances(dictionary, dict_alphabet, word_alphabet, isMeddra_dict):\n Xs = []\n Ys = []\n\n if isMeddra_dict:\n for concept_id, concept_name in dictionary.items():\n\n Y = norm_utils.get_dict_index(dict_alphabet, concept_id)\n if Y >= 0 and Y < norm_utils.get_dict_size(dict_alphabet):\n Ys.append(Y)\n else:\n continue\n\n\n tokens = my_tokenize(concept_name)\n word_ids = []\n for token in tokens:\n if token in stop_word:\n continue\n token = norm_utils.word_preprocess(token)\n word_id = word_alphabet.get_index(token)\n word_ids.append(word_id)\n\n Xs.append(word_ids)\n else :\n for concept_id, concept in dictionary.items():\n Y = norm_utils.get_dict_index(dict_alphabet, concept_id)\n if Y >= 0 and Y < norm_utils.get_dict_size(dict_alphabet):\n pass\n else:\n continue\n\n # for concept_name in concept.names:\n #\n # tokens = my_tokenize(concept_name)\n # word_ids = []\n # for token in tokens:\n # token = norm_utils.word_preprocess(token)\n # word_id = word_alphabet.get_index(token)\n # word_ids.append(word_id)\n #\n # Ys.append(Y)\n # Xs.append(word_ids)\n\n\n tokens = my_tokenize(concept.names[0])\n word_ids = []\n for token in tokens:\n if token in stop_word:\n continue\n token = norm_utils.word_preprocess(token)\n word_id = word_alphabet.get_index(token)\n word_ids.append(word_id)\n\n Ys.append(Y)\n Xs.append(word_ids)\n\n\n return Xs, Ys\n\n\ndef dict_pretrain(dictionary, dictionary_reverse, d, isMeddra_dict, optimizer, neural_model):\n logging.info('use dict pretrain ...')\n\n dict_Xs, dict_Ys = generate_dict_instances(dictionary, neural_model.dict_alphabet, neural_model.word_alphabet, isMeddra_dict)\n\n data_loader = DataLoader(MyDataset(dict_Xs, dict_Ys), opt.batch_size, shuffle=True, collate_fn=my_collate)\n\n expected_accuracy = int(d.config['norm_neural_pretrain_accuracy'])\n\n logging.info(\"start dict pretraining ...\")\n\n bad_counter = 0\n best_accuracy = 0\n\n for idx in range(9999):\n epoch_start = time.time()\n\n neural_model.train()\n\n correct, total = 0, 0\n\n sum_loss = 0\n\n train_iter = iter(data_loader)\n num_iter = len(data_loader)\n\n for i in range(num_iter):\n\n x, lengths, y = next(train_iter)\n\n y_pred = neural_model.forward(x, lengths)\n\n l = neural_model.loss(y_pred, y)\n\n sum_loss += l.item()\n\n l.backward()\n\n if opt.gradient_clip > 0:\n torch.nn.utils.clip_grad_norm_(neural_model.parameters(), opt.gradient_clip)\n optimizer.step()\n neural_model.zero_grad()\n\n total += y.size(0)\n _, pred = torch.max(y_pred, 1)\n correct += (pred == y).sum().item()\n\n epoch_finish = time.time()\n accuracy = 100.0 * correct / total\n logging.info(\"epoch: %s pretraining finished. Time: %.2fs. loss: %.4f Accuracy %.2f\" % (\n idx, epoch_finish - epoch_start, sum_loss / num_iter, accuracy))\n\n\n if accuracy > expected_accuracy:\n logging.info(\"Exceed {}% training accuracy, breaking ... \".format(expected_accuracy))\n break\n\n if accuracy > best_accuracy:\n best_accuracy = accuracy\n bad_counter = 0\n else:\n bad_counter += 1\n\n if bad_counter >= opt.patience:\n logging.info('Early Stop!')\n break\n\n return\n\n\ndef train(train_data, dev_data, test_data, d, dictionary, dictionary_reverse, opt, fold_idx, isMeddra_dict):\n logging.info(\"train the neural-based normalization model ...\")\n\n external_train_data = []\n if d.config.get('norm_ext_corpus') is not None:\n for k, v in d.config['norm_ext_corpus'].items():\n if k == 'tac':\n external_train_data.extend(load_data_fda(v['path'], True, v.get('types'), v.get('types'), False, True))\n else:\n raise RuntimeError(\"not support external corpus\")\n if len(external_train_data) != 0:\n train_data.extend(external_train_data)\n\n logging.info(\"build alphabet ...\")\n word_alphabet = Alphabet('word')\n norm_utils.build_alphabet_from_dict(word_alphabet, dictionary, isMeddra_dict)\n norm_utils.build_alphabet(word_alphabet, train_data)\n if opt.dev_file:\n norm_utils.build_alphabet(word_alphabet, dev_data)\n if opt.test_file:\n norm_utils.build_alphabet(word_alphabet, test_data)\n norm_utils.fix_alphabet(word_alphabet)\n logging.info(\"alphabet size {}\".format(word_alphabet.size()))\n\n\n if d.config.get('norm_emb') is not None:\n logging.info(\"load pretrained word embedding ...\")\n pretrain_word_embedding, word_emb_dim = build_pretrain_embedding(d.config.get('norm_emb'),\n word_alphabet,\n opt.word_emb_dim, False)\n word_embedding = nn.Embedding(word_alphabet.size(), word_emb_dim, padding_idx=0)\n word_embedding.weight.data.copy_(torch.from_numpy(pretrain_word_embedding))\n embedding_dim = word_emb_dim\n else:\n logging.info(\"randomly initialize word embedding ...\")\n word_embedding = nn.Embedding(word_alphabet.size(), d.word_emb_dim, padding_idx=0)\n word_embedding.weight.data.copy_(\n torch.from_numpy(random_embedding(word_alphabet.size(), d.word_emb_dim)))\n embedding_dim = d.word_emb_dim\n\n\n\n dict_alphabet = Alphabet('dict')\n norm_utils.init_dict_alphabet(dict_alphabet, dictionary)\n norm_utils.fix_alphabet(dict_alphabet)\n\n neural_model = NeuralNormer(word_alphabet, word_embedding, embedding_dim, dict_alphabet)\n\n train_X = []\n train_Y = []\n for doc in train_data:\n\n if isMeddra_dict:\n temp_X, temp_Y = generate_instances(doc.entities, word_alphabet, dict_alphabet)\n else:\n temp_X, temp_Y = generate_instances_ehr(doc.entities, word_alphabet, dict_alphabet, dictionary_reverse)\n train_X.extend(temp_X)\n train_Y.extend(temp_Y)\n\n\n train_loader = DataLoader(MyDataset(train_X, train_Y), opt.batch_size, shuffle=True, collate_fn=my_collate)\n\n optimizer = optim.Adam(neural_model.parameters(), lr=opt.lr, weight_decay=opt.l2)\n\n if opt.tune_wordemb == False:\n freeze_net(neural_model.word_embedding)\n\n if d.config['norm_neural_pretrain'] == '1':\n dict_pretrain(dictionary, dictionary_reverse, d, isMeddra_dict, optimizer, neural_model)\n\n\n best_dev_f = -10\n best_dev_p = -10\n best_dev_r = -10\n\n bad_counter = 0\n\n logging.info(\"start training ...\")\n\n for idx in range(opt.iter):\n epoch_start = time.time()\n\n neural_model.train()\n\n train_iter = iter(train_loader)\n num_iter = len(train_loader)\n\n sum_loss = 0\n\n correct, total = 0, 0\n\n for i in range(num_iter):\n\n x, lengths, y = next(train_iter)\n\n y_pred = neural_model.forward(x, lengths)\n\n l = neural_model.loss(y_pred, y)\n # debug feili\n # if np.any(np.isnan(l.item())):\n # logging.info(\"loss: {}\".format(l.item()))\n # exit()\n\n sum_loss += l.item()\n\n l.backward()\n\n if opt.gradient_clip > 0:\n torch.nn.utils.clip_grad_norm_(neural_model.parameters(), opt.gradient_clip)\n optimizer.step()\n neural_model.zero_grad()\n\n total += y.size(0)\n _, pred = torch.max(y_pred, 1)\n correct += (pred == y).sum().item()\n\n epoch_finish = time.time()\n accuracy = 100.0 * correct / total\n logging.info(\"epoch: %s training finished. Time: %.2fs. loss: %.4f Accuracy %.2f\" % (\n idx, epoch_finish - epoch_start, sum_loss / num_iter, accuracy))\n\n if opt.dev_file:\n p, r, f = norm_utils.evaluate(dev_data, dictionary, dictionary_reverse, None, neural_model, None, d, isMeddra_dict)\n logging.info(\"Dev: p: %.4f, r: %.4f, f: %.4f\" % (p, r, f))\n else:\n f = best_dev_f\n\n if f > best_dev_f:\n logging.info(\"Exceed previous best f score on dev: %.4f\" % (best_dev_f))\n\n if fold_idx is None:\n torch.save(neural_model, os.path.join(opt.output, \"norm_neural.pkl\"))\n else:\n torch.save(neural_model, os.path.join(opt.output, \"norm_neural_{}.pkl\".format(fold_idx+1)))\n\n best_dev_f = f\n best_dev_p = p\n best_dev_r = r\n\n bad_counter = 0\n else:\n bad_counter += 1\n\n if len(opt.dev_file) != 0 and bad_counter >= opt.patience:\n logging.info('Early Stop!')\n break\n\n logging.info(\"train finished\")\n\n if len(opt.dev_file) == 0:\n torch.save(neural_model, os.path.join(opt.output, \"norm_neural.pkl\"))\n\n return best_dev_p, best_dev_r, best_dev_f\n\n\n\n","sub_path":"norm_neural.py","file_name":"norm_neural.py","file_ext":"py","file_size_in_byte":17153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"33594673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 17 15:11:43 2020\r\n\r\n@author: Jamie\r\n\"\"\"\r\n\r\ndef add (a,b,c):\r\n answer=a+b+c\r\n return answer\r\na1=add (1,2,3)\r\nprint(a1)\r\n ","sub_path":"add function.py","file_name":"add function.py","file_ext":"py","file_size_in_byte":178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"177346511","text":"#!/usr/local/bin/python3.7\n# encoding: utf-8\n\"\"\"\nController for a process with many steps forming a directed graph with cycles.\n\nold.constructor.host_constructor is a description\n\nIt defines classes_and_methods\n\n@author: Jonathan Gossage\n\n@copyright: 2018 Jonathan Gossage All rights reserved.\n\n@license: Apache2\n\n@contact: jgossage at gmail.com\n@deffield updated: Updated\n\"\"\"\n\nimport sys\nimport os\n\nimport argparse\nfrom getpass import getuser\nimport logging\nfrom pathlib import Path\nimport shutil\nfrom typing import Tuple, Sequence, List\nfrom warnings import warn\n\nfrom ruamel.yaml import YAML\n\nimport utilities.arg_parser\nfrom utilities.setup_logging import capture_sys_output\nfrom utilities.yaml_loader import YamlLoader\n\n__all__ = []\n__version__ = '0.1.0'\n__date__ = '2018-08-27'\n__updated__ = '2018-08-27'\n\n\nclass MakeWorkspace(argparse.Action):\n \"\"\"Handle creation of a non-temporary workspace\"\"\"\n def __init__(self, option_strings: Sequence[str], dest: str, **kwargs) -> None:\n super().__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace, values: List[Path], # @UnusedVariable\n option_string: Sequence[str]=None) -> None: # @UnusedVariable\n if values.exists(): # Workspace exists\n if values.is_dir():\n shutil.rmtree(str(values)) # Remove the old copy\n else:\n values.rm()\n values.mkdir() # Create the workspace\n setattr(namespace, self.dest, values)\n\n\ndef toPath(path: str) -> Path:\n \"\"\"\"Convert string to Path\"\"\"\n p = Path(path)\n return p\n\n\ndef getConfig() -> List[Path]:\n \"\"\"\n Gets the standard list of configuration files.\n The first file found is considered the base file and the others will update the base file in the order they are encountered.\n We start with the files specified in /etc/WiseOldBird/stdcfglist.yaml.\n None of the files needs to exist.\n \"\"\"\n cfg = []\n yaml = YAML(typ='unsafe')\n p = Path('/etc/WiseOldBird/stdcfglist.yaml')\n if p.is_file():\n cfglist = None\n with p.open(mode='r') as fp:\n cfglist = yaml.load(fp)\n if cfglist is not None and len(cfglist) > 0:\n for c in cfglist:\n c = Path(c)\n if c.is_file():\n cfg.append(c)\n return cfg\n\n\nclass JobManager():\n def __init__(self, argv: Sequence[str]=None, prog: str=None) -> None:\n self._logger = logging.getLogger() # Start with the root logger in default configuration\n self._logger.setLevel(logging.DEBUG)\n self._user = getuser()\n self._home = os.environ['HOME']\n self._args, self._program_name = self._handleArguments(argv, prog)\n self._logger.setLevel(logging.DEBUG if self._args.debug is not None else logging.INFO)\n stdcfg = getConfig() # Get the standard list of configuration files\n # Add the optional configuration files specified on the command line\n if self._args.add is not None:\n stdcfg.extend(self._args.add)\n elif self._args.replace is not None:\n stdcfg = self._args.replace # Only use the configuration files specified on the command line\n # Build the configuration by updating the base configuration file with all the update files found\n self._config = YamlLoader(stdcfg)()\n\n def __call__(self) -> int:\n try:\n if self._args.debug is not None:\n raise RuntimeError('Raised at the end of execution in debug mode to verify that uncaught exceptions are logged')\n return 0\n\n except KeyboardInterrupt:\n # handle keyboard interrupt\n return 0\n except BaseException as e: # pylint: disable=broad-except\n self._logger.exception('JOB MANAGER Error', exc_info=e)\n return 2\n\n def _handleArguments(self, # IGNORE:C0111 @DontTrace\n argv: Sequence=None,\n prog=None) -> Tuple:\n \"\"\"Command line options.\"\"\"\n # Setup the arguments\n if argv is None: # Running production - use arguments from command line\n argv = sys.argv[1:]\n\n # Setup the information needed by the argument parser\n program_version = \"v{}\".format(__version__)\n program_build_date = str(__updated__)\n if prog is not None: # Unit testing - simplify results for easier checking\n program_name = prog\n # Setup argument parser in debug mode\n parser = utilities.arg_parser.ArgParser(prog=program_name, usage='')\n else:\n program_name = os.path.basename(sys.argv[0])\n program_shortdesc = __import__('__main__').__doc__.split(\"\\n\")[1]\n program_license = \"\"\"{}\n\n Created by Jonathan Gossage on {}.\n Copyright 2018 Jonathan Gossage. All rights reserved.\n\n Licensed under the Apache License 2.0\n http://www.apache.org/licenses/LICENSE-2.0\n\n Distributed on an \"AS IS\" basis without warranties\n or conditions of any kind, either express or implied.\n\n USAGE\n \"\"\".format(program_shortdesc, str(__date__))\n # Setup argument parser in production mode\n parser = utilities.arg_parser.ArgParser(description=program_license,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n program_version_message = '{} {} ({})'.format(program_name, program_version, program_build_date)\n\n # Add the acceptable arguments\n parser.add_argument('-d', '--debug', dest='debug', type=toPath, action=MakeWorkspace,\n help='debugging path to retained workspace')\n parser.add_argument('-a', '--add', dest='add', type=toPath, action='store', nargs='*',\n help='use this/these configuration file[s] in addition to the standard files')\n parser.add_argument('-r', '--replace', dest='replace', type=toPath, action='store', nargs='*',\n help='use this/these configuration file[s] in place of the standard files')\n parser.add_argument('-v', '--version', action='version', version=program_version_message)\n parser.add_argument(dest='job', help='name of the table for the job to be run')\n\n # Process arguments\n args = parser.parse_args(argv)\n\n # Check for conflicting arguments\n if args.replace is not None:\n if args.add is not None:\n warn('Task Controller: The arguments --replace and --add conflict - using --replace')\n args.add = None\n return (args, program_name)\n\n\nif __name__ == \"__main__\":\n logging.captureWarnings(True)\n with capture_sys_output():\n sys.exit(JobManager()())\n","sub_path":"ConstructDevelopmentSystem/src/manager/job_manager.py","file_name":"job_manager.py","file_ext":"py","file_size_in_byte":6883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"231367171","text":"import os\n\n\ndef info():\n print('\\n##########################')\n print('# APPLICATIONS WRAPPER #')\n print('##########################\\n')\n print('1 - Rocker: Launch rocker image in docker on IP localhost:8787')\n print('')\n\n\ndef is_number(s):\n try:\n float(s)\n except ValueError:\n try:\n complex(s)\n except ValueError:\n return False\n\n return True\n\n\ndef getSelection():\n selection = input('Select the process to launch or type exit: ')\n\n if selection == 'exit':\n print('Exiting program')\n exit(0)\n\n try:\n int(selection)\n except:\n print('[Errn 0]: Bad Selection')\n\n return selection\n\n\ndef launchApp(selection):\n if selection == 1:\n os.system(\n 'sh ~/workspace/repos/psoftware/scripts/subScripts/' +\n 'rocker_launch.sh'\n )\n\n\ndef main():\n\n info()\n\n goodSelection = False\n\n while goodSelection is False:\n\n selection = getSelection()\n\n if is_number(selection):\n selection = int(selection)\n if selection in range(1, 2):\n goodSelection = True\n continue\n else:\n print('[Errn 1]: Selection not in range')\n\n launchApp(selection)\n\nmain()\n","sub_path":"scripts/scriptsWrapper.py","file_name":"scriptsWrapper.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"13435998","text":"# Copyright (c) 2016 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport time\n\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nfrom dragonflow._i18n import _LE, _LW\nfrom dragonflow.common import utils as df_utils\nfrom dragonflow.db import models\n\nLOG = log.getLogger(__name__)\n\nMIN_SYNC_INTERVAL_TIME = 60\n\n\nclass CacheManager(object):\n def __init__(self):\n self._table_name_mapping = {\n models.LogicalSwitch.table_name: {},\n models.LogicalPort.table_name: {},\n models.LogicalRouter.table_name: {},\n models.Floatingip.table_name: {},\n models.SecurityGroup.table_name: {},\n models.QosPolicy.table_name: {},\n }\n\n def get(self, table, key):\n return self._table_name_mapping[table].get(key)\n\n def set(self, table, key, value):\n self._table_name_mapping[table][key] = value\n\n def remove(self, table, key):\n del self._table_name_mapping[table][key]\n\n def get_tables(self):\n return self._table_name_mapping.keys()\n\n\nclass DBConsistencyManager(object):\n\n def __init__(self, controller):\n self.topology = controller.topology\n self.nb_api = controller.nb_api\n self.db_store = controller.db_store\n self.controller = controller\n self.db_sync_time = cfg.CONF.df.db_sync_time\n if self.db_sync_time < MIN_SYNC_INTERVAL_TIME:\n self.db_sync_time = MIN_SYNC_INTERVAL_TIME\n self._daemon = df_utils.DFDaemon()\n self.cache_manager = CacheManager()\n\n def process(self, direct):\n self.topology.check_topology_info()\n self._process_db_tables_comparison(direct)\n\n def run(self):\n while True:\n time.sleep(self.db_sync_time)\n self.nb_api.db_change_callback(None, None, \"db_sync\", \"db_sync\")\n LOG.debug(\"Enter db consistent processing\")\n\n def daemonize(self):\n return self._daemon.daemonize(self.run)\n\n def stop(self):\n return self._daemon.stop()\n\n def _process_db_tables_comparison(self, direct):\n \"\"\"Do the comparison and sync according to the difference between\n df db and local cache\n\n :param direct: Indicate the process mode, if True, it will sync\n the data immediately once it found the difference,\n if False, it will do the sync job after twice data\n comparisons.\n \"\"\"\n self.controller.register_chassis()\n topics = self.topology.topic_subscribed.keys()\n for table in self.cache_manager.get_tables():\n try:\n self.handle_data_comparison(topics, table, direct)\n except Exception as e:\n LOG.exception(_LE(\"Exception occurred when\"\n \"handling db comparison: %s\"), e)\n\n def _verify_object(self, table, id, action, df_object, local_object=None):\n \"\"\"Verify the object status and judge whether to create/update/delete\n the object or not, we'll use twice comparison to verify the status,\n first comparison result will be stored in the cache and if second\n comparison result is still consistent with the cache, we can make\n sure the object status\n\n :param table: Resource object type\n :param id: Resource object id\n :param action: Operate action(create/update/delete)\n :param df_object: Object from df db\n :param local_object: Object from local cache\n \"\"\"\n df_version = df_object.get_version() if df_object else None\n local_version = local_object.get_version() if local_object else None\n\n old_cache_obj = self.cache_manager.get(table, id)\n if not old_cache_obj or old_cache_obj.get_action() != action:\n cache_obj = CacheObject(action, df_version, local_version)\n self.cache_manager.set(table, id, cache_obj)\n return\n\n old_df_version = old_cache_obj.get_df_version()\n old_local_version = old_cache_obj.get_local_version()\n if action == 'create':\n if df_version >= old_df_version:\n self.controller.update(df_object)\n self.cache_manager.remove(table, id)\n return\n elif action == 'update':\n if df_version < old_df_version:\n return\n if local_version <= old_local_version:\n self.controller.update(df_object)\n self.cache_manager.remove(table, id)\n else:\n cache_obj = CacheObject(action, df_version, local_version)\n self.cache_manager.set(table, id, cache_obj)\n elif action == 'delete':\n model = models.table_class_mapping[table]\n self.controller.delete_by_id(model, id)\n self.cache_manager.remove(table, id)\n else:\n LOG.warning(_LW('Unknown action %s in db consistent'), action)\n\n def _get_df_and_local_objects(self, topic, table):\n df_objects = []\n local_objects = []\n if table == models.LogicalSwitch.table_name:\n df_objects = self.nb_api.get_all_logical_switches(topic)\n local_objects = self.db_store.get_lswitchs(topic)\n elif table == models.LogicalPort.table_name:\n df_objects = self.nb_api.get_all_logical_ports(topic)\n local_objects = self.db_store.get_ports(topic)\n elif table == models.LogicalRouter.table_name:\n df_objects = self.nb_api.get_routers(topic)\n local_objects = self.db_store.get_routers(topic)\n elif table == models.SecurityGroup.table_name:\n df_objects = self.nb_api.get_security_groups(topic)\n local_objects = self.db_store.get_security_groups(topic)\n elif table == models.Floatingip.table_name:\n df_objects = self.nb_api.get_floatingips(topic)\n local_objects = self.db_store.get_floatingips(topic)\n elif table == models.QosPolicy.table_name:\n df_objects = self.nb_api.get_qos_policies(topic)\n local_objects = self.db_store.get_qos_policies(topic)\n return df_objects, local_objects\n\n def _compare_df_and_local_data(\n self, table, df_objects, local_objects, direct):\n \"\"\"Compare specific resource type df objects and local objects\n one by one, we could judge whether to create/update/delete\n the corresponding object.\n\n :param table: Resource object type\n :param df_object: Object from df db\n :param local_object: Object from local cache\n :param direct: the process model, if True, we'll do the operation\n directly after this comparison, if False, we'll go into the verify\n process which need twice comparison to do the operation.\n \"\"\"\n local_object_map = {}\n for local_object in local_objects:\n local_object_map[local_object.get_id()] = local_object\n for df_object in df_objects[:]:\n df_id = df_object.get_id()\n df_version = df_object.get_version()\n if df_version is None:\n LOG.error(_LE(\"Version is None in df_object: %s\"), df_object)\n continue\n local_object = local_object_map.pop(df_id, None)\n if local_object:\n local_version = local_object.get_version()\n if local_version is None:\n LOG.debug(\"Version is None in local_object: %s\",\n local_object)\n self.controller.update(df_object)\n elif df_version > local_version:\n LOG.debug(\"Find a newer version df object: %s\",\n df_object)\n if direct:\n self.controller.update(df_object)\n else:\n self._verify_object(\n table, df_id, 'update',\n df_object, local_object)\n else:\n LOG.debug(\"Find an additional df object: %s\", df_object)\n if direct:\n self.controller.update(df_object)\n else:\n self._verify_object(table, df_id,\n 'create', df_object)\n\n for local_object in local_object_map.values():\n LOG.debug(\"Find a redundant local object: %s\", local_object)\n if direct:\n self.controller.delete(local_object)\n else:\n self._verify_object(\n table, local_object.get_id(),\n 'delete', None, local_object)\n\n def _get_and_compare_df_and_local_data(self, table, direct, topic=None):\n df_objects, local_objects = self._get_df_and_local_objects(\n topic, table)\n self._compare_df_and_local_data(\n table, df_objects, local_objects, direct)\n\n def handle_data_comparison(self, tenants, table, direct):\n for topic in tenants:\n self._get_and_compare_df_and_local_data(table, direct, topic)\n\n\nclass CacheObject(object):\n def __init__(self, action, df_version, local_version):\n self.action = action\n self.df_version = df_version\n self.local_version = local_version\n\n def get_action(self):\n return self.action\n\n def get_df_version(self):\n return self.df_version\n\n def get_local_version(self):\n return self.local_version\n","sub_path":"dragonflow/db/db_consistent.py","file_name":"db_consistent.py","file_ext":"py","file_size_in_byte":10055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"443993866","text":"import sys\nimport os\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtWebEngineWidgets import *\nfrom PyQt5.QtGui import *\n\nos.chdir(r\"C:\\\\Users\\\\Foisal\\\\Documents\\\\Programming\\\\Projects\\\\Python\\\\pyqt5\\\\Browser\")\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super(MainWindow,self).__init__()\n #homepage\n self.browser = QWebEngineView()\n self.browser.setUrl(QUrl(\"file:///\"+os.path.realpath(\"files/home.html\").replace(\"\\\\\",\"/\")))\n self.setWindowIcon(QIcon('files/logo.ico'))\n self.browser.loadFinished.connect(self.update_title)\n self.setCentralWidget(self.browser)\n\n #display\n self.showMaximized()\n\n #navbar\n navbar = QToolBar()\n self.addToolBar(navbar)\n\n self.create_menu_bar()\n\n back_btn = QAction(QIcon(\"files/back.png\"),\"Back\",self)\n back_btn.triggered.connect(self.browser.back)\n navbar.addAction(back_btn)\n\n forward_btn = QAction(QIcon(\"files/forward.png\"),\"Forward\",self)\n forward_btn.triggered.connect(self.browser.forward)\n navbar.addAction(forward_btn)\n\n reload_btn = QAction(QIcon(\"files/reload.png\"),\"Reload\",self)\n reload_btn.triggered.connect(self.browser.reload)\n navbar.addAction(reload_btn)\n\n stop_btn = QAction(QIcon(\"files/stop.png\"),\"Stop\", self)\n stop_btn.triggered.connect(self.browser.stop)\n navbar.addAction(stop_btn)\n\n home_btn = QAction(QIcon(\"files/home.png\"),\"Home\",self)\n home_btn.triggered.connect(self.homepage)\n navbar.addAction(home_btn)\n\n self.url_bar = QLineEdit()\n self.url_bar.returnPressed.connect(self.navigate_to_url)\n navbar.addWidget(self.url_bar)\n\n self.browser.urlChanged.connect(self.update_url)\n\n search_btn = QAction(QIcon(\"files/search.png\"),\"Search\",self)\n search_btn.triggered.connect(self.navigate_to_url)\n navbar.addAction(search_btn)\n\n self.setStyleSheet(\"\"\"QWidget{\n background-color: rgb(48, 48, 48);\n color: rgb(255, 255, 255);\n }\n\n /* Style the tab using the tab sub-control. Note that\n it reads QTabBar _not_ QTabWidget */\n QLabel, QToolButton, QTabBar::tab {\n background: rgb(90, 90, 90);\n border: 2px solid rgb(90, 90, 90);\n /*border-bottom-color: #C2C7CB; /* same as the pane color */\n border-radius: 10px;\n min-width: 8ex;\n padding: 5px;\n margin-right: 2px;\n color: rgb(255, 255, 255);\n }\n\n QLabel:hover, QToolButton::hover, QTabBar::tab:selected, QTabBar::tab:hover {\n background: rgb(49, 49, 49);\n border: 2px solid rgb(0, 36, 36);\n background-color: rgb(0, 36, 36);\n }\n\n QLineEdit {\n border: 2px solid rgb(0, 36, 36);\n border-radius: 10px;\n padding: 5px;\n background-color: rgb(0, 36, 36);\n color: rgb(255, 255, 255);\n }\n QLineEdit:hover {\n border: 2px solid rgb(0, 66, 124);\n }\n QLineEdit:focus{\n border: 2px solid rgb(0, 136, 255);\n color: rgb(200, 200, 200);\n }\n QPushButton{\n background: rgb(49, 49, 49);\n border: 2px solid rgb(0, 36, 36);\n background-color: rgb(0, 36, 36);\n padding: 5px;\n border-radius: 10px;\n }\"\"\")\n\n def create_menu_bar(self):\n menu_bar = QMenuBar()\n self.setMenuBar(menu_bar)\n\n google_btn = QAction(\"Google Search\", self)\n google_btn.triggered.connect(self.google)\n menu_bar.addAction(google_btn)\n\n maps_btn = QAction(\"Google Maps\", self)\n maps_btn.triggered.connect(self.maps)\n menu_bar.addAction(maps_btn)\n\n translate_btn = QAction(\"Google Translate\", self)\n translate_btn.triggered.connect(self.translate)\n menu_bar.addAction(translate_btn)\n\n bing_btn = QAction(\"Bing Search\", self)\n bing_btn.triggered.connect(self.bing)\n menu_bar.addAction(bing_btn)\n\n yahoo_btn = QAction(\"Yahoo Search\", self)\n yahoo_btn.triggered.connect(self.yahoo)\n menu_bar.addAction(yahoo_btn)\n\n duckduckgo_btn = QAction(\"Duckduckgo Search\", self)\n duckduckgo_btn.triggered.connect(self.duckduckgo)\n menu_bar.addAction(duckduckgo_btn)\n\n wikipedia_btn = QAction(\"Wikipedia Search\", self)\n wikipedia_btn.triggered.connect(self.wikipedia)\n menu_bar.addAction(wikipedia_btn)\n\n proton_btn = QAction(\"Protonmail\", self)\n proton_btn.triggered.connect(self.proton)\n menu_bar.addAction(proton_btn)\n\n dropbox_btn = QAction(\"dropbox\", self)\n dropbox_btn.triggered.connect(self.dropbox)\n menu_bar.addAction(dropbox_btn)\n\n yt_btn = QAction(\"Youtube\", self)\n yt_btn.triggered.connect(self.yt)\n menu_bar.addAction(yt_btn)\n\n facebook_btn = QAction(\"Facebook\", self)\n facebook_btn.triggered.connect(self.facebook)\n menu_bar.addAction(facebook_btn)\n\n instagram_btn = QAction(\"Instagram\", self)\n instagram_btn.triggered.connect(self.instagram)\n menu_bar.addAction(instagram_btn)\n\n messenger_btn = QAction(\"Messenger\", self)\n messenger_btn.triggered.connect(self.messenger)\n menu_bar.addAction(messenger_btn)\n\n whatsapp_btn = QAction(\"Whatsapp\", self)\n whatsapp_btn.triggered.connect(self.whatsapp)\n menu_bar.addAction(whatsapp_btn)\n\n telegram_btn = QAction(\"Telegram\", self)\n telegram_btn.triggered.connect(self.telegram)\n menu_bar.addAction(telegram_btn)\n\n github_btn = QAction(\"Github\", self)\n github_btn.triggered.connect(self.github)\n menu_bar.addAction(github_btn)\n\n more = QMenu(\"More \", self)\n menu_bar.addMenu(more)\n\n replit_btn = QAction(\"Replit\", self)\n replit_btn.triggered.connect(self.replit)\n more.addAction(replit_btn)\n\n hackerrank_btn = QAction(\"HackerRank\",self)\n hackerrank_btn.triggered.connect(self.hackerrank)\n more.addAction(hackerrank_btn)\n \n sololearn_btn = QAction(\"Sololearn\",self)\n sololearn_btn.triggered.connect(self.sololearn)\n more.addAction(sololearn_btn)\n\n w3schools_btn = QAction(\"W3schools\",self)\n w3schools_btn.triggered.connect(self.w3schools)\n more.addAction(w3schools_btn)\n\n freecodecamp_btn = QAction(\"FreeCodeCamp\",self)\n freecodecamp_btn.triggered.connect(self.freecodecamp)\n more.addAction(freecodecamp_btn)\n\n leetcode_btn = QAction(\"Leetcode\",self)\n leetcode_btn.triggered.connect(self.leetcode)\n more.addAction(leetcode_btn)\n\n codingbat_btn = QAction(\"Codingbat\",self)\n codingbat_btn.triggered.connect(self.codingbat)\n more.addAction(codingbat_btn)\n\n option = QMenu(\"Option\",self)\n menu_bar.addMenu(option)\n\n about_btn = QAction(\"About\", self)\n about_btn.triggered.connect(self.about_url)\n option.addAction(about_btn)\n\n p = QAction(\"P\",self)\n p.triggered.connect(self.p)\n option.addAction(p)\n\n webdev = QAction(\"Practise\",self)\n webdev.triggered.connect(self.webdev)\n option.addAction(webdev)\n\n exit_btn = QAction(\"Exit\", self)\n exit_btn.triggered.connect(exit)\n option.addAction(exit_btn)\n \n def update_title(self):\n title = self.browser.page().title()\n self.setWindowTitle(\"% s \" % title)\n\n def p(self):\n self.browser.setUrl(QUrl(\"https://www.youtube.com/watch?v=BBKHfoADJnc&list=PL2FHm7GZu6dmPSPp1Ym4R2SpIgWHFRFHE\"))\n\n def webdev(self):\n self.browser.setUrl(QUrl(\"file:///C:/Users/Foisal/Documents/Programming/Projects/WebDev/index.html\"))\n \n def navigate_to_url(self):\n url = self.url_bar.text()\n if url[:2] == \"C:\":\n url = \"file:///\"+url\n if url[:4] != \"http\" and url[:8] != \"file:///\" and url[:3] != \"www\":\n url = \"https://duckduckgo.com/?q=\"+url\n if url[:3] == \"www\":\n url = \"https://\" + url\n self.browser.setUrl(QUrl(url))\n\n def update_url(self,url):\n block = [\"xnxx\",\"xvideos\",\"xfantazy\",\"xhamster\",\"youporn\",\"sex\",\"fuck\",\"hot\",\"nude\",\"couple\",\"sunney+leone\",\"jacklin\",\"gia+steel\",\"pornhub\"]\n for i in block:\n if i in url.toString().lower():\n exit()\n else:\n self.url_bar.setText(url.toString())\n\n def about_url(self):\n path = os.path.realpath(\"files/about.html\")\n url = \"file:///\" + path.replace(\"\\\\\", \"/\")\n self.browser.setUrl(QUrl(url))\n\n def homepage(self):\n self.browser.setUrl(QUrl(\"file:///\"+os.path.realpath(\"files/home.html\").replace(\"\\\\\",\"/\")))\n\n def duckduckgo(self):\n self.browser.setUrl(QUrl(\"https://duckduckgo.com/\"))\n\n def facebook(self):\n self.browser.setUrl(QUrl(\"https://www.facebook.com/\"))\n\n def messenger(self):\n self.browser.setUrl(QUrl(\"https://www.messenger.com/\"))\n\n def yt(self):\n self.browser.setUrl(QUrl(\"https://www.youtube.com/\"))\n\n def whatsapp(self):\n self.browser.setUrl(QUrl(\"https://web.whatsapp.com/\"))\n\n def instagram(self):\n self.browser.setUrl(QUrl(\"https://www.instagram.com/\"))\n\n def google(self):\n self.browser.setUrl(QUrl(\"https://www.google.com/\"))\n\n def github(self):\n self.browser.setUrl(QUrl(\"https://github.com/\"))\n\n def bing(self):\n self.browser.setUrl(QUrl(\"https://www.bing.com/\"))\n\n def yahoo(self):\n self.browser.setUrl(QUrl(\"https://www.yahoo.com/\"))\n \n def replit(self):\n self.browser.setUrl(QUrl(\"https://replit.com/~\"))\n\n def maps(self):\n self.browser.setUrl(QUrl(\"https://www.google.com/maps/@22.3259344,91.8198678,12z\"))\n\n def translate(self):\n self.browser.setUrl(QUrl(\"https://translate.google.com/\"))\n\n def proton(self):\n self.browser.setUrl(QUrl(\"https://mail.protonmail.com/inbox\"))\n \n def telegram(self):\n self.browser.setUrl(QUrl(\"https://web.telegram.org/\"))\n\n def dropbox(self):\n self.browser.setUrl(QUrl(\"https://www.dropbox.com/\"))\n\n def wikipedia(self):\n self.browser.setUrl(QUrl(\"https://www.wikipedia.org/\"))\n\n def hackerrank(self):\n self.browser.setUrl(QUrl(\"https://www.hackerrank.com/dashboard\"))\n\n def sololearn(self):\n self.browser.setUrl(QUrl(\"https://www.sololearn.com/profile/19855955\"))\n\n def leetcode(self):\n self.browser.setUrl(QUrl(\"https://leetcode.com/\"))\n\n def w3schools(self):\n self.browser.setUrl(QUrl(\"https://www.w3schools.com/\"))\n\n def freecodecamp(self):\n self.browser.setUrl(QUrl(\"https://www.freecodecamp.org/learn/?messages=success%5B0%5D%3DSuccess%2521%2520You%2520have%2520signed%2520in%2520to%2520your%2520account.%2520Happy%2520Coding%2521\"))\n\n def codingbat(self):\n self.browser.setUrl(QUrl(\"https://codingbat.com/python\"))\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n QApplication.setApplicationName(\"PineApple Browser\")\n QApplication.setApplicationVersion(\"1.02\")\n QApplication.setApplicationDisplayName(\"PineApple Browser\")\n QApplication.setDesktopFileName(\"PineApple Browser\")\n window = MainWindow()\n app.exec()\n","sub_path":"browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":12230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"154261647","text":"\"\"\"\nTa koda kopira vse notebooke spletne knjige v spletno stran in pripravi stran,\nki jih poveže\n\"\"\"\nimport os\nimport nbformat\nimport shutil\n\nEXCLUDE_NOTEBOOKS = ['NM2016.ipynb',\n 'PiNM2016-17.ipynb',\n 'Predavanje 10b - Taylorjeve vrste.ipynb',\n 'working.ipynb']\nPAGEFILE = \"\"\"title: {title}\nurl:\nsave_as: {htmlfile}\nTemplate: {template}\n\n{{% notebook notebooks/{notebook_file} cells[{cells}] %}}\n\"\"\"\n\nINTRO_TEXT = \"\"\"Ta domača stran je pripravljena na podlagi spletnega učbenika \n[Programiranje in numerične metode v ekosistemu Pythona](https://github.com/jankoslavic/pypinm), \nki ga je pripravil Janko Slavič v obliki Jupyter notebookov.\n\"\"\"\n\n\ndef abspath_from_here(*args):\n here = os.path.dirname(__file__)\n path = os.path.join(here, *args)\n return os.path.abspath(path)\n\nNB_SOURCE_DIR = abspath_from_here('..')\nNB_DEST_DIR = abspath_from_here('content', 'notebooks')\nPAGE_DEST_DIR = abspath_from_here('content', 'pages')\n\n\ndef copy_notebooks():\n nblist = sorted(nb for nb in os.listdir(NB_SOURCE_DIR)\n if nb.endswith('.ipynb') and nb not in EXCLUDE_NOTEBOOKS)\n name_map = {nb: nb.rsplit('.', 1)[0].lower() + '.html'\n for nb in nblist}\n\n figsource = abspath_from_here('..', 'fig')\n figdest = abspath_from_here('content', 'fig')\n\n if os.path.exists(figdest):\n shutil.rmtree(figdest)\n shutil.copytree(figsource, figdest)\n\n figurelist = os.listdir(abspath_from_here('content', 'fig'))\n figure_map = {os.path.join('fig', fig) : os.path.join('/pypinm/fig', fig)\n for fig in figurelist}\n\n for nb in nblist:\n base, ext = os.path.splitext(nb)\n print('-', nb)\n\n content = nbformat.read(os.path.join(NB_SOURCE_DIR, nb),\n as_version=4)\n\n if nb == 'NM2016.ipynb':\n cells = '1:'\n template = 'page'\n title = 'Numerične metode 2016/17'\n content.cells[2].source = INTRO_TEXT\n else:\n cells = '2:'\n template = 'booksection'\n title = content.cells[0].source.split('')[1].split('')[0]\n if title == '':\n #if not title.startswith('') or len(title.splitlines()) > 1:\n raise ValueError('title not found in first cell')\n title = title.lstrip('#').strip()\n\n # put nav below title\n content.cells[0], content.cells[1], content.cells[2] = content.cells[2], content.cells[0], content.cells[1]\n\n # Replace internal URLs and figure links in notebook\n for cell in content.cells:\n if cell.cell_type == 'markdown':\n for nbname, htmlname in name_map.items():\n if nbname in cell.source:\n cell.source = cell.source.replace(nbname, htmlname)\n for figname, newfigname in figure_map.items():\n if figname in cell.source:\n cell.source = cell.source.replace(figname, newfigname)\n\n nb_no_spaces = nb.replace(' ', '_')\n nbformat.write(content, os.path.join(NB_DEST_DIR, nb_no_spaces))\n\n pagefile = os.path.join(PAGE_DEST_DIR, base + '.md')\n htmlfile = base.lower() + '.html'\n with open(pagefile, 'w', encoding='utf-8') as f:\n f.write(PAGEFILE.format(title=title,\n htmlfile=htmlfile,\n notebook_file=nb_no_spaces,\n template=template,\n cells=cells))\n\nif __name__ == '__main__':\n copy_notebooks()","sub_path":"book/copy_notebooks.py","file_name":"copy_notebooks.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473623748","text":"from common import cnx\n\n\nclass Table:\n\n def __init__(self, sql_read_statement, params=None):\n self.headers, self.data = self._fetch_table_contents(sql_read_statement, params)\n self.table = (self.headers, *self.data)\n\n def __repr__(self):\n column_lengths = [max([len(str(i[x])) for i in self.table]) for x in range(len(self.data[0]))]\n divider_text, header_text = \"+\", \"\"\n\n for i, header in enumerate(self.headers):\n padding_left = round((column_lengths[i] - len(header))/2 + 0.5) + 1\n padding_right = round((column_lengths[i] - len(header))/2 - 0.5) + 1\n header_text += \"|\" + \" \" * padding_left + str(header) + \" \" * padding_right\n divider_text += \"-\" * (padding_left + padding_right + len(header)) + \"+\"\n header_text += \"|\"\n full_text = divider_text + \"\\n\" + header_text + \"\\n\" + divider_text + \"\\n\"\n\n for record in self.data:\n for i, field in enumerate(record):\n padding_left = 1\n padding_right = (column_lengths[i] - len(str(field))) + 1\n full_text += \"|\" + \" \" * padding_left + str(field) + \" \" * padding_right\n full_text += \"|\\n\"\n full_text += divider_text\n return full_text\n\n @staticmethod\n @cnx.connection_handler()\n def _fetch_table_contents(connection, cursor, statement, params=None):\n cursor.execute(statement, params)\n data = cursor.fetchall()\n return tuple(i[0] for i in cursor.description), data\n\n def sort_by(self, column, asc=False):\n self.data = sorted(self.data, key=lambda x: x[column], reverse=asc)\n","sub_path":"classes/Table.py","file_name":"Table.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"275169616","text":"import uuid\n\nfrom rift.data.handler import get_handler\n\nJOB_COLLECTION = \"jobs\"\n\n\nclass Tenant(object):\n def __init__(self, tenant_id, name=None, targets=None):\n self.tenant_id = tenant_id\n self.name = name\n self.targets = targets if targets is not None else list()\n\n def as_dict(self):\n return {\n \"tenant_id\": self.tenant_id,\n \"name\": self.name,\n \"targets\": [target.as_dict() for target in self.targets]\n }\n\n\nclass Job(object):\n def __init__(self, tenant_id, name, actions, job_id=None):\n self.tenant_id = tenant_id\n self.name = name\n self.actions = actions\n self.job_id = job_id if job_id is not None else uuid.uuid4()\n\n def as_dict(self):\n return {\n \"job_id\": self.job_id,\n \"tenant_id\": self.tenant_id,\n \"name\": self.name,\n \"actions\": [action.as_dict() for action in self.actions]\n }\n\n\nclass Action(object):\n def __init__(self, targets, action_type, parameters=None):\n self.targets = targets\n self.action_type = action_type\n self.parameters = parameters if parameters is not None else dict()\n\n def as_dict(self):\n return {\n \"targets\": [target.as_dict() for target in self.targets],\n \"action_type\": self.action_type,\n \"parameters\": self.parameters\n }\n\n\nclass Target(object):\n \"\"\"\n Represents a target node to execute actions against\n \"\"\"\n def __init__(self, name, public_ip, private_ip):\n self.name = name\n self.public_ip = public_ip\n self.private_ip = private_ip\n\n def as_dict(self):\n return {\n \"name\": self.name,\n \"public_ip\": self.public_ip,\n \"private_ip\": self.private_ip\n }\n\n\ndef build_job_from_dict(job_dict):\n tenant_id = job_dict[\"tenant_id\"]\n name = job_dict[\"name\"]\n actions = [\n _build_action_from_dict(action_dict)\n for action_dict in job_dict[\"actions\"]]\n job_id = job_dict[\"job_id\"]\n\n return Job(tenant_id=tenant_id, name=name, actions=actions, job_id=job_id)\n\n\ndef _build_action_from_dict(action_dict):\n targets = [\n _build_target_from_dict(target_dict)\n for target_dict in action_dict[\"targets\"]]\n action_type = action_dict[\"action_type\"]\n parameters = action_dict[\"parameters\"]\n return Action(\n targets=targets,\n action_type=action_type,\n parameters=parameters\n )\n\n\ndef _build_target_from_dict(target_dict):\n return Target(**target_dict)\n\n\ndef save_job(job):\n db_handler = get_handler()\n db_handler.insert_document(\n object_name=JOB_COLLECTION, document=job.as_dict()\n )\n\n\ndef update_job(job):\n db_handler = get_handler()\n db_handler.update_document(\n object_name=JOB_COLLECTION,\n document=job.as_dict(),\n query_filter={\"job_id\": job.job_id}\n )\n\ndef get_job(job_id):\n db_handler = get_handler()\n job_dict = db_handler.get_document(\n object_name=JOB_COLLECTION,\n query_filter={\"job_id\": job_id})\n\n return build_job_from_dict(job_dict)\n\ndef get_jobs(tenant_id):\n db_handler = get_handler()\n jobs_dict = db_handler.get_documents(\n object_name=JOB_COLLECTION,\n query_filter={\"tenant_id\": tenant_id})\n\n return [build_job_from_dict(job) for job in jobs_dict]\n\ndef delete_job(job_id):\n db_handler = get_handler()\n db_handler.delete_document(\n object_name=JOB_COLLECTION,\n query_filter={\"job_id\": job_id}\n )\n","sub_path":"rift/data/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"336767333","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport time\n\n\nTICKS = 1024\nHARMONICS = 8\nFREQUENCY = 1200\nSTEP = FREQUENCY / HARMONICS\n\nclass Harmonic:\n def __init__(self, frequency, ticks):\n self.amplitude = random.uniform(0.0, 1.0)\n self.phase = random.uniform(0.0, 2*np.pi)\n current_xs = [0 for _ in range(ticks)]\n current_xs = [self.amplitude*np.sin(frequency*t+self.phase) for t in range(ticks)]\n self.xs = current_xs\n\nclass Signal:\n def __init__(self, harmonic_amount, ticks, step):\n current_sum = [0 for _ in range(ticks)]\n start = time.time()\n for i in range(1, harmonic_amount+1):\n current_harmonic = Harmonic(step*i, ticks)\n current_sum = [current_sum[t]+current_harmonic.xs[t] for t in range(ticks)]\n self.elapsed_time = time.time() - start\n self.xss = current_sum\n self.ts = [t for t in range(ticks)]\n\ndef generate_signal(harmonic_amount, ticks, step):\n return Signal(harmonic_amount, ticks, step)\n\ndef calc_mean(signal, ticks):\n mean = sum(signal.xss) / ticks\n print(\"Mean = {}\".format(mean))\n return mean\n\ndef calc_dispertion(signal, mean, ticks):\n dispertion = sum(((x-mean)*(x-mean)) for x in signal.xss) / (ticks-1)\n print(\"Dispertion = {}\".format(dispertion))\n print('----------------------------------------------------------')\n\ndef calc_autocorrelation(signal, mean, ticks):\n autocorr_sum = [sum([(signal.xss[t]-mean)*(signal.xss[t+tau]-mean) \\\n for t in range(ticks)]) for tau in range(ticks)]\n autocorr_sum = np.divide(autocorr_sum, (ticks-1))\n return autocorr_sum\n\ndef calc_correlation(signal_1, signal_2, mean_1, mean_2, ticks):\n corr_sum = [sum([(signal_1.xss[t]-mean_1)*(signal_2.xss[t+tau]-mean_2) \\\n for t in range(ticks)]) for tau in range(ticks)]\n corr_sum = np.divide(corr_sum, (ticks-1))\n return corr_sum\n\ndef calc_complexity(num):\n times = [generate_signal(HARMONICS, TICKS*i, STEP).elapsed_time for i in range(1, num+1)]\n nums = [TICKS*i for i in range(1, num+1)]\n return times, nums\n\nsignal_x = generate_signal(HARMONICS, TICKS*2, STEP)\nsignal_y = generate_signal(HARMONICS, TICKS*2, STEP)\n\nmean_x = calc_mean(signal_x, TICKS*2)\ncalc_dispertion(signal_x, mean_x, TICKS*2)\n\nmean_y = calc_mean(signal_y, TICKS*2)\ncalc_dispertion(signal_y, mean_y, TICKS*2)\n\nautocorr_x = calc_autocorrelation(signal_x, mean_x, TICKS)\nautocorr_y = calc_autocorrelation(signal_y, mean_y, TICKS)\ncorr_xy = calc_correlation(signal_x, signal_y, mean_x, mean_y, TICKS)\n\ncomplexity_t, complexity_N = calc_complexity(10)\n\nplt.subplot(3, 2, 1)\nplt.plot(signal_x.ts, signal_x.xss, 'm')\nplt.ylabel('x(t)')\nplt.grid(True)\n\nplt.subplot(3, 2, 3)\nplt.plot(signal_y.ts, signal_y.xss, 'b')\nplt.xlabel('t')\nplt.ylabel('y(t)')\nplt.grid(True)\n\nplt.subplot(3, 2, 5)\nplt.plot(complexity_N, complexity_t, 'k')\nplt.xlabel('N')\nplt.ylabel('t')\nplt.grid(True)\n\nttau = np.arange(0, TICKS, 1)\n\nplt.subplot(3, 2, 2)\nplt.plot(ttau, autocorr_x, 'm')\nplt.ylabel('Rxx')\nplt.grid(True)\n\nplt.subplot(3, 2, 4)\nplt.plot(ttau, autocorr_y, 'b')\nplt.ylabel('Ryy')\nplt.grid(True)\n\nplt.subplot(3, 2, 6)\nplt.plot(ttau, corr_xy, 'c')\nplt.xlabel('tau')\nplt.ylabel('Rxy')\nplt.grid(True)\n\nplt.savefig('fig2.png')\nplt.show()\n","sub_path":"Anna_Doroshenko_IO52/lab02.py","file_name":"lab02.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"572352554","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\nimport inspect\nimport logging\nimport os\nfrom pathlib import Path\nfrom urllib.parse import urlparse\n\nimport classy_vision\nimport torch\nfrom classy_vision.generic.opts import check_generic_args, get_parser\nfrom classy_vision.generic.registry_utils import import_all_packages_from_directory\nfrom classy_vision.generic.util import load_checkpoint, load_json\nfrom classy_vision.hooks import (\n CheckpointHook,\n LossLrMeterLoggingHook,\n ModelComplexityHook,\n ProfilerHook,\n TimeMetricsHook,\n)\nfrom classy_vision.tasks import FineTuningTask, build_task\nfrom classy_vision.trainer.elastic_trainer import ElasticTrainer\nfrom torch.distributed import Backend\nfrom torchelastic.p2p import CoordinatorP2P\nfrom torchvision import set_video_backend\n\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(\n level=logging.INFO, format=\"[%(levelname)s] %(asctime)s %(module)s: %(message)s\"\n)\n\n\n# local_rank == host local rank assigned and passed by torch.multiprocessing\ndef main(local_rank, c10d_backend, rdzv_init_url, max_world_size, classy_args):\n torch.manual_seed(0)\n set_video_backend(classy_args.video_backend)\n\n # Loads config, sets up task\n config = load_json(classy_args.config_file)\n\n task = build_task(config)\n\n # Load checkpoint, if available\n checkpoint = load_checkpoint(classy_args.checkpoint_folder, classy_args.device)\n task.set_checkpoint(checkpoint)\n\n pretrained_checkpoint = load_checkpoint(\n classy_args.pretrained_checkpoint_folder, classy_args.device\n )\n if pretrained_checkpoint is not None:\n assert isinstance(\n task, FineTuningTask\n ), \"Can only use a pretrained checkpoint for fine tuning tasks\"\n task.set_pretrained_checkpoint(pretrained_checkpoint)\n\n hooks = [\n LossLrMeterLoggingHook(classy_args.log_freq),\n ModelComplexityHook(),\n TimeMetricsHook(),\n ]\n\n if classy_args.checkpoint_folder != \"\":\n args_dict = vars(classy_args)\n args_dict[\"config\"] = config\n hooks.append(\n CheckpointHook(\n classy_args.checkpoint_folder,\n args_dict,\n checkpoint_period=classy_args.checkpoint_period,\n )\n )\n if classy_args.profiler:\n hooks.append(ProfilerHook())\n\n task.set_hooks(hooks)\n\n assert c10d_backend == Backend.NCCL or c10d_backend == Backend.GLOO\n if c10d_backend == torch.distributed.Backend.NCCL:\n # needed to enable NCCL error handling\n os.environ[\"NCCL_BLOCKING_WAIT\"] = \"1\"\n\n coordinator = CoordinatorP2P(\n c10d_backend=c10d_backend,\n init_method=rdzv_init_url,\n max_num_trainers=max_world_size,\n process_group_timeout=60000,\n )\n trainer = ElasticTrainer(\n use_gpu=classy_args.device == \"gpu\",\n num_dataloader_workers=classy_args.num_workers,\n local_rank=local_rank,\n elastic_coordinator=coordinator,\n input_args={},\n )\n trainer.train(task)\n\n\ndef parse_classy_args():\n \"\"\"\n parses default classy args from sys.argv adding some nice-to-have\n decorations (e.g. automatically set --device depending on the host type)\n \"\"\"\n parser = get_parser()\n args = parser.parse_args()\n\n args.config_file = to_abs_path(args.config_file)\n args.device = \"gpu\" if torch.cuda.is_available() else \"cpu\"\n check_generic_args(args)\n return args\n\n\n# TODO we may want to upstream this to classy_vision utils\ndef to_abs_path(config_path_url):\n \"\"\"\n Returns the absolute file path to the classy config file\n\n Get config relative to classy's module\n to_abs_path(\"classy-vision://config/resnet_50.json\")\n -- or --\n\n Get config relative to this script\n to_abs_path(\"my_config_dir/resnet_50.json\")\n -- or --\n\n Get config from absolute path\n to_abs_path(\"/absolute/config/dir/path/resnet_50.json\")\n \"\"\"\n config_url = urlparse(config_path_url)\n if config_url.scheme == \"classy-vision\":\n # read relative to classy_vision module\n classy_path = Path(inspect.getfile(classy_vision)).parent\n classy_config_file = os.path.join(\n classy_path, f\"{config_url.netloc}{config_url.path}\"\n )\n else:\n # read relative to script if not absolute path\n if os.path.isabs(config_url.path):\n classy_config_file = config_url.path\n else:\n classy_config_file = os.path.join(\n os.path.dirname(__file__), config_url.path\n )\n return classy_config_file\n\n\ndef default_local_world_size():\n \"\"\"\n If CUDA is available, returns the number of GPU devices on the host.\n Otherwise returns 1.\n \"\"\"\n if torch.cuda.is_available():\n return torch.cuda.device_count()\n else:\n return 1\n\n\nif __name__ == \"__main__\":\n # num_nodes == number of hosts participating on this job\n # assumes homogeneous hosts\n # local_world_size = number of workers to run per node\n # world_size = total number of workers\n num_nodes = os.environ.get(\"SIZE\", 1)\n min_num_nodes = os.environ.get(\"MIN_SIZE\", num_nodes)\n max_num_nodes = os.environ.get(\"MAX_SIZE\", num_nodes)\n\n local_world_size = default_local_world_size()\n min_world_size = local_world_size * min_num_nodes\n max_world_size = local_world_size * max_num_nodes\n\n if torch.cuda.is_available():\n if not local_world_size:\n num_gpus = torch.cuda.device_count()\n log.info(f\"Found {num_gpus} gpus on this host\")\n local_world_size = num_gpus\n else:\n if not local_world_size:\n local_world_size = 1\n\n world_size = local_world_size * num_nodes\n log.info(f\"Running {local_world_size}/{world_size} workers on this host\")\n\n rdzv_endpoint = os.environ.get(\"RDZV_ENDPOINT\", \"localhost:2379\")\n job_id = os.environ.get(\"JOB_ID\", \"torchelastic_classy_vision_example\")\n rdzv_init_method = (\n f\"etcd://{rdzv_endpoint}/{job_id}\"\n f\"?min_workers={min_world_size}\"\n f\"&max_workers={max_world_size}\"\n f\"&last_call_timeout=5\"\n )\n log.info(f\"rdzv init method={rdzv_init_method}\")\n\n c10d_backend = os.environ.get(\"TORCH_DISTRIBUTED_BACKEND\", Backend.GLOO).lower()\n\n file_root = Path(__file__).parent\n import_all_packages_from_directory(file_root)\n\n if local_world_size == 1:\n local_rank = 0\n main(\n local_rank,\n c10d_backend,\n rdzv_init_method,\n max_world_size,\n parse_classy_args(),\n )\n else:\n torch.multiprocessing.spawn(\n fn=main,\n args=(c10d_backend, rdzv_init_method, max_world_size, parse_classy_args()),\n nprocs=local_world_size,\n join=True,\n )\n","sub_path":"examples/classy_vision/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"417340240","text":"import os\nfrom setuptools import find_packages, setup\n\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n\n__version__ = None\nexec(open(os.path.join(THIS_DIR, \"muffnn\", \"version.py\")).read())\n\nsetup(\n name='muffnn',\n version=__version__,\n author='Civis Analytics, Inc.',\n author_email='opensource@civisanalytics.com',\n packages=find_packages(),\n url='https://github.com/civisanalytics/muffnn',\n description=('Multilayer Feed-Forward Neural Network (MuFFNN) models with '\n 'TensorFlow and scikit-learn'),\n long_description=open(os.path.join(THIS_DIR, 'README.md')).read(),\n include_package_data=True,\n license=\"BSD-3\"\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"294810760","text":"from celluloid import Camera\nfrom view import plot_board\nimport utils as u\nfrom heapq import heappush, heappop\n\n\ndef search(board: list, origin: tuple,\n target: tuple, camera: Camera = None) -> list:\n queue = [(0, [origin])]\n u.trapezoidal_dist.values = {origin: 0}\n processed = {origin}\n path = [None]\n\n while path[-1] != target:\n if not queue:\n path = None\n break\n\n path = heappop(queue)[1]\n curr = path[-1]\n if curr not in (origin, target):\n # marca como visitado\n board[curr[0]][curr[1]] = .4\n\n # Append moves\n for move in u.available_moves(board, path[-1]):\n if move not in processed:\n heappush(queue, (u.trapezoidal_dist(move, target),\n path + [move]))\n if move != target:\n # marca como tocado\n board[move[0]][move[1]] = .2\n processed.add(move)\n\n if camera is not None:\n plot_board(board)\n camera.snap()\n\n board[origin[0]][origin[1]] = u.str2n['#']\n return path\n","sub_path":"best_first.py","file_name":"best_first.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"330415930","text":"import os\nimport re\nimport tempfile\n\nfrom commands.AbstractCommand import AbstractCommand\nfrom config.config import API_TOKEN\nfrom models.Location import Location\n\n\nclass AddCommand(AbstractCommand):\n STATE_START = 0\n STATE_NAME = 1\n STATE_IMAGE = 2\n STATE_COORDINATES = 3\n\n def __init__(self, bot, connection):\n super().__init__(bot, connection)\n self.__previous_state = None\n self.__location = None\n self.reload()\n\n def process(self, message):\n self.process_next_state(message)\n\n def process_next_state(self, message):\n result_message = ''\n message_info = self.get_message_info(message)\n\n if self.__previous_state is None:\n self.increment_step()\n\n self.get_location().set_user_id(message_info.get_user().get_id())\n\n result_message = \"\"\"\n You want add new location. Please write location name:\n \"\"\"\n elif self.__previous_state == self.STATE_START:\n self.increment_step()\n self.get_location().set_name(message_info.get_text())\n\n result_message = \"\"\"Please add location photo or use: \\n{}\"\"\".format(self.get_cancel_step_commands_text())\n\n elif self.__previous_state == self.STATE_NAME:\n self.increment_step()\n if message_info.get_file_id() is not None:\n file_info = self.bot.get_file(message_info.get_file_id())\n downloaded_file = self.bot.download_file(file_info.file_path)\n\n if downloaded_file != '':\n file_url = os.path.join(tempfile.gettempdir(), '{}.jpg'.format(message_info.get_file_id()))\n with open(file_url, 'wb') as new_file:\n new_file.write(downloaded_file)\n\n self.get_location().set_photo_url(file_url)\n\n result_message = \"\"\"Please add coordinates in format (50.45466, 30.5238) without brackets, where:\n 50.45466 - latitude\n 30.5238 - longitude\n \\n{}\"\"\".format(self.get_cancel_step_commands_text())\n elif self.__previous_state == self.STATE_IMAGE:\n location_coordinates = message_info.get_text()\n if self.is_coordinates(location_coordinates) is True:\n latitude, longtitude = location_coordinates.split(',')\n self.get_location().set_latitude(latitude.strip())\n self.get_location().set_longtitude(longtitude.strip())\n\n self.save(message)\n\n if result_message != '':\n self.bot.send_message(message_info.get_chat().get_id(), result_message)\n\n def is_coordinates(self, text):\n result = re.search(r\"([0-9]{1,2}).([0-9]+),([\\s]{0,})([0-9]{1,2}).([0-9]+)\", text)\n return result is not None\n\n def save(self, message):\n connection = self.connection.get_connection()\n c = connection.cursor()\n c.execute(self.get_location().get_insert_query())\n connection.commit()\n self.connection.close_connection()\n\n self.bot.send_message(self.get_message_info(message).get_chat().get_id(), 'Location successfully saved')\n self.reload()\n\n def reload(self):\n self.__previous_state = None\n self.__location = Location()\n\n def increment_step(self):\n if self.__previous_state is None:\n self.__previous_state = self.STATE_START\n elif self.__previous_state == self.STATE_START:\n self.__previous_state = self.STATE_NAME\n elif self.__previous_state == self.STATE_NAME:\n self.__previous_state = self.STATE_IMAGE\n elif self.__previous_state == self.STATE_IMAGE:\n self.__previous_state = self.STATE_COORDINATES\n else:\n self.reload()\n\n def get_location(self) -> Location:\n return self.__location\n\n def get_cancel_step_commands_text(self):\n return \"\"\"\n /next_step - got to next step of current command\n /cancel - for cancel add new location\n \"\"\"","sub_path":"commands/AddCommand.py","file_name":"AddCommand.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"169656142","text":"import pygame\nfrom network import Network\nimport threading\nimport time\nimport json\nimport random\n\nusername = input(\"Nome do jogador: \")\nusers = (username,)\nnetwork_received = None\n\n\n# Tamanho da tela\nWIDTH = 1200 # Largura da tela.\nHEIGHT = 600 # Altura da tela.\nMARGIN = 5 # Margem entre as celulas.\n# Tela\ntela = pygame.display.set_mode([WIDTH, HEIGHT])\n# Cores\ncor_branca = (255, 255, 255)\ncor_cinza = (105, 105, 105)\ncor_cinza_fosco = (108, 123, 139)\ncor_cinza_claro = (220, 220, 220)\ncor_vermelho = (250, 128, 114)\ncor_vermelho_escuro = (165, 42, 42)\ncor_verde_escuro = (60, 179, 113)\ncor_verde = (152, 251, 152)\ncor_preta = (0,0,0)\n# Superficies\nsup = pygame.Surface((WIDTH/4, HEIGHT))\nsup2 = pygame.Surface((WIDTH/4, HEIGHT))\nsup3 = pygame.Surface((175,HEIGHT))\nsup.fill(cor_verde)\nsup2.fill(cor_vermelho)\nsup3.fill(cor_cinza_fosco)\n\n# Retangulos\nretangulo = pygame.Rect(0,0, 175, 100)\nrect_acertos = pygame.Rect(175,0, 300, 100)\nrect_erros = pygame.Rect(900,0, 300, 100)\n\n# Fontes\npygame.font.init()\nfont_padrao = pygame.font.get_default_font()\nfonte_jogo = pygame.font.SysFont(font_padrao, 30)\n\n# Textos Padrão\nacertos = fonte_jogo.render('Acertos: ', 1, (cor_branca))\nerros = fonte_jogo.render('Erros: ', 1, (cor_branca))\njogadores = fonte_jogo.render('Jogadores: ', 1, (cor_branca))\n# Tempo da rodada\ntempo_rodada = 120\n\n# Dados\ndado0 = ['R', 'I', 'F', 'O', 'B', 'X']\ndado1 = ['I', 'F', 'E', 'H', 'E', 'Y']\ndado2 = ['D', 'E', 'N', 'O', 'W', 'S']\ndado3 = ['U', 'T', 'O', 'K', 'N', 'D']\ndado4 = ['H', 'M', 'S', 'R', 'A', 'O']\ndado5 = ['L', 'U', 'P', 'E', 'T', 'S']\ndado6 = ['A', 'C', 'I', 'T', 'O', 'A']\ndado7 = ['Y', 'L', 'G', 'K', 'U', 'E']\ndado8 = ['Q', 'B', 'M', 'J', 'O', 'A']\ndado9 = ['E', 'H', 'I', 'S', 'P', 'N']\ndado10 = ['V', 'E', 'T', 'I', 'G', 'N']\ndado11 = ['B', 'A', 'L', 'I', 'Y', 'T']\ndado12 = ['E', 'Z', 'A', 'V', 'N', 'D']\ndado13 = ['R', 'A', 'L', 'E', 'S', 'C']\ndado14 = ['U', 'W', 'I', 'L', 'R', 'G']\ndado15 = ['P', 'A', 'C', 'E', 'M', 'D']\n\nlista_dados = [dado0,dado1,dado2,dado3,dado4,dado5,dado6,dado7,dado8,dado9,dado10,dado11,dado12,dado13,dado14,dado15]\n\n#### Inicio dos metodos estaticos ####\ndef quitGame():\n pygame.quit()\n quit()\n\ndef enviar():\n print('enviado!')\n pass\ndef pontoJogadores(p):\n pontos = p\n if pontos > 0:\n pt = fonte_jogo.render(str(pontos), 0, cor_branca)\n tela.blit(pt, (140, 103))\ndef players(u):\n plays = u.__len__()\n h = 103\n w = 30\n if u.__len__()>0:\n while plays > 0:\n p = fonte_jogo.render(u[plays-1], 1, cor_branca)\n tela.blit(p, (w,h))\n h = h + 20\n plays -= 1\n\n\ndef certo_errado(err, corr):\n cor = corr.__len__()\n er = err.__len__()\n w1 = 925\n w2 = 200\n he = 103\n hc = 103\n if err.__len__()> 0:\n while er > 0:\n e = fonte_jogo.render(err[er-1], 1, cor_vermelho_escuro)\n tela.blit(e, (w1, he))\n he = he+20\n er -=1\n if he > 580:\n w1 = w1 + 145\n he = 103\n if corr.__len__()> 0:\n while cor > 0:\n e = fonte_jogo.render(corr[cor-1], 1, cor_verde_escuro)\n tela.blit(e, (w2, hc))\n hc = hc+20\n cor -=1\n if hc > 580:\n w2 = w2 + 145\n hc = 103\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, cor_preta)\n return textSurface, textSurface.get_rect()\n\ndef button(msg, x, y, w, h, i, a, action=None):\n # Eventos do mouse nos botoes\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\n pygame.draw.rect(tela, a, (x,y,w,h))\n if click[0] == 1 and action != None:\n action()\n else:\n pygame.draw.rect(tela, i, (x,y,w,h))\n textSuperfice, textRect = text_objects(msg,fonte_jogo)\n textRect.center = ((x + (w/2)),(y +(h/2)))\n tela.blit(textSuperfice, textRect)\n\n#### Fim dos metodos estaticos ####\nclass Game():\n def __init__(self):\n pygame.init()\n # network\n self.network = Network()\n self.network.connect()\n self.network.login(username)\n netThread = threading.Thread(target=self.update_network)\n netThread.start()\n pygame.display.set_caption(\"Boogle\")\n relogio = pygame.time.Clock()\n\n arq = open('palavras.txt', 'r')\n lista_palavras = arq.readlines()\n\n sair = False\n b1 = random.randint(0, 5)\n b2 = random.randint(0, 5)\n b3 = random.randint(0, 5)\n b4 = random.randint(0, 5)\n b5 = random.randint(0, 5)\n b6 = random.randint(0, 5)\n b7 = random.randint(0, 5)\n b8 = random.randint(0, 5)\n b9 = random.randint(0, 5)\n b10 = random.randint(0, 5)\n b11 = random.randint(0, 5)\n b12 = random.randint(0, 5)\n b13 = random.randint(0, 5)\n b14 = random.randint(0, 5)\n b15 = random.randint(0, 5)\n b16 = random.randint(0, 5)\n pontos = 0\n lista_clicados = []\n lista_digitados = []\n lista_erradas = []\n lista_corretas = []\n\n clicado1 = False\n clicado2 = False\n clicado3 = False\n clicado4 = False\n clicado5 = False\n clicado6 = False\n clicado7 = False\n clicado8 = False\n clicado9 = False\n clicado10 = False\n clicado11 = False\n clicado12 = False\n clicado13 = False\n clicado14 = False\n clicado15 = False\n clicado16 = False\n while sair != True:\n for event in pygame.event.get():\n # Eventos\n if event.type == pygame.QUIT:\n sair = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n # User clicks the mouse. Get the position\n pos = pygame.mouse.get_pos()\n print(\"Click \", pos)\n mouse = pygame.mouse.get_pos()\n\n if 480 + 100 > mouse[0] > 480 and 40 + 100 > mouse[1] > 40:\n if clicado1 == False:\n # print (dado0[b1])\n lista_clicados.append(dado0[b1])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado1 = True\n else:\n print(lista_clicados.__len__())\n print(dado0[b1])\n\n elif 585 + 100 > mouse[0] > 585 and 40 + 100 > mouse[1] > 40:\n if clicado2 == False:\n # print (dado1[b2])\n lista_clicados.append(dado1[b2])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado2 = True\n else:\n print(lista_clicados.__len__())\n print(dado1[b2])\n elif 690 + 100 > mouse[0] > 690 and 40 + 100 > mouse[1] > 40:\n if clicado3 == False:\n # print (dado2[b3])\n lista_clicados.append(dado2[b3])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado3 = True\n else:\n print(lista_clicados.__len__())\n print(dado2[b3])\n elif 795 + 100 > mouse[0] > 795 and 40 + 100 > mouse[1] > 40:\n if clicado4 == False:\n # print (dado3[b4])\n lista_clicados.append(dado3[b4])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado4 = True\n else:\n print(lista_clicados.__len__())\n print(dado3[b4])\n elif 480 + 100 > mouse[0] > 480 and 145 + 100 > mouse[1] > 145:\n if clicado5 == False:\n # print (dado4[b5])\n lista_clicados.append(dado4[b5])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado5 = True\n else:\n print(lista_clicados.__len__())\n print(dado4[b5])\n elif 585 + 100 > mouse[0] > 585 and 145 + 100 > mouse[1] > 145:\n if clicado6 == False:\n # print (dado5[b6])\n lista_clicados.append(dado5[b6])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado6 = True\n else:\n print(lista_clicados.__len__())\n print(dado5[b6])\n elif 690 + 100 > mouse[0] > 690 and 145 + 100 > mouse[1] > 145:\n if clicado7 == False:\n # print (dado6[b7])\n lista_clicados.append(dado6[b7])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado7 = True\n else:\n print(lista_clicados.__len__())\n print(dado6[b7])\n elif 795 + 100 > mouse[0] > 795 and 145 + 100 > mouse[1] > 145:\n if clicado8 == False:\n # print(dado7[b8])\n lista_clicados.append(dado7[b8])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado8 = True\n else:\n print(lista_clicados.__len__())\n print(dado7[b8])\n elif 480 + 100 > mouse[0] > 480 and 250 + 100 > mouse[1] > 250:\n if clicado9 == False:\n # print (dado8[b9])\n lista_clicados.append(dado8[b9])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado9 = True\n else:\n print(lista_clicados.__len__())\n print(dado8[b9])\n elif 585 + 100 > mouse[0] > 585 and 250 + 100 > mouse[1] > 250:\n if clicado10 == False:\n # print (dado9[b10])\n lista_clicados.append(dado9[b10])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado10 = True\n else:\n print(lista_clicados.__len__())\n print(dado9[b10])\n elif 690 + 100 > mouse[0] > 690 and 250 + 100 > mouse[1] > 250:\n if clicado11 == False:\n # print (dado10[b11])\n lista_clicados.append(dado10[b11])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado11 = True\n else:\n print(lista_clicados.__len__())\n print(dado10[b11])\n elif 795 + 100 > mouse[0] > 795 and 250 + 100 > mouse[1] > 250:\n if clicado12 == False:\n # print (dado11[b12])\n lista_clicados.append(dado11[b12])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado12 = True\n else:\n print(lista_clicados.__len__())\n print(dado11[b12])\n elif 480 + 100 > mouse[0] > 480 and 355 + 100 > mouse[1] > 355:\n if clicado13 == False:\n # print (dado12[b13])\n lista_clicados.append(dado12[b13])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado13 = True\n else:\n print(lista_clicados.__len__())\n print(dado12[b13])\n elif 585 + 100 > mouse[0] > 585 and 355 + 100 > mouse[1] > 355:\n if clicado14 == False:\n # print (dado13[b14])\n lista_clicados.append(dado13[b14])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado14 = True\n else:\n print(lista_clicados.__len__())\n print(dado13[b14])\n elif 690 + 100 > mouse[0] > 690 and 355 + 100 > mouse[1] > 355:\n if clicado15 == False:\n # print (dado14[b15])\n lista_clicados.append(dado14[b15])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado15 = True\n else:\n print(lista_clicados.__len__())\n print(dado14[b15])\n elif 795 + 100 > mouse[0] > 795 and 355 + 100 > mouse[1] > 355:\n if clicado16 == False:\n # print (dado15[b16])\n lista_clicados.append(dado15[b16])\n print(lista_clicados.__len__())\n print(lista_clicados[0])\n clicado16 = True\n else:\n print(lista_clicados.__len__())\n print(dado15[b16])\n elif 515 + 130 > mouse[0] > 425 and 530 + 50 > mouse[1] > 530:\n lista_clicados.clear()\n clicado1 = False\n clicado2 = False\n clicado3 = False\n clicado4 = False\n clicado5 = False\n clicado6 = False\n clicado7 = False\n clicado8 = False\n clicado9 = False\n clicado10 = False\n clicado11 = False\n clicado12 = False\n clicado13 = False\n clicado14 = False\n clicado15 = False\n clicado16 = False\n # print((\"\").join(lista_palavras))\n if lista_corretas.__len__() > 0:\n print('corretas:' + str(lista_corretas))\n if lista_erradas.__len__() > 0:\n print('erradas:' + str(lista_erradas))\n\n elif 740 + 130 > mouse[0] > 425 and 530 + 50 > mouse[1] > 530:\n if click_list.__len__() > 0:\n a = ('').join(click_list)\n if a not in lista_digitados:\n lista_digitados.append(('').join(click_list))\n if a + '\\n' not in (lista_palavras):\n lista_erradas.append(a)\n print(\"erradas: \" + str(lista_erradas))\n else:\n lista_corretas.append(a)\n print(\"corretas: \" + str(lista_corretas))\n pontos = pontos + 10\n lista_clicados.clear()\n clicado1 = False\n clicado2 = False\n clicado3 = False\n clicado4 = False\n clicado5 = False\n clicado6 = False\n clicado7 = False\n clicado8 = False\n clicado9 = False\n clicado10 = False\n clicado11 = False\n clicado12 = False\n clicado13 = False\n clicado14 = False\n clicado15 = False\n clicado16 = False\n else:\n lista_clicados.clear()\n clicado1 = False\n clicado2 = False\n clicado3 = False\n clicado4 = False\n clicado5 = False\n clicado6 = False\n clicado7 = False\n clicado8 = False\n clicado9 = False\n clicado10 = False\n clicado11 = False\n clicado12 = False\n clicado13 = False\n clicado14 = False\n clicado15 = False\n clicado16 = False\n for item in lista_digitados:\n print(item)\n else:\n lista_clicados.clear()\n for item in lista_digitados:\n print(item)\n relogio.tick(20)\n # Criando os elementos de tela\n tela.fill(cor_cinza_fosco)\n tela.blit(sup, [175, 0])\n tela.blit(sup2, [WIDTH * 3 / 4, 0])\n tela.blit(sup3, [0, 30])\n pygame.draw.rect(tela, cor_cinza, retangulo)\n pygame.draw.rect(tela, cor_verde_escuro, rect_acertos)\n pygame.draw.rect(tela, cor_vermelho_escuro, rect_erros)\n # mostrar jogadores na tela\n players(users)\n # mostrar pontos na tela\n pontoJogadores(pontos)\n # mostrar erros e acertos na tela\n certo_errado(lista_erradas, lista_corretas)\n # Eventos e criação do butao\n button('Limpar', 515, 530, 130, 50, cor_cinza_claro, cor_cinza, None)\n button('Enviar', 740, 530, 130, 50, cor_cinza_claro, cor_cinza, enviar)\n button(dado0[b1], 480, 40, 100, 100, cor_branca, cor_verde, None)\n button(dado1[b2], 585, 40, 100, 100, cor_branca, cor_verde, None)\n button(dado2[b3], 690, 40, 100, 100, cor_branca, cor_verde, None)\n button(dado3[b4], 795, 40, 100, 100, cor_branca, cor_verde, None)\n button(dado4[b5], 480, 145, 100, 100, cor_branca, cor_verde, None)\n button(dado5[b6], 585, 145, 100, 100, cor_branca, cor_verde, None)\n button(dado6[b7], 690, 145, 100, 100, cor_branca, cor_verde, None)\n button(dado7[b8], 795, 145, 100, 100, cor_branca, cor_verde, None)\n button(dado8[b9], 480, 250, 100, 100, cor_branca, cor_verde, None)\n button(dado9[b10], 585, 250, 100, 100, cor_branca, cor_verde, None)\n button(dado10[b11], 690, 250, 100, 100, cor_branca, cor_verde, None)\n button(dado11[b12], 795, 250, 100, 100, cor_branca, cor_verde, None)\n button(dado12[b13], 480, 355, 100, 100, cor_branca, cor_verde, None)\n button(dado13[b14], 585, 355, 100, 100, cor_branca, cor_verde, None)\n button(dado14[b15], 690, 355, 100, 100, cor_branca, cor_verde, None)\n button(dado15[b16], 795, 355, 100, 100, cor_branca, cor_verde, None)\n\n # Textos na tela\n tela.blit(acertos, (195, 35))\n tela.blit(erros, (925, 35))\n tela.blit(jogadores, (20, 35))\n\n\n # Mostrar letras digitadas\n click_list = lista_clicados\n i = 0\n while i != click_list.__len__():\n digitados = fonte_jogo.render(('').join(click_list), 0, cor_branca)\n i = i + 1\n tela.blit(digitados, (585, 480))\n\n # Timer\n segundos = pygame.time.get_ticks() / 1000\n resto = int(segundos)\n timer = tempo_rodada\n timer -= resto\n contador = fonte_jogo.render('Tempo: ' + str(timer), 0, cor_branca)\n tela.blit(contador, (630, 3))\n\n # Atualiza a tela\n pygame.display.update()\n if timer == 0:\n sair = True\n pygame.quit()\n\n def update(self):\n\n pass\n\n \n def update_network(self):\n global network_received\n while True:\n data = {'action': 'update', 'id': username}\n network_received = json.loads(self.network.update(json.dumps(data)))\n time.sleep(0.05)\n\nGame()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"554781126","text":"class Interacao:\n def __init__(self):\n self.inicio = \"\\nMenu Inicial\" + \"\\n\" + \"O que você deseja?\"\n self.menu1 = \"0 - Sair\"\n self.menu2 = \"1 - Logar\"\n self.menu3 = \"1 - Cadastrar Funcionário\"\n self.menu5 = \"0 - Sair\"\n self.menu6 = \"1 - Cadastrar Veículos\"\n self.menu7 = \"2 - Identificar Veículos\"\n self.menu8 = \"3 - Remover Veículos\"\n self.menu9 = \"4 - Cadastrar Eventos\"\n self.menu10 = \"5 - Cadastrar Ocorrencias\"\n self.menu11 = \" - Cadastrar Áreas Especiais\"\n self.menu12 = \"6 - Monitorar Estacionamento\"\n self.menu13 = \"7 - Monitorar Eventos\"\n self.menu14 = \"8 - Monitorar Ocorrencias\"\n self.menu111 = \"\\nQual área deseja monitorar?\"\n self.menu15 = \"0 - Todos\"\n self.menu16 = \"1 - Bloco A\"\n self.menu17 = \"2 - Bloco B\"\n self.menu18 = \"3 - Bloco C\"\n self.menu19 = \"4 - Bloco D\"\n self.menu20 = \"5 - Bloco E\"\n self.menu21 = \"6 - Bloco F\"\n self.menu22 = \"7 - Bloco G\"\n self.menu23 = \"8 - Bloco Central\"\n self.menu24 = \"Em qual área?\"\n self.menu25 = \"2 - Dar permissão em Áreas Especiais\"\n self.menu26 = \"100 - Deslogar\"\n self.menu27 = \"1 - Cadastrar Áreas Especiais\"\n self.menu28 = \"2 - Monitorar Estacionamento\"\n self.menu29 = \"3 - Monitorar Eventos\"\n self.menu30 = \"4 - Monitorar Ocorrencias\\n5 - Monitorar Áreas Especiais\\n6 - Remover Áreas Especiais\\\n \\n7 - Cadastrar Eventos\\n8 - Dar Permissão em Áreas Especiais\\n9 - Gerar Relatórios\"\n\n self.menu31 = \"1 - Batidas\"\n self.menu32 = \"2 - Furto ou Assalto\"\n self.menu33 = \"3 - Estacionamento Indevido\"\n self.menu34 = \"4 - Inundação\"\n self.menu35 = \"5 - Dano ao Veículo\"\n self.menu36 = \"6 - Outros\"\n\n self.menu37 = \"1 - Funcionário\"\n self.menu38 = \"2 - Professores\"\n self.menu39 = \"3 - Convidados\"\n self.menu40 = \"4 - Reitores\"\n self.menu41 = \"5 - Outros\"\n\n self.menu42 = \"1 - Estacionamento\"\n self.menu43 = \"2 - Eventos\"\n self.menu44 = \"3 - Ocorrências\"\n self.menu45 = \"4 - Áreas Especias\"\n \n \n \n \n\n\n\n def getInteracao(self):\n temp = self.inicio + \"\\n\" + self.menu1 + \"\\n\" + self.menu2\n return temp\n def getInteracao2(self):\n temp = self.menu5 + \"\\n\" + self.menu6 + \"\\n\" + self.menu7 + \"\\n\" + self.menu8 + \\\n \"\\n\" + self.menu9 + \"\\n\" + self.menu10 + \"\\n\" + self.menu12+ \"\\n\" + self.menu13\\\n + \"\\n\" + self.menu14 + \"\\n\" + self.menu26\n return temp\n def getInteracao3(self):\n temp = self.menu111+\"\\n\" + self.menu15+\"\\n\" + self.menu16+\"\\n\" + self.menu17+\"\\n\" + self.menu18\\\n +\"\\n\" + self.menu19+\"\\n\" + self.menu20+\"\\n\" + self.menu21+\"\\n\" + self.menu22+\"\\n\" + self.menu23\n return temp\n def getInteracao4(self):\n temp = self.menu24+\"\\n\" + self.menu16+\"\\n\" + self.menu17+\"\\n\" + self.menu18\\\n +\"\\n\" + self.menu19+\"\\n\" + self.menu20+\"\\n\" + self.menu21+\"\\n\" + self.menu22+\"\\n\" + self.menu23\n return temp\n def getInteracaoRH(self):\n return self.menu3 + \"\\n\" + self.menu25 + \"\\n\" + self.menu26\n def getInteracaoGestor(self):\n return self.menu27 + \"\\n\" + self.menu28 + \"\\n\" + self.menu29 + \"\\n\" + self.menu30 + \"\\n\" + self.menu26\n def getInteracaoOcorrencias(self):\n return self.menu31 + \"\\n\" + self.menu32 + \"\\n\" + self.menu33 + \"\\n\" + self.menu34 + \"\\n\" + self.menu35 \\\n + \"\\n\" + self.menu36\n def getInteracaoAcesso(self):\n return self.menu37 + \"\\n\" + self.menu38 + \"\\n\" + self.menu39 + \"\\n\" + self.menu40 + \"\\n\" + self.menu41\n def getInteracaoRelatorios(self):\n return self.menu42 + \"\\n\" + self.menu43 + \"\\n\" + self.menu44 + \"\\n\" + self.menu45","sub_path":"MoraisParking - Python/MoraisParking - Python/interacao.py","file_name":"interacao.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"540137880","text":"# frozenset() great for immutable entries. No ability to call add() or insert().\n# frozenset() is Static.\n# Duplicates entries not allow\n\nmy_str = 'Hello'\na = frozenset(my_str)\n# frozenset({'l', 'H', 'e', 'o'})\n\nb = frozenset({my_str})\n# frozenset({'Hello'})\n\nc = {'my_nums': frozenset({1, 2, 3})}\n# c is \n# dict_keys(['my_nums'])\n# dict_values([frozenset({1, 2, 3})])\n\n\nd = {\n 'earth': frozenset({'foo', 'bar', 'alice', 'bob'}),\n 'mars': frozenset({'alien', 'monster', 'creature'})\n }\n# dict with a frozenset as values\nprint(d.get('earth'))\n# frozenset({'bob', 'foo', 'alice', 'bar'})\n","sub_path":"python/sets_frozen.py","file_name":"sets_frozen.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"583806548","text":"def main():\n t = int(input())\n for item in range(t):\n n = int(input())\n a,d = list(), list()\n a = [int (x) for x in input().split()]\n d = [int (x) for x in input().split()]\n a.sort()\n d.sort()\n i,j,c,min = 0,0,0,0\n while(imin):\n min=c\n else:\n c-=1\n j+=1\n print(min)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/Minimum_Platform.py","file_name":"Minimum_Platform.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"506156129","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2017-2019 sunborn23@github.com\n# Copyright (C) 2019 CDMIUB@github.com\n\nimport configparser\nimport datetime\nimport email\nimport email.header\nimport email.mime.text\nimport email.mime.multipart\nimport imaplib\nimport os\nimport re\nimport smtplib\nimport sys\nfrom _socket import gaierror\n\nconfig = None\nconfig_file_path = \"autoresponder.config.ini\"\nincoming_mail_server = None\noutgoing_mail_server = None\nstatistics = {\n \"start_time\": datetime.datetime.now(),\n \"mails_loading_error\": 0,\n \"mails_total\": 0,\n \"mails_processed\": 0,\n \"mails_in_trash\": 0,\n \"mails_wrong_sender\": 0\n}\n\n\ndef run():\n get_config_file_path()\n initialize_configuration()\n connect_to_mail_servers()\n check_folder_names()\n check_local_path()\n mails = fetch_emails()\n for mail in mails:\n process_email(mail)\n log_statistics()\n shutdown(0)\n\n\ndef get_config_file_path():\n if \"--help\" in sys.argv or \"-h\" in sys.argv:\n display_help_text()\n if \"--config-path\" in sys.argv and len(sys.argv) >= 3:\n global config_file_path\n config_file_path = sys.argv[2]\n if not os.path.isfile(config_file_path):\n shutdown_with_error(\"Configuration file not found. Expected it at '\" + config_file_path + \"'.\")\n\n\ndef initialize_configuration():\n try:\n config_file = configparser.ConfigParser()\n config_file.read(config_file_path, encoding=\"UTF-8\")\n global config\n config = {\n 'in.user': cast(config_file[\"login credentials\"][\"mailserver.incoming.username\"], str),\n 'in.pw': cast(config_file[\"login credentials\"][\"mailserver.incoming.password\"], str),\n 'out.user': cast(config_file[\"login credentials\"][\"mailserver.outgoing.username\"], str),\n 'out.pw': cast(config_file[\"login credentials\"][\"mailserver.outgoing.password\"], str),\n 'display.name': cast(config_file[\"login credentials\"][\"mailserver.outgoing.display.name\"], str),\n 'display.mail': cast(config_file[\"login credentials\"][\"mailserver.outgoing.display.mail\"], str),\n 'in.host': cast(config_file[\"mail server settings\"][\"mailserver.incoming.imap.host\"], str),\n 'in.port': cast(config_file[\"mail server settings\"][\"mailserver.incoming.imap.port.ssl\"], str),\n 'out.host': cast(config_file[\"mail server settings\"][\"mailserver.outgoing.smtp.host\"], str),\n 'out.port': cast(config_file[\"mail server settings\"][\"mailserver.outgoing.smtp.port.tls\"], str),\n 'folders.inbox': cast(config_file[\"mail server settings\"][\"mailserver.incoming.folders.inbox.name\"], str),\n 'folders.trash': cast(config_file[\"mail server settings\"][\"mailserver.incoming.folders.trash.name\"], str),\n 'request.from': cast(config_file[\"mail content settings\"][\"mail.request.from\"], str),\n 'reply.subject': cast(config_file[\"mail content settings\"][\"mail.reply.subject\"], str).strip(),\n 'reply.body': cast(config_file[\"mail content settings\"][\"mail.reply.body\"], str).strip(),\n }\n except KeyError as e:\n shutdown_with_error(\"Configuration file is invalid! (Key not found: \" + str(e) + \")\")\n depends = {\n 'nothing': None,\n 'delete': None,\n 'forward': 'post.address',\n 'move': 'post.folder',\n 'download': 'post.path',\n }\n try:\n config['post.action'] = cast(config_file[\"post-reply action settings\"][\"post.action\"], str).strip()\n if config['post.action'] not in depends:\n shutdown_with_error(\"Post-reply action {} is invalid!\".format(config['post.action']))\n except KeyError:\n config['post.action'] = 'nothing'\n \n dkey=depends[config['post.action']]\n if dkey is not None:\n try:\n config[dkey]= cast(config_file[\"post-reply action settings\"][dkey], str).strip()\n except KeyError as e:\n shutdown_with_error(\"Configuration file is invalid! (post.action = \"+config['post.action']+\" reqires \"+dkey)\n\n\ndef connect_to_mail_servers():\n connect_to_imap()\n connect_to_smtp()\n\n\ndef check_folder_names():\n global incoming_mail_server\n global outgoing_mail_server\n (retcode, msg_count) = incoming_mail_server.select(config['folders.inbox'])\n if retcode != \"OK\" or re.match('[^0-9]',msg_count[0].decode()):\n shutdown_with_error(\"Inbox folder does not exist: \" + config['folders.inbox'])\n (retcode, msg_count) = incoming_mail_server.select(config['folders.trash'])\n if retcode != \"OK\" or re.match('[^0-9]',msg_count[0].decode()):\n shutdown_with_error(\"Trash folder does not exist: \" + config['folders.trash'])\n if 'post.folder' not in config: \n return()\n (retcode, msg_count) = incoming_mail_server.select(config['post.folder'])\n if retcode != \"OK\" or re.match('[^0-9]',msg_count[0].decode()):\n shutdown_with_error(\"Destination folder does not exist: \" + config['post.folder'])\n\n\ndef connect_to_imap():\n global incoming_mail_server\n try:\n do_connect_to_imap()\n except gaierror:\n shutdown_with_error(\"IMAP connection failed! Specified host not found.\")\n except imaplib.IMAP4_SSL.error as e:\n shutdown_with_error(\"IMAP login failed! Reason: '\" + cast(e.args[0], str, 'UTF-8') + \"'.\")\n except Exception as e:\n shutdown_with_error(\"IMAP connection/login failed! Reason: '\" + cast(e, str) + \"'.\")\n\n\ndef do_connect_to_imap():\n global incoming_mail_server\n incoming_mail_server = imaplib.IMAP4_SSL(config['in.host'], config['in.port'])\n (retcode, capabilities) = incoming_mail_server.login(config['in.user'], config['in.pw'])\n if retcode != \"OK\":\n shutdown_with_error(\"IMAP login failed! Return code: '\" + cast(retcode, str) + \"'.\")\n\n\ndef connect_to_smtp():\n global outgoing_mail_server\n try:\n do_connect_to_smtp()\n except gaierror:\n shutdown_with_error(\"SMTP connection failed! Specified host not found.\")\n except smtplib.SMTPAuthenticationError as e:\n shutdown_with_error(\"SMTP login failed! Reason: '\" + cast(e.smtp_error, str, 'UTF-8') + \"'.\")\n except Exception as e:\n shutdown_with_error(\"SMTP connection/login failed! Reason: '\" + cast(e, str) + \"'.\")\n\n\ndef do_connect_to_smtp():\n global outgoing_mail_server\n outgoing_mail_server = smtplib.SMTP(config['out.host'], config['out.port'])\n outgoing_mail_server.starttls()\n (retcode, capabilities) = outgoing_mail_server.login(config['out.user'], config['out.pw'])\n if not (retcode == 235 or retcode == 250):\n shutdown_with_error(\"SMTP login failed! Return code: '\" + str(retcode) + \"'.\")\n\n\ndef fetch_emails():\n global incoming_mail_server\n global outgoing_mail_server\n # get the message ids from the inbox folder\n incoming_mail_server.select(config['folders.inbox'])\n (retcode, message_indices) = incoming_mail_server.search(None, 'ALL')\n if retcode == 'OK':\n messages = []\n for message_index in message_indices[0].split():\n # get the actual message for the current index\n (retcode, data) = incoming_mail_server.fetch(message_index, '(RFC822)')\n if retcode == 'OK':\n # parse the message into a useful format\n message = email.message_from_string(data[0][1].decode('utf-8'))\n (retcode, data) = incoming_mail_server.fetch(message_index, \"(UID)\")\n if retcode == 'OK':\n mail_uid = parse_uid(cast(data[0], str, 'UTF-8'))\n message['mailserver_email_uid'] = mail_uid\n messages.append(message)\n else:\n statistics['mails_loading_error'] += 1\n log_warning(\"Failed to get UID for email with index '\" + message_index + \"'.\")\n else:\n statistics['mails_loading_error'] += 1\n log_warning(\"Failed to get email with index '\" + message_index + \"'.\")\n statistics['mails_total'] = len(messages)\n return messages\n else:\n return []\n\n\ndef process_email(mail):\n# try:\n mail_from = email.header.decode_header(mail['From'])\n mail_sender = mail_from[-1]\n mail_sender = cast(mail_sender[0], str, 'UTF-8')\n if config['request.from'] in mail_sender or config['request.from'] == '':\n reply_to_email(mail)\n if config['post.action'] == 'delete':\n delete_email(mail)\n elif config['post.action'] == 'forward':\n forward_email(mail)\n elif config['post.action'] == 'move':\n move_email(mail)\n elif config['post.action'] == 'download':\n download_email(mail)\n else:\n pass\n else:\n statistics['mails_wrong_sender'] += 1\n statistics['mails_processed'] += 1\n# except Exception as e:\n# log_warning(\"Unexpected error while processing email: '\" + str(e) + \"'.\")\n\n\ndef reply_to_email(mail):\n global outgoing_mail_server\n try:\n receiver_emails = email.header.decode_header(mail['Reply-To'])\n except TypeError:\n receiver_emails = email.header.decode_header(mail['From'])\n #get actual email adress, in case field entry is in form \"John Doe \" \n for x,e in receiver_emails:\n e = 'utf-8' if e is None else e\n y = x.decode(e) if isinstance(x,bytes) else x\n if '@' in y:\n receiver_email = y\n break\n message = email.mime.text.MIMEText(config['reply.body'])\n message['Subject'] = config['reply.subject']\n message['To'] = receiver_email\n message['From'] = email.utils.formataddr((\n cast(email.header.Header(config['display.name'], 'utf-8'), str), config['display.mail']))\n outgoing_mail_server.sendmail(config['display.mail'], receiver_email, message.as_string())\n\ndef forward_email(mail):\n global outgoing_mail_server\n sender = email.header.decode_header(mail['From'])\n parts = []\n for x,e in sender :\n e = 'utf-8' if e is None else e\n y = x.decode(e) if isinstance(x,bytes) else x\n parts.append(y)\n subject = mail['Subject']\n prefix = '{} (from {})'.format(subject,' '.join(parts)) \n receiver_email = config['post.address']\n message = mail #email.message_from_string(mail.as_string())\n message.replace_header('Subject', prefix)\n message.replace_header(\"To\", receiver_email)\n message.replace_header(\"From\", email.utils.formataddr((\n cast(email.header.Header(config['display.name'], 'utf-8'), str), config['display.mail'])))\n outgoing_mail_server.sendmail(config['display.mail'], receiver_email, message.as_string().encode('utf-8'))\n delete_email(mail)\n\ndef move_email(mail):\n global incoming_mail_server\n mail_uid=mail['mailserver_email_uid']\n retcode,_ = incoming_mail_server.uid('COPY', mail_uid, config['post.folder'])\n if retcode != \"OK\":\n shutdown_with_error(\"Failed moving message to folder: \" + config['post.folder'])\n else:\n delete_email(mail)\n\ndef check_local_path():\n if not 'post.path' in config:\n return()\n path = config['post.path']\n if not os.path.isdir(path):\n shutdown_with_error(\"Local directory does not exist: \"+path)\n if not os.access(path, os.W_OK):\n shutdown_with_error(\"Cannot write to local directory: \"+path)\n \ndef download_email(mail):\n subject = email.header.decode_header(mail['Subject'])\n parts = []\n for x,e in subject :\n e = 'utf-8' if e is None else e\n y = x.decode(e) if isinstance(x,bytes) else x\n parts.append(y)\n short='_'.join(parts[0:min(len(y),5)])\n mail_uid=mail['mailserver_email_uid']\n filename = '{}_{}.txt'.format(mail_uid,short)\n path=os.path.join(config['post.path'],filename)\n with open(path,'wb') as f:\n f.write(mail.as_string().encode('utf-8'))\n delete_email(mail)\n\ndef delete_email(mail):\n global incoming_mail_server\n result = incoming_mail_server.uid('COPY', mail['mailserver_email_uid'], config['folders.trash'])\n if result[0] == \"OK\":\n statistics['mails_in_trash'] += 1\n else:\n log_warning(\"Copying email to trash failed. Reason: \" + str(result))\n incoming_mail_server.uid('STORE', mail['mailserver_email_uid'], '+FLAGS', '(\\Deleted)')\n incoming_mail_server.expunge()\n\n\ndef parse_uid(data):\n pattern_uid = re.compile('\\d+ \\(UID (?P\\d+)\\)')\n match = pattern_uid.match(data)\n return match.group('uid')\n\n\ndef cast(obj, to_type, options=None):\n try:\n if options is None:\n return to_type(obj)\n else:\n return to_type(obj, options)\n except ValueError and TypeError:\n return obj\n\n\ndef shutdown_with_error(message):\n message = \"Error! \" + str(message)\n message += \"\\nCurrent configuration file path: '\" + str(config_file_path) + \"'.\"\n if config is not None:\n message += \"\\nCurrent configuration: \" + str(config)\n print(message)\n shutdown(1)\n\n\ndef log_warning(message):\n print(\"Warning! \" + message)\n\n\ndef log_statistics():\n run_time = datetime.datetime.now() - statistics['start_time']\n total_mails = statistics['mails_total']\n loading_errors = statistics['mails_loading_error']\n wrong_sender_count = statistics['mails_wrong_sender']\n processing_errors = total_mails - statistics['mails_processed']\n moving_errors = statistics['mails_processed'] - statistics['mails_in_trash'] - statistics['mails_wrong_sender']\n total_warnings = loading_errors + processing_errors + moving_errors\n message = \"Executed \"\n message += \"without warnings \" if total_warnings is 0 else \"with \" + str(total_warnings) + \" warnings \"\n message += \"in \" + str(run_time.total_seconds()) + \" seconds. \"\n message += \"Found \" + str(total_mails) + \" emails in inbox\"\n message += \". \" if wrong_sender_count is 0 else \" with \" + str(wrong_sender_count) + \" emails from wrong senders. \"\n message += \"Processed \" + str(statistics['mails_processed']) + \\\n \" emails, replied to \" + str(total_mails - wrong_sender_count) + \" emails. \"\n if total_warnings is not 0:\n message += \"Encountered \" + str(loading_errors) + \" errors while loading emails, \" + \\\n str(processing_errors) + \" errors while processing emails and \" + \\\n str(moving_errors) + \" errors while moving emails to trash.\"\n print(message)\n\n\ndef display_help_text():\n print(\"Options:\")\n print(\"\\t--help: Display this help information\")\n print(\"\\t--config-path : \"\n \"Override path to config file (defaults to same directory as the script is)\")\n exit(0)\n\n\ndef shutdown(error_code):\n if incoming_mail_server is not None:\n try:\n incoming_mail_server.close()\n except Exception:\n pass\n try:\n incoming_mail_server.logout()\n except Exception:\n pass\n if outgoing_mail_server is not None:\n try:\n outgoing_mail_server.quit()\n except Exception:\n pass\n if error_code != 0:\n raise SystemExit\n\n\nrun()\n","sub_path":"run_autoresponder.py","file_name":"run_autoresponder.py","file_ext":"py","file_size_in_byte":15089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"173692468","text":"import numpy as np\nimport numpy.linalg as la\nimport scipy.sparse as spp\n\n\nclass FastDiagonalisationStokesSolver:\n def __init__(\n self,\n grid_size_r,\n grid_size_z,\n dx,\n real_dtype=np.float64,\n bc_type=\"homogenous_neumann_along_z_and_r\",\n ):\n self.dx = dx\n self.grid_size_r = grid_size_r\n self.grid_size_z = grid_size_z\n self.real_dtype = real_dtype\n self.bc_type = bc_type\n self.radial_coord = (\n np.linspace(dx / 2, grid_size_r * dx - dx / 2, grid_size_r)\n .astype(real_dtype)\n .reshape(grid_size_r, 1)\n )\n\n (\n poisson_matrix_z,\n poisson_matrix_r,\n derivative_matrix_r,\n ) = self.construct_fdm_matrices()\n self.apply_boundary_conds_to_poisson_matrices(\n poisson_matrix_z, poisson_matrix_r, derivative_matrix_r\n )\n self.compute_spectral_decomp_of_poisson_matrices(\n poisson_matrix_z, poisson_matrix_r, derivative_matrix_r\n )\n\n # allocate buffer for spectral field manipulation\n self.spectral_field_buffer = np.zeros_like(self.inv_eig_val_matrix)\n\n def construct_fdm_matrices(self):\n \"\"\"\n Construct the finite difference matrices\n \"\"\"\n inv_dx2 = self.real_dtype(1 / self.dx / self.dx)\n inv_2dx = self.real_dtype(1 / 2 / self.dx)\n poisson_matrix_z = inv_dx2 * spp.diags(\n [-1, 2, -1],\n [-1, 0, 1],\n shape=(self.grid_size_z, self.grid_size_z),\n format=\"csr\",\n )\n poisson_matrix_z = poisson_matrix_z.toarray().astype(self.real_dtype)\n poisson_matrix_r = inv_dx2 * spp.diags(\n [-1, 2, -1],\n [-1, 0, 1],\n shape=(self.grid_size_r, self.grid_size_r),\n format=\"csr\",\n )\n poisson_matrix_r = poisson_matrix_r.toarray().astype(self.real_dtype)\n derivative_matrix_r = inv_2dx * spp.diags(\n [1, -1], [-1, 1], shape=(self.grid_size_r, self.grid_size_r), format=\"csr\"\n )\n derivative_matrix_r = derivative_matrix_r.toarray().astype(self.real_dtype)\n derivative_matrix_r[...] = derivative_matrix_r / self.radial_coord\n\n return poisson_matrix_z, poisson_matrix_r, derivative_matrix_r\n\n def apply_boundary_conds_to_poisson_matrices(\n self,\n poisson_matrix_z,\n poisson_matrix_r,\n derivative_matrix_r,\n ):\n \"\"\"\n Apply boundary conditions to matrices\n \"\"\"\n inv_dx2 = self.real_dtype(1 / self.dx / self.dx)\n if self.bc_type == \"homogenous_neumann_along_z_and_r\":\n # neumann at z=0 and r/z=L, but the modification below operates on\n # nodes at z=dx/2 and r/z=L-dx/2, because of the grid shift in sims.\n poisson_matrix_z[0, 0] = inv_dx2\n poisson_matrix_z[-1, -1] = inv_dx2\n poisson_matrix_r[-1, -1] = inv_dx2\n # neumann at R_max\n derivative_matrix_r[-1, -2] = 0\n\n elif self.bc_type == \"homogenous_neumann_along_r_and_periodic_along_z\":\n poisson_matrix_z[0, -1] = poisson_matrix_z[0, 1]\n poisson_matrix_z[-1, 0] = poisson_matrix_z[-1, -2]\n poisson_matrix_r[-1, -1] = inv_dx2\n # neumann at R_max\n derivative_matrix_r[-1, -2] = 0\n\n elif self.bc_type == \"homogenous_dirichlet_along_r_and_periodic_along_z\":\n poisson_matrix_z[0, -1] = poisson_matrix_z[0, 1]\n poisson_matrix_z[-1, 0] = poisson_matrix_z[-1, -2]\n\n def compute_spectral_decomp_of_poisson_matrices(\n self,\n poisson_matrix_z,\n poisson_matrix_r,\n derivative_matrix_r,\n ):\n \"\"\"\n Compute spectral decomposition (eigenvalue and vectors) of the\n Poisson matrices\n \"\"\"\n eig_vals_r, eig_vecs_r = la.eig(poisson_matrix_r - derivative_matrix_r)\n # sort eigenvalues in decreasing order\n idx = eig_vals_r.argsort()[::-1]\n eig_vals_r[...] = eig_vals_r[idx]\n eig_vecs_r[...] = eig_vecs_r[:, idx]\n self.eig_vecs_r = eig_vecs_r\n self.inv_of_eig_vecs_r = la.inv(eig_vecs_r)\n\n eig_vals_z, eig_vecs_z = la.eig(poisson_matrix_z)\n # sort eigenvalues in decreasing order\n idx = eig_vals_z.argsort()[::-1]\n eig_vals_z[...] = eig_vals_z[idx]\n eig_vecs_z[...] = eig_vecs_z[:, idx]\n self.tranpose_of_eig_vecs_z = np.transpose(eig_vecs_z)\n self.tranpose_of_inv_of_eig_vecs_z = np.transpose(la.inv(eig_vecs_z))\n\n eig_val_matrix = np.tile(\n eig_vals_z.reshape(1, self.grid_size_z), reps=(self.grid_size_r, 1)\n ) + np.tile(eig_vals_r.reshape(self.grid_size_r, 1), reps=(1, self.grid_size_z))\n self.inv_eig_val_matrix = self.real_dtype(1) / eig_val_matrix\n\n def solve(self, solution_field, rhs_field):\n \"\"\"\n solves the Stokes stream function pseudo Poisson:\n -d^2 solution_field / dr^2 - d^2 solution_field / dx^2\n + d solution_field / dr / r = rhs_field\n \"\"\"\n # transform to spectral space (\"forward transform\")\n la.multi_dot(\n [\n self.inv_of_eig_vecs_r,\n np.multiply(rhs_field, self.radial_coord),\n self.tranpose_of_inv_of_eig_vecs_z,\n ],\n out=self.spectral_field_buffer,\n )\n\n # convolution (elementwise) in spectral space\n np.multiply(\n self.spectral_field_buffer,\n self.inv_eig_val_matrix,\n out=self.spectral_field_buffer,\n )\n\n # transform to physical space (\"backward transform\")\n solution_field[...] = la.multi_dot(\n [self.eig_vecs_r, self.spectral_field_buffer, self.tranpose_of_eig_vecs_z],\n )\n","sub_path":"pyaxisymflow/kernels/FastDiagonalisationStokesSolver.py","file_name":"FastDiagonalisationStokesSolver.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"274725995","text":"import turtle\n\nt = turtle.Turtle()\nt.color(\"blue\")\nt.fillcolor(\"red\")\n\nvalue = [120, 56, 309, 220, 156, 23, 98]\n\ndef draw():\n for i in value :\n t.begin_fill()\n t.left(90)\n t.fd(i)\n t.right(90)\n t.write(str(i), font = ('Times New Roman', 16, 'bold'))\n t.fd(40)\n t.right(90)\n t.fd(i)\n t.left(90)\n t.end_fill()\n\ndraw()\nturtle.mainloop()","sub_path":"basic/def08_drawGraph.py","file_name":"def08_drawGraph.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"315901735","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\n\nfrom vpmotree.views import *\n\n# Imports related to Djangular API's\n# https://github.com/pyaf/djangular/blob/master/djangular/urls.py\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom django.views.generic import RedirectView\n# End of API Imports\n\nrouter = routers.DefaultRouter()\n# router.register(r'users', UserViewSet)\n\nurlpatterns = (\n url(r'^api/organisations/$', AllTeamsView.as_view()),\n url(r'^api/filtered_organisations/$', FilteredTeamsView.as_view(), name=\"filtered_teams\"),\n url(r'^api/projects/$', AllProjectsView.as_view()),\n url(r'^api/projects/add/$', CreateProjectView.as_view()),\n url(r'^api/projects/(?P.+)/$', UpdateProjectView.as_view()),\n url(r'^api/teams/add/$', CreateTeamView.as_view()),\n url(r'^api/deliverable/add/$', CreateDeliverableView.as_view()),\n\n url(r\"^api/update_project/(?P<_id>.+)/$\", UpdateProjectView.as_view(), name=\"update_project\"),\n\n url(r\"^api/teams_tree/(?P.+)/$\", TeamTreeView.as_view(), name=\"team_tree_view\"),\n url(r\"^api/project_tree/(?P.+)/$\", ProjectTreeView.as_view(), name=\"project_tree_view\"),\n\n url(r'^api/messages/(?P.+)/$', MessageListView.as_view(), name=\"message_list\"),\n\n url(r'^(?P.*\\..*)/$', RedirectView.as_view(url='/static/%(path)s')),\n url(r'^', TemplateView.as_view(template_name='angular/index.html')),\n)","sub_path":"vpmotree/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"555618539","text":"import glob\nimport os\nfrom pathlib import Path\n\nfrom strictdoc.backend.dsl.errors.document_tree_error import DocumentTreeError\nfrom strictdoc.backend.source_file_syntax.reader import (\n SourceFileTraceabilityReader,\n)\nfrom strictdoc.cli.cli_arg_parser import ExportCommandConfig\nfrom strictdoc.core.document_finder import DocumentFinder\nfrom strictdoc.core.finders.source_files_finder import (\n SourceFilesFinder,\n SourceFile,\n)\nfrom strictdoc.core.source_tree import SourceTree\nfrom strictdoc.core.traceability_index import TraceabilityIndex\nfrom strictdoc.core.traceability_index_builder import TraceabilityIndexBuilder\nfrom strictdoc.export.excel.excel_generator import ExcelGenerator\nfrom strictdoc.export.html.html_generator import HTMLGenerator\nfrom strictdoc.export.rst.document_rst_generator import DocumentRSTGenerator\nfrom strictdoc.helpers.file_modification_time import get_file_modification_time\nfrom strictdoc.helpers.timing import timing_decorator\n\n\nclass ExportAction:\n @staticmethod\n @timing_decorator(\"Export\")\n def export(config: ExportCommandConfig, parallelizer):\n assert parallelizer\n cwd = os.getcwd()\n strict_own_files = glob.iglob(\n \"{}/strictdoc/**/*\".format(config.strictdoc_root_path),\n recursive=True,\n )\n strict_own_files = [\n f\n for f in strict_own_files\n if f.endswith(\".html\") or f.endswith(\".py\")\n ]\n latest_strictdoc_own_file = max(strict_own_files, key=os.path.getctime)\n strictdoc_last_update = get_file_modification_time(\n latest_strictdoc_own_file\n )\n\n assert isinstance(config.formats, list)\n\n path_to_single_file_or_doc_root = config.input_paths\n if isinstance(path_to_single_file_or_doc_root, str):\n path_to_single_file_or_doc_root = [config.input_paths]\n output_dir = config.output_dir if config.output_dir else \"output\"\n\n if not os.path.isabs(output_dir):\n output_dir = os.path.join(cwd, output_dir)\n\n output_html_root = \"{}/html\".format(output_dir)\n\n document_tree, asset_dirs = DocumentFinder.find_sdoc_content(\n path_to_single_file_or_doc_root, output_html_root, parallelizer\n )\n\n try:\n traceability_index: TraceabilityIndex = (\n TraceabilityIndexBuilder.create(document_tree)\n )\n except DocumentTreeError as exc:\n print(exc.to_print_message())\n exit(1)\n\n if config.experimental_enable_file_traceability:\n source_tree: SourceTree = SourceFilesFinder.find_source_files(\n output_html_root, document_tree\n )\n source_files = source_tree.source_files\n source_file: SourceFile\n for source_file in source_files:\n traceability_reader = SourceFileTraceabilityReader()\n traceability_info = traceability_reader.read_from_file(\n source_file.full_path\n )\n if traceability_info:\n traceability_index.attach_traceability_info(\n source_file.in_doctree_source_file_rel_path,\n traceability_info,\n )\n document_tree.attach_source_tree(source_tree)\n\n if \"html\" in config.formats or \"html-standalone\" in config.formats:\n Path(output_html_root).mkdir(parents=True, exist_ok=True)\n HTMLGenerator.export_tree(\n config,\n document_tree,\n traceability_index,\n output_html_root,\n strictdoc_last_update,\n asset_dirs,\n parallelizer,\n )\n\n if \"rst\" in config.formats:\n output_rst_root = \"{}/rst\".format(output_dir)\n Path(output_rst_root).mkdir(parents=True, exist_ok=True)\n DocumentRSTGenerator.export_tree(\n document_tree, traceability_index, output_rst_root\n )\n\n if \"excel\" in config.formats:\n output_excel_root = \"{}/excel\".format(output_dir)\n ExcelGenerator.export_tree(\n document_tree,\n traceability_index,\n output_excel_root,\n config.fields,\n )\n","sub_path":"strictdoc/core/actions/export_action.py","file_name":"export_action.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"368637152","text":"import json\nimport pytest\nfrom jsonschema import FormatChecker, Draft4Validator, ValidationError\n\nfrom app import app\n\n\nfile_content = 'Welcome,\\r\\n\\r\\nyou are connected to an FTP or SFTP server used for testing purposes by Rebex FTP/SSL' \\\n ' or Rebex SFTP sample code.\\r\\nOnly read access is allowed and the FTP download speed is limited to ' \\\n '16KBps.\\r\\n\\r\\nFor infomation about Rebex FTP/SSL, Rebex SFTP and other Rebex .NET components, please' \\\n ' visit our website at http://www.rebex.net/\\r\\n\\r\\nFor feedback and support, contact ' \\\n 'support@rebex.net\\r\\n\\r\\nThanks!\\r\\n'\nschema_200 = {\n 'type': 'object',\n 'properties': {\n 'ip': {'type': 'string', 'format': 'ipv4', 'enum': ['195.144.107.198']},\n 'hostname': {'type': 'string', 'format': 'hostname', 'enum': ['test.rebex.net']},\n 'path': {'type': 'string', 'enum': ['/readme.txt']},\n 'content': {'type': 'string', 'enum': [file_content]}\n },\n 'additionalProperties': False,\n 'required': ['ip', 'hostname', 'path', 'content']\n}\n\n\n@pytest.fixture\ndef client(request):\n return app.test_client()\n\n\ndef test_successful(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=195.144.107.198&path=/readme.txt')\n response_json = json.loads(response.data)\n assert response.status_code == 200\n validator = Draft4Validator(schema_200, format_checker=FormatChecker(('ipv4', 'hostname')))\n validation_errors = [error.message for error in validator.iter_errors(response_json)]\n if validation_errors:\n raise ValidationError(validation_errors)\n\n\ndef test_unknown_ip(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=127.0.0.1&path=/readme.txt')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': 'Specified ip address is not registered in service!'}\n\n\ndef test_incorrect_ip(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=a.b.c.d&path=/readme.txt')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': [\"'a.b.c.d' is not a 'ipv4'\"]}\n\n\ndef test_ip_is_absent(client):\n response = client.get('/sftp/api/v1.0/get-file?path=/readme.txt')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': [\"'ip' is a required property\"]}\n\n\ndef test_path_is_absent(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=195.144.107.198')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': [\"'path' is a required property\"]}\n\n\ndef test_path_is_empty(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=195.144.107.198&path=')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': [\"'' is too short\"]}\n\n\ndef test_path_is_not_exists(client):\n response = client.get('/sftp/api/v1.0/get-file?ip=195.144.107.198&path=/unknown.txt')\n response_json = json.loads(response.data)\n assert response.status_code == 404\n assert response_json == {'error': 'File not found!'}\n\n\ndef test_incorrect_request(client):\n response = client.get('/sftp/api/v1.0/get-file')\n response_json = json.loads(response.data)\n assert response.status_code == 400\n assert response_json == {'error': [\"'ip' is a required property\", \"'path' is a required property\"]}\n\n\ndef test_unexpected_post(client):\n response = client.post('/sftp/api/v1.0/get-file?ip=195.144.107.198&path=/readme.txt')\n assert response.status_code == 405\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"300475776","text":"from django.urls import path\nfrom banner import views\n\napp_name = 'banner'\n\nurlpatterns = [\n path('save/', views.save_banner, name='save'),\n path('show/', views.show_banner, name='show'),\n path('edit/', views.edit_banner, name='edit'),\n]\n","sub_path":"banner/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"26157043","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom .forms import DebitEntryForm, TransactionsForms, SecondPageForm, CreditEntryForm, OverviewForm\nfrom .models import CreditEntry, SecondPage, DebitEntry, Overview\nfrom random import randrange\nfrom django.contrib import messages\n\ncompanyIdDict = {'2909': ['Verizon Wireless', '141 Industrial Parkway', 'Branchburg', '1720010'], '1644': ['ATT', 'New York City', 'New York', '70817081'], '60':['Pierre', '23 WestVille Avenue','Caldwell', '70817081']}\n\nlastSecondPage = SecondPage.objects.last() \nlastDebitEntry = DebitEntry.objects.last()\nlastCreditEntry = CreditEntry.objects.last()\n\ncarrierNumber = lastSecondPage.accountBottom\nfiscal = lastSecondPage.postDate.year\ncompCode = lastSecondPage.companyCode\ncurrency = lastSecondPage.currency\nglAcc = lastDebitEntry.accountBottom\ndifferenceDebitCredit = lastDebitEntry.amount - lastCreditEntry.amount\n\ntry:\n carrierDetails = companyIdDict[carrierNumber]\nexcept KeyError:\n carrierDetails = \"carrier not found for Account Number {accNum} that was entered in last page. Go back to correct it.\".format(accNum=carrierNumber)\ncompanyInfo = [carrierNumber, carrierDetails]\n\ndef docNumGen():\n return '1600000' + str(randrange(0,999))\n\ndef landPage(request):\n if request.method == 'POST':\n form = TransactionsForms(request.POST)\n if form.is_valid():\n transactionCode = form.cleaned_data['transactionCode']\n print(transactionCode)\n if transactionCode.lower() == 'vf04':\n return redirect(secondPage)\n else:\n form = TransactionsForms()\n return render(request, \"main/landingPage.html\", {'form': form})\n\ndef secondPage(request):\n try:\n if request.session['docNum']:\n documentNumber = request.session['docNum']\n print(documentNumber)\n messages.add_message(request, 20, 'Document Number is {docNum}'.format(docNum=documentNumber))\n print(request.session.get_expiry_age())\n except KeyError:\n pass\n if request.method == 'POST':\n form = SecondPageForm(request.POST)\n if form.is_valid():\n secondPageData = form.save()\n return redirect(debitEntry)\n else: \n form = SecondPageForm()\n return render(request, 'main/secondPage.html', {'form': form})\n\ndef debitEntry(request):\n lastSecondPage = SecondPage.objects.last() \n carrierNumber = lastSecondPage.accountBottom\n try:\n carrierDetails = companyIdDict[carrierNumber]\n except KeyError:\n carrierDetails = \"carrier not found for Account Number {accNum} that was entered in last page. Go back to correct it.\".format(accNum=carrierNumber)\n companyInfo = [carrierNumber, carrierDetails]\n if request.method == 'POST':\n form = DebitEntryForm(request.POST)\n if form.is_valid():\n debitEntryData = form.save()\n return redirect(creditEntry)\n else: \n form = DebitEntryForm()\n return render(request, 'main/debitEntry.html', {'form': form, 'companyInfo': companyInfo, 'lastSecondPage': lastSecondPage})\n\ndef creditEntry(request):\n lastSecondPage = SecondPage.objects.last() \n lastDebitEntry = DebitEntry.objects.last() \n compCode = lastSecondPage.companyCode\n currency = lastSecondPage.currency\n glAcc = lastDebitEntry.accountBottom\n listForHtml = [compCode, glAcc, currency]\n if request.method == 'POST':\n form = CreditEntryForm(request.POST)\n print(listForHtml[2])\n if form.is_valid():\n creditEntrydata = form.save()\n return redirect(overview)\n else: \n form = CreditEntryForm()\n print(listForHtml[2])\n return render(request, 'main/creditEntry.html', {'listForHtml': listForHtml, 'form': form})\n\ndef overview(request):\n lastSecondPage = SecondPage.objects.last() \n lastDebitEntry = DebitEntry.objects.last()\n lastCreditEntry = CreditEntry.objects.last()\n fiscal = lastSecondPage.postDate.year\n try:\n carrierDetails = companyIdDict[carrierNumber]\n except KeyError:\n carrierDetails = \"carrier not found for Account Number {accNum} that was entered in last page. Go back to correct it.\".format(accNum=carrierNumber)\n companyInfo = [carrierNumber, carrierDetails]\n differenceDebitCredit = lastDebitEntry.amount - lastCreditEntry.amount\n if request.method == 'POST':\n form = OverviewForm(request.POST)\n if form.is_valid():\n overviewData = form.save()\n cleanedForm = form.cleaned_data\n lastSecondPage.reference = cleanedForm['reference']\n lastCreditEntry.trdgPartBA = cleanedForm['trdgPartBA']\n lastSecondPage.docHeader = cleanedForm['docHeader']\n lastSecondPage.save()\n lastCreditEntry.save()\n request.session['docNum'] = docNumGen()\n return redirect(secondPage)\n else: \n form = OverviewForm()\n return render(request, 'main/overview.html', {'lastSecondPage': lastSecondPage, 'lastDebitEntry': lastDebitEntry, 'lastCreditEntry': lastCreditEntry, 'fiscal': fiscal, 'form': form, 'companyInfo': companyInfo, 'differenceDebitCredit': differenceDebitCredit})\n\ndef docHeaderPage(request):\n return render(request, 'main/docHeaderPage.html')\n\ndef fastDataEntry(request):\n return render(request, 'main/fastDataEntry.html')\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425438894","text":"import backFunc\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.screenmanager import Screen\nfrom kivy.uix.button import ButtonBehavior\nfrom kivy.uix.image import Image\nimport subprocess\nimport mysql.connector\nfrom threading import Thread\nfrom kivy.uix.dropdown import DropDown\nfrom kivy.uix.boxlayout import BoxLayout\n\n\nclass HomeScreen(Screen):\n pass\n\n\nclass SchoolIdCreate(Screen):\n pass\n\n\nclass SchoolIdCreate2(Screen):\n pass\n\n\nclass SchoolIdCreate3(Screen):\n pass\n\n\nclass TeacherIdCheck(Screen):\n pass\n\n\nclass TeacherIdCreate(Screen):\n pass\n\n\nclass IndexScreen(Screen):\n pass\n\n\nclass DisplayTimeTable(Screen):\n pass\n\n\n# class for functions\nclass ImageButton(ButtonBehavior, Image):\n pass\n\n\nGUI = Builder.load_file('main.kv')\n\n\nclass MainApp(App):\n def build(self):\n return GUI\n\n def change_screen(self, screen_name):\n global screen_manager\n screen_manager = self.root.ids['screen_manager']\n screen_manager.current = screen_name\n\n def check_school_id(self):\n MainApp.change_screen(self, 'HomeScreen')\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n school_pa = self.root.ids['HomeScreen'].ids[\"school_pa\"].text\n school_check = backFunc.school_id_check(school_id, school_pa)\n if school_check == True:\n MainApp.change_screen(self, \"TeacherIdCheck\")\n else:\n self.root.ids['HomeScreen'].ids[\"school_id\"].text = \"\"\n self.root.ids['HomeScreen'].ids[\"school_pa\"].text = \"\"\n\n def lower_grade(self, grade_recived_lower):\n global school_lower_grade\n school_lower_grade = grade_recived_lower\n print(school_lower_grade)\n\n def upper_grade(self, grade_recived_upper):\n global school_upper_grade\n school_upper_grade = grade_recived_upper\n print(school_upper_grade)\n\n def School_id_create(self):\n school_id = self.root.ids['SchoolIdCreate'].ids[\"school_id\"].text\n school_pa = self.root.ids['SchoolIdCreate'].ids[\"school_pa\"].text\n if self.root.ids['SchoolIdCreate'].ids[\"school_periods_day\"].text in \"1234567890\":\n school_periods_day = self.root.ids['SchoolIdCreate'].ids[\"school_periods_day\"].text\n try:\n backFunc.school_id_create1(school_id, school_pa, school_periods_day, school_lower_grade, school_upper_grade)\n MainApp.School_id_create2(self)\n except NameError:\n self.root.ids['SchoolIdCreate'].ids[\"submit\"].text = \"Form Incomplete\"\n except:\n self.root.ids['SchoolIdCreate'].ids[\"school_id\"].text = \"\"\n self.root.ids['SchoolIdCreate'].ids[\"school_id\"].hint_text = \"This id is taken, please try another one\"\n else:\n self.root.ids['SchoolIdCreate'].ids[\"school_periods_day\"].text = \"\"\n self.root.ids['SchoolIdCreate'].ids[\"school_periods_day\"].hint_text = \"Enter a Numeric Value\"\n\n def School_id_create2(self):\n MainApp.change_screen(self, \"SchoolIdCreate2\")\n global grades_school\n grades_school = []\n for i in range(int(school_lower_grade), int(school_upper_grade) + 1):\n grades_school.append(i)\n MainApp.count = 0\n MainApp.School_id_create3(self)\n\n count = 0\n\n # rotate through each grade in the school asking for the number of sections\n def School_id_create3(self):\n if MainApp.count < len(grades_school):\n grade = grades_school[MainApp.count]\n print(grade)\n self.root.ids['SchoolIdCreate2'].ids[\"label_message\"].text = f\"How many sections does grade {grade} has\"\n MainApp.change_screen(self, \"SchoolIdCreate2\")\n global sections_in_class\n sections_in_class = self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].text\n MainApp.count += 1\n MainApp.count2 = 0\n else:\n if sections_in_class in \"1234567890\":\n MainApp.check_school_id(self)\n else:\n self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].text = \"\"\n self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].hint_text = \"Enter a Numeric Value\"\n\n count2 = 0\n\n def sub1(self, subject):\n global subject1\n subject1 = subject\n\n def sub2(self, subject):\n global subject2\n subject2 = subject\n\n def sub3(self, subject):\n global subject3\n subject3 = subject\n\n def sub4(self, subject):\n global subject4\n subject4 = subject\n\n def sub5(self, subject):\n global subject5\n subject5 = subject\n\n def sub6(self, subject):\n global subject6\n subject6 = subject\n\n def sub7(self, subject):\n global subject7\n subject7 = subject\n\n def sub8(self, subject):\n global subject8\n subject8 = subject\n\n def sub9(self, subject):\n global subject9\n subject9 = subject\n\n def sub10(self, subject):\n global subject10\n subject10 = subject\n\n def School_id_create4(self):\n if self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].text in \"1234567890\":\n if MainApp.count2 < int(self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].text):\n self.root.ids['SchoolIdCreate3'].ids[\"grade_name\"].text = str(\n MainApp.count + school_lower_grade - 1) + chr(\n MainApp.count2 + 65)\n MainApp.change_screen(self, \"SchoolIdCreate3\")\n else:\n MainApp.School_id_create3(self)\n else:\n self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].text = \"\"\n self.root.ids['SchoolIdCreate2'].ids[\"number_sections\"].hint_text = \"Enter a Numeric Value\"\n\n def subject_assigning(self):\n school_id = self.root.ids['SchoolIdCreate'].ids[\"school_id\"].text\n try:\n subject_list = (subject1, subject2, subject3, subject4, subject5, subject6, subject7, subject8, subject9, subject10)\n backFunc.school_id_create2(school_id, chr(MainApp.count2 + 65), str(MainApp.count + school_lower_grade - 1), subject1, subject2, subject3, subject4, subject5, subject6, subject7, subject8, subject9, subject10)\n MainApp.count2 += 1\n MainApp.School_id_create4(self)\n except NameError:\n self.root.ids['SchoolIdCreate3'].ids[\"submit\"].text = \"Form Incomplete\"\n\n def check_teacher_id(self):\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n teacher_id = self.root.ids['TeacherIdCheck'].ids['teacher_id'].text\n teacher_pa = self.root.ids['TeacherIdCheck'].ids['teacher_pa'].text\n teacher_check = backFunc.teacher_id_check(school_id, teacher_id, teacher_pa)\n if teacher_check == True:\n self.root.ids['IndexScreen'].ids['username'].text = self.root.ids['TeacherIdCheck'].ids['teacher_id'].text\n MainApp.change_screen(self, \"IndexScreen\")\n else:\n self.root.ids['TeacherIdCheck'].ids[\"teacher_id\"].text = \"\"\n self.root.ids['TeacherIdCheck'].ids[\"teacher_pa\"].text = \"\"\n\n def subject_of_teacher(self, subject_recived):\n global subject_teacher\n subject_teacher = subject_recived\n print(subject_teacher)\n\n def type_of_teacher(self, type_recived):\n global type_teacher\n type_teacher = type_recived\n print(type_teacher)\n\n def grade_of_teacher(self, grade_recived):\n global grade_teacher\n grade_teacher = grade_recived\n print(grade_teacher)\n\n def grade_of_teacher2(self, grade_recived2):\n global grade_teacher2\n grade_teacher2 = grade_recived2\n print(grade_teacher2)\n\n def teacher_id_create(self):\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n teacher_id = self.root.ids['TeacherIdCreate'].ids[\"teacher_id\"].text\n teacher_pa = self.root.ids['TeacherIdCreate'].ids[\"teacher_pa\"].text\n try:\n backFunc.teacher_id_create(school_id, teacher_id, teacher_pa, subject_teacher, type_teacher, grade_teacher,\n grade_teacher2)\n self.root.ids['TeacherIdCreate'].ids[\"teacher_id\"].text = \"\"\n self.root.ids['TeacherIdCreate'].ids[\"teacher_pa\"].text = \"\"\n MainApp.check_teacher_id(self)\n MainApp.change_screen(self, \"TeacherIdCheck\")\n except NameError:\n self.root.ids['TeacherIdCreate'].ids[\"submit\"].text = \"Form Incomplete\"\n except:\n teacher_id = self.root.ids['TeacherIdCreate'].ids[\"teacher_id\"].text = \"\"\n teacher_id = self.root.ids['TeacherIdCreate'].ids[\n \"teacher_id\"].hint_text = \"This id is taken, please try another one\"\n\n def index_create_time_table(self):\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n teacher_id = self.root.ids['TeacherIdCheck'].ids['teacher_id'].text\n mydb = mysql.connector.connect(username=\"doadmin\",password=\"aiyherpvx760tdng\",host=\"db-mysql-blr1-16639-do-user-7263481-0.a.db.ondigitalocean.com\",port=\"25060\",database=school_id)\n mycursor = mydb.cursor()\n mycursor.execute(f\"SELECT teacher_type FROM teacher_general_record WHERE teacher_id = '{teacher_id}'\")\n for i in mycursor:\n teacher_type = i[0]\n if teacher_type == \"teacher\":\n self.root.ids[\"IndexScreen\"].ids[\"create_button\"].text = \"You don\\'t have the write to create a time table\"\n else:\n try:\n backFunc.table_droper(school_id)\n backFunc.teacher_assign(school_id)\n backFunc.create_tables_for_classes(school_id)\n backFunc.create_time_table(school_id)\n except:\n self.root.ids[\"IndexScreen\"].ids[\"create_button\"].text = \"insufficient teachers\"\n\n def index_update_time_table(self):\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n teacher_id = self.root.ids['TeacherIdCheck'].ids['teacher_id'].text\n mydb = mysql.connector.connect(username=\"doadmin\",password=\"aiyherpvx760tdng\",host=\"db-mysql-blr1-16639-do-user-7263481-0.a.db.ondigitalocean.com\",port=\"25060\",database=school_id)\n mycursor = mydb.cursor()\n mycursor.execute(f\"SELECT teacher_type FROM teacher_general_record WHERE teacher_id = '{teacher_id}'\")\n for i in mycursor:\n teacher_type = i[0]\n if teacher_type == \"teacher\":\n self.root.ids[\"IndexScreen\"].ids[\n \"update_button\"].text = \"You don\\'t have the write to update the time table\"\n else:\n try:\n backFunc.create_time_table(school_id)\n except:\n self.root.ids[\"IndexScreen\"].ids[\"update_button\"].text = \"First click the create time table button\"\n\n def display_time_table(self):\n school_id = self.root.ids['HomeScreen'].ids[\"school_id\"].text\n teacher_id = self.root.ids['TeacherIdCheck'].ids[\"teacher_id\"].text\n\n mydb = mysql.connector.connect(\n username=\"doadmin\",\n password=\"aiyherpvx760tdng\",\n host=\"db-mysql-blr1-16639-do-user-7263481-0.a.db.ondigitalocean.com\",\n port=\"25060\",\n database=school_id)\n mycursor = mydb.cursor()\n\n mycursor.execute(f\"SELECT * FROM {teacher_id}\")\n for i in mycursor:\n day = str(i[0])\n self.root.ids['DisplayTimeTable'].ids[f\"p{day}\"].text = f\"Period {str(i[0])}\"\n self.root.ids['DisplayTimeTable'].ids[f\"p{day}\"].color = 0, 0, 0, 1\n self.root.ids['DisplayTimeTable'].ids[f\"mon{day}\"].text = i[1]\n self.root.ids['DisplayTimeTable'].ids[f\"mon{day}\"].color = 0, 0, 0, 1\n self.root.ids['DisplayTimeTable'].ids[f\"tue{day}\"].text = i[2]\n self.root.ids['DisplayTimeTable'].ids[f\"tue{day}\"].color = 0, 0, 0, 1\n self.root.ids['DisplayTimeTable'].ids[f\"wen{day}\"].text = i[3]\n self.root.ids['DisplayTimeTable'].ids[f\"wen{day}\"].color = 0, 0, 0, 1\n self.root.ids['DisplayTimeTable'].ids[f\"thr{day}\"].text = i[4]\n self.root.ids['DisplayTimeTable'].ids[f\"thr{day}\"].color = 0, 0, 0, 1\n self.root.ids['DisplayTimeTable'].ids[f\"fri{day}\"].text = i[5]\n self.root.ids['DisplayTimeTable'].ids[f\"fri{day}\"].color = 0, 0, 0, 1\n\n MainApp.change_screen(self, \"DisplayTimeTable\")\n\n\nMainApp().run()\n\n# find a place for this thing\n# while True:\n# Thread(target = MainApp().chatRecive(\"Left\")).start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399699029","text":"import torch.nn as nn \nimport torch\n\n\nclass one_conv(nn.Module):\n def __init__(self, inchanels, growth_rate, kernel_size = 3):\n super(one_conv, self).__init__()\n self.conv = nn.Conv2d(inchanels, growth_rate, kernel_size=kernel_size, padding=kernel_size>>1, stride=1)\n self.relu = nn.ReLU()\n def forward(self, x):\n output = self.relu(self.conv(x))\n return torch.cat((x, output), 1)\n\nclass RDB(nn.Module):\n def __init__(self, G0, C, G, kernel_size = 3):\n super(RDB, self).__init__()\n convs = []\n for i in range(C):\n convs.append(one_conv(G0+i*G, G))\n self.conv = nn.Sequential(*convs)\n #local_feature_fusion\n self.LFF = nn.Conv2d(G0+C*G, G0, kernel_size=1, padding=0, stride=1)\n def forward(self, x):\n out = self.conv(x)\n lff = self.LFF(out)\n #local residual learning\n return lff + x\n\nclass Network(nn.Module):\n def __init__(self):\n super(Network, self).__init__()\n '''\n D: RDB number\n C: the number of conv layer in RDB\n G: the growth rate\n G0:local and global feature fusion layers\n '''\n self.D = 20\n self.C = 6\n self.G = 32\n self.G0 = 64\n kernel_size = 3\n\n # shallow feature extraction \n self.SFE = nn.Conv2d(3, self.G0, kernel_size=kernel_size, padding=kernel_size>>1, stride=1)\n # feature extraction \n self.FE = nn.Conv2d(self.G0, self.G0, kernel_size=kernel_size, padding=kernel_size>>1, stride=1)\n # RDB for paper we have D RDB block\n self.RDBS = nn.ModuleList()\n for d in range(self.D):\n self.RDBS.append(RDB(self.G0, self.C, self.G, kernel_size))\n # Global feature fusion\n self.GFF = nn.Sequential(\n nn.Conv2d(self.D*self.G0, self.G0, kernel_size=1, padding=0 , stride=1), \n nn.Conv2d(self.G0, self.G0, kernel_size=kernel_size, padding=kernel_size>>1, stride=1), \n )\n # feature reconstruction\n self.FR = nn.Conv2d(self.G0, 3, kernel_size=kernel_size, padding=kernel_size>>1, stride=1)\n #init\n for para in self.modules():\n if isinstance(para, nn.Conv2d):\n nn.init.kaiming_normal_(para.weight)\n if para.bias is not None:\n para.bias.data.zero_()\n\n def forward(self, x):\n f_1 = self.SFE(x)\n out = self.FE(f_1)\n RDB_outs = []\n for i in range(self.D):\n out = self.RDBS[i](out)\n RDB_outs.append(out)\n out = torch.cat(RDB_outs, 1)\n out = self.GFF(out)\n out = f_1 + out \n\n out = self.FR(out)\n out = x + out\n return out\n","sub_path":"model/rdnp/netmodel.py","file_name":"netmodel.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"266266797","text":"# 반복문\n# for -> 지정된 횟수, 정해진 횟수 -> 시퀀스 데이터 타입 연동\n# while -> 0 ~ 무한대 -> 언제 끝날지 모를때\n\na = [1,2,3,4,5]\nwhile len(a) > 0:\n print(a.pop())\n\n\na = [1,2,3,4,5]\n# 로직은 동일 => 조건문을 간결하게 구현하시오\n# 멤버가 모두 비워지면 => [] => 조건문에 넣으면 => False 되니까\n# 멤버가 있는지 없는지 => a만 넣어두면 조건문에서 체크가 된다\nwhile a:\n print(a.pop())\n\n# 반복문이 정상적으로 잘 끝났음을 알게하는 표현\n\n# a = [1,2,3,4,5]\n# while a:\n# print(a.pop())\n# if len(a) == 2:\n# break\n\n# else:\n# print('반복문 정상적으로 끝남')","sub_path":"basic/py9.py","file_name":"py9.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"309060526","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom sqlalchemy import func\nfrom sqlalchemy import sql\n\nfrom placement.db.sqlalchemy import models\nfrom placement import db_api\n\n\nclass Usage(object):\n\n def __init__(self, resource_class=None, usage=0):\n self.resource_class = resource_class\n self.usage = int(usage)\n\n\ndef get_all_by_resource_provider_uuid(context, rp_uuid):\n \"\"\"Get a list of Usage objects filtered by one resource provider.\"\"\"\n usage_list = _get_all_by_resource_provider_uuid(context, rp_uuid)\n return [Usage(**db_item) for db_item in usage_list]\n\n\ndef get_all_by_project_user(context, project_id, user_id=None):\n \"\"\"Get a list of Usage objects filtered by project and (optional) user.\"\"\"\n usage_list = _get_all_by_project_user(context, project_id,\n user_id=user_id)\n return [Usage(**db_item) for db_item in usage_list]\n\n\n@db_api.placement_context_manager.reader\ndef _get_all_by_resource_provider_uuid(context, rp_uuid):\n query = (context.session.query(models.Inventory.resource_class_id,\n func.coalesce(func.sum(models.Allocation.used), 0))\n .join(models.ResourceProvider,\n models.Inventory.resource_provider_id ==\n models.ResourceProvider.id)\n .outerjoin(models.Allocation,\n sql.and_(models.Inventory.resource_provider_id ==\n models.Allocation.resource_provider_id,\n models.Inventory.resource_class_id ==\n models.Allocation.resource_class_id))\n .filter(models.ResourceProvider.uuid == rp_uuid)\n .group_by(models.Inventory.resource_class_id))\n result = [dict(resource_class=context.rc_cache.string_from_id(item[0]),\n usage=item[1])\n for item in query.all()]\n return result\n\n\n@db_api.placement_context_manager.reader\ndef _get_all_by_project_user(context, project_id, user_id=None):\n query = (context.session.query(models.Allocation.resource_class_id,\n func.coalesce(func.sum(models.Allocation.used), 0))\n .join(models.Consumer,\n models.Allocation.consumer_id == models.Consumer.uuid)\n .join(models.Project,\n models.Consumer.project_id == models.Project.id)\n .filter(models.Project.external_id == project_id))\n if user_id:\n query = query.join(models.User,\n models.Consumer.user_id == models.User.id)\n query = query.filter(models.User.external_id == user_id)\n query = query.group_by(models.Allocation.resource_class_id)\n result = [dict(resource_class=context.rc_cache.string_from_id(item[0]),\n usage=item[1])\n for item in query.all()]\n return result\n","sub_path":"placement/objects/usage.py","file_name":"usage.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"18933372","text":"import numpy as np\nfrom sklearn.manifold import MDS\nfrom sklearn.metrics import euclidean_distances\nimport scipy\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nimport os\nfrom matplotlib.image import BboxImage\nfrom matplotlib.transforms import Bbox, TransformedBbox\nfrom pycocotools.coco import COCO\nfrom annotation_scatter import annotate_scatter\nimport shutil\n\ndef getImage(path):\n return OffsetImage(plt.imread(path, 0), zoom=0.1)\n\n\n\n\n\n# Generate a list of tags\n# possible_tags = pickle.load(open('possible_tags.pkl', 'rb'))\n\n# tags = []\n# logging.info('Testing: get embedding of all possible tags')\n# for tag in possible_tags:\n# tags.append(tag)\n\n\n\nfrom itertools import zip_longest\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)\n\n\nf = open('/home/ubuntu/CCA-images-text/main/i2t_results.txt', 'r')\n# Array of top 5 tags for each image\nX = [np.array([line1, line2.replace(\" \", \"\").split(',')], dtype=object) for line1, line2 in grouper(2, f)]\n\n# Generate annotation tag for each image\n# ann_dict = {'kitchen_counter': ['kitchen', 'counter'], 'kitchen_refrigerator': ['kitchen', 'refrigerator']}\n# ann_dict = {'kitchen_counter': ['kitchen', 'counter']}\n# ann_dict = {'kitchen_refrigerator': ['kitchen', 'refrigerator']}\n# ann_dict = {'kitchen': ['kitchen'], 'bedroom': ['bedroom'], 'bathroom': ['bathroom'], 'living': ['living']}\n# ann_dict = {'kitchen': ['kitchen', 'island']}\n# ann_dict = {'living': ['living', 'fireplace']}\nann_dict = {'bathroom': ['bathroom']}\n# annot_list, indices_list = annotate_scatter(X, ann_list = [\"bathroom\"])\n# annot_list, indices_list = annotate_scatter(X, ann_dict = ann_dict)\nannot_list, indices_list = annotate_scatter(X, ann_dict = ann_dict)\n\n# annot_list, indices_list = annotate_scatter(X, [\"dog\", \"cat\"])\n# print(annot_list)\n# print(len(annot_list))\nprint(len(indices_list))\n\n\ndef gen_scatter_multi_tag(annot_list, indices_list):\n # Load score matrix\n scores_obj = np.load('/newvolume/score_matrix.npz')\n scores = scores_obj['scores']\n\n # Slice out the scores relating to the images tags with the relevant tags\n score_subset = list(map(scores.__getitem__, indices_list))\n\n # Generate MDS object\n mds = MDS(n_components=2, dissimilarity=\"precomputed\")\n\n # Calculate euclidean distance between each image word vector\n similarities = euclidean_distances(score_subset)\n\n pos = mds.fit(similarities).embedding_\n\n # label_list = ['kitchen counter', 'kitchen refrigerator']\n # label_list = ['kitchen refrigerator']\n # label_list = ['kitchen island', 'kitchen']\n label_list = ['bathroom']\n\n group = np.array(annot_list)\n\n # colors = {'kitchen counter':'red', 'kitchen refrigerator': 'blue'}\n # colors = {'kitchen island':'black', 'kitchen': 'red'}\n # colors = {'fireplace': 'black', 'living': 'yellow'}\n colors = {'bathroom': 'green'}\n\n col_list = [c for c in map(lambda x: colors[x],annot_list)]\n\n fig, ax = plt.subplots()\n\n scatter_x = np.array(pos[:,0])\n scatter_y = np.array(pos[:,1])\n\n################################################################################\n# # Uncomment to add coloured dots instead of images to scatter plot #############\n for g in np.unique(group):\n ix = np.where(group == g)\n ax.scatter(scatter_x[ix], scatter_y[ix], c = colors[g], label = g)\n ax.legend(loc='lower right')\n################################################################################\n\n################################################################################\n# Uncomment section below to add images instead of dots as points of scatter plot\n # Plot image instead of point\n # obtain file paths for each image\n annFile = '/newvolume/annotations/instances_val2014.json'\n coco_val = COCO(annFile)\n ids = coco_val.getAnnIds()\n annotations = coco_val.loadAnns(ids)\n\n img_info = {}\n for ann in annotations:\n image_id = ann['image_id']\n if image_id not in img_info:\n img_info[image_id] = coco_val.imgs[image_id]\n\n img_path_list = []\n for image_id, info in img_info.items():\n file_name = info['file_name']\n img = '/newvolume/val2014/' + file_name\n img_path_list.append(img)\n\n # # Slice out the relevant images\n img_subset = list(map(img_path_list.__getitem__, indices_list))\n\n print(len(img_subset))\n # dest = '/newvolume/kitchen_island'\n dest = '/newvolume/bathroom'\n # dest_super = '/newvolume/kitchen'\n dest_super = '/newvolume/bathroom'\n print(\"annot_list = \", annot_list)\n # dest = '/newvolume/mds_results'\n for g, path in zip(annot_list, img_subset):\n print(g)\n if g == 'living fireplace':\n shutil.copy(path, dest)\n elif g == 'bathroom':\n shutil.copy(path, dest_super)\n else:\n continue\n\n\n # for x0, y0, path in zip(scatter_x, scatter_y,img_subset):\n # print(path)\n # shutil.copy(path, dest)\n # ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)\n # ax.add_artist(ab)\n # plt.scatter(pos[:, 0], pos[:, 1], c= col_list)\n################################################################################\n # return ax\n\n plt.show()\n\n plt.savefig('/newvolume/images_bathroom.pdf')\n\ngen_scatter_multi_tag(annot_list, indices_list)\n\n\n\n\ndef gen_scatter_single_tag(annot_list, indices_list, ax = None):\n # Load score matrix\n scores_obj = np.load('/newvolume/score_matrix.npz')\n scores = scores_obj['scores']\n\n print(len(scores))\n\n # Slice out the scores relating to the images tags with the relevant tags\n score_subset = list(map(scores.__getitem__, indices_list))\n\n # Generate MDS object\n mds = MDS(n_components=2, dissimilarity=\"precomputed\")\n\n # Calculate euclidean distance between each image word vector\n similarities = euclidean_distances(score_subset)\n\n pos = mds.fit(similarities).embedding_\n print(len(pos))\n\n # fig = plt.figure(figsize=(12,10))\n\n # colors = ['red','blue','green','orange', 'black']\n # label_list = ['kitchen', 'bedroom', 'bathroom', 'living room']\n label_list = ['kitchen']\n # label_list = ['living_room']\n # label_list = ['bathroom']\n # label_list = ['dog', 'cat']\n\n group = np.array(annot_list)\n\n # colors = {'kitchen':'red', 'bedroom':'blue', 'bathroom':'green', 'living':'orange'}\n # colors = {'kitchen':'red'}\n colors = {'living':'yellow'}\n # colors = {'dog':'red', 'cat':'blue'}\n col_list = [c for c in map(lambda x: colors[x],annot_list)]\n print(len(col_list))\n print(col_list)\n if ax == None:\n fig, ax = plt.subplots()\n\n scatter_x = np.array(pos[:,0])\n scatter_y = np.array(pos[:,1])\n for g in np.unique(group):\n ix = np.where(group == g)\n ax.scatter(scatter_x[ix], scatter_y[ix], c = colors[g], label = g)\n\n################################################################################\n# Uncomment section below to add images instead of dots as points of scatter plot\n # Plot image instead of point\n # obtaine file paths for each image\n # annFile = '/newvolume/annotations/instances_val2014.json'\n # coco_val = COCO(annFile)\n # ids = coco_val.getAnnIds()\n # annotations = coco_val.loadAnns(ids)\n\n # img_info = {}\n # for ann in annotations:\n # image_id = ann['image_id']\n # if image_id not in img_info:\n # img_info[image_id] = coco_val.imgs[image_id]\n\n # img_path_list = []\n # for image_id, info in img_info.items():\n # file_name = info['file_name']\n # img = '/newvolume/val2014/' + file_name\n # img_path_list.append(img)\n\n # # Slice out the relevant images\n # img_subset = list(map(img_path_list.__getitem__, indices_list))\n\n\n # dest = '/newvolume/bathroom'\n # for x0, y0, path in zip(scatter_x, scatter_y,img_subset):\n # print(path)\n # # shutil.copy(path, dest)\n # ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)\n # ax.add_artist(ab)\n ################################################################################\n\n ax.legend(loc='lower right')\n # colors = {'kitchen':'red', 'bedroom':'blue', 'bathroom':'green', 'washroom':'black', 'tarmac': 'orange', 'notlabelled': 'white'}\n\n # col_list = [c for c in map(lambda x: colors[x],annot_list)]\n # plt.scatter(pos[:, 0], pos[:, 1], c= col_list)\n\n # col_list = [c for c in map(lambda x: colors[x],annot_list)]\n # plt.scatter(pos[:, 0], pos[:, 1], c= col_list)\n plt.show()\n\n # plt.savefig('/newvolume/images_room_type.pdf')\n plt.savefig('/newvolume/images_kitchens_and_kitchen_islands.pdf')\n\n#gen_scatter_single_tag(annot_superset, indices_key_superset, ax = ax_obj)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# import chart_studio.plotly as py\n# from plotly.offline import plot\n# import plotly.graph_objs as go\n\n# import numpy as np\n\n# from sklearn import manifold\n# from sklearn.metrics import euclidean_distances\n# from sklearn.decomposition import PCA\n# import matplotlib.pyplot as plt\n\n# n_samples = 20\n# seed = np.random.RandomState(seed=3)\n# X_true = seed.randint(0, 20, 2 * n_samples).astype(np.float)\n# X_true = X_true.reshape((n_samples, 2))\n# # Center the data\n# X_true -= X_true.mean()\n\n# similarities = euclidean_distances(X_true)\n\n# # Add noise to the similarities\n# noise = np.random.rand(n_samples, n_samples)\n# noise = noise + noise.T\n# noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0\n# similarities += noise\n\n# mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed,\n# dissimilarity=\"precomputed\", n_jobs=1)\n# pos = mds.fit(similarities).embedding_\n\n# print(pos)\n\n# pos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((pos ** 2).sum())\n# print(pos)\n\n# # Rotate the data\n# clf = PCA(n_components=2)\n# X_true = clf.fit_transform(X_true)\n\n# pos = clf.fit_transform(pos)\n\n\n\n# fig = plt.figure(figsize=(12,10))\n\n# plt.scatter(pos[:, 0], pos[:, 1])\n# plt.scatter(X_true[:, 0], X_true[:, 1])\n\n# plt.show()\n\n# data = []\n# p1 = go.Scatter(x=X_true[:, 0], y=X_true[:, 1],\n# mode='markers+lines',\n# marker=dict(color='navy', size=10),\n# line=dict(width=1),\n# name='True Position')\n# data.append(p1)\n# p2 = go.Scatter(x=pos[:, 0], y=pos[:, 1],\n# mode='markers+lines',\n# marker=dict(color='turquoise', size=10),\n# line=dict(width=1),\n# name='MDS')\n# data.append(p2)\n\n\n\n\n\n# layout = go.Layout(xaxis=dict(zeroline=False, showgrid=False,\n# ticks='', showticklabels=False),\n# yaxis=dict(zeroline=False, showgrid=False,\n# ticks='', showticklabels=False),\n","sub_path":"main/mds_pca.py","file_name":"mds_pca.py","file_ext":"py","file_size_in_byte":10896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"589645801","text":"# -*- coding: utf-8 -*-\n\"\"\"Test generation of bandwidth measurements document (v3bw)\"\"\"\nimport json\nimport os.path\n\nfrom sbws import __version__ as version\nfrom sbws.globals import SPEC_VERSION, SBWS_SCALING, TORFLOW_SCALING\nfrom sbws.lib.resultdump import Result, load_result_file\nfrom sbws.lib.v3bwfile import (V3BWHeader, V3BWLine, TERMINATOR, LINE_SEP,\n KEYVALUE_SEP_V110, num_results_of_type,\n V3BWFile)\nfrom sbws.util.timestamp import now_fname\n\ntimestamp = 1523974147\ntimestamp_l = str(timestamp)\nversion_l = KEYVALUE_SEP_V110.join(['version', SPEC_VERSION])\nsoftware_l = KEYVALUE_SEP_V110.join(['software', 'sbws'])\nsoftware_version_l = KEYVALUE_SEP_V110.join(['software_version', version])\nfile_created = '2018-04-25T13:10:57'\nfile_created_l = KEYVALUE_SEP_V110.join(['file_created', file_created])\nlatest_bandwidth = '2018-04-17T14:09:07'\nlatest_bandwidth_l = KEYVALUE_SEP_V110.join(['latest_bandwidth',\n latest_bandwidth])\nheader_ls = [timestamp_l, version_l, file_created_l, latest_bandwidth_l,\n software_l, software_version_l, TERMINATOR]\nheader_str = LINE_SEP.join(header_ls) + LINE_SEP\nearliest_bandwidth = '2018-04-16T14:09:07'\nearliest_bandwidth_l = KEYVALUE_SEP_V110.join(['earliest_bandwidth',\n earliest_bandwidth])\ngenerator_started = '2018-04-16T14:09:05'\ngenerator_started_l = KEYVALUE_SEP_V110.join(['generator_started',\n generator_started])\nheader_extra_ls = [timestamp_l, version_l,\n earliest_bandwidth_l, file_created_l, generator_started_l,\n latest_bandwidth_l,\n software_l, software_version_l, TERMINATOR]\nheader_extra_str = LINE_SEP.join(header_extra_ls) + LINE_SEP\n\nbwl_str = \"bw=56 bw_bs_mean=61423 bw_bs_median=55656 \"\\\n \"desc_avg_bw_bs=1000000000 desc_obs_bw_bs_last=524288 \"\\\n \"desc_obs_bw_bs_mean=524288 error_circ=0 error_misc=0 error_stream=1 \" \\\n \"master_key_ed25519=g+Shk00y9Md0hg1S6ptnuc/wWKbADBgdjT0Kg+TSF3s \" \\\n \"nick=A \" \\\n \"node_id=$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA rtt=456 success=1 \" \\\n \"time=2018-04-17T14:09:07\\n\"\n\nv3bw_str = header_extra_str + bwl_str\n\n\ndef test_v3bwheader_str():\n \"\"\"Test header str\"\"\"\n header = V3BWHeader(timestamp_l, file_created=file_created)\n assert header_str == str(header)\n\n\ndef test_v3bwheader_extra_str():\n \"\"\"Test header str with additional headers\"\"\"\n header = V3BWHeader(timestamp_l,\n file_created=file_created,\n generator_started=generator_started,\n earliest_bandwidth=earliest_bandwidth)\n assert header_extra_str == str(header)\n\n\ndef test_v3bwheader_from_lines():\n \"\"\"\"\"\"\n header_obj = V3BWHeader(timestamp_l,\n file_created=file_created,\n generator_started=generator_started,\n earliest_bandwidth=earliest_bandwidth)\n header, _ = V3BWHeader.from_lines_v110(header_extra_ls)\n assert str(header_obj) == str(header)\n\n\ndef test_v3bwheader_from_text():\n \"\"\"\"\"\"\n header_obj = V3BWHeader(timestamp_l,\n file_created=file_created,\n generator_started=generator_started,\n earliest_bandwidth=earliest_bandwidth)\n header, _ = V3BWHeader.from_text_v110(header_extra_str)\n assert str(header_obj) == str(header)\n\n\ndef test_num_results_of_type(result_success, result_error_stream):\n assert num_results_of_type([result_success], 'success') == 1\n assert num_results_of_type([result_error_stream], 'success') == 0\n assert num_results_of_type([result_success], 'error-stream') == 0\n assert num_results_of_type([result_error_stream], 'error-stream') == 1\n\n\ndef test_v3bwline_from_results_file(datadir):\n lines = datadir.readlines('results.txt')\n d = dict()\n for line in lines:\n r = Result.from_dict(json.loads(line.strip()))\n fp = r.fingerprint\n if fp not in d:\n d[fp] = []\n d[fp].append(r)\n bwl = V3BWLine.from_data(d, fp)\n # bw store now B, not KB\n bwl.bw = round(bwl.bw / 1000)\n assert bwl_str == str(bwl)\n\n\ndef test_from_results_read(datadir, tmpdir, conf, args):\n results = load_result_file(str(datadir.join(\"results.txt\")))\n expected_header = V3BWHeader(timestamp_l,\n earliest_bandwidth=earliest_bandwidth,\n latest_bandwidth=latest_bandwidth)\n expected_bwls = [V3BWLine.from_results(results[fp]) for fp in results]\n # bw store now B, not KB\n expected_bwls[0].bw = round(expected_bwls[0].bw / 1000)\n expected_f = V3BWFile(expected_header, expected_bwls)\n # This way is going to convert bw to KB\n v3bwfile = V3BWFile.from_results(results)\n assert str(expected_f)[1:] == str(v3bwfile)[1:]\n output = os.path.join(args.output, now_fname())\n v3bwfile.write(output)\n\n\ndef test_from_arg_results_write(datadir, tmpdir, conf, args):\n results = load_result_file(str(datadir.join(\"results.txt\")))\n v3bwfile = V3BWFile.from_results(results)\n output = os.path.join(args.output, now_fname())\n v3bwfile.write(output)\n assert os.path.isfile(output)\n\n\ndef test_from_arg_results_write_read(datadir, tmpdir, conf, args):\n results = load_result_file(str(datadir.join(\"results.txt\")))\n v3bwfile = V3BWFile.from_results(results)\n output = os.path.join(args.output, now_fname())\n v3bwfile.write(output)\n with open(output) as fd:\n v3bw = fd.read()\n assert v3bw == str(v3bwfile)\n\n\ndef test_sbws_scale(datadir):\n results = load_result_file(str(datadir.join(\"results.txt\")))\n v3bwfile = V3BWFile.from_results(results, scaling_method=SBWS_SCALING)\n assert v3bwfile.bw_lines[0].bw == 8\n\n\ndef test_torflow_scale(datadir):\n results = load_result_file(str(datadir.join(\"results.txt\")))\n v3bwfile = V3BWFile.from_results(results, scaling_method=TORFLOW_SCALING)\n assert v3bwfile.bw_lines[0].bw == 1000\n v3bwfile = V3BWFile.from_results(results, scaling_method=TORFLOW_SCALING,\n torflow_cap=0.0001)\n assert v3bwfile.bw_lines[0].bw == 1000\n v3bwfile = V3BWFile.from_results(results, scaling_method=TORFLOW_SCALING,\n torflow_cap=1, torflow_round_digs=0)\n assert v3bwfile.bw_lines[0].bw == 524\n","sub_path":"tests/unit/lib/test_v3bwfile.py","file_name":"test_v3bwfile.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"521494279","text":"from setuptools import find_packages\nfrom setuptools import setup\n\nimport os\n\n\nlong_description = (\n open(os.path.join(\"src\", \"hexagonit\", \"socialbutton\", \"docs\", \"README.rst\")).read() + \"\\n\" +\n open(os.path.join(\"src\", \"hexagonit\", \"socialbutton\", \"docs\", \"HISTORY.rst\")).read() + \"\\n\" +\n open(os.path.join(\"src\", \"hexagonit\", \"socialbutton\", \"docs\", \"CONTRIBUTORS.rst\")).read())\n\n\nsetup(\n name='hexagonit.socialbutton',\n version='0.11',\n description=\"Adds viewlets for embedding codes such as social buttons for Plone.\",\n long_description=long_description,\n classifiers=[\n \"Framework :: Plone\",\n \"Framework :: Plone :: 4.3\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\"],\n keywords='',\n author='Hexagon IT',\n author_email='oss@hexagonit.fi',\n url='http://www.hexagonit.fi',\n license='BSD',\n packages=find_packages('src', exclude=['ez_setup']),\n package_dir={'': 'src'},\n namespace_packages=['hexagonit'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'plone.stringinterp >= 1.0.11',\n 'setuptools'],\n extras_require={'test': ['hexagonit.testing']},\n entry_points=\"\"\"\n # -*- Entry points: -*-\n\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\")\n","sub_path":"pypi_install_script/hexagonit.socialbutton-0.11/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590131712","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\loutilities\\user\\model.py\n# Compiled at: 2020-03-21 07:22:44\n# Size of source mod 2**32: 11272 bytes\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_security import UserMixin, RoleMixin\ndb = SQLAlchemy()\nTable = db.Table\nColumn = db.Column\nInteger = db.Integer\nFloat = db.Float\nBoolean = db.Boolean\nString = db.String\nText = db.Text\nDate = db.Date\nTime = db.Time\nDateTime = db.DateTime\nSequence = db.Sequence\nEnum = db.Enum\nUniqueConstraint = db.UniqueConstraint\nForeignKey = db.ForeignKey\nrelationship = db.relationship\nbackref = db.backref\nobject_mapper = db.object_mapper\nBase = db.Model\nDESCR_LEN = 512\nINTEREST_LEN = 32\nAPPLICATION_LEN = 32\nUSERROLEDESCR_LEN = 512\nROLENAME_LEN = 32\nEMAIL_LEN = 100\nNAME_LEN = 256\nPASSWORD_LEN = 255\nUNIQUIFIER_LEN = 255\nAPP_CONTRACTS = 'contracts'\nAPP_MEMBERS = 'members'\nAPP_ROUTES = 'routes'\nAPP_SCORES = 'scores'\nAPP_ALL = [APP_CONTRACTS, APP_MEMBERS, APP_ROUTES, APP_SCORES]\nuserinterest_table = Table('users_interests', (Base.metadata), (Column('user_id', Integer, ForeignKey('user.id'))),\n (Column('interest_id', Integer, ForeignKey('interest.id'))),\n info={'bind_key': 'users'})\nappinterest_table = Table('apps_interests', (Base.metadata), (Column('application_id', Integer, ForeignKey('application.id'))),\n (Column('interest_id', Integer, ForeignKey('interest.id'))),\n info={'bind_key': 'users'})\napprole_table = Table('apps_roles', (Base.metadata), (Column('application_id', Integer, ForeignKey('application.id'))),\n (Column('role_id', Integer, ForeignKey('role.id'))),\n info={'bind_key': 'users'})\n\nclass Interest(Base):\n __tablename__ = 'interest'\n __bind_key__ = 'users'\n id = Column((Integer()), primary_key=True)\n interest = Column(String(INTEREST_LEN))\n users = relationship('User', secondary=userinterest_table,\n backref=(backref('interests')))\n applications = relationship('Application', secondary=appinterest_table,\n backref=(backref('interests')))\n description = Column(String(DESCR_LEN))\n public = Column(Boolean)\n version_id = Column(Integer, nullable=False, default=1)\n __mapper_args__ = {'version_id_col': version_id}\n\n\nclass Application(Base):\n __tablename__ = 'application'\n __bind_key__ = 'users'\n id = Column((Integer()), primary_key=True)\n application = Column(String(APPLICATION_LEN))\n version_id = Column(Integer, nullable=False, default=1)\n __mapper_args__ = {'version_id_col': version_id}\n\n\nclass RolesUsers(Base):\n __tablename__ = 'roles_users'\n __bind_key__ = 'users'\n id = Column((Integer()), primary_key=True)\n user_id = Column('user_id', Integer(), ForeignKey('user.id'))\n role_id = Column('role_id', Integer(), ForeignKey('role.id'))\n\n\nclass Role(Base, RoleMixin):\n __tablename__ = 'role'\n __bind_key__ = 'users'\n id = Column((Integer()), primary_key=True)\n name = Column((String(ROLENAME_LEN)), unique=True)\n description = Column(String(USERROLEDESCR_LEN))\n applications = relationship('Application', secondary=approle_table,\n backref=(backref('roles')))\n version_id = Column(Integer, nullable=False, default=1)\n __mapper_args__ = {'version_id_col': version_id}\n\n\nclass User(Base, UserMixin):\n __tablename__ = 'user'\n __bind_key__ = 'users'\n id = Column(Integer, primary_key=True)\n email = Column((String(EMAIL_LEN)), unique=True)\n password = Column(String(PASSWORD_LEN))\n name = Column(String(NAME_LEN))\n given_name = Column(String(NAME_LEN))\n last_login_at = Column(DateTime())\n current_login_at = Column(DateTime())\n last_login_ip = Column(String(100))\n current_login_ip = Column(String(100))\n login_count = Column(Integer)\n active = Column(Boolean())\n fs_uniquifier = Column(String(UNIQUIFIER_LEN))\n confirmed_at = Column(DateTime())\n roles = relationship('Role', secondary='roles_users', backref=backref('users', lazy='dynamic'))\n version_id = Column(Integer, nullable=False, default=1)\n __mapper_args__ = {'version_id_col': version_id}\n\n\nclass ManageLocalTables:\n\n def __init__(self, db, appname, localusermodel, localinterestmodel, hasuserinterest=False):\n \"\"\"\n operations on localuser model for callers of User model\n\n :param db: SQLAlchemy instance used by caller\n :param appname: name of application, must match Application.application\n :param localusermodel: model class for User, in the slave database (must have user_id column)\n :param localinterestmodel: model class for Interest, in the slave database\n :param hasuserinterest: (optional) if localusermodel has interest_id field, the users are copied for\n each interest used by appname, default False\n \"\"\"\n self.db = db\n self.localusermodel = localusermodel\n self.localusertable = localusermodel.__table__.name\n self.hasuserinterest = hasuserinterest\n self.localinterestmodel = localinterestmodel\n self.localinteresttable = localinterestmodel.__table__.name\n self.application = Application.query.filter_by(application=appname).one()\n\n def _updateuser_byinterest(self):\n if not db.engine.has_table(self.localusertable):\n return\n alllocal = {}\n for localuser in self.localusermodel.query.all():\n alllocal[(localuser.user_id, localuser.interest_id)] = localuser\n\n for user in User.query.all():\n for interest in Interest.query.all():\n if self.application not in interest.applications:\n pass\n else:\n localinterest = self.localinterestmodel.query.filter_by(interest_id=(interest.id)).one()\n if (\n user.id, localinterest.id) in alllocal:\n localuser = alllocal.pop((user.id, localinterest.id))\n localuser.active = user.active\n else:\n newlocal = self.localusermodel(user_id=(user.id), interest_id=(localinterest.id), active=True)\n self.db.session.add(newlocal)\n\n for user_id, interest_id in alllocal:\n localuser = self.localusermodel.query.filter_by(user_id=user_id, interest_id=interest_id).one()\n localuser.active = False\n\n def _updateuser_only(self):\n if not db.engine.has_table(self.localusertable):\n return\n alllocal = {}\n for localuser in self.localusermodel.query.all():\n alllocal[localuser.user_id] = localuser\n\n for user in User.query.all():\n if user.id in alllocal:\n localuser = alllocal.pop(user.id)\n localuser.active = user.active\n else:\n newlocal = self.localusermodel(user_id=(user.id), active=(user.active))\n self.db.session.add(newlocal)\n\n for user_id in alllocal:\n localuser = self.localusermodel.query.filter_by(user_id=user_id).one()\n localuser.active = False\n\n def _updateinterest(self):\n if not db.engine.has_table(self.localinteresttable):\n return\n alllocal = {}\n for localinterest in self.localinterestmodel.query.all():\n alllocal[localinterest.interest_id] = localinterest\n\n for interest in Interest.query.all():\n if self.application not in interest.applications:\n continue\n if interest.id in alllocal:\n discard = alllocal.pop(interest.id)\n else:\n newlocal = self.localinterestmodel(interest_id=(interest.id))\n self.db.session.add(newlocal)\n\n for interest_id in alllocal:\n localinterest = self.localinterestmodel.query.filter_by(interest_id=interest_id).one()\n self.db.session.delete(localinterest)\n\n def update(self):\n \"\"\"\n keep localuser and localinterest tables consistent with external db User table\n \"\"\"\n self._updateinterest()\n db.session.flush()\n if self.hasuserinterest:\n self._updateuser_byinterest()\n else:\n self._updateuser_only()\n self.db.session.commit()","sub_path":"pycfiles/loutilities-3.2.3-py3.6/model.cpython-36.py","file_name":"model.cpython-36.py","file_ext":"py","file_size_in_byte":8326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"181514840","text":"#!/usr/bin/python\n\n# A script to produce name labels for each pupil, on a per-class basis. Uses reportLab to output printable PDF documents sized\n# to fit Avery L7160 label sheets.\n\n# Standard libraries.\nimport os\nimport sys\n\n# PIL - the Python Image Library, used for bitmap image manipulation.\nimport PIL\nimport PIL.ImageFont\nimport PIL.ImageDraw\n\n# ReportLab - used for PDF document generation.\nimport reportlab.lib.units\nimport reportlab.lib.utils\nimport reportlab.lib.colors\nimport reportlab.pdfgen.canvas\nimport reportlab.lib.pagesizes\nimport reportlab.graphics.renderPM\n\n# Data-handling.\nimport pandas\n\n# Our own library.\nimport dataLib\n\n# Load the config file.\nconfig = dataLib.loadConfig([\"dataFolder\"])\n\n# Make sure the output folder exists.\nlabelsRoot = config[\"dataFolder\"] + os.sep + \"Labels\"\nformLabelsRoot = labelsRoot + os.sep + \"Form Labels\"\nspineLabelsRoot = labelsRoot + os.sep + \"Spine Labels\"\nos.makedirs(formLabelsRoot, exist_ok=True)\nos.makedirs(spineLabelsRoot, exist_ok=True)\n\n# We are printing on Avery L7160 labels (A4, 7 rows of 3 labels) - set the page size and borders, in mm.\npageWidth = 210\npageHeight = 297\nlabelsX = 3\nlabelsY = 7\nlabelWidth = 63.5\nlabelHeight = 38.1\nlabelBorder = 40\nlabelHorizontalGap = 3\nlineSpacing = 30\ninitialFontSize = 132\nfontSizeStep = 4\nleftBorder = (pageWidth - ((labelWidth * labelsX) + (labelHorizontalGap * 2))) / 2\ntopBorder = (pageHeight - (labelHeight * labelsY)) / 2\n\n# Splits a string into two as-even-as-possible strings, split by space.\ndef evenlySplitString(theString):\n\ttheString = theString.strip()\n\tif theString.find(\" \") == -1:\n\t\treturn(theString, \"\")\n\tstringSplit = theString.split(\" \")\n\tif len(stringSplit) == 2:\n\t\treturn(stringSplit[0], stringSplit[1])\n\tresult1 = \"\"\n\tresult2 = \"\"\n\tlowestDiff = 999\n\tfor pl in range(1, len(stringSplit)):\n\t\ttempResult1 = \" \".join(stringSplit[:pl])\n\t\ttempResult2 = \" \".join(stringSplit[pl:])\n\t\ttempDiff = abs(len(tempResult1)-len(tempResult2))\n\t\tif tempDiff < lowestDiff:\n\t\t\tresult1 = tempResult1\n\t\t\tresult2 = tempResult2\n\t\t\tlowestDiff = tempDiff\n\treturn(result1, result2)\n\n# Set up a bunch of different font sizes for use with name labels.\nfonts = {}\nfor fontSize in range(4, 129, 4):\n\tfonts[fontSize] = PIL.ImageFont.truetype(\"DejaVuSerif.ttf\", fontSize)\n\nprint(\"Writing per-form PDF Stickers...\")\npupils = pandas.read_csv(config[\"dataFolder\"] + os.sep + \"pupils.csv\", header=0)\n\nforms = {}\nfor pupilsIndex, pupilsValue in pupils.iterrows():\n\tforms[pupilsValue[\"Form\"]] = 1\n\nfor form in forms.keys():\n\t# Create the blank PDF document to start drawing page elements on.\n\tpdfCanvas = reportlab.pdfgen.canvas.Canvas(formLabelsRoot + os.sep + form + \".pdf\")\n\tlabelCount = 0\n\tfor pupilsIndex, pupilsValue in pupils.iterrows():\n\t\tif form == pupilsValue[\"Form\"]:\n\t\t\tlabelX = labelCount % labelsX\n\t\t\tlabelY = ((labelCount - labelX) / labelsX) % labelsY\n\t\t\t\n\t\t\t# Create a blank image to place the label details on.\n\t\t\tlabelImageWidth = int(labelWidth*10)\n\t\t\tlabelImageHeight = int(labelHeight*10)\n\t\t\tlabelImage = PIL.Image.new(\"RGB\", (labelImageWidth,labelImageHeight), (255, 255, 255))\n\t\t\t\n\t\t\t# Draw the pupil's full name on the label image, centred, 20 pixels down from the top.\n\t\t\tfontSize = initialFontSize\n\t\t\tline1Width = labelImageWidth\n\t\t\tline1Height = labelImageHeight\n\t\t\tline2Width = labelImageWidth\n\t\t\tline2Height = labelImageHeight\n\t\t\ttextDrawer = PIL.ImageDraw.Draw(labelImage)\n\t\t\tline1Text, line2Text = evenlySplitString(pupilsValue[\"GivenName\"] + \" \" + pupilsValue[\"FamilyName\"])\n\t\t\twhile line1Width >= (labelImageWidth-labelBorder) or line2Width >= (labelImageWidth-labelBorder) or (line1Height + lineSpacing + line2Height) >= labelImageHeight:\n\t\t\t\tfontSize = fontSize - fontSizeStep\n\t\t\t\tline1Width, line1Height = textDrawer.textsize(line1Text, font=fonts[fontSize])\n\t\t\t\tline2Width, line2Height = textDrawer.textsize(line2Text, font=fonts[fontSize])\n\t\t\ttextDrawer.text((int((labelImageWidth-line1Width)/2), (labelBorder / 2)), line1Text, fill=\"black\", font=fonts[fontSize])\n\t\t\ttextDrawer.text((int((labelImageWidth-line2Width)/2), line1Height+lineSpacing), line2Text, fill=\"black\", font=fonts[fontSize])\n \n\t\t\t# Place the label image on the PDF document.\n\t\t\tpdfCanvas.drawInlineImage(labelImage, (leftBorder+(labelX*(labelWidth+labelHorizontalGap)))*reportlab.lib.units.mm, (pageHeight-(topBorder+((labelY+1)*labelHeight)))*reportlab.lib.units.mm, labelWidth*reportlab.lib.units.mm, labelHeight*reportlab.lib.units.mm)\n\t\t\t\n\t\t\tlabelCount = labelCount + 1\n\t# Save the PDF document.\n\tpdfCanvas.save()\n\t\nfor form in forms.keys():\n\t# Create the blank PDF document to start drawing page elements on.\n\tpdfCanvas = reportlab.pdfgen.canvas.Canvas(spineLabelsRoot + os.sep + form + \".pdf\")\n\tlabelCount = 0\n\tfor pupilsIndex, pupilsValue in pupils.iterrows():\n\t\tif form == pupilsValue[\"Form\"]:\n\t\t\tlabelX = labelCount % labelsX\n\t\t\tlabelY = ((labelCount - labelX) / labelsX) % labelsY\n\t\t\t\n\t\t\t# Create a blank image to place the label details on.\n\t\t\tlabelImageWidth = int(labelWidth*10)\n\t\t\tlabelImageHeight = int((labelHeight/3)*10)\n\t\t\tlabelImage = PIL.Image.new(\"RGB\", (labelImageWidth,labelImageHeight), (255, 255, 255))\n\t\t\t\n\t\t\t# Draw the pupil's given name.\n\t\t\tfontSize = initialFontSize\n\t\t\tlineWidth = labelImageWidth\n\t\t\tlineHeight = labelImageHeight / 3\n\t\t\ttextDrawer = PIL.ImageDraw.Draw(labelImage)\n\t\t\twhile lineWidth >= (labelImageWidth-labelBorder) or lineHeight >= labelImageHeight:\n\t\t\t\tfontSize = fontSize - fontSizeStep\n\t\t\t\tlineWidth, lineHeight = textDrawer.textsize(pupilsValue[\"GivenName\"], font=fonts[fontSize])\n\t\t\ttextDrawer.text((int((labelImageWidth-lineWidth)/2), (labelBorder / 2)), pupilsValue[\"GivenName\"], fill=\"black\", font=fonts[fontSize])\n \n\t\t\t# Place the label image on the PDF document.\n\t\t\tpdfCanvas.drawInlineImage(labelImage, (leftBorder+(labelX*(labelWidth+labelHorizontalGap)))*reportlab.lib.units.mm, (pageHeight-(topBorder+((labelY+1)*labelHeight)))*reportlab.lib.units.mm, labelWidth*reportlab.lib.units.mm, labelHeight*reportlab.lib.units.mm)\n\t\t\t\n\t\t\tlabelCount = labelCount + 1\n\t# Save the PDF document.\n\tpdfCanvas.save()\n","sub_path":"generateClassNameStickers.py","file_name":"generateClassNameStickers.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"584416209","text":"#!/usr/bin/env python\n#\n# Copyright 2012 Jordon Mears (http://www.finefrog.com/)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tornado.ioloop\nimport tornado.web\n\nimport handlers\n\napplication = tornado.web.Application([\n (r'/', handlers.IndexHandler),\n (r'/q/?', handlers.QueryHandler),\n (r'/query/?', handlers.QueryHandler),\n (r'/query-browser.html', handlers.QueryBrowserHandler),\n (r'/api/(.*)', tornado.web.StaticFileHandler, {'path' : './api'}),\n (r'/static/(.*)', tornado.web.StaticFileHandler, {'path' : './static'}),\n (r'/(crossdomain\\.xml)', tornado.web.StaticFileHandler, {'path' : './'})\n])\n\nif __name__ == '__main__':\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"536635814","text":"\"\"\"Decorators for API resources.\"\"\"\nimport functools\n\nfrom flask import request\n\nfrom api.exception import BadRequestException\n\n\ndef expect_required_fields(func):\n \"\"\"Examines an HTTP request to verify thit it contains all required fields.\n\n Raises:\n BadRequestException: If any any required fields are missing.\n \"\"\"\n @functools.wraps(func)\n def decorated(instance, *args, **kwargs):\n request_data = request.get_json(force=True, silent=True)\n missing_fields = []\n given_fields = request_data.keys()\n for required_field in instance.__model__.required_fields():\n if required_field not in given_fields:\n missing_fields.append(required_field)\n if len(missing_fields) > 0:\n message = f'Missing required fields: [{\", \".join(missing_fields)}]'\n raise BadRequestException(message)\n return func(instance, *args, **kwargs)\n return decorated\n\ndef refuse_unknown_fields(func):\n \"\"\"Examines an HTTP request to verify thit it does not contain any\n unknown fields.\n\n Raises:\n BadRequestException: If any any unknown fields are discovered.\n \"\"\"\n @functools.wraps(func)\n def decorated(instance, *args, **kwargs):\n request_data = request.get_json(force=True, silent=True)\n model = instance.__model__\n unknown_fields = []\n known_fields = model.required_fields() + model.optional_fields() + ['id']\n for given_field in request_data:\n if given_field not in known_fields:\n unknown_fields.append(given_field)\n if len(unknown_fields) > 0:\n message = f'Unknown fields: [{\", \".join(unknown_fields)}]'\n raise BadRequestException(message)\n return func(instance, *args, **kwargs)\n return decorated\n\n#def audit_request(func):\n# \"\"\"Ensures that we have a valid request from the client.\n#\n# Raises:\n# BadRequestException: If no data was received with the request.\n# \"\"\"\n# @functools.wraps(func)\n# def decorated(instance, *args, **kwargs):\n# request_data = request.get_json(force=True, silent=True)\n# if not request_data:\n# raise BadRequestException('No data received with the request.')\n","sub_path":"02_trivia_api/backend/api/resources/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"148332508","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nMydataset = pd.read_csv('path4.csv')\r\nelevation = Mydataset.iloc[:,:].values\r\n\r\nz = Mydataset.iloc[:,3].values\r\nx = np.linspace(0,54,1025)\r\nx_resize = np.linspace(0,54,256)\r\nN_elevation= len(z)\r\nZ_512 = np.zeros([256])\r\n\r\ndef AverageStep(InputData,OutputData):\r\n InputData_calc = InputData.copy()\r\n OutputData_calc = OutputData.copy()\r\n \r\n na = len(InputData_calc)\r\n nb = len(OutputData_calc)\r\n step = int(na/nb)\r\n\r\n for i in range(0,na-step,step):\r\n contain=0\r\n for j in range(step):\r\n contain = contain + InputData_calc[i+j]\r\n average = contain/step\r\n pointer = int(i/step+1)\r\n OutputData_calc[pointer-1]=average\r\n \r\n return OutputData_calc\r\n \r\nZ_resize = AverageStep(z,Z_512)\r\n \r\nplt.plot(x_resize,Z_resize)\r\n#plt.plot(x,z)\r\nplt.grid(True)\r\nplt.plot ","sub_path":"csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"303532314","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Volin',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('author', models.CharField(max_length=20, verbose_name='auth.user')),\n ('title', models.CharField(max_length=100, verbose_name='Nazwa zadania')),\n ('destination', models.CharField(blank=True, max_length=50, verbose_name='Miejsce ')),\n ('description', models.TextField(verbose_name='Opis')),\n ('publication_date', models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')),\n ],\n options={\n 'ordering': ['-id'],\n },\n ),\n ]\n","sub_path":"Volontario/Ind/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"500879214","text":"from flask import Flask\nfrom flask import Flask, request, jsonify\nimport json\nfrom flask_restful import Resource,Api\n\nfrom Prerdiction import Prediction\nfrom Productivity import Productivity\n\napp = Flask(__name__)\napi = Api(app)\n\nclass Api(Resource):\n #get request to call the json objects sent to the backend\n def get(self):\n request_data = request.data\n request_data = json.loads(request_data.decode('utf-8'))\n return request_data\n #post request to get the data from front end to do processing\n def post(self):\n request_data = request.data\n request_data = json.loads(request_data.decode('utf-8'))\n date = request_data['date']\n startTime = request_data['startTime']\n endTime = request_data['endTime']\n capacity = request_data['capacity']\n p1 = Prediction(date, startTime,endTime)\n irr = p1.getIrradiance()\n e1 = Productivity(irr,1,capacity)\n pro = e1.getUnits()\n print(\"Productivity : \",pro)\n return round(pro,2)\napi.add_resource(Api,\"/api\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Hosting_backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"593986124","text":"from math import ceil\nimport torch\nfrom torchvision import transforms, datasets\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport numpy as np\nimport torchvision\n\n\ndef data_processing(filepath, batch_size=4):\n \"\"\"\n Prepare data for the network. We transform the images\n and return training, validation and test sets.\n Args:\n filepath (str): path to the folder with all data images.\n batch_size (int): size of each batch.\n Returns:\n tuple: (train_loader, validation_loader, test_loader)\n \"\"\"\n data_transform = transforms.Compose([\n transforms.Resize([256,342]),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))\n ])\n music_dataset = datasets.ImageFolder(root=filepath, transform=data_transform)\n batch_size = 4\n train_data, validation_data, test_data = torch.utils.data.random_split(\n music_dataset, [ceil(0.6*len(music_dataset)),\n ceil(0.2*len(music_dataset)),\n len(music_dataset)-(ceil(0.6*len(music_dataset))+ceil(0.2*len(music_dataset)))])\n train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,shuffle=True)\n validation_loader = torch.utils.data.DataLoader(validation_data, batch_size=batch_size,shuffle=True)\n test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size,shuffle=True)\n return train_loader, validation_loader, test_loader\n","sub_path":"data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"243565291","text":"from PyQt4 import QtCore, QtGui\nimport sys\nfrom patientlist_ui import Ui_PatientList\n\nclass MyListWidget(QtGui.QMainWindow): \n\n\tdef __init__(self, parent=None):\n\t\tQtGui.QWidget.__init__(self, parent)\n\t\tself.ui = Ui_PatientList()\n\t\tself.ui.setupUi(self)\n\t\tself.show()\n\t\n\tdef ItemDoubleClicked(self,index):\n\t\tQMessageBox.information(None,\"Hello!\",\"You Double Clicked: \\n\"+index.data().toString()) \n \n \ndef main(): \n app \t= QtGui.QApplication(sys.argv)\n listWidget \t= MyListWidget(None) \n\n QObject.connect(listWidget,SIGNAL(\"doubleClicked(QModelIndex)\"),\n\t\tlistWidget,SLOT(\"ItemDoubleClicked(QModelIndex)\")) \n return app.exec_()\nif __name__ == '__main__':\n main()","sub_path":"qtpy/patientlist.py","file_name":"patientlist.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"80489219","text":"#!/usr/bin/env python\n\"\"\"\n \n map_park_name.py\n new york park names\n \"\"\"\nimport sys\nfrom csv import reader\ncol = -8\n#dict = ['front of','inside','opposite of','outside','rear of']\ndata = reader(sys.stdin)\nnext(data)\nfor raw_cols in data:\n if raw_cols[col] == '':\n key = 'N/A'\n _time = raw_cols[col]\n _type = 'STRING'\n _col_name = 'premises'\n _valid = 'NULL'\n else:\n key = raw_cols[col]\n _time = raw_cols[col]\n _type = 'STRING'\n _col_name = 'premises'\n _valid = 'VALID'\n print (\"{0:s}\\t{1:s},{2:s},{3:s},{4:s}\".format(key, _time, _type, _col_name, _valid))","sub_path":"column_summary/map_PREM_TYP_DESC.py","file_name":"map_PREM_TYP_DESC.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"226683490","text":"#!/usr/bin/python3\n\"\"\"create a route /status on the object app_views that returns a JSON.\"\"\"\nfrom flask import Flask, jsonify, abort, request, make_response\nfrom api.v1.views import app_views\nfrom models import storage\nfrom models.place import Place\nfrom models.city import City\nfrom models.user import User\n\n\n@app_views.route('/cities//places', strict_slashes=False)\ndef all_places(city_id):\n \"\"\"Retrieves the list of all place objects.\"\"\"\n new_dict = []\n if not storage.get(City, city_id):\n abort(404)\n for plc in storage.all('Place').values():\n if city_id == plc.to_dict()['city_id']:\n new_dict.append(plc.to_dict())\n return jsonify(new_dict)\n\n\n@app_views.route('/places/', strict_slashes=False,\n methods=['GET'])\ndef get_place(place_id):\n \"\"\"GET the list of all place objects.\"\"\"\n try:\n plc = jsonify(storage.get(Place, place_id).to_dict())\n return plc\n except BaseException:\n abort(404)\n\n\n@app_views.route('/places/', strict_slashes=False,\n methods=['DELETE'])\ndef delete_place(place_id):\n \"\"\"GET the list of all place objects.\"\"\"\n plc = storage.get(Place, place_id)\n if plc:\n plc.delete(), storage.save()\n return {}\n else:\n abort(404)\n\n\n@app_views.route('cities//places', methods=['POST'],\n strict_slashes=False)\ndef create_place(city_id):\n \"\"\"POST the list of all place objects.\"\"\"\n plc = request.get_json()\n if not storage.get(City, city_id):\n abort(404)\n if type(plc) is not dict:\n abort(400, {'Not a JSON'})\n elif 'user_id' not in plc:\n abort(400, {'Missing user_id'})\n elif 'name' not in plc:\n abort(400, {'Missing name'})\n elif not storage.get(User, plc['user_id']):\n abort(404)\n else:\n plc['city_id'] = city_id\n new_plc = Place(**plc)\n storage.new(new_plc)\n storage.save()\n return make_response(jsonify(new_plc.to_dict()), 201)\n\n\n@app_views.route('/places/', strict_slashes=False,\n methods=['PUT'])\ndef update_place(place_id):\n \"\"\"PUT the list of all place objects.\"\"\"\n update_plc = request.get_json()\n if type(update_plc) is not dict:\n abort(400, {'Not a JSON'})\n plc = storage.get(Place, place_id)\n if not plc:\n abort(404)\n else:\n for key, value in update_plc.items():\n if key not in ['id', 'user_id', 'city_id', 'created_at',\n 'updated_at']:\n setattr(plc, key, value)\n storage.save()\n return jsonify(plc.to_dict())\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378694801","text":"## ConcentrationPlotter returns a map of the difference between two concentration plots for the same area, latitude and longitude\r\n## Can be run standalone (use main to pass arguments if so desired) or use a python script to pass through values to generate multiple plots\r\n\r\nimport numpy as np\r\nimport os\r\nimport rpnpy.librmn.all as rmn\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.basemap import Basemap\r\nfrom math import cos, radians\r\nimport errno\r\nimport logging\r\n\r\n## constants\r\ncurrentDir = os.path.dirname(os.path.abspath(__file__))\r\ndefaultPathStnd = os.path.join(currentDir,'FST_files/GEMMACH_dev_rev_67537156/20100710000000/model/')\r\ndefaultPathAlt = os.path.join(currentDir,'FST_files/adomKPPKPPB_adomYB/20100710000000/model/')\r\ndefaultSave = currentDir\r\n# defaultFile is the name of the FST files to be compared\r\ndefaultFile = '2010071000_001'\r\ndefaultIp1=76696048\r\n# defaultSpc not in list format since this function only takes one species\r\ndefaultSpc='TO3'\r\ndefaultDiffCmap = 'RdBu'\r\ndefaultConcCmap = 'spectral'\r\ndefaultRev = True\r\ndefaultExt = 'neither'\r\ndefaultProjection = 'stere'\r\ndefaultBins = None\r\n# defaultClear removes a set of x/y coordinates from the data\r\ndefaultClear = 0\r\n# buff indicates the degress of extra buffer space to be added to the map dimensions. May be needed if the map does not display all of the data\r\nbuff = 2\r\nR=6400E3 #radius of earth\r\n# cmaps is a list of all possible default colormaps. Currently the list is incomplete, though maps not in this list may still be plotted\r\ncmaps = ['RdBu', 'Greys','cubehelix','jet','spectral']\r\n\r\ndef getConc(filePath, level, spc):\r\n \"\"\" Get the concentration data for an FST file.\r\n\r\n Returns the data in an array, the datakey as a key and the fileID of the FST file.\r\n \"\"\"\r\n\r\n try:\r\n fileID = rmn.fstopenall(filePath,rmn.FST_RO)\r\n dataKey = rmn.fstinf(fileID,nomvar=spc,ip1=level)['key']\r\n dataRec = rmn.fstluk(dataKey)\r\n concData = dataRec['d']\r\n print ('File {} recorded'.format(filePath))\r\n return {'concData':concData, 'dataKey':dataKey, 'fileID':fileID}\r\n except TypeError:\r\n print('Unable to record file {}. Please see log for details'.format(filePath))\r\n # log an error into the log file\r\n logging.warning('nomvar {} and ip1 {} could not be found for file {}.'.format(fileID, spc, level, filePath))\r\n pass\r\n\r\ndef concDiff(concDataStnd, concDataAlt):\r\n \"\"\" Get the differences between two sets of concentration data.\r\n\r\n Returns the difference between two concentration data sets in an array.\r\n \"\"\"\r\n\r\n # Get the dimensions of the difference data, assume both concentration data sets are the same size\r\n dim1 = concDataStnd.shape[0]\r\n dim2 = concDataStnd.shape[1]\r\n # Initialize an array of zeros.\r\n diffData = np.zeros((dim1,dim2))\r\n # Replace the zeros with differences between the concentrations.\r\n # Note that the difference should be Model-Base\r\n for i in range(dim1):\r\n for j in range(dim2):\r\n diffVal = concDataAlt[i][j]-concDataStnd[i][j]\r\n diffData[i][j] = diffVal\r\n return diffData\r\n\r\ndef getGrid(dataKey, fileID):\r\n \"\"\" Get the grid details in form of lon/lat of the FST file. \"\"\"\r\n\r\n # Get the file metadata, then add on the keypair for 'iunit'\r\n fileMeta = rmn.fstprm(dataKey)\r\n fileMeta['iunit'] = fileID\r\n # Get the grid data and decode it\r\n gridData = rmn.ezqkdef(fileMeta)\r\n gridDecode = rmn.decodeGrid(gridData)\r\n llGridData = rmn.gdll(gridData)\r\n latData = llGridData['lat']\r\n lonData = llGridData['lon']\r\n return {'gridll':llGridData,'gridID':gridData, 'latData':latData,'lonData':lonData}\r\n\r\ndef closeFST(fileID):\r\n \"\"\" Closes the FST file once relevant data has been saved. \"\"\"\r\n\r\n rmn.fstcloseall(fileID)\r\n print ('File has been closed.')\r\n\r\ndef gridCheck(gridStnd, gridAlt):\r\n \"\"\" Does a sanity check in case the grids are different for the FST files. \"\"\"\r\n\r\n if (np.array_equiv(gridStnd['lat'],gridAlt['lat'])) and (np.array_equiv(gridStnd['lon'],gridAlt['lon'])):\r\n True\r\n else:\r\n print('The area of the files do not match each other. Program may not function as expected. See log for more details.')\r\n logging.warning('Grids for current run do not match up. The differences are : \\n' + str(np.setdiff1d(gridStnd,gridAlt)))\r\n\r\ndef maxDimensions(lowLon,highLon,lowLat,highLat,buff):\r\n \"\"\" Get the maximum dimensions of the map.\r\n\r\n Note that this function is still underdevelopment and may not represent the ideal dimensions for the resulting map.\r\n \"\"\"\r\n\r\n lonDiff = radians(highLon - lowLon)\r\n latDiff = radians(highLat - lowLat)\r\n radBuffer = 2*(radians(buff))\r\n yDist = R*(latDiff + radBuffer)\r\n Rad1 = R*cos(lowLat)\r\n Rad2 = R*cos(highLat)\r\n xDist1 = Rad1*(lonDiff + radBuffer)\r\n xDist2 = Rad2*(lonDiff + radBuffer)\r\n xDist = (xDist1+xDist2)/2\r\n return {'xDist':xDist, 'yDist':yDist}\r\n\r\ndef midLatLon(lonData, latData):\r\n \"\"\" Provides an alternate manner in which to calculate the central lon/lat values. \"\"\"\r\n\r\n ni = len(lonData)\r\n nj = len(lonData[0])\r\n #find the middle value between these\r\n if ni%2==0:\r\n if nj%2==0:\r\n midLon=(lonData[ni//2-1,nj//2]+lonData[ni//2,nj//2])/2\r\n midLat=(latData[ni//2,nj//2-1]+latData[ni//2,nj//2])/2\r\n else:\r\n midLon=(lonData[ni//2-1,nj//2]+lonData[ni//2,nj//2])/2\r\n midlat=(latData[ni//2,nj//2-1]+latData[ni//2,nj//2])/2\r\n else:\r\n if nj%2==0:\r\n midLon=(lonData[ni//2,nj//2]+lonData[ni//2,nj//2+1])/2\r\n midLat=(latData[ni//2,nj//2]+latData[ni//2,nj//2+1])/2\r\n else:\r\n midLon=lonData[ni//2,nj//2]\r\n midLat=latData[ni//2,nj//2]\r\n return {'midLat':midLat, 'midLon':midLon}\r\n\r\ndef reverseName(mapType, reverse):\r\n \"\"\" Returns the reverse mapType if reverse=True, otherwise returns mapType. \"\"\"\r\n\r\n if reverse == True:\r\n mapType = mapType + '_r'\r\n return mapType\r\n else:\r\n return mapType\r\n\r\ndef isCmap(mapType):\r\n \"\"\" Checks to see if the mapType is in the list of default colormaps. \"\"\"\r\n\r\n if mapType in cmaps:\r\n return True\r\n else:\r\n print('Warning: Type mapType is not in the list of cmaps, may resort to default cmap.')\r\n # TODO: If cmap is invalid, set cmap = default cmap\r\n # note that this behaviour might be default! May set to cmap 'jet' though\r\n\r\ndef cmapType(cmap,reverse):\r\n \"\"\" Returns map details. \"\"\"\r\n\r\n isCmap(cmap)\r\n mapType = reverseName(cmap,reverse)\r\n return mapType\r\n\r\ndef makeDir(path):\r\n \"\"\" Creates a directory if it doesn't exist.\r\n\r\n Existence errors will be ignored. All other errors will be raised.\r\n \"\"\"\r\n\r\n try:\r\n os.makedirs(path)\r\n except OSError as exc:\r\n if exc.errno == errno.EEXIST and os.path.isdir(path):\r\n pass\r\n else:\r\n raise\r\n\r\ndef plotConc(concData, lonData, latData, saveLoc, modelRun, prtype, ip1, spc, cmapType, bins, minVal, maxVal, extension, name, removed,buff):\r\n \"\"\" Plots and saves concentration data.\r\n\r\n Will plot difference data if difference data was passed.\r\n \"\"\"\r\n\r\n # useful things for determining projection details\r\n lowLon = np.amin(lonData)\r\n lowLat = np.amin(latData)\r\n highLon = np.amax(lonData)\r\n highLat = np.amax(latData)\r\n maxDim = maxDimensions(lowLon,highLon,lowLat,highLat,buff)\r\n midLon = (highLon+lowLon)/2\r\n midLat = (highLat + lowLat)/2\r\n # Uncomment the following lines for an alternative midLatLon calculation\r\n #mids = midLatLon(lonData,latData)\r\n #midLon = mids['midLon']\r\n #midLat = mids['midLat']\r\n max_width = maxDim['xDist']\r\n max_height = maxDim['yDist']\r\n # Initialize the figure\r\n fig = plt.figure(figsize=(8,8))\r\n\r\n # Create the map based on projection type\r\n if (prtype=='ortho') or (prtype == 'nsper') or (prtype == 'laea') or (prtype == 'aeqd') or (prtype == 'gnom') or (prtype == 'lcc'):\r\n concMap = Basemap(projection=prtype, resolution = 'c', lon_0=midLon, lat_0=midLat, width=max_width, height=max_height)\r\n elif prtype == 'stere':\r\n concMap = Basemap(projection=prtype, lon_0=midLon,lat_0=midLat,width=max_width,height=max_height)\r\n elif (prtype == 'cyl') or (prtype == 'merc'):\r\n concMap = Basemap(projection=prtype, resolution='c', llcrnrlat=lowLat, urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon)\r\n elif (prtype == 'aea') or (prtype == 'eqdc'):\r\n concMap = Basemap(projection = prtype, lon_0=midLon, lat_0=midLat, llcrnrlat=lowLat, urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon)\r\n else:\r\n print('Error: Could not generate map. Try a different projection.')\r\n # Can check the available basemap types and add to existing if statements\r\n\r\n # Add in other map details\r\n mapColor = cmapType\r\n mapBins = bins\r\n # if stripping the borders of the data....\r\n if removed != 0:\r\n ni = len(lonData)\r\n nj = len(lonData[0])\r\n n_pil = removed\r\n x, y = concMap(lonData[n_pil:ni-n_pil,n_pil:nj-n_pil], latData[n_pil:ni-n_pil,n_pil:nj-n_pil])\r\n concMap.pcolormesh(x,y,concData[n_pil:ni-n_pil,n_pil:nj-n_pil],cmap=plt.cm.get_cmap(mapColor,mapBins))\r\n else:\r\n x, y = concMap(lonData, latData)\r\n concMap.pcolormesh(x, y, concData, cmap=plt.cm.get_cmap(mapColor, mapBins))\r\n concMap.drawcoastlines(color='lightgray')\r\n concMap.drawcountries(color='gray')\r\n concMap.drawstates(color='gray')\r\n # Comment out the following to remove lonlat lines\r\n concMap.drawmeridians(np.arange(0,360,10), labels=[0,0,0,1], fontsize=6)\r\n concMap.drawparallels(np.arange(-180,180,10), labels=[1,0,0,0],fontsize=6)\r\n\r\n # Add colorbar and details\r\n #TODO: Fix the set label option for the colorbar, right now the colorbar doesn't have a title\r\n cbar = plt.colorbar(extend = extension, shrink=0.5)\r\n cbar.set_label=('Concentration: '+spc)\r\n plt.clim(minVal, maxVal)\r\n\r\n # Name and save the figure\r\n hy = ((os.popen('r.ip1 {}'.format(ip1))).read()).lstrip()\r\n plt.title('{}, {} \\n hy: {}, Spc: {}'.format(name,modelRun, hy,spc))\r\n fig.savefig(os.path.join(saveLoc, modelRun) + '_' + spc + '_' + name + '.png', dpi=300, bbox_inches='tight', pad_inches=0.3)\r\n\r\n plt.close('all')\r\n\r\ndef diffPlot(fileRun=defaultFile, baseFile=defaultPathStnd+defaultFile, modelFile=defaultPathStnd+defaultFile, savePath=defaultSave, level=defaultIp1, species=defaultSpc, buffering = buff, mapType=defaultDiffCmap, reverse=False, extension='neither', projType='stere', vmin=None, vmax=None, totalBins=defaultBins,partName='test',removed=defaultClear):\r\n \"\"\" Execute difference plot creation. \"\"\"\r\n\r\n logging.basicConfig(filename='ConcentrationPlotter.log', level=logging.DEBUG,format='%(asctime)s %(message)s')\r\n\r\n # print the min number of messages produced by librmn\r\n rmn.fstopt(rmn.FSTOP_MSGLVL,rmn.FSTOPI_MSG_CATAST)\r\n # get the data for the standard first, close file to continue\r\n concDataStnd = getConc(baseFile,level,species)\r\n if concDataStnd == None:\r\n return None\r\n else:\r\n gridStnd = getGrid(concDataStnd['dataKey'],concDataStnd['fileID'])\r\n closeFST(concDataStnd['fileID'])\r\n # get the data for the alternative, close file to continue\r\n concDataAlt = getConc(modelFile,level,species)\r\n if concDataAlt == None:\r\n return None\r\n else:\r\n gridAlt = getGrid(concDataAlt['dataKey'],concDataAlt['fileID'])\r\n closeFST(concDataAlt['fileID'])\r\n # get the difference between the datasets\r\n diffData = concDiff(concDataStnd['concData'],concDataAlt['concData'])\r\n # check that the grid sizes make sense\r\n gridCheck(gridStnd['gridll'],gridAlt['gridll'])\r\n # minor cleanup\r\n cmapDetails = cmapType(mapType,reverse)\r\n makeDir(savePath)\r\n # plot and save the figure\r\n plotConc(diffData, gridStnd['lonData'], gridStnd['latData'], savePath, fileRun, projType, level, species,cmapDetails, totalBins, vmin, vmax, extension, partName,removed,buffering)\r\n\r\ndef concPlot(fileRun=defaultFile, modelFile=defaultPathStnd+defaultFile, savePath=defaultSave, level=defaultIp1, species=defaultSpc, buffering=buff, mapType=defaultConcCmap, reverse=False, extension='neither', projType='stere', vmin=None, vmax=None, totalBins=defaultBins, partName='test', removed=defaultClear):\r\n \"\"\" Execute the concentration plot creation. \"\"\"\r\n\r\n logging.basicConfig(filename='ConcentrationPlotter.log', level=logging.DEBUG,format='%(asctime)s %(message)s')\r\n\r\n # print the min number of messages produced by librmn\r\n rmn.fstopt(rmn.FSTOP_MSGLVL,rmn.FSTOPI_MSG_CATAST)\r\n # get concentration and grid data, then close file\r\n concData = getConc(modelFile,level,species)\r\n if concData == None:\r\n return None\r\n else:\r\n gridData = getGrid(concData['dataKey'],concData['fileID'])\r\n closeFST(concData['fileID'])\r\n # minor cleanup\r\n cmapDetails =cmapType(mapType, reverse)\r\n makeDir(savePath)\r\n # plot and save the figure\r\n plotConc(concData['concData'], gridData['lonData'], gridData['latData'], savePath, fileRun, projType, level, species, cmapDetails, totalBins, vmin, vmax, extension, partName, removed, buffering)\r\n\r\n# To run this program alone, uncomment one of the following and include desired parameters\r\n# Otherwise the defaults will run (and I can't guarantee it'll work if the files have been moved!)\r\n\r\n# diffPlot()\r\n# concPlot()\r\n","sub_path":"ConcentrationCrop/ConcPlotter Zoom/ConcentrationPlotter.py","file_name":"ConcentrationPlotter.py","file_ext":"py","file_size_in_byte":13619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"120437879","text":"\"\"\"\nhttps://leetcode.com/problems/gas-station/\nBrute force: Try to start with every position, simulate it.\nTime Complexity: O(N^2)\n\nWhen we go through the position, we know the current start point is not possible when we found that there exists an i, such that,\n\n1. For every j in (start, i), sum(gas[start:j+1]) - sum(cost[start:j+1]) > 0 ==> make sure we can reach i\n2. sum(gas[start:i+1]) - sum(cost[start:i+1]) < 0 ==> we cannot go from i to i + 1.\n\nWhen we found such a position, we know we cannot start from any point in the range [start, i], so we need to start from i + 1.\nIf (i + 1) could be the starting position, we need to make sure (i+1) could reach the end, and,\nsum(gas[i+1:]) - sum(cost[i+1:]) + sum(gas[:i+1]) - sum(cost[:i+1]) >= 0\n\nTime complexity: O(N)\n\"\"\"\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n n = len(gas)\n tank, start, total = 0, 0, 0\n for i in range(n):\n tank = tank + gas[i] - cost[i]\n if tank < 0:\n start = i + 1\n total += tank\n tank = 0\n if total + tank < 0:\n return -1\n else:\n return start\n","sub_path":"0134_GasStation.py","file_name":"0134_GasStation.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"547689868","text":"from django.shortcuts import render\nfrom .models import *\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom hashlib import md5\nfrom django.utils import timezone\nimport random\nimport os\nfrom .sendVerCode import codeSender\nfrom cv import faceDet\nfrom cv.faceMerge import faceMerge\nimport json\nfrom django.forms.models import model_to_dict\nimport time\n\ndef exceptError(func):\n \"错误记录装饰器\"\n def wrap(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n \"在errorRecord文件中记录错误\"\n with open(\"errorRecord\", 'a') as f:\n f.write(f\"{e}\\n\")\n return JsonResponse(Auth.res(\"未知错误\", \"\"))\n return wrap\n\n@csrf_exempt\n@exceptError\ndef uploadFaceImg(request):\n \"上传人脸图片\"\n res = {\n \"mes\": \"\",\n \"data\": \"\"\n }\n uploadImgDir = os.path.join(\"static\", \"FaceImg\")\n # 读取post中的图片\n fd = request.FILES['pic'].read()\n userId = request.POST.get(\"id\")\n name = md5(fd).hexdigest()\n # 查询是否存在相应用户\n try:\n user = UserInfo.objects.get(id=userId)\n except UserInfo.DoesNotExist:\n return JsonResponse(Auth.error(1))\n\n # 查询图片是否已经存在\n try:\n img = FaceImg.objects.get(md5=name)\n except FaceImg.DoesNotExist:\n filePath = os.path.join(uploadImgDir, f\"{name}.jpg\")\n # 将图片字节流写入文件\n with open(filePath, \"wb\") as f:\n f.write(fd)\n \n # 查询图片对象是否存在\n try:\n img = FaceImg.objects.get(user=user)\n except FaceImg.DoesNotExist:\n img = FaceImg(md5=name, path=filePath, user=user)\n img.save()\n else:\n img.path=filePath\n img.save()\n \n else:\n filePath = img.path\n\n\n # 调用人脸检测器检测是否由人脸\n if not faceDet.hasFace(filePath):\n res['mes'] = \"该图片未包含人脸,请重新上传\"\n else:\n # windows系统path处理\n if \"\\\\\" in filePath:\n filePath = filePath.replace(\"\\\\\", \"/\")\n res['data'] = f\"/{filePath}\"\n return JsonResponse(res)\n\n\ndef faceMerge_(request):\n model = request.GET.get('modelId')\n userList = request.GET.get(\"userList\")\n try:\n model = ModelImg.objects.get(id=model)\n dstList = [UserInfo.objects.get(id=int(i)).faceImg.path for i in userList.split(\",\")]\n except ModelImg.DoesNotExist:\n return JsonResponse(Auth.error(1))\n \n outImg = f\"static/outImg/{str(int(time.time()*1000))}.jpg\"\n faceMerge(modelImg=model.path.replace(\"\\\\\", '/'), \n dstList=[i.replace(\"\\\\\", '/') for i in dstList], \n faces=json.loads(model.faces),\n outImg=outImg)\n return JsonResponse(Auth.res(\"\", outImg))\n\n\ndef getModels(request):\n models = [{\"id\": i.id, \"path\": i.path} for i in ModelImg.objects.all()]\n return JsonResponse(Auth.res(\"\", models))\n\n\n@exceptError\ndef getAllClass(request):\n res = []\n for class_ in Class.objects.all():\n res.append({\n \"id\": class_.id,\n \"name\": class_.name, \n })\n return JsonResponse(Auth.res(\"\", res))\n\n@exceptError\ndef getUserByClass(request):\n classId = request.GET.get(\"classId\")\n res = []\n mes = \"\"\n if classId:\n try:\n class_ = Class.objects.get(id=classId)\n except Class.DoesNotExist:\n return JsonResponse(Auth.error(1))\n for stu in class_.students.all():\n try:\n faceimg = \"/\" + stu.faceImg.path.replace(\"\\\\\", \"/\")\n except UserInfo.faceImg.RelatedObjectDoesNotExist:\n faceimg = None\n res.append({\n \"id\": stu.id,\n \"name\": stu.username,\n \"faceImg\": faceimg,\n })\n else:\n mes = \"参数错误\"\n return JsonResponse(Auth.res(mes, res))\n\nclass Auth:\n\n sender = codeSender()\n\n @classmethod\n def userSet(cls, request):\n username = request.GET.get(\"username\")\n phoneNumber = request.GET.get(\"phoneNumber\")\n userId = request.GET.get(\"id\")\n\n \n # 都不为空\n if username and phoneNumber:\n try:\n user = UserInfo.objects.get(id=userId)\n except UserInfo.DoesNotExist:\n return JsonResponse(cls.error(1))\n user.username = username\n user.phoneNumber = phoneNumber\n user.save()\n return JsonResponse(cls.res(\"\", \"修改成功\"))\n return JsonResponse(cls.error(1))\n\n @classmethod\n @csrf_exempt\n def passwordSet(cls, request):\n curPass = request.POST.get(\"curPass\")\n Pass = request.POST.get(\"Pass\")\n userId = request.POST.get(\"id\")\n\n try:\n user = UserInfo.objects.get(id=userId).user\n except:\n return JsonResponse(cls.error(1))\n if user.check_password(curPass):\n user.set_password(Pass)\n user.save()\n return JsonResponse(cls.res(\"\", \"修改成功\"))\n return JsonResponse(cls.res(\"当前密码错误\", \"\"))\n\n @staticmethod\n def detVerCode(verCode, email):\n res = \"\"\n try:\n code = VerCode.objects.get(email=email)\n if str(code.code) == str(verCode):\n res = ''\n else:\n res = \"验证码错误\"\n except VerCode.DoesNotExist:\n res = \"请先获取验证码\"\n return res\n\n @staticmethod\n def res(mes, data=\"\"):\n return {\"mes\": mes, \"data\": data}\n\n @classmethod\n def error(cls, mesId):\n mes = \"\"\n # 错误分类\n if mesId == 0:\n mes = \"数据库链接错误\"\n elif mesId == 1:\n mes = \"参数错误\"\n else:\n mes = \"未知错误\"\n return cls.res(mes, \"\")\n \n @classmethod\n def senVerCode(cls, request):\n \"发送验证码\"\n email = request.GET.get(\"email\")\n try:\n u = User.objects.filter(email=email)\n assert u.count() > 0\n return JsonResponse(cls.res(\"该邮箱已注册\"))\n except AssertionError:\n pass\n\n # 卡发送时间\n try:\n eCode = VerCode.objects.get(email=email)\n if (timezone.now() - eCode.time).seconds <= 60:\n return JsonResponse(cls.res(\"发送间隔太小,请等会再尝试\"))\n except VerCode.DoesNotExist:\n pass\n \n # 随机生成验证码\n code = ''.join([str(random.randint(0,9)) for i in range(6)])\n # 调用发送模块\n res = cls.sender.send(email, code)\n if \"成功\" in res:\n try:\n v = VerCode.objects.get(email=email)\n v.code = code\n v.time = timezone.now()\n v.save()\n except VerCode.DoesNotExist:\n VerCode(email=email, code=code, time=timezone.now()).save()\n return JsonResponse(cls.res(\"\", res))\n\n @classmethod\n @csrf_exempt\n def monitorLogin(cls, request):\n \"管理员登录\"\n email = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n \n # 判断用户是否存在\n try:\n user = User.objects.get(username=email)\n except User.DoesNotExist:\n return JsonResponse(cls.res(\"用户不存在\", \"\"))\n\n if user.check_password(password):\n if user.userinfo.Class.monitor == user.userinfo:\n userinfo = UserInfo.objects.get(user=user)\n return JsonResponse(cls.res(\"\", {\n \"user\": userinfo.id,\n \"class\": userinfo.Class.id\n }))\n else:\n return JsonResponse(cls.res(\"非管理员用户不允许登录\", \"\"))\n else:\n return JsonResponse(cls.res(\"用户名或密码错误\", \"\"))\n\n\n\n @classmethod\n def getUserInfo(cls, request):\n userId = request.GET.get(\"id\")\n if userId:\n try:\n userInfo = UserInfo.objects.get(id=userId)\n except User.DoesNotExist:\n return JsonResponse(cls.error(1))\n else:\n try:\n faceimg = \"/\" + userInfo.faceImg.path.replace(\"\\\\\", \"/\")\n except UserInfo.faceImg.RelatedObjectDoesNotExist:\n faceimg = None\n user = userInfo.user\n res = {\n \"username\": userInfo.username,\n \"email\": user.username,\n \"phoneNumber\": userInfo.phoneNumber,\n \"class\": userInfo.Class.name,\n \"faceImg\": faceimg\n }\n return JsonResponse(cls.res(\"\", res))\n else:\n return JsonResponse(cls.error(1))\n\n @classmethod\n @csrf_exempt\n @exceptError\n def login(cls, request):\n email = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n \n try:\n user = User.objects.get(username=email)\n except User.DoesNotExist:\n return JsonResponse(cls.res(\"用户不存在\", \"\"))\n if user.check_password(password):\n userinfo = UserInfo.objects.get(user=user)\n return JsonResponse(cls.res(\"\", userinfo.id))\n else:\n return JsonResponse(cls.res(\"用户名或密码错误\", \"\"))\n\n @classmethod\n @csrf_exempt # 使此次请求忽略csrf校验\n @exceptError\n def register(cls, request):\n \"注册\"\n res = {}\n username = request.POST.get(\"username\")\n email = request.POST.get(\"email\")\n password = request.POST.get(\"password\")\n phoneNumber = request.POST.get(\"phoneNumber\")\n verCode = request.POST.get(\"verCode\")\n\n # 验证验证码的正确性\n verCodeRes = cls.detVerCode(verCode, email)\n if verCodeRes:\n return JsonResponse(cls.res(verCode))\n # 前端传来的班级\n _class = request.POST.get(\"class\")\n\n \n\n\n classExist = True\n\n # 创建用户\n try:\n User.objects.create_user(email, email, password)\n except Exception as a:\n print(a)\n return JsonResponse(cls.error(0)) \n \n # 如果班级不存在就创建班级\n try:\n class_ = Class.objects.get(name=_class)\n except Class.DoesNotExist:\n # 后端班级对象\n classExist = False\n class_ = Class(name=_class)\n class_.save()\n \n try:\n user = User.objects.get(username=email)\n userInfo = UserInfo(user=user, username=username , Class=class_, phoneNumber=phoneNumber)\n userInfo.save()\n except Exception as a:\n print(a)\n return JsonResponse(cls.error(0)) \n \n if not classExist:\n class_.monitor = userInfo\n class_.save()\n\n return JsonResponse(cls.res(\"\", \"注册成功\"))","sub_path":"backend/common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"7530512","text":"\"\"\"\nModule designed to perform file and directory ops\n\"\"\"\n\nfrom io import BytesIO\nimport os\nimport shutil\nfrom zipfile import ZipFile\n\nUPLOADS_DIR = '/tmp/toUpload'\nXML_UNZIPPED_FOLDER = '/tmp/unzipped_xml'\nJSON_FOLDER = '/tmp/toUpload/json'\nAVRO_FOLDER = '/tmp/toUpload/avro'\nZIPPED_FILES = '/tmp/toUpload/zips'\n\n\ndef clean_tmp_dir():\n \"\"\"\n Clean temporal directory\n \"\"\"\n\n if os.path.exists(XML_UNZIPPED_FOLDER):\n shutil.rmtree(XML_UNZIPPED_FOLDER, ignore_errors=True)\n\n os.mkdir(XML_UNZIPPED_FOLDER)\n\n if os.path.exists(UPLOADS_DIR):\n shutil.rmtree(UPLOADS_DIR, ignore_errors=True)\n\n os.mkdir(UPLOADS_DIR)\n os.mkdir(JSON_FOLDER)\n os.mkdir(AVRO_FOLDER)\n\n\ndef get_signals_zipped_file(s3_client, file_path, landing_bucket):\n \"\"\"\n Get zipped file which contains signals in xml format\n :param s3_client: s3 client\n :param file_path: target file path\n :param landing_bucket: landing bucket name\n :return: a ZipFile which contains signals\n \"\"\"\n stream_body = (s3_client.Bucket(landing_bucket).Object(file_path).get())['Body'].read()\n in_memory = BytesIO(stream_body)\n return ZipFile(in_memory, \"r\")\n\n\ndef unzip_signals_file(zipped_file):\n \"\"\"\n Unzip signals zip file\n :param zipped_file: signals zip file\n :return: a signals list\n \"\"\"\n zipped_file.extractall(os.path.join(XML_UNZIPPED_FOLDER))\n zipped_file.close()\n return [os.path.join(XML_UNZIPPED_FOLDER, f) for f in os.listdir(XML_UNZIPPED_FOLDER) if\n os.path.isfile(os.path.join(XML_UNZIPPED_FOLDER, f))]\n\n\ndef get_signal_list(s3_client, bucket, key):\n \"\"\"\n Receive a bucket name and key and returns a signals list.\n :param s3_client:\n :param bucket:\n :param key:\n :return:\n \"\"\"\n zipped_file = get_signals_zipped_file(s3_client, key, bucket)\n signal_file_list = unzip_signals_file(zipped_file)\n return signal_file_list\n","sub_path":"src/signal-preprocessor/file_handler.py","file_name":"file_handler.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"230978398","text":"from django import forms\nfrom sio.models import *\n\nclass CreateStudentForm(forms.ModelForm):\n class Meta:\n model = Student\n exclude = ()\n\n def clean_andrew_id(self):\n andrew_id = self.cleaned_data.get('andrew_id')\n if Student.objects.filter(andrew_id__exact=andrew_id):\n raise forms.ValidationError(\"AndrewID is already taken.\")\n return andrew_id\n\n\nclass CreateCourseForm(forms.ModelForm):\n class Meta:\n model = Course\n exclude = ('students', ) \n\n def clean_course_number(self):\n course_number = self.cleaned_data.get('course_number')\n if Course.objects.filter(course_number__exact=course_number):\n raise forms.ValidationError(\"Course %s already exists.\" % \n course_number)\n return course_number\n\n","sub_path":"in-class/2016-09-28 ModelForms/hand-out code/sio/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"326904141","text":"from flask import Flask, render_template, session, redirect, url_for, escape, request, json, g, flash, jsonify\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.openid import OpenID\nfrom flask_oauth import OAuth\nimport urllib\nimport re\nimport os\nfrom database import init_db, db_session, Base\nfrom models import User as User\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\napp.config.update(dict(\n\tSECRET_KEY='development key',\n\tDEBUG=True,\n\tSTEAM_API_KEY=os.environ['STEAM_API_KEY'],\n\tTWITTER_CONSUMER_KEY=os.environ['TWITTER_CONSUMER_KEY'],\n\tTWITTER_CONSUMER_SECRET=os.environ['TWITTER_CONSUMER_SECRET'],\n))\n\noid = OpenID(app)\n\noauth = OAuth()\n\n_steam_id_re = re.compile('steamcommunity.com/openid/id/(.*?)$')\n\ninit_db()\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n\tdb_session.remove()\n\n# bridge steam api\ndef get_steam_userinfo(steam_id):\n\toptions = {\n\t\t'key': app.config['STEAM_API_KEY'],\n\t\t'steamids': steam_id\n\t}\n\turl = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0001/?%s' % urllib.urlencode(options)\n\tresponse = json.load(urllib.urlopen(url))\n\tresponse_dict = {\n\t\t'avatar': response['response']['players']['player'][0]['avatar'] or '',\n\t\t'personaname': response['response']['players']['player'][0]['personaname'] or '',\n\t} \n\treturn response_dict\n\n@app.route('/')\ndef home_handler():\n\tif g.user:\n\t\treturn redirect('/dashboard')\n\telse:\n\t\treturn render_template('index.html')\n\n@app.route('/about')\ndef about_handler():\n\tif g.user:\n\t\treturn render_template('about.html', logged=True)\n\telse:\n\t\treturn render_template('about.html', logged=False)\n\n@app.route('/contact')\ndef contact_hanlder():\n\tif g.user:\n\t\treturn render_template('contact.html', logged=True)\n\telse:\n\t\treturn render_template('contact.html', logged=False)\n\n@app.route('/dashboard')\ndef dashboard_handler():\n\tif g.user:\n\t\tsession['tweet_format_string'] = g.user.tweet_format_string\n\t\tsession['tweet_twitch_username'] = g.user.tweet_twitch_username\n\t\tsession['tweet_custom_win'] = g.user.tweet_custom_win\n\t\tsession['tweet_custom_loss'] = g.user.tweet_custom_loss\n\n\t\treturn render_template('dashboard.html', logged=True)\n\telse:\n\t\treturn redirect('/')\n\n@app.route('/dashboard', methods=['POST'])\ndef dashboard_post_handler():\n\tg.user = User.query.get(session['user_id'])\n\n\tg.user.tweet_format_string = request.form['tweet-format']\n\tg.user.tweet_twitch_username = request.form['twitch']\n\tg.user.tweet_custom_win = request.form['win']\n\tg.user.tweet_custom_loss = request.form['lose']\n\tdb_session.commit()\n\n\tsession['tweet_format_string'] = g.user.tweet_format_string\n\tsession['tweet_twitch_username'] = g.user.tweet_twitch_username\n\tsession['tweet_custom_win'] = g.user.tweet_custom_win\n\tsession['tweet_custom_loss'] = g.user.tweet_custom_loss\n\n\treturn jsonify({\n\t\t\t'success': True, # can be False if something went wrong\n\t\t\t'message': \"Successfully saved settings\",\n\t\t}\n\t)\n\n@app.route('/dashboard/filters', methods=['POST'])\ndef dashboard_filters_post_handler():\n\tg.user = User.query.get(session['user_id'])\n\n\treturn jsonify({\n\t\t\t'success': True, # can be False if something went wrong\n\t\t\t'message': \"Successfully added filter\"\n\t\t}\n\t)\n\n@app.route('/settings')\ndef settings_handler():\n\tif g.user:\n\t\treturn render_template('settings.html', logged=True)\n\telse:\n\t\treturn redirect('/')\n\n# steam login\n\n@app.route('/login')\n@oid.loginhandler\ndef login_handler():\n\tif g.user is not None:\n\t\treturn redirect(oid.get_next_url())\n\treturn oid.try_login('http://steamcommunity.com/openid')\n\n@oid.after_login\ndef create_or_login(resp):\n\tmatch = _steam_id_re.search(resp.identity_url)\n\tg.user = User.get_or_create(match.group(1), db_session)\n\tsteamdata = get_steam_userinfo(g.user.steam_id)\n\tg.user.steam_nickname = steamdata['personaname']\n\tg.user.steam_avatar = steamdata['avatar']\n\tdb_session.commit()\n\t\n\tsession['user_id'] = g.user.id\n\tsession['nickname'] = g.user.steam_nickname\n\tsession['avatar'] = g.user.steam_avatar\n\tif g.user.twitter_nickname != '':\n\t\tsession['twitter_user'] = g.user.twitter_nickname\n\n\tflash('You are logged in as %s' % g.user.steam_nickname)\n\n\treturn redirect(oid.get_next_url())\n\n@app.before_request\ndef before_request():\n\tg.user = None\n\tif 'user_id' in session:\n\t\tg.user = User.query.get(session['user_id'])\n\n@app.route('/logout')\ndef logout():\n\tsession.clear()\n\treturn redirect(oid.get_next_url())\n\n# twitter login\n\ntwitter = oauth.remote_app('twitter',\n\tbase_url='https://api.twitter.com/1.1/',\n\trequest_token_url='https://api.twitter.com/oauth/request_token',\n\taccess_token_url='https://api.twitter.com/oauth/access_token',\n\tauthorize_url='https://api.twitter.com/oauth/authorize',\n\tconsumer_key=app.config['TWITTER_CONSUMER_KEY'],\n\tconsumer_secret=app.config['TWITTER_CONSUMER_SECRET']\n)\n\n@twitter.tokengetter\ndef get_twitter_token(token=None):\n\treturn session.get('twitter_token')\n\n@app.route('/twitter_login')\ndef twitter_login_handler():\n\treturn twitter.authorize(callback=url_for('oauth_authorized', next=request.args.get('next') or request.referrer or None))\n\n@app.route('/twitter_logout')\ndef twitter_logout_handler():\n\tg.user = User.query.get(session['user_id'])\n\n\tg.user.twitter_access_token = ''\n\tg.user.twitter_access_token_secret = ''\n\tg.user.twitter_nickname = ''\n\tdb_session.commit()\n\n\tsession.pop('twitter_user', None)\n\n\tflash('You were signed out of Twitter.')\n\n\treturn redirect('/settings')\n\n@app.route('/oauth_authorized')\n@twitter.authorized_handler\ndef oauth_authorized(resp):\n\tnext_url = request.args.get('next') or url_for('dashboard')\n\tif resp is None:\n\t\tflash(u'You denied the request to sign in.')\n\t\treturn redirect(next_url)\n\n\tg.user = User.query.get(session['user_id'])\n\n\tg.user.twitter_access_token = resp['oauth_token']\n\tg.user.twitter_access_token_secret = resp['oauth_token_secret']\n\tg.user.twitter_nickname = resp['screen_name']\n\tdb_session.commit()\n\n\tsession['twitter_user'] = resp['screen_name']\n\t\n\tflash('You were signed in as %s' % resp['screen_name'])\n\n\treturn redirect(next_url)\n\n# start server\n\nif __name__ == '__main__':\n\tapp.run(port=38165, debug=True)\n","sub_path":"dotabrag.py","file_name":"dotabrag.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"133437070","text":"'''\n1111111111111\n\n\n\n使用前pip 一下transformers 保证版本最新.\n'''\n\n\n\n\n\n\n\n# https://www.ctolib.com/amp/brightmart-albert_zh.html\n\nfrom transformers import *\nimport torch\nfrom torch.nn.functional import softmax\n\n\n\n\nfrom transformers import *\n\n\n\n\n\npretrained = 'voidful/albert_chinese_xxlarge'\ntokenizer = BertTokenizer.from_pretrained(pretrained) # 主要这里面的tokenizer是bert的.\n\n\n\nquestion, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n# 看看这个函数怎么用\ntokenizer.encode_plus(question, text,) # 就是编码成 albert的输入格式, 一个input(里面是2句话做好了sep,并且有token,表示句子顺序的,还有attentionmask用于设置padding的.\n\n\n\n\n\nmodel = AlbertForSequenceClassification.from_pretrained(pretrained)\n\ninputtext = \"今天[MASK]情很好\" # 编码后第一个位置是cls,所以msk的索引是3\n#计算mask所在的索引位置,\n\nAutoModelWithLMHead\n\n\n'''\n正规运行的模型一共有4个:\nAlbertForMaskedLM --------输入一个mask文本,来返回maks的真正内容.\n\n\nAlbertForSequenceClassification \"\"\"Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n \n \nAlbertForTokenClassification @add_start_docstrings(\n \"\"\"Albert Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. \"\"\",\n ALBERT_START_DOCSTRING,\n)\n\n\n\nAlbertForQuestionAnswering \"\"\"Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n'''\n\n\n\n\n\n\n\n\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\nmodel = AlbertForMaskedLM.from_pretrained(pretrained)\n\n\n\nmaskpos = tokenizer.encode(inputtext, add_special_tokens=True).index(103)\n\ninput_ids = torch.tensor(tokenizer.encode(inputtext, add_special_tokens=True)).unsqueeze(0) # Batch size 1\noutputs = model(input_ids, masked_lm_labels=input_ids)\nloss, prediction_scores = outputs[:2]\nlogit_prob = softmax(prediction_scores[0, maskpos]).data.tolist()\npredicted_index = torch.argmax(prediction_scores[0, maskpos]).item()\npredicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]\nprint(predicted_token,logit_prob[predicted_index])\n\n\n\n\n'''\n下面进行使用hugging face 进行模型训练.\n'''\nmodel.num_parameters()\n# model.train()\n\n\nfrom transformers import LineByLineTextDataset\n\ndataset = LineByLineTextDataset(\n tokenizer=tokenizer,\n file_path=\"./lunyu.txt\",\n block_size=256,\n)\nfrom transformers import DataCollatorForLanguageModeling\n\ndata_collator = DataCollatorForLanguageModeling(\n tokenizer=tokenizer, mlm=True, mlm_probability=0.15\n)\n\n\nfrom transformers import Trainer, TrainingArguments\n\ntraining_args = TrainingArguments(\n output_dir=\"./lunyuAlbert\",\n overwrite_output_dir=True,\n num_train_epochs=20,\n per_gpu_train_batch_size=16,\n save_steps=2000,\n save_total_limit=2,\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n data_collator=data_collator,\n train_dataset=dataset,\n prediction_loss_only=True,\n)\n\n# %%time\ntrainer.train()\n\n\n\n\n\n\n\n'''\n模型名\tMODEL_NAME\nalbert_tiny_google_zh\tvoidful/albert_chinese_tiny\nalbert_small_google_zh\tvoidful/albert_chinese_small\nalbert_base_zh (from google)\tvoidful/albert_chinese_base\nalbert_large_zh (from google)\tvoidful/albert_chinese_large\nalbert_xlarge_zh (from google)\tvoidful/albert_chinese_xlarge\nalbert_xxlarge_zh (from google)\tvoidful/albert_chinese_xxlarge\n'''\n\n\n\n\nprint(1)\n\n\n\n'''\n调用简单:去https://huggingface.co/voidful/albert_chinese_xxlarge\n上面搜索模型,然后\n'''\n\nfrom transformers import AlbertTokenizer, AlbertForSequenceClassification\nimport torch\n\ntokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')\nmodel = AlbertForSequenceClassification.from_pretrained('albert-base-v2')\ninput_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\nlabels = torch.tensor([1]).unsqueeze(0) # Batch size 1\noutputs = model(input_ids, labels=labels)\nloss, logits = outputs[:2]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"albert使用/22222albert.py","file_name":"22222albert.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"629894706","text":"from .models import Question, Answer, Subject\nfrom io import BytesIO\nfrom reportlab.pdfgen import *\nfrom reportlab.lib.pagesizes import *\nfrom reportlab.lib import utils\n\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Indenter\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\n\nimport random\n\n\nclass PDFWriter():\n\tdef __init__(self, buffer, page_size):\n\t\tself.buffer = buffer\n\t\tif page_size == 'A4':\n\t\t\tself.page_size = A4\n\t\telif page_size == 'Letter':\n\t\t\tself.page_size = letter\n\t\tself.width, self.height = self.page_size\n\n\tdef generate_exam(self, title, question_ids):\n\t\tdocument = SimpleDocTemplate(self.buffer, rightMargin = 72, leftMargin = 72, topMargin = 30, bottomMargin = 72, pageSize = self.page_size)\n\t\tstyles = getSampleStyleSheet()\n\t\tdata = []\n\t\tcorrect_answers = []\n\t\tdata.append(Paragraph(\"Name:__________________________\", styles['Normal']))\n\t\tdata.append(Spacer(self.width, self.height/48))\n\t\tdata.append(Paragraph(title, styles['Title']))\n\t\tdata.append(Spacer(self.width, self.height/36))\n\t\tquestion_number = 1;\n\t\tfor q_id in question_ids:\n\t\t\tquestion = Question.objects.get(pk = q_id)\n\t\t\timages = question.image_set.all()\n\n\t\t\t\n\t\t\tfor image in images:\n\t\t\t\tif(image.image_field):\n\t\t\t\t\timg = utils.ImageReader(image.image_field)\n\t\t\t\t\twidth, height = img.getSize()\n\n\t\t\t\t\tif width > self.width or height > self.height:\n\t\t\t\t\t\taspect = height/float(width)\n\t\t\t\t\t\twidth = self.width*0.9\n\t\t\t\t\t\theight = aspect*width\n\n\n\n\t\t\t\t\tprint(image.image_field)\n\t\t\t\t\ti = Image(image.image_field)\n\t\t\t\t\ti.drawWidth = width\n\t\t\t\t\ti.drawHeight = height\n\t\t\t\t\tdata.append(i)\n\n\t\t\tanswers = list(question.answer_set.all())\n\t\t\tdata.append(Paragraph(str(question_number) + \". \"+ question.question_field, styles['Normal']))\n\t\t\tletters = ['a) ', 'b) ', 'c) ', 'd) ', 'f) ', 'g) ']\n\t\t\tcounter = 0\n\n\t\t\trandom.shuffle(answers)\n\t\t\tfor answer in answers:\n\t\t\t\tif answer.correct_answer_field == True:\n\t\t\t\t\tcorrect = str(question_number) + \". \" + letters[counter]\n\t\t\t\t\tcorrect_answers.append(correct.strip(\")\"))\n\t\t\t\tdata.append(Indenter(left = 0.2*inch))\n\t\t\t\tdata.append(Paragraph(letters[counter] + \" \" + answer.answer_field, styles['Normal']))\n\t\t\t\tdata.append(Indenter(left = -0.2*inch))\n\t\t\t\tcounter = counter+1\n\n\t\t\tquestion_number=question_number+1\n\t\t\tdata.append(Spacer(self.width, self.height/30))\n\n\t\tdata.append(PageBreak())\n\t\tdata.append(Paragraph(\"Answer Key\", styles['Title']))\n\t\tfor q in correct_answers:\n\t\t\tdata.append(Paragraph(q, styles['Normal']))\n\n\t\tdocument.build(data)\n\t\tpdf = self.buffer.getvalue()\n\t\tself.buffer.close()\n\t\treturn pdf\n \n\n","sub_path":"exammaker/exams/PDFWriter.py","file_name":"PDFWriter.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"627997668","text":"from .base_page import BasePage\nfrom .locators import ProductPageLocators\nfrom selenium.common.exceptions import NoAlertPresentException\nimport math\n\nclass ProductPage(BasePage):\n def add_to_card(self):\n buttun = self.browser.find_element(*ProductPageLocators.BUTTON_ADD_CARD)\n buttun.click()\n\n def solve_quiz_and_get_code(self):\n alert = self.browser.switch_to.alert\n x = alert.text.split(\" \")[2]\n answer = str(math.log(abs((12 * math.sin(float(x))))))\n alert.send_keys(answer)\n alert.accept()\n try:\n alert = self.browser.switch_to.alert\n print(\"Your code: {}\".format(alert.text))\n alert.accept()\n except NoAlertPresentException:\n print(\"No second alert presented\")\n\n def should_be_message(self):\n message = self.browser.find_element(*ProductPageLocators.PRODUCT_ADD_CARD).text\n product = self.browser.find_element(*ProductPageLocators.PRODUCT).text\n assert message == product, \"message incorect\"\n\n def should_be_cost(self):\n message_cost = self.browser.find_element(*ProductPageLocators.COST_ADD_CARD).text\n product_cost = self.browser.find_element(*ProductPageLocators.PRODUCT_COST).text\n assert product_cost == message_cost, \"cost incorect\"\n\n def should_not_be_success_message(self):\n assert self.is_not_element_present(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be\"\n\n def should_be_disappeared(self):\n assert self.is_disappeared(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be\"","sub_path":"pages/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"477792116","text":"# -*- coding: utf-8 -*-\nimport platform\n\nif platform.system() == 'Darwin':\n UNITY_PATH = r'\"/Applications/Unity/Unity.app/Contents/MacOS/Unity\"'\nelif platform.system() == 'Windows':\n UNITY_PATH = r'\"c:/Program Files/Unity/Editor/Unity.exe\"'\n\nPRODUCT_NAME = \"mcworld\"\n\n#生成的apk或ipa全名\n#产品名_发行公司_v版本号_运行框架_发行版或可调试版\n#mcworld_yy_v1.1.1_mono_release_1970_01_01.apk\n#mcworld_yy_v1.1.1_il2cpp_debug_1970_01_01.apk\n\nGAME_PRODUCT_NAME = \"{0}_v{1}_{2}_{3}_{4}\"\n\ndef GetAndroidProductName(product, version, devmode, backend, time_str):\n return GAME_PRODUCT_NAME.format(product, version,\n backend, devmode, time_str) + \".apk\"\n","sub_path":"product/build/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"299809798","text":"# Orca\n#\n# Copyright 2004-2008 Sun Microsystems Inc.\n# Copyright 2001, 2002 BAUM Retec, A.G.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the\n# Free Software Foundation, Inc., Franklin Street, Fifth Floor,\n# Boston MA 02110-1301 USA.\n\n\"\"\"Provides methods that convert the role name of an Accessible\nobject into localized strings for speech and braille.\"\"\"\n\n__id__ = \"$Id: rolenames.py 4484 2009-01-31 15:40:03Z wwalker $\"\n__version__ = \"$Revision: 4484 $\"\n__date__ = \"$Date: 2009-01-31 10:40:03 -0500 (Sat, 31 Jan 2009) $\"\n__copyright__ = \"Copyright (c) 2004-2008 Sun Microsystems Inc.\"\n__license__ = \"LGPL\"\n\nimport debug\nimport settings\n\nimport pyatspi\n\nfrom orca_i18n import _ # for gettext support\nfrom orca_i18n import C_ # to provide qualified translatable strings\n\n########################################################################\n# #\n# Rolenames derived from atk/atk/atkobject.c:role_items. #\n# #\n########################################################################\n\n#[[[TODO: eitani - These are here for backward compatability, they should \n#disappear]]]\n\nROLE_INVALID = \"invalid\"\nROLE_ACCEL_LABEL = \"accelerator label\"\nROLE_ALERT = \"alert\"\nROLE_ANIMATION = \"animation\"\nROLE_ARROW = \"arrow\"\nROLE_CALENDAR = \"calendar\"\nROLE_CAPTION = \"caption\"\nROLE_CANVAS = \"canvas\"\nROLE_CHECK_BOX = \"check box\"\nROLE_CHECK_MENU_ITEM = \"check menu item\"\nROLE_COLOR_CHOOSER = \"color chooser\"\nROLE_COLUMN_HEADER = \"column header\"\nROLE_COMBO_BOX = \"combo box\"\nROLE_DATE_EDITOR = \"dateeditor\"\nROLE_DESKTOP_ICON = \"desktop icon\"\nROLE_DESKTOP_FRAME = \"desktop frame\"\nROLE_DIAL = \"dial\"\nROLE_DIALOG = \"dialog\"\nROLE_DIRECTORY_PANE = \"directory pane\"\nROLE_DOCUMENT_FRAME = \"document frame\"\nROLE_DRAWING_AREA = \"drawing area\"\nROLE_ENTRY = \"entry\"\nROLE_FILE_CHOOSER = \"file chooser\"\nROLE_FILLER = \"filler\"\nROLE_FONT_CHOOSER = \"fontchooser\"\nROLE_FORM = \"form\"\nROLE_FRAME = \"frame\"\nROLE_GLASS_PANE = \"glass pane\"\nROLE_HEADING = \"heading\"\nROLE_HTML_CONTAINER = \"html container\"\nROLE_ICON = \"icon\"\nROLE_IMAGE = \"image\"\nROLE_INTERNAL_FRAME = \"internal frame\"\nROLE_INPUT_METHOD_WINDOW = \"input method window\"\nROLE_LABEL = \"label\"\nROLE_LAYERED_PANE = \"layered pane\"\nROLE_LINK = \"link\"\nROLE_LIST = \"list\"\nROLE_LIST_ITEM = \"list item\"\nROLE_MENU = \"menu\"\nROLE_MENU_BAR = \"menu bar\"\nROLE_MENU_ITEM = \"menu item\"\nROLE_OPTION_PANE = \"option pane\"\nROLE_PAGE_TAB = \"page tab\"\nROLE_PAGE_TAB_LIST = \"page tab list\"\nROLE_PANEL = \"panel\"\nROLE_PASSWORD_TEXT = \"password text\"\nROLE_POPUP_MENU = \"popup menu\"\nROLE_PROGRESS_BAR = \"progress bar\"\nROLE_PUSH_BUTTON = \"push button\"\nROLE_RADIO_BUTTON = \"radio button\"\nROLE_RADIO_MENU_ITEM = \"radio menu item\"\nROLE_ROOT_PANE = \"root pane\"\nROLE_ROW_HEADER = \"row header\"\nROLE_SCROLL_BAR = \"scroll bar\"\nROLE_SCROLL_PANE = \"scroll pane\"\nROLE_SECTION = \"section\"\nROLE_SEPARATOR = \"separator\"\nROLE_SLIDER = \"slider\"\nROLE_SPLIT_PANE = \"split pane\"\nROLE_SPIN_BOX = \"spinbox\"\nROLE_SPIN_BUTTON = \"spin button\"\nROLE_STATUSBAR = \"statusbar\"\nROLE_TABLE = \"table\"\nROLE_TABLE_CELL = \"table cell\"\nROLE_TABLE_COLUMN_HEADER = \"table column header\"\nROLE_TABLE_ROW_HEADER = \"table row header\"\nROLE_TEAR_OFF_MENU_ITEM = \"tear off menu item\"\nROLE_TERMINAL = \"terminal\"\nROLE_TEXT = \"text\"\nROLE_TOGGLE_BUTTON = \"toggle button\"\nROLE_TOOL_BAR = \"tool bar\"\nROLE_TOOL_TIP = \"tool tip\"\nROLE_TREE = \"tree\"\nROLE_TREE_TABLE = \"tree table\"\nROLE_UNKNOWN = \"unknown\"\nROLE_VIEWPORT = \"viewport\"\nROLE_WINDOW = \"window\"\nROLE_HEADER = \"header\"\nROLE_FOOTER = \"footer\"\nROLE_PARAGRAPH = \"paragraph\"\nROLE_APPLICATION = \"application\"\nROLE_AUTOCOMPLETE = \"autocomplete\"\nROLE_EDITBAR = \"edit bar\"\nROLE_EMBEDDED = \"embedded component\"\n\nclass Rolename:\n \"\"\"Provides localized forms of rolenames for speech and Braille.\n \"\"\"\n\n def __init__(self, rolename, brailleShort, brailleLong, speech):\n \"\"\"Created a new rolename with the given parameters.\n\n Arguments:\n - rolename: the internationalized (e.g., machine) name for the role\n - brailleShort: the localized short string for Braille display\n - brailleLong: the localized long string for Braille display\n - speech: the localized string to speak for speech\n \"\"\"\n\n self.rolename = rolename\n self.brailleShort = brailleShort\n self.brailleLong = brailleLong\n self.speech = speech\n\n# [[[TODO: WDW - the AT-SPI also has getLocalizedRoleName, which might a\n# more appropriate thing to use, as it covers the situation where an app\n# has developed a brand new component with a brand new role. Logged as\n# buzilla bug 319780.]]]\n#\nrolenames = {}\n\nrolenames[ROLE_INVALID] = Rolename(\\\n ROLE_INVALID,\n # Translators: short braille for the rolename of an invalid GUI object.\n # We strive to keep it under three characters to preserve real estate.\n #\n _(\"???\"),\n # Translators: long braille for the rolename of an invalid object.\n # We typically make these 'camel' case.\n #\n _(\"Invalid\"),\n # Translators: spoken words for the rolename of an invalid object.\n #\n _(\"invalid\"))\n\nrolenames[ROLE_ACCEL_LABEL] = Rolename(\n ROLE_ACCEL_LABEL,\n # Translators: short braille for an accelerator (what you see in a menu).\n # We strive to keep it under three characters to preserve real estate.\n #\n _(\"acc\"),\n # Translators: long braille for an accelerator (what you see in a menu).\n # We typically make these 'camel' case.\n #\n _(\"Accelerator\"),\n # Translators: spoken words for an accelerator (what you see in a menu).\n #\n _(\"accelerator\"))\n\nrolenames[ROLE_ALERT] = Rolename(\n ROLE_ALERT,\n # Translators: short braille for the rolename of an alert dialog.\n # NOTE for all the short braille words: they we strive to keep them\n # around three characters to preserve real estate on the braille\n # display. The letters are chosen to make them unique across all\n # other rolenames, and they typically act like an abbreviation.\n #\n _(\"alrt\"),\n # Translators: long braille for the rolename of an alert dialog.\n # NOTE for all the long braille words: we typically make them\n # 'camel' case -- multiple words are bunched together with no\n # spaces between them and the first letter of each word is\n # capitalized.\n #\n _(\"Alert\"),\n # Translators: spoken words for the rolename of an alert dialog.\n # NOTE for all the spoken words: these are the words one would use\n # when speaking.\n #\n _(\"alert\"))\n\nrolenames[ROLE_ANIMATION] = Rolename(\n ROLE_ANIMATION,\n # Translators: short braille for the rolename of an animation widget.\n #\n _(\"anim\"),\n # Translators: long braille for the rolename of an animation widget.\n #\n _(\"Animation\"),\n # Translators: spoken words for the rolename of an animation widget.\n #\n _(\"animation\"))\n\nrolenames[ROLE_ARROW] = Rolename(\n ROLE_ARROW,\n # Translators: short braille for the rolename of an arrow widget.\n #\n _(\"arw\"),\n # Translators: long braille for the rolename of an animation widget.\n #\n _(\"Arrow\"),\n # Translators: spoken words for the rolename of an animation widget.\n #\n _(\"arrow\"))\n\nrolenames[ROLE_CALENDAR] = Rolename(\n ROLE_CALENDAR,\n # Translators: short braille for the rolename of a calendar widget.\n #\n _(\"cal\"),\n # Translators: long braille for the rolename of a calendar widget.\n #\n _(\"Calendar\"),\n # Translators: spoken words for the rolename of a calendar widget.\n #\n _(\"calendar\"))\n\nrolenames[ROLE_CANVAS] = Rolename(\n ROLE_CANVAS,\n # Translators: short braille for the rolename of a canvas widget.\n #\n _(\"cnv\"),\n # Translators: long braille for the rolename of a canvas widget.\n #\n _(\"Canvas\"),\n # Translators: spoken words for the rolename of a canvas widget.\n #\n _(\"canvas\"))\n\nrolenames[ROLE_CAPTION] = Rolename(\n ROLE_CAPTION,\n # Translators: short braille for the rolename of a caption (e.g.,\n # table caption).\n #\n _(\"cptn\"),\n # Translators: long braille for the rolename of a caption (e.g.,\n # table caption).\n #\n _(\"Caption\"),\n # Translators: spoken words for the rolename of a caption (e.g.,\n # table caption).\n #\n _(\"caption\"))\n\nrolenames[ROLE_CHECK_BOX] = Rolename(\n ROLE_CHECK_BOX,\n # Translators: short braille for the rolename of a checkbox.\n #\n _(\"chk\"),\n # Translators: long braille for the rolename of a checkbox.\n #\n _(\"CheckBox\"),\n # Translators: spoken words for the rolename of a checkbox.\n #\n _(\"check box\"))\n\nrolenames[ROLE_CHECK_MENU_ITEM] = Rolename(\n ROLE_CHECK_MENU_ITEM,\n # Translators: short braille for the rolename of a check menu item.\n #\n _(\"chk\"),\n # Translators: long braille for the rolename of a check menu item.\n #\n _(\"CheckItem\"),\n # Translators: spoken words for the rolename of a check menu item.\n #\n _(\"check item\"))\n\nrolenames[ROLE_COLOR_CHOOSER] = Rolename(\n ROLE_COLOR_CHOOSER,\n # Translators: short braille for the rolename of a color chooser.\n #\n _(\"clrchsr\"),\n # Translators: long braille for the rolename of a color chooser.\n #\n _(\"ColorChooser\"),\n # Translators: spoken words for the rolename of a color chooser.\n #\n _(\"color chooser\"))\n\nrolenames[ROLE_COLUMN_HEADER] = Rolename(\n ROLE_COLUMN_HEADER,\n # Translators: short braille for the rolename of a column header.\n #\n _(\"colhdr\"),\n # Translators: long braille for the rolename of a column header.\n #\n _(\"ColumnHeader\"),\n # Translators: spoken words for the rolename of a column header.\n #\n _(\"column header\"))\n\nrolenames[ROLE_COMBO_BOX] = Rolename(\n ROLE_COMBO_BOX,\n # Translators: short braille for the rolename of a combo box.\n #\n _(\"cbo\"),\n # Translators: long braille for the rolename of a combo box.\n #\n _(\"Combo\"),\n # Translators: spoken words for the rolename of a combo box.\n #\n _(\"combo box\"))\n\nrolenames[ROLE_DATE_EDITOR] = Rolename(\n ROLE_DATE_EDITOR,\n # Translators: short braille for the rolename of a date editor.\n #\n _(\"dat\"),\n # Translators: long braille for the rolename of a date editor.\n #\n _(\"DateEditor\"),\n # Translators: spoken words for the rolename of a date editor.\n #\n _(\"date editor\"))\n\nrolenames[ROLE_DESKTOP_ICON] = Rolename(\n ROLE_DESKTOP_ICON,\n # Translators: short braille for the rolename of a desktop icon.\n #\n _(\"icn\"),\n # Translators: long braille for the rolename of a desktop icon.\n #\n _(\"DesktopIcon\"),\n # Translators: spoken words for the rolename of a desktop icon.\n #\n _(\"desktop icon\"))\n\nrolenames[ROLE_DESKTOP_FRAME] = Rolename(\n ROLE_DESKTOP_FRAME,\n # Translators: short braille for the rolename of a desktop frame.\n #\n _(\"frm\"),\n # Translators: long braille for the rolename of a desktop frame.\n #\n _(\"DesktopFrame\"),\n # Translators: spoken words for the rolename of a desktop frame.\n #\n _(\"desktop frame\"))\n\nrolenames[ROLE_DIAL] = Rolename(\n ROLE_DIAL,\n # Translators: short braille for the rolename of a dial.\n # You should attempt to treat it as an abbreviation of\n # the translated word for \"dial\". It is OK to use an\n # unabbreviated word as long as it is relatively short.\n #\n C_(\"shortbraille\", \"dial\"),\n # Translators: long braille for the rolename of a dial.\n #\n _(\"Dial\"),\n # Translators: spoken words for the rolename of a dial.\n #\n _(\"dial\"))\n\nrolenames[ROLE_DIALOG] = Rolename(\n ROLE_DIALOG,\n # Translators: short braille for the rolename of a dialog.\n #\n _(\"dlg\"),\n # Translators: long braille for the rolename of a dialog.\n #\n _(\"Dialog\"),\n # Translators: spoken words for the rolename of a dialog.\n #\n _(\"dialog\"))\n\nrolenames[ROLE_DIRECTORY_PANE] = Rolename(\n ROLE_DIRECTORY_PANE,\n # Translators: short braille for the rolename of a directory pane.\n #\n _(\"dip\"),\n # Translators: long braille for the rolename of a directory pane.\n #\n _(\"DirectoryPane\"),\n # Translators: spoken words for the rolename of a directory pane.\n #\n _(\"directory pane\"))\n\nrolenames[ROLE_DOCUMENT_FRAME] = Rolename(\n ROLE_DOCUMENT_FRAME,\n # Translators: short braille for the rolename of an HTML document frame.\n #\n _(\"html\"),\n # Translators: long braille for the rolename of an HTML document frame.\n #\n _(\"HtmlPane\"),\n # Translators: spoken words for the rolename of an HTML document frame.\n #\n _(\"html content\"))\n\nrolenames[ROLE_DRAWING_AREA] = Rolename(\n ROLE_DRAWING_AREA,\n # Translators: short braille for the rolename of a drawing area.\n #\n _(\"draw\"),\n # Translators: long braille for the rolename of a drawing area.\n #\n _(\"DrawingArea\"),\n # Translators: spoken words for the rolename of a drawing area.\n #\n _(\"drawing area\"))\n\nrolenames[ROLE_FILE_CHOOSER] = Rolename(\n ROLE_FILE_CHOOSER,\n # Translators: short braille for the rolename of a file chooser.\n #\n _(\"fchsr\"),\n # Translators: long braille for the rolename of a file chooser.\n #\n _(\"FileChooser\"),\n # Translators: spoken words for the rolename of a file chooser.\n #\n _(\"file chooser\"))\n\nrolenames[ROLE_FILLER] = Rolename(\n ROLE_FILLER,\n # Translators: short braille for the rolename of a filler.\n #\n _(\"flr\"),\n # Translators: long braille for the rolename of a filler.\n #\n _(\"Filler\"),\n # Translators: spoken words for the rolename of a filler.\n #\n _(\"filler\"))\n\nrolenames[ROLE_FONT_CHOOSER] = Rolename(\n ROLE_FONT_CHOOSER,\n # Translators: short braille for the rolename of a font chooser.\n #\n _(\"fnt\"),\n # Translators: long braille for the rolename of a font chooser.\n #\n _(\"FontChooser\"),\n # Translators: spoken words for the rolename of a font chooser.\n #\n _(\"font chooser\"))\n\nrolenames[ROLE_FORM] = Rolename(\n ROLE_FORM,\n # Translators: short braille for the rolename of a form.\n # You should attempt to treat it as an abbreviation of\n # the translated word for \"form\". It is OK to use an\n # unabbreviated word as long as it is relatively short.\n #\n C_(\"shortbraille\", \"form\"),\n # Translators: long braille for the rolename of a form.\n #\n _(\"Form\"),\n # Translators: spoken words for the rolename of a form.\n #\n _(\"form\"))\n\nrolenames[ROLE_FRAME] = Rolename(\n ROLE_FRAME,\n # Translators: short braille for the rolename of a frame.\n #\n _(\"frm\"),\n # Translators: long braille for the rolename of a frame.\n #\n _(\"Frame\"),\n # Translators: spoken words for the rolename of a frame.\n #\n _(\"frame\"))\n\nrolenames[ROLE_GLASS_PANE] = Rolename(\n ROLE_GLASS_PANE,\n # Translators: short braille for the rolename of a glass pane.\n #\n _(\"gpn\"),\n # Translators: long braille for the rolename of a glass pane.\n #\n _(\"GlassPane\"),\n # Translators: spoken words for the rolename of a glass pane.\n #\n _(\"glass pane\"))\n\nrolenames[ROLE_HEADING] = Rolename(\n ROLE_HEADING,\n # Translators: short braille for the rolename of a heading.\n #\n _(\"hdng\"),\n # Translators: long braille for the rolename of a heading.\n #\n _(\"Heading\"),\n # Translators: spoken words for the rolename of a heading.\n #\n _(\"heading\"))\n\nrolenames[ROLE_HTML_CONTAINER] = Rolename(\n ROLE_HTML_CONTAINER,\n # Translators: short braille for the rolename of an html container.\n #\n _(\"html\"),\n # Translators: long braille for the rolename of an html container.\n #\n _(\"HtmlContainer\"),\n # Translators: spoken words for the rolename of an html container.\n #\n _(\"h t m l container\"))\n\nrolenames[ROLE_ICON] = Rolename(\n ROLE_ICON,\n # Translators: short braille for the rolename of a icon.\n #\n _(\"icn\"),\n # Translators: long braille for the rolename of a icon.\n #\n _(\"Icon\"),\n # Translators: spoken words for the rolename of a icon.\n #\n _(\"icon\"))\n\nrolenames[ROLE_IMAGE] = Rolename(\n ROLE_IMAGE,\n # Translators: short braille for the rolename of a image.\n #\n _(\"img\"),\n # Translators: long braille for the rolename of a image.\n #\n _(\"Image\"),\n # Translators: spoken words for the rolename of a image.\n #\n _(\"image\"))\n\nrolenames[ROLE_INTERNAL_FRAME] = Rolename(\n ROLE_INTERNAL_FRAME,\n # Translators: short braille for the rolename of an internal frame.\n #\n _(\"ifrm\"),\n # Translators: long braille for the rolename of an internal frame.\n #\n _(\"InternalFrame\"),\n # Translators: spoken words for the rolename of an internal frame.\n #\n _(\"internal frame\"))\n\nrolenames[ROLE_LABEL] = Rolename(\n ROLE_LABEL,\n # Translators: short braille for the rolename of a label.\n #\n _(\"lbl\"),\n # Translators: long braille for the rolename of a label.\n #\n _(\"Label\"),\n # Translators: spoken words for the rolename of a label.\n #\n _(\"label\"))\n\nrolenames[ROLE_LAYERED_PANE] = Rolename(\n ROLE_LAYERED_PANE,\n # Translators: short braille for the rolename of a layered pane.\n #\n _(\"lyrdpn\"),\n # Translators: long braille for the rolename of a layered pane.\n #\n _(\"LayeredPane\"),\n # Translators: spoken words for the rolename of a layered pane.\n #\n _(\"layered pane\"))\n\nrolenames[ROLE_LINK] = Rolename(\n ROLE_LINK,\n # Translators: short braille for the rolename of a link.\n #\n _(\"lnk\"),\n # Translators: long braille for the rolename of a link.\n #\n _(\"Link\"),\n # Translators: spoken words for the rolename of a link.\n #\n _(\"link\"))\n\nrolenames[ROLE_LIST] = Rolename(\n ROLE_LIST,\n # Translators: short braille for the rolename of a list.\n #\n _(\"lst\"),\n # Translators: long braille for the rolename of a list.\n #\n _(\"List\"),\n # Translators: spoken words for the rolename of a list.\n #\n _(\"list\"))\n\nrolenames[ROLE_LIST_ITEM] = Rolename(\n ROLE_LIST_ITEM,\n # Translators: short braille for the rolename of a list item.\n #\n _(\"lstitm\"),\n # Translators: long braille for the rolename of a list item.\n #\n _(\"ListItem\"),\n # Translators: spoken words for the rolename of a list item.\n #\n _(\"list item\"))\n\nrolenames[ROLE_MENU] = Rolename(\n ROLE_MENU,\n # Translators: short braille for the rolename of a menu.\n #\n _(\"mnu\"),\n # Translators: long braille for the rolename of a menu.\n #\n _(\"Menu\"),\n # Translators: spoken words for the rolename of a menu.\n #\n _(\"menu\"))\n\nrolenames[ROLE_MENU_BAR] = Rolename(\n ROLE_MENU_BAR,\n # Translators: short braille for the rolename of a menu bar.\n #\n _(\"mnubr\"),\n # Translators: long braille for the rolename of a menu bar.\n #\n _(\"MenuBar\"),\n # Translators: spoken words for the rolename of a menu bar.\n #\n _(\"menu bar\"))\n\nrolenames[ROLE_MENU_ITEM] = Rolename(\n ROLE_MENU_ITEM,\n # Translators: short braille for the rolename of a menu item.\n #\n _(\"mnuitm\"),\n # Translators: long braille for the rolename of a menu item.\n #\n _(\"MenuItem\"),\n # Translators: spoken words for the rolename of a menu item.\n #\n _(\"menu item\"))\n\nrolenames[ROLE_OPTION_PANE] = Rolename(\n ROLE_OPTION_PANE,\n # Translators: short braille for the rolename of an option pane.\n #\n _(\"optnpn\"),\n # Translators: long braille for the rolename of an option pane.\n #\n _(\"OptionPane\"),\n # Translators: spoken words for the rolename of an option pane.\n #\n _(\"option pane\"))\n\nrolenames[ROLE_PAGE_TAB] = Rolename(\n ROLE_PAGE_TAB,\n # Translators: short braille for the rolename of a page tab.\n #\n _(\"pgt\"),\n # Translators: long braille for the rolename of a page tab.\n #\n _(\"Page\"),\n # Translators: spoken words for the rolename of a page tab.\n #\n _(\"page\"))\n\nrolenames[ROLE_PAGE_TAB_LIST] = Rolename(\n ROLE_PAGE_TAB_LIST,\n # Translators: short braille for the rolename of a page tab list.\n #\n _(\"tblst\"),\n # Translators: long braille for the rolename of a page tab list.\n #\n _(\"TabList\"),\n # Translators: spoken words for the rolename of a page tab list.\n #\n _(\"tab list\"))\n\nrolenames[ROLE_PANEL] = Rolename(\n ROLE_PANEL,\n # Translators: short braille for the rolename of a panel.\n #\n _(\"pnl\"),\n # Translators: long braille for the rolename of a panel.\n #\n _(\"Panel\"),\n # Translators: spoken words for the rolename of a panel.\n #\n _(\"panel\"))\n\nrolenames[ROLE_PASSWORD_TEXT] = Rolename(\n ROLE_PASSWORD_TEXT,\n # Translators: short braille for the rolename of a password field.\n #\n _(\"pwd\"),\n # Translators: long braille for the rolename of a password field.\n #\n _(\"Password\"),\n # Translators: spoken words for the rolename of a password field.\n #\n _(\"password\"))\n\nrolenames[ROLE_POPUP_MENU] = Rolename(\n ROLE_POPUP_MENU,\n # Translators: short braille for the rolename of a popup menu.\n #\n _(\"popmnu\"),\n # Translators: long braille for the rolename of a popup menu.\n #\n _(\"PopupMenu\"),\n # Translators: spoken words for the rolename of a popup menu.\n #\n _(\"popup menu\"))\n\nrolenames[ROLE_PROGRESS_BAR] = Rolename(\n ROLE_PROGRESS_BAR,\n # Translators: short braille for the rolename of a progress bar.\n #\n _(\"pgbar\"),\n # Translators: long braille for the rolename of a progress bar.\n #\n _(\"Progress\"),\n # Translators: spoken words for the rolename of a progress bar.\n #\n _(\"progress bar\"))\n\nrolenames[ROLE_PUSH_BUTTON] = Rolename(\n ROLE_PUSH_BUTTON,\n # Translators: short braille for the rolename of a push button.\n #\n _(\"btn\"),\n # Translators: long braille for the rolename of a push button.\n #\n _(\"Button\"),\n # Translators: spoken words for the rolename of a push button.\n #\n _(\"button\"))\n\nrolenames[ROLE_RADIO_BUTTON] = Rolename(\n ROLE_RADIO_BUTTON,\n # Translators: short braille for the rolename of a radio button.\n #\n _(\"radio\"),\n # Translators: long braille for the rolename of a radio button.\n #\n _(\"RadioButton\"),\n # Translators: spoken words for the rolename of a radio button.\n #\n _(\"radio button\"))\n\nrolenames[ROLE_RADIO_MENU_ITEM] = Rolename(\n ROLE_RADIO_MENU_ITEM,\n # Translators: short braille for the rolename of a radio menu item.\n #\n _(\"rdmnuitm\"),\n # Translators: long braille for the rolename of a radio menu item.\n #\n _(\"RadioItem\"),\n # Translators: spoken words for the rolename of a radio menu item.\n #\n _(\"radio menu item\"))\n\nrolenames[ROLE_ROOT_PANE] = Rolename(\n ROLE_ROOT_PANE,\n # Translators: short braille for the rolename of a root pane.\n #\n _(\"rtpn\"),\n # Translators: long braille for the rolename of a root pane.\n #\n _(\"RootPane\"),\n # Translators: spoken words for the rolename of a root pane.\n #\n _(\"root pane\"))\n\nrolenames[ROLE_ROW_HEADER] = Rolename(\n ROLE_ROW_HEADER,\n # Translators: short braille for the rolename of a row header.\n #\n _(\"rwhdr\"),\n # Translators: long braille for the rolename of a row header.\n #\n _(\"RowHeader\"),\n # Translators: spoken words for the rolename of a row header.\n #\n _(\"row header\"))\n\nrolenames[ROLE_SCROLL_BAR] = Rolename(\n ROLE_SCROLL_BAR,\n # Translators: short braille for the rolename of a scroll bar.\n #\n _(\"scbr\"),\n # Translators: long braille for the rolename of a scroll bar.\n #\n _(\"ScrollBar\"),\n # Translators: spoken words for the rolename of a scroll bar.\n #\n _(\"scroll bar\"))\n\nrolenames[ROLE_SCROLL_PANE] = Rolename(\n ROLE_SCROLL_PANE,\n # Translators: short braille for the rolename of a scroll pane.\n #\n _(\"scpn\"),\n # Translators: long braille for the rolename of a scroll pane.\n #\n _(\"ScrollPane\"),\n # Translators: spoken words for the rolename of a scroll pane.\n #\n _(\"scroll pane\"))\n\nrolenames[ROLE_SECTION] = Rolename(\n ROLE_SECTION,\n # Translators: short braille for the rolename of a section (e.g., in html).\n #\n _(\"sctn\"),\n # Translators: long braille for the rolename of a section (e.g., in html).\n #\n _(\"Section\"),\n # Translators: spoken words for the rolename of a section (e.g., in html).\n #\n _(\"section\"))\n\nrolenames[ROLE_SEPARATOR] = Rolename(\n ROLE_SEPARATOR,\n # Translators: short braille for the rolename of a separator.\n #\n _(\"seprtr\"),\n # Translators: long braille for the rolename of a separator.\n #\n _(\"Separator\"),\n # Translators: spoken words for the rolename of a separator.\n #\n _(\"separator\"))\n\nrolenames[ROLE_SLIDER] = Rolename(\n ROLE_SLIDER,\n # Translators: short braille for the rolename of a slider.\n #\n _(\"sldr\"),\n # Translators: long braille for the rolename of a slider.\n #\n _(\"Slider\"),\n # Translators: spoken words for the rolename of a slider.\n #\n _(\"slider\"))\n\nrolenames[ROLE_SPLIT_PANE] = Rolename(\n ROLE_SPLIT_PANE,\n # Translators: short braille for the rolename of a split pane.\n #\n _(\"spltpn\"),\n # Translators: long braille for the rolename of a split pane.\n #\n _(\"SplitPane\"),\n # Translators: spoken words for the rolename of a split pane.\n #\n _(\"split pane\"))\n\nrolenames[ROLE_SPIN_BUTTON] = Rolename(\n ROLE_SPIN_BUTTON,\n # Translators: short braille for the rolename of a spin button.\n #\n _(\"spin\"),\n # Translators: long braille for the rolename of a spin button.\n #\n _(\"SpinButton\"),\n # Translators: spoken words for the rolename of a spin button.\n #\n _(\"spin button\"))\n\nrolenames[ROLE_STATUSBAR] = Rolename(\n ROLE_STATUSBAR,\n # Translators: short braille for the rolename of a statusbar.\n #\n _(\"statbr\"),\n # Translators: long braille for the rolename of a statusbar.\n #\n _(\"StatusBar\"),\n # Translators: spoken words for the rolename of a statusbar.\n #\n _(\"status bar\"))\n\nrolenames[ROLE_TABLE] = Rolename(\n ROLE_TABLE,\n # Translators: short braille for the rolename of a table.\n #\n _(\"tbl\"),\n # Translators: long braille for the rolename of a table.\n #\n _(\"Table\"),\n # Translators: spoken words for the rolename of a table.\n #\n _(\"table\"))\n\nrolenames[ROLE_TABLE_CELL] = Rolename(\n ROLE_TABLE_CELL,\n # Translators: short braille for the rolename of a table cell.\n #\n _(\"cll\"),\n # Translators: long braille for the rolename of a table cell.\n #\n _(\"Cell\"),\n # Translators: spoken words for the rolename of a table cell.\n #\n _(\"cell\"))\n\nrolenames[ROLE_TABLE_COLUMN_HEADER] = Rolename(\n ROLE_TABLE_COLUMN_HEADER,\n # Translators: short braille for the rolename of a table column header.\n #\n _(\"colhdr\"),\n # Translators: long braille for the rolename of a table column header.\n #\n _(\"ColumnHeader\"),\n # Translators: spoken words for the rolename of a table column header.\n #\n _(\"column header\"))\n\nrolenames[ROLE_TABLE_ROW_HEADER] = Rolename(\n ROLE_TABLE_ROW_HEADER,\n # Translators: short braille for the rolename of a table row header.\n #\n _(\"rwhdr\"),\n # Translators: long braille for the rolename of a table row header.\n #\n _(\"RowHeader\"),\n # Translators: spoken words for the rolename of a table row header.\n #\n _(\"row header\"))\n\nrolenames[ROLE_TEAR_OFF_MENU_ITEM] = Rolename(\n ROLE_TEAR_OFF_MENU_ITEM,\n # Translators: short braille for the rolename of a tear off menu item.\n #\n _(\"tomnuitm\"),\n # Translators: long braille for the rolename of a tear off menu item.\n #\n _(\"TearOffMenuItem\"),\n # Translators: spoken words for the rolename of a tear off menu item.\n #\n _(\"tear off menu item\"))\n\nrolenames[ROLE_TERMINAL] = Rolename(\n ROLE_TERMINAL,\n # Translators: short braille for the rolename of a terminal.\n #\n _(\"term\"),\n # Translators: long braille for the rolename of a terminal.\n #\n _(\"Terminal\"),\n # Translators: spoken words for the rolename of a terminal.\n #\n _(\"terminal\"))\n\nrolenames[ROLE_TEXT] = Rolename(\n ROLE_TEXT,\n # Translators: short braille for the rolename of a text entry field.\n #\n _(\"txt\"),\n # Translators: long braille for the rolename of a text entry field.\n #\n _(\"Text\"),\n # Translators: spoken words for the rolename of a text entry field.\n #\n _(\"text\"))\n\nrolenames[ROLE_ENTRY] = rolenames[ROLE_TEXT]\n\nrolenames[ROLE_TOGGLE_BUTTON] = Rolename(\n ROLE_TOGGLE_BUTTON,\n # Translators: short braille for the rolename of a toggle button.\n #\n _(\"tglbtn\"),\n # Translators: long braille for the rolename of a toggle button.\n #\n _(\"ToggleButton\"),\n # Translators: spoken words for the rolename of a toggle button.\n #\n _(\"toggle button\"))\n\nrolenames[ROLE_TOOL_BAR] = Rolename(\n ROLE_TOOL_BAR,\n # Translators: short braille for the rolename of a toolbar.\n #\n _(\"tbar\"),\n # Translators: long braille for the rolename of a toolbar.\n #\n _(\"ToolBar\"),\n # Translators: spoken words for the rolename of a toolbar.\n #\n _(\"tool bar\"))\n\nrolenames[ROLE_TOOL_TIP] = Rolename(\n ROLE_TOOL_TIP,\n # Translators: short braille for the rolename of a tooltip.\n #\n _(\"tip\"),\n # Translators: long braille for the rolename of a tooltip.\n #\n _(\"ToolTip\"),\n # Translators: spoken words for the rolename of a tooltip.\n #\n _(\"tool tip\"))\n\nrolenames[ROLE_TREE] = Rolename(\n ROLE_TREE,\n # Translators: short braille for the rolename of a tree.\n #\n _(\"tre\"),\n # Translators: long braille for the rolename of a tree.\n #\n _(\"Tree\"),\n # Translators: spoken words for the rolename of a tree.\n #\n _(\"tree\"))\n\nrolenames[ROLE_TREE_TABLE] = Rolename(\n ROLE_TREE_TABLE,\n # Translators: short braille for the rolename of a tree table.\n #\n _(\"trtbl\"),\n # Translators: long braille for the rolename of a tree table.\n #\n _(\"TreeTable\"),\n # Translators: spoken words for the rolename of a tree table.\n #\n _(\"tree table\"))\n\nrolenames[ROLE_UNKNOWN] = Rolename(\n ROLE_UNKNOWN,\n # Translators: short braille for when the rolename of an object is unknown.\n #\n _(\"unk\"),\n # Translators: long braille for when the rolename of an object is unknown.\n #\n _(\"Unknown\"),\n # Translators: spoken words for when the rolename of an object is unknown.\n #\n _(\"unknown\"))\n\nrolenames[ROLE_VIEWPORT] = Rolename(\n ROLE_VIEWPORT,\n # Translators: short braille for the rolename of a viewport.\n #\n _(\"vwprt\"),\n # Translators: long braille for the rolename of a viewport.\n #\n _(\"Viewport\"),\n # Translators: spoken words for the rolename of a viewport.\n #\n _(\"viewport\"))\n\nrolenames[ROLE_WINDOW] = Rolename(\n ROLE_WINDOW,\n # Translators: short braille for the rolename of a window.\n #\n _(\"wnd\"),\n # Translators: long braille for the rolename of a window.\n #\n _(\"Window\"),\n # Translators: spoken words for the rolename of a window.\n #\n _(\"window\"))\n\nrolenames[ROLE_HEADER] = Rolename(\n ROLE_HEADER,\n # Translators: short braille for the rolename of a header.\n #\n _(\"hdr\"),\n # Translators: long braille for the rolename of a header.\n #\n _(\"Header\"),\n # Translators: spoken words for the rolename of a header.\n #\n _(\"header\"))\n\nrolenames[ROLE_FOOTER] = Rolename(\n ROLE_FOOTER,\n # Translators: short braille for the rolename of a footer.\n #\n _(\"ftr\"),\n # Translators: long braille for the rolename of a footer.\n #\n _(\"Footer\"),\n # Translators: spoken words for the rolename of a footer.\n #\n _(\"footer\"))\n\nrolenames[ROLE_PARAGRAPH] = Rolename(\n ROLE_PARAGRAPH,\n # Translators: short braille for the rolename of a paragraph.\n #\n _(\"para\"),\n # Translators: long braille for the rolename of a paragraph.\n #\n _(\"Paragraph\"),\n # Translators: spoken words for the rolename of a paragraph.\n #\n _(\"paragraph\"))\n\nrolenames[ROLE_APPLICATION] = Rolename(\n ROLE_APPLICATION,\n # Translators: short braille for the rolename of a application.\n #\n _(\"app\"),\n # Translators: long braille for the rolename of a application.\n #\n _(\"Application\"),\n # Translators: spoken words for the rolename of a application.\n #\n _(\"application\"))\n\nrolenames[ROLE_AUTOCOMPLETE] = Rolename(\n ROLE_AUTOCOMPLETE,\n # Translators: short braille for the rolename of a autocomplete.\n #\n _(\"auto\"),\n # Translators: long braille for the rolename of a autocomplete.\n #\n _(\"AutoComplete\"),\n # Translators: spoken words for the rolename of a autocomplete.\n #\n _(\"autocomplete\"))\n\nrolenames[ROLE_EDITBAR] = Rolename(\n ROLE_EDITBAR,\n # Translators: short braille for the rolename of an editbar.\n #\n _(\"edtbr\"),\n # Translators: long braille for the rolename of an editbar.\n #\n _(\"EditBar\"),\n # Translators: spoken words for the rolename of an editbar.\n #\n _(\"edit bar\"))\n\nrolenames[ROLE_EMBEDDED] = Rolename(\n ROLE_EMBEDDED,\n # Translators: short braille for the rolename of an embedded component.\n #\n _(\"emb\"),\n # Translators: long braille for the rolename of an embedded component.\n #\n _(\"EmbeddedComponent\"),\n # Translators: spoken words for the rolename of an embedded component.\n #\n _(\"embedded component\"))\n\n\n# [[[TODO: eitani - This is for backward compatability, we now put in pyatspi \n# keys into the dictionary]]]\n\n_legacy_rolename_keys = rolenames.keys()\n\nfor sym in dir(pyatspi):\n if sym.startswith('ROLE_'):\n possible_key = sym.replace('ROLE_','').replace('_','').lower()\n for key in _legacy_rolename_keys:\n if key.replace(' ','') == possible_key:\n pyatspi_role = getattr(pyatspi, sym)\n rolenames[pyatspi_role] = rolenames[key]\n\ndef _adjustRole(obj, role):\n \"\"\"Adjust the role to what the role really is.\n \"\"\"\n\n # Return fake \"menu\" role names.\n #\n if (role == pyatspi.ROLE_MENU_ITEM) \\\n and (obj.childCount > 0):\n role = ROLE_MENU\n\n # If this is an ARIA button with the \"haspopup:true\" attribute, then\n # it's really a menu.\n #\n if role in [pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_MENU_ITEM]:\n attributes = obj.getAttributes()\n for attribute in attributes:\n if attribute.startswith(\"haspopup:true\"):\n role = ROLE_MENU\n break\n\n return role\n\ndef getSpeechForRoleName(obj, role=None):\n \"\"\"Returns the localized name of the given Accessible object; the name is\n suitable to be spoken. If a localized name cannot be discovered, this\n will return the string as defined by the at-spi.\n\n Arguments:\n - obj: an Accessible object\n\n Returns a string containing the localized name of the object suitable\n to be spoken.\n \"\"\"\n\n role = _adjustRole(obj, role or obj.getRole())\n\n # If the enum is not in the dictionary, check by name.\n role_entry = \\\n rolenames.get(role) or rolenames.get(obj.getRoleName())\n if role_entry:\n return role_entry.speech\n else:\n debug.println(debug.LEVEL_WARNING, \"No rolename for %s\" % repr(role))\n localizedRoleName = obj.getLocalizedRoleName()\n if localizedRoleName and len(localizedRoleName):\n return localizedRoleName\n else:\n return repr(role)\n\ndef getShortBrailleForRoleName(obj, role=None):\n \"\"\"Returns the localized name of the given Accessible object; the name is\n a short string suitable for a Braille display. If a localized name cannot\n be discovered, this will return the string as defined by the at-spi.\n\n Arguments:\n - obj: an Accessible object\n\n Returns a short string containing the localized name of the object\n suitable for a Braille display.\n \"\"\"\n\n role = _adjustRole(obj, role or obj.getRole())\n\n # If the enum is not in the dictionary, check by name.\n role_entry = \\\n rolenames.get(role) or rolenames.get(obj.getRoleName())\n if role_entry:\n return role_entry.brailleShort\n else:\n debug.println(debug.LEVEL_WARNING, \"No rolename for %s\" % repr(role))\n localizedRoleName = obj.getLocalizedRoleName()\n if localizedRoleName and len(localizedRoleName):\n return localizedRoleName\n else:\n return repr(role)\n\ndef getLongBrailleForRoleName(obj, role=None):\n \"\"\"Returns the localized name of the given Accessible object; the name is\n a long string suitable for a Braille display. If a localized name cannot\n be discovered, this will return the string as defined by the at-spi.\n\n Arguments:\n - obj: an Accessible object\n\n Returns a string containing the localized name of the object suitable for\n a Braille display.\n \"\"\"\n\n role = _adjustRole(obj, role or obj.getRole())\n\n # If the enum is not in the dictionary, check by name.\n role_entry = \\\n rolenames.get(role) or rolenames.get(obj.getRoleName())\n if role_entry:\n return role_entry.brailleLong\n else:\n debug.println(debug.LEVEL_WARNING, \"No rolename for %s\" % repr(role))\n localizedRoleName = obj.getLocalizedRoleName()\n if localizedRoleName and len(localizedRoleName):\n return localizedRoleName\n else:\n return repr(role)\n\ndef getBrailleForRoleName(obj, role=None):\n \"\"\"Returns the localized name of the given Accessible object; the name is\n a string suitable for a Braille display. If a localized name cannot\n be discovered, this will return the string as defined by the at-spi.\n\n Arguments:\n - obj: an Accessible object\n\n Returns a string containing the localized name of the object suitable for\n a Braille display. The actual string will depend upon the value of\n the 'brailleRolenameStyle' setting.\n \"\"\"\n\n if settings.brailleRolenameStyle == settings.BRAILLE_ROLENAME_STYLE_SHORT:\n return getShortBrailleForRoleName(obj, role)\n else:\n return getLongBrailleForRoleName(obj, role)\n","sub_path":"usr/share/python-support/gnome-orca/orca/rolenames.py","file_name":"rolenames.py","file_ext":"py","file_size_in_byte":39428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"559844377","text":"# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # 假设最大串\n max_subs = ''\n subs = ''\n for index, i in enumerate(s):\n # 新的字符不在子串中,子串变长\n if i not in subs:\n subs += i\n # 对比子串和最大串\n if len(subs) > len(max_subs):\n max_subs = subs\n else:\n # 找到重复出现的字符的位置,从它的下一位开始组成新的串\n subs = subs[subs.index(i) + 1:] + i\n\n return max_subs\n\n\nif __name__ == '__main__':\n assert Solution().lengthOfLongestSubstring('abccdefg') == 'cdefg'\n assert Solution().lengthOfLongestSubstring('abcabcbb') == 'abc'\n \n","sub_path":"leetcode/0003.longest-substring-without-repeating-characters/longest-substring-without-repeating-characters_2.py","file_name":"longest-substring-without-repeating-characters_2.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590401209","text":"# from scipy.stats import poisson\nfrom numpy.random import poisson\nfrom model.Neuron import Neuron\n\nclass PoissonNeuron(Neuron):\n def __init__(self, tau, meanSpikesPerSecond, name, outputs=None, parentPop=None):\n # Determine Lambda and set up our poisson distribution\n self.expectedMeanSpikeRate = meanSpikesPerSecond\n self.meanSpikeProbabilityPerMs = (self.expectedMeanSpikeRate / 10)\n self.poissonLambda = self.meanSpikeProbabilityPerMs * tau # Lambda mean probability of a spike per timestep (plus variance).\n # self.poissonDistribution = poisson(self.poissonLambda)\n # print(self.poissonDistribution)\n self.name = name\n self.tau = tau\n self.time = 0\n self.parentPopulation = parentPop\n self.type = \"PoissonNeuron\"\n\n # Set up outputs\n if outputs is None:\n self.outputs = []\n else:\n self.outputs = outputs\n\n # Set up records\n self.vv = []\n self.spikeRecord = []\n\n def step(self):\n self.time += self.tau\n # Evaluate Poisson source\n if poisson(self.poissonLambda, 1) > 0:\n # if self.poissonDistribution.rvs((1,))[0] > 0:\n self.spikeRecord.append(self.time)\n for axon in self.outputs:\n axon.enqueue()\n self.vv.append(40)\n else:\n self.vv.append(-60)\n","sub_path":"model/PoissonNeuron.py","file_name":"PoissonNeuron.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"23336810","text":"import cv2 as cv\nimport numpy as np\nimport imageio\nimport scipy.ndimage\nfrom skimage.measure import _structural_similarity\n\ndef dodge(front,back):\n result=front*255/(255-back+1)\n result[result>255]=255\n result[back==255]=255\n return result.astype('uint8')\n\ndef gray(bgr):\n bgr[:,:,0] = bgr[:,:,0] * 0.1114\n bgr[:,:,1] = bgr[:,:,1] * 0.587\n bgr[:,:,2] = bgr[:,:,2] * 0.299\n return bgr\n\nssim = _structural_similarity.compare_ssim\npath = '/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/test_transfer/'\ncategory = ['cat', 'dog', 'pig'] # 1. cat, 2. dog, 3. pig\n\ncat_path = path + category[0]\ndog_path = path + category[1]\npig_path = path + category[2]\nfor i in range(1,12):\n pic_human = '/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/test_human/human_%04d.jpg'%(i)\n pic_cat = cat_path + '/human_cat_%04d.jpg'%(i)\n pic_dog = dog_path + '/human_dog_%04d.jpg'%(i)\n pic_pig = pig_path + '/human_pig_%04d.jpg'%(i)\n\n # Read Image\n img_human = cv.imread(pic_human)\n img_human = cv.resize(img_human, (256, 256))\n img_cat = cv.imread(pic_cat)\n img_dog = cv.imread(pic_dog)\n img_pig = cv.imread(pic_pig)\n\n # Canny algorithm\n #human_gray = cv.cvtColor(img_human, cv.COLOR_BGR2GRAY)\n #cat_gray = cv.cvtColor(img_cat, cv.COLOR_BGR2GRAY)\n #dog_gray = cv.cvtColor(img_dog, cv.COLOR_BGR2GRAY)\n #pig_gray = cv.cvtColor(img_pig, cv.COLOR_BGR2GRAY)\n\n human_gray = gray(img_human)\n cat_gray = gray(img_cat)\n dog_gray = gray(img_dog)\n pig_gray = gray(img_pig)\n\n human_gray2 = 255 - human_gray\n cat_gray2 = 255 - cat_gray\n dog_gray2 = 255 - dog_gray\n pig_gray2 = 255 - pig_gray\n\n #human_edges = cv.Canny(human_gray, 170, 190)\n #cat_edges = cv.Canny(cat_gray, 170, 190)\n #dog_edges = cv.Canny(dog_gray, 170, 190)\n #pig_edges = cv.Canny(pig_gray, 170, 190)\n\n # Gaussian Blurring\n human_gauss = cv.GaussianBlur(human_gray2, (5,5), 150)\n cat_gauss = cv.GaussianBlur(cat_gray2, (5,5), 150)\n dog_gauss = cv.GaussianBlur(dog_gray2, (5,5), 150)\n pig_gauss = cv.GaussianBlur(pig_gray2, (5,5), 150)\n\n # Dodge processing\n human_dodge = dodge(human_gauss, human_gray)\n cat_dodge = dodge(cat_gauss, cat_gray)\n dog_dodge = dodge(dog_gauss, dog_gray)\n pig_dodge = dodge(pig_gauss, pig_gray)\n\n cv.imwrite('/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/edge_result/cat/cat_%04d.jpg'%(i), cat_dodge)\n cv.imwrite('/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/edge_result/dog/dog_%04d.jpg'%(i), dog_dodge)\n cv.imwrite('/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/edge_result/pig/pig_%04d.jpg'%(i), pig_dodge)\n cv.imwrite('/home/cheeze/PycharmProjects/KJW/capstone_project/human2animal/transfer_network/image_transfer/edge_result/human/human_%04d.jpg'%(i), human_dodge)\n\n human = np.asarray(human_gauss)\n cat = np.asarray(cat_gauss)\n dog = np.asarray(dog_gauss)\n pig = np.asarray(pig_gauss)\n\n cat_err = np.sum((human_dodge.astype(\"float\") - cat_dodge.astype(\"float\"))**2)\n cat_err /= float(human_gauss.shape[0] * human_gauss.shape[1])\n cat_ssim = ssim(human_dodge, cat_dodge)\n\n dog_err = np.sum((human_dodge.astype(\"float\") - dog_dodge.astype(\"float\"))**2)\n dog_err /= float(human_gauss.shape[0] * human_gauss.shape[1])\n dog_ssim = ssim(human_dodge, dog_dodge)\n\n pig_err = np.sum((human_dodge.astype(\"float\") - pig_dodge.astype(\"float\"))**2)\n pig_err /= float(human_gauss.shape[0] * human_gauss.shape[1])\n pig_ssim = ssim(human_dodge, pig_dodge)\n\n\n print(\"The MSE of %04dth cat is : %f\"%(i, cat_err))\n print(\"The MSE of %04dth dog is : %f\"%(i, dog_err))\n print(\"The MSE of %04dth pig is : %f\\n\"%(i, pig_err))\n print(\"The SSIM of %04dth cat is : %f\"%(i, cat_ssim))\n print(\"The SSIM of %04dth dog is : %f\"%(i, dog_ssim))\n print(\"The SSIM of %04dth pig is : %f\\n\\n\\n\"%(i, pig_ssim))\n\n\n","sub_path":"1. capstone/3. Classifier/edge_and_similarity.py","file_name":"edge_and_similarity.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"512954076","text":"from django.shortcuts import render\nfrom django.views.generic.base import View\nfrom database.models import Post\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nimport time\n\nfrom . import runTSPY_Online\n\n#from TSPY_Online.py import runTSPY_Online\n\nclass HomePage(View):\n def get(self, request):\n # code to query the database goes here!\n posts = Post.objects.all()[::-1]\n context = {}\n context[\"posts\"] = posts\n context[\"MEDIA_URL\"] = settings.MEDIA_URL\n return render(request, 'index.html', context)\n\nclass CreatePost(View):\n def post(self,request):\n name = request.POST.get(\"name\")\n if name == \"\":\n name = \"Anonymous\"\n date = time.strftime(\"%x\")\n name += (\" on %s\" % date)\n url = request.POST.get(\"imgURL\")\n caption = request.POST.get(\"caption\")\n if caption == \"\":\n caption = \"Untitled\"\n brightness = request.POST.get(\"brightness\")\n if brightness == \"\":\n brightness = \"1.5\"\n contrast = request.POST.get(\"contrast\")\n if contrast == \"\":\n contrast = \"1.5\"\n opacity = request.POST.get(\"opacity\")\n if opacity == \"\":\n opacity = \"0.75\"\n\n post = Post(imgURL=url, caption=caption, postedBy=name)\n post.save()\n postID = post.id\n\n mediaPath = settings.MEDIA_ROOT\n runTSPY_Online.runTSPY_Online(url,postID,mediaPath,brightness,contrast,opacity)\n return HttpResponseRedirect(\"/post/%s\" % postID)\n\nclass PostPage(View):\n def get(self, request, postID):\n post = Post.objects.get(id=postID)\n context = {}\n context[\"post\"] = post\n context[\"MEDIA_URL\"] = settings.MEDIA_URL\n context[\"TSP_Url\"] = settings.MEDIA_URL + \"TSPY_Online_Post\" + postID + \".png\"\n return render(request, 'post.html', context)\n\nclass GalleryPage(View):\n def get(self,request):\n posts = Post.objects.all()[::-1]\n context = {}\n context[\"posts\"] = posts\n context[\"MEDIA_URL\"] = settings.MEDIA_URL\n return render(request,'gallery.html',context)\n\nclass HelpPage(View):\n def get(self,request):\n return render(request,'help.html')\n\nclass AboutPage(View):\n def get(self,request):\n return render(request,'about.html')","sub_path":"TSPY_Online/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"585322194","text":"import logging\nimport pytest\n\nfrom conftest import DUT_VTEP_IP\nfrom tests.common.utilities import wait\nfrom tests.common.helpers.assertions import pytest_assert as pt_assert\n\n\npytestmark = [\n pytest.mark.topology('t0'),\n pytest.mark.device_type('vs')\n]\n\n\nclass Test_EVPN_Config():\n @pytest.fixture(scope=\"class\")\n def setup_dut(self, evpn_env):\n evpn_env.setup_dut_base()\n yield\n evpn_env.teardown_dut_base()\n\n @pytest.fixture(scope=\"class\")\n def vrf_vni_map_set(self, duthost, setup_dut):\n duthost.shell(\"config vrf add Vrf1\")\n duthost.shell(\"config vrf add_vrf_vni_map Vrf1 10000\")\n yield\n duthost.shell(\"config vrf del_vrf_vni_map Vrf1\")\n duthost.shell(\"config vrf del Vrf1\")\n wait(3)\n duthost.shell(\"vtysh -c 'configure' -c 'no vrf {}'\".format(\"Vrf1\"))\n\n def test_vlan_vni_map_configuration(self, duthost, setup_dut):\n # vtep\n res = duthost.shell(\"redis-cli -n 4 -c hgetall 'VXLAN_TUNNEL|vtep'\")\n res_list = res['stdout_lines']\n pt_assert(res_list[0] == 'src_ip')\n pt_assert(res_list[1] == DUT_VTEP_IP)\n\n res = duthost.shell(\"redis-cli -n 0 -c hgetall 'VXLAN_TUNNEL_TABLE:vtep'\")\n res_list = res['stdout_lines']\n pt_assert(res_list[0] == 'src_ip')\n pt_assert(res_list[1] == DUT_VTEP_IP)\n\n # evpnnvo\n res = duthost.shell(\"redis-cli -n 4 -c hgetall 'VXLAN_EVPN_NVO|evpnnvo1'\")\n res_list = res['stdout_lines']\n pt_assert(res_list[0] == 'source_vtep')\n pt_assert(res_list[1] == 'vtep')\n\n res = duthost.shell(\"redis-cli -n 0 -c hgetall 'VXLAN_EVPN_NVO_TABLE:evpnnvo1'\")\n res_list = res['stdout_lines']\n pt_assert(res_list[0] == 'source_vtep')\n pt_assert(res_list[1] == 'vtep')\n\n # map\n res = duthost.shell(\"redis-cli -n 4 -c hgetall 'VXLAN_TUNNEL_MAP|vtep|map_10000_Vlan1000'\")\n res_list = res['stdout_lines']\n pt_assert(res_list[1] == '10000')\n pt_assert(res_list[3] == 'Vlan1000')\n\n res = duthost.shell(\"redis-cli -n 0 -c hgetall 'VXLAN_TUNNEL_MAP_TABLE:vtep:map_10000_Vlan1000'\")\n res_list = res['stdout_lines']\n logging.info(res_list)\n pt_assert(res_list[1] == '10000')\n pt_assert(res_list[3] == 'Vlan1000')\n\n def test_vrf_vni_map_configuration(self, duthost, vrf_vni_map_set):\n # vrf\n res = duthost.shell(\"redis-cli -n 4 -c hgetall 'VRF|Vrf1'\")\n res_list = res['stdout_lines']\n pt_assert('vni' in res_list)\n pt_assert('10000' in res_list)\n\n res = duthost.shell(\"redis-cli -n 0 -c hgetall 'VRF_TABLE:Vrf1'\")\n res_list = res['stdout_lines']\n pt_assert('vni' in res_list)\n pt_assert('10000' in res_list)\n\n res = duthost.shell(\"redis-cli -n 0 -c hgetall 'VXLAN_VRF_TABLE:vtep:evpn_map_10000_Vrf1'\")\n res_list = res['stdout_lines']\n pt_assert('10000' in res_list)\n pt_assert('Vrf1' in res_list)","sub_path":"tests/evpn/test_evpn_config.py","file_name":"test_evpn_config.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"242253136","text":"#!/usr/bin/python3\nfrom sys import argv;\nimport sys;\n#Jason Cariaga\n#171001720\n#done using Python 3.8\nimport hashlib\nimport random\nimport string\nimport time\n\n\ndef sha256(data):\n\t#remember that data in update must be binary\n\tfirst = hashlib.sha256()\n\tfirst.update(data) #places data in hash function\n\tcomputed = first.hexdigest()\n\t#print(computed)\n\treturn computed\n\ndef getBin (hash):\n\tbinar = bin(int('1'+hash, 16))[3:]\n\treturn binar\n\ndef findleadbits(sechash):\n\tbinres = getBin(sechash)\n\tresult = 0\n\t#print(binres)\n\tfor x in range(len(binres)):\n\t\tif not(str(binres[x]) == '0'): #add +1 in [x] for righter bits\n\t\t\tbreak;\n\t\tresult += 1\n\t#print(result)\n\treturn result;\n\ntry:\n\tpowheader = argv[1]\n\tmsgfile = argv[2]\nexcept:\n\tprint(\"please include arguments: [pow-header, original message file]\")\n\texit()\n\n#storing header data into variables now:\nfailtest = []\npassed = 1\nfile = ''\ninithash = ''\nproofwork = ''\nnbits = 0\nfinalhash = ''\n\ntry:\n\tf = open(powheader, 'r')\n\tg = open(msgfile, 'r')\nexcept:\n\tprint(\"Invalid file! Try again\")\n\texit()\ng.close()\nf.close()\n\nwith open(powheader, 'r') as pow:\n\theader = pow.readlines()\n\t#gets rid of \\n\n\tfor line in range(len(header)):\n\t\theader[line] = header[line].replace(\"\\n\", \"\")\n\tfor part in header:\n\t\tif not part:\n\t\t\tcontinue\n\t\t#print(part)\n\t\tarrch = part.split()\n\t\tcheck = arrch[0]\n\t\tif \"file\" in check.lower():\n\t\t\tfile = arrch[1]\n\t\tif \"initial-hash:\" in check.lower():\n\t\t\tinithash = arrch[1]\n\t\tif \"proof-of-work:\" in check.lower():\n\t\t\tproofwork = arrch[1]\n\t\tif \"hash:\" in check.lower():\n\t\t\tfinalhash = arrch[1]\n\t\tif \"leading-bits\" in check.lower():\n\t\t\tnbits = arrch[1]\n\t# print(file)\n\t# print(inithash)\n\t# print(proofwork)\n\t# print(nbits)\n\t#covers first case\n\twith open(msgfile, 'rb') as msg:\n\t\tmessage = msg.read()\n\t\tsecmsg = sha256(message)\n\t\tif not (secmsg == inithash):\n\t\t\tfailtest.append(\"Test Failed: Message file does NOT hash to the correct value!\")\n\n\t#checks second case of proof of work\n\tdata = proofwork + secmsg\n\thashdata = sha256(data.encode())\n\tif not (hashdata == finalhash):\n\t\tfailtest.append(\"Test Failed: Final Hash of proof of work and file hash string does not match!\")\n\tif not (findleadbits(hashdata) == int(nbits)):\n\t\tfailtest.append(\"Test Failed: Leading-bits number does NOT match header's\")\n\n\tif not failtest:\n\t\tprint(\"pass\")\n\telse:\n\t\tprint('\\n'.join(failtest))\n","sub_path":"Project 4/jmc803proj4/pow-check.py","file_name":"pow-check.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"646129832","text":"\n\n# [1,1,4,2,1,3]\n# Move 4, 1, 3 => [1,1,1,2,3,4]\n# pull 1 and put at end of lowest\n# 3)\n\n# => create a set\n# get counts for each\n# create the ideal set\n# find the number of changes\n# [1,1,4,2,1,3]\n# [1,1,1,2,3,4]\n\nfrom collections import deque\nclass Solution:\n\n # For every letter in name\n # if there exists in typed the same letter with at least as many pressed\n # then true\n\n\n def is_long_pressed_name(self, name: str, typed: str) -> bool:\n\n len_n = len(name)\n len_t = len(typed)\n if len_t < len_t:\n return False\n\n name_q = deque(name)\n typed_q = deque(typed)\n\n i = 0\n name_letter_counts = {}\n typed_letter_counts = {}\n\n num_cur_ltr = 0\n cur_ltr = name_q.popleft()\n counter = 1\n while name_q:\n name_letter_counts[str(num_cur_ltr) + cur_ltr] = counter\n\n next_letter = name_q.popleft()\n if next_letter == cur_ltr:\n counter = counter + 1\n else:\n counter, num_cur_ltr = 1, num_cur_ltr + 1\n cur_ltr = next_letter\n\n # capture the last letter\n name_letter_counts[str(num_cur_ltr) + cur_ltr] = counter\n\n # now get counts from typed name\n num_cur_ltr = 0\n cur_ltr = typed_q.popleft()\n counter = 1\n while typed_q:\n typed_letter_counts[str(num_cur_ltr) + cur_ltr] = counter\n\n next_letter = typed_q.popleft()\n if next_letter == cur_ltr:\n counter = counter + 1\n else:\n counter, num_cur_ltr = 1, num_cur_ltr + 1\n cur_ltr = next_letter\n\n # capture the last letter\n typed_letter_counts[str(num_cur_ltr) + cur_ltr] = counter\n\n # must have same letters in each\n if list(name_letter_counts.keys()) != list(typed_letter_counts.keys()):\n return False\n\n for key in name_letter_counts.keys():\n if typed_letter_counts.get(key) < name_letter_counts[key]:\n return False\n\n return True\n\n\n\n\n\n\n\n\n","sub_path":"is_long_pressed_name/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"373178572","text":"from PIL import Image, ImageDraw #Подключим необходимые библиотеки.\r\nimport random\r\nimport io\r\nclass kartinka:\r\n def __init__(self,img):\r\n self.image = Image.open(io.BytesIO(img))#Image.open(img)\r\n #self.image = img\r\n self.draw = ImageDraw.Draw(self.image) # Создаем инструмент для рисования\r\n self.width = self.image.size[0] # Определяем ширину\r\n self.height = self.image.size[1] # Определяем высоту\r\n self.pix = self.image.load() # Выгружаем значения пикселей\r\n\r\n def image_to_bytes(self):\r\n b=io.BytesIO()\r\n self.image.save(b, 'JPEG')\r\n image_bytes = b.getvalue()\r\n return image_bytes\r\n\r\n def negative(self):\r\n for i in range(self.width):\r\n for j in range(self.height):\r\n a = self.pix[i, j][0]\r\n b = self.pix[i, j][1]\r\n c = self.pix[i, j][2]\r\n self.draw.point((i, j), (255 - a, 255 - b, 255 - c))\r\n\r\n def shum(self,factor):#добавляем на картинку шум\r\n for i in range(self.width):\r\n for j in range(self.height):\r\n rand = random.randint(-factor, factor)\r\n a = self.pix[i, j][0] + rand\r\n b = self.pix[i, j][1] + rand\r\n c = self.pix[i, j][2] + rand\r\n if (a < 0):\r\n a = 0\r\n if (b < 0):\r\n b = 0\r\n if (c < 0):\r\n c = 0\r\n if (a > 255):\r\n a = 255\r\n if (b > 255):\r\n b = 255\r\n if (c > 255):\r\n c = 255\r\n self.draw.point((i, j), (a, b, c))","sub_path":"BotTelegram/kartinka.py","file_name":"kartinka.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"19247294","text":"# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom pants.backend.python.rules.pex import Pex\nfrom pants.backend.python.rules.pex_from_targets import PexFromTargetsRequest\nfrom pants.backend.python.rules.python_sources import PythonSourceFiles, PythonSourceFilesRequest\nfrom pants.backend.python.subsystems.ipython import IPython\nfrom pants.backend.python.target_types import PythonSources\nfrom pants.core.goals.repl import ReplImplementation, ReplRequest\nfrom pants.engine.fs import Digest, MergeDigests\nfrom pants.engine.rules import Get, MultiGet, collect_rules, rule\nfrom pants.engine.unions import UnionRule\n\n\nclass PythonRepl(ReplImplementation):\n name = \"python\"\n required_fields = (PythonSources,)\n\n\n@rule\nasync def create_python_repl_request(repl: PythonRepl) -> ReplRequest:\n pex_request = Get(\n Pex,\n PexFromTargetsRequest(\n (tgt.address for tgt in repl.targets),\n output_filename=\"python.pex\",\n include_source_files=False,\n ),\n )\n sources_request = Get(PythonSourceFiles, PythonSourceFilesRequest(repl.targets))\n pex, sources = await MultiGet(pex_request, sources_request)\n merged_digest = await Get(\n Digest, MergeDigests((pex.digest, sources.source_files.snapshot.digest))\n )\n return ReplRequest(\n digest=merged_digest,\n binary_name=pex.output_filename,\n env={\"PEX_EXTRA_SYS_PATH\": \":\".join(sources.source_roots)},\n )\n\n\nclass IPythonRepl(ReplImplementation):\n name = \"ipython\"\n required_fields = (PythonSources,)\n\n\n@rule\nasync def create_ipython_repl_request(repl: IPythonRepl, ipython: IPython) -> ReplRequest:\n pex_request = Get(\n Pex,\n PexFromTargetsRequest(\n (tgt.address for tgt in repl.targets),\n output_filename=\"ipython.pex\",\n entry_point=ipython.entry_point,\n additional_requirements=ipython.all_requirements,\n include_source_files=True,\n ),\n )\n sources_request = Get(PythonSourceFiles, PythonSourceFilesRequest(repl.targets))\n pex, sources = await MultiGet(pex_request, sources_request)\n merged_digest = await Get(\n Digest, MergeDigests((pex.digest, sources.source_files.snapshot.digest))\n )\n return ReplRequest(\n digest=merged_digest,\n binary_name=pex.output_filename,\n env={\"PEX_EXTRA_SYS_PATH\": \":\".join(sources.source_roots)},\n )\n\n\ndef rules():\n return [\n *collect_rules(),\n UnionRule(ReplImplementation, PythonRepl),\n UnionRule(ReplImplementation, IPythonRepl),\n ]\n","sub_path":"src/python/pants/backend/python/rules/repl.py","file_name":"repl.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"381005417","text":"from domain.punch import Punch\n\n\nclass User:\n def __init__(self, name, email):\n self.id = 0\n self.name = name\n self.email = email\n self.punches = []\n\n def to_punch(self):\n self.punches.append(Punch())\n\n def get_work_hours_by(self, date):\n punches = self.get_punches_by(date)\n count_punches = self.__count_punches(punches)\n\n hours = 0\n for index in range(0, count_punches, 2):\n start = punches[index]\n end = punches[index + 1]\n hours += (end.hour - start.hour)\n return hours\n\n def get_punches_by(self, date):\n punches = filter(\n lambda punch: (punch.day == date.day\n and punch.month == date.month\n and punch.year == date.year),\n self.punches)\n return list(punches)\n\n @staticmethod\n def __count_punches(punches):\n count_punches = len(punches)\n return count_punches if count_punches % 2 == 0 else count_punches - 1\n","sub_path":"domain/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"308642131","text":"import requests\nimport json\nfrom argparse import ArgumentParser\nimport netifaces as ni\n\ndef post_to_slack(url, message):\n if url:\n requests.post(url, headers={'content-type': 'application/json'}, data=json.dumps({'text': message}))\n\ndef get_ip(interface):\n return ni.ifaddresses(interface)[ni.AF_INET][0]['addr']\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('interface')\n parser.add_argument('-s', '--slack')\n parser.add_argument('--debug', action='store_true', default=False)\n args = parser.parse_args()\n\n ip = get_ip(args.interface)\n msg_list = [f'[INFO] IP address: {ip}']\n\n if msg_list:\n post_to_slack(args.slack, '\\n'.join(msg_list))\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"123619736","text":"import math\nimport sys\n\n\n\npos_adj = []\nneg_adj = []\npos_comp = []\nneg_comp = []\npos_nouns = []\nneg_nouns = []\nvalid_names= []\nzero_nouns = ['nothing', 'zero']\n\nfirst_person = []\nsecond_person = []\n\ndef Assert(b, s):\n if not b:\n sys.stderr.write(s + \" at line \" + \"ERROR\" + \"\\n\")\n sys.exit(1)\n\ndef isFirstPerson(s):\n return s in first_person\n \ndef isSecondPerson(s):\n return s in second_person\n\ndef isNoun(word):\n return word in pos_nouns or word in neg_nouns or word in zero_nouns\n\ndef isAdjective(word):\n return word in pos_adj or word in neg_adj\n\ndef isComparative(word):\n return word in pos_comp or word in neg_comp\n\n#returns 1 for \"nice\" and neutral nouns, -1 for nasty ones\ndef nounValue(word):\n Assert(isNoun(word), \"Tried to find the nounvalue of a non-noun\")\n return 1 if word in pos_nouns else -1 if word in neg_nouns else 0\n\n#return s with all whitespace characters removed\ndef trimWhitespace(s):\n trimmed = \"\"\n for c in s:\n if c not in ['\\t', '\\r', '\\n', ' ']:\n trimmed += c\n return trimmed\n \n#return s with all whitespace characters before the first non-whitedspace character removed\ndef trimLeadingWhitespace(s):\n trimIndex = 0\n for c in s:\n if c in ['\\t', '\\r', '\\n', ' ']:\n trimIndex +=1\n else:\n break\n return s[trimIndex:]\n\n#A whitespace-agnositic beginswith method\ndef beginsWithNoWhitespace(s, pattern):\n return beginsWith(trimWhitespace(s), pattern)\n\ndef beginsWith(s, pattern):\n return s[:len(pattern)] == pattern \n \ndef loadFileIntoList(filename, list):\n f = open(filename, 'r')\n for word in f.readlines():\n list.append(word.split(\" \")[-1][:-1])\n f.close()\n\n#load initial noun and adjective lists\ndef loadWordLists():\n loadFileIntoList(\"include/neutral_adjective.wordlist\" , pos_adj)\n loadFileIntoList(\"include/positive_adjective.wordlist\", pos_adj)\n loadFileIntoList(\"include/negative_adjective.wordlist\", neg_adj)\n loadFileIntoList(\"include/positive_noun.wordlist\", pos_nouns)\n loadFileIntoList(\"include/neutral_noun.wordlist\" , pos_nouns)\n loadFileIntoList(\"include/negative_noun.wordlist\", neg_nouns)\n loadFileIntoList(\"include/positive_comparative.wordlist\", pos_comp)\n loadFileIntoList(\"include/negative_comparative.wordlist\", neg_comp)\n loadFileIntoList(\"include/character.wordlist\", valid_names)\n \n loadFileIntoList(\"include/second_person.wordlist\", second_person)\n loadFileIntoList(\"include/second_person_possessive.wordlist\", second_person)\n loadFileIntoList(\"include/second_person_reflexive.wordlist\", second_person)\n \n loadFileIntoList(\"include/first_person.wordlist\", first_person)\n loadFileIntoList(\"include/first_person_possessive.wordlist\", first_person)\n loadFileIntoList(\"include/first_person_reflexive.wordlist\", first_person)\n\nroman_values = { 'M': 1000, 'D': 500, 'C': 1000, 'L': 50, 'X': 10, 'V': 5, 'I': 1 }\ndef parseRomanNumeral(roman_string):\n roman_string = roman_string.upper() \n strindex = 0\n roman_sum = 0\n while strindex < len(roman_string) - 1:\n if(roman_values[roman_string[strindex]] < roman_values[roman_string[strindex+1]]):\n roman_sum -= roman_values[roman_string[strindex]]\n else:\n roman_sum += roman_values[roman_string[strindex]]\n strindex += 1\n return roman_sum + roman_values[roman_string[strindex]]\n\ndef isNumber(s):\n words = s.split(\" \")\n for word in words:\n if isNoun(word):\n return True\n return False\n\n\n#parse a string that is supposed to evaluate to a number\ndef safeParseNum(s):\n words = s.split(\" \")\n nounIndex = len(words)\n for i in range(0,len(words)):\n if isNoun(words[i]):\n nounIndex = i\n break\n if(nounIndex < len(words)):\n value = nounValue(words[nounIndex])\n for word in words[:nounIndex]:\n if isAdjective(word):\n value *= 2\n return value\n else:\n return 0\n\n#parse a string that is supposed to evaluate to a number\ndef parseNum(s):\n words = s.split(\" \")\n nounIndex = len(words)\n for i in range(0,len(words)):\n if isNoun(words[i]):\n nounIndex = i\n break\n Assert (nounIndex < len(words), str(words) + \"\\nExpected a number, but found no noun\")\n value = nounValue(words[nounIndex])\n for word in words[:nounIndex]:\n if isAdjective(word):\n value *= 2\n return value\n\n#returns the index of the leftmost punctuation mark in s\ndef findPunctuation(s):\n valids = []\n for val in [s.find('.'), s.find('!'), s.find('?')]:\n if val >= 0:\n valids.append(val)\n return -1 if len(valids) == 0 else min(valids)\n\ndef wordToOperator(op):\n if op == \"sum\":\n return \"+\"\n elif op == \"difference\":\n return \"-\"\n elif op == \"quotient\":\n return \"/\"\n elif op == \"product\":\n return \"*\"\n else:\n Assert(False, \"Illegal Operator\")\n \nclass Tree:\n def __init__(self, v, l, r):\n self.value = v\n self.left = l\n self.right = r\n\n\nbinop = [\"sum\", \"difference\", \"quotient\", \"product\"]\nunop = [\"square\", \"cube\", \"twice\"]\ndef buildExpressionTree(expr, target, speaker, vartable):\n Assert (len(expr) > 0, \"Ill-formed Expression in \" + str(expr))\n if expr[0] == \"square\":\n if expr[1] == \"root\":\n op = \"math.sqrt\"\n expr = expr[2:]\n num, expr = buildExpressionTree(expr, target, speaker, vartable)\n return Tree(op, num, \"\"), expr\n elif expr[0] == \"remainder\":\n if expr[1] == \"of\" and expr[2] == \"the\" and expr[3] == \"quotient\":\n expr = expr[4:]\n op = \"%\"\n left, expr = buildExpressionTree(expr, target, speaker, vartable)\n right, expr = buildExpressionTree(expr, target, speaker, vartable)\n return Tree(op, left, right), expr\n if expr[0] in binop:\n op = wordToOperator(expr[0])\n expr = expr[1:]\n left, expr = buildExpressionTree(expr, target, speaker, vartable)\n right, expr = buildExpressionTree(expr, target, speaker, vartable)\n return Tree(op, left, right), expr\n elif expr[0] in unop:\n op = expr[0]\n expr = expr[1:]\n num, expr = buildExpressionTree(expr, target, speaker, vartable)\n return Tree(op, num, \"\"), expr\n\n if True:\n i = 1 if expr[0] == \"and\" else 0\n numstr = \"\"\n while expr[i] not in binop and expr[i] not in unop and expr[i] not in [\"and\", \"remainder\"]:\n if expr[i] in [\"you\", \"thee\", \"yourself\", \"thyself\", \"thou\"]:\n expr = expr[i + 1:]\n return Tree(target, \"\", \"\"), expr\n elif expr[i] in [\"me\", \"myself\", \"i\"]:\n expr = expr[i + 1:]\n return Tree(speaker, \"\", \"\"), expr\n elif expr[i].capitalize() in vartable:\n name = expr[i]\n expr = expr[i + 1:]\n return Tree(name.capitalize(), \"\", \"\"), expr\n elif i == len(expr) - 1:\n numstr += expr[i]\n i = len(expr)\n break\n else:\n numstr += expr[i] + \" \"\n i += 1\n if i == len(expr):\n expr = []\n else:\n expr = expr[i:]\n if not isNumber(numstr):\n return buildExpressionTree(expr, target, speaker, vartable)\n else:\n return Tree(str(parseNum(numstr)), \"\", \"\"), expr\n\ndef concatWords(wordArray):\n c = \"\"\n for word in wordArray:\n c += word\n return c\n\ndef firstWord(statement):\n words = statement.split(\" \")\n for word in words:\n if len(word) > 0:\n return word\n \ndef getActOrSceneNumber(s, actOrScene):\n num = s[s.find(actOrScene):].split(\" \")[1]\n if num.find(':') > 0:\n num = num[:num.find(':')]\n else:\n Assert (False, \"Bad \" + actOrScene + \" heading\")\n return parseRomanNumeral(num)\n\ndef getActOrSceneDescription(s):\n desc = trimWhitespace(s[s.find(':')+1:]).lower()\n p = findPunctuation(desc)\n if p > 0:\n desc = desc[:p]\n return desc\n\nloadWordLists()","sub_path":"lang.py","file_name":"lang.py","file_ext":"py","file_size_in_byte":8207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"199925325","text":"\"\"\"\nexport PYTHONPATH=$PYTHONPATH:~/Desktop/projects/m251:~/Desktop/projects/del8\n\npython3 m251/exp_groups/paper/nlp/intermediate/results/merge_results.py\n\n\"\"\"\nimport collections\nimport csv\nimport json\nimport os\n\nimport numpy as np\n\nfrom del8.core.experiment import experiment\nfrom del8.core.storage.storage import RunState\nfrom del8.core.utils.type_util import hashabledict\n\nfrom m251.data.processing.constants import NUM_GLUE_TRAIN_EXAMPLES\nfrom m251.fisher.execs import merging_execs\nfrom m251.exp_groups.paper.results import utils as result_utils\n\nfrom m251.exp_groups.paper.nlp.intermediate import defs\n\nget_single_score = result_utils.get_single_score\nresult_file = result_utils.result_file\n\nBAD_FINETUNE_RUN_UUIDS = defs.BAD_FINETUNE_RUN_UUIDS\n\n\nMERGE_PAIRS_JSON = result_file(\"nlp/intermediate/merge_pairs.json\")\n\n\ndef _is_bad_cola(mtm, res):\n return mtm.task == \"cola\" and not get_single_score(res.results)\n\n\ndef _is_bad_mrpc(mtm, res):\n return mtm.task == \"mrpc\" and get_single_score(res.results) < 75\n\n\ndef _is_bad_qqp(mtm, res):\n return (\n mtm.task == \"qqp\"\n and mtm.model_checkpoint_uuid == \"536880b57b0248718b8f9748f8b2e847\"\n )\n\n\ndef create_json(merge_exp):\n with merge_exp.get_storage() as storage:\n exps_data = storage.retrieve_storage_data(experiment_uuid=[merge_exp.uuid])\n\n merge_run_ids = exps_data.get_finished_runs_ids(experiment_uuid=merge_exp.uuid)\n\n items = []\n for run_id in merge_run_ids:\n merge_run = exps_data.get_run_data(run_id)\n\n params = merge_run.get_single_item_by_class(merge_exp.params_cls)\n reses = merge_run.get_items_by_class(merging_execs.MergingEvaluationResults)\n\n # print([(r.weighting[0], get_single_score(r.results)) for r in reses])\n\n res = max(reses, key=lambda r: get_single_score(r.results))\n og_res = max(reses, key=lambda r: r.weighting[0])\n donor_body_res = max(reses, key=lambda r: r.weighting[1])\n\n assert og_res.weighting[0] == 1.0\n assert donor_body_res.weighting[1] == 1.0\n\n target_mtm, donor_mtm = params.models_to_merge\n\n if target_mtm.fisher_run_uuid in BAD_FINETUNE_RUN_UUIDS:\n continue\n elif donor_mtm.fisher_run_uuid in BAD_FINETUNE_RUN_UUIDS:\n continue\n\n items.append(\n {\n \"target_task\": target_mtm.task,\n \"donor_task\": donor_mtm.task,\n \"trial_index\": params.trial_index,\n \"original_score\": og_res.results,\n \"merged_score\": res.results,\n \"donor_body_score\": donor_body_res.results,\n \"weighting\": res.weighting[0],\n }\n )\n\n return items\n\n\ndef create_csv_table(filepath, round_digits=1):\n items = result_utils.load_json(filepath)\n\n row_groups = collections.defaultdict(list)\n for item in items:\n group_key = hashabledict(\n {\n \"target_task\": item[\"target_task\"],\n \"donor_task\": item[\"donor_task\"],\n }\n )\n row_groups[group_key].append(item)\n\n header = [\n \"task\",\n \"donor\",\n \"merged score\",\n \"stddev\",\n \"orig score\",\n \"stddev\",\n \"mean boost\",\n \"stddev\",\n \"max boost\",\n \"min boost\",\n \"num trials\",\n ]\n body = []\n for hp, row_items in row_groups.items():\n og_scores = np.array(\n [get_single_score(item[\"original_score\"]) for item in row_items]\n )\n merged_scores = np.array(\n [get_single_score(item[\"merged_score\"]) for item in row_items]\n )\n row = [\n hp[\"target_task\"],\n hp[\"donor_task\"],\n round(np.mean(merged_scores), round_digits),\n round(np.std(merged_scores), round_digits),\n #\n round(np.mean(og_scores), round_digits),\n round(np.std(og_scores), round_digits),\n #\n round(np.mean(merged_scores - og_scores), round_digits),\n round(np.std(merged_scores - og_scores), round_digits),\n #\n round(np.max(merged_scores - og_scores), round_digits),\n round(np.min(merged_scores - og_scores), round_digits),\n len(row_items),\n ]\n body.append(row)\n\n body = sorted(body, key=lambda r: r[:2])\n\n rows = [header] + body\n\n return result_utils.csv_to_str(rows)\n\n\nif __name__ == \"__main__\":\n from m251.exp_groups.paper.nlp.intermediate import fisher\n from m251.exp_groups.paper.nlp.intermediate import merge\n\n ###########################################################################\n\n merge_exp = merge.Merge_Pairs_Normalized_LastCkpt\n summary = create_json(merge_exp)\n # s = json.dumps(summary, indent=2)\n # print(s)\n\n filepath = MERGE_PAIRS_JSON\n with open(filepath, \"w\") as f:\n json.dump(summary, f, indent=2)\n\n t = create_csv_table(filepath)\n print(t)\n","sub_path":"m251/exp_groups/paper/nlp/intermediate/results/merge_results.py","file_name":"merge_results.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"314183875","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport services.controlers.loggControler\nimport services.querys.incidentTypeQuery\nfrom services.exceptions import *\nimport os\nimport hashlib\nimport re\nimport cgi\nimport urllib\n\nclass IncidentTypesControler:\n\tdef get(self):\n\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\tincidentTypesList=[]\n\t\ttry:\n\t\t\tdata = incidentTypeQuery.get()\n\t\t\tfor incidentTypeObject in data:\n\t\t\t\tincidentType=incidentTypeObject.toDictReduced()\n\t\t\t\tincidentTypesList.append(incidentType)\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn incidentTypesList\n\n\tdef getAllWithFilter(self, sessionJson):\n\t\tincidentTypeObjects = []\n\t\ttry:\n\t\t\t# Verifica tipo de usuario\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tuserTypeQuery = services.querys.userTypeQuery.UserTypeQuery()\n\t\t\tif int(sessionJson[\"userTypeId\"]) == int(userTypeQuery.getUserTypeByAutoId(0)[\"id\"]):\n\t\t\t\tincidentTypeObjects = incidentTypeQuery.get()\n\t\t\telse:\n\t\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\t\tincidentTypeObjects = incidentTypeQuery.getByCompany(sessionJson[\"companyIdSession\"])\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn incidentTypeObjects\n\n\tdef getWithFilter(self, sessionJson):\n\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\tincidentTypesList=[]\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\t# Verifica tipo de usuario\n\t\t\tuserTypeQuery = services.querys.userTypeQuery.UserTypeQuery()\n\t\t\tdata = []\n\t\t\tif sessionJson[\"userTypeId\"] == int(userTypeQuery.getUserTypeByAutoId(0)[\"id\"]):\n\t\t\t\tdata = incidentTypeQuery.get()\n\t\t\telif sessionJson[\"userTypeId\"] == int(userTypeQuery.getUserTypeByAutoId(1)[\"id\"]):\n\t\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\t\tdata = incidentTypeQuery.getByCompany(sessionJson[\"companyIdSession\"])\n\t\t\tfor incidentTypeObject in data:\n\t\t\t\tincidentType=incidentTypeObject.toDictReduced()\n\t\t\t\tincidentTypesList.append(incidentType)\n\t\t\tstate=OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn incidentTypesList, state\n\n\tdef getById(self, identifier):\n\t\tincidentType={}\n\t\ttry:\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tattributesList=[]\n\t\t\tincidentTypeObject = incidentTypeQuery.getById(identifier)\n\t\t\tincidentType = incidentTypeObject.toDictFront()\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn incidentType\n\n\tdef getByFatherCode(self, fatherCode, sessionJson):\n\t\tincidentTypesList=[]\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tdata = incidentTypeQuery.getByFatherCode(fatherCode, sessionJson[\"companyIdSession\"])\n\t\t\tfor incidentTypeObject in data:\n\t\t\t\tincidentType=incidentTypeObject.toDictReduced()\n\t\t\t\tincidentTypesList.append(incidentType)\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn incidentTypesList\n\n\tdef addIncidentType(self, code, name, fatherCode, sessionJson):\n\t\tmessage=\"TIPO_DE_INCIDENTE_NO_REGISTRADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tsessionJson[\"userTypeId\"] = int(sessionJson[\"userTypeId\"])\n\t\t\tsessionJson[\"companyIdSession\"] = int(sessionJson[\"companyIdSession\"])\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\t# VALIDACIONES\n\t\t\tdoRegister = True\n\t\t\tif incidentTypeQuery.getExists(code, fatherCode):\n\t\t\t\tdoRegister = False\n\t\t\t\tstate = 203\n\t\t\t\tmessage = message + \": EL ELEMENTO YA EXISTE\"\n\t\t\t# REGISTRO\n\t\t\tif doRegister == True:\n\t\t\t\tquery = incidentTypeQuery.add(code, name, fatherCode, sessionJson[\"companyIdSession\"])\n\t\t\t\tmessage=\"TIPO_DE_INCIDENTE_REGISTRADO\"\n\t\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef editIncidentType(self, code, name, fatherCode, identifier):\n\t\tmessage=\"TIPO_DE_INCIDENTE_NO_MODIFICADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tincidentTypeObject = incidentTypeQuery.getById(identifier)\n\t\t\tincidentTypeObject.code = code\n\t\t\tincidentTypeObject.fatherCode = fatherCode\n\t\t\tincidentTypeObject.name = name\n\t\t\tincidentTypeObject.upperCaseName = name.upper()\n\t\t\tincidentTypeQuery.edit(incidentTypeObject)\n\t\t\tmessage=\"TIPO_DE_INCIDENTE_MODIFICADO\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn message, state\n\n\tdef loadIncidentTypes(self, data):\n\t\tmessageInfo=\"TIPOS_DE_INCIDENTE_NO_CARGADOS\"\n\t\tstate = 300\n\t\tmsn = []\n\t\teditTemp = \"\"\n\t\ttry:\n\t\t\terror=False\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tfor obj in data:\t\t\t\n\t\t\t\tcode = obj[\"Codigo\"]\n\t\t\t\tname = obj[\"TipoDeEscenario\"]\n\t\t\t\tif \"CodigoDelPadre\" in obj:\n\t\t\t\t\tfatherCode = obj[\"CodigoDelPadre\"]\n\t\t\t\telse:\n\t\t\t\t\tfatherCode = \"-1\"\n\t\t\t\tcompanyId = int(obj[\"IdEmpresa\"])\n\t\t\t\texists, incidentTypeObj = incidentTypeQuery.getObjIfExists(code, fatherCode, companyId)\n\t\t\t\tif exists:\n\t\t\t\t\tincidentTypeObj.name = name\n\t\t\t\t\tstate = incidentTypeQuery.edit(incidentTypeObj)\n\t\t\t\telse:\n\t\t\t\t\tstate, objId = incidentTypeQuery.add(code, name, fatherCode, companyId)\n\t\t\t\tif state != OK:\n\t\t\t\t\terror=True\n\t\t\tif error == False:\n\t\t\t\tmessageInfo=\"TIPOS_DE_INCIDENTE_CARGADOS\"\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Controler: RolesControler-loadPermissions()', ERROR_NO_DEFINIDO, e.message)\n\t\treturn messageInfo, state\n\n\tdef\tdropAllIncidentTypes(self):\n\t\tmessage=\"TIPOS_DE_INCIDENTE_NO_ELIMINADOS\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tincidentTypeQuery = services.querys.incidentTypeQuery.IncidentTypeQuery()\n\t\t\tincidentTypeQuery.dropAll()\n\t\t\tmessage=\"TIPOS_DE_INCIDENTE_ELIMINADOS\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n","sub_path":"services/controlers/incidentTypesControler.py","file_name":"incidentTypesControler.py","file_ext":"py","file_size_in_byte":6786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"167440426","text":"\"\"\"Standard definition.\"\"\"\n\n\nclass Standard(object):\n \"\"\"\n Standard definition for all defined rules.\n\n Later lookup the config file for a path to a rules directory\n or fallback to default `ansiblelater/data/*`.\n \"\"\"\n\n def __init__(self, standard_dict):\n \"\"\"\n Initialize a new standard object and returns None.\n\n :param standard_dict: Dictionary object containing all neseccary attributes\n\n \"\"\"\n self.id = standard_dict.get(\"id\", \"\")\n self.name = standard_dict.get(\"name\")\n self.version = standard_dict.get(\"version\")\n self.check = standard_dict.get(\"check\")\n self.types = standard_dict.get(\"types\")\n\n\n def __repr__(self): # noqa\n return \"Standard: %s (version: %s, types: %s)\" % (\n self.name, self.version, self.types)\n","sub_path":"ansiblelater/standard.py","file_name":"standard.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"281001087","text":"from flask import request, url_for, Blueprint\nfrom flask_restplus import Resource, Api\nfrom ..models import Note, Tag\nfrom flask_restplus import fields\n\nblueprint = Blueprint('api', __name__)\n\napi = Api(blueprint,\n title=\"Note App\",\n version='1.0',\n description=\"API documentation for my graph notes app\")\n\n\n# Models\nnote_ns = api.namespace('notes',\n description=\"Operations for retrieving \"\n \"Notes, Child Notes and Parent Notes.\")\n\nnote_content = api.model('Note Content', {\n \"content\": fields.String\n })\n\npaginated_notes_meta = api.model('Paginated Notes Meta', {\n \"currentPage\": fields.Integer,\n \"itemsPerPage\": fields.Integer,\n})\n\n\npaginated_notes_links = api.model('Paginated Notes Links', {\n \"currentPageEndpoint\": fields.String,\n \"nextPageEndpoint\": fields.String,\n \"prevPageEndpoint\": fields.String\n})\n\nnote_links = api.model('Note Links', {\n \"currentNoteEndpoint\": fields.String,\n \"parentNoteEndpoint\": fields.String,\n \"childNoteEndpoint\": fields.String,\n})\n\nnote_model = api.model('Note Model', {\n 'id': fields.Integer,\n 'uid': fields.String,\n 'content': fields.String,\n 'createdAt': fields.DateTime,\n 'archived': fields.Boolean,\n 'tags': fields.List(fields.String),\n '_links': fields.Nested(note_links)\n})\n\npaginated_notes_model = api.model('Paginated Notes Model', {\n 'data': fields.List(fields.Nested(note_model)),\n '_meta': fields.Nested(paginated_notes_meta),\n '_links': fields.Nested(paginated_notes_links)\n})\n\n\n# Routes\n@note_ns.route('/')\nclass Notes(Resource):\n \"\"\" Main Note routes.\n \"\"\"\n @api.marshal_with(paginated_notes_model)\n @api.response(200, 'Successfully read notes')\n @api.param('page', 'Number of the page to get')\n @api.param('per_page', 'Number of notes per page')\n @api.param('tag', \"Get notes matching this tag\")\n @api.param('start_date', \"Date to match after eg. 1970-10-10\")\n @api.param('end_date', \"Date to match before eg. 1970-10-15\")\n @api.param('search', \"Get notes with content containing this string\")\n def get(self):\n\n \"\"\" Get outstanding notes\n\n Begins with the base clause and adds additional query clauses.\n \"\"\"\n\n # Query parameters\n params = {}\n\n # Base Query\n query = \"\"\"\n MATCH (n: Note)\n \"\"\"\n\n # Parse query parameters\n params['tag'] = request.args.get('tag')\n params['search'] = request.args.get(\"search\")\n params['start_date'] = request.args.get(\"start_date\")\n params['end_date'] = request.args.get('end_date')\n params['page'] = request.args.get('page', 1, type=int)\n params['per_page'] = request.args.get('per_page', 5, type=int)\n\n # Pagination variables\n params['skip'] = (params['page'] * params['per_page']) - params['per_page']\n params['limit'] = (params['per_page']) + 1\n\n if params['tag']:\n tag_clause = \"<-[:TAGGED]-(t: Tag)\"\n query = \"\".join((query, tag_clause))\n\n # Add query clauses.\n archived_clause = \"WHERE n.archived = False\"\n query = \" \".join((query, archived_clause))\n\n if params['tag']:\n tag_clause = \"AND t.text = $tag\"\n query = \" \".join((query, tag_clause))\n if params['search']:\n search_clause = \"AND toLower(n.content) CONTAINS toLower($search) \"\n query = \" \".join((query, search_clause))\n if params['start_date']:\n start_date_clause = \"AND n.createdAt > $start_date\"\n query = \" \".join((query, start_date_clause))\n if params['end_date']:\n end_date_clause = \"AND n.createdAt < $end_date\"\n query = \" \".join((query, end_date_clause))\n\n # Return clause with pagination\n return_clause = \"\"\"\n RETURN n\n ORDER BY n.createdAt DESC\n \"\"\"\n pagination_clause = \"SKIP $skip LIMIT $limit\"\n query = \" \".join((query, return_clause, pagination_clause))\n\n # Get paginated Note collection\n data = Note.to_collection_dict(query,\n params,\n 'api.notes_notes',\n search=params['search'],\n start_date=params['start_date'],\n end_date=params['end_date'],\n per_page=params['per_page'],\n tag=params['tag'])\n return data\n\n @api.marshal_with(note_model)\n @api.response(201, 'Successfully created new note')\n @api.expect(note_content)\n def post(self):\n \"\"\" Create a new parent note\n\n Returns the newly created parent note.\n \"\"\"\n\n # Parse content\n data = request.get_json()\n content = data[\"content\"]\n\n if content:\n note = Note(content=content)\n note.save_note()\n return note.to_dict()\n # TODO return error message\n\n\n@note_ns.route('/')\nclass NotesNote(Resource):\n\n \"\"\" Individual Notes\n \"\"\"\n\n @api.marshal_with(note_model)\n @api.response(200, 'Successfully read note')\n def get(self, uid):\n\n \"\"\" Get a single note\n\n Allows the user to get a single note from\n the database according to the id.\n \"\"\"\n\n note = Note.nodes.get_or_none(uid=uid)\n if note:\n return note.to_dict()\n # else...\n\n\n@note_ns.route('//parent')\nclass NoteParent(Resource):\n\n \"\"\" For finding parent Notes.\n \"\"\"\n\n @api.marshal_with(note_model)\n @api.response(200, 'Successfully read note')\n def get(self, uid):\n\n \"\"\" Get parent of note by id\n\n Get a parent note from the database\n according to the child's id\"\"\"\n\n child = Note.nodes.get_or_none(uid=uid)\n if child:\n parent = child.parent.get_or_none()\n if parent:\n return parent.to_dict()\n # else....\n # else ...\n\n\n@note_ns.route('//child')\nclass NoteChild(Resource):\n\n \"\"\" Finding Child Notes.\n \"\"\"\n\n @api.marshal_with(note_model)\n @api.response(200, 'Successfully read note')\n def get(self, uid):\n\n \"\"\" Get child of note by id\n\n Get a child note from the database\n according to the parent's id\"\"\"\n \n parent = Note.nodes.get_or_none(uid=uid)\n if parent:\n child = parent.child.get_or_none()\n if child:\n return child.to_dict()\n # else....\n # else ...\n\n @api.marshal_with(note_model)\n @api.response(201, 'Successfully created child note')\n @api.expect(note_content)\n def post(self, uid):\n\n \"\"\" Create a child of note by id\n\n Create and return a child note of the note according\n to id and archive the parent note \"\"\"\n\n parent = Note.nodes.get_or_none(uid=uid)\n if parent:\n # Parse content\n data = request.get_json()\n content = data.get(\"content\")\n # Create child\n child = Note(content=content)\n child.save()\n # Connect parent and child\n parent.child.connect(child)\n child.parent.connect(parent) # TODO test this\n parent.archived = True\n parent.save()\n child.save()\n return child.to_dict()\n # else...\n\n\n@note_ns.route(\"//archive\")\nclass NoteArchive(Resource):\n \"\"\"\n Archive a note\n \"\"\"\n @api.marshal_with(note_model)\n @api.response(200, 'Successfully archived note')\n def post(self, uid):\n \"\"\" Archive a note\n \"\"\"\n note = Note.nodes.get_or_none(uid=uid)\n if note:\n note.archived = True\n note.save()\n return note.to_dict()\n # else...\n","sub_path":"app/api/api_routes.py","file_name":"api_routes.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"367152716","text":"# 이 코드에서는 Python으로 손쉽게 Computer Vision API를 호출하는 방법을 소개해 드립니다.\n# Comupter Vision 이미지 분석 API method에 대한 문서는 이곳에서 참고하세요.\n# https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa\n\n# SQLER 강좌의 내용 https://www.sqler.com/board_CSharp/1095782 을 참조하세요.\n\n# requests 라이브러리를 사용하여 Python에서 간단하게 REST API 호출을 진행합니다.\nimport requests\n\n# 웹 서비스의 응답(Response)를 처리하려면 json 라이브러리가 필요합니다.\nimport json\n\n# SUBSCRIPTION_KEY를 자신의 Computer Vision 서비스의 키로 수정하세요.\nSUBSCRIPTION_KEY = \"xxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n\n# 아래 Vision_service_address를 자신에게 할당된 Computer Vision API 서비스의 주소로 수정해야 합니다. \n# 유료 가입 계정과 7일 체험 계정의 endpoint가 다를 수 있습니다. 맨 뒤의 \"/v2.0/\"을 확인하세요.\nvision_service_address = \"https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/\" \n\n# 호출하려는 API 함수의 이름을 주소에 추가합니다.\naddress = vision_service_address + \"analyze\"\n\n# analyze image 함수의 문서에 따르면 세 가지의 Optional(선택적) 파라미터가 있습니다 : language, details, visualFeatures 파라미터\nparameters = {'visualFeatures':'Description,Color',\n 'language':'en'}\n\n# 분석할 이미지가 포함된 파일을 열어서 파일 오브젝트로 가져옵니다.\nimage_path = \"./TestImages/PolarBear.jpg\"\nimage_data = open(image_path, \"rb\").read()\n\n# analyze image 함수 문서에서 기술한대로, HTTP 헤더에 구독 키와 content-type을 지정합니다.\n# content-type 값은 \"application/octet-stream\" 입니다.\nheaders = {'Content-Type': 'application/octet-stream',\n 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY}\n\n# analyze image 함수 문서에서 가이드 하는 것처럼, HTTP POST 방식으로 함수를 호출합니다.\nresponse = requests.post(address, headers=headers, params=parameters, data=image_data)\n\n# HTTP 호출에서 오류가 생기면, 예외를 발생 시킵니다.\nresponse.raise_for_status()\n\n# 리턴 받은 JSON 결과를 출력합니다.\nresults = response.json()\nprint(json.dumps(results))\n\n\n# description에 있는 모든 태그를 인쇄합니다.\nprint()\nprint('all tags')\nfor item in results['description']['tags']:\n print(item)\n\n# description의 첫 번째 태그를 인쇄합니다.\nprint()\nprint('first_tag')\nprint(results['description']['tags'][0])\n\n\n","sub_path":"python-for-beginners/17 - JSON/read_key_pair_list.py","file_name":"read_key_pair_list.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225165581","text":"from pathlib import Path\nfrom windcomponents import *\nfrom settings import *\nimport os\nimport shutil\nimport json\nimport explorer\nimport widget\nimport DefaultWidget\nimport re\n\ndef getSTR(strd):\n if(strd == None):\n return \"\"\n else:\n return str(strd)\n\nclass WidgetEmeeter:\n name: str\n desc: str\n version: str\n update: float\n uid: str\n path: str\n\n def getSettings(self):\n try:\n if(os.path.exists(self.dir + \"/properties.json\")):\n with open(self.dir + \"/properties.json\", \"r\") as f:\n decode_s = json.JSONDecoder().decode(f.read())\n return decode_s.get(self.uid) if decode_s.get(self.uid) != None else {}\n else:\n return {}\n except:\n return {}\n\n def saveSettings(self, settings):\n js = None\n try:\n if(os.path.exists(self.dir + \"/properties.json\")):\n with open(self.dir + \"/properties.json\", \"r\") as f:\n js = json.JSONDecoder().decode(f.read())\n else:\n js = {}\n except:\n js = {}\n\n with open(self.dir + \"/properties.json\", \"w\") as f:\n js[self.uid] = settings\n f.write(json.dumps(js))\n\n def __init__(self, name: str, desc: str, version: str, update: float, uid: str, dir: str, path: str):\n self.name = name\n self.desc = desc\n self.version = version\n self.update = update\n self.uid = uid\n self.dir = dir\n self.path = path\n\nclass Emeeter:\n dir: str\n name: str\n desc: str\n author: str\n uid: str\n widgets: list\n\n def __init__(self, dir: str, name: str, desc: str, author: str, uid: str):\n self.dir = dir\n self.name = name\n self.desc = desc\n self.author = author\n self.localisation = None\n self.uid = uid\n self.widgets = []\n\n \n\ndef listdir_fullpath(a_dir):\n return [name for name in os.listdir(a_dir)\n if os.path.isdir(os.path.join(a_dir, name))]\n\nasync def save(a, b):\n with open(str(Path(__file__).resolve().parent) + \"/data/\" + a, \"w\") as f:\n f.write(b)\n\ndef LoadLocale():\n try:\n global WINDOWLOCALe\n WINDOWLOCALe = json.loads(open(str(Path(__file__).resolve().parent)+\"/data/localisation.json\").read())[LOCALe]\n print(\"Localization set \" + LOCALe)\n except:\n print(\"An error occurred while loading the localization...\")\n\nclass WorkWindow(QMainWindow):\n items = {}\n\n def __init__(self, config):\n super().__init__()\n self.active_w = []\n self.config = config\n self.setMinimumSize(800, 390)\n self.setWindowFlags(Qt.Dialog)\n self.initUI()\n \n \"\"\"PRIVATE\"\"\"\n def initUI(self):\n self.theme = [\n 0x000000, #Default_color\n 0xffffff, #back_color\n 0x008cff, #Sellected_color\n 0x333333, #Active_color\n 0x333333, #BACTIVE\n 0xffffff, #BACTIVE\n [\n 0x363636,\n 0x0066ff\n ],\n 0x000000, #scrollbar\n [\n 0x333333, #checkbox active\n 0xfcfcfc #checkbox n active\n ]\n ]\n\n w = QDesktopWidget().screenGeometry()\n\n self.statusBar().setStyleSheet(\"background-color: #ffffff\")\n\n self.setWindowTitle('Wrain')\n\n self.setStatus(\"done_01\")\n\n self.setGeometry((w.width() - w.width() * 0.6)*0.5, (w.height() - w.height() * 0.5)*0.5, w.width() * 0.6, w.height() * 0.5)\n\n self.items[\"itemlist\"] = QSpeciaList(self)\n\n if(\"empty_01\" in WINDOWLOCALe):\n self.items[\"itemlist\"].empty_text = WINDOWLOCALe[\"empty_01\"]\n\n self.items[\"add-item\"] = QButtonE(self)\n self.items[\"add-item\"].logger = self.statusBar().showMessage\n\n self.items[\"d_tools\"] = layer()\n self.items[\"d_tools\"].setVisable(False)\n\n if(\"st_button_01\" in WINDOWLOCALe and \"st_button_03\" in WINDOWLOCALe and \"st_button_05\" in WINDOWLOCALe):\n self.items[\"header\"] = QHeader(self, [WINDOWLOCALe[\"st_button_01\"], WINDOWLOCALe[\"st_button_03\"], WINDOWLOCALe[\"st_button_05\"]])\n self.items[\"header\"].handler = self.headerTracker\n \n if(\"st_version_01\" in WINDOWLOCALe and \"st_desc_01\" in WINDOWLOCALe):\n self.items[\"body-left\"] = infoBlock(self, WINDOWLOCALe[\"st_version_01\"], WINDOWLOCALe[\"st_desc_01\"])\n \n self.items[\"body-right\"] = widgetManager(self)\n self.items[\"body-settings\"] = systemSettings(self)\n\n self.items[\"body-settings\"].listener = self.settingsChangeListener\n\n self.items[\"d_tools\"].add(self.items[\"header\"])\n self.items[\"d_tools\"].add(self.items[\"body-left\"])\n self.items[\"d_tools\"].add(self.items[\"body-right\"])\n self.items[\"d_tools\"].add(self.items[\"body-settings\"])\n\n self.updateProjectList()\n self.initStartup()\n\n def buildDescription(self, desc, localisation):\n def replacer(math):\n print(localisation.keys())\n for local in localisation.keys():\n if(local == math.group(1)):\n return localisation[local]\n else:\n return math.group(0)\n\n return re.sub(r\"\\{\\$([aA-zZ0-9_]+)\\}\", replacer, desc)\n\n def settingsChangeListener(self, index, pd, bl):\n item = self.getSellection()\n s = item.odata.widgets[item.sellected].getSettings()\n if(index == 0):\n s[\"on-the-top\"] = bl\n item.odata.widgets[item.sellected].saveSettings(s)\n\n \"\"\"PUBLIC\"\"\"\n def removeSellection(self):\n index = 0\n for item in self.items[\"itemlist\"].items:\n if(item.sellected != -2):\n del self.items[\"itemlist\"].items[index]\n shutil.rmtree(item.odata.dir)\n self.items[\"d_tools\"].setVisable(False)\n self.items[\"itemlist\"].update()\n index+=1\n\n \"\"\"PRIVATE\"\"\"\n def headerTracker(self, index):\n item = self.getSellection()\n\n if(index == 0):\n itemid = str(item.odata.uid + \"#\" + str(item.sellected))\n\n if(item.sellected != -1):\n if(self.getWindowByUid(itemid) == None):\n self.startup(item)\n if(\"st_button_02\" in WINDOWLOCALe):\n self.items[\"header\"].setText(0, WINDOWLOCALe[\"st_button_02\"])\n self.items[\"itemlist\"].update()\n else:\n index = 0\n for active in self.active_w:\n if(str(active.id) == itemid):\n self.setStatus(\"st_rm_complete_01\")\n self.active_w[index].close()\n item.active.remove(item.sellected)\n del self.active_w[index]\n if(\"st_button_01\" in WINDOWLOCALe):\n self.items[\"header\"].setText(0, WINDOWLOCALe[\"st_button_01\"])\n self.items[\"itemlist\"].update()\n return\n index += 1\n return\n \n if(index == 1):\n #AUTOSTART\n if(not item.odata.widgets[item.sellected].uid in self.config.get(\"active_emiters\")):\n self.config.get(\"active_emiters\").append(item.odata.widgets[item.sellected].uid)\n if(\"st_button_04\" in WINDOWLOCALe):\n self.items[\"header\"].setText(1, WINDOWLOCALe[\"st_button_04\"])\n aysync.run_await(save(\"config.json\", json.dumps(self.config, sort_keys=True, indent=4)))\n else:\n self.config.get(\"active_emiters\").remove(item.odata.widgets[item.sellected].uid)\n if(\"st_button_03\" in WINDOWLOCALe):\n self.items[\"header\"].setText(1, WINDOWLOCALe[\"st_button_03\"])\n aysync.run_await(save(\"config.json\", json.dumps(self.config, sort_keys=True, indent=4)))\n return\n \n if(index == 2):\n explorer.openFolder(item.odata.dir)\n\n \"\"\"PUBLIC\"\"\"\n def getSellection(self):\n for item in self.items[\"itemlist\"].items:\n if(item.sellected != -2):\n return item\n return -2\n \"\"\"PRIVATE\"\"\"\n def updateProjectList(self):\n rt_list = []\n self.setStatus(\"loading_01\")\n decoder = json.JSONDecoder()\n \n if(os.path.exists(installer.WORKPATH)):\n\n for dir in listdir_fullpath(installer.WORKPATH):\n dir = installer.WORKPATH + dir\n\n if(os.path.exists(dir + \"/project.json\")):\n with open(dir + \"/project.json\") as f:\n decoded = decoder.decode(f.read())\n\n section = QTSection(decoded.get(\"package\").get(\"name\"))\n\n section.odata = Emeeter(\n dir,\n decoded.get(\"package\").get(\"name\").replace(\"\\n\", \"|\"),\n decoded.get(\"package\").get(\"desc\"),\n decoded.get(\"package\").get(\"author\"),\n decoded.get(\"uid\")\n )\n if(os.path.exists(dir + \"/localisation.json\")):\n try:\n with open(dir + \"/localisation.json\") as F:\n local = decoder.decode(F.read())\n section.odata.localisation = local.get(LOCALe)\n except:\n self.setStatus(\"st_no_localisation\")\n else:\n self.setStatus(\"st_no_localisation\")\n\n section.addHandler(self.loadWidgetMenu)\n\n for wg in decoded.get(\"widgets\"):\n with open(dir + \"/\" + str(wg) + \".json\") as w:\n wdecode = decoder.decode(w.read())\n section.addChildren(wdecode.get(\"widget\").get(\"name\"))\n section.odata.widgets.append(WidgetEmeeter(\n wdecode.get(\"widget\").get(\"name\").replace(\"\\n\", \"|\"),\n wdecode.get(\"widget\").get(\"description\"),\n str(wdecode.get(\"widget\").get(\"version\") if wdecode.get(\"widget\").get(\"version\") != None else decoded.get(\"package\").get(\"version\")),\n wdecode.get(\"widget\").get(\"update\"),\n wdecode.get(\"uid\"),\n dir,\n dir + \"/\" + str(wg) + \".json\"\n ))\n \n rt_list.append(section)\n else:\n shutil.rmtree(dir)\n self.items[\"itemlist\"].items = rt_list\n self.items[\"itemlist\"].update()\n self.setStatus(\"done_01\")\n \n \"\"\"PRIVATE\"\"\"\n def loadWidgetMenu(self, data, type):\n self.items[\"d_tools\"].setVisable(type != None and data.sellected != -1)\n sets = data.odata.widgets[data.sellected].getSettings()\n itemid = str(data.odata.uid + \"#\" + str(data.sellected))\n sellected = data.odata.widgets[data.sellected]\n self.items[\"header\"].setText(-1, sellected.name)\n\n if(type != None):\n self.items[\"body-settings\"].clear()\n\n description = sellected.desc if sellected.desc != None else WINDOWLOCALe[\"st_no_description\"]\n description = self.buildDescription(description, data.odata.localisation if data.odata.localisation != None else {})\n\n if(sets != None):\n self.items[\"body-settings\"].addParameter(WINDOWLOCALe[\"dr_dx11_mp\"], sets.get(\"on-the-top\") if sets.get(\"on-the-top\") != None else False)\n\n if(not sellected.uid in self.config.get(\"active_emiters\")):\n if(\"st_button_03\" in WINDOWLOCALe):\n self.items[\"header\"].setText(1, WINDOWLOCALe[\"st_button_03\"])\n else:\n if(\"st_button_04\" in WINDOWLOCALe):\n self.items[\"header\"].setText(1, WINDOWLOCALe[\"st_button_04\"])\n \n if(self.getWindowByUid(itemid) == None):\n if(\"st_button_01\" in WINDOWLOCALe):\n self.items[\"header\"].setText(0, WINDOWLOCALe[\"st_button_01\"])\n else:\n if(\"st_button_02\" in WINDOWLOCALe):\n self.items[\"header\"].setText(0, WINDOWLOCALe[\"st_button_02\"])\n\n self.items[\"body-left\"].restore()\n self.items[\"body-left\"].setText(getSTR(sellected.version), description)\n \n self.update()\n \n return\n \"\"\"PRIVATE\"\"\"\n\n def getWindowByUid(self, uid):\n for act in self.active_w:\n if(act.id == uid):\n return act\n else:\n return None\n\n \"\"\"PRIVATE\"\"\"\n def startup(self, item, index = None):\n index = index if index != None else item.sellected\n\n DECODER = json.JSONDecoder()\n\n with open(item.odata.widgets[index].path) as f:\n decode_s = DECODER.decode(f.read())\n\n if(decode_s.get(\"widget\") != None):\n drawer = os.path.join(item.odata.dir, str(index)+\".py\")\n drawername = \".py\"\n\n if(decode_s.get(\"widget\").get(\"drawer\") != None):\n drawer = os.path.join(item.odata.dir, decode_s.get(\"widget\").get(\"drawer\"))\n drawername = decode_s.get(\"widget\").get(\"drawer\")\n\n settings = Settings(None, None, item.odata.name, None)\n if(decode_s.get(\"widget\").get(\"default\") != None):\n settings = Settings(\n decode_s.get(\"widget\").get(\"default\").get(\"width\"),\n decode_s.get(\"widget\").get(\"default\").get(\"height\"),\n item.odata.name,\n decode_s.get(\"widget\").get(\"default\").get(\"origin\")\n )\n\n item.active.append(index)\n item.wid = item.odata.uid\n\n self.items[\"d_tools\"].update()\n\n try:\n w = widget.Widget(decode_s.get(\"widget\"), drawer, drawername, settings, self, item.odata.uid + \"#\" + str(index))\n \n s = item.odata.widgets[index].getSettings()\n if(s.get(\"x\") != None and s.get(\"y\") != None):\n w.move(s[\"x\"], s[\"y\"])\n \n self.active_w.append(w)\n except:\n self.setStatus(\"st_initialisation_error\")\n else:\n self.setStatus(\"st_initialisation_error\")\n\n def initStartup(self):\n emiters = []\n for item in self.items[\"itemlist\"].items:\n index = 0\n for sl in item.odata.widgets:\n if(sl.uid in self.config[\"active_emiters\"]):\n print(\"Run \"+sl.uid)\n self.startup(item, index)\n emiters.append(sl.uid)\n index += 1\n for emiter in self.config[\"active_emiters\"]:\n if(not emiter in emiters):\n self.config[\"active_emiters\"].remove(emiter)\n aysync.run_await(save(\"config.json\", json.dumps(self.config, indent=4)))\n\n def closeEvent(self, event):\n self.hide()\n if(len(self.active_w) == 0):\n def show():\n self.show()\n del self.active_w[0]\n if(\"st_open_01\" in WINDOWLOCALe):\n dw = DefaultWidget.Widget(WINDOWLOCALe[\"st_open_01\"])\n dw.show()\n dw.mousePressEvent = lambda event: show()\n self.active_w.append(dw)\n event.ignore()\n\n def resizeEvent(self, event):\n l_bar = self.width() * 0.4 if self.width() * 0.4 < 300 else 300\n \n self.items[\"itemlist\"].resize(l_bar, self.height() - 52)\n\n self.items[\"add-item\"].resize(l_bar, 30)\n self.items[\"add-item\"].move(0, self.height() - 52)\n\n self.items[\"header\"].move(l_bar, 0)\n self.items[\"header\"].resize(self.width() - l_bar, 30)\n\n self.items[\"body-right\"].resize(self.width() - l_bar*2, self.height() - 30 - 150)\n self.items[\"body-right\"].move(l_bar*2, 30)\n\n self.items[\"body-left\"].resize(l_bar, self.height() - 30 - 150)\n self.items[\"body-left\"].move(l_bar, 30)\n\n self.items[\"body-settings\"].resize(l_bar, 150)\n self.items[\"body-settings\"].move(l_bar, self.height() - 150)\n\n #common_autostart\n def setStatus(self, status):\n if(status in WINDOWLOCALe):\n self.statusBar().showMessage(WINDOWLOCALe[status])","sub_path":"main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":16968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"347571128","text":"import re\nfrom collections import OrderedDict\n\nfrom django import forms\nfrom django.conf import settings\nfrom govuk_forms.forms import GOVUKForm\n\nfrom datetime import date, datetime, timedelta\n\nfrom ..fields import CustomSplitDateFieldNameAndAddressHistory\n\n\nclass PreviousAddressEntryForm(GOVUKForm):\n\n ERROR_MESSAGE_POSTCODE_NOT_ENTERED = 'Please enter your postcode'\n\n field_label_classes = 'form-label-bold'\n auto_replace_widgets = True\n error_summary_title = 'There was a problem'\n\n postcode = forms.CharField(label='Postcode', error_messages={'required': 'Please enter your postcode'})\n\n\nclass PreviousAddressSelectForm(GOVUKForm):\n # Address validation messages\n ERROR_MESSAGE_ADDRESS_BLANK = 'Please select your address'\n\n # Moved in/out date validation messages\n ERROR_MESSAGE_DATE_BLANK = 'Enter the full date, including the day, month and year'\n ERROR_MESSAGE_DAY_OUT_OF_RANGE = 'Day must be between 1 and 31'\n ERROR_MESSAGE_MONTH_OUT_OF_RANGE = 'Month must be between 1 and 12'\n ERROR_MESSAGE_MOVED_IN_YEAR_BEFORE_1900 = 'Date moved in must be after 1900'\n ERROR_MESSAGE_MOVED_OUT_YEAR_BEFORE_1900 = 'Date you moved out must be after 1900'\n ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS = 'Enter the whole year (4 digits)'\n ERROR_MESSAGE_INVALID_DATE = 'Enter a real date'\n ERROR_MESSAGE_NON_NUMERIC = 'Use numbers for the date'\n\n ERROR_MESSAGE_MOVED_IN_DATE_AFTER_CURRENT_DATE = 'Enter the full date, including day, month and year. This cannot be in the future'\n ERROR_MESSAGE_MOVED_IN_DATE_AFTER_MOVED_OUT_DATE = 'Date you moved in must be before date you moved out'\n\n ERROR_MESSAGE_MOVED_OUT_DATE_AFTER_CURRENT_DATE = 'Enter the full date, including day, month and year. This cannot be in the future'\n ERROR_MESSAGE_MOVED_OUT_DATE_BEFORE_MOVED_IN_DATE = 'Date you moved out must be after the date you moved in'\n\n ERROR_MESSAGE_MOVED_OUT_DATE_OVER_FIVE_YEARS_AGO = 'Date you moved out must be less than five years ago'\n\n auto_replace_widgets = True\n field_label_classes = 'form-label-bold'\n error_summary_title = 'There was a problem'\n\n address = forms.ChoiceField(\n label='Select address',\n required=True,\n error_messages={'required': ERROR_MESSAGE_ADDRESS_BLANK}\n )\n moved_in_date = CustomSplitDateFieldNameAndAddressHistory(\n label='Date you moved in',\n required=True,\n help_text='For example, 31 03 1980',\n min_value=None,\n max_value=CustomSplitDateFieldNameAndAddressHistory.TODAY,\n allow_short_year=False,\n error_messages={'required': ERROR_MESSAGE_DATE_BLANK,\n 'incomplete': ERROR_MESSAGE_DATE_BLANK,\n 'max_today': ERROR_MESSAGE_MOVED_IN_DATE_AFTER_CURRENT_DATE,\n 'invalid': ERROR_MESSAGE_INVALID_DATE},\n day_error_messages={'min_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n month_error_messages={'min_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n year_min_value=1900,\n year_max_value=None,\n year_error_messages={'min_value': ERROR_MESSAGE_MOVED_IN_YEAR_BEFORE_1900,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC,\n 'short_year': ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS},\n )\n moved_out_date = CustomSplitDateFieldNameAndAddressHistory(\n label='Date you moved out',\n required=True,\n help_text='For example, 31 03 1980',\n min_value=None,\n max_value=CustomSplitDateFieldNameAndAddressHistory.TODAY,\n allow_short_year=False,\n error_messages={'required': ERROR_MESSAGE_DATE_BLANK,\n 'incomplete': ERROR_MESSAGE_DATE_BLANK,\n 'max_today': ERROR_MESSAGE_MOVED_OUT_DATE_AFTER_CURRENT_DATE,\n 'invalid': ERROR_MESSAGE_INVALID_DATE},\n day_error_messages={'min_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n month_error_messages={'min_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n year_min_value=1900,\n year_max_value=None,\n year_error_messages={'min_value': ERROR_MESSAGE_MOVED_OUT_YEAR_BEFORE_1900,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC,\n 'short_year': ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS},\n )\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Configure available address choices via passed kwarg.\n \"\"\"\n self.choices = kwargs.pop('choices')\n super(PreviousAddressSelectForm, self).__init__(*args, **kwargs)\n self.fields['address'].choices = self.choices\n\n def clean(self):\n super().clean()\n\n # check start date is after end date\n start_date = self.cleaned_data.get('moved_in_date', None)\n end_date = self.cleaned_data.get('moved_out_date', None)\n if start_date and end_date and end_date <= start_date:\n self.add_error('moved_in_date', self.ERROR_MESSAGE_MOVED_IN_DATE_AFTER_MOVED_OUT_DATE)\n self.add_error('moved_out_date', self.ERROR_MESSAGE_MOVED_OUT_DATE_BEFORE_MOVED_IN_DATE)\n\n end_date = self.cleaned_data.get('moved_out_date', None)\n five_years_ago = subtract_years(datetime.today().date(), 5)\n if end_date and five_years_ago > end_date:\n self.add_error('moved_out_date', self.ERROR_MESSAGE_MOVED_OUT_DATE_OVER_FIVE_YEARS_AGO)\n\n # de-duplicate error messages for each field\n for field, errors in self.errors.items():\n dedup = OrderedDict([(k, None) for k in errors])\n self.errors[field] = list(dedup.keys())\n\n\nclass PreviousAddressManualForm(GOVUKForm):\n \"\"\"\n Form for adding previous addresses to childminder/nanny applicants, people in the home, children etc.\n \"\"\"\n\n # Manual address entry field validation messages\n ERROR_MESSAGE_STREET_LINE_1_BLANK = 'Please enter the first line of your address'\n ERROR_MESSAGE_STREET_LINE_1_TOO_LONG = 'The first line of your address must be under 50 characters long'\n ERROR_MESSAGE_STREET_LINE_2_TOO_LONG = 'The second line of your address must be under 50 characters long'\n ERROR_MESSAGE_TOWN_BLANK = 'Please enter the name of the town or city'\n ERROR_MESSAGE_TOWN_INVALID = 'Spell out the name of the town or city using letters'\n ERROR_MESSAGE_TOWN_TOO_LONG = 'The name of the town or city must be under 50 characters long'\n ERROR_MESSAGE_COUNTY_INVALID = 'Spell out the name of the county using letters'\n ERROR_MESSAGE_COUNTY_TOO_LONG = 'The name of the county must be under 50 characters long'\n ERROR_MESSAGE_COUNTRY_BLANK = 'Please enter the name of the country'\n ERROR_MESSAGE_COUNTRY_INVALID = 'Spell out the name of the country using letters'\n ERROR_MESSAGE_COUNTRY_TOO_LONG = 'The name of the country must be under 50 characters long'\n ERROR_MESSAGE_POSTCODE_BLANK = 'Please enter your postcode'\n ERROR_MESSAGE_POSTCODE_INVALID = 'Please enter a valid postcode'\n ERROR_MESSAGE_POSTCODE_INVALID_UK_ADDRESS = 'Placeholder - Altered in view for ID'\n\n # Moved in/out date validation messages\n ERROR_MESSAGE_DATE_BLANK = 'Enter the full date, including the day, month and year'\n ERROR_MESSAGE_DAY_OUT_OF_RANGE = 'Day must be between 1 and 31'\n ERROR_MESSAGE_MONTH_OUT_OF_RANGE = 'Month must be between 1 and 12'\n ERROR_MESSAGE_MOVED_IN_YEAR_BEFORE_1900 = 'Date moved in must be after 1900'\n ERROR_MESSAGE_MOVED_OUT_YEAR_BEFORE_1900 = 'Date you moved out must be after 1900'\n ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS = 'Enter the whole year (4 digits)'\n ERROR_MESSAGE_INVALID_DATE = 'Enter a real date'\n ERROR_MESSAGE_NON_NUMERIC = 'Use numbers for the date'\n\n ERROR_MESSAGE_MOVED_IN_DATE_AFTER_CURRENT_DATE = 'Enter the full date, including day, month and year. This cannot be in the future'\n ERROR_MESSAGE_MOVED_IN_DATE_AFTER_MOVED_OUT_DATE = 'Date you moved in must be before date you moved out'\n\n ERROR_MESSAGE_MOVED_OUT_DATE_AFTER_CURRENT_DATE = 'Enter the full date, including day, month and year. This cannot be in the future'\n ERROR_MESSAGE_MOVED_OUT_DATE_BEFORE_MOVED_IN_DATE = 'Date you moved out must be after the date you moved in'\n\n ERROR_MESSAGE_MOVED_OUT_DATE_OVER_FIVE_YEARS_AGO = 'Date you moved out must be less than five years ago'\n\n auto_replace_widgets = True\n field_label_classes = 'form-label-bold'\n error_summary_title = 'There was a problem'\n\n street_line1 = forms.CharField(\n label='Address line 1',\n required=True,\n error_messages={'required': ERROR_MESSAGE_STREET_LINE_1_BLANK}\n )\n\n street_line2 = forms.CharField(\n label='Address line 2',\n required=False\n )\n\n town = forms.CharField(\n label='Town or city',\n required=True,\n error_messages={'required': ERROR_MESSAGE_TOWN_BLANK}\n )\n\n county = forms.CharField(\n label='County (optional)',\n required=False\n )\n\n country = forms.CharField(\n label='Country',\n required=True,\n error_messages={'required': ERROR_MESSAGE_COUNTRY_BLANK}\n )\n\n postcode = forms.CharField(\n label='Postcode',\n required=True,\n error_messages={'required': ERROR_MESSAGE_POSTCODE_BLANK}\n )\n\n moved_in_date = CustomSplitDateFieldNameAndAddressHistory(\n label='Date you moved in',\n required=True,\n help_text='For example, 31 03 2012',\n min_value=None,\n max_value=CustomSplitDateFieldNameAndAddressHistory.TODAY,\n allow_short_year=False,\n error_messages={'required': ERROR_MESSAGE_DATE_BLANK,\n 'incomplete': ERROR_MESSAGE_DATE_BLANK,\n 'max_today': ERROR_MESSAGE_MOVED_IN_DATE_AFTER_CURRENT_DATE,\n 'invalid': ERROR_MESSAGE_INVALID_DATE},\n day_error_messages={'min_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n month_error_messages={'min_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n year_min_value=1900,\n year_max_value=None,\n year_error_messages={'min_value': ERROR_MESSAGE_MOVED_IN_YEAR_BEFORE_1900,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC,\n 'short_year': ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS},\n )\n moved_out_date = CustomSplitDateFieldNameAndAddressHistory(\n label='Date you moved out',\n required=True,\n help_text='For example, 31 03 2012',\n min_value=None,\n max_value=CustomSplitDateFieldNameAndAddressHistory.TODAY,\n allow_short_year=False,\n error_messages={'required': ERROR_MESSAGE_DATE_BLANK,\n 'incomplete': ERROR_MESSAGE_DATE_BLANK,\n 'max_today': ERROR_MESSAGE_MOVED_OUT_DATE_AFTER_CURRENT_DATE,\n 'invalid': ERROR_MESSAGE_INVALID_DATE},\n day_error_messages={'min_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_DAY_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n month_error_messages={'min_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'max_value': ERROR_MESSAGE_MONTH_OUT_OF_RANGE,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC},\n year_min_value=1900,\n year_max_value=None,\n year_error_messages={'min_value': ERROR_MESSAGE_MOVED_OUT_YEAR_BEFORE_1900,\n 'invalid': ERROR_MESSAGE_NON_NUMERIC,\n 'short_year': ERROR_MESSAGE_YEAR_LESS_THAN_4_DIGITS},\n )\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Setup initial data for the manual form\n \"\"\"\n record = kwargs.pop('record', None)\n moved_in_date = kwargs.pop('moved_in_date', None)\n moved_out_date = kwargs.pop('moved_out_date', None)\n lived_abroad = kwargs.pop('lived_abroad', None)\n super().__init__(*args, **kwargs)\n\n if record:\n self.fields['street_line1'].initial = record.street_line1\n self.fields['street_line2'].initial = record.street_line2\n self.fields['town'].initial = record.town\n self.fields['county'].initial = record.county\n self.fields['country'].initial = record.country\n self.fields['postcode'].initial = record.postcode\n self.fields['moved_in_date'].initial = moved_in_date\n self.fields['moved_out_date'].initial = moved_out_date\n\n if not lived_abroad:\n self.base_fields['country'].required = False\n self.base_fields['postcode'].required = True\n self.base_fields['country'].label = 'Country (optional)'\n self.base_fields['postcode'].label = 'Postcode'\n if lived_abroad:\n self.base_fields['postcode'].required = False\n self.base_fields['country'].required = True\n self.base_fields['country'].label = 'Country'\n self.base_fields['postcode'].label = 'Postcode (optional)'\n\n def clean(self):\n super().clean()\n\n # check start date is after end date\n start_date = self.cleaned_data.get('moved_in_date', None)\n end_date = self.cleaned_data.get('moved_out_date', None)\n if start_date and end_date and end_date <= start_date:\n self.add_error('moved_in_date', self.ERROR_MESSAGE_MOVED_IN_DATE_AFTER_MOVED_OUT_DATE)\n self.add_error('moved_out_date', self.ERROR_MESSAGE_MOVED_OUT_DATE_BEFORE_MOVED_IN_DATE)\n\n end_date = self.cleaned_data.get('moved_out_date', None)\n five_years_ago = subtract_years(datetime.today().date(), 5)\n if end_date and five_years_ago > end_date:\n self.add_error('moved_out_date', self.ERROR_MESSAGE_MOVED_OUT_DATE_OVER_FIVE_YEARS_AGO)\n\n def clean_street_line1(self):\n \"\"\"\n Street name and number validation\n :return: string\n \"\"\"\n street_line1 = self.cleaned_data['street_line1']\n if len(street_line1) > 50:\n raise forms.ValidationError(self.ERROR_MESSAGE_STREET_LINE_1_TOO_LONG)\n return street_line1\n\n def clean_street_line2(self):\n \"\"\"\n Street name and number line 2 validation\n :return: string\n \"\"\"\n street_line2 = self.cleaned_data['street_line2']\n if len(street_line2) > 50:\n raise forms.ValidationError(self.ERROR_MESSAGE_STREET_LINE_2_TOO_LONG)\n return street_line2\n\n def clean_town(self):\n \"\"\"\n Town validation\n :return: string\n \"\"\"\n town = self.cleaned_data['town']\n if re.match(settings.REGEX['TOWN'], town) is None:\n raise forms.ValidationError(self.ERROR_MESSAGE_TOWN_INVALID)\n if len(town) > 50:\n raise forms.ValidationError(self.ERROR_MESSAGE_TOWN_TOO_LONG)\n return town\n\n def clean_county(self):\n \"\"\"\n County validation\n :return: string\n \"\"\"\n county = self.cleaned_data['county']\n if county != '':\n if re.match(settings.REGEX['COUNTY'], county) is None:\n raise forms.ValidationError(self.ERROR_MESSAGE_COUNTY_INVALID)\n if len(county) > 50:\n raise forms.ValidationError(self.ERROR_MESSAGE_COUNTY_TOO_LONG)\n return county\n\n def clean_country(self):\n \"\"\"\n Country validation\n :return: string\n \"\"\"\n country = self.cleaned_data['country']\n if country != '':\n if re.match(settings.REGEX['COUNTRY'], country) is None:\n raise forms.ValidationError(self.ERROR_MESSAGE_COUNTRY_INVALID)\n if len(country) > 50:\n raise forms.ValidationError(self.ERROR_MESSAGE_COUNTRY_TOO_LONG)\n return country\n\n def clean_postcode(self):\n \"\"\"\n Postcode validation\n :return: string\n \"\"\"\n postcode = self.cleaned_data['postcode']\n if postcode != '':\n postcode_no_space = postcode.replace(\" \", \"\")\n postcode_uppercase = postcode_no_space.upper()\n if not self.base_fields['postcode'].required:\n if re.match(settings.REGEX['POSTCODE_MANUAL'], postcode_uppercase) is None:\n raise forms.ValidationError(self.ERROR_MESSAGE_POSTCODE_INVALID)\n else:\n if re.match(settings.REGEX['POSTCODE_UPPERCASE'], postcode_uppercase) is None:\n raise forms.ValidationError(self.ERROR_MESSAGE_POSTCODE_INVALID_UK_ADDRESS)\n return postcode\n\n\ndef subtract_years(dt, years):\n \"\"\"\n Method returning the date submitted minus the years specified\n :param dt: a datetime object\n :param years: the number of years to remove\n :return: a datetime object\n \"\"\"\n try:\n dt = dt.replace(year=dt.year-years)\n except ValueError:\n dt = dt.replace(year=dt.year-years, day=dt.day-1)\n return dt","sub_path":"application/forms/other_person_health_check/previous_addresses.py","file_name":"previous_addresses.py","file_ext":"py","file_size_in_byte":17707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"223933667","text":"\"\"\"Module for analysing feeding buzz bouts\"\"\"\n\nimport time\nfrom collections import defaultdict\n\nfrom helper.write_data import write_array\nfrom sonochiro_dataset_creation import load_sonochiro_file\n\n\ndef transect_entries(sonochiro_array):\n \"\"\"Return a dictionary with for each transect sorted timestamps of all recordings\"\"\"\n activity_times = defaultdict(list)\n for row in sonochiro_array:\n transect, sec_time = row[1], row[5]\n activity_times[transect].append(sec_time)\n for tr in activity_times: # sort all entry times\n activity_times[tr] = sorted(activity_times[tr])\n return activity_times\n\n\ndef find_activity_gaps(sonochiro_array, gap_sec):\n \"\"\"Return a dictionary with for each transect the end time of each\n activity gap same as or larger than specified gap_sec\"\"\"\n activity_gaps = defaultdict(list)\n activity_times = transect_entries(sonochiro_array)\n for transect in activity_times:\n last_activity = 0 # ensure first recording of transect is included\n for activity in activity_times[transect]:\n if activity - last_activity >= gap_sec: # if it is the end time of a gap longer than gap_sec seconds\n activity_gaps[transect].append(activity)\n last_activity = activity\n return activity_gaps\n\n\ndef find_time_since_end_activity_gap(activity_gap_dict, transect, recording_time):\n \"\"\"Return time as int since last activity gap for a given transect and recording time\"\"\"\n for i, gap_end_time in enumerate(activity_gap_dict[transect]):\n if recording_time < gap_end_time:\n return recording_time - activity_gap_dict[transect][i-1]\n elif recording_time == gap_end_time:\n return 0\n else: # the entry is after the last gap_end_time so will not be found with above for loop\n return recording_time - activity_gap_dict[transect][-1]\n\n\ndef create_bout_analysis_dataset(sonochiro_array, gap_sec, only_pp=True, buzz_index=2):\n \"\"\"Create and return a sonochiro array with additional information per file on time since last gap\n and whether a buzz index was higher or the same as specified buzz_index. Can filter out everything\n that is not identified as a Pippistrellus pippistrellus.\n \"\"\"\n if only_pp: # filter out entries other than Pippistrellus pippistrellus\n edited_array = [row for row in sonochiro_array if row[8] == \"PippiT\"]\n else:\n edited_array = sonochiro_array[:] # create copy to avoid editing original array\n activity_gaps = find_activity_gaps(edited_array, gap_sec)\n for i, row in enumerate(edited_array):\n transect, time_in_sec = row[1], row[5]\n gap_dt = find_time_since_end_activity_gap(activity_gaps, transect, time_in_sec)\n row.extend([gap_dt, 0])\n if row[19] >= buzz_index:\n row[-1] = 1\n edited_array[i] = row\n column_names = ['filename', 'transect', 'site', 'colour', 'night', 'total_time_sec', 'detector', 'comp_fl',\n 'final_id', 'contact', 'group', 'group_index', 'species', 'species_index',\n 'nb_calls', 'med_freq', 'med_int', 'i_qual', 'i_sc', 'i_buzz', 'gap_dt', 'buzz']\n return edited_array, column_names\n\n\nif __name__ == \"__main__\":\n gap = 30 # which amount of seconds is defined as a gap\n file_to_write = \"dataset_bout_analysis_with_{}_second_gaps.csv\".format(gap)\n\n start = time.time()\n sc = load_sonochiro_file()[0]\n print(\"loaded sc file in {:.3f} seconds\".format(time.time()-start))\n start2 = time.time()\n bout_array, col_names = create_bout_analysis_dataset(sc, gap)\n print(\"created bout array in {:.3f} seconds\".format(time.time() - start2))\n write_array(bout_array, col_names, file_to_write)\n","sub_path":"feed_buzz_bout_analysis.py","file_name":"feed_buzz_bout_analysis.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"646930618","text":"class Solution:\r\n def eraseOverlapIntervals(self, intervals):\r\n\r\n if not intervals:\r\n return 0\r\n\r\n erase_count = 0\r\n\r\n intervals.sort(key=lambda interval: interval[0])\r\n\r\n previous_end = intervals[0][1]\r\n\r\n for i in range(1,len(intervals)):\r\n interval = intervals[i]\r\n start = interval[0]\r\n end = interval[1]\r\n\r\n if start < previous_end:\r\n erase_count += 1\r\n previous_end = min(previous_end, end)\r\n\r\n else:\r\n previous_end = end\r\n\r\n return erase_count","sub_path":"Intervals/LC_435_eraseOverlapIntervals.py","file_name":"LC_435_eraseOverlapIntervals.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"416953421","text":"\nimport numpy as np\nimport constants as const\nimport codecs\n\nclass Loc():\n def __init__(self,x,y):\n self.x = x\n self.y = y\n \n def __eq__(self,other):\n return (self.x == other.x) and (self.y == other.y)\n \n def __ne__(self,other):\n return (self.x != other.x) or (self.y != other.y)\n \n def __str__(self):\n return '('+str(self.x)+','+str(self.y)+')'\n \n def __hash__(self):\n return hash(str(self))\n \ndef find_location_in_array(x,xs):\n xs = np.array(xs)\n index = np.where(xs==x)[0]\n if (index.size==0):\n return None\n else:\n return index[0]\n \ndef compute_adjacent(loc,world):\n minx = 0; maxx = world.height-1;\n miny = 0; maxy = world.width-1;\n \n nextxs = []\n if loc.x == 0:\n nextxs.append(1)\n elif loc.x == maxx:\n nextxs.append(maxx-1)\n else:\n nextxs.append(loc.x+1)\n nextxs.append(loc.x-1)\n \n nextys = []\n if loc.y == 0:\n nextys.append(1)\n elif loc.y == maxy:\n nextys.append(maxy-1)\n else:\n nextys.append(loc.y+1)\n nextys.append(loc.y-1)\n \n nextlocs = []\n for x in nextxs:\n nextlocs.append(gw.Loc(x,loc.y))\n for y in nextys:\n nextlocs.append(gw.Loc(loc.x,y))\n \n return nextlocs \n\nclass GridWorld():\n \n def __init__(self, width, height, start_x, start_y, end_x, end_y):\n # TODO: check conditions on width, height, start_x, start_y, end_x, end_y\n \n self.width = width\n self.height = height\n self.starting_position = Loc(start_x,start_y)\n self.ending_position = Loc(end_x,end_y)\n self.current_position = self.starting_position\n \n self.termination = False\n \n self.world = np.zeros((width,height))\n self.world[start_x,start_y] = const.STARTING\n self.world[end_x,end_y] = const.ENDING\n \n def add_wall(self,x,y):\n # TODO: check conditions on x,y\n self.world[x,y] = const.WALL\n \n def add_trap(self,x,y):\n # TODO: check conditions on x,y\n self.world[x,y] = const.TRAP\n \n def reset(self):\n self.termination = False\n self.current_position = self.starting_position\n \n return self.current_position, 0, self.termination, []\n \n def step(self,action):\n \n if(not self.termination):\n self.current_position, transition_msgs = self._compute_transition(action)\n reward, reward_msgs = self._compute_reward()\n termination_msgs = self._check_termination()\n return self.current_position, reward, self.termination, [transition_msgs,reward_msgs,termination_msgs]\n \n else:\n return Loc(-1,-1), -1, self.termination, 'Game is over'\n \n def _compute_transition(self,action):\n x = self.current_position.x\n y = self.current_position.y\n \n if action==const.LEFT:\n if (y==0): return self.current_position, 'I can not move out of the world'\n elif (self.world[x,y-1]==const.WALL): return self.current_position, 'I can not move past the wall'\n else: return Loc(x,y-1), 'I moved'\n \n elif action==const.UP:\n if (x==0): return self.current_position, 'I can not move out of the world'\n elif (self.world[x-1,y]==const.WALL): return self.current_position, 'I can not move past the wall'\n else: return Loc(x-1,y), 'I moved'\n \n elif action==const.RIGHT:\n if (y==self.width-1): return self.current_position, 'I can not move out of the world'\n elif (self.world[x,y+1]==const.WALL): return self.current_position, 'I can not move past the wall'\n else: return Loc(x,y+1), 'I moved'\n \n elif action==const.DOWN:\n if (x==self.height-1): return self.current_position, 'I can not move out of the world'\n elif (self.world[x+1,y]==const.WALL): return self.current_position, 'I can not move past the wall'\n else: return Loc(x+1,y), 'I moved'\n \n def _compute_reward(self):\n if(self.current_position == self.ending_position):\n return 100, None\n elif(self.world[self.current_position.x,self.current_position.y]==const.TRAP):\n return -100, None \n else:\n return -1, None\n \n def _check_termination(self):\n if(self.current_position == self.ending_position):\n self.termination = True\n return 'Objective reached'\n elif(self.world[self.current_position.x,self.current_position.y]==const.TRAP):\n self.termination = True\n return 'You fell into a trap!'\n \n def print_basic(self):\n np.set_printoptions(formatter={'float': \" {: 0.0f} \".format})\n \n printworld = self._get_world_representation()\n print(printworld)\n print('\\n')\n \n np.set_printoptions()\n \n def print_unicode(self):\n printworld = self._get_world_representation()\n \n rows = []\n for i in range(self.height):\n rows.append([const.translate_to_unicode(int(printworld[i,j])) for j in range(self.width)])\n for i in range(self.height):\n print(*rows[i], sep=' ')\n print('\\n')\n \n def _get_world_representation(self):\n repworld = self.world.copy()\n repworld[self.current_position.x, self.current_position.y] = const.PLAYER\n return repworld\n ","sub_path":"week12/gridworld.py","file_name":"gridworld.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"434198033","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nimport statistics \nimport os\nimport time\nimport multiprocessing \nimport random\nfrom sklearn import svm\nimport sys\nimport copy\nimport pickle\nimport bisect \nimport numba \n\n# This file handles the creation of the training and test sets for Experiment 2\n\ndef mean_feature(data):\n return statistics.mean(data)\n\n@numba.jit(nopython=True)\ndef upper_feature(data):\n '''\n Takes in a set of data, assumed to be sorted. \n Returns item at the start of the top 20%\n '''\n upper_index = len(data) // 5\n return data[upper_index]\n \n@numba.jit(nopython=True)\ndef calculateMagnitudes(flow_list, frame_index, debugging = False):\n '''\n Calculate the magnitudes for each optical flow value\n Return magnitudes as a sorted list\n '''\n step = 1\n #debugging\n if debugging:\n step = 2\n magnitudes = numba.typed.List() \n\n for x in range(0, len((flow_list[frame_index][0])), step):\n for y in range(0, len((flow_list[frame_index])), step):\n magnitude = float(np.linalg.norm(flow_list[frame_index][y][x]))\n\n magnitudes.append(magnitude)\n\n sorted_magnitudes = sorted(magnitudes)\n return sorted_magnitudes\n\n@numba.jit(nopython=True)\ndef calculateRelatives(dif_fm_upper, dif_fm_mean, dif_fm_sd, average_flow):\n '''\n Calculate relative features by dividing each item by mean\n '''\n rel_dif_fm_mean = numba.typed.List() \n rel_dif_fm_upper = numba.typed.List() \n rel_dif_fm_sd = numba.typed.List()\n\n for item in dif_fm_upper:\n rel_dif_fm_upper.append(item / average_flow)\n\n for item in dif_fm_mean:\n rel_dif_fm_mean.append(item / average_flow)\n\n for item in dif_fm_sd:\n rel_dif_fm_sd.append(item / average_flow)\n\n return rel_dif_fm_upper, rel_dif_fm_mean, rel_dif_fm_sd\n \n\n\ndef processVideo(file, load_folder, return_dict, relative = False, debugging = False):\n '''\n Convert optical flow of a clip to features\n '''\n flow_list = pickle.load( open( os.path.join(load_folder, file), \"rb\" ))\n\n typed_flow_list = numba.typed.List()\n [typed_flow_list.append(np.array(x)) for x in flow_list] \n flow_list = typed_flow_list\n\n mean_list = []\n median_list =[]\n sd_list = []\n upper_mark = []\n dif_fm_upper = numba.typed.List()\n dif_fm_mean = numba.typed.List()\n dif_fm_sd = numba.typed.List()\n rel_mean_pos = numba.typed.List()\n\n if len(file.split(\".\"))> 1:\n name = file.split(\".\")\n else:\n name = file\n\n for frame_index in range(len(flow_list)):\n #get optical flow from 2 frames and save changes in magnitudes\n \n if len(flow_list[frame_index]) < 1:\n continue\n \n magnitudes = calculateMagnitudes(flow_list, frame_index, debugging)\n\n\n mean = statistics.mean(magnitudes)\n mean_list.append(mean) # mean of whole flow\n median_list.append(statistics.median(magnitudes)) #median of all flow\n sd_list.append(statistics.pstdev(magnitudes)) # sd of all flow\n\n \n if len(mean_list)>1:\n dif_fm_mean.append(abs(mean_list[-1] - mean_list[-2])) # Difference between this fmames mean val and last frame's mean val\n if len(sd_list)>1:\n dif_fm_sd.append(abs(sd_list[-1] - sd_list[-2])) # Difference between this frames sd val and last frame's sd val\n\n upper_mark.append(upper_feature(np.array(magnitudes)))\n if len(upper_mark)>1:\n dif_fm_upper.append(abs(upper_mark[-1] - upper_mark[-2])) # Difference between this frames max val and last frame's max val\n \n if not sd_list[-1] == 0:\n rel_mean_pos.append(mean / (max(magnitudes) - min(magnitudes)))\n\n\n # For each max frame difference calculate the distance relative to mean of whole video\n average_flow = mean_feature(mean_list)\n \n\n #Are We testing relative? If so do the following. If not leave commented.\n if relative:\n dif_fm_upper, dif_fm_mean, dif_fm_sd = calculateRelatives(dif_fm_upper, dif_fm_mean, dif_fm_sd, average_flow)\n \n # Rate of change of mean & sd:\n mean_change_rate = []\n sd_change_rate = []\n for index in range(1, len(dif_fm_mean)):\n mean_change_rate.append(abs(dif_fm_mean[index] - dif_fm_mean[index-1]))\n sd_change_rate.append(abs(dif_fm_sd[index] - dif_fm_sd[index-1]))\n\n\n video_windspeed = name.split(\"-\")[-1]\n video_features = {} \n \n video_features[\"category\"] = video_windspeed\n video_features[\"mean\"] = average_flow\n video_features[\"median\"] = mean_feature(median_list)\n video_features[\"sd\"] = mean_feature(sd_list)\n video_features[\"mean_dif_fm_upper\"] = mean_feature(dif_fm_upper)\n video_features[\"max_dif_fm_upper\"] = upper_feature(np.sort(dif_fm_upper))\n video_features[\"mean_dif_fm_mean\"] = mean_feature(dif_fm_mean)\n video_features[\"max_dif_fm_mean\"] = upper_feature(np.sort(dif_fm_mean))\n video_features[\"mean_dif_fm_sd\"] = mean_feature(dif_fm_sd)\n video_features[\"max_dif_fm_sd\"] = upper_feature(np.sort(dif_fm_sd))\n video_features[\"mean_rate_of_mean_change\"] = mean_feature( mean_change_rate)\n video_features[\"mean_rate_of_sd_change\"] = mean_feature(sd_change_rate)\n video_features[\"mean_relative_position\"] = mean_feature(rel_mean_pos)\n\n return_dict[name] = video_features\n\n\ndef evalSet(video_set, directory, flowtype, start_time):\n '''\n Send every data item off for processing and format returned features\n '''\n # Extract the features of each video in its own thread.\n # A maximum of 12 threads run at a time (for optimal performance on development platform) \n set_results = {}\n count = 0\n total_folders = len(video_set)\n threads = []\n manager = multiprocessing.Manager()\n return_dict = manager.dict()\n for video in video_set:\n save_folder = os.path.join(directory, video)\n load_folder = os.path.join(save_folder, flowtype)\n\n for file in os.listdir(load_folder):\n while len(threads) >= 10:\n for thread in threads:\n if not thread.is_alive():\n threads.remove(thread)\n # Return and save each feature from the video using a thread-safe dictionary \n for key,value in return_dict.items():\n for feat_key, feat_val in value.items():\n if not feat_key in set_results.keys():\n set_results[feat_key] = []\n set_results[feat_key].append(feat_val) \n del return_dict[key]\n\n p = multiprocessing.Process(target=processVideo, args=(file, load_folder, return_dict, debugging))\n threads.append(p)\n p.start()\n\n\n count +=1 \n if count % 10 == 0:\n print(\"Completed {} out of {} folders\".format(count, total_folders))\n \n current_time = time.time()\n time_taken = current_time - start_time\n print(\"Taken {} seconds so far, or approximately {} minutes.\".format(time_taken, time_taken//60))\n \n\n\n # Wait for any remaining threads to finish before continuing\n for thread in threads:\n thread.join()\n for key,value in return_dict.items():\n for feat_key, feat_val in value.items():\n set_results[feat_key].append(feat_val) \n del return_dict[key]\n \n print(len(set_results))\n print(len(set_results[\"category\"]))\n\n return set_results\n \n\nif __name__ == '__main__':\n\n flowtype = \"DenseFlow\"# dense\n relative = False\n debugging = False \n if len(sys.argv)>1:\n if sys.argv[1].lower() == \"dense\":\n flowtype = \"DenseFlow\"\n elif sys.argv[1].lower() == \"points\":\n flowtype = \"PointsFlow\"\n else:\n print(sys.argv[1])\n raise Exception(\"Bad argument; argument 1\")\n\n if len(sys.argv)>2:\n if sys.argv[2].lower() == \"true\":\n print(\"Relative = True\")\n relative = True\n elif sys.argv[2].lower() == \"false\":\n relative = False\n else:\n print(sys.argv[1])\n raise Exception(\"Bad argument; argument 2\")\n\n start = time.time()\n \n load_directory = os.path.join(os.path.split(os.path.abspath(os.curdir))[0], \"OpticalFlow\")\n Save_directory = os.path.join(os.path.split(os.path.abspath(os.curdir))[0], os.path.join(\"DataSets\", flowtype))\n\n # New method: Store per wind category in lists of every feature from each clip.\n\n # Separate into training and test datasets\n training_video_sets = []\n test_video_sets = []\n \n # Get 5 different test and training configurations \n for group in range(3):\n #Order into wind force categories\n videos_by_force = [[] for x in range(13)]\n for wind_force in range(0, 13):\n for video in os.listdir(load_directory):\n ending = \"-\"+str(wind_force)\n if video.endswith(ending):\n videos_by_force[wind_force].append(video)\n \n # take 20% of the video of each wind force and separate them into a test set.\n training_video_sets.append([])\n test_video_sets.append([])\n for wind_force in range(0, 13):\n total = len(videos_by_force[wind_force])\n if group == 0:\n print(total, \"videos of force\", str(wind_force))\n test_set_size = int(total/5) # 20% of each force for testing\n for video in range(test_set_size):\n choice = random.choice(videos_by_force[wind_force])\n test_video_sets[group].append(choice)\n videos_by_force[wind_force].remove(choice)\n\n for remainder in videos_by_force[wind_force]:\n training_video_sets[group].append(remainder)\n \n\n total_test_videos = len(test_video_sets[0])\n\n print(\"Finished establishing data sets\")\n\n for set_index in range(len(training_video_sets)):\n \n training_features = evalSet(training_video_sets[set_index], load_directory, flowtype, start)\n\n test_features = evalSet(test_video_sets[set_index], load_directory, flowtype, start)\n\n\n if not os.path.exists(os.path.join(Save_directory,str(set_index))):\n os.mkdir(os.path.join(Save_directory,str(set_index)))\n print(\"\\n\\nSaving\")\n with open(Save_directory+\"\\\\\"+str(set_index)+\"\\\\TrainingSet\"+str(set_index), 'wb') as out:\n pickle.dump(training_features, out)\n with open(Save_directory+\"\\\\\"+str(set_index)+\"\\\\TestSet\"+str(set_index), 'wb') as out:\n pickle.dump(test_features, out)\n\n \n end=time.time()\n print(\"Moment of truth...\")\n print(\"threading global averages time:\")\n print(str(end - start))\n\n","sub_path":"3rd year/evaluateDataSetsV2.py","file_name":"evaluateDataSetsV2.py","file_ext":"py","file_size_in_byte":10898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"472609251","text":"# Import necessary modules \r\nfrom sklearn.neighbors import KNeighborsClassifier \r\n#from sklearn.model_selection import train_test_split \r\n#from scapy.all import rdpcap\r\n\r\nimport joblib as joblib\r\nimport Read_pcap_scapy\r\n\r\n# Loading data test data\r\nfile_name = \"Thesis-git\\Vagrant_Network\\server\\server_traffic_5m.pcap\"\r\n#file_name = \"Thesis-git\\DTU_server\\dtu_server_nordvpn_25m.pcap\"\r\ndata = Read_pcap_scapy.FindFeaturesInLargeFiles(file_name)\r\n#print(data)\r\n## Create feature and target arrays \r\nX = data[:,1:]\r\ny = data[:,0] \r\n\r\nknn = KNeighborsClassifier(n_neighbors=7)\r\nknn.fit(X, y)\r\n\r\n## Save the model as a pickle in a file \r\njoblib.dump(knn, 'knnModel_7neighbor_5m.pkl') ","sub_path":"KNN_training.py","file_name":"KNN_training.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"654055110","text":"import socket\n# import diemdanhsv\n# import dangnhap\n# import csdl\n# import admin_lop\nimport dangnhap\nimport adminlop\nimport diemdanh\nimport backend.xacthuc as xacthuc\n\ndef main():\n ten_thiet_bi = socket.gethostname()\n\n file=open(ten_thiet_bi+\".txt\",\"a\")\n file.close()\n\n data=[]\n with open(ten_thiet_bi+\".txt\",\"r\") as file:\n data= file.read().split(\"\\n\")\n if data[0] != \"\":\n if xacthuc.kt_loaitk(data[0]) == \"1\":\n adminlop.main()\n else:\n diemdanh.main()\n else:\n dangnhap.main()\n\n\nif __name__ == '__main__':\n main()","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"65081029","text":"import sys\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom reproject import reproject_interp, reproject_from_healpix\nfrom iminuit import Minuit\nimport time\n\n\nclass linmap_chi2:\n def __init__(self, map1, maps, maskmap, errormap):\n self.map1 = map1\n self.maps = maps\n self.maskmap = maskmap\n self.errormap = errormap\n\n def model(self, pars):\n return np.sum(pars[:-1] * np.moveaxis(self.maps, 0, -1), axis=2) + pars[-1]\n\n def residuals(self, pars):\n return self.map1 - self.model(pars)\n\n def __call__(self, *pars):\n pars = np.array(pars)\n model = self.model(pars)\n residuals = self.map1 - model\n residuals /= self.errormap\n residuals *= self.maskmap\n chi2 = np.sum(np.power(residuals, 2))\n return chi2\n\n\nclass dustmap_residuals:\n def __init__(self, dustmap, colname, inmaps, scale=1., errorname='None'):\n \"\"\"\n Constructor for class to create extinction residuals from extinction cube and set of\n gas maps for given distance range.\n :param dustmap: `string`\n FITS file with dust map\n :param colname: `string`\n name of column containing dust map\n :param inmaps: `list`\n FITS file with WCS map in first HDU (gas maps)\n :param scale: `float`\n scaling to apply to the extinction map (so that fitting coeff are O(1))\n :param scale: `string`\n name of column containing error map, 'None' for no error\n \"\"\"\n\n # read in dust map\n self.dustmap = fits.open(dustmap)[1]\n self.colname = colname\n self.scale = scale\n self.errorname = errorname\n\n # read gas maps\n self.gasmaps = []\n self.nreg = len(inmaps)\n self.region = []\n for s, region in enumerate(inmaps):\n for filename in region:\n self.region.append(s)\n self.gasmaps.append(fits.open(filename)[0])\n\n def reproject_dustmap(self, outheader):\n \"\"\"\n Reprojects dust map (and errors) on the desired WCS\n :param outheader: `~astropy.io.fits.header.Header`\n output map header\n :return: outmap: `~numpy.ndarray`\n output map\n :return: errormap: `~numpy.ndarray`\n erromap\n \"\"\"\n\n # load properties of healpix grid\n coordsys = self.dustmap.header['COORDSYS']\n if coordsys == 'C':\n coordsys = 'ICRS'\n elif coordsys == 'E':\n coordsys = 'Ecliptic'\n elif coordsys == 'G':\n coordsys = 'Galactic'\n else:\n print('coordinate system of input dust map unknown:', coordsys)\n\n nested = self.dustmap.header['ORDERING']\n if nested == 'NESTED':\n nested = True\n elif nested == 'RING':\n nested = False\n else:\n print('ordering of input dust map unknown:', nested)\n\n # dust map\n outmap, footprint = reproject_from_healpix((self.dustmap.data[self.colname], coordsys),\n outheader, nested=nested)\n\n # error map\n if self.errorname == 'None':\n errormap = np.ones(np.shape(outmap))\n else:\n errormap, footprint = reproject_from_healpix(\n (self.dustmap.data[self.errorname], coordsys),\n outheader, nested=nested)\n\n outmap *= self.scale\n errormap *= self.scale\n\n return outmap, errormap\n\n def reproject_gasmaps(self, outheader):\n \"\"\"\n Reproject gas maps onto desired output WCS\n :param outheader: `~astropy.io.fits.header.Header`\n output map header\n :return: gasmaps: `~numpy.ndarray`\n input gas maps reprojected onto the output WCS as 3D array (#, lon, lat)\n \"\"\"\n gasmaps = np.zeros([len(self.gasmaps), outheader['NAXIS2'], outheader['NAXIS1']])\n for s, inmap in enumerate(self.gasmaps):\n repromap, footrpint = reproject_interp(inmap, outheader)\n gasmaps[s] = repromap\n\n return gasmaps\n\n def fit(self, extmap, gasmaps, maskmap, errormap, outfilename='fit', outdir='./',\n split=True):\n\n chi2 = linmap_chi2(extmap, gasmaps, maskmap, errormap)\n\n # define params tuple, initial values, limits, etc\n ptup = ()\n kwdarg = {}\n # map coefficients\n for n in range(len(gasmaps)):\n ptup = ptup + ('A_' + str(n),)\n kwdarg['A_' + str(n)] = 1.\n kwdarg['error_A_' + str(n)] = 0.01\n kwdarg['limit_A_' + str(n)] = (0., 1.e4)\n # constant\n ptup = ptup + ('C',)\n kwdarg['C'] = 0.\n kwdarg['error_C'] = 0.01\n kwdarg['limit_C'] = (-1.e4, 1.e4)\n\n # fitting\n m = Minuit(chi2, forced_parameters=ptup, errordef=1, **kwdarg)\n fitres = m.migrad()[0]\n\n # save results\n saveout = sys.stdout\n file = open(outdir + outfilename + '.log', 'w')\n sys.stdout = file\n print('parameters')\n for n in range(len(gasmaps)):\n print(m.values['A_' + str(n)], m.errors['A_' + str(n)])\n print(m.values['C'], m.errors['C'])\n print('FCN', m.fval, 'dof', extmap.size - len(m.args))\n print('Minuit output')\n print(fitres)\n sys.stdout = saveout\n file.close()\n\n # calculate residuals\n residuals = chi2.residuals(np.array(m.args))\n\n # calculate weights of each region\n parvals = np.array(m.args)\n parvals[-1] = 0 # remove constant\n total_model = chi2.model(parvals)\n weights = []\n for s in range(self.nreg):\n parvals = np.array(m.args)\n for k in range(len(self.region)):\n if self.region[k] == s:\n pass\n else:\n parvals[k] = 0.\n model_reg = chi2.model(parvals)\n weight = model_reg / total_model\n weight[total_model < 0.1] = 0.\n weights.append(weight)\n\n return fitres, residuals, weights\n\n def make(self, lmin, lmax, bmin, bmax, pixsize, outfilename, names, outdir='./',\n mask='None', name='L. Tibaldo', email='luigi.tibaldo@irap.omp.eu'):\n \"\"\"\n Make residual maps over a sky region\n :param lmin: `float`\n minimum longitude (deg)\n :param lmax: `float`\n maximum longitude (deg)\n :param bmin: `float`\n minimum latitude (deg)\n :param bmax: `float`\n maximum latitude (deg)\n :param pixsize: `float`\n pixel size (deg)\n :param outfilename: `str`\n root for the output file names\n :param outdir: `str`\n output directory\n :param mask: `str`\n conditions to use a pixel at latitude lat and longitude lon in fit (passed to Python eval),\n default 'None' to accept all pixels\n :param name:\n :param email:\n :return:\n \"\"\"\n\n # create output WCS\n outwcs = WCS(naxis=2) # wcs class\n npix = (np.array([lmax - lmin, bmax - bmin]) / pixsize).astype(int)\n outwcs.wcs.crpix = [int(1 + npix[0] / 2) + 0.5, int(1. - bmin / pixsize) + 0.5]\n outwcs.wcs.cdelt = [-pixsize, pixsize]\n outwcs.wcs.crval = [(lmax + lmin) / 2, 0.]\n outwcs.wcs.ctype = ['GLON-CAR', 'GLAT-CAR']\n outwcs.wcs.cunit = ['deg', 'deg']\n # create output header\n outheader = outwcs.to_header()\n outheader['NAXIS'] = 2\n outheader['NAXIS1'] = int((lmax - lmin) / pixsize) + 1\n outheader['NAXIS2'] = int((bmax - bmin) / pixsize) + 1\n\n # reproject input map onto required grid\n dustmap, errormap = self.reproject_dustmap(outheader)\n\n # reproject gas maps onto output map footprint\n gasmaps = self.reproject_gasmaps(outheader)\n\n # create mask map\n maskmap = np.ones(np.shape(dustmap))\n if mask == 'None':\n pass\n else:\n for ll in range(outheader['NAXIS1']):\n for bb in range(outheader['NAXIS2']):\n lon = outwcs.wcs.crval[0] + outwcs.wcs.cdelt[0] * (\n ll - outwcs.wcs.crpix[0])\n lat = outwcs.wcs.crval[1] + outwcs.wcs.cdelt[1] * (\n bb - outwcs.wcs.crpix[1])\n if eval(mask):\n pass\n else:\n maskmap[bb, ll] = 0\n\n # set NaNs to zero\n dustmap = np.nan_to_num(dustmap)\n gasmaps = np.nan_to_num(gasmaps)\n errormap = np.nan_to_num(errormap)\n # set to 1 error if == 0\n errormap[errormap == 0.] = 1.\n\n print('Finished reprojecting maps, starting fit')\n\n # model fitting\n fitres, residuals, weights = self.fit(dustmap, gasmaps, maskmap, errormap, outfilename,\n outdir, split=True)\n\n # save total residual map\n hdu = fits.PrimaryHDU(header=outheader, data=residuals)\n # add history cards\n hdu.header.add_history('map generated by {}, {}'.format(name, email))\n hdu.header.add_history('on ' + time.ctime() + ' ' + time.tzname[1])\n hdu.writeto(outdir + outfilename + '.fits')\n\n # save splitted residuals\n for s in range(self.nreg):\n split_residuals = residuals * weights[s]\n split_residuals[split_residuals < 0] = 0.\n hdu = fits.PrimaryHDU(header=outheader, data=split_residuals)\n # add history cards\n hdu.header.add_history('map generated by {}, {}'.format(name, email))\n hdu.header.add_history('on ' + time.ctime() + ' ' + time.tzname[1])\n hdu.writeto(outdir + outfilename + '_{}.fits'.format(names[s]))\n","sub_path":"ISM/dustmap_residuals.py","file_name":"dustmap_residuals.py","file_ext":"py","file_size_in_byte":9785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"344647732","text":"#\r\n# Author: Alvin Thai\r\n# Description: \r\n# Huffman created prefix coding, or binary encoding that tells a program where to traverse in a binary tree. All prefix codes are unique. The program creates a binary tree given preorder and inorder traversals, prints the postorder traversal, and decodes a binary sequence to provide values from leaf nodes.\r\n#\r\nclass BinaryTree:\r\n def __init__(self):\r\n self._value = None\r\n self._left = None\r\n self._right = None\r\n \r\n # assigns first element of the preorder list to BinaryTree object, creates preorder and inorder lists for the left and right nodes, and continues assigning values to BinaryTree nodes until the preorder list is empty \r\n def make_tree(self, preorder, inorder):\r\n if len(preorder) == 0:\r\n return None\r\n else:\r\n self._value = preorder[0]\r\n inorder_left = inorder[:inorder.index(preorder[0])] # takes elements to the left of the root node value in inorder list\r\n preorder_left = preorder[1:len(inorder_left)+1] # elements from right of the root node value up to length of inorder_left\r\n inorder_right = inorder[inorder.index(preorder[0])+1:len(inorder)] # remaining elements of inorder list\r\n preorder_right = preorder[len(preorder_left)+1:len(preorder)] # remaining elements of preorder list\r\n l = BinaryTree()\r\n self._left = l.make_tree(preorder_left, inorder_left)\r\n self._left = l\r\n r = BinaryTree()\r\n self._right = r.make_tree(preorder_right, inorder_right)\r\n self._right = r\r\n return self\r\n \r\n def __str__(self):\r\n if self._value == None:\r\n return str(\"None\")\r\n else:\r\n return \"({} {} {})\".format(str(self._value), str(self._left), str(self._right))\r\n\r\n# reads file to get preorder, inorder, and encoded binary sequences\r\ndef get_orders():\r\n file_lines = []\r\n preorder = []\r\n inorder = []\r\n file = input('Input file: ')\r\n try:\r\n data = open(file)\r\n except:\r\n print(\"ERROR: Could not open file \" + file)\r\n else:\r\n data = data.readlines()\r\n for line in data:\r\n line = line.rstrip('\\n').split()\r\n file_lines.append(line)\r\n preorder = file_lines[0]\r\n inorder = file_lines[1]\r\n \r\n encoded = str(file_lines[2][0])\r\n return preorder, inorder, encoded\r\n\r\n# recurses through the left and right nodes of the tree, then the root to get postorder sequence\r\ndef postorder(tree):\r\n if tree._value == None:\r\n return \"\"\r\n if tree._left == None and tree._right == None:\r\n return str(tree._value)\r\n elif tree._left != None and tree._right != None:\r\n order = str(postorder(tree._left) + \" \" + postorder(tree._right) + \" \" + tree._value).split()\r\n order = \" \".join(order) # removes extra spaces from None values\r\n return order\r\n\r\n# returns decoded string from encoded sequence and binary tree\r\ndef decoder(tree, encoded):\r\n ptrhead = tree\r\n decoded = \"\"\r\n for i in range(0, len(encoded)):\r\n if encoded[i] == \"0\" and ptrhead._left._value != None:\r\n ptrhead = ptrhead._left\r\n if ptrhead._left._value == None and ptrhead._right._value == None: # values of left and right nodes are checked to see if a leaf node is landed on\r\n decoded += str(ptrhead._value)\r\n ptrhead = tree\r\n continue\r\n elif encoded[i] == \"1\" and ptrhead._right._value != None:\r\n ptrhead = ptrhead._right\r\n if ptrhead._left._value == None and ptrhead._right._value == None:\r\n decoded += str(ptrhead._value)\r\n ptrhead = tree\r\n continue\r\n else:\r\n ptrhead = tree # ptrhead returns to the root of the tree when a 0 or 1 does not traverse tree\r\n return decoded\r\n \r\ndef main():\r\n a, b, c = get_orders()\r\n t = BinaryTree()\r\n t.make_tree(a, b)\r\n print(postorder(t))\r\n print(decoder(t, c))\r\nmain()\r\n \r\n","sub_path":"huffman.py","file_name":"huffman.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"510638623","text":"import os, sys\n\n'''Set up paths for RCNN.'''\ndef add_path(path):\n if path not in sys.path:\n sys.path.insert(0, path)\n\nthis_dir = os.getcwd()\nlibs_path = os.path.join(this_dir, '..', 'libs', 'layers') # Add lib to PYTHONPATH\nadd_path(libs_path)\nlibs_path = os.path.join(this_dir, '..', 'libs', 'utils') # Add lib to PYTHONPATH\nadd_path(libs_path)","sub_path":"models/_init_path.py","file_name":"_init_path.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"533057360","text":"materias = {\n\t\"Matematicas\":0,\n\t\"Fisica\":0,\n\t\"Biologia\":0,\n\t\"Quimica\": 0,\n\t\"Derecho\":0\n\t}\nsuma = 0\nestado = \"\"\nfor materia in materias:\n\tnota_materia = float(input(f\"Ingrese la calificación de {materia}: \"))\n\tmaterias[materia] = nota_materia\n\tsuma = suma + nota_materia\npromedio = suma / len(materias)\nif promedio >=1 and promedio <= 2:\n\testado = \"Examen en frebrero\"\nelif promedio >= 3 and promedio <= 6:\n\testado = \"Examen en diciembre\"\nelif promedio >= 7 and promedio <= 11:\n\testado = \"Aprueba\"\nelif promedio == 12:\n\testado = \"Aprueba con honores\"\n\nprint(\"\\n\\n\\t\\tCalificaciones\")\nfor materia in materias:\n\tprint(f\"{materia}:{materias[materia]}\")\n\nprint(f\"El promedio es: {promedio}\")\nprint(f\"Estado: {estado}\")\n\n","sub_path":"Escuela/Ejercicios/Variables, Array y Estructuras de control/Ejercicio_3.py","file_name":"Ejercicio_3.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"370373743","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass RiskpluscoreRiskQueryResult(object):\n\n def __init__(self):\n self._info_code = None\n self._risk_desc = None\n self._risk_type = None\n self._risk_value = None\n\n @property\n def info_code(self):\n return self._info_code\n\n @info_code.setter\n def info_code(self, value):\n self._info_code = value\n @property\n def risk_desc(self):\n return self._risk_desc\n\n @risk_desc.setter\n def risk_desc(self, value):\n self._risk_desc = value\n @property\n def risk_type(self):\n return self._risk_type\n\n @risk_type.setter\n def risk_type(self, value):\n self._risk_type = value\n @property\n def risk_value(self):\n return self._risk_value\n\n @risk_value.setter\n def risk_value(self, value):\n self._risk_value = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.info_code:\n if hasattr(self.info_code, 'to_alipay_dict'):\n params['info_code'] = self.info_code.to_alipay_dict()\n else:\n params['info_code'] = self.info_code\n if self.risk_desc:\n if hasattr(self.risk_desc, 'to_alipay_dict'):\n params['risk_desc'] = self.risk_desc.to_alipay_dict()\n else:\n params['risk_desc'] = self.risk_desc\n if self.risk_type:\n if hasattr(self.risk_type, 'to_alipay_dict'):\n params['risk_type'] = self.risk_type.to_alipay_dict()\n else:\n params['risk_type'] = self.risk_type\n if self.risk_value:\n if hasattr(self.risk_value, 'to_alipay_dict'):\n params['risk_value'] = self.risk_value.to_alipay_dict()\n else:\n params['risk_value'] = self.risk_value\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = RiskpluscoreRiskQueryResult()\n if 'info_code' in d:\n o.info_code = d['info_code']\n if 'risk_desc' in d:\n o.risk_desc = d['risk_desc']\n if 'risk_type' in d:\n o.risk_type = d['risk_type']\n if 'risk_value' in d:\n o.risk_value = d['risk_value']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/RiskpluscoreRiskQueryResult.py","file_name":"RiskpluscoreRiskQueryResult.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"401175289","text":"from django.core.exceptions import ValidationError\nfrom django.test import TestCase\n\nfrom accounting.models import Associate, PurchaseItem, SaleItem\nfrom inventory.models import Item\nfrom inventory.tests.item_factory import ItemFactory\nfrom .accounting_factory import AssociateFactory, PurchaseFactory, \\\n PurchaseItemFactory, SaleFactory, \\\n SaleItemFactory, PaymentFactory, ItemReturnFactory\n\n\nclass AssociateMethodTests(TestCase):\n def test_associate_model_accepts_numbers_for_tin_and_contact_number(self):\n associate = Associate.objects.create(TIN='123456789',\n company_name='green apple',\n contact_person='jobs',\n contact_number='123456', type='C')\n self.assertIsInstance(associate, Associate)\n\n def test_associate_model_does_not_accept_invalid_data(self):\n with self.assertRaises(ValidationError):\n Associate.objects.create(company_name='greenapple',\n contact_person='jobs',\n contact_number='123456', type='C')\n with self.assertRaises(ValidationError):\n Associate.objects.create(TIN='123456789as0',\n company_name='apple',\n contact_person='jobs',\n contact_number='123a456', type='C')\n\n def test_associate_should_return_proper_str(self):\n associate = AssociateFactory()\n self.assertEqual(str(associate), str(associate.company_name))\n\n\nclass PurchaseMethodTests(TestCase):\n def test_purchase_model_str_method(self):\n purchase = PurchaseFactory()\n self.assertEqual(str(purchase),\n purchase.shipment_delivery_receipt_number)\n\n def test_purchase_model_save_method_should_fail_supplier_field_is_not_a_supplier(\n self):\n client = AssociateFactory(type='C')\n with self.assertRaises(ValidationError):\n purchase = PurchaseFactory(supplier=client)\n\n\nclass PurchaseItemMethodTests(TestCase):\n def setUp(self):\n self.item = ItemFactory()\n self.purchase = PurchaseFactory()\n self.purchaseitem = PurchaseItem(purchase=self.purchase, item=self.item,\n quantity=1,\n purchase_unit_cost=3)\n self.purchaseitem.save()\n\n def test_buy_item_should_be_triggered_on_purchase_item_post_save(self):\n item = Item.objects.get(id=self.item.id)\n self.assertEqual(item.id, self.purchaseitem.item.id) # sanity check\n self.assertNotEqual(item.quantity, self.purchaseitem.item.quantity)\n self.assertNotEqual(item.unit_price, self.purchaseitem.item.unit_price)\n\n def test_delete_item_should_be_triggered_on_purchase_item_post_delete(self):\n item = Item.objects.get(id=self.item.id)\n self.purchaseitem.delete()\n self.assertEqual(item.id, self.purchaseitem.item.id) # sanity check\n self.assertNotEqual(item.quantity, self.purchaseitem.item.quantity)\n self.assertNotEqual(item.unit_price, self.purchaseitem.item.unit_price)\n\n def test_purchaseitem_model_str_method(self):\n purchaseitem = PurchaseItemFactory()\n self.assertEqual(str(purchaseitem),\n \"{0}-{1}\".format(purchaseitem.purchase,\n purchaseitem.item))\n\n\nclass SaleMethodTests(TestCase):\n def test_sale_model_str_method(self):\n sale = SaleFactory()\n self.assertEqual(str(sale), sale.delivery_receipt_number)\n\n def test_sale_model_save_method_should_fail_client_field_is_not_a_client(\n self):\n supplier = AssociateFactory(type='S')\n with self.assertRaises(ValidationError):\n SaleFactory(client=supplier)\n\n def test_sale_model_total_revenue_should_return_correct_value(self):\n sale = SaleFactory()\n sale_item = SaleItemFactory(sale=sale)\n sale_items = SaleItem.objects.filter(sale=sale)\n result = 0\n for i in sale_items:\n result += i.total_revenue()\n self.assertEqual(sale.total_revenue(), result)\n\n def test_sale_model_total_profit_should_return_correct_value(self):\n sale = SaleFactory()\n sale_item = SaleItemFactory(sale=sale)\n sale_items = SaleItem.objects.filter(sale=sale)\n result = 0\n for i in sale_items:\n result += i.total_profit()\n self.assertEqual(sale.total_profit(), result)\n\n\nclass SaleItemMethodTests(TestCase):\n def setUp(self):\n self.item = ItemFactory()\n self.sale = SaleFactory()\n self.saleitem = SaleItem(sale=self.sale, item=self.item, quantity=1,\n sale_unit_cost=1, discount=0)\n self.saleitem.save()\n\n def test_saleitem_model_str_method(self):\n saleitem = SaleItemFactory()\n self.assertEqual(str(saleitem),\n \"{0}-{1}\".format(saleitem.sale, saleitem.item))\n\n def test_orig_unit_price_should_be_saved_on_sale_item_save(self):\n item = Item.objects.get(id=self.item.id)\n self.assertEqual(item.id, self.saleitem.item.id) # sanity check\n self.assertNotEqual(item.quantity, self.saleitem.item.quantity)\n self.assertEqual(item.unit_price, self.saleitem.sale_orig_cost)\n\n def test_add_item_should_be_triggered_on_sale_item_post_delete(self):\n item = Item.objects.get(id=self.item.id)\n self.saleitem.delete()\n self.assertEqual(item.id, self.saleitem.item.id) # sanity check\n self.assertNotEqual(item.quantity, self.saleitem.item.quantity)\n\n def test_sale_item_model_total_revenue_should_return_correct_value(self):\n sale_item = SaleItemFactory()\n self.assertEqual(sale_item.total_revenue(),\n sale_item.sale_unit_cost * sale_item.quantity)\n\n def test_sale_item_model_total_profit_should_return_correct_value(self):\n sale_item = SaleItemFactory()\n self.assertEqual(sale_item.total_profit(),\n (sale_item.sale_unit_cost - sale_item.sale_orig_cost) *\n sale_item.quantity)\n\n\nclass PaymentMethodTests(TestCase):\n def test_str_should_return_proper_value(self):\n sale = SaleFactory()\n saleitem = SaleItemFactory(sale=sale)\n payment = PaymentFactory(sale=sale)\n self.assertEqual(str(payment), str(payment.client) + \"-\" + str(\n payment.sale) + \"-\" + str(payment.date))\n\n def test_save_should_raise_validation_error_if_amount_exceeds_sale_amount(\n self):\n with self.assertRaises(ValidationError):\n PaymentFactory(amount=1000000)\n\n def test_save_should_work(self):\n sale = SaleFactory()\n saleitem = SaleItemFactory(sale=sale)\n payment = PaymentFactory(sale=sale, amount=0.001)\n self.assertIsNotNone(payment)\n\n\nclass ItemReturnMethodTests(TestCase):\n def test_str_should_return_proper_value(self):\n itemreturn = ItemReturnFactory()\n self.assertEqual(str(itemreturn),\n str(itemreturn.date) + \"-\" + str(itemreturn.saleitem))\n\n def test_save_should_raise_validation_error_if_return_quantity_is_more_than_sold_quantity(\n self):\n with self.assertRaises(ValidationError):\n ItemReturnFactory(returned_quantity=10)\n\n def test_if_replaced_quantity_is_more_than_zero_it_should_reduce_quantity_in_item(\n self):\n item = ItemFactory(quantity=10)\n saleitem = SaleItemFactory(item=item, quantity=5)\n itemreturn = ItemReturnFactory(saleitem=saleitem, replaced_quantity=3)\n result_item = Item.objects.get(pk=item.id)\n self.assertEqual(result_item.quantity, 2)\n\n def test_if_restock_is_True_then_add_item_quantity(self):\n item = ItemFactory(quantity=10)\n saleitem = SaleItemFactory(item=item, quantity=5)\n itemreturn = ItemReturnFactory(saleitem=saleitem, restock=True,\n returned_quantity=5)\n result_item = Item.objects.get(pk=item.id)\n self.assertEqual(result_item.quantity, item.quantity)\n","sub_path":"server/accounting/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":8269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"258852741","text":"class ketoDistribution():\r\n def __init__(self,min_cal,max_cal,min_weight,max_weight):\r\n self.min_cal=min_cal\r\n self.max_cal=max_cal\r\n self.min_weight=min_weight\r\n self.max_weight=max_weight\r\n \r\n def carb(self):\r\n self.min_carbs=10*self.min_cal/100\r\n self.max_carbs=10*self.max_cal/100\r\n \r\n def prot(self):\r\n self.min_protein=2.2*self.min_weight*4\r\n self.max_protein=2.2*self.max_weight*4\r\n\r\n def fat(self):\r\n self.min_fat=self.min_cal-(self.min_carbs + self.min_protein)\r\n self.max_fat=self.max_cal-(self.max_carbs + self.max_protein)\r\n\r\n def information(self):\r\n\r\n choice=input('How you want your ditribution?(c/cals or g/grams): ')\r\n\r\n if choice=='c':\r\n self.info={\r\n 'Carbs':str(int(self.min_carbs))+'-'+str(int(self.max_carbs))+' Cal',\r\n 'Protein':str(int(self.min_protein))+'-'+str(int(self.max_protein))+' Cal',\r\n 'Fat':str(int(self.min_fat))+'-'+str(int(self.max_fat))+ ' Cal'\r\n } \r\n print(self.info)\r\n if choice=='g':\r\n self.info={\r\n 'Carbs':str(int(int(self.min_carbs)/4))+'-'+str(int(int(self.max_carbs)/4))+' g',\r\n 'Protein':str(int(int(self.min_protein)/4)) +'-'+str(int(int(self.max_protein)/4))+' g',\r\n 'Fat':str(int(int(self.min_fat)/9))+'-'+str(int(int(self.max_fat)/9))+' g'\r\n } \r\n print(self.info)","sub_path":"DietDistributor/ketodiet.py","file_name":"ketodiet.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"175612411","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom . import routes as handlers\nfrom .database import Base, engine\n\norigins = [\"http://localhost\", \"http://localhost:3000\", \"https://parky.ml\"]\n\n\ndef create_app():\n app = FastAPI()\n\n app.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n # Initialize DB connection\n Base.metadata.create_all(bind=engine)\n\n # Register handlers\n app.get(\"/\")(handlers.handle_status)\n\n app.post(\"/user\")(handlers.handle_signup)\n app.post(\"/user/signin\")(handlers.handle_signin)\n\n app.get(\"/vehicle\")(handlers.handle_get_vehicles)\n app.get(\"/vehicle/{number}\")(handlers.handle_find_vehicle)\n app.post(\"/vehicle\")(handlers.handle_register_vehicle)\n\n app.post(\"/v2d/auth/{uid}/{vid}\")(handlers.handle_start_session)\n app.post(\"/v2d/auth/vehicle\")(handlers.handle_auth_vehicle)\n app.post(\"/v2d/auth/client\")(handlers.handle_auth_client)\n\n app.get(\"/parking\")(handlers.handle_get_all_parking_lot)\n app.get(\"/parking/{parking_id}/{user_id}\")(handlers.handle_reserve)\n app.get(\"/parking/{parking_id}/{vehicle_number}\")(handlers.handle_income_car)\n app.get(\"/parking/{vehicle_number}\")(handlers.handle_go_out_car)\n\n return app\n","sub_path":"backend/parky/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"263827016","text":"#!/usr/bin/env python\nimport RPi.GPIO as GPIO\nimport time\n\n\ndef abrir ():\n channel = 21\n canal = 20\n\n # GPIO setup\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(channel, GPIO.OUT)\n GPIO.setup(canal, GPIO.OUT)\n\n def motor_on(pin, pin2):\n GPIO.output(pin, GPIO.HIGH) # Turn motor on\n GPIO.output(pin2, GPIO.LOW)\n\n\n def motor_off(pin, pin2):\n GPIO.output(pin, GPIO.LOW) # Turn motor off\n GPIO.output(pin2, GPIO.HIGH) # Turn motor off\n\n try:\n motor_off(channel, canal)\n time.sleep(2)\n motor_on(channel, canal)\n except KeyboardInterrupt:\n GPIO.cleanup()\nabrir()\n","sub_path":"src/dome/por.py","file_name":"por.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"445495933","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom .models import Recipe, Step, Ingredient, Category\n\n\n#def index(request):\n# recipes = Recipe.objects.all()\n# return render(request, \"main/index.html\", {'recipes': recipes})\n\ndef recipe_list(request):\n object_list = Recipe.objects.all()\n\n paginator = Paginator(list(object_list), 2) # 5 рецептов на каждой странице\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n try:\n Recipes = paginator.page(page_number)\n except PageNotAnInteger:\n Recipes = paginator.page(1)\n except EmptyPage:\n Recipes = paginator.page(paginator.num_pages)\n print(page_number)\n return render(request, 'main/index.html', {'page_obj': page_obj, 'recipes': Recipes})\n\ndef recipe_category(request, slug):\n category = {'meat':'Мясо',\n 'bird':'Птица',\n 'fish':'Рыба',\n 'bakery':'Выпечка',\n 'salat':'Салаты',\n 'cereals':'Крупы',\n 'vegetables':'Овощи',\n 'cold':'Холодное',\n 'sweet':'Сладкое'}\n this_category = category[slug]\n object_list = Recipe.objects.all().filter(category = Category.objects.get(name=this_category) )\n\n paginator = Paginator(list(object_list), 2) # 5 рецептов на каждой странице\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n try:\n Recipes = paginator.page(page_number)\n except PageNotAnInteger:\n Recipes = paginator.page(1)\n except EmptyPage:\n Recipes = paginator.page(paginator.num_pages)\n print(page_number)\n return render(request, 'main/index.html', {'page_obj': page_obj, 'recipes': Recipes})\n\ndef recipe_detail(request, id):\n object = Recipe.objects.get(id=id)\n\n ingredients = Ingredient.objects.all().filter(recipe_id=id)\n\n steps = Step.objects.all().filter(recipe_id=id)\n\n # print(ing_list[0]['ing'])\n context = {'recipe': object,\n 'ingredients': ingredients,\n 'steps': steps}\n\n return render(request, 'main/recipe.html', context=context)","sub_path":"FoodForStudent/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"82820419","text":"import tensorflow as tf\nimport numpy as np\nimport pickle\nimport os\n\n\ntf.reset_default_graph()\n\nlogs_path = \"./logs2\"\npath = './data'\n\nbatch_size = 100\nepochs = 50\nlearning_rate = 0.001\nX = tf.placeholder(tf.float32, [None, 32, 32, 3])\nY_ = tf.placeholder(tf.float32, [None, 10])\nlr = tf.Variable(0.1)\ndrop_1 = tf.placeholder(tf.float32)\ndrop_2 = tf.placeholder(tf.float32)\nbest_acc = 0\n\ndef next_batch(i):\n fo = open(os.path.join(path,\"data_batch_{}\".format(i)), 'rb')\n dict_ = pickle.load(fo, encoding='latin1')\n label = dict_['labels']\n data = dict_['data']\n img = np.reshape(data,(10000,3,32,32))\n img = np.transpose(img,(0,2,3,1))\n\n label = np.reshape(label,(10000))\n label = label.T\n y_one_hot = np.zeros((label.size,10))\n y_one_hot[np.arange(label.size),label] = 1\n return img,y_one_hot\n\ndef test_batch():\n fo = open(os.path.join(path,\"test_batch\"), 'rb')\n dict_ = pickle.load(fo, encoding='latin1')\n label = dict_['labels']\n data = dict_['data']\n img = np.reshape(data,(10000,3,32,32))\n img = np.transpose(img,(0,2,3,1))\n\n label = np.reshape(label,(10000))\n label = label.T\n y_one_hot = np.zeros((label.size,10))\n y_one_hot[np.arange(label.size),label] = 1\n return img,y_one_hot\n\ndef G2_Net():\n\n conv1 = tf.layers.conv2d(inputs = X, filters = 32, kernel_size = 7, strides = 1, padding = \"same\", activation = tf.nn.relu, name = \"conv1\")\n b_norm1 = tf.layers.batch_normalization(inputs = conv1, axis = -1, momentum = 0.99, epsilon = 0.001, center = True, scale = True, name = \"batch_norm1\")\n pool1 = tf.layers.max_pooling2d(inputs = b_norm1, pool_size = 2, strides=2, name = \"max_pool1\")\n\n pool1_flat = tf.reshape(pool1, [-1, 16 * 16* 32])\n dense1 = tf.layers.dense(inputs = pool1_flat, units = 1024, activation = tf.nn.relu, name = \"dense1\")\n logits = tf.layers.dense(inputs = dense1, units = 10)\n out = tf.nn.softmax(logits, name=\"softmax_output\")\n\n return out\n\ndef nn():\n prediction = G2_Net()\n cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits = prediction,labels = Y_))\n optimizer = tf.train.AdamOptimizer(lr).minimize(cost)\n correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n\n tf.summary.scalar(\"cost\", cost)\n tf.summary.scalar(\"accuracy\", accuracy)\n\n summary_op = tf.summary.merge_all()\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())\n\n with tf.Session() as sess:\n saver.restore(sess,\"./freeze1/model.ckpt\")\n #sess.run(init)\n pt = 0\n for epoch in range(epochs):\n epoch_loss = 0\n for j in range(4):\n train_x, train_y = next_batch(j+1)\n train_size = len(train_x)\n i =0\n while i < (train_size-batch_size):\n start = i\n end = i+batch_size\n batch_x = np.array(train_x[start:end])\n batch_x = batch_x/255\n batch_y = np.array(train_y[start:end])\n c = 0\n _, c, pred, summary, acc = sess.run([optimizer, cost, prediction, summary_op, accuracy], feed_dict={X: batch_x, Y_: batch_y, lr: learning_rate, drop_1: 0.25, drop_2: 0.5})\n writer.add_summary(summary, pt)\n pt += 1\n epoch_loss += c\n i+=batch_size\n save_path = saver.save(sess, \"./freeze1/model.ckpt\")\n batch_x, batch_y = next_batch(5)\n batch_x = batch_x/255\n sum_ = 0\n for i__ in range(0,10000,100):\n val_acc = accuracy.eval({X: batch_x[i__:i__+100], Y_:batch_y[i__:i__+100]})\n sum_ += val_acc\n sum_ = sum_/100\n print(' Epoch: ',epoch+1,' completed out of: ',epochs,' train_acc: ', acc, ' val_acc: ', sum_)\n batch_x, batch_y = test_batch()\n batch_x = batch_x/255\n sum_ = 0\n for i__ in range(0,10000,100):\n val_acc = accuracy.eval({X: batch_x[i__:i__+100], Y_:batch_y[i__:i__+100]})\n sum_ += val_acc\n sum_ = sum_/100\n print(' Test_acc: ', sum_)\n\ndef main():\n nn()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code2.py","file_name":"code2.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"378139780","text":"import asyncio\nimport logging\nimport socket\nfrom collections import namedtuple\n\nimport netfilterqueue\nfrom dpkt import icmp, ip\nfrom netfilter import TCPEndPoint\nfrom utility import Net\n\n\nclass ContainerProxy:\n\n def __init__(self, container_mgr, config): \n self.endpoint = TCPEndPoint(config.firewall.get_interface_ip(), config.firewall.proxy_port)\n self.container_mgr = container_mgr\n self.config = config\n\n def start(self, loop):\n '''\n Starts the proxy server on the specified loop\n '''\n logging.info('Starting the container proxy server on %s', self.endpoint.port)\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # This option allows multiple processes to listen on the same port\n # server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n server_socket.bind(('0.0.0.0', int(self.endpoint.port)))\n return asyncio.start_server(self.client_connected,\n sock=server_socket,\n loop=loop)\n\n async def proxy(self, reader, writer, start_data, container_name):\n '''\n Proxies data between the client connected to the proxy and the container\n specified by container name\n '''\n read_buffer = self.config.firewall.read_buffer\n\n try:\n while True:\n if start_data is not None:\n data = start_data\n start_data = None\n else:\n data = await reader.read(read_buffer)\n if not data:\n break\n # Update last seen so that the idle monitor can determine\n # if the container has not received network IO\n await self.container_mgr.update_container(container_name)\n writer.write(data)\n await writer.drain()\n except ConnectionResetError:\n logging.debug('Connection reset writer %s', container_name)\n except Exception as ex:\n logging.error('proxy - %s', ex)\n finally:\n await self.close_stream_writer(writer)\n\n async def close_stream_writer(self, writer):\n ''' \n Safely closes the specified stream writer\n '''\n try:\n # If the call to open_connection failed, the writer\n # will be null1\n if not writer is None:\n writer.close()\n await writer.wait_closed()\n except Exception as ex:\n # Most likely connection reset from client sending a RST\n logging.debug('Closing writer %s', ex)\n\n async def client_connected(self, client_reader, client_writer):\n\n start_data = None\n remote_writer = None\n \n # Read a bit of data to see if this is just a scanner\n try:\n source_addr = client_writer.get_extra_info('peername')\n source_ip = Net.ipstr_to_int(source_addr[0])\n source_port = source_addr[1]\n container_addr = self.container_mgr.connections.get(source_ip, source_port)\n # This can happen if someone tries to connect directly to tcp:5996\n if container_addr is None:\n await self.close_stream_writer(client_writer)\n return\n\n # Some TCP discovery scanners will not send any data but SSH clients\n # send a client banner.\n if self.config.firewall.read_client:\n start_data = await client_reader.read(self.config.firewall.read_buffer)\n await client_reader.drain()\n except ConnectionResetError:\n # Client sent a RST pkt no need to clean up writer\n return\n\n # If a scanner is doing a connect scan for discovery it will not send any\n # data. Setting read_client to true during a discovery scan will prevent\n # containers from starting up and overloading the system\n if self.config.firewall.read_client and (start_data is None or len(start_data) == 0):\n await self.close_stream_writer(client_writer)\n return\n\n start_data = None\n host = container_addr[0]\n port = container_addr[1]\n\n # Start the container for the specified address\n container = await self.container_mgr.start_if_not_running(host, port, 6)\n\n if container is None:\n await self.close_stream_writer(client_writer)\n return\n\n host = Net.ipint_to_str(host)\n\n # It might take a couple of tries to hit the container until it\n # fully spins up\n for retry in range(1, container.start_retry_count):\n try:\n logging.debug('Attempt %s to connect to %s %s:%s',\n retry, container.name, host, port)\n remote_reader, remote_writer = await asyncio.open_connection(host, port)\n except Exception as err:\n await asyncio.sleep(container.start_delay)\n logging.debug(err)\n continue\n\n # Pass the initial data that was received above plus the container\n # name so that we know what container to update in the\n # container manager\n asyncio.ensure_future(self.proxy(\n client_reader, remote_writer, start_data, container.name))\n asyncio.ensure_future(self.proxy(\n remote_reader, client_writer, None, container.name))\n return\n\n # If there was never a connection made the and remote writer\n # will be null\n if not remote_writer is None:\n await self.close_stream_writer(remote_writer)\n\n await self.close_stream_writer(client_writer)\n","sub_path":"proxies.py","file_name":"proxies.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"176159110","text":"# pylint: disable=no-self-argument\nfrom wtforms.fields import (\n BooleanField, DateField,\n StringField, SubmitField,\n TextAreaField, TimeField\n)\nfrom flask_wtf import FlaskForm\nfrom wtforms.validators import DataRequired, ValidationError\nfrom wtforms.widgets.html5 import DateInput, TimeInput\nfrom datetime import datetime\n\n\nclass AppointmentForm(FlaskForm):\n name= StringField('Name',validators=[DataRequired()])\n start_date= DateField('Start Date',validators=[DataRequired()], widget=DateInput())\n start_time= TimeField('Start Time',validators=[DataRequired()], widget=TimeInput())\n end_date= DateField('End Date',validators=[DataRequired()], widget=DateInput())\n end_time= TimeField('End Time',validators=[DataRequired()], widget=TimeInput())\n description= TextAreaField('Description',validators=[DataRequired()])\n private= BooleanField('Private')\n submit= SubmitField('Create Appointment')\n\n def validate_end_date(form, field): \n start = datetime.combine(form.start_date.data, form.start_time.data)\n # end = datetime.combine(field.data, form.end_time.data)\n print(field)\n end = datetime.combine(form.end_date.data, form.end_time.data)\n if start >= end:\n msg = \"End date/time must come after start date/time\"\n raise ValidationError(msg)","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"496265357","text":"# 시간 더하기 미션 1\nprint('몇시간 후의 시간을 알려드릴까요? (현재: 오전 10시)')\na = int(input())\ntime = a + 10 # 총시간을 구함\nnow = \"\" # 오전 오후를 담을 변수\ncnt = 0\nwhile time > 12: # 총시간이 12를 넘으면 (문제가 12시간제 이기때문에)\n time -= 12 # 12를 빼고\n cnt += 1 # 카운팅\n if cnt % 2 == 0: # 현재 오전에서 짝수번 바뀌면 그대로 오전\n now = \"오전\"\n else: # 홀수번 바뀌면 반대로 오후\n now = \"오후\"\nprint(now, time, '시')\n","sub_path":"python/jeongseon`sProblem04.py","file_name":"jeongseon`sProblem04.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"241964038","text":"# -*- coding: UTF-8 -*-\n\"\"\"\ntitle: 统计打字方案数\nAlice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.\nIn order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.\n For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.\n Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.\nHowever, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.\n For example, when Alice sent the message \"bob\", Bob received the string \"2266622\".\nGiven a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.\nSince the answer may be very large, return it modulo 109 + 7.\n\n\nExample 1:\nInput: pressedKeys = \"22233\"\nOutput: 8\nExplanation:\nThe possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.\n\nExample 2:\nInput: pressedKeys = \"222222222222222222222222222222222222\"\nOutput: 82876089\nExplanation:\nThere are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n\n\nConstraints:\n1 <= pressedKeys.length <= 10^5\npressedKeys only consists of digits from '2' - '9'.\n\"\"\"\n\n\nclass Solution:\n def countTexts(self, pressedKeys: str) -> int:\n \"\"\"\n 分组DP。dp[i] 表示以pressKey[i]结尾的方案个数,其中dp[0]=1\n 分情况讨论状态转移方程:\n 1、若pressedKeys[i] != pressedKeys[i-1],则 dp[i]=dp[i-1],可理解为在长度为i-1的字符串后面加了一个字符i(固定字母),此时方案数不变\n 2、若pressedKeys[i] == pressedKeys[i-1],则 dp[i]=dp[i-1] + dp[i-2],可理解为在长度为i-1的字符串后面加了一个字符i,只不过这个字符与字符i-1相同,\n 此时的方案数为dp[i-1];另外,字符i 与 字符i-1可以合并组成一个新字母,然后接到长度为i-2的字符串后面,此时的方案数为dp[i-2]\n 3、若pressedKeys[i] == pressedKeys[i-1] == pressedKeys[i-2],则 dp[i]=dp[i-1] + dp[i-2] + dp[i-3],可理解为 情况2的基础上,\n 字符i、字符i-1、字符i-2合并组成一个新字母,然后接到长度为i-3的字符串后面,此时的方案数为dp[i-3]\n 4、若pressedKeys[i] == pressedKeys[i-1] == pressedKeys[i-2] == pressedKeys[i-3],且字符为7或9,则 dp[i]=dp[i-1] + dp[i-2] + dp[i-3] + dp[i-4],\n 可理解为 情况3的基础上,字符i、字符i-1、字符i-2、字符i-3合并组成一个新字母,然后接到长度为i-4的字符串后面,此时的方案数为dp[i-4]\n 5、以情况2为例,假设pressedKeys[i] == pressedKeys[i-1],i = 1,即 i < 2,此时dp[i-2]不存在,则认为dp[i-2]=1,\n 表示在长度为i-1的字符串后面加了一个字符i,此时方案数为dp[i-1];然后,字符i 与 字符i-1合并组成一个字母,此时的方案数为1\n \"\"\"\n mod = 10 ** 9 + 7\n n = len(pressedKeys)\n dp = [0] * n\n dp[0] = 1\n for i in range(1, n):\n # 无论哪种情况,dp[i]都大于等于dp[i-1]\n val = dp[i - 1]\n ch = pressedKeys[i]\n if ch == pressedKeys[i - 1]:\n val += dp[i - 2] if i >= 2 else 1\n if i >= 2 and ch == pressedKeys[i - 2]:\n val += dp[i - 3] if i >= 3 else 1\n if i >= 3 and ch == pressedKeys[i - 3] and ch in ['7', '9']:\n val += dp[i - 4] if i >= 4 else 1\n dp[i] = val % mod\n return dp[-1]\n\n\nif __name__ == '__main__':\n print(Solution().countTexts(\"222222222222222222222222222222222222\"))\n","sub_path":"weekly_contest/292/a2266_count-number-of-texts.py","file_name":"a2266_count-number-of-texts.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"366392871","text":"import csv\nimport pandas as pd\nimport re\n\ndataset_filepath = 'C:/Users/18281/Desktop/学习/医学信息技术专业实践与训练/day2/menu.csv'\n\n\n# 导入数据\ndef load_data(data_file):\n data = []\n with open(data_file, 'r') as csvfile:\n data_reader = csv.DictReader(csvfile)\n for row in data_reader:\n data.append((row['Category'], row['Item'], row['Calories'], row['Calories from Fat'], row['Total Fat'],\n row['Cholesterol'],\n row['Sugars']))\n return data\n\n\nmenu_data = load_data(dataset_filepath)\nmenu_df = pd.read_csv(dataset_filepath, index_col='Item',\n usecols=['Category', 'Item', 'Serving Size', 'Calories', 'Calories from Fat', 'Total Fat',\n 'Cholesterol',\n 'Sugars'])\n\n# 数据预览(head、info、describe)\nprint('菜单数据预览:')\nprint(menu_df.head())\nprint('菜单数据信息info:')\nprint(menu_df.info())\nprint('菜单数据信息describe:')\nprint(menu_df.describe())\n\n# 营养成分最高的单品\nprint('Calories最高的单品:\\t{},\\tCalories为:{}'.format(menu_df['Calories'].idxmax(), menu_df['Calories'].max()))\nprint('Calories from Fat最高的单品:\\t{},\\tCalories from Fat为:{}'.format(menu_df['Calories from Fat'].idxmax(),\n menu_df['Calories from Fat'].max()))\nprint('Total Fat最高的单品:\\t{},\\tTotal Fat为:{}'.format(menu_df['Total Fat'].idxmax(), menu_df['Total Fat'].max()))\nprint('Cholesterol最高的单品:\\t{},\\tCholesterol为:{}'.format(menu_df['Cholesterol'].idxmax(), menu_df['Cholesterol'].max()))\nprint('Sugars最高的单品:\\t{},\\tSugars为:{}\\n'.format(menu_df['Sugars'].idxmax(), menu_df['Sugars'].max()))\n\n# 营养成分最低的单品\nprint('Calories最低的单品:\\t{},\\tCalories为:{}'.format(menu_df[menu_df['Calories'] == 0].index.tolist(),\n menu_df['Calories'].min()))\nprint('Calories from Fat最低的单品:\\t{},\\tCalories from Fat为:{}'.format(\n menu_df[menu_df['Calories from Fat'] == 0].index.tolist(),\n menu_df['Calories from Fat'].min()))\nprint('Total Fat最低的单品:\\t{},\\tTotal Fat为:{}'.format(menu_df[menu_df['Total Fat'] == 0].index.tolist(),\n menu_df['Total Fat'].min()))\nprint('Cholesterol最低的单品:\\t{},\\tCholesterol为:{}'.format(menu_df[menu_df['Cholesterol'] == 0].index.tolist(),\n menu_df['Cholesterol'].min()))\nprint('Sugars最低的单品:\\t{},\\tSugars为:{}'.format(menu_df[menu_df['Sugars'] == 0].index.tolist(), menu_df['Sugars'].min()))\n\n# 菜单类型的单品数目分布(降序)\nprint('菜单类型的单品数目分布(降序)\\n{}'.format(menu_df['Category'].value_counts()))\n\n# 菜单类型的营养成分分布\ncategory = menu_df.groupby('Category')\nfor group, frame in category:\n mean_Calories = frame['Calories'].mean()\n max_Calories = frame['Calories'].max()\n min_Calories = frame['Calories'].min()\n mean_calories_from_fat = frame['Calories from Fat'].mean()\n max_calories_from_fat = frame['Calories from Fat'].max()\n min_calories_from_fat = frame['Calories from Fat'].min()\n mean_total_fat = frame['Total Fat'].mean()\n max_total_fat = frame['Total Fat'].max()\n min_total_fat = frame['Total Fat'].min()\n mean_Cholesterol = frame['Cholesterol'].mean()\n max_Cholesterol = frame['Cholesterol'].max()\n min_Cholesterol = frame['Cholesterol'].min()\n mean_Sugars = frame['Sugars'].mean()\n max_Sugars = frame['Sugars'].max()\n min_Sugars = frame['Sugars'].min()\n print('{}的平均Calories:{},\\t最高Calories:{},\\t最低Calories:{}'.format(group, mean_Calories, max_Calories, min_Calories))\n print('{}的平均Calories from Fat:{},\\t最高Calories from Fat:{},\\t最低Calories from Fat:{}'.format(group, mean_Calories,\n max_Calories,\n min_Calories))\n print(\n '{}的平均Total Fat:{},\\t最高Total Fat:{},\\t最低Total Fat:{}'.format(group, mean_Calories, max_Calories, min_Calories))\n print('{}的平均Cholesterol:{},\\t最高Cholesterol:{},\\t最低Cholesterol:{}'.format(group, mean_Calories, max_Calories,\n min_Calories))\n print('{}的平均Sugars:{},\\t最高Sugars:{},\\t最低Sugars:{}'.format(group, mean_Calories, max_Calories, min_Calories))\n\n# 营养成分最高的菜单类型\nprint('Calories平均值最大的菜单类型:\\t{},\\tCalories平均值为:{}'.format(category['Calories'].mean().idxmax(),\n category['Calories'].mean().max()))\nprint(\n 'Calories from Fat平均值最大的菜单类型:\\t{},\\tCalories from Fat平均值为:{}'.format(category['Calories from Fat'].mean().idxmax(),\n category['Calories from Fat'].mean().max()))\nprint('Total Fat平均值最大的菜单类型:\\t{},\\tTotal Fat平均值为:{}'.format(category['Total Fat'].mean().idxmax(),\n category['Total Fat'].mean().max()))\nprint('Cholesterol平均值最大的菜单类型:\\t{},\\tCholesterol平均值为:{}'.format(category['Cholesterol'].mean().idxmax(),\n category['Cholesterol'].mean().max()))\nprint(\n 'Sugars平均值最大的菜单类型:\\t{},\\tSugars平均值为:{}'.format(category['Sugars'].mean().idxmax(), category['Sugars'].mean().max()))\n\n# 营养成分最高的菜单类型\nprint('Calories平均值最小的菜单类型:\\t{},\\tCalories平均值为:{}'.format(category['Calories'].mean().idxmin(),\n category['Calories'].mean().min()))\nprint(\n 'Calories from Fat平均值最小的菜单类型:\\t{},\\tCalories from Fat平均值为:{}'.format(category['Calories from Fat'].mean().idxmin(),\n category['Calories from Fat'].mean().min()))\nprint('Total Fat平均值最小的菜单类型:\\t{},\\tTotal Fat平均值为:{}'.format(category['Total Fat'].mean().idxmin(),\n category['Total Fat'].mean().min()))\nprint('Cholesterol平均值最小的菜单类型:\\t{},\\tCholesterol平均值为:{}'.format(category['Cholesterol'].mean().idxmin(),\n category['Cholesterol'].mean().min()))\nprint(\n 'Sugars平均值最小的菜单类型:\\t{},\\tSugars平均值为:{}'.format(category['Sugars'].mean().idxmin(), category['Sugars'].mean().min()))\n\n# 查看各菜单类型的前五项单品\nfor group, frame in category:\n print(group, '\\n', frame['Serving Size'][0:5])\n\n# 过滤数据,只保留包含'g'的单品,inplace=True直接修改原df\nfor item in menu_df['Serving Size']:\n if 'g' not in item:\n menu_df.drop(index=(menu_df[menu_df['Serving Size'] == item].index), inplace=True)\n\n# 数据处理,将gram值在df中新建一列\ngram_size = []\nfor item in menu_df['Serving Size']:\n i = re.findall(r'\\d+\\.?\\d*', item[-6:-3])\n gram_size.append(int(i[0]))\nmenu_df['gram size'] = gram_size\nprint(menu_df)\n\n# 份量最多最少的单品\nprint('份量最多的单品:{},份量为:{}'.format(menu_df['gram size'].idxmax(), menu_df['gram size'].max()))\nprint('份量最少的单品:{},份量为:{}'.format(menu_df['gram size'].idxmin(), menu_df['gram size'].min()))\n\n# 份量最多最少的菜单类型\ncategory = menu_df.groupby('Category')\nfor group, frame in category:\n mean_gram_size = frame['gram size'].mean()\nprint('gram size平均值最大的菜单类型:\\t{},\\tgram size平均值为:{}'.format(category['gram size'].mean().idxmax(),\n category['gram size'].mean().max()))\n\nprint('gram size平均值最小的菜单类型:\\t{},\\tgram size平均值为:{}'.format(category['gram size'].mean().idxmin(),\n category['gram size'].mean().min()))\n","sub_path":"python/menu/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":8589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"149037609","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 Dremio\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"Tests for a GA version config for the `nessiedemo` package.\"\"\"\nimport os\nimport sys\nfrom subprocess import run # noqa: S404\n\nimport pytest\nfrom pytest import fixture, skip\n\nfrom nessiedemo.demo import setup_demo\nfrom .util import demo_setup_fixture_for_tests, expect_error\n\n\n__anything_done: bool = False\n\n\n@fixture(scope=\"function\", autouse=True)\ndef before_all(tmpdir_factory, request) -> None: # noqa: ANN001\n \"\"\"Sets up env-vars to use a pytest temp-dir and use assets from the source-tree.\"\"\"\n global __anything_done\n\n demo_setup_fixture_for_tests(tmpdir_factory, request)\n\n def __dispose_spark() -> None:\n if __anything_done:\n # Should not do this import, which would import pyspark, which fails, if we're running the wrong Python version\n from nessiedemo.delta_spark import delta_spark_dispose\n\n print(\"TEST-TEARDOWN: Disposing SparkContext...\")\n delta_spark_dispose()\n\n request.addfinalizer(__dispose_spark)\n\n\nclass TestWithDelta:\n \"\"\"Test NessieDemo with Deltlake.\"\"\"\n\n @staticmethod\n def __test_with_delta(versions_yaml: str, spark_version: int, required_envs: list) -> None:\n \"\"\"Test NessieDemo plus NessieDemoDelta.\"\"\"\n global __anything_done\n\n if False in [e in os.environ for e in required_envs]:\n skip(\n \"Missing mandatory environment variable(s) {} for in-development-yaml-test, skipping test\".format(\n \", \".join([\"{}={}\".format(e, os.environ[e] if e in os.environ else \"\") for e in required_envs])\n )\n )\n\n __anything_done = True\n\n demo = setup_demo(versions_yaml)\n\n print(\"Nessie version: {}\".format(demo.get_nessie_version()))\n\n # Same with notebooks: must NOT import nessiedemo.spark BEFORE the demo's setup has \"pip-install-ed\" the spark dependencies\n from nessiedemo.delta_spark import delta_spark_for_demo\n\n spark, sc, jvm, demo_delta = delta_spark_for_demo(demo, spark_version=spark_version)\n assert spark.conf.get(\"spark.hadoop.nessie.ref\") == \"main\"\n assert spark.conf.get(\"spark.hadoop.nessie.url\") == demo.get_nessie_api_uri()\n assert spark.conf.get(\"spark.jars.packages\") == \"org.projectnessie:nessie-deltalake-spark{}:{}\".format(\n spark_version, demo.get_nessie_version()\n )\n assert sc is not None\n assert jvm is not None\n\n run([\"nessie\", \"branch\", \"dev\"]) # noqa: S603 S607\n demo_delta.change_ref(\"dev\")\n\n dataset = demo.fetch_dataset(\"region-nation\")\n\n region_path = demo_delta.table_path(\"testing/region\")\n\n region_df = spark.read.load(dataset[\"region.parquet\"])\n region_df.write.format(\"delta\").mode(\"overwrite\").option(\"hadoop.nessie.ref\", \"dev\").save(region_path)\n\n spark.sql(\"CREATE TABLE region USING delta LOCATION '{}'\".format(region_path))\n\n assert spark.sql(\"SELECT COUNT(*) FROM region\").collect()[0][0] == 5\n\n # Verify that the table does not exist on the main branch\n demo_delta.change_ref(\"main\")\n # TODO the following fails with Delta 0.6!\n expect_error(\"pyspark.sql.utils.AnalysisException\", lambda: spark.sql(\"SELECT COUNT(*) FROM region\"))\n\n run([\"nessie\", \"merge\", \"dev\", \"-b\", \"main\", \"--force\"]) # noqa: S603 S607\n\n demo_delta.change_ref(\"main\")\n assert spark.sql(\"SELECT COUNT(*) FROM region\").collect()[0][0] == 5\n\n @pytest.mark.skip(\"Skipped until necessary Nessie PR is in\")\n @pytest.mark.forked\n def test_with_delta_spark3(self: object) -> None:\n \"\"\"Test NessieDemo+Spark against Nessie 0.6.\"\"\"\n TestWithDelta.__test_with_delta(\"in-development/nessie-0.6-delta-spark3.yml\", 3, [])\n\n # TODO figure out why the 'expect_error' checking that the 'region' table does not exist on the main branch fails,\n # the table seems to exist on the main branch although it's created on the dev branch\n @pytest.mark.skip(\"Delta/Spark2 behaves differently\")\n @pytest.mark.forked\n def test_with_delta_spark2(self: object) -> None:\n \"\"\"Test NessieDemo+Spark against Nessie 0.6.\"\"\"\n if sys.version_info >= (3, 8):\n skip(\"The necessary configuration requires pyspark==2.4.x, which does not work with Python > 3.7\")\n TestWithDelta.__test_with_delta(\"in-development/nessie-0.6-delta-spark2.yml\", 2, [])\n","sub_path":"pydemolib/tests/test_with_delta_spark.py","file_name":"test_with_delta_spark.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"324534911","text":"import sys\nimport os\n\nfrom unittest import TestCase\nfrom icon_cisco_firepower_management_center.actions.add_scan_result import AddScanResult\nfrom icon_cisco_firepower_management_center.actions.add_scan_result.schema import Input\nfrom unit_test.util import Util\nfrom unittest.mock import patch\nfrom insightconnect_plugin_runtime.exceptions import PluginException\n\nsys.path.append(os.path.abspath(\"../\"))\n\n\n@patch(\"ssl.SSLSocket.connect\", side_effect=Util.mock_connect)\n@patch(\"ssl.SSLSocket.write\", side_effect=Util.mock_write)\n@patch(\"ssl.SSLSocket.send\", side_effect=Util.mock_send)\n@patch(\"ssl.SSLSocket.recv\", side_effect=Util.mock_recv)\n@patch(\"requests.post\", side_effect=Util.mocked_requests)\n@patch(\"requests.request\", side_effect=Util.mocked_requests)\nclass TestAddScanResult(TestCase):\n def test_add_scan_result(self, mock_connect, mock_write, mock_send, mock_recv, mock_post, mock_request):\n action = Util.default_connector(AddScanResult())\n actual = action.run(\n {\n Input.SCAN_RESULT: {\n \"host\": {\n \"ip_address\": \"0.0.0.164\",\n \"operating_system\": {\"name\": \"Ubuntu\", \"vendor\": \"Canonical\", \"version\": \"16.04\"},\n },\n \"scan_result_details\": {\n \"description\": \"Example description\",\n \"protocol_id\": \"6\",\n \"scanner_id\": \"ProductZImport\",\n \"source_id\": \"ProductZ\",\n \"vulnerability_id\": \"943387\",\n \"vulnerability_title\": \"Virus Wire 0\",\n },\n },\n Input.OPERATION: \"ScanUpdate\",\n }\n )\n expected = {\"errors\": 0, \"commands_processed\": 4}\n self.assertEqual(actual, expected)\n\n def test_add_scan_result_bad(self, mock_connect, mock_write, mock_send, mock_recv, mock_post, mock_request):\n action = Util.default_connector(AddScanResult())\n with self.assertRaises(PluginException) as error:\n action.run(\n {\n Input.SCAN_RESULT: {\n \"host\": {\n \"ip_address\": \"999.999.999.999\",\n \"operating_system\": {\"name\": \"Ubuntu\", \"vendor\": \"Canonical\", \"version\": \"16.04\"},\n },\n \"scan_result_details\": {\n \"description\": \"Example description\",\n \"protocol_id\": \"6\",\n \"scanner_id\": \"ProductZImport\",\n \"source_id\": \"ProductZ\",\n \"vulnerability_id\": \"943387\",\n \"vulnerability_title\": \"Virus Wire 0\",\n },\n },\n Input.OPERATION: \"ScanUpdate\",\n }\n )\n self.assertEqual(error.exception.cause, \"The provided IP address 999.999.999.999 is invalid.\")\n self.assertEqual(error.exception.assistance, \"Please provide a valid IP address for the host and try again.\")\n","sub_path":"plugins/cisco_firepower_management_center/unit_test/test_add_scan_result.py","file_name":"test_add_scan_result.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"491268661","text":"import os\nimport tarfile\nfrom typing import Tuple\n\nimport PIL\nimport pandas as pd\nimport torch\nfrom PIL.Image import Image\nfrom torch import Tensor\nfrom torch.nn.functional import one_hot\nfrom torch.utils.data import Dataset, DataLoader, BatchSampler, RandomSampler\nfrom torchvision import transforms\nfrom torchvision.datasets.folder import default_loader\nfrom torchvision.datasets.utils import download_url, check_integrity\n\nfrom utilities.path import data_path\n\n\ndef default_loader_rgb(path):\n return PIL.Image.open(path).convert('RGB')\n\n\ndef generate_transform_dict(origin_width: int = 64, width: int = 64, scale_ratio: float = 0.6) -> dict:\n \"\"\"\n Source: https://github.com/bnu-wangxun/Deep_Metric/blob/master/DataSet/CUB200.py\n \"\"\"\n normalize = transforms.Normalize(mean=[0.502, 0.459, 0.408], std=[0.5, 0.5, 0.5])\n return {\n 'rand-crop': transforms.Compose([\n transforms.Resize(origin_width),\n transforms.RandomResizedCrop(scale=(scale_ratio, 1), size=width),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]),\n 'random_crop': transforms.Compose([\n transforms.Resize(origin_width),\n transforms.RandomResizedCrop(scale=(scale_ratio, 1.0), size=width),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]),\n 'center-crop': transforms.Compose([\n transforms.Resize(origin_width),\n transforms.CenterCrop(width),\n transforms.ToTensor(),\n normalize,\n ]),\n 'center-crop-no-norm': transforms.Compose([\n transforms.Resize(origin_width),\n transforms.CenterCrop(width),\n transforms.ToTensor()\n ]),\n 'resize': transforms.Compose([\n transforms.Resize(width),\n transforms.ToTensor(),\n normalize,\n ]),\n 'auto_augment': transforms.Compose([\n transforms.Resize(origin_width),\n transforms.RandomResizedCrop(scale=(scale_ratio, 1.0), size=width),\n transforms.RandomHorizontalFlip(),\n transforms.RandAugment(num_ops=2, magnitude=9),\n transforms.ToTensor(),\n normalize,\n ]),\n }\n\n\nclass CubDataset(Dataset):\n ZIP_URL = 'https://data.caltech.edu/records/65de6-vp158/files/CUB_200_2011.tgz?download=1'\n ZIP_FNAME = 'CUB_200_2011.tgz'\n ZIP_MD5 = '97eceeb196236b17998738112f37df78'\n\n IMG_WIDTH = 64\n TRANSFORMS = generate_transform_dict(origin_width=IMG_WIDTH, width=IMG_WIDTH)\n\n def __init__(self, train: bool = True, transforms_key: str = 'center-crop', load_bboxes: bool = False,\n use_one_hot: bool = False):\n self.data_path = os.path.join(data_path, 'cub-200-2011')\n self.img_dir_path = os.path.join(self.data_path, 'CUB_200_2011/images')\n self.transforms = self.__class__.TRANSFORMS[transforms_key]\n self.train = train\n\n self._ensure_data_exist()\n # Data Columns: ['img_id', 'filepath', 'target', 'target_name', 'is_training_img', (optional) 'bbox.{x,y,w,h}']\n self.data: pd.DataFrame = self._load(load_bboxes=load_bboxes)\n self.load_bboxes = load_bboxes\n self.bbox_cols = [c for c in self.data if c.startswith('bbox.')]\n self.use_one_hot = use_one_hot\n\n def _ensure_data_exist(self):\n os.makedirs(self.data_path, exist_ok=True)\n if not os.path.exists(self.img_dir_path):\n # Download\n zip_fpath = os.path.join(self.data_path, self.__class__.ZIP_FNAME)\n if not os.path.exists(zip_fpath) or not check_integrity(zip_fpath):\n download_url(self.__class__.ZIP_URL, self.data_path, self.__class__.ZIP_FNAME, self.__class__.ZIP_MD5)\n # Unzip\n with tarfile.open(zip_fpath, \"r:gz\") as tar:\n print(f'\\t[{self.__class__.__name__}::_ensure_data_exist] Extracting \"{zip_fpath}\"')\n tar.extractall(path=self.data_path)\n\n def _load(self, load_bboxes: bool = False):\n images = pd.read_csv(os.path.join(self.data_path, 'CUB_200_2011', 'images.txt'), sep=' ',\n names=['img_id', 'filepath'])\n image_class_labels = pd.read_csv(os.path.join(self.data_path, 'CUB_200_2011', 'image_class_labels.txt'),\n sep=' ', names=['img_id', 'target'])\n train_test_split = pd.read_csv(os.path.join(self.data_path, 'CUB_200_2011', 'train_test_split.txt'),\n sep=' ', names=['img_id', 'is_training_img'])\n class_names = pd.read_csv(os.path.join(self.data_path, 'CUB_200_2011', 'classes.txt'),\n sep=' ', names=['target', 'target_name'])\n data = images.merge(image_class_labels.merge(class_names, on='target'), on='img_id')\n data = data.merge(train_test_split, on='img_id')\n if load_bboxes:\n data = data.merge(\n pd.read_csv(os.path.join(self.data_path, 'CUB_200_2011', 'bounding_boxes.txt'),\n sep=' ', names=['img_id', 'bbox.x', 'bbox.y', 'bbox.w', 'bbox.h']),\n on='img_id')\n return data[data.is_training_img == (1 if self.train else 0)]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx: int) -> Tuple[Image or Tensor, int] or Tuple[Image or Tensor, int, Tensor]:\n sample = self.data.iloc[idx]\n path = os.path.join(self.img_dir_path, sample.filepath)\n target = sample.target - 1 # Targets start at 1 by default, so shift to 0\n target = torch.tensor(target) if not self.use_one_hot else one_hot(torch.tensor(target), 200)\n img = default_loader_rgb(path)\n if self.transforms is not None:\n img = self.transforms(img)\n if self.load_bboxes:\n return img, target.float(), torch.from_numpy(sample[self.bbox_cols].astype(float).to_numpy())\n return img, target.float()\n\n\nclass CubSegmentationDataset(CubDataset):\n SEGM_ZIP_URL = 'https://data.caltech.edu/records/w9d68-gec53/files/segmentations.tgz?download=1'\n SEGM_ZIP_FNAME = 'segmentations.tgz'\n SEGM_ZIP_MD5 = '4d47ba1228eae64f2fa547c47bc65255'\n\n def __init__(self, segm_transforms_key: str = 'center-crop-no-norm', *cub_args, **cub_kwargs):\n super(CubSegmentationDataset, self).__init__(*cub_args, **cub_kwargs)\n self.segm_dir_path = os.path.join(self.data_path, 'CUB_200_2011/segmentations')\n self._ensure_segmentation_data_exit()\n self.segm_transforms = self.__class__.TRANSFORMS[segm_transforms_key]\n\n def _ensure_segmentation_data_exit(self):\n if not os.path.exists(self.segm_dir_path):\n # Download\n zip_fpath = os.path.join(self.data_path, self.__class__.SEGM_ZIP_FNAME)\n if not os.path.exists(zip_fpath) or not check_integrity(zip_fpath):\n download_url(self.__class__.SEGM_ZIP_URL, self.data_path, self.__class__.SEGM_ZIP_FNAME,\n self.__class__.SEGM_ZIP_MD5)\n # Unzip\n with tarfile.open(zip_fpath, \"r:gz\") as tar:\n print(f'\\t[{self.__class__.__name__}::_ensure_data_exist] Extracting \"{zip_fpath}\"')\n tar.extractall(path=os.path.dirname(self.segm_dir_path))\n\n def __getitem__(self, idx: int) -> Tuple[Image or Tensor, int, Tensor] or \\\n Tuple[Image or Tensor, int, Tensor, Tensor]:\n img, target, bbox = super(CubSegmentationDataset, self).__getitem__(idx)\n segm_fpath = os.path.join(self.segm_dir_path, self.data.iloc[idx].filepath.replace(\".jpg\", \".png\"))\n seg = default_loader(segm_fpath)\n if self.segm_transforms is not None:\n seg = self.segm_transforms(seg)\n if self.load_bboxes:\n return img, target, bbox, seg\n return img, target, seg # seg is a 0-1 mask of the same shape as img\n\n\nclass CubDataLoader(DataLoader):\n \"\"\"\n CubDataLoader Class:\n This class is used to access CUB-200-2011 dataset via PyTorch's Dataloading API.\n \"\"\"\n\n def __init__(self, train=True, ds_transforms_key: str = 'center-crop', device: str = 'cpu', use_val: bool = False,\n val_size=None, use_one_hot: bool = True, **kwargs):\n self.use_one_hot = use_one_hot\n train_ds, val_ds = CubDataset(train=train, transforms_key=ds_transforms_key, use_one_hot=use_one_hot), None\n if train and use_val and val_size is not None:\n ts = len(train_ds)\n vs = int(ts * val_size) if type(val_size) == float and val_size < 1.0 else val_size\n ts -= vs\n train_ds, val_ds = torch.utils.data.random_split(train_ds, [ts, vs])\n ds = train_ds if not use_val or val_ds is None else val_ds\n if 'pin_memory' not in kwargs:\n kwargs['pin_memory'] = device != 'cpu'\n super(CubDataLoader, self).__init__(dataset=ds, shuffle=True, **kwargs)\n\n @property\n def vis_transforms(self) -> transforms.Compose:\n return transforms.Compose([\n transforms.Normalize(mean=[0., 0., 0.], std=[2.0, 2.0, 2.0]),\n transforms.Normalize(mean=[-0.502, -0.459, -0.408], std=[1.0, 1.0, 1.0])\n ])\n\n @property\n def n_classes(self) -> int:\n # noinspection PyUnresolvedReferences\n return 200\n\n\nif __name__ == '__main__':\n # ds_ = CubDataset(load_bboxes=True)\n # print(ds_.data.columns)\n # print(ds_.data.iloc[100])\n #\n # ds_ = CubSegmentationDataset(load_bboxes=True)\n # print(ds_.data.columns)\n # print(ds_.data.iloc[100])\n # ds_100_ = ds_[100]\n # print(ds_100_[0].shape, ds_100_[3].shape)\n # print(ds_100_[3].min(), ds_100_[3].max())\n\n # Dataloader\n dl_ = CubDataLoader(train=True, batch_size=1, device='cpu')\n batch_ = next(iter(dl_))\n print(batch_[0].shape)\n\n import torchvision.transforms.functional as F\n import matplotlib.pyplot as plt\n\n # plt.imshow(F.to_pil_image(batch_[0][0]))\n plt.imshow(F.to_pil_image(dl_.vis_transforms(batch_[0][0])))\n plt.show()\n","sub_path":"src/dataset/cub.py","file_name":"cub.py","file_ext":"py","file_size_in_byte":10142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"515965570","text":"from django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom .views import (IndexView, ProductView, ProductCreateView, ProductDeleteView, ProductUpdateView, ReviewCreate, ReviewDeleteView, ReviewUpdateView, ReviewListView)\n\n\nurlpatterns = [\n path('', IndexView.as_view(), name='index'),\n path('/product', ProductView.as_view(), name='product'),\n path('add/', ProductCreateView.as_view(), name='product-add'),\n path('/update', ProductUpdateView.as_view(), name='product-update'),\n path('/delete', ProductDeleteView.as_view(), name='product-delete'),\n path('/review/add', ReviewCreate.as_view(), name='review-add'),\n path('/review/delete', ReviewDeleteView.as_view(), name='review-delete'),\n path('/review/update', ReviewUpdateView.as_view(), name='review-update'),\n path('reviews-list', ReviewListView.as_view(), name='review-list')\n]","sub_path":"source/webapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"405699520","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[14]:\n\n\n'''\n5. (20 points) Implement the Blum-Blum-Shub PRNG \n\nSection 2.10 (pp. 41-43) describes the Blum-Blum-Shub algorithm for \ngenerating cryptographically secure pseudo-random bits. Implement the \nalgorithm as a program to reproduce the results on page 43. \n\nThat is, your program should:\n\n a. Hardcode the values for p and q;\n b. Compute n from those;\n c. Using the value given for x, compute and print the values x0, x1, \n ..., x8. For the moment, don't worry about producing the values \n b0, b1, ..., b8.\n\nYour answer will be a source file in Python or Java. \nPlease call it bbsprng.{java,py}.\n\n\n'''\n\ndef bbsprng():\n result = [0] * 9\n\n # a.\n p = 24672462467892469787\n q = 396736894567834589803\n \n # b.\n n = p * q\n x = 873245647888478349013\n\n # c.\n for i in range(9):\n x = (x**2) % n\n result[i] = x\n \n return result\n\nresult = bbsprng()\nfor i in range(len(result)):\n print(str(result[i]) + \"\\n\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"bbsprng.py","file_name":"bbsprng.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"308226586","text":"#!/usr/bin/python\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom email_credentials import email_credentials\nfrom sqlite3 import connect\nfrom os.path import dirname, abspath\nfrom dateutil.parser import parse\n\ndef send_mail(data):\n mailhost, fromaddr, toaddrs, subject, credentials = email_credentials()\n username, password = credentials\n subject = 'seanweather weekly report'\n body = 'Here are some interesting results, my good-looking friend:\\n\\n' + data\n msg = MIMEText(body, _charset=\"UTF-8\")\n msg['Subject'] = Header(subject, \"utf-8\")\n server = smtplib.SMTP(mailhost)\n server.starttls()\n server.login(username, password)\n server.sendmail(fromaddr, toaddrs, msg.as_string())\n server.quit()\n\ndef gather_data(cur):\n data = \"Last week's lookups\\n\"\n query = 'select zipcode, count(*) as c from lookup group by zipcode order by c desc'\n data += '\\n'.join('{}{:>3}'.format(*result) for result in cur.execute(query))\n data += '\\n\\nComments\\n'\n query = 'select date, text from comment'\n results = ((parse(date), text) for date, text in cur.execute(query))\n data += u'\\n'.join(u'{:>12} -- {}'.format(date.strftime('%m/%d %H:%M'), text) for date, text in results)\n return data\n\ndef clean_up(cur):\n cur.execute('delete from lookup')\n cur.execute('delete from comment')\n cur.execute('update location set cache=\"\" where julianday(last_updated) < julianday()-1')\n\nif __name__ == '__main__':\n directory = dirname(abspath(__file__))\n conn = connect(directory + '/db.db')\n cur = conn.cursor()\n send_mail(gather_data(cur))\n clean_up(cur)\n conn.commit()\n conn.close()\n","sub_path":"email_report.py","file_name":"email_report.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"65269076","text":"\nfrom django.shortcuts import render, redirect\nfrom .forms import RegisterForm\nfrom django.core.mail import send_mail\n\ndef profile(request):\n if request.user.is_authenticated:\n return render(request, 'accounts/profile.html')\n else:\n return redirect('index')\n\ndef SignUp(request):\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n email_address = form.cleaned_data['email']\n form.save()\n try:\n send_mail('Alert!', \"Someone new has signed up for the website. Verify and group them quickly.\", 'noreply@villamachine.com', ['mattv@villamachine.com'])\n send_mail('Welcome!', \"Thanks for signing up with us at Villa Machine! You will be verified within the next business day, although usually it's less than 10 minutes.\", 'noreply@villamachine.com', [email_address])\n except:\n pass\n return redirect('login')\n else:\n ##form = RegisterForm()\n return render(request, 'accounts/signup.html', { 'form': form })\n else:\n form = RegisterForm()\n return render(request, 'accounts/signup.html', { 'form': form })\n","sub_path":"mysite/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"37042557","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nhtml = urlopen(\"http://www.pythonscraping.com/pages/warandpeace.html\")\nbsObj = BeautifulSoup(html, \"html.parser\")\nnameList = bsObj.findAll(\"span\", {\"class\":\"green\"})\n\n\nnameList = bsObj.findAll(text=\"the prince\") \nprint (nameList) # 返回一个包含该n个text的list\n\n'''\nfor name in nameList:\n print(name) # 不用get_text()会打印整个标签\n print(name.get_text())\n'''","sub_path":"chapter2/1-selectByClass.py","file_name":"1-selectByClass.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"234765266","text":"print(\"Lemonade Tycoon v0.1\")\ntotalLemons = 0\nice = 0\nsugar = 0\ntotalDays = 0\n\n\n\ndef stock():\n global lemonPurchase\n stockMenu = True\n while stockMenu:\n print(\"1. Buy Lemons\")\n print(\"2. Buy Ice\")\n print(\"3. Buy Sugar\")\n print(\"4. Check Stock\")\n print(\"5. GO back\")\n stockMenu = input(\"What to do?\")\n if stockMenu == \"1\":\n lemonPurchase = int(input(\"How Many Lemons DO you want?\"))\n totalLemons = + lemonPurchase\n elif stockMenu == \"4\":\n print(\"Lemons: {}\".format(totalLemons))\n print(\"Ice: {}\".format(ice))\n print(\"Sugar: {}\".format(sugar))\n elif stockMenu == \"5\":\n stockMenu = False\n\n\nans = True\nwhile ans:\n print (\"Day {}\".format(totalDays))\n print(\"Choices\")\n print(\"1. Next Day\")\n print(\"2. Buy Stock\")\n\n ans = input(\"What to do?\")\n if ans == \"1\":\n totalDays += 1\n elif ans == \"2\":\n stock()\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"60194459","text":"#!/usr/bin/env python\n\n#LINK: https://leetcode-cn.com/problems/move-zeroes/\nclass Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n j = 0\n for i in range(len(nums)):\n if nums[i]:\n nums[i],nums[j] = nums[j],nums[i]\n j+=1\n \n # for i in range(j+1,len(nums)):\n # nums[i] =0\n\n# 1遍:progress 50%","sub_path":"Week_01/2moveZeros.py","file_name":"2moveZeros.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"285772858","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport requests\nimport base64\nimport codecs\nimport os\nimport re\nimport urllib3\nurllib3.disable_warnings()\n\ndef safe_base64_decode(s): # 解码\n try:\n if len(s) % 4 != 0:\n s = s + '=' * (4 - len(s) % 4)\n base64_str = base64.urlsafe_b64decode(s)\n return bytes.decode(base64_str)\n except Exception as e:\n print('解码错误:', e)\n\ndef Retry_request(url): #超时重传\n flag=True\n while flag:\n try:\n header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}\n res = requests.get(url, headers=header, timeout=5, verify=False) # verify =false 防止请求时因为代理导致证书不安全\n if res.headers['Connection']!='close':\n flag=False\n return res.text\n except Exception as e:\n print('注意检查网络,下载文件出错,对应的url地址为:'+url,e)\n\n\ndef writeRules(sublink): #写回配置\n try:\n other=[]\n data = Retry_request(sublink) #请求订阅\n ssrdata=safe_base64_decode(data).strip().split('\\n')\n rules = Retry_request('https://raw.githubusercontent.com/ConnersHua/Profiles/master/Clash/Pro.yaml') #请求规则_神机规则\n p_rule= Retry_request('https://raw.githubusercontent.com/lzdnico/ToClash/master/General.yml') #基础规则_默认不配置DNS\n #p_rule=rules.split('Proxy:')[0] #基础规则_默认配置DNS,与上面二选一\n l_rule = rules.split('Rule:\\n')[1]\n Peoxies = 'Proxy:\\n'\n \n\n name =''\n for i in range(len(ssrdata)): #节点组\n \n ssrlink=safe_base64_decode(ssrdata[i].replace('ssr://', ''))\n config=re.split(':|&|=|/\\?',ssrlink)\n remark1 =safe_base64_decode(config[11])\n\n\n # 匹配不同订阅格式\n if i < len(ssrdata)-1:\n ssrlink2=safe_base64_decode(ssrdata[i+1].replace('ssr://', ''))\n config2=re.split(':|&|=|/\\?',ssrlink2)\n remark2 =safe_base64_decode(config2[11])\n\n if remark1 == remark2:\n remark = safe_base64_decode(config[-1])\n else :\n remark = remark1\n remark2 = remark1\n # 匹配不同订阅格式结束\n\n #简单粗暴的解决一些机场节点名字重复的问题\n if remark in name: \n continue\n name += remark #占用空间大,不会出错\n #name = remark #占用空间小一点,可能会出错\n #简单粗暴的解决一些机场节点名字重复的问题结束\n \n #接下来是给节点加图标的,需要深度自定义,可以全部删除\n if \"30倍\" in remark:\n continue\n if \"香港\" in remark:\n remark = '🇭🇰' + remark\n if \"美国\" in remark or \"狮城\" in remark :\n remark = '🇺🇸' + remark\n if \"深港\" in remark or \"沪港\" in remark or \"京港\" in remark or \"杭港\" in remark:\n remark = '🇨🇳 👉👉 🇭🇰' + remark\n if \"深美\" in remark or \"沪美\" in remark or \"京美\" in remark or \"杭美\" in remark:\n remark = '🇨🇳 👉👉 🇺🇸' + remark\n if \"深日\" in remark or \"沪日\" in remark or \"京日\" in remark or \"杭日\" in remark:\n remark = '🇨🇳 👉👉 🇯🇵' + remark\n if \"深台\" in remark or \"沪台\" in remark or \"京台\" in remark or \"杭台\" in remark:\n remark = '🇨🇳 👉👉 🇨🇳' + remark\n #加图标到此结束\n\n name += remark\n print(remark)\n pwd = safe_base64_decode(config[5])\n obfsparam=safe_base64_decode(config[7])\n protoparam =safe_base64_decode(config[9]) \n Json={ 'name': remark, 'type': 'ssr', 'server': config[0], 'port': config[1], 'password':pwd , 'cipher': config[3], 'protocol': config[2], 'protocolparam': protoparam, 'obfs': config[4], 'obfsparam': obfsparam }\n #print(Json)\n Peoxies +='- '+str(Json)+'\\n'\n other.append(remark)\n\n\n #策略组\n ProxyGroup='\\n\\nProxy Group:\\n\\n'\\\n '- { name: \"😀故障切换\", type: \"fallback\", \"proxies\": ' + str(other) + ', url: \"http://www.gstatic.com/generate_204\", interval: 300'+ '}\\n\\n\\n'\\\n '- { name: \"🚀手动选择\", type: \"select\", \"proxies\": ' + str(other) + '}\\n\\n\\n'\\\n '- { name: \"PROXY\", type: select, proxies: [ \"😀故障切换\",\"🚀手动选择\",\"DIRECT\"] }\\n'\\\n '- { name: \"ForeignMedia\", type: select, proxies: [\"PROXY\",\"🚀手动选择\"] }\\n'\\\n '- { name: \"DomesticMedia\", type: select, proxies: [\"DIRECT\",\"PROXY\",\"🚀手动选择\"] }\\n'\\\n '- { name: \"Hijacking\", type: select, proxies: [\"REJECT\", \"DIRECT\"] }\\n'\\\n '- { name: \"Apple\", type: select, proxies: [\"DIRECT\", \"PROXY\"] }\\n'\\\n '- { name: \"Final\", type: select, proxies: [\"PROXY\", \"DIRECT\"] }\\n\\n\\n'\\\n 'Rule:\\n'\n return p_rule+Peoxies+ProxyGroup+l_rule #回传配置\n except Exception as e:\n print('返回规则错误:',e)\n\n\ndef getClash(nodes): #写文件\n \n try:\n\n\n with codecs.open('./config.yaml', \"w\",encoding = 'utf-8') as f:\n f.writelines(nodes)\n\n \n except Exception as e:\n print('main Error:', e)\n\nif __name__ == \"__main__\":\n try:\n url = \"\" \n data = writeRules(url)\n getClash(data)\n input('任意键退出')\n except Exception as e:\n print('main Error:', e)\n","sub_path":"旧脚本不推荐使用/SSR_Clash_NoGroup.py","file_name":"SSR_Clash_NoGroup.py","file_ext":"py","file_size_in_byte":6030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"258438037","text":"import matplotlib.pyplot as plt\nimport math\n\ndef plotter(xData, yData, givenPlot, logScale=False):\n x = xData\n if (logScale):\n y = math.log10(yData)\n else:\n y = yData\n \n return givenPlot.bar(x, y)","sub_path":"plotter/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"345142464","text":"import json\r\nimport os\r\nimport random\r\nimport pandas as pd\r\nfrom keras.preprocessing.sequence import pad_sequences\r\n\r\n# The original dataset is 50 videos of pushing, and 50 videos of other activity.\r\n# The reason to separate videos is to facilitate data preparation and avoid manual labeling.\r\n# openpose is used to get landmark features of each video frame as json file\r\n# To keep track of all frames of the videos including their landmark features and coresponding labels, a dictionary is defined\r\n# where keys are the label of each video (push_0, push_1, ..., other_0, other_1, ..) and values are vector of size (n,75)\r\n# where 'n' is the number of frames and 75 is fixed for all json files which represent the vector size of the land mark: 'pose_keypoints_2d'\r\n\r\n\r\n# input = push_0_000000000000_keypoints\r\n# output= push_0\r\ndef get_video_name(file_name):\r\n parts = file_name.split('_')\r\n return (parts[0] + '_' + parts[1])\r\n\r\n\r\n# the if statement is added since some json files did not have 'pose_keypoints_2d'\r\n\r\n# returning a dict where keys are video labels(push_0,push_1, ..)\r\n# and values are landmark vectors corresponding to frames of the video\r\ndef read_data_from_landmarks(json_dir):\r\n video_to_landmarks = {}\r\n for file in os.listdir(json_dir):\r\n file_path = json_dir + '\\\\' + file\r\n temp = json.load(open(file_path))\r\n if len(temp['people']) == 0:\r\n pass\r\n else:\r\n key = get_video_name(file)\r\n value = temp['people'][0]['pose_keypoints_2d']\r\n video_to_landmarks.setdefault(key, []).append(value)\r\n\r\n return video_to_landmarks\r\n\r\n# dictonary is a hashtable and shuffle not work.To shuffle :\r\n# get the list of keys, shuffle the keys and get the values of the corresponding keys\r\n# define a seed for random to be iterable --> random.Random(seed)\r\ndef shuffle_data (video_to_landmarks):\r\n shuffled_keys = list(video_to_landmarks.keys())\r\n random.Random(4).shuffle(shuffled_keys)\r\n labels = shuffled_keys\r\n train_data = []\r\n for key in labels:\r\n train_data.append(video_to_landmarks[key])\r\n\r\n return train_data, labels\r\n\r\n# After this step, No SHUFFLE should be applied in any other step\r\n\r\n# Driver\r\njson_dir = \"D:\\\\tamu\\\\courses\\\\DeepLearning\\\\ProjectPart5\\\\openpose_json\"\r\nvideo_to_landmarks = read_data_from_landmarks(json_dir)\r\ntrain_data, labels = shuffle_data(video_to_landmarks)\r\n\r\n# padding frames of different videos, the bellow function will automatically pad to max length\r\ninput_data = pad_sequences(train_data, dtype='float32', maxlen = 125, padding='post')\r\n\r\n# get dataframe so the data could be saved as CSV file as input: (dataframe input should be 2d)\r\n# reshaping the data so it could convertto dataframe\r\nr = input_data.shape[0]\r\nm = input_data.shape[1]\r\nn = input_data.shape[2]\r\n\r\nreshaped_inputdata = input_data.reshape(r, m*n)\r\ninput_df = pd.DataFrame(data=reshaped_inputdata, index=labels)\r\ncsv_filepath = \"D:\\\\tamu\\\\courses\\\\DeepLearning\\\\ProjectPart5\\\\input_data_2.csv\"\r\ninput_df.to_csv(csv_filepath)\r\n\r\n\r\nprint('input_data.shape: ',input_data.shape)\r\nprint('reshaped_inputdata.shape: ', reshaped_inputdata.shape)","sub_path":"sub_3/source_code/reading_json_file.py.py","file_name":"reading_json_file.py.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"197123399","text":"import os\n\nENV = 'test'\nSECRET_KEY = os.getenv('OK_SESSION_KEY', 'testkey')\n\nDEBUG = False\nASSETS_DEBUG = False\nTESTING_LOGIN = True\nDEBUG_TB_INTERCEPT_REDIRECTS = False\nINSTANTCLICK = False\n\nSQLALCHEMY_TRACK_MODIFICATIONS = False\nSQLALCHEMY_DATABASE_URI = 'sqlite:///../oktest.db'\nWTF_CSRF_CHECK_DEFAULT = False\nWTF_CSRF_ENABLED = False\n\nCACHE_TYPE = 'simple'\n\nGOOGLE_CONSUMER_KEY = ''\n","sub_path":"server/settings/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"24970788","text":"\nclass Solution:\n def helper(self,A,B):\n temp = A\n times = 1\n al = len(A)\n bl = len(B)\n\n while True:\n\n #重点在寻找这个终结点\n #如果A的每一个下标都在temp字符串中能够并可能搜索到B字符串\n #如果本次再无法搜索到字符串则不能再搜索到,因为之后的添加也只是重复的A,是没有意义的寻找\n if len(temp) - al >= bl:\n if temp.find(B) != -1:\n return times\n else:\n return -1\n\n #因为B是A的子串,所以当temp的长度大于等于bl时,就应该进行搜索\n if len(temp) >= bl:\n if temp.find(B) != -1:\n return times\n\n times += 1\n temp += A\n\ns = Solution()\nprint(s.helper(\"abcabcabcabc\",\"abac\"))\n","sub_path":"leetcode/686.py","file_name":"686.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"295285589","text":"\nimport numpy as np\n\nimport argparse\nimport logging\n\n\nimport os, glob, pathlib\n\nfrom matplotlib import pyplot\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nmpl.rcParams.update({'axes.labelsize': 45})\nmpl.rcParams.update({'xtick.labelsize': 50})\nmpl.rcParams.update({'ytick.labelsize': 50})\nmpl.rcParams.update({'axes.titlesize':40})\nmpl.rcParams.update({'legend.fontsize':14})\n\ndef gen_2d_pdist(logweights, data_n, data_sub_n, bins):\n\n logpdist = np.zeros((bins.size-1, bins.size-1))\n logpdist[:] = -np.inf\n\n # bin for N_v\n for i, lb_n in enumerate(bins[:-1]):\n ub_n = bins[i+1]\n\n ## All Ntwid vals that are in this bin\n mask_n = (data_n >= lb_n) & (data_n < ub_n)\n\n # bin for N_v1 (subvol)\n for j, lb_sub in enumerate(bins[:-1]):\n ub_sub = bins[j+1]\n\n ## All Ntwid_sub that are in this bin\n mask_sub = (data_sub_n >= lb_sub) & (data_sub_n < ub_sub)\n\n ## All values that fall in this bin\n mask = mask_n & mask_sub\n\n ## No values fall in this bin - continue\n if not mask.any():\n continue\n\n assert np.isinf(-logpdist[i,j])\n\n this_logweights = logweights[mask]\n max_val = this_logweights.max()\n this_logweights -= max_val\n\n logpdist[i,j] = np.log(np.exp(this_logweights).sum()) + max_val\n\n return -logpdist\n\n\nfnames = glob.glob(\"nstar_*/nstar_*/phiout.dat\")\n\nall_n_dat = np.array([])\nall_sub_n_dat = np.array([])\n\nstart = 300\n\nfor fname in fnames:\n print(\"doing fname: {}\".format(os.path.dirname(fname)))\n ds = dr.loadPhiSub(fname)\n\n all_n_dat = np.append(all_n_dat, ds.data[start:][\"N\"])\n all_sub_n_dat = np.append(all_sub_n_dat, ds.ds_sub.data[start:][\"N\"])\n\nbins_n = np.arange(0, all_n_dat.max()+2, 1)\n\nhist, xb, yb = np.histogram2d(all_n_dat, all_sub_n_dat, bins=bins_n)\nxx, yy = np.meshgrid(bins_n, bins_n, indexing='ij')\n\nplt.pcolormesh(xx, yy, np.log(hist))\n\n\nplt.close('all')\nwham_ds = np.load('all_data.dat.npz')\ndata = wham_ds['data_aux']\nlogweights = wham_ds['logweights']\n\nassert np.allclose(data, all_n_dat)\n\n\nneglogpdist = gen_2d_pdist(logweights, all_n_dat, all_sub_n_dat, bins_n)\nplt.pcolormesh(xx, yy, neglogpdist, cmap='jet')\nplt.colorbar()\n\n\ndef get_bias(kappa, nstar, neglogpdist, bins_n):\n bias = 0.5*kappa*((bins_n[:-1]-nstar)**2)\n biased_neglogpdist = neglogpdist + bias[:,None]\n biased_neglogpdist -= biased_neglogpdist.min()\n\n biased_Nv = -np.log(np.exp(-biased_neglogpdist).sum(axis=1))\n biased_Ns = -np.log(np.exp(-biased_neglogpdist).sum(axis=0))\n\n\n return biased_neglogpdist, biased_Nv, biased_Ns\n\n\nplt.close('all')\nkappa = beta * 0.54\n\nnstars = np.arange(-40, 110, 10)\n#plt.pcolormesh(xx, yy, biased_neglogpdist, cmap='jet')\n\nfor nstar in nstars:\n biased_neglogpdist, biased_Nv, biased_Ns = get_bias(kappa, nstar, neglogpdist, bins_n)\n\n print(\"nstar: {} : {:.1f} : {:.1f}\".format(nstar, bins_n[biased_Nv.argmin()], bins_n[biased_Ns.argmin()]))\n\n\n\n","sub_path":"scratch/sam/pattern_prep/analyze/plot_2d_overlap.py","file_name":"plot_2d_overlap.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"522582227","text":"from .baseschema import ma\nfrom marshmallow import fields, post_dump, post_load, pre_load\nfrom src.models.learning_point import LearningPoint, LearningPointTags\nfrom src.database.utils.crud import read_rows\nfrom nltk.tokenize import TweetTokenizer\nfrom src.database.db import get_db_session\nimport re\nimport string \n#TODO:\n# finish LearningPoints Tags schema\n# overide the learningStreamLearningPoints and learningStreams fields\n# ensure that overridden fields do not have refrences to circular models\n# ensure that refrences to tags do not include fields that point to other models\nclass LearningPointSchema(ma.ModelSchema):\n episodes = fields.Nested('EpisodeSchema',\n many = True, \n exclude=('learningPoints', 'episodeLearningPoints', 'episodeTags', 'tags'))\n episodeLearningPoints = fields.Nested('EpisodeLearningPointsSchema', \n many = True, \n exclude = ('learningPoint','learningPointId'), dump_only = True)\n tags = fields.Nested('TagSchema', \n many = True, \n exclude = ('learningPoints', 'learningPointTags', \n 'episodes', 'episodeTags', \n 'learningPracticesTags', 'learningPractices',\n 'learningStreamTags', 'learningStreams'))\n learningPointTags = fields.Nested('LearningPointTagsSchema', \n many = True, \n exclude = ('learningPoint', 'learningPointId'), \n dump_only = True)\n learningPracticeLearningPoints = fields.Nested('LearningPracticeLearningPointsSchema', \n many = True, \n exclude = ('learningPoint', 'learningPointID'),\n dump_only = True)\n learningPractices = fields.Nested('LearningPracticeSchema', \n many = True, \n exclude= ('learningPoints', 'learningPracticesLearningPoints'))\n class Meta:\n model = LearningPoint\n init_session, _ = get_db_session()\n sqla_session = init_session\n href = ma.Hyperlinks({\n \"self\":[\n ma.URLFor('apiV1_0.learning_points_id', id = ''),\n ma.URLFor('apiV1_0.learning_points_slug', slug = '')\n ],\n \"collection\": ma.URLFor('apiV1_0.learning_points')\n })\n @pre_load\n def check_data(self, data):\n if data.get('id') is None:\n if data.get('name') is None:\n raise ValueError('Must Include name')\n punct = set(string.punctuation)\n #if both the id and the slug is none then this is a completely new blog\n #generate the slug from the title by tokenizing the lowered title and filtering for only alphanumeric characters\n #then use the join method on the filtered slug tokens to form a slug_like_this from ['slug','like','this']\n slug_array = TweetTokenizer().tokenize(data['name'].lower())\n if len(slug_array) == 1:\n data['slug'] = slug_array[0]\n else:\n slug_array = list(filter(lambda x: not re.match(\"(\\\\d|\\\\W)+\", x) and not x in punct, slug_array))\n data['slug'] = '_'.join(slug_array)\n query = read_rows(LearningPoint, filters= [\n {\n 'slug': {\n 'comparitor': '==',\n 'data': data['slug']\n }\n }\n ]).one_or_none()\n count = 1\n #loop over until you find a unique slug by appending an incrementing count to the end of the slug\n while query is not None:\n slug = data['slug'] + '_' + str(count)\n query = read_rows(LearningPoint, filters= [\n {\n 'slug': {\n 'comparitor': '==',\n 'data': slug\n }\n }\n ]).one_or_none()\n data['slug'] = slug\n count += 1\n else:\n print(\"learning point working 1\")\n for key in list(data.keys()):\n if key != 'id':\n del data[key]\n print(\"learning point done\")\n @post_dump\n def cleanup(self, data):\n if data.get('episodeLearnigPoints') is not None:\n data['episodes'] = data['episodeLearningPoints']\n del data['episodeLearningPoints']\n if data.get('learningPointTags') is not None:\n data['tags'] = data['learningPointTags']\n del data['learningPointTags']\n if data.get('learningPracticeLearningPoints') is not None:\n data['learningPractices'] = data['learningPracticeLearningPoints']\n del data['learningPracticeLearningPoints']\n return data\n @post_load\n def load_learning_point(self, data):\n pass\nclass LearningPointTagsSchema(ma.ModelSchema):\n tag = fields.Nested('TagSchema', \n exclude = ('learningPoints', 'learningPointTags', \n 'episodes', 'episodeTags', \n 'learningPracticesTags', 'learningPractices',\n 'learningStreamTags', 'learningStreams'))\n learningPoint = fields.Nested(LearningPointSchema,\n exclude = ('learningPointTags', 'tags', \n 'episodes', 'episodeLearningPoints', \n 'learningPracticeLearningPoint', 'learningPractice'))\n class Meta:\n model = LearningPointTags","sub_path":"src/utils/marshmallow/learning_point_schema.py","file_name":"learning_point_schema.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"181138722","text":"from django.urls import path\nfrom . import views\n\napp_name = \"job\"\n\nurlpatterns = [\n path('', views.jobs, name=\"jobs\"),\n path('job/', views.detail, name=\"detail\"),\n path('add_job/', views.add_job, name=\"add_job\"),\n path('update/', views.update_job, name=\"update\"),\n path('delete/', views.delete_job, name=\"delete\"),\n path('1', views.listing, name=\"listing\"),\n\n]\n\n","sub_path":"job/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"29241680","text":"import httplib2\nimport json\n\nget_http=httplib2.Http()\n\ndef get_geo_location(location_str):\n \n Google_api_key='AIzaSyBdmaN-TIMFejXVYa3zasOeg8-JV2_wSFQ'\n \n url='https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={}'.format(location_str, Google_api_key)\n result=json.loads(get_http.request(url,'GET'))\n\n if result:\n \n latitude=result['results'][0]['geometry']['loctaion']['lat']\n langtitude=result['results'][0]['geometry']['loctaion']['lan']\n else:\n return \"No Result\"\n return latitude, langtitude\n \n \ndef get_restuarant(food,location_str):\n \n lat,lan=get_geo_location(location_str)\n foursq_client_id ='1LVBZOQ3UJQWZV2SX5FQU5BKUALE2J1EQOZPKX5OJWCSPTJC'\n foursq_client_secret ='43HXB5CD5LNO4KUFCLCKS3JSFOS10JT2SEEY5UVQXUQYVR3M'\n \n url='https://api.foursquare.com/v2/venues/search?client_id={0}&client_secret={1}&v=20160201&ll={2},{3}&query={4}'.format(foursq_client_id,\n foursq_client_secret, lat,lan,food)\n result=json.loads(get_http.request(url,'GET'))\n \n if result:\n response=result['response']['venues']\n \n for venue in response:\n venue_id=str(venue['id'])\n shop_name=str(venue['name'])\n contact=str(venue['contact']['phone'])\n address=str(venue['location']['formattedAddress'])\n restuarant_details={'rest_id':venue_id, 'rest_name':shop_name, 'rest_contact':contact, 'rest_address':address}\n \n else:\n return \"No Result\"\n\n return restuarant_details\n\nif __name__=='__main__':\n \n get_restuarant(\"Pizza\", \"Tokyo, Japan\")\n get_restuarant(\"Tacos\", \"Jakarta, Indonesia\")\n get_restuarant(\"Tapas\", \"Maputo, Mozambique\")\n get_restuarant(\"Falafel\", \"Cairo, Egypt\")\n get_restuarant(\"Spaghetti\", \"New Delhi, India\")\n get_restuarant(\"Cappuccino\", \"Geneva, Switzerland\") \n get_restuarant(\"Sushi\", \"Los Angeles, California\")\n get_restuarant(\"Steak\", \"La Paz, Bolivia\")\n get_restuarant(\"Gyros\", \"Sydney Austrailia\")\n ","sub_path":"UDACITY_REST/Restuarant_ID/Fetch_resturanat.py","file_name":"Fetch_resturanat.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"42874981","text":"import os\nfrom typing import List, Mapping, Optional, Tuple\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\nAMPHIPOD_COSTS = {\n \"A\": 1,\n \"B\": 10,\n \"C\": 100,\n \"D\": 1000,\n}\n\nHALLWAY_Y = 1\nHOLE_X = [3, 5, 7, 9]\n\n\nclass Point:\n def __init__(self, x: int, y: int) -> None:\n self.x = x\n self.y = y\n\n def as_tuple(self) -> Tuple[int, int]:\n return self.x, self.y\n\n def __hash__(self) -> int:\n return hash(self.as_tuple())\n\n def __eq__(self, __o: object) -> bool:\n if not isinstance(__o, Point):\n return NotImplemented\n return self.as_tuple() == __o.as_tuple()\n\n def path_to_horiz(self, end_pt: \"Point\") -> List[\"Point\"]:\n if self.y != end_pt.y:\n raise Exception()\n direction = 1\n if end_pt.x < self.x:\n direction = -1\n\n pts = [\n Point(x, self.y)\n for x in range(self.x + direction, end_pt.x + direction, direction)\n ]\n return pts\n\n def path_to_vert(self, end_pt: \"Point\") -> List[\"Point\"]:\n if self.x != end_pt.x:\n raise Exception()\n direction = 1\n if end_pt.y < self.y:\n direction = -1\n\n pts = [\n Point(self.x, y)\n for y in range(self.y + direction, end_pt.y + direction, direction)\n ]\n return pts\n\n def path_to(self, end_pt: \"Point\") -> List[\"Point\"]:\n # if end_pt.y < self.y:\n # interm = Point(self.x, end_pt.y)\n # return self.path_to_vert(interm) + interm.path_to_horiz(end_pt)\n # else:\n # interm = Point(end_pt.x, self.y)\n # return self.path_to_horiz(interm) + interm.path_to_vert(end_pt)\n if self.x == end_pt.x:\n return self.path_to_vert(end_pt)\n interm1 = Point(self.x, HALLWAY_Y)\n interm2 = Point(end_pt.x, HALLWAY_Y)\n\n return (\n self.path_to_vert(interm1)\n + interm1.path_to_horiz(interm2)\n + interm2.path_to_vert(end_pt)\n )\n\n def __repr__(self) -> str:\n return str(self.as_tuple())\n\n\ndef generate_open_points(positions: Mapping[Point, str]) -> List[Point]:\n return [x for x in positions if positions[x] == \".\"]\n\n\ndef generate_amphipod_positions(\n positions: Mapping[Point, str]\n) -> Mapping[str, Tuple[Point, Point]]:\n amphipod_positions = {}\n for x in AMPHIPOD_COSTS:\n amphipod_positions[x] = []\n\n for x in positions:\n if positions[x] in AMPHIPOD_COSTS:\n amphipod_positions[positions[x]].append(x)\n\n return {\n x: (amphipod_positions[x][0], amphipod_positions[x][1])\n for x in amphipod_positions\n }\n\n\ndef compute_heuristic_single_type_no_hole(\n amphipod_type: str, pt1: Point, pt2: Point\n) -> int:\n hole_dists = [abs(pt1.x - hx) + abs(pt2.x - hx) for hx in HOLE_X]\n min_dist = min(hole_dists)\n\n # Plus 3 to go down into hole\n return AMPHIPOD_COSTS[amphipod_type] * (min_dist + 3)\n\n\ndef compute_heuristic_single_type(amphipod_type: str, pt1: Point, pt2: Point) -> int:\n heuristic_dist = 0\n if pt1.y == HALLWAY_Y and pt2.y == HALLWAY_Y:\n return compute_heuristic_single_type_no_hole(amphipod_type, pt1, pt2)\n if pt1.x == pt2.x:\n # This is a simplification, but since amphipods cannot park outside a hole it is valid\n return 0\n if pt1.y == HALLWAY_Y + 2:\n end_pt = pt1\n start_pt = pt2\n elif pt2.y == HALLWAY_Y + 2:\n end_pt = pt2\n start_pt = pt1\n elif pt1.y == HALLWAY_Y + 1:\n end_pt = pt1\n start_pt = pt2\n heuristic_dist += 2\n elif pt2.y == HALLWAY_Y + 1:\n end_pt = pt2\n start_pt = pt1\n heuristic_dist += 2\n else:\n raise Exception(\"This should not happen.\")\n\n interm = Point(start_pt.x, HALLWAY_Y)\n\n path = start_pt.path_to(interm) + interm.path_to(end_pt)\n\n # -1 because we want to end up next to, not on\n heuristic_dist += len(path) - 1\n\n return AMPHIPOD_COSTS[amphipod_type] * heuristic_dist\n\n\ndef compute_heuristic(amphipod_positions: Mapping[str, Tuple[Point, Point]]) -> int:\n return sum(\n [\n compute_heuristic_single_type(\n x, amphipod_positions[x][0], amphipod_positions[x][1]\n )\n for x in amphipod_positions\n ]\n )\n\n\ndef generate_unique_id(positions: Mapping[Point, str]) -> str:\n hallway_pts = [x.x for x in positions if x.y == HALLWAY_Y]\n hallway_min_x = min(hallway_pts)\n hallway_max_x = max(hallway_pts)\n\n identifier = \"\"\n\n for x in range(hallway_min_x, hallway_max_x + 1):\n identifier += positions[Point(x, HALLWAY_Y)]\n\n for x in HOLE_X:\n for y in [HALLWAY_Y + 1, HALLWAY_Y + 2]:\n identifier += positions[Point(x, y)]\n\n return identifier\n\n\nclass BoardState:\n def __init__(\n self,\n positions: Mapping[Point, str],\n cost: int = 0,\n parent: Optional[\"BoardState\"] = None,\n ) -> None:\n self.parent = parent\n self.positions = positions\n self.cost = cost\n self.open_points = generate_open_points(self.positions)\n self.amphipod_positions = generate_amphipod_positions(self.positions)\n self.heuristic = compute_heuristic(self.amphipod_positions)\n self.uid = generate_unique_id(self.positions)\n\n def estimated_cost(self) -> int:\n return self.cost + self.heuristic\n\n def __hash__(self) -> int:\n return hash(self.uid)\n\n def __eq__(self, __o: object) -> bool:\n if not isinstance(__o, BoardState):\n return NotImplemented\n return self.uid == __o.uid\n\n def is_valid_destination(\n self, amphipod_type: str, start: Point, end: Point\n ) -> bool:\n if end.x in HOLE_X and end.y == HALLWAY_Y:\n return False\n if (\n end.y == HALLWAY_Y + 1\n and self.positions[Point(end.x, end.y + 1)] != amphipod_type\n ):\n return False\n if start.y == HALLWAY_Y and end.y == HALLWAY_Y:\n return False\n if (\n start.y == HALLWAY_Y + 1\n and self.positions[Point(start.x, start.y + 1)] == amphipod_type\n ):\n return False\n return True\n\n def is_path_open(self, start: Point, end: Point) -> bool:\n path = start.path_to(end)\n\n for x in path:\n if self.positions[x] != \".\":\n return False\n\n return True\n\n def generate_next_valid_boards(self) -> List[\"BoardState\"]:\n next_boards = []\n\n for x in self.amphipod_positions:\n for start_pt in self.amphipod_positions[x]:\n for end_pt in self.open_points:\n\n # print(f\"Move {start_pt} to {end_pt}\")\n\n if self.is_valid_destination(\n self.positions[start_pt], start_pt, end_pt\n ) and self.is_path_open(start_pt, end_pt):\n new_positions = {x: self.positions[x] for x in self.positions}\n new_positions[end_pt] = self.positions[start_pt]\n new_positions[start_pt] = \".\"\n path_len = len(start_pt.path_to(end_pt))\n cost = (\n self.cost\n + AMPHIPOD_COSTS[self.positions[start_pt]] * path_len\n )\n\n next_boards.append(BoardState(new_positions, cost, self))\n\n return next_boards\n\n def visualize(self) -> None:\n for y in range(HALLWAY_Y + 4):\n for x in range(14):\n if Point(x, y) in self.positions:\n print(self.positions[Point(x, y)], end=\"\")\n else:\n print(\"#\", end=\"\")\n print(\"\")\n\n\npts = {}\nwith open(f\"{cur_dir}/sample_input\") as f:\n for y, line in enumerate(f):\n for x, c in enumerate(line.rstrip()):\n if c in [\".\", \"A\", \"B\", \"C\", \"D\"]:\n pts[Point(x, y)] = c\n\nprint(pts)\nstate = BoardState(pts)\nstate.visualize()\n\nstates = [state]\nvisited_states = set()\nsolution_found = len([x for x in states if x.heuristic == 0]) != 0\nwhile not solution_found:\n state = states[0]\n print(state.estimated_cost())\n state.visualize()\n states = states[1:]\n\n visited_states.add(state)\n\n next_states = state.generate_next_valid_boards()\n next_states = [x for x in next_states if x not in visited_states]\n\n states += next_states\n\n states.sort(key=lambda x: x.estimated_cost())\n solution_found = len([x for x in states if x.heuristic == 0]) != 0\n if solution_found:\n solution = [x for x in states if x.heuristic == 0][0]\n\n states = [x for x in states if x not in visited_states]\n\n # for x in states:\n # print(x.estimated_cost())\n # x.visualize()\n\nprint(solution.cost)\n\npath = []\nwhile solution is not None:\n path.append(solution)\n solution = solution.parent\nprint(\"Full path\")\nfor x in reversed(path):\n print(x.cost)\n x.visualize()\n","sub_path":"2021/23/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":9021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"609155014","text":"# Purpose: Python 2/3 compatibility layer\n# Created: 12.05.13\n# Copyright (c) 2013-2018, Manfred Moitzi\n# License: MIT License\n\nimport sys\nimport functools\nimport array\n\nPY3 = sys.version_info.major > 2\nif sys.version_info[:2] > (3, 2):\n from collections.abc import Sequence\nelse:\n from collections import Sequence\n\n\nif PY3:\n import html\n escape = functools.partial(html.escape, quote=True)\n basestring = str\n ustr = str\n unicode2bytes = lambda s: bytes(s, encoding='utf-8')\n import reprlib\nelse: # Python 2.7\n import cgi\n import repr as reprlib\n escape = functools.partial(cgi.escape, quote=True)\n ustr = unicode\n unicode2bytes = lambda s: s.encode('utf-8')\n\n\ndef byte_to_hexstr(byte):\n if PY3:\n return \"%0.2X\" % byte\n else:\n return \"%0.2X\" % ord(byte)\n\n\ndef encode_hex_code_string_to_bytes(data):\n byte_array = array.array('B', (int(data[index:index+2], 16) for index in range(0, len(data), 2)))\n if PY3:\n return byte_array.tobytes()\n else:\n return byte_array.tostring()\n\n\ndef isstring(s):\n return isinstance(s, basestring)\n","sub_path":"ezdxf/tools/c23.py","file_name":"c23.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"56191495","text":"import acm\nfrom DealPackageDevKit import CompositeAttributeDefinition, DealPackageChoiceListSource, AttributeDialog, Action, Object, Bool, CalcVal, ParseSuffixedFloat\nfrom CompositeAttributes import BuySell \nfrom CompositeTradeDefinition import TradeDefinition\n\nclass NDFTradeDefinition(TradeDefinition):\n\n def OnInit(self, trade, showBuySell=True, **kwargs):\n super(NDFTradeDefinition, self).OnInit(trade, showBuySell, **kwargs)\n self._settlementCurrencyChoices = DealPackageChoiceListSource()\n self._ndfCurrencyTwoChoices = DealPackageChoiceListSource()\n\n def Attributes(self):\n \n attributes = super(NDFTradeDefinition, self).Attributes()\n \n\n attributes['fxNDFAmount1'] = BuySell( label=self.UniqueCallback('@NDFAmounts1Label'),\n buySellLabels=[\"B\", \"S\", \"-\"],\n objMapping=self._trade+'.FxForwardAmount1',\n enabled=self.UniqueCallback('@NDFAmountsEnabled'),\n showBuySell=False)\n attributes['fxNDFAmount2'] = BuySell( label=self.UniqueCallback('@NDFAmounts2Label'),\n buySellLabels=[\"B\", \"S\", \"-\"],\n objMapping=self._trade+'.FxForwardAmount2',\n enabled= self.UniqueCallback('@NDFAmountsEnabled'),\n showBuySell=False)\n attributes['fxNDFCurrencyOne'] = Object( label='Curr Pair',\n objMapping=self._trade+'.FxForwardCurrencyOne',\n choiceListSource=self.UniqueCallback('@NDFCurrencyOneChoices'),\n onChanged=self.UniqueCallback('@UpdateSettlementCurrencyChoices|@UpdateNDFCurrencyTwoChoices'))\n attributes['fxNDFCurrencyTwo'] = Object( label='',\n objMapping=self._trade+'.FxForwardCurrencyTwo',\n choiceListSource=self.UniqueCallback('@NDFCurrencyTwoChoices'),\n onChanged=self.UniqueCallback('@UpdateSettlementCurrencyChoices'))\n attributes['fxNDFSettlementDate'] = Object( label='Settle Date',\n objMapping=self._trade+'.FxForwardSettlementDate',\n transform=self.UniqueCallback('@TransformSettlementPeriodToDate'))\n attributes['fxNDFPoints'] = Object( label='Points',\n objMapping=self._trade+'.FxForwardPoints',\n enabled=self.UniqueCallback('@NDFAmountsEnabled')) \n attributes['settlementCurrency'] = Object( label='Settle Curr',\n objMapping=self._trade+'.SettlementCurrency',\n choiceListSource=self.UniqueCallback('@SettlementCurrencyChoices'))\n attributes['quotingMethod'] = Action( label=self.UniqueCallback('@QuotingMethodLabel'),\n sizeToFit=True,\n action=self.UniqueCallback('@QuotingMethod'))\n \n \n return attributes\n \n # Enabled callbacks\n def NDFAmountsEnabled(self, attributeName):\n return self.Trade().FxForwardCurrencyOne() and self.Trade().FxForwardCurrencyTwo()\n \n # Visible callbacks\n \n # ChoiceListSource callbacks\n def SettlementCurrencyChoices(self, attributeName):\n if self._settlementCurrencyChoices.IsEmpty():\n self.UpdateSettlementCurrencyChoices()\n return self._settlementCurrencyChoices\n \n def NDFCurrencyOneChoices(self, attributeName):\n return self.Trade().Instrument().DefaultOneCurrencies()\n \n def NDFCurrencyTwoChoices(self, attributeName):\n if self._ndfCurrencyTwoChoices.IsEmpty():\n self.UpdateNDFCurrencyTwoChoices()\n return self._ndfCurrencyTwoChoices \n \n # Label callbacks\n def NDFAmounts1Label(self, attributeName):\n if self.NDFAmountsEnabled(attributeName):\n return 'Amount '+self.Trade().FxForwardCurrencyOne().Name()\n else:\n return 'Amount 1'\n \n def NDFAmounts2Label(self, attributeName):\n if self.NDFAmountsEnabled(attributeName):\n return 'Amount '+self.Trade().FxForwardCurrencyTwo().Name()\n else:\n return 'Amount 2'\n \n def QuotingMethodLabel(self, attributeName):\n if self.NDFIsNormalQuoted():\n return 'N'\n else:\n return 'I'\n\n # Transform callbacks\n def TransformSettlementPeriodToDate(self, name, date, *args):\n try: \n date = self.Trade().FxForwardSettlementDateFromPeriod(date)\n return date\n except:\n return date\n \n # OnChanged callbacks\n def UpdateMirrorPortfolioChoices(self, *args):\n self._mirrorPortfolioChoices.Clear()\n counterparty = self.Trade().Counterparty()\n if counterparty:\n self._mirrorPortfolioChoices.AddAll(counterparty.OwnedPortfolios())\n \n def UpdateCollateralAgreementChoices(self, *args):\n self._collateralAgreementChoices.Clear()\n collateralAgreements = acm.Risk().CollateralAgreements(self.Trade().Counterparty(), self.Trade().Acquirer())\n self._collateralAgreementChoices.AddAll(collateralAgreements)\n \n def UpdateSettlementCurrencyChoices(self, *args):\n self._settlementCurrencyChoices.Clear()\n self._settlementCurrencyChoices.AddAll(self.Trade().Instrument().DefaultDealtCurrencies())\n \n def UpdateNDFCurrencyTwoChoices(self, *args):\n self._ndfCurrencyTwoChoices.Clear()\n self._ndfCurrencyTwoChoices.AddAll(self.Trade().Instrument().DefaultTwoCurrencies())\n \n def QuotingMethod(self, *args):\n self.Trade().FxForwardQuotingMethod()\n\n # Util\n def NDFIsNormalQuoted(self):\n quotationType = self.Trade().Instrument().Quotation().QuotationType()\n underlyingCurrency = self.Trade().Instrument().Underlying()\n currencyPair = self.Trade().CurrencyPair()\n if currencyPair:\n return ( (quotationType != 'Per Unit Inverse' and underlyingCurrency == currencyPair.Currency1()) or\n (quotationType == 'Per Unit Inverse' and underlyingCurrency == currencyPair.Currency2()) )\n else:\n return True\n","sub_path":"Extensions/Default/FPythonCode/CompositeNDFTradeDefinition.py","file_name":"CompositeNDFTradeDefinition.py","file_ext":"py","file_size_in_byte":7126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425140648","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport traceback as tb\nimport yaml\nimport time\nimport export_to_telegraph\nfrom common import telegraph_token\nimport re\n\nclass DBClass(object):\n def __init__(self, name, default = {}):\n self.name = \"db/%s.yaml\" % name\n try:\n with open(self.name) as f:\n self.db = yaml.load(f, Loader=yaml.FullLoader)\n except Exception as e:\n print(e)\n tb.print_exc()\n self.db = default\n\n def save(self):\n with open(self.name, 'w') as f:\n f.write(yaml.dump(self.db, sort_keys=True, indent=2, allow_unicode=True))\n\n\nclass _Source(DBClass):\n def __init__(self):\n super().__init__(\"source\")\n\n def add(self, chatname):\n if chatname not in self.db:\n self.db[chatname] = 0\n self.save()\n return 'success'\n return 'source already added'\n\n def remove(self, chatname):\n if chatname in self.db:\n self.db.pop(chatname, None)\n return 'success'\n return 'no such source'\n\n def iterate(self, chatname, max):\n while self.db[chatname] < max:\n self.db[chatname] += 1\n self.save()\n yield self.db[chatname]\n\nclass _Subscription(DBClass):\n def __init__(self):\n super().__init__(\"subscription\")\n\n def add(self, x, mode):\n if x not in self.db or self.db[x]['mode'] != mode:\n self.db[x] = mode\n self.save()\n\n def remove(self, x):\n self.db.pop(x, None)\n\ndef getLan(title):\n if re.search(u'[\\u4e00-\\u9fff]', title):\n return 'zh'\n return 'en'\n\nclass _Pool(DBClass):\n def __init__(self):\n super().__init__(\"pool\")\n\n def add(self, x):\n export_to_telegraph.token = telegraph_token\n r = export_to_telegraph.get(x)\n self.db[x] = {\n \"view\": r['views'],\n \"language\": getLan(r['title']),\n } \n self.save()\n\nclass _Sent(DBClass):\n def __init__(self):\n super().__init__(\"sent\")\n\n def forget(self, x):\n self.db.pop(x, None)\n self.save()\n\n def add(self, gid, url):\n if not gid in self.db:\n self.db[gid] = set()\n self.db[gid].add(url)\n self.save()\n\nSubscription = _Subscription()\nSent = _Sent()\nPool = _Pool()\nSource = _Source()","sub_path":"db/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"645788025","text":"#!/usr/bin/env python\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2011-2013, The BIOM Format Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\nfrom __future__ import division\nfrom pyqi.core.command import Command, Parameter, ParameterCollection\n\nfrom numpy import std\n\nfrom biom.util import (compute_counts_per_sample_stats, \n safe_md5,\n biom_open)\nfrom biom.parse import parse_biom_table\nfrom biom.table import Table\n\n__author__ = \"Greg Caporaso\"\n__copyright__ = \"Copyright 2011-2013, The BIOM Format Development Team\"\n__credits__ = [\"Greg Caporaso\"]\n__license__ = \"BSD\"\n__version__ = \"1.2.0-dev\"\n__maintainer__ = \"Greg Caporaso\"\n__email__ = \"gregcaporaso@gmail.com\"\n\nclass TableSummarizer(Command):\n \"\"\"\n Example usage:\n from biom.commands.table_summarizer import TableSummarizer\n from biom.parse import parse_biom_table\n c = TableSummarizer()\n table_f = open(\"table.biom\",\"U\")\n t = parse_biom_table(table_f)\n table_f.seek(0)\n result = c(table=(t,None))\n result = c(table=(t,None),qualitative=True)\n result = c(table=(t,table_f),qualitative=True)\n table_f.close()\n \"\"\"\n BriefDescription = \"Summarize sample or observation data in a BIOM table\"\n LongDescription = \"Provides details on the observation counts per sample, including summary statistics, as well as metadata categories associated with samples and observations.\"\n Parameters = ParameterCollection([\n Parameter(Name='table', \n DataType=tuple,\n Description='the input BIOM table', \n Required=True),\n Parameter(Name='qualitative', \n DataType=bool,\n Description=('Present counts as number of unique '\n 'observation ids per sample, rather than '\n 'counts of observations per sample.'), \n Required=False,\n Default=False),\n Parameter(Name='suppress_md5', \n DataType=bool,\n Description=('Do not compute md5sum of table. '\n 'Useful if you\\'re concerned about runtime.'), \n Required=False,\n Default=False)\n ])\n\n def run(self, **kwargs):\n \"\"\"\n table: two-element tuple containing the biom table to summarize and\n the file(-like) object containing the original table data. The\n second element of the tuple (the file(-like) object) may be\n None. If this is the case, the MD5 sum will *not* be computed\n qualitative: counts are presented as number of unique observation\n ids per sample, rather than total observation count per\n sample\n suppress_md5: if ``True``, the MD5 sum of the table file contents will\n not be computed. This parameter is ignored if\n ``table[1] is None``\n \"\"\"\n result = {}\n qualitative = kwargs['qualitative']\n table, table_lines = kwargs['table']\n \n min_counts, max_counts, median_counts, mean_counts, counts_per_sample =\\\n compute_counts_per_sample_stats(table, qualitative)\n num_observations = len(table.ObservationIds)\n \n suppress_md5 = (table_lines is None) or kwargs['suppress_md5']\n \n counts_per_sample_values = counts_per_sample.values()\n \n if table.SampleMetadata is None:\n sample_md_keys = [\"None provided\"]\n else:\n sample_md_keys = table.SampleMetadata[0].keys()\n \n if table.ObservationMetadata is None:\n observation_md_keys = [\"None provided\"]\n else:\n observation_md_keys = table.ObservationMetadata[0].keys()\n \n lines = []\n \n num_samples = len(counts_per_sample)\n lines.append('Num samples: %d' % num_samples)\n lines.append('Num observations: %d' % num_observations)\n if not qualitative:\n total_count = sum(counts_per_sample_values)\n lines.append('Total count: %d' % total_count)\n lines.append('Table density (fraction of non-zero values): %1.3f' % \\\n table.getTableDensity())\n if not suppress_md5:\n lines.append('Table md5 (unzipped): %s' % safe_md5(table_lines))\n lines.append('')\n\n if qualitative:\n lines.append('Observations/sample summary:')\n else:\n lines.append('Counts/sample summary:')\n lines.append(' Min: %r' % min_counts)\n lines.append(' Max: %r' % max_counts)\n lines.append(' Median: %1.3f' % median_counts)\n lines.append(' Mean: %1.3f' % mean_counts)\n lines.append(' Std. dev.: %1.3f' % std(counts_per_sample_values))\n lines.append(' Sample Metadata Categories: %s' % '; '.join(sample_md_keys))\n lines.append(' Observation Metadata Categories: %s' % '; '.join(observation_md_keys))\n \n lines.append('')\n if qualitative:\n lines.append('Observations/sample detail:')\n else:\n lines.append('Counts/sample detail:')\n \n sorted_counts_per_sample = [(v,k) for k,v in counts_per_sample.items()]\n sorted_counts_per_sample.sort()\n for v,k in sorted_counts_per_sample:\n lines.append(' %s: %r' % (k,v))\n \n result['biom-summary'] = lines\n return result\n \n\nCommandConstructor = TableSummarizer\n","sub_path":"biom/commands/table_summarizer.py","file_name":"table_summarizer.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"508117102","text":"'''\nCreated by the authors.\n@wallissoncarvalho\n@machadoyang\n'''\n\nimport pandas as pd\nimport methods\nimport geoprocessing\nimport flowsignatures\nimport clustering\nimport plot\n\n\n\n\n\nobserved_flows = pd.read_pickle(r'data\\observed_flows.pkl')\n\n\n##GENERATING FLOW STATIONS SHAPEFILE\nflow_stations = geoprocessing.shape_estacoes_area(observed_flows,r'data/stations_hidroweb.xls',r'shapefiles/BHSF_WGS1984.shp')\naffected_stations = pd.read_pickle(r'data\\affected_stations_final.pkl')\n\n##STATIONS AFFECTED BY RESERVOIRS\nlist_affected = []\nfor column in affected_stations.columns:\n list_affected = list_affected+list(affected_stations[column].dropna())\nflow_stations=flow_stations.drop(list(map(int,list_affected)))\nflow_stations.to_file(r'shapefiles/flow_stations.shp')\nlist_affected = list_affected+ ['46105000']\n##GENERATION FLOW SIGNATURES\nsignatures = flowsignatures.all_signatures(observed_flows)\nsignatures = signatures.drop(list_affected) #REMOVING STATIONS AFFECTEDS BY RESERVOIRS\nsignatures=pd.read_pickle(r'data/signatures.pkl')\n\n\n\n##GENERATING Physiographic Data\nphysiographic_data = geoprocessing.physiographic_data(r'shapefiles\\Watersheds.shp',r'shapefiles\\LongestFlowPath.shp',r'raster/mdt_23s.tif')\nphysiographic_data.to_pickle(r'data/physiographic_data.pkl')\nphysiographic_data = pd.read_pickle(r'data/physiographic_data.pkl')\n\n\n#GENERATING ALL PARAMETERS\nall_parameters = pd.concat([physiographic_data,signatures],axis=1, sort=True)\nall_parameters['Q90'] = all_parameters['Q90']/all_parameters['AreaKm2']\nall_parameters['Q10'] = all_parameters['Q10']/all_parameters['AreaKm2']\nall_parameters['Qmean'] = all_parameters['Qmean']/all_parameters['AreaKm2']\nall_parameters=all_parameters.dropna()\nall_parameters=all_parameters.rename(columns={'AreaKm2':'Area','Slp1085':'$S_{10-85}$','Elev_Mean':'$E_{mean}$','Elev_std':'$E_{std}$',\n 'Q90':'$Q_{90}$','Qmean':'$Q_{mean}$','Q10':'$Q_{10}$','RBF':'$RB_{Flash}$',\n 'SFDC':'$S_{FDC}$','IBF':'$I_{BF}$'})\nall_parameters.to_pickle(r'data/all_parameters.pkl')\n\n\n#ANALYZING CORRELATIONS\ncorrelation = all_parameters.corr(method='spearman')\ncalc_correlations = methods.calc_high_correlations(correlation)\nplot.correlation_matrix(all_parameters)\n\n\n#REMOVING HIGH CORRELATIONS\nall_parameters.pop('Area')\nall_parameters.pop('$S_{FDC}$')\nall_parameters.pop('AC')\n\n\n#Standardizing ALL PARAMETERS\nall_parameters = methods.standard_data(all_parameters)\n\n\n##CLUSTERING PROCESS\ncluster = clustering.kmeans_ward_evaluation(all_parameters)\nplot.cluster_evaluation(all_parameters)\n\n##PLOT WARD DENDOGRAM\nplot.dendogram(all_parameters)\n\n#CLUSTERING ASSESSMENT\nall_parameters = pd.read_pickle(r'data/all_parameters.pkl')\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"630396731","text":"import logging\nfrom abc import abstractmethod\n\nfrom commands import AddKarmaCommand\nfrom config import Config\nfrom model.karma import KarmaType\nfrom model.member import Member\nfrom slack_channel.abstract_event_handler import AbstractEventHandler\nfrom slack_channel.slack_parser import SlackParser\n\n\nclass AbstractKarmaEventHandler(AbstractEventHandler):\n\n @property\n @abstractmethod\n def name(self) -> str:\n pass\n\n @abstractmethod\n def _get_command_symbol(self) -> str:\n pass\n\n @property\n def command(self) -> AddKarmaCommand:\n return AddKarmaCommand()\n\n def get_usage(self):\n return self._get_command_symbol() + \" recipient [[for ] reason]\"\n\n @property\n def _help_message(self):\n return self._get_command_symbol() + \" -?\"\n\n def can_handle(self, slack_event):\n text = slack_event[\"text\"]\n return text.startswith(self._get_command_symbol())\n\n def _invoke_handler_logic(self, slack_event):\n try:\n command_text = slack_event['text']\n args = self._parse_command_text(command_text)\n self.command.execute(awarded_to=args[\"recipient\"],\n awarded_by=slack_event[\"user\"],\n reason=args[\"reason\"],\n karma_type=args[\"karma_type\"])\n self._send_reaction_response(slack_event)\n except Exception as ex:\n logging.exception(ex)\n\n def _parse_command_text(self, command_text):\n command_text = SlackParser.replace_slack_id_tokens_with_usernames(command_text)\n karma_type_arg = command_text[:2]\n karma_type = KarmaType.POZZYPOZ if karma_type_arg == \"++\" else KarmaType.NEGGYNEG\n command_text = command_text[3:]\n\n if command_text.find(\" for \") != -1:\n command_split = command_text.split(\" for \")\n recipient = self._parse_recipient(command_split[0].split(\" \"))\n else:\n command_split = command_text.split(\" \")\n recipient = self._parse_recipient(command_split)\n\n reason = self._parse_reason(command_text, recipient)\n\n return {\"recipient\": recipient, \"reason\": reason, \"karma_type\": karma_type}\n\n def _parse_recipient(self, command_split):\n possible_username = command_split[0]\n decided_username = \" \".join(command_split)\n\n username_is_known = self._username_is_known(possible_username)\n if username_is_known:\n decided_username = possible_username\n\n return decided_username\n\n @staticmethod\n def _username_is_known(username):\n m = Member.get_member_by_username(username)\n if m is not None:\n return True\n else:\n return False\n\n @staticmethod\n def _parse_reason(command_text, recipient):\n recipient_length = len(recipient) + 1 # +1 to account for space\n if command_text.find(\" for \") != -1:\n recipient_length += 4\n reason = command_text[recipient_length:]\n return reason\n\n def __init__(self, debug=False):\n self.config = Config()\n self.config.connect_to_db()\n super(AbstractKarmaEventHandler, self).__init__(debug)\n\n\nclass IncrementKarmaEventHandler(AbstractKarmaEventHandler):\n\n @property\n def name(self):\n return \"Pozzy-poz\"\n\n def _get_command_symbol(self):\n return \"++\"\n\n def __init__(self, debug=False):\n super(IncrementKarmaEventHandler, self).__init__(debug)\n\n\nclass DecrementKarmaEventHandler(AbstractKarmaEventHandler):\n\n @property\n def name(self):\n return \"Neggy-neg\"\n\n def _get_command_symbol(self):\n return \"--\"\n\n def __init__(self, debug=False):\n self.debug = debug\n super(DecrementKarmaEventHandler, self).__init__(debug)\n","sub_path":"slack_channel/add_karma_event_handler.py","file_name":"add_karma_event_handler.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"594423215","text":"from exercises.patterns.factory.maze_factory import MazeFactory\nfrom exercises.patterns.factory.enchanted_maze_factory import EnchantedMazeFactory\nfrom exercises.patterns.factory.player import Player\nfrom exercises.patterns.factory.wizard import Wizard\nfrom exercises.patterns.factory.direction import Direction\nfrom exercises.patterns.factory.maze_game import create_factory_maze_type_a, create_factory_maze_type_b\n\nmaze = create_factory_maze_type_a(MazeFactory)\nenchanted_maze = create_factory_maze_type_b(EnchantedMazeFactory)\n\npinky = Player(\"Pinky\", maze.get_room_by_number(1))\nharry = Wizard(\"Harry\", enchanted_maze.get_room_by_number(1))\n\n\ndef test_play_maze():\n play(maze, pinky)\n\n\ndef test_play_enchanted_maze():\n play_enchanted(enchanted_maze, harry)\n\n\ndef play(maze, player):\n print(\"\\n--> Player {} enters the maze in room {}\".format(player.player_id, player.current_room.room_number))\n room1 = player.current_room\n for side in Direction.ALL:\n print(\"\\t{} SIDE: {}\".format(side, room1.get_side(side)))\n\n door = room1.get_side(Direction.EAST)\n if not door.is_open:\n door.unlock()\n door.enter(player)\n\n # lol, this line gave me so many headaches - python is different than Java! :)\n room2 = player.current_room\n for side in Direction.ALL:\n print(\"\\t{} SIDE: {}\".format(side, room2.get_side(side)))\n\n\ndef play_enchanted(maze, player):\n print(\"\\n---> Wizard {} enters the enchanted maze in room {}\".format(player.player_id, player.current_room.room_number))\n room1 = player.current_room\n for side in Direction.ALL:\n print(\"\\t{} SIDE: {}\".format(side, room1.get_side(side)))\n\n door = room1.get_side(Direction.SOUTH)\n player.unlock_with_spell(door)\n door.enter(player)\n\n room2 = player.current_room\n for side in Direction.ALL:\n print(\"\\t{} SIDE: {}\".format(side, room2.get_side(side)))\n\n","sub_path":"exercises/patterns/test/test_maze_game.py","file_name":"test_maze_game.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"645793168","text":"from framework.command.command import Command\nfrom framework.config import config\nfrom framework.rom import base_types\nfrom framework.rom import meta\nfrom framework.rom import rom_object\nfrom framework.rom import rom_property\nfrom framework.rom import manager\nfrom framework.task.task import CommandTask\nfrom framework.task.task import ExecuteMode\nfrom framework.utils import log\n\n\nclass RomCommandTask(CommandTask):\n def __init__(self, cmd, mode=ExecuteMode.SynCoroutine):\n CommandTask.__init__(self, cmd, mode=mode)\n\n def scheduled(self):\n self.commandobj.scheduled()\n super().scheduled()\n\n def running(self):\n self.commandobj.running()\n super().running()\n\n def success(self):\n if self.commandobj.isrunning() is True:\n self.commandobj.success()\n elif self.commandobj.issuccess() is not True:\n self.commandobj.fail()\n if self.commandobj.AutoDelete:\n manager.ROMManager.delete_object(self.commandobj.handle)\n self.commandobj = None\n super().success()\n\n def fail(self):\n self.commandobj.fail()\n if self.commandobj.AutoDelete:\n manager.ROMManager.delete_object(self.commandobj.handle)\n self.commandobj = None\n super().fail()\n\n\nclass ROMCommandStateEnum(base_types.ROMEnum):\n INIT = 0, 'Init'\n SCHEDULED = 1, 'Scheduled'\n RUNNING = 2, 'Running'\n SUCCESS = 3, 'Success'\n FAIL = 4, 'Fail'\n\n\n@meta.rom(private=True)\nclass ROMCommand(Command, rom_object.ROMObject):\n CommandState = rom_property.EnumProperty(ROMCommandStateEnum, default=ROMCommandStateEnum.INIT, category='state',\n display='Command State')\n\n AutoDelete = rom_property.BoolProperty(default=True, display='Auto Delete Command', category='input')\n\n def __init__(self):\n super().__init__()\n self.pre_running_cbs = set()\n attr = self.get_attr('NoCommit')\n if not attr or not attr.value:\n # This command needs to commit configuration before running\n self.register_pre_running_cb(config.Configurator().apply)\n\n def register_pre_running_cb(self, cb):\n if cb not in self.pre_running_cbs:\n self.pre_running_cbs.add(cb)\n\n def on_prop_changed(self, prop_obj, old_value=None):\n if prop_obj.name == 'CommandState':\n if self.CommandState == ROMCommandStateEnum.SCHEDULED:\n for cb in self.pre_running_cbs:\n cb()\n\n parent = self.get_parent()\n from framework.smart_scripter import control_commands\n if isinstance(parent, control_commands.GroupCommand):\n if isinstance(prop_obj, rom_property.HandleProperty):\n if not prop_obj.aggregate:\n if old_value:\n o = manager.ROMManager.get_object(old_value)\n if hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count -= 1\n o = manager.ROMManager.get_object(self.get_property(prop_obj.name))\n if hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count += 1\n else:\n o.ref_by_command_count = 1\n else:\n for handle in old_value:\n o = manager.ROMManager.get_object(handle)\n if hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count -= 1\n new_value = self.get_property(prop_obj.name)\n for handle in new_value:\n o = manager.ROMManager.get_object(handle)\n if hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count += 1\n else:\n o.ref_by_command_count = 1\n\n def _finalize(self):\n parent = self.get_parent()\n from framework.smart_scripter import control_commands\n if isinstance(parent, control_commands.GroupCommand):\n for cls in self._rom_bases:\n for prop in cls._properties.values():\n if isinstance(prop, rom_property.HandleProperty):\n value = self.get_property(prop.name)\n if not prop.aggregate:\n o = manager.ROMManager.get_object(value)\n if o and hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count -= 1\n else:\n for handle in value:\n o = manager.ROMManager.get_object(handle)\n if o and hasattr(o, 'ref_by_command_count'):\n o.ref_by_command_count -= 1\n\n def scheduled(self):\n self.CommandState = ROMCommandStateEnum.SCHEDULED\n\n def running(self):\n self.CommandState = ROMCommandStateEnum.RUNNING\n\n def isrunning(self):\n return self.CommandState == ROMCommandStateEnum.RUNNING\n\n def issuccess(self):\n return self.CommandState == ROMCommandStateEnum.SUCCESS\n\n def success(self):\n self.CommandState = ROMCommandStateEnum.SUCCESS\n log.Logger.CL.info('Execute {} done.'.format(self.handle))\n\n def fail(self):\n self.CommandState = ROMCommandStateEnum.FAIL\n log.Logger.CL.info('Execute {} fail.'.format(self.handle))\n\n def execute(self, async_mode=True):\n \"\"\"\n create a CommandTask with default model that execute self command\n :return:\n \"\"\"\n log.Logger.CL.info('Executing {} with parameter: \\n{}'.format(self.handle, self.get_parameter_string()))\n try:\n self.check_user()\n if async_mode is True:\n self.user.commpro.add_task(RomCommandTask(self))\n else:\n self.scheduled()\n self.running()\n self._run()\n self.success()\n except Exception as e:\n log.Logger.CL.exception(e)\n self.fail()\n raise\n\n def reset_command_state(self):\n self.CommandState = ROMCommandStateEnum.INIT\n\n def get_parameter_string(self):\n props = []\n for name, prop in self._properties.items():\n if prop.category != 'output'and not prop.private:\n props.append('{}:{}'.format(name, self.get_prop_in_str(name)))\n return '\\n'.join(props)\n\n","sub_path":"CL/framework/command/rom_command.py","file_name":"rom_command.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"259048611","text":"#!/usr/bin/env pypy3\r\n\"\"\"\r\nFlexAEADv1.py - this class is used to define the FlexAEADv1 cipher\r\nUsage:\r\n import FlexAEADv1\r\nOptions:\r\n no options\r\n\"\"\"\r\n__author__ = 'Eduardo Marsola do Nascimento'\r\n__copyright__ = 'Copyright 2018-11-25'\r\n__credits__ = ''\r\n__license__ = 'MIT'\r\n__version__ = '0.01'\r\n__maintainer__ = ''\r\n__email__ = ''\r\n__status__ = 'Development'\r\n\r\nfrom FlexAESBox import FlexAESBox\r\nimport math\r\n\r\ndef byteToHex(data):\r\n \"\"\"\r\n byteToHex - convert a byte array into a comma sepparated hex representation\r\n Args:\r\n data: the byte array to be converted\r\n Returns:\r\n returns comma separated hex representation.\r\n \"\"\"\r\n result = '0x{:02X}'.format(data[0])\r\n for ch in data[1:]:\r\n result += ',0x{:02X}'.format(ch)\r\n return result\r\n\r\nclass FlexAEADv1:\r\n dirSBox = [ FlexAESBox.dirSBox0 ]\r\n invSBox = [ FlexAESBox.invSBox0 ]\r\n nSBoxes = len( dirSBox )\r\n \r\n def __init__(self, key = bytes(16), nBytes = 8, nRounds = 0):\r\n self.nBytes = nBytes\r\n self.counter = bytes([0] * self.nBytes)\r\n self.checksum = bytes([0] * self.nBytes)\r\n\r\n t0 = bytes([0] * int(len(key)/2))\r\n t1 = b''\r\n ### init nRounds for the subkey generation\r\n self.nRounds = int(math.log(len(t0),2)+2)\r\n while(len(t1)<(nBytes*8)):\r\n t0 = self.dirPFK( t0, key)\r\n t0 = self.dirPFK( t0, key)\r\n t0 = self.dirPFK( t0, key)\r\n t1 += t0\r\n self.key0 = t1[nBytes*0:nBytes*2]\r\n self.key1 = t1[nBytes*2:nBytes*4]\r\n self.key2 = t1[nBytes*4:nBytes*6]\r\n self.key3 = t1[nBytes*6:nBytes*8]\r\n\r\n if(nRounds==0):\r\n self.nRounds = int(math.log(nBytes,2)+2)\r\n else:\r\n self.nRounds = nRounds\r\n \r\n ### Debug - comment next line\r\n \"\"\"\r\n print(' ### FlexAEADv1 - init ### - Debug Start')\r\n print(' self.nRounds : ',self.nRounds)\r\n print(' self.key0 : '+byteToHex(self.key0))\r\n print(' self.key1 : '+byteToHex(self.key1))\r\n print(' self.key2 : '+byteToHex(self.key2))\r\n print(' self.key3 : '+byteToHex(self.key3))\r\n print('self.checksum : '+byteToHex(self.checksum))\r\n print(' self.counter : '+byteToHex(self.counter))\r\n print(' ### FlexAEADv1 - init ### - Debug End')\r\n #\"\"\"\r\n \r\n def encryptMessage( self, nonce, AD, message ):\r\n self.counter = FlexAEADv1.inc32(self.dirPFK( nonce, self.key3))\r\n self.checksum = bytes([0]*self.nBytes)\r\n ### Debug - comment next line\r\n \"\"\"\r\n print(' ### FlexAEADv1 - encryptmessage ### - Debug Start')\r\n print('self.checksum : '+byteToHex(self.checksum))\r\n print(' self.counter : '+byteToHex(self.counter))\r\n print(' s0 : '+byteToHex(self.dirPFK( self.counter, self.key3)))\r\n print(' ### FlexAEADv1 - encryptmessage ### - Debug End')\r\n #\"\"\"\r\n ### Encrypt the Associate Data just to calculate the tag\r\n AD += bytes([0] * (len(AD)%self.nBytes))\r\n i = 0\r\n while( i < len(AD)):\r\n self.encryptBlock(AD[i:i+self.nBytes],isAD=True)\r\n i += self.nBytes\r\n ### Encrypt the PlainText\r\n state = b''\r\n while( len(state)+self.nBytes < len(message)):\r\n state += self.encryptBlock(message[len(state):len(state)+self.nBytes])\r\n lastblock, tag = self.encryptBlock(message[len(state):], final = True)\r\n return state+lastblock, tag\r\n\r\n def decryptMessage( self, nonce, AD, message, tag ):\r\n self.counter = FlexAEADv1.inc32(self.dirPFK( nonce, self.key3))\r\n self.checksum = bytes([0]*self.nBytes)\r\n ### Debug - comment next line\r\n \"\"\"\r\n print(' ### FlexAEADv1 - decryptmessage ### - Debug Start')\r\n print('self.checksum : '+byteToHex(self.checksum))\r\n print(' self.counter : '+byteToHex(self.counter))\r\n print(' s0 : '+byteToHex(self.dirPFK( self.counter, self.key2)))\r\n print(' ### FlexAEADv1 - decryptmessage ### - Debug End')\r\n #\"\"\"\r\n ### Encrypt the Associate Data just to calculate the tag\r\n AD += bytes([0] * (len(AD)%self.nBytes))\r\n i = 0\r\n while( i < len(AD)):\r\n self.encryptBlock(AD[i:i+self.nBytes],isAD=True)\r\n i += self.nBytes\r\n ### Encrypt the PlainText\r\n state = b''\r\n while( len(state)+self.nBytes < len(message)):\r\n state += self.decryptBlock(message[len(state):len(state)+self.nBytes],None)\r\n lastblock, validmessage = self.decryptBlock(message[len(state):], tag, final = True)\r\n if( validmessage ):\r\n return state+lastblock, validmessage\r\n else:\r\n return b'', validmessage\r\n\r\n def encryptBlock( self, block, final=False, isAD=False ):\r\n if( final ):\r\n paddingXOR = bytes([0xAA] * self.nBytes)\r\n if( len(block)0) ):\r\n i -= 1\r\n if( (int(state[i])==0x80) and (i>0)):\r\n return state[:i], True\r\n ### Debug - comment next line\r\n \"\"\"\r\n print(' i : ',i)\r\n print(' state[i] : ',state[i])\r\n print(' state : '+byteToHex(state))\r\n #\"\"\"\r\n return b'', False\r\n else:\r\n self.counter = FlexAEADv1.inc32(self.counter)\r\n return state\r\n\r\n def inc32( block, inc=1 ):\r\n state = b''\r\n for i in range(0,len(block),4):\r\n state += ((int.from_bytes(block[i:(i+4)],'big')+inc).to_bytes(4,'big'))\r\n return state\r\n\r\n def shuffleLayer( block ):\r\n zero = 0\r\n half = int(len(block)/2)\r\n state = [0]*len(block)\r\n for i in range(half):\r\n state[(2*i)+0] = (int(block[i+zero])&0xF0) + \\\r\n ((int(block[i+half])&0xF0)>>4)\r\n state[(2*i)+1] = ((int(block[i+zero])&0x0F)<<4)+\\\r\n (int(block[i+half])&0x0F)\r\n return bytes(state)\r\n\r\n def invshuffleLayer( block ):\r\n zero = 0\r\n half = int(len(block)/2)\r\n state = [0]*len(block)\r\n for i in range(half):\r\n state[i+zero] = (int(block[(2*i)+0])&0xF0) + \\\r\n ((int(block[(2*i)+1])&0xF0)>>4)\r\n state[i+half] = (int(block[(2*i)+1])&0x0F) + \\\r\n ((int(block[(2*i)+0])&0x0F)<<4)\r\n return bytes(state)\r\n\r\n def dirSBoxLayer( block ):\r\n state = [0]*len(block)\r\n for i in range(len(block)):\r\n state[i] = FlexAEADv1.dirSBox[i%FlexAEADv1.nSBoxes][int(block[i])]\r\n return bytes(state)\r\n\r\n def invSBoxLayer( block ):\r\n state = [0]*len(block)\r\n for i in range(len(block)):\r\n state[i] = FlexAEADv1.invSBox[i%FlexAEADv1.nSBoxes][int(block[i])]\r\n return bytes(state)\r\n\r\n def dirPFK( self, plaintext, key_pfk):\r\n if len(plaintext)*2 != len(key_pfk):\r\n print('wrong block({})/key({}) size on dirPFK'.format(len(plaintext),len(key_pfk)))\r\n return plaintext\r\n \r\n half = int(len(plaintext)/2)\r\n ciphertext = bytes([int(a)^int(b) for a,b in zip(plaintext,key_pfk)])\r\n \r\n for i in range(self.nRounds):\r\n ### Shuffle Layer\r\n ciphertext = FlexAEADv1.shuffleLayer(ciphertext)\r\n left = ciphertext[:half]\r\n right = ciphertext[half:]\r\n ### SBox Layer (right)\r\n right = FlexAEADv1.dirSBoxLayer(right)\r\n #### XOR L + R -> L\r\n left = bytes([int(a)^int(b) for a,b in zip(left,right)])\r\n ### SBox Layer (left)\r\n left = FlexAEADv1.dirSBoxLayer(left)\r\n #### XOR L + R -> R\r\n right = bytes([int(a)^int(b) for a,b in zip(left,right)])\r\n ### SBox Layer (right)\r\n right = FlexAEADv1.dirSBoxLayer(right)\r\n ### ciphertext = left+right\r\n ciphertext = left+right\r\n \r\n ciphertext = bytes([int(a)^int(b) for a,b in zip(ciphertext,key_pfk[len(ciphertext):])])\r\n\r\n return ciphertext\r\n\r\n def invPFK( self, ciphertext, key_pfk):\r\n if len(ciphertext)*2 != len(key_pfk):\r\n print('wrong block({})/key({}) size on dirPFK'.format(len(ciphertext),len(key_pfk)))\r\n return ciphertext\r\n \r\n half = int(len(ciphertext)/2)\r\n plaintext = bytes([int(a)^int(b) for a,b in zip(ciphertext,key_pfk[len(ciphertext):])])\r\n \r\n for i in range(self.nRounds):\r\n ### ciphertext = left+right\r\n left = plaintext[:half]\r\n right = plaintext[half:]\r\n ### SBox Layer (right)\r\n right = FlexAEADv1.invSBoxLayer(right)\r\n #### XOR L + R -> R\r\n right = bytes([int(a)^int(b) for a,b in zip(left,right)])\r\n ### SBox Layer (left)\r\n left = FlexAEADv1.invSBoxLayer(left)\r\n #### XOR L + R -> L\r\n left = bytes([int(a)^int(b) for a,b in zip(left,right)])\r\n ### SBox Layer (right)\r\n right = FlexAEADv1.invSBoxLayer(right)\r\n ### Shuffle Layer\r\n plaintext = left + right\r\n plaintext = FlexAEADv1.invshuffleLayer(plaintext)\r\n \r\n plaintext = bytes([int(a)^int(b) for a,b in zip(plaintext,key_pfk)])\r\n\r\n return plaintext\r\n\r\n \r\ndef __templatefunc( input1, input2, input3):\r\n \"\"\"\r\n __templatefunc - this function ....\r\n Args:\r\n input1: first arg ....\r\n input2: second arg ....\r\n input3: third arg ....\r\n Returns:\r\n the function result.\r\n \"\"\"\r\n pass\r\n return\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n # track execution time\r\n from datetime import datetime\r\n startTime=datetime.now()\r\n #\r\n print(sys.version)\r\n \"\"\"\r\n your code\r\n \"\"\"\r\n # track execution time\r\n finishTime=datetime.now()\r\n print( '\\nStart: {}, Finish:{}, Running Time: {}'\r\n ''.format(startTime.replace(microsecond=0),\r\n finishTime.replace(microsecond=0),\r\n finishTime-startTime))\r\n ################### END #################\r\n","sub_path":"flexaead/python/FlexAEADv1.py","file_name":"FlexAEADv1.py","file_ext":"py","file_size_in_byte":13531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"406848331","text":"from matplotlib import pyplot as plt\n\ndef visualize_images(legend, *args):\n if(len(args) == 0):\n return\n \n nrows, ncols = len(args), len(args[0]) \n fig, axs = plt.subplots(nrows=nrows, ncols=ncols) \n if nrows == 1:\n for row, images in enumerate(args):\n for col in range(ncols):\n axs[col].imshow(images[col], cmap=plt.cm.gray)\n return\n \n for row, images in enumerate(args): # for each bunch of objects\n for col, ax in enumerate(axs[row]): # for each object show it on correct row and col\n if (row == 0):\n ax.set_title(legend[col])\n \n ax.imshow(images[col], cmap=plt.cm.gray)\n ax.set_xticks([])\n\ndef visualize_one(title, image):\n plt.title(title)\n plt.imshow(image)\n\ndef visualize_pairs(*pairs):\n visualize_images((\"lr\", \"hr\"), *pairs)\n \ndef visualize_triplets(*triplets):\n visualize_images((\"lr\", \"prediction\", \"hr\"), *triplets)\n","sub_path":"utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"260029390","text":"import socket\n\n\nserver_ip=\"127.0.0.1\"\nserver_port=10000\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n\ndef main():\n while True:\n msg = input(\">>\")\n client.sendto(msg.encode(), (server_ip,server_port))\n\nif __name__ == \"__main__\":\n main()","sub_path":"sistemi_IV/python/bruno_luca/prova.py","file_name":"prova.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"518254489","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import date\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\nimport requests\n\n\nclass EmployeeVerification(models.Model):\n _name = 'employee.verification'\n _rec_name = 'verification_id'\n\n verification_id = fields.Char('ID', readonly=True, copy=False)\n employee = fields.Many2one('hr.employee', string='Employee', required=True, help='You can choose the employee for background verification')\n address = fields.Many2one(related='employee.address_home_id', string='Address', readonly=False)\n assigned_by = fields.Many2one('res.users', string='Assigned By', readonly=1, default=lambda self: self.env.uid)\n agency = fields.Many2one('res.partner', string='Agency', domain=[('verification_agent', '=', True)], help='You can choose a Verification Agent')\n resume_uploaded = fields.Many2many('ir.attachment', string=\"Resume of Applicant\",\n help='You can attach the copy of your document', copy=False)\n description_by_agency = fields.Char(string='Description', readonly=True)\n agency_attachment_id = fields.Many2one('ir.attachment', string='Attachment',help='Attachment from Agency')\n field_check = fields.Boolean(string='Check', invisible=True)\n assigned_date = fields.Date(string=\"Assigned Date\", readonly=True, default=date.today())\n expected_date = fields.Date(state='Expected Date', help='Expected date of completion of background varification')\n state = fields.Selection([\n ('draft', 'Draft'),\n ('assign', 'Assigned'),\n ('submit', 'Varification Completed'),\n ], string='Status', default='draft')\n company_id = fields.Many2one('res.company', 'Company',\n default=lambda self: self.env['res.company'].browse(1))\n\n\n \n def download_attachment(self):\n if self.agency_attachment_id:\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/binary/image?model=ir.attachment&field=datas&id=%s&filename=%s' % (self.agency_attachment_id.id,self.agency_attachment_id.name),\n 'target': 'new',\n }\n else:\n raise UserError(_(\"No attachments available.\"))\n\n \n def assign_statusbar(self):\n if self.agency:\n if self.address or self.resume_uploaded:\n self.state = 'assign'\n template = self.env.ref('employee_background.assign_agency_email_template')\n self.env['mail.template'].browse(template.id).send_mail(self.id, force_send=True)\n else:\n raise UserError(_(\"There should be at least address or resume of the employee.\"))\n else:\n raise UserError(_(\"Agency is not assigned. Please select one of the Agency.\"))\n\n # sequence generation for employee verification\n @api.model\n def create(self, vals):\n seq = self.env['ir.sequence'].next_by_code('res.users') or '/'\n vals['verification_id'] = seq\n return super(EmployeeVerification, self).create(vals)\n\n \n def unlink(self):\n if self.state not in 'draft':\n raise UserError(_('You cannot delete the verification created.'))\n super(EmployeeVerification, self).unlink()\n","sub_path":"employee_background/models/employee_verification.py","file_name":"employee_verification.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"300868827","text":"import os\nimport numpy as np\nimport math\nimport re\nimport datetime\n\nDAY = 1 # days\n\n\nclass Parser:\n CONFIG = None\n \n # shrink data size by averaging over a time period\n # twoD_list: list of values (one commit value for each day)\n # x: number of days to average on\n # returns list with of x elements from commit_list averaged\n @staticmethod\n def avg_x_days(twoD_list, x):\n def avg(commit_list):\n result = []\n for count in xrange(1, 1 + int(math.ceil(len(commit_list)/float(x)))):\n arr = commit_list[(count-1) * x: count * x]\n avg = sum(arr)/float(len(arr))\n result.append(avg)\n return result\n twoD_list_avg_x_days = []\n for word in twoD_list:\n twoD_list_avg_x_days.append(avg(word))\n return twoD_list_avg_x_days\n\n @staticmethod\n def add_dict_entry(dict_, key, num):\n if key in dict_:\n dict_[key].append(num)\n else:\n dict_[key] = [num]\n \n # Create file with list of top words\n @classmethod\n def write_word_file(cls, words):\n f = open(cls.CONFIG['DATA_DIR'] + 'commit_words.txt', 'w')\n for key in words:\n f.write(key + '\\n')\n f.close()\n\n # Create file with list of commit dates\n @classmethod\n def write_dates_file(cls, dates):\n def to_pretty_date(date):\n year,month,day = date.split('-')\n return datetime.date(int(year), int(month), int(day)).strftime('%B %d %Y')\n \n f = open(cls.CONFIG['DATA_DIR'] + 'commit_dates.txt', 'w')\n for date in dates:\n f.write(to_pretty_date(date) + '\\n')\n f.close()\n\n # process the input commit data file\n @classmethod\n def process_file(cls, file_name):\n f = open(file_name, 'r')\n repo_name = None\n word_dict = {}\n dates = []\n \n for line in f:\n if not repo_name:\n repo_name = line\n continue\n \n lineSplit = re.split('\\t| ', line)\n \n if len(lineSplit) == 2 and lineSplit[0] is not '%':\n word = lineSplit[0]\n num = int(lineSplit[1])\n Parser.add_dict_entry(word_dict, word, num)\n elif lineSplit[0] is '%':\n dates.append(lineSplit[1])\n f.close()\n # iterate over dictionary, make into array of values\n twoD_list = [word_dict[key] for key in word_dict]\n\n # Create file with list of commit words\n cls.write_word_file(word_dict)\n\n # Create file with list of commit dates\n cls.write_dates_file(dates)\n\n # shrink data size by averaging over a time period\n if cls.CONFIG['granularity'] > DAY:\n twoD_list = cls.avg_x_days(twoD_list, cls.CONFIG['granularity'])\n \n if cls.CONFIG['overlay_words']:\n return twoD_list\n else:\n # order 2D array structure as a list of date entries\n # with each date entry containing a list of entries for each word\n return np.flipud(np.rot90(twoD_list)).tolist()\n \n @classmethod\n def parse(cls):\n data_dir = cls.CONFIG['BASE_DIR']\n if (cls.CONFIG['test']):\n in_file = 'test.txt'\n data_dir += '/test/'\n else:\n in_file = 'commits.txt'\n data_dir += '/Analyzer/'\n data = []\n for file_name in os.listdir(data_dir):\n if file_name.endswith(in_file):\n data += cls.process_file(data_dir + file_name)\n return data\n \n","sub_path":"WavMaker/Parser/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"257127614","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx,y = np.loadtxt('ANUscan.dat',delimiter=',',unpack=True)\nLx,Ly = np.loadtxt('Lykke.csv',unpack=True)\ndx,dy = np.loadtxt('../Digitizer/DIB-8037.csv',delimiter=',',unpack=True)\nsx,sy = np.loadtxt('../Digitizer/sar07b.csv',delimiter=',',unpack=True)\nsx2,sy2 = np.loadtxt('../Digitizer/sar07c2.csv',delimiter=',',unpack=True)\nmx,my = np.loadtxt('../Digitizer/mabs17a.csv',delimiter=',',unpack=True)\nspec = np.loadtxt('0wavenumber10K.txt', usecols=(0, 1, 2), unpack=True)\n\n#Mabbs17 Model\nmx = spec[0]+12468\nmy = spec[2]\n\n#Mabbs17 Data\nv = (max(my)-min(my))/(max(y)-min(y))\nmy /=v\nmy -= 600\n\n\n#Sarre07 Rotational Model\nsx *=0.1\nsx = 1e7/sx\nv = (max(sy)-min(sy))/(max(y)-min(y))\nsy /=v\nv = np.mean(sy)\nsy +=1800-v\n#Sarre07 at 2.7K\nsx2 *=0.1\nsx2 = 1e7/sx2\nv = (max(sy2)-min(sy2))/(max(y)-min(y))\nsy2 /=v\nv = np.mean(sy2)\nsy2 +=1900-v\n\n#DIB Astro\ndx *=0.1\ndx = 1e7/dx\nv = (max(dy)-min(dy))/(max(y)-min(y))\ndy /=v\nv = np.mean(dy)\ndy +=2400-v\n#ANU\nx = 1e7/x\n#Lineberger\nsubr = np.logical_and(Lx>x[-1],Lx12449,x<12465)\nay = y[subr]\nax = x[subr]\nb = max(ay)\nsubi = np.logical_and(ay>b-0.001,ay<1000)\nc = ax[subi]\nprint(b)\nprint(c)\n\nsubr = np.logical_and(Lx>12449,Lx<12465)\nay = Ly[subr]\nax = Lx[subr]\nLb = max(ay)\nsubi = np.logical_and(ay>Lb-0.001,ay<1000)\nLc = ax[subi]\nprint(Lb)\nprint(Lc)\n\nratio = b/Lb\nLy *= ratio\nshift = Lc-c\n#Lx -= shift\nLz = Lx-shift\nprint(shift)\n\n#Plotting Shifts\nLy +=600\n\nplt.plot(x,y,label='ANU')\nplt.plot(Lx,Ly,label='Lineberger')\nplt.plot(dx,dy,label='DIB')\nplt.plot(sx,sy,label='Sarre07 Model')\nplt.plot(sx2,sy2,label='Sarre07 2.7K')\nplt.plot(mx,my,label='Mabbs17 Model')\nplt.plot((12459.033,12459.033),(2500,-600),'C7--')\nplt.plot((12440.77,12440.77),(2500,-600),'C7--')\nplt.xlim(12380,12510)\nplt.legend()\nplt.show()\n","sub_path":"Scripts/compplot.py","file_name":"compplot.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"572514511","text":"#!/usr/bin/env python3\nfrom robot_ros import RobotRos\nfrom robot import Robot\nimport rospy\nimport numpy as np\n\nKICK_TIMEOUT = 3\nGETUPFRONT_TIMEOUT = 7\nGETUPBACK_TIMEOUT = 10\ngoal_list = [np.array([2, 2, 0]), np.array([-2, 2, 0]), np.array([-2, -2, 0]), np.array([2, -2, 0])]\ncurrent_stage = 0\nrospy.init_node(\"soccer_strategy\")\n\nrobot = RobotRos(team=Robot.Team.FRIENDLY, role=Robot.Role.GOALIE, status=Robot.Status.READY, robot_name=\"robot1\")\n\nrospy.sleep(1)\nr = rospy.Rate(10)\nwhile rospy.get_param(\"walking_engine_ready\") == \"false\":\n r.sleep()\n\nwhile not rospy.is_shutdown():\n rostime = rospy.get_rostime().secs + rospy.get_rostime().nsecs * 1e-9\n if robot.status == Robot.Status.WALKING:\n # publish a goal robot.goal_position geometry_msgs/Pose2D to /robot_name/goal\n pass\n\n elif robot.status == Robot.Status.FALLEN_BACK:\n robot.terminate_walking_publisher.publish()\n robot.trajectory_publisher.publish(\"getupback\")\n robot.trajectory_complete = False\n robot.status = Robot.Status.TRAJECTORY_IN_PROGRESS\n print(\"getupback\")\n\n elif robot.status == Robot.Status.FALLEN_FRONT:\n robot.terminate_walking_publisher.publish()\n robot.trajectory_publisher.publish(\"getupfront\")\n robot.trajectory_complete = False\n robot.status = Robot.Status.TRAJECTORY_IN_PROGRESS\n print(\"getupback\")\n\n elif robot.status == Robot.Status.READY:\n robot.set_navigation_position(goal_list[current_stage])\n robot.status = Robot.Status.WALKING\n current_stage = (current_stage + 1) % 4\n\n elif robot.status == Robot.Status.TRAJECTORY_IN_PROGRESS:\n if robot.trajectory_complete:\n robot.status = Robot.Status.READY\n else:\n pass\n\n if robot.status != robot.previous_status:\n print(robot.robot_name + \" status changes to \" + str(robot.status))\n robot.previous_status = robot.status\n\n","sub_path":"soccer_strategy/src/walking_demo.py","file_name":"walking_demo.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"196293042","text":"import unittest\n\n\nclass Solution(object):\n def __init__(self):\n self.combinations = []\n\n def combination_sum(self, k, n):\n def combination_helper(k, n, partial):\n if k == 0:\n if n == 0:\n partial.sort()\n if partial not in self.combinations:\n self.combinations.append(partial)\n else:\n remaining_set = set(range(1, 10)) - set(partial)\n for num in list(remaining_set):\n partial.append(num)\n combination_helper(k-1, n-num, partial[:])\n partial.pop()\n combination_helper(k, n, [])\n return self.combinations\n\n\nclass SolutionTestCase(unittest.TestCase):\n def test_example(self):\n solution = Solution().combination_sum(3, 9)\n self.assertEqual(len(solution), 3)\n self.assertIn([1, 2, 6], solution)\n self.assertIn([1, 3, 5], solution)\n self.assertIn([2, 3, 4], solution)\n\n def test_max(self):\n solution = Solution().combination_sum(9, 45)\n self.assertEqual(len(solution), 1)\n self.assertIn([1, 2, 3, 4, 5, 6, 7, 8, 9], solution)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"leetcode/216.combination_sum_iii.py","file_name":"216.combination_sum_iii.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"232873982","text":"# coding=utf8\n# __author__ = \"xinming_ye\"\n# __title__ = \"战斗牛测试demo\"\n# __desc__ = \"\"\"只是个demo\"\"\"\nfrom airtest.core.api import *\nfrom airtest.core.api import device as current_device\nfrom poco.drivers.android.uiautomation import AndroidUiautomationPoco\nimport random\nimport re\nfrom testflow.lib.myBase.smokeBase2 import SmokeTestCase\nfrom poco.exceptions import *\nfrom testflow.lib.utils.sznMethod import RoomNumber_click\nfrom poco.pocofw import Poco\nfrom poco.drivers.std import StdPoco\nfrom testflow.lib.utils.installation import install_android_app\n\n\nclass SmokeTest(SmokeTestCase):\n def __init__(self):\n super(SmokeTest, self).__init__()\n self.dev2 = None\n\n @classmethod\n def name(cls):\n return 'supeznSmoke'\n\n @classmethod\n def getNetInfo(cls):\n return {\n \"author\": 'xinming_ye',\n \"remark\": 'any data',\n 'any-keys': 'any-values',\n }\n\n def setUp(self):\n # self.package_name = 'supezn.u9game.com'\n # apk_path = self.R('res/app/gameclient-debug.apk')\n # if self.package_name not in current_device().list_app():\n # install_android_app(current_device().adb, apk_path)\n # wake()\n # start_app(self.package_name)\n # start_app(\"com.burakgon.dnschanger\")\n # self.poco_android(\"com.burakgon.dnschanger:id/dns1_edittext\").wait_for_appearance()\n # self.poco_android(\"com.burakgon.dnschanger:id/dns1_edittext\").click()\n # self.poco_android(\"com.burakgon.dnschanger:id/dns1_edittext\").set_text(\"59.110.152.15\")\n # self.poco_android(\"com.burakgon.dnschanger:id/dns2_edittext\").click()\n # self.poco_android(\"com.burakgon.dnschanger:id/dns2_edittext\").set_text(\"59.110.152.15\")\n # if self.poco_android(\"com.burakgon.dnschanger:id/start_stop_button\").get_text() != \"STOP\":\n # self.poco_android(\"com.burakgon.dnschanger:id/start_stop_button\").click()\n\n # start_app(self.package_name)\n set_current(0)\n login = Template(self.R('res/img/login.png'), threshold=0.9)\n self.assertTrue(exists(login), 'App started.')\n\n self.poco1(\"Btn_WxLogin\").click()\n try:\n self.poco_android(\"com.tencent.mm:id/bwn\").click()\n except:\n pass\n\n def runTest(self):\n # region大厅功能\n self.poco1(\"Btn_Statement0\").click()\n self.poco1(\"Btn_Statement\").click()\n self.poco1(\"Btn_Updata\").click()\n\n sleep(1)\n self.poco1(tag=391).click()\n\n self.poco1(\"Panel_HeadFrame\").click()\n self.poco1(\"Image_19\").click()\n\n self.poco1(\"Btn_Dial\").click([0.5, 0.5])\n self.poco1(tag=866).wait_for_appearance()\n Dial_Num = int(self.poco1(tag=866).get_text())\n self.poco1(\"Btn_Close\").click()\n\n card_before_invitation = int(self.poco1(\"Label_CardNumber\").get_text())\n\n self.poco1(\"Btn_Invitation_code\").click()\n # Poco.wait_for_all(self.poco, \"Btn_OK\", timeout=10)\n # wait(self.poco(tag=\"244\"))\n try:\n self.poco1(\"Btn_OK\").click()\n print(self.poco1(\"Label_Tips\").get_text())\n self.poco1(\"Btn_OK\").click()\n\n self.poco1(\"TextField_Code\").set_text(\"888888\")\n # Poco.wait_for_all(self.poco, \"Btn_OK\", timeout=10)\n # wait(self.poco(tag=\"244\"))\n self.poco1(\"Btn_OK\").click() # 第一个ok\n self.poco1(\"Btn_Cancel\").click() # 第二个面板的cancel\n self.poco1(\"Btn_OK\").click()\n sleep(1)\n self.poco1(tag=352).click() # 第二个面板的OK\n print(self.poco1(\"Label_Tips\").get_text())\n if self.poco1(\"Label_Tips\").get_text() == \"该邀请码错误,请重新输入\":\n self.poco1(\"Btn_Close\").click()\n self.poco1(\"Btn_Close\").click()\n card_after_invitation = int(self.poco1(\"Label_CardNumber\").get_text())\n if card_after_invitation != card_before_invitation + 8:\n print(\"Error:invitation reward\")\n except:\n pass\n # try:\n # self.assert_Equal(self, card_before_invitation, card_after_invitation, msg=\"error from invitation reward\")\n # print(\"invitationCode reward correct\")\n # except:\n # print(Exception.message)\n # else:\n # pass\n self.poco1(\"Btn_RealName\").click()\n self.poco1(\"Text_EnterName\").set_text(u\"马燕小\")\n self.poco1(\"Text_EnterID\").set_text(\"310123456789012345\")\n self.poco1(tag=49).click()\n\n self.poco1(\"Btn_RealName\").click()\n self.poco1(\"Btn_Close\").click()\n card_before_sign = int(self.poco1(\"Label_CardNumber\").get_text())\n Dial_Num = 0\n self.poco1(\"Btn_Sign\", tag=540).click()\n if self.poco1(\"lbSign\", tag=871).get_text() != \"今日已领\":\n # self.site_capture.snapshot('before_sign_scene')\n self.poco1(\"Btn_Sign\", tag=870).click()\n # self.site_capture.snapshot('after_sign_scene')\n card_after_sign = int(self.poco1(\"Label_CardNumber\").get_text())\n if (card_after_sign - card_before_sign) != 1:\n print(\"Error from sign_reward\")\n self.poco1(\"Btn_Sign\", tag=540).click()\n if self.poco1(\"lbSign\", tag=871).get_text() != \"今日已领\":\n print(\"Error from after_sign statement\")\n Dial_Num += Dial_Num\n # if self.poco(\"lbSign\", tag=871).get_text() == \"今日已领\":\n # self.site_capture.snapshot('Today has been signed')\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Share\").click()\n if self.poco1(\"Btn_ShareToCircle\", enabled=True).exists():\n self.poco1(\"Btn_ShareToCircle\").click()\n self.poco_android(\"com.tencent.mm:id/hg\").click()\n self.poco1(\"Btn_Close\").click()\n sleep(1)\n\n self.poco1(\"Panel_Room_Card\").click()\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Announce\").click()\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Record\").click()\n self.poco1(\"Btn_Close\").click()\n self.poco1(\"Btn_Close\").wait_for_disappearance()\n\n self.poco1(\"Btn_Rule\").click([0.5, 0.5])\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Service\").click([0.5, 0.5])\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Setting\").click([0.5, 0.5])\n self.poco1(\"Slider_MainMusic\").swipe('left')\n self.poco1(\"Slider_MainMusic\").swipe('right')\n self.poco1(\"Slider_MainEffect\").swipe('left')\n self.poco1(\"Slider_MainEffect\").swipe('right')\n self.poco1(\"Btn_Close\").click()\n # endregion\n # region dial\n self.poco1(\"Btn_Dial\").click([0.5, 0.5])\n i = 1\n if Dial_Num != int(self.poco1(tag=866).get_text()):\n print(\"Error:dial_num is incorrect\")\n Dial_Num = int(self.poco1(tag=866).get_text())\n if Dial_Num < 0:\n print(\"Error:dial_num is negative number\")\n while Dial_Num >= 0:\n card_before_dial = int(self.poco1(\"Label_CardNumber\").get_text())\n self.poco1(\"Btn_lottery\").click()\n try:\n while not self.poco1(tag=535).exists():\n sleep(0.1)\n print(self.poco1(tag=535).get_text())\n except PocoNoSuchNodeException:\n print(PocoNoSuchNodeException.message, 'Unable to catch the message')\n else:\n print [Exception.message, 'Other exception']\n sleep(1)\n card_after_dial = int(self.poco1(\"Label_CardNumber\").get_text())\n print('Loop:', i, 'Dial_Num: ', Dial_Num)\n i += 1\n print('card_change:', (card_after_dial - card_before_dial))\n Dial_Num -= 1\n self.poco1(\"Btn_Dial\").click()\n self.poco1(\"Btn_Close\").click()\n\n self.poco1(\"Btn_Mall\").click()\n self.poco1(\"Btn_Close\").click()\n # endregion\n # region 创建房间\n\n # region 牛元帅\n Card_current = int(self.poco1(\"Label_CardNumber\").get_text())\n self.poco1(\"Panel_CreateRoom\").click([0.5, 0.5])\n self.poco1(\"CB_Game3\", tag=7535).click()\n random.choice(self.poco1(\"Panel_PlayerNum12\").offspring(type=\"CheckBox\")).click()\n random.choice(self.poco1(\"Panel_Round\").offspring(type=\"CheckBox\")).click()\n self.poco1(\"Panel_Pay\").child(\"Check_2\").click()\n random.choice(self.poco1(\"Panel_Score\").offspring(type=\"CheckBox\")).click()\n random.choice(self.poco1(\"Panel_RateSel\").offspring(type=\"CheckBox\")).click()\n random.choice(self.poco1(\"Panel_RateTuizhu\").offspring(type=\"CheckBox\")).click()\n random.choice(self.poco1(\"Panel_laizi\").offspring(type=\"CheckBox\")).click()\n self.poco1(\"Panel_DoubleRate\").child(\"Button_DoubleRate\").click()\n random.choice(self.poco1(\"Panel_PopDoubleRate\").offspring(type=\"CheckBox\")).click()\n self.poco1(\"Panel_DoubleRate\").child(\"Button_DoubleRate\").click()\n random.choice(self.poco1(\"Panel_AutoStart\").offspring(type=\"CheckBox\")).click()\n for AdvanceOps in self.poco1(\"Panel_AdvanceOps\").offspring(type=\"CheckBox\"):\n if random.choice([\"0\", \"1\"]) == \"1\":\n AdvanceOps.click()\n self.poco1(\"Panel_Options\").child(\"Check_8\").click()\n snapshot(\"D:\\GitHub\\my-testflow\\pocounit-results\\screenShot\\SaveRules.jpg\", u\"保存规则\")\n Pay_Card = re.sub(\"\\D\", \"\", self.poco1(\"Panel_Pay\").child(\"Check_2\").child(\"Label_Desc\").get_text())\n self.poco1(\"Btn_Create\").click()\n\n sleep(1)\n\n self.poco1(\"Btn_setting\").click()\n self.poco1(\"Btn_RoomExit\").click()\n\n try:\n self.assertEqual((Card_current - int(Pay_Card)), int(self.poco1(\"Label_CardNumber\").get_text()), \"Payment right:1-1\")\n except:\n print [Exception.message, \"Payment wrong:1-1\"]\n print(\"card_before:\", Card_current, \"card_pay\", int(Pay_Card), \"card_current\", int(self.poco1(\"Label_CardNumber\").get_text()))\n\n self.poco1(\"Btn_MyRoom\").click()\n self.poco1(\"Btn_InvitePlayer\").click()\n self.poco_android(\"com.tencent.mm:id/fw\").child(\"android.widget.RelativeLayout\")[2].click()\n self.poco_android(\"com.tencent.mm:id/an3\").click()\n sleep(0.5)\n self.poco_android(\"com.tencent.mm:id/an2\").click()\n\n self.poco1(\"Panel_Template\").click()\n\n self.poco1(\"Btn_Info\").click()\n self.poco1(\"Btn_Close\").click()\n self.poco1(\"Btn_inviteFriend\").click()\n self.poco_android(\"com.tencent.mm:id/fw\").child(\"android.widget.RelativeLayout\")[2].click()\n self.poco_android(\"com.tencent.mm:id/an3\").click()\n sleep(0.5)\n self.poco_android(\"com.tencent.mm:id/an2\").click()\n\n self.poco1(\"Btn_setting\").click()\n self.poco1(\"Slider_RoomMusic\").drag_to(self.poco1(\"Slider_RoomMusic\").focus([0, 0.5]))\n self.poco1(\"Slider_RoomMusic\").drag_to(self.poco1(\"Slider_RoomMusic\").focus([1, 0.5]))\n self.poco1(\"Slider_RoomEffect\").drag_to(self.poco1(\"Slider_RoomMusic\").focus([0, 0.5]))\n self.poco1(\"Slider_RoomEffect\").drag_to(self.poco1(\"Slider_RoomMusic\").focus([1, 0.5]))\n if self.poco1(\"Btn_ShockOpen\").exists():\n self.poco1(\"Btn_ShockOpen\").click()\n if self.poco1(\"Btn_ShockClose\").exists():\n self.poco1(\"Btn_ShockClose\").click()\n sleep(0.5)\n self.poco1(\"Btn_ShockOpen\").click()\n\n for DesktopChoice in self.poco1(tag=1708).offspring(touchable=True):\n DesktopChoice.click()\n\n self.poco1(\"Btn_RoomDisband\").click()\n self.poco1(\"Btn_Ok\").click()\n # endregion\n # region 牛元帅交互\n # self.poco1(\"Btn_Close\").click() # demonstration only\n self.poco1(\"Panel_CreateRoom\").click([0.5, 0.5])\n save_rule = Template(self.R('D:\\GitHub\\my-testflow\\pocounit-results\\screenShot\\SaveRules.jpg'), threshold=0.95)\n self.assertTrue(exists(save_rule), 'rule saved')\n self.poco1(\"Btn_Create\").click()\n self.poco1(\"Btn_ready\").click()\n Room_number = self.poco1(\"Label_RoomNumber\").get_text()\n set_current(1)\n self.poco2(\"Panel_JoinRoom\").click([0.5, 0.5])\n RoomNumber_click(self.poco2, Room_number)\n self.poco2(\"Btn_ready\").click()\n\n self.poco1(\"Btn_Start\").click()\n\n # endregion\n # endregion\n\n def tearDown(self):\n self.site_capture.snapshot('TearDown from user ' + self.ID)\n stop_app(self.package_name)\n\n\nif __name__ == '__main__':\n import pocounit\n\n pocounit.main()\n","sub_path":"testflow/scripts/supezn2/smoke2.py","file_name":"smoke2.py","file_ext":"py","file_size_in_byte":12649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"547789365","text":"import yaml\n\n\nclass Compute:\n \"\"\"\n Represents a Compute resource\n \"\"\"\n\n def __init__(self, c_name, cores):\n self.name = c_name\n self.cores = cores\n self.free_cores = self.cores\n\n def __repr__(self):\n \"\"\"\n Pretty print Compute\n :return:\n \"\"\"\n return \"\" % (\n self.name, self.cores, self.free_cores)\n\n\nclass ComputeCreator:\n \"\"\"\n Compute Creator\n \"\"\"\n\n def __init__(self):\n self.computes = []\n\n def read_computes(self, computes_file):\n \"\"\"\n Reads yaml compute file and generates Compute objects\n :param computes_file: yaml compute file\n :return: list of Compute objects\n \"\"\"\n with open(computes_file, 'r') as c_file:\n try:\n for name, cores in yaml.load(c_file).items():\n compute = Compute(name, cores)\n self.computes.append(compute)\n except yaml.YAMLError as exc:\n raise exc\n return self.computes\n","sub_path":"src/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"347134097","text":"import json\nimport time\n\nfrom query_db import get_phase_time, query_data, query_data_job, query_sample_data, query_current_job\nfrom process_data import process_data, process_data_job\n\n\ndef demo(read_client: object, sys_measurements: list, job_measurements: list) -> None:\n \"\"\"\n Convertor demo, it only process 10 minutes of data\n \"\"\"\n start = 1571346551\n half_day = 12 * 60 * 60\n end = start + half_day\n\n error_count = 0\n\n st = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.localtime(start))\n et = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.localtime(end))\n\n process_dict = [\n \"CPU_Temperature\",\n \"CPU_Usage\",\n \"Fan_Speed\",\n \"Inlet_Temperature\",\n \"Job_Info\",\n \"Memory_Usage\",\n \"Node_Power_Usage\",\n \"cluster_unified_metrics\",\n \"node_job_info\",\n \"system_metrics\"\n ]\n\n # print(\"-------------------------------------------------------\")\n # print(f\"All measurements :{len(job_measurements) + len(sys_measurements)}\")\n # print(f\"Numerical measurements :{len(process_dict)}\")\n # print(f\"Jobs measurements :{len(job_measurements)}\")\n # print(f\"Other measurements :{len(sys_measurements) - len(process_dict)}\")\n # print(\"-------------------------------------------------------\")\n\n # for mea in sys_measurements:\n # if mea in process_dict:\n # json_data = query_data(mea, read_client, st, et)\n # if json_data:\n # print(f\"Converting {mea}...\")\n # print(\"---- Original data point ----\")\n # print(json.dumps(json_data[0], indent=4))\n\n # converted_data_point = process_data(json_data[0], mea, error_count)\n # print(\"---- Converted data point ----\")\n # print(json.dumps(converted_data_point, indent=4))\n # print(\"-------------------------------------------------------\")\n # print(error_count)\n # data_points.append(converted_data_point)\n # print(json.dumps(data_points, indent=4))\n\n # # Convert job metrics\n # job_measurements = [\"i764687\", \"j-775882\", \"qu_1082110A434\"]\n # # data_points = []\n # for mea in job_measurements:\n # print(f\"Converting {mea}...\")\n # json_data = query_data_job(mea, read_client)\n # if json_data:\n # print(\"---- Original data point ----\")\n # print(json.dumps(json_data, indent=4))\n\n # converted_data_point = process_data_job(json_data, mea)\n # print(\"---- Converted data point ----\")\n # print(json.dumps(converted_data_point, indent=4))\n # print(\"-------------------------------------------------------\")\n\n current_job_data = query_current_job(read_client)\n print(json.dumps(current_job_data, indent=4))\n return","sub_path":"tools/MBConvertor/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447473396","text":"from collections import namedtuple\nfrom typing import Optional, List, Tuple, Union, Type\n\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.db.models import signals\nfrom django.utils.timezone import now\nfrom requests import Response\nfrom requests.exceptions import ConnectionError\n\nfrom .utils import make_soup, get_from_url, run_threads\n\nif False: # pragma: nocover\n from ..generics.realms import RealmBase\n from ..generics.models import RealmBaseModel\n from ..models import PartnerLink, ModelWithPartnerLinks\n\n_PARTNERS_REGISTRY: Optional[dict] = None\n_CACHE_TIMEOUT: int = 28800 # 8 часов\n\n\nclass PartnerBase:\n \"\"\"Базовый класс для работы с партнёрскими сайтами.\"\"\"\n\n ident: str = None\n title: str = None\n link_mutator: str = None\n\n def __init__(self, partner_id: str):\n self.partner_id = partner_id\n\n def get_link_data(self, realm: 'RealmBase', link: 'PartnerLink') -> dict:\n \"\"\"Возвращает словарь с данными партнёрской ссылки.\n\n :param realm:\n :param link:\n\n \"\"\"\n link_url = link.url\n\n link_mutator = self.link_mutator.replace('{partner_id}', self.partner_id)\n\n if '?' in link_url and link_mutator.startswith('?'):\n link_mutator = link_mutator.replace('?', '&')\n\n url = f'{link_url}{link_mutator}'\n\n title = f'{realm.model.get_verbose_name()} на {self.title}'\n description = link.description\n\n if description:\n title = f'{title} — {description}'\n\n page_soup = self.get_page_soup(link_url)\n\n if not page_soup:\n return {}\n\n price = self.get_price(\n page_soup\n ).lower().strip(' .').replace('руб', 'руб.').replace('₽', 'руб.').strip()\n\n if price.isdigit():\n price += ' руб.'\n\n data = {\n 'icon_url': f'https://favicon.yandex.net/favicon/{self.title}',\n 'title': title,\n 'url': url,\n 'price': price,\n 'time': now()\n }\n return data\n\n @classmethod\n def get_page(cls, url: str) -> Response:\n return get_from_url(url, timeout=20)\n\n @classmethod\n def get_page_soup(cls, url: str) -> Optional[BeautifulSoup]:\n\n try:\n page = cls.get_page(url)\n\n except ConnectionError:\n return\n\n return make_soup(page.text)\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n return ''\n\n\nclass BooksRu(PartnerBase):\n \"\"\"Класс реализует работу по партнёрской программе сайта books.ru.\"\"\"\n\n ident: str = 'booksru'\n title: str = 'books.ru'\n link_mutator: str = '?partner={partner_id}'\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n\n price = ''\n\n if page_soup:\n matches = page_soup.select('h3.book-price')\n\n if matches:\n price = matches[0].text\n\n return price\n\n\nclass LitRes(PartnerBase):\n \"\"\"Класс реализует работу по партнёрской программе сайта litres.ru.\"\"\"\n\n ident: str = 'litres'\n title: str = 'litres.ru'\n link_mutator: str = '?lfrom={partner_id}'\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n\n price = ''\n\n if page_soup:\n matches = page_soup.select('.simple-price')\n\n if matches:\n price = matches[0].text\n\n return price\n\n\nclass Ozon(PartnerBase):\n \"\"\"Класс реализует работу по партнёрской программе сайта ozon.ru.\"\"\"\n\n ident: str = 'ozon'\n title: str = 'ozon.ru'\n link_mutator: str = '?partner={partner_id}'\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n\n price = ''\n\n if page_soup:\n matches = page_soup.findAll('span', attrs={'itemprop': 'price', 'class': 'hidden'})\n\n if matches:\n price = matches[0].text\n\n return price\n\n\nclass ReadRu(PartnerBase):\n \"\"\"Класс реализует работу по партнёрской программе сайта ozon.ru.\"\"\"\n\n ident: str = 'readru'\n title: str = 'read.ru'\n link_mutator: str = '?pp={partner_id}'\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n\n price = ''\n\n if page_soup:\n matches = page_soup.select('.read2__book_price__fullprice')\n\n if not matches:\n matches = page_soup.select('.book_price3__fullprice')\n\n if matches:\n price = matches[0].text\n if price:\n try:\n price = price.encode('latin1').decode('cp1251').strip().split(' ')[0]\n except UnicodeEncodeError:\n pass\n\n return price\n\n\nclass LabirintRu(PartnerBase):\n \"\"\"Класс реализует работу по партнёрской программе сайта labirint.ru.\"\"\"\n\n ident: str = 'labirint'\n title: str = 'labirint.ru'\n link_mutator: str = '?p={partner_id}'\n\n @classmethod\n def get_price(cls, page_soup: BeautifulSoup) -> str:\n\n price = ''\n\n if page_soup:\n matches = page_soup.select('.buying-price-val-number')\n\n if matches:\n price = matches[0].text\n\n return price\n\n\ndef get_cache_key(instance: 'RealmBaseModel') -> str:\n \"\"\"Возвращает ключ записи кэша для указанного экземпляра сущности.\n\n :param instance:\n\n \"\"\"\n return f'partner_links|{instance.__class__.__name__}|{instance.pk}'\n\n\ndef init_partners_module():\n \"\"\"Инициализирует объекты известных партнёров и заносит их в реестр.\"\"\"\n\n global _PARTNERS_REGISTRY\n\n if _PARTNERS_REGISTRY is not None:\n return\n\n _PARTNERS_REGISTRY = {}\n\n PARTNER_CLASSES = [BooksRu, LitRes, Ozon, ReadRu, LabirintRu]\n\n partners_settings = settings.PARTNER_IDS\n\n for partner_class in PARTNER_CLASSES:\n ident = partner_class.ident\n if ident in partners_settings:\n _PARTNERS_REGISTRY[ident] = partner_class(partners_settings[ident])\n\n from ..models import PartnerLink\n\n def partner_links_cache_invalidate(*args, **kwargs):\n \"\"\"Сбрасывает кеш партнёрских ссылок при изменении данных\n моделей ссылок или их удалении.\n\n \"\"\"\n cache_key = get_cache_key(kwargs.get('instance').linked_object)\n cache.delete(cache_key)\n\n signals.post_save.connect(partner_links_cache_invalidate, sender=PartnerLink, weak=False)\n signals.post_delete.connect(partner_links_cache_invalidate, sender=PartnerLink, weak=False)\n\n\ninit_partners_module()\n\n\ndef get_partners_choices() -> List[Tuple[str, str]]:\n \"\"\"Возвращает варианты выбора известных партнёров для раскрывающихся списков.\"\"\"\n\n choices = []\n\n for partner in _PARTNERS_REGISTRY.values():\n choices.append((partner.ident, partner.title))\n\n return choices\n\n\ndef get_partner_links(realm: Type['RealmBase'], item: Union['RealmBaseModel', 'ModelWithPartnerLinks']) -> dict:\n \"\"\"Возвращает словарь с данными по партнёрским ссылкам,\n готовый для передачи в шаблон.\n\n :param realm:\n :param item:\n\n \"\"\"\n cache_key = get_cache_key(item)\n links_data = cache.get(cache_key)\n\n Task = namedtuple('Task', ['link', 'realm', 'partner'])\n\n def contribute_info(task: Task):\n data = task.partner.get_link_data(task.realm, task.link)\n\n if data:\n links_data.append(data)\n\n if links_data is None:\n\n links_data = []\n tasks = []\n\n for link in item.partner_links.order_by('partner_alias', 'description').all():\n partner = _PARTNERS_REGISTRY.get(link.partner_alias)\n\n if partner:\n tasks.append(Task(\n link=link,\n realm=realm,\n partner=partner\n ))\n\n if tasks:\n run_threads(tasks, contribute_info)\n\n cache.set(cache_key, links_data, _CACHE_TIMEOUT)\n\n return {'links': links_data}\n","sub_path":"pythonz/apps/integration/partners.py","file_name":"partners.py","file_ext":"py","file_size_in_byte":8565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"251139075","text":"roles_os = {'linux':[\n \"admin\"\n ],'win':[\n \"xxx\"\n ]}\n\nnonsupport_mapping = {\n 'xx-xxxx':['3rd_party/','src/python_service/scanner_helper/'],\n 'xx-xxx':['src/test/','L10N/'],\n}\n\nnonsupport_filetype = {'.js','.config','.go','.properties','.html','.java'}\n","sub_path":"fortify_codescan/conf/reporole.py","file_name":"reporole.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"242857791","text":"\"\"\"\r\n\n\n[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-\ndimensional Turing machine invented in the late 1980s. The ant starts out on a\ngrid of black and white cells and follows a simple set of rules that has\ncomplex emergent behavior.\n\n![Langton's ant](https://edabit-\nchallenges.s3.amazonaws.com/LangtonsAntAnimated.gif)\n\nThe ant can travel in any of the four cardinal directions on each step. The\nant moves according to the following rules:\n\n * At a white square (1), turn 90° right, flip the color of the square, and move forward one unit.\n * At a black square (0), turn 90° left, flip the color of the square, and move forward one unit.\n * The grid has no limits and therefore if the ant moves outside the borders, the grid should be expanded with 0s, respectively maintaining the rectangle shape.\n\nCreate a function **Langton's Ant** with the following parameters:\n\n grid - a two-dimensional list of 1s and 0s\n # representing white and black cells respectively\n \n column - horizontal position of the ant\n \n row - ant's vertical position\n \n n - number of iterations\n \n direction - ant's current direction\n # 0 - north, 1 - east, 2 - south, 3 - west\n # default value will be 0\n\n... and returns the **state** of the grid after `n` iterations.\n\n### Examples\n\n langtons_ant([[1]], 0, 0, 1, 0) ➞ [[0, 0]]\n # Initially facing north (0), at the first iteration the ant turns\n # right because it stands on a white square, 1. After that, it flips\n # the square and moves forward.\n \n langtons_ant([[0]], 0, 0, 1, 0) ➞ [[0, 1]]\n \n langtons_ant([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 2, 2, 10, 1) ➞ [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 1]]\n\n### Notes\n\nN/A\n\n\"\"\"\r\n\ndef langtons_ant(grid, col, row, n, direction=0):\n for i in range(0,n):\n if grid[row][col] == 1:\n grid[row][col] = 0\n direction = (direction + 1) % 4\n else:\n grid[row][col] = 1\n direction = (direction - 1) % 4\n if direction == 0:\n if row == 0:\n grid.insert(0,len(grid[0])*[0])\n else:\n row -= 1\n elif direction == 1:\n if col == len(grid[0]) - 1:\n grid = list(map(lambda x: x + [0],grid))\n col += 1\n elif direction == 2:\n if row == len(grid)-1:\n grid.append(len(grid[0])*[0])\n row += 1\n elif col == 0:\n grid = list(map(lambda x: [0] + x,grid))\n else:\n col -= 1\n return grid\n\n","sub_path":"8jYLBswq9jnttZeox_6.py","file_name":"8jYLBswq9jnttZeox_6.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"271522202","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 11 13:03:23 2017\n\n@author: claire\n\"\"\"\n\n# set of functions\nimport mne\nfrom mne import io\n\n\ndef import_bdf(data_path, subject):\n # function to import bdf file and do basic preprocessing :\n# - chanloc and chan info\n# - ref to mastoids\n\n # import data\n raw = mne.io.read_raw_edf(data_path + subject + '_task.bdf', stim_channel=-1, misc=['EXG6', 'EXG7', 'EXG8', 'GSR1', 'GSR2', 'Erg1', 'Erg2', 'Resp', 'Plet', 'Temp'], preload=True)\n raw.rename_channels(mapping={'E1H1\\t//EXG1 HE ': 'EOG L', 'E2H2\\t//EXG2 HE ': 'EOG R', 'E3LE\\t//EXG3 LE ': 'EOG V L', 'E5M2\\t//EXG5 M2 ': 'M2', 'E4M1\\t//EXG4 M1 ': 'M1' })\n raw.set_channel_types(mapping={'EOG L': 'eog', 'EOG R': 'eog', 'EOG V L': 'eog'})\n \n raw, _ =mne.io.set_eeg_reference(raw, ref_channels=['M1', 'M2'])\n raw.info['bads'] = ['M1', 'M2']\n \n # get eletrodes loc\n montage= mne.channels.read_montage('standard_1020', path = '/home/claire/Appli/mne-python/mne/channels/data/montages/')\n raw.set_montage(montage)\n raw.interpolate_bads(reset_bads=False) # \n events = mne.find_events(raw, verbose=True)\n\n raw.pick_types(raw.info, eeg=True, eog=True, exclude='bads') \n\n return raw, events\n \n\n\n","sub_path":"Old/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"159536571","text":"import requests, hashlib, time, random, sys, OpenSSL\nfrom OpenSSL import crypto\nimport base64\nkey_file = open(\"private.pem\", \"r\")\nkey = key_file.read()\nkey_file.close()\n\npkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)\n\nchave = sys.argv[1]\nauth = hashlib.sha256(chave.encode('utf-8')).hexdigest()\n\nprint ('auth medidor: ' + auth)\n\nurl = 'https://sc-gir.rhcloud.com/modulo_entrada'\n\n\t\nwhile True:\n\tvalor = random.uniform(2,4)\n\tvalor_sign = OpenSSL.crypto.sign(pkey, valor, \"sha256\") \n\ttimestamp = time.time()\n\ttimestamp_sign = OpenSSL.crypto.sign(pkey, timestamp, \"sha256\") \n\t\n\t\n\tdata = {\n\t\t'valor': valor,\n\t\t'valor_sign': base64.b64encode(valor_sign),\n\t\t'timestamp': timestamp,\n\t\t'timestamp_sign': base64.b64encode(timestamp_sign),\n\t\t'auth': auth\n\t}\n\t\t\n\tr = requests.post(url, data)\n\ttime.sleep(1)\n\t\n\tprint (r.text)\n","sub_path":"medidor-new.py","file_name":"medidor-new.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"133084788","text":"import sqlite3\ndb=sqlite3.connect(\"kutuphane.db\")\nimlec=db.cursor()\n\nmenu=\"\"\"\n [1] Kitap Ara\n [2] Yazar Ara\n\"\"\"\n\nprint(menu)\nislem=input(\"İşleminiz: \")\nif islem==\"1\":\n isim=input(\"Kitap Adı:\")\n sorgu=(\"select * from kitaplar where kitap='{}'\".format(isim))\n imlec.execute(sorgu)\n veriler=imlec.fetchall()\n for veri in veriler:\n print(veri)\nelif islem==\"2\":\n yazar=input(\"Yazar Adı Giriniz: \")\n sorgu=(\"select * from kitaplar where yazar='{}'\".format(yazar))\n imlec.execute(sorgu)\n veriler=imlec.fetchall()\n for veri in veriler:\n print(veri)\nelse:\n print(\"Yanlış Seçim!\")\n\ndb.close()","sub_path":"kutuphane_uygulaması.py","file_name":"kutuphane_uygulaması.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"534543132","text":"import unittest\r\nimport re\r\n\r\nfrom flaskr import util\r\n\r\n\r\nclass ClassNameTest(unittest.TestCase):\r\n def test_all_names(self):\r\n data = util.load_csv()\r\n names = util.get_raw_classlist(data)\r\n for name in names:\r\n # ignore the numbers\r\n if re.match(\"\\\\d+\", str(name)):\r\n continue\r\n self.assertNotEqual(util.get_name(name), \"Error!\", f'|{name} failed!|')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"backend/tests/ClassNameTest.py","file_name":"ClassNameTest.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"150137041","text":"import mysql.connector\nfrom mysql.connector import Error\nfrom mysql.connector import errorcode\nfrom random import seed\n#from random import random\nfrom random import randint\nimport random\nimport string\nimport serial\n\nser=serial.Serial(\"/dev/ttyUSB0\",9600)\nser.baudrate=9600\n\n#readSerial = ser.readline()\n#print(readSerial)\n\ndef randomString(stringLenght=8):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLenght))\n\ndef InserirValoresNaTabela(inteiro, macaco):\n\n try:\n conn = mysql.connector.connect( \n host=\"localhost\",\n user=\"rushadores\",\n password=\"rushadores@123\",\n database=\"rushadores\"\n )\n cursor = conn.cursor()\n mySql_query = \"INSERT INTO python_teste (inteiro, macaco) VALUES (%s, %s)\"\n record = (inteiro, macaco)\n #cursor = conn.cursor()\n cursor.execute(mySql_query, record)\n conn.commit() \n #print(cursor.rowcount, \"Inserido com sucesso\")\n #cursor.close()\n\n except mysql.connector.Error as error:\n print(\"Erro {}\".format(error))\n \n finally:\n if(conn.is_connected()):\n conn.close()\n print(\"Conexao finalizada\")\n\n#InserirValoresNaTabela(randomString(), randomString())\nwhile 1:\n readSerial = ser.readline()\n print(\"Inserindo valores:\",readSerial,readSerial)\n InserirValoresNaTabela(readSerial, readSerial)\n#mycursor = mydb.cursor()\n#sql = \"INSERT INTO python_teste (inteiro) VALUES (1)\"\n#mycursor.execute(sql)\n#mydb.commit\n\n#print(mycursor.rowcount, \"rushadores\")\n","sub_path":"LinkaTech-Python/testemysql.py","file_name":"testemysql.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"170877367","text":"from django.shortcuts import render\nfrom user.models import UserSensorDetail\nfrom sensor_owner.models import SensorDetail\nfrom django.core.paginator import Paginator\nfrom django.core.paginator import EmptyPage\nfrom django.core.paginator import PageNotAnInteger\n\n\ndef is_sensor_present(request, sensor_data):\n if UserSensorDetail.objects.filter(user_name=request.user, sensor_id=sensor_data).exists():\n return True\n else:\n return False\n\n\ndef manage_sensors(request):\n user_sensor_data = UserSensorDetail.objects.filter(user_name=request.user)\n available_sensor_data = SensorDetail.objects.all()\n\n # Show 5 user sensors per page\n paginator = Paginator(user_sensor_data, 5)\n user_sensor_page = request.GET.get('user-sensor-page')\n try:\n user_sensors = paginator.page(user_sensor_page)\n except PageNotAnInteger:\n # If sensor_page is not an integer, deliver first sensor_page.\n user_sensors = paginator.page(1)\n except EmptyPage:\n # If sensor_page is out of range (e.g. 9999), deliver last sensor_page of results.\n user_sensors = paginator.page(paginator.num_pages)\n\n # Show 5 available_sensors per sensor_page\n paginator = Paginator(available_sensor_data, 5)\n sensor_page = request.GET.get('sensor-page')\n try:\n available_sensors = paginator.page(sensor_page)\n except PageNotAnInteger:\n available_sensors = paginator.page(1)\n except EmptyPage:\n available_sensors = paginator.page(paginator.num_pages)\n return render(request, 'manage_sensors.html', {'user_sensors': user_sensors,\n 'available_sensors': available_sensors,\n 'user_sensor_page': \"user-sensor-page\",\n 'sensor_page':\"sensor-page\"})\n\n\ndef add_sensor(request, pk):\n available_sensor_data = SensorDetail.objects.all()\n sensor_data = available_sensor_data.get(id=pk)\n current_user = request.user\n error_message = ''\n success_message = ''\n if is_sensor_present(request, sensor_data):\n error_message = 'Sensor already subscribed'\n else:\n new_sensor = UserSensorDetail()\n new_sensor.user_name = current_user\n new_sensor.sensor_id = sensor_data\n new_sensor.save()\n success_message = 'Sensor with ID '+ str(sensor_data.sensor_id) + ' subscribed'\n\n user_sensor_data = UserSensorDetail.objects.filter(user_name=request.user)\n return render(request, 'manage_sensors.html', {'user_sensors': user_sensor_data, 'available_sensors': available_sensor_data,\n 'error_message': 'Sensor already subscribed', 'error_message': error_message,\n 'success_message': success_message})\n\n\ndef delete_sensor(request, pk):\n sensor = UserSensorDetail.objects.get(id=pk)\n sensor.delete()\n\n user_sensor_data = UserSensorDetail.objects.filter(user_name=request.user)\n available_sensor_data = SensorDetail.objects.all()\n success_message = 'Sensor deleted'\n\n return render(request, 'manage_sensors.html', {'user_sensors': user_sensor_data, 'available_sensors': available_sensor_data,\n 'success_message': success_message})\n\n\ndef sensor_data_table(request):\n all_available_sensors = SensorDetail.objects.all()\n paginator = Paginator(all_available_sensors, 2) # Show 25 available_sensors per page\n\n page = request.GET.get('page-available')\n try:\n available_sensors = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n available_sensors = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n available_sensors = paginator.page(paginator.num_pages)\n\n return render(request, 'manage_sensors.html', {'available_sensors': available_sensors})\n\n","sub_path":"manage_sensors/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"621481716","text":"import sys,time,os\nfrom CSM37F58_APP_ui import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom serial.tools.list_ports import *\nfrom picture_qrc import *\nimport datetime\nfrom IIC_CH341 import *\nfrom PyQt5.QtCore import QTimer\nimport numpy as np\n\n\nclass MyApp(QtWidgets.QMainWindow, Ui_MainWindow):\n CMD_CSM37F58_IAP_CHECKSUM_ADDRESS = 0xEC00\n CMD_CSM37F58_IAP_GET_VERSION_ADDRESS = 0xFFFF\n\n def __init__(self):\n super(MyApp, self).__init__()\n QtWidgets.QMainWindow.__init__(self)\n self.setupUi(self)\n Ui_MainWindow.__init__(self)\n # logo\n self.setWindowIcon(QIcon(\":picture/img/110.png\"))\n # 默认时间戳\n self.time_stamp = datetime.datetime.now().strftime('%Y-%m-%d')\n\n # #初始化显示大小\n self.init_default_display()\n self.init_watch_table_all()\n self.init_read_timer()\n\n ##\n # #初始化信号槽\n self.btn_update_all.clicked.connect(self.update_watch_table_display)\n self.btn_cmd_1.clicked.connect(self.on_click_btn_cmd_1)\n self.btn_cmd_2.clicked.connect(self.on_click_btn_cmd_2)\n self.btn_cmd_3.clicked.connect(self.on_click_btn_cmd_3)\n self.btn_cmd_4.clicked.connect(self.on_click_btn_cmd_4)\n self.btn_cmd_5.clicked.connect(self.on_click_btn_cmd_5)\n self.btn_cmd_6.clicked.connect(self.on_click_btn_cmd_6)\n self.btn_cmd_7.clicked.connect(self.on_click_btn_cmd_7)\n self.btn_cmd_8.clicked.connect(self.on_click_btn_cmd_8)\n self.btn_cmd_9.clicked.connect(self.on_click_btn_cmd_9)\n self.btn_cmd_query.clicked.connect(self.on_click_btn_cmd_query)\n self.btn_cmd_write.clicked.connect(self.on_click_btn_cmd_write)\n self.btn_cmd_read.clicked.connect(self.on_click_btn_cmd_read)\n self.btn_cmd_reset.clicked.connect(self.on_clicked_btn_cmd_reset)\n self.btn_query_state.clicked.connect(self.on_clicked_btn_query_state)\n # IAP\n self.btn_iap_loadfile.clicked.connect(self.on_clicked_btn_iap_loadfile)\n self.btn_iap_start.clicked.connect(self.on_clicked_btn_iap_start)\n self.btn_iap_erase.clicked.connect(self.on_clicked_btn_iap_erase)\n self.btn_iap_get_version.clicked.connect(self.on_clicked_btn_iap_get_version)\n self.btn_iap_read_flash.clicked.connect(self.on_clicked_btn_iap_read_flash)\n #line\n self.line_body_height.textChanged.connect(self.on_changed_line_body_data)\n self.line_body_weight.textChanged.connect(self.on_changed_line_body_data)\n self.line_body_years_old.textChanged.connect(self.on_changed_line_body_data)\n self.line_body_gender.textChanged.connect(self.on_changed_line_body_data)\n self.line_body_mode.textChanged.connect(self.on_changed_line_body_data)\n\n self.btn_read_timer.clicked.connect(self.on_clicked_btn_read_timer)\n #\n self.read_timer = QTimer()\n self.read_timer.timeout.connect(self.read_timer_event)\n # self.read_timer.start(int(self.line_read_time.text()))\n\n def on_clicked_btn_read_timer(self):\n print(\"click read_timer\")\n if(self.btn_read_timer.text()==\"结束\"):\n self.btn_read_timer.setText(\"开始\")\n self.timer_event_enable = False\n # print(\"stop\")\n self.read_timer.stop()\n else:\n #print(\"start\")\n self.btn_read_timer.setText(\"结束\")\n self.timer_event_enable = True\n # self.read_timer.timeout.connect(self.read_timer_event)\n self.read_timer.start(int(self.line_read_time.text()))\n\n def read_timer_event(self):\n print(\"timer_event:\",datetime.datetime.now().strftime('%Y-%m-%d:%H:%M:%S'))\n if self.timer_event_enable == True:\n self.i2c_read_bytes()\n\n def read_save_file(self,s):\n with open(\"./record.csv\",\"a+\") as f:\n f.write(s)\n\n def i2c_read_bytes(self):\n try:\n protocol = CH341AIIC()\n save_mode ='big'\n if self.comboBox_read_timer.currentText() == \"小端模式\":\n save_mode = 'little'\n\n address_read = int(self.line_timer_read_addr.text(),16)\n length = int(self.line_timer_read_byte_len.text())\n print(\"read:\", hex(address_read))\n result = False\n read = bytearray()\n if length == 1:\n result, read = protocol.read_byte(address_read)\n else:\n result,read = protocol.read_bytes(address_read,length)\n # print(\"type:\",type(read)) #bytes\n\n print(str(result),read.hex())\n\n if result:\n # QMessageBox.information(self, \"提示\", \"读取成功\")\n value = int.from_bytes(read,byteorder= save_mode)\n self.plainTextEdit_read_timer.appendPlainText(\"[\" + datetime.datetime.now().strftime('%H:%M:%S') + \"]: 0x\" + read.hex()+\",\"+str(value))\n self.read_save_file(str(value)+'\\n')\n print(str(value))\n else:\n QMessageBox.information(self, \"错误\", \"读取失败,请检查硬件\")\n\n except Exception as e:\n print(str(e))\n self.timer_event_enable =False\n QMessageBox.information(self, \"错误\", \"读取失败,请检查硬件\" + str(e))\n\n def init_read_timer(self):\n self.line_timer_read_addr.setText(\"0x11AC\")\n self.line_timer_read_byte_len.setText(\"1\")\n self.comboBox_read_timer.addItems([\"大端模式\",\"小端模式\"])\n f = open(\"./record.csv\", \"a+\")\n f.close()\n\n def on_clicked_btn_iap_read_flash(self):\n try:\n protocol = CH341AIIC()\n self.progress_bar = QProgressDialog()\n self.progress_bar.setWindowTitle(\"读取Flash中....\")\n self.progress_bar.setWindowIcon(QIcon(\":picture/img/110.png\"))\n self.progress_bar.show()\n self.textBrowser_iap_read.clear()\n self.refresh_app()\n print(\"read_flash:\"+str(self.frame_cnt+2))\n self.textBrowser_iap_read.append(\"共加载%s包,加1包校验\"%(self.frame_cnt+2))\n for i in range(self.frame_cnt+1):\n result,ret = protocol.read_bytes(i*512,512)\n print(\"正在读取第%s包\"%(i+1))\n if not result:\n self.progress_bar.close()\n QMessageBox.information(self, \"提示\", \"没有ACK信号,请检查模块\")\n break\n self.textBrowser_iap_read.append(\"第%s包(512):\"%(i+1))\n self.progress_bar.setValue((i / (self.frame_cnt + 2) * 100))\n self.textBrowser_iap_read.append(ret.hex())\n self.refresh_app()\n # 读校验区\n time.sleep(0.1)\n result, ret = protocol.read_bytes(self.CMD_CSM37F58_IAP_CHECKSUM_ADDRESS, 512)\n self.textBrowser_iap_read.append(\"第%s包(校验码):\" % (self.frame_cnt+2))\n self.textBrowser_iap_read.append(ret.hex())\n self.progress_bar.setValue(100)\n except Exception as e:\n print(\"on_clicked_btn_iap_read_flash\",str(e))\n QMessageBox.information(self, \"提示\", \"初始化CS341失败,请检查硬件\")\n\n def on_clicked_btn_iap_get_version(self):\n print(\"获取版本\")\n try:\n protocol = CH341AIIC()\n time.sleep(0.01)\n result,version = protocol.read_bytes(self.CMD_CSM37F58_IAP_GET_VERSION_ADDRESS,4)\n if result:\n print(bytes(version).hex())\n QMessageBox.information(self, \"提示\",\"得到版本号: %s\"%((bytes(version)).hex()))\n else:\n QMessageBox.information(self, \"提示\", \"发送命令失败\")\n except Exception as e:\n QMessageBox.information(self, \"提示\", \"初始化CS341失败,请检查硬件\")\n\n def on_clicked_btn_iap_erase(self):\n\n self.CSM37F58_IAP_CMD = [0xA0, 0x00, 0x00, 0xAA, 0x55, 0xA5, 0x5A]\n try:\n protocol = CH341AIIC()\n protocol.reset_io_D0(0.005)\n time.sleep(0.01)\n result = protocol.write_bytes(self.CSM37F58_IAP_CMD)\n if result:\n self.btn_iap_start.setEnabled(True)\n QMessageBox.information(self, \"提示\",\"命令发送成功\")\n else:\n QMessageBox.information(self, \"提示\", \"发送命令失败\")\n except Exception as e:\n QMessageBox.information(self, \"提示\", \"初始化CS341失败,请检查硬件\")\n def on_clicked_btn_iap_start(self):\n\n print(\"clicked iap start\")\n try:\n file = open(self.bin_path,\"rb\")\n bin_data = file.read()\n file.close()\n print(len(bin_data),int(len(bin_data)/512))\n self.iic_send_bin_file(bin_data)\n self.btn_iap_start.setEnabled(False)\n except Exception as e:\n print(str(e))\n QMessageBox.information(self, \"提示\", \"请先选择Bin文件!\")\n\n def iic_send_bin_file(self,bin_data):\n self.progress_bar = QProgressDialog()\n print(\"正在准备发送...\")\n try:\n protocol = CH341AIIC()\n self.frame_cnt = int(len(bin_data) / 512)\n self.progress_bar.setWindowTitle(\"在线升级中(IAP)....\")\n self.progress_bar.setWindowIcon(QIcon(\":picture/img/110.png\"))\n self.progress_bar.show()\n self.refresh_app()\n for i in range(self.frame_cnt):\n data_512bytes = bin_data[i*512:i*512+512]\n result = protocol.write_iap_bytes(i*512,bytearray(data_512bytes))\n self.progress_bar.setValue((i/(self.frame_cnt+1)*100))\n if not result:\n self.progress_bar.close()\n QMessageBox.information(self, \"提示\", \"发送失败,请检查硬件\")\n return\n time.sleep(0.01)\n # print(\"升级中...\"+str(i))\n # 发送最后一帧,可能不满512bytes,补足0xff\n last_frame = bin_data[(self.frame_cnt)*512:]\n print(\"last_frame:\"+str(len(last_frame))+\":\"+(last_frame.hex()))\n last = bytearray(512)\n for i in range(512):\n last[i] = 0xff\n for i in range(len(last_frame)):\n last[i] = last_frame[i]\n protocol.write_iap_bytes(self.frame_cnt*512,last)\n print((\"发送last: \"+bytes(last).hex()))\n # send checksum\n protocol.write_iap_bytes(self.CMD_CSM37F58_IAP_CHECKSUM_ADDRESS,self.iap_checksum)\n self.progress_bar.setValue(100)\n print(\"升级完成\")\n except Exception as e:\n print(str(e))\n QMessageBox.information(self, \"提示\", \"发送失败,请检查硬件\")\n\n def on_clicked_btn_iap_loadfile(self):\n print(\"load file clicked\")\n try:\n self.bin_path, describe = QFileDialog.getOpenFileName(self, 'Open file', '.', \"txt files (*.bin)\")\n print(self.bin_path)\n\n file = open(self.bin_path, \"rb\");bin_data = file.read();file.close()\n # get checksum\n self.frame_cnt = int(len(bin_data)/512)\n # load\n self.textBrowser_iap.append(\"共加载到%sBytes,将发送%s包(加1包校验)\"%(len(bin_data),int(len(bin_data)/512)+2))\n for i in range(self.frame_cnt):\n data_512bytes = bin_data[512*i:512*i + 512]\n self.textBrowser_iap.append(\"第%s包(512):\"%(i+1))\n self.textBrowser_iap.append(data_512bytes.hex())\n self.refresh_app()\n # load_end\n self.iap_checksum = bytearray(512)\n for i in range(512):\n self.iap_checksum[i] = 0xff\n for i in range(self.frame_cnt):\n data_512bytes = bin_data[512*i:i*512+512]\n checksum = 0x00\n for j in range(512):\n checksum += data_512bytes[j]\n self.iap_checksum[i+5] = checksum&0xff\n print(hex(checksum&0xff))\n # 最后一帧处理\n last_frame = bin_data[(self.frame_cnt)*512:]\n last = bytearray(512)\n for i in range(512):\n last[i] = 0xff\n for i in range(len(last_frame)):\n last[i] = last_frame[i]\n checksum = 0x00\n print(\"last_len:\",len(last))\n for i in range(512):\n checksum += last[i]\n # last\n #\n self.iap_checksum[5+self.frame_cnt] = checksum&0xff\n self.iap_checksum[4] = self.frame_cnt+1\n self.textBrowser_iap.append(\"第%s包(512):\" % (self.frame_cnt + 1))\n self.textBrowser_iap.append(bytes(last).hex())\n self.refresh_app()\n #main_checksum\n version = 0x00\n for i in range(self.frame_cnt+1):\n version +=self.iap_checksum[5+i]\n print(\"main_CHECKSUM:\",version)\n version = version&0xffff\n main_version = (version&0xff00)>>8\n other_version = (version&0xff)\n self.iap_checksum[0] = main_version\n self.iap_checksum[1] = other_version\n self.iap_checksum[2] = (~main_version)&0xff\n self.iap_checksum[3] = (~other_version)&0xff\n checksum =0x00\n self.iap_checksum[511]=0x00\n for i in range(512):\n checksum +=self.iap_checksum[i]\n self.iap_checksum[511] = checksum&0xff\n\n self.textBrowser_iap.append(\"第%s包(校验码):\" % (self.frame_cnt + 2))\n self.textBrowser_iap.append(bytes(self.iap_checksum).hex())\n print(\"checksum:\"+bytes(self.iap_checksum).hex())\n self.btn_iap_loadfile.setText(\"已选择: \"+self.bin_path)\n self.btn_iap_read_flash.setEnabled(True)\n except Exception as e:\n print(str(e))\n\n def on_clicked_btn_query_state(self):\n print(\"查询状态...\")\n try:\n protocol = CH341AIIC()\n if not protocol.get_input_D7():\n QMessageBox.information(self,\"提示\",\"检测到低电平\")\n else:\n QMessageBox.information(self, \"提示\", \"检测到高电平\")\n except Exception as e:\n QMessageBox.information(self,\"提示\",\"失败,请检查硬件\")\n def on_clicked_btn_cmd_reset(self):\n try:\n protocol = CH341AIIC()\n protocol.reset_io_D0(0.005)\n print(\"event:按键复位\")\n QMessageBox.information(self,\"提示\",\"发送成功\")\n except Exception as e:\n QMessageBox.information(self,\"提示\",\"失败,请检查硬件\")\n def on_changed_line_body_data(self):\n try:\n body_list = [0xA0,0x10,0x58,0x02,0xC1,0xAA,0x9E,0x00]\n body_height = int(self.line_body_height.text())\n body_weight = int(float(self.line_body_weight.text())*10)\n body_years_old = int(self.line_body_years_old.text())\n body_gender = self.line_body_gender.text() == \"男\"\n body_mode = 0\n body_list[3] = body_weight>>8\n body_list[4] = body_weight&0xff\n body_list[5] = body_height\n body_list[6] = body_gender*0x80 + body_years_old\n str_dis = ('0x'+' 0x'.join('{:02x}'.format(x) for x in body_list))\n print(str_dis)\n self.line_cmd_2.setText(str_dis)\n print(str(body_height),str(body_weight),str(body_years_old),str(body_gender),str(body_mode))\n except Exception as e:\n print(str(e))\n print(\"editing...\")\n\n def on_click_btn_cmd_1(self):\n\n self.iic_send_bytes(self.line_cmd_1.text(),True)\n\n def on_click_btn_cmd_2(self):\n hex_str = self.line_cmd_2.text()\n cmd_hex = hex_str.replace(\"0x\",\"\")\n cmd_bytes = bytes.fromhex(cmd_hex)\n cmd = [cmd_bytes[0],cmd_bytes[1],cmd_bytes[2],cmd_bytes[3]]\n self.iic_send_bytes(bytes(cmd).hex())\n cmd[2] = cmd_bytes[2]+1\n cmd[3] = cmd_bytes[4]\n self.iic_send_bytes(bytes(cmd).hex())\n cmd[2] = cmd_bytes[2]+2\n cmd[3] = cmd_bytes[5]\n self.iic_send_bytes(bytes(cmd).hex())\n cmd[2] = cmd_bytes[2]+3\n cmd[3] = cmd_bytes[6]\n self.iic_send_bytes(bytes(cmd).hex())\n cmd[2] = cmd_bytes[2]+4\n cmd[3] = cmd_bytes[7]\n self.iic_send_bytes(bytes(cmd).hex(),True)\n\n def on_click_btn_cmd_3(self):\n self.btn_cmd_3.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_3.text(),True)\n self.btn_cmd_3.setEnabled(True)\n\n def on_click_btn_cmd_4(self):\n self.btn_cmd_4.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_4.text(),True)\n self.btn_cmd_4.setEnabled(True)\n\n def on_click_btn_cmd_5(self):\n self.btn_cmd_5.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_5.text(),True)\n self.btn_cmd_5.setEnabled(True)\n\n def on_click_btn_cmd_6(self):\n self.btn_cmd_6.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_6.text(),True)\n self.btn_cmd_6.setEnabled(True)\n\n def on_click_btn_cmd_7(self):\n self.btn_cmd_7.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_7.text(),True)\n self.btn_cmd_7.setEnabled(True)\n def on_click_btn_cmd_8(self):\n self.btn_cmd_8.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_8.text(),True)\n self.btn_cmd_8.setEnabled(True)\n def on_click_btn_cmd_9(self):\n self.btn_cmd_9.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_9.text(),True)\n self.btn_cmd_9.setEnabled(True)\n def on_click_btn_cmd_query(self):\n self.btn_cmd_query.setEnabled(False)\n self.iic_read_byte(self.line_cmd_query.text(), True, self.line_cmd_query_dis)\n self.btn_cmd_query.setEnabled(True)\n\n def on_click_btn_cmd_write(self):\n self.btn_cmd_write.setEnabled(False)\n self.iic_send_bytes(self.line_cmd_write.text(),True)\n self.btn_cmd_write.setEnabled(True)\n\n def on_click_btn_cmd_read(self):\n self.btn_cmd_read.setEnabled(False)\n self.iic_read_byte(self.line_cmd_read.text(),True,self.line_cmd_read_dis)\n self.btn_cmd_read.setEnabled(True)\n\n def iic_read_byte(self,hex_str,dis_success,dis_line):\n try:\n cmd_hex = hex_str.replace(\"0x\", \"\")\n cmd_bytes = bytes.fromhex(cmd_hex)\n print(hex_str)\n protocol = CH341AIIC()\n print(hex(cmd_bytes[1]),hex(cmd_bytes[2]))\n address_read = (cmd_bytes[1]*256+cmd_bytes[2])\n print(\"read:\", hex(address_read))\n result,read = protocol.read_byte(address_read)\n dis_line.setText(\"读取到数据:\"+hex(read[0]))\n if dis_success & result:\n QMessageBox.information(self, \"提示\", \"读取成功\")\n elif dis_success:\n QMessageBox.information(self, \"错误\", \"读取失败,请检查硬件\")\n except Exception as e:\n print(str(e))\n QMessageBox.information(self, \"错误\", \"读取失败,请检查硬件\" + str(e))\n\n def refresh_app(self):\n\n qApp.processEvents()\n\n def iic_send_bytes(self,hex_str, dis_success = False):\n\n try:\n cmd_hex = hex_str.replace(\"0x\",\"\")\n cmd_bytes = bytes.fromhex(cmd_hex)\n\n protocol = CH341AIIC()\n protocol.set_clk(protocol.IIC_CLK_100kHz)\n result = protocol.write_bytes(cmd_bytes)\n print(str(cmd_bytes.hex()))\n if dis_success&result:\n QMessageBox.information(self,\"提示\",\"发送成功\")\n elif dis_success:\n QMessageBox.information(self, \"错误\", \"发送失败,请检查硬件\" )\n except Exception as e:\n print(str(e))\n QMessageBox.information(self,\"错误\",\"发送失败,请检查硬件\"+str(e))\n\n\n\n def init_default_display(self):\n # size\n self.__desktop = QApplication.desktop()\n qRect = self.__desktop.screenGeometry() # 设备屏幕尺寸\n self.resize(qRect.width() * 45/ 100, qRect.height() * 90 / 100)\n self.move(qRect.width() / 3, qRect.height() / 30)\n\n\n def init_watch_table_all(self):\n\n\n self.watch_modle_dev_set = QStandardItemModel(64, 3)\n self.watch_table_dev_set.setModel(self.watch_modle_dev_set)\n\n\n self.watch_modle_dev_info = QStandardItemModel(24, 3)\n self.watch_table_dev_info.setModel(self.watch_modle_dev_info)\n\n self.watch_modle_usr_info = QStandardItemModel(128, 3)\n self.watch_table_usr_info.setModel(self.watch_modle_usr_info)\n\n self.watch_modle_usr_bia = QStandardItemModel(128, 3)\n self.watch_table_usr_bia.setModel(self.watch_modle_usr_bia)\n\n # page2\n self.watch_modle_analy_result = QStandardItemModel(128, 3)\n self.watch_table_analy_result.setModel(self.watch_modle_analy_result)\n\n self.watch_modle_tst_middle = QStandardItemModel(128, 3)\n self.watch_table_tst_middle.setModel(self.watch_modle_tst_middle)\n\n self.watch_modle_com_log = QStandardItemModel(24, 3)\n self.watch_table_com_log.setModel(self.watch_modle_com_log)\n\n self.watch_modle_res_real = QStandardItemModel(128, 3)\n self.watch_table_res_real.setModel(self.watch_modle_res_real)\n\n\n\n def update_watch_table_display(self):\n\n # 查询数据库数据\n # self.watch_modle.setItem(0,0,QStandardItem(\"示例\"))\n self.progress_bar = QProgressDialog()\n\n try:\n protocol = CH341AIIC()\n protocol.set_clk(protocol.IIC_CLK_100kHz)\n # print(\"逐个读地址:\", hex(address_read))\n self.progress_bar.setWindowTitle(\"更新RAM中....\")\n self.progress_bar_current = 0\n self.progress_bar_total = (64 + 24 + 128 + 128 + 128 + 128 + 128 + 24)\n self.progress_bar.setWindowIcon(QIcon(\":picture/img/110.png\"))\n self.progress_bar.show()\n\n self.update_table(protocol, start_addr=0x1000, read_length=64, watch_modle=self.watch_modle_dev_set)\n\n self.update_table(protocol, start_addr=0x1040, read_length=24, watch_modle=self.watch_modle_dev_info)\n\n self.update_table(protocol, start_addr=0x1058, read_length=128, watch_modle=self.watch_modle_usr_info)\n\n self.update_table(protocol, start_addr=0x10d8, read_length=128, watch_modle=self.watch_modle_usr_bia)\n\n # page 2\n self.update_table(protocol, start_addr=0x1158, read_length=128, watch_modle=self.watch_modle_analy_result)\n\n self.update_table(protocol, start_addr=0x11d8, read_length=128, watch_modle=self.watch_modle_tst_middle)\n\n self.update_table(protocol, start_addr=0x1258, read_length=24, watch_modle=self.watch_modle_com_log)\n\n self.update_table(protocol, start_addr=0x1270, read_length=128, watch_modle=self.watch_modle_res_real)\n except Exception as e:\n QMessageBox.information(self,\"错误\",str(e))\n\n\n\n\n\n def update_table(self,protocol, start_addr,read_length,watch_modle):\n for i in range(read_length):\n ret = protocol.read_byte(start_addr + i)\n if ret[0] == True:\n for x in ret[1]:\n watch_modle.setItem(i, 0, QStandardItem(\"%s + \"%(hex(start_addr))+str(hex(i)+\"=\"+hex(start_addr+i))))\n watch_modle.setItem(i, 1, QStandardItem(str(hex(x))))\n self.progress_bar_current = self.progress_bar_current+1\n self.progress_bar.setValue(self.progress_bar_current*100/self.progress_bar_total)\n QtCore.QCoreApplication.processEvents()\n else:\n print(\"读取失败...\")\n self.progress_bar.close()\n raise Exception(\"读取失败,请检查硬件。\")\n\n\n\n\n def on_click_watch_table_view(self, model_index):\n pass\n print(\"add:\",model_index.row(),model_index.column())\n # QMessageBox.information(self,\"提示\",\"隐藏当前列\",QMessageBox.Yes|QMessageBox.No)\n\nclass Custum_complains(QThread):\n # const\n def __init__(self):\n super(Custum_complains, self).__init__()\n def run(self):\n pass\n try:\n # 串口工作主流程\n \"\"\"主循环\"\"\"\n while True:\n pass\n time.sleep(0.1)\n except Exception as e:\n print(str(e))\n\n def mainloop_app(self):\n try:\n pass\n app = QtWidgets.QApplication(sys.argv)\n window = MyApp()\n window.show()\n pass\n except Exception as e:\n print(str(e))\n finally:\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n try:\n custum = Custum_complains()\n custum.start()\n custum.mainloop_app()\n except Exception as e:\n print(str(e))\n finally:\n pass\n\n\n\n\n","sub_path":"CSM37F58_APP.py","file_name":"CSM37F58_APP.py","file_ext":"py","file_size_in_byte":25156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"84663529","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\n\n\ndef _create_initial_state(cell, cell_type, dtype):\n state_size = cell.state_size\n if isinstance(state_size, tuple):\n states = []\n for idx, size in enumerate(state_size):\n state_in = tf.placeholder(dtype, [None, size], name='state_{}'.format(idx))\n states.append(state_in)\n states = tuple(states)\n if cell_type == tf.contrib.rnn.BasicLSTMCell or cell_type == tf.contrib.rnn.LSTMCell:\n states = tf.contrib.rnn.LSTMStateTuple(*states)\n return states\n state_in = tf.placeholder(dtype, [None, state_size], name='state_0')\n return state_in\n\n\ndef maybe_dropout_cell(dropout, hidden_size, cell_fn):\n cell = cell_fn(hidden_size)\n cell_type = cell.__class__\n if dropout:\n cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=1.-dropout)\n return cell, cell_type\n\n\ndef stacked_rnn(inputs, hidden_sizes, cell_fn, scope, dropouts=None, dtype=tf.float32, reuse=False):\n with tf.variable_scope(scope, reuse=reuse):\n if dropouts is None:\n dropouts = [None] * len(hidden_sizes)\n\n layers, cell_types = [], []\n fixed_hidden_sizes = hidden_sizes + [hidden_sizes[-1]]\n for idx, (dropout, hidden_size) in enumerate(zip(dropouts, fixed_hidden_sizes[:-1])):\n cell, cell_type = maybe_dropout_cell(\n dropout, hidden_size, cell_fn)\n if hidden_size != fixed_hidden_sizes[idx + 1]:\n cell = tf.contrib.rnn.OutputProjectionWrapper(cell, fixed_hidden_sizes[idx + 1])\n layers.append(cell)\n cell_types.append(cell_type)\n\n initial_states = tuple(\n [_create_initial_state(cell, cell_type, dtype)\n for cell, cell_type in zip(layers, cell_types)])\n layers = tf.contrib.rnn.MultiRNNCell(layers)\n outputs, states = tf.nn.dynamic_rnn(\n layers, inputs,\n initial_state=initial_states,\n dtype=dtype,\n time_major=False)\n return outputs, states, initial_states, layers.zero_state\n","sub_path":"alchemy/layers/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"334300252","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import throw, _\nimport frappe.defaults\nfrom frappe.utils import cint, flt, get_fullname, cstr\nfrom frappe.contacts.doctype.address.address import get_address_display\nfrom erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings import get_shopping_cart_settings\nfrom frappe.utils.nestedset import get_root_of\nfrom erpnext.accounts.utils import get_account_name\nfrom erpnext.utilities.product import get_qty_in_stock\nfrom erpnext.shopping_cart.cart import get_address_docs,get_debtors_account,get_applicable_shipping_rules,apply_cart_settings\n\n\n@frappe.whitelist()\ndef get_cart_quotation(party,doc):\n\t# addresses = get_address_docs(party=party)\n\t# if not doc.customer_address and addresses:\n\t# \tupdate_cart_address(\"customer_address\", addresses[0].name)\n\t return {\n\t \t\"doc\": doc,\n\t\t# \"shipping_addresses\": [{\"name\": address.name, \"display\": address.display}\n\t\t# \tfor address in addresses],\n\t\t# \"billing_addresses\": [{\"name\": address.name, \"display\": address.display}\n\t\t# \tfor address in addresses],\n\t\t#\"shipping_rules\": get_applicable_shipping_rules(party=party,quotation=doc)\n\t }\n\ndef _get_cart_quotation(party):\n\t'''Return the open Quotation of type \"Shopping Cart\" or make a new one'''\n\tquotation = frappe.get_all(\"Quotation\", fields=[\"name\"], filters=\n\t\t{party.doctype.lower(): party.name, \"order_type\": \"Shopping Cart\", \"docstatus\": 0},\n\t\torder_by=\"modified desc\", limit_page_length=1)\n\n\tif quotation:\n\t\tqdoc = frappe.get_doc(\"Quotation\", quotation[0].name)\n\telse:\n\t\tqdoc = frappe.get_doc({\n\t\t\t\"doctype\": \"Quotation\",\n\t\t\t\"naming_series\": get_shopping_cart_settings().quotation_series or \"QTN-CART-\",\n\t\t\t\"quotation_to\": party.doctype,\n\t\t\t\"company\": frappe.db.get_value(\"Shopping Cart Settings\", None, \"company\"),\n\t\t\t\"order_type\": \"Shopping Cart\",\n\t\t\t\"status\": \"Draft\",\n\t\t\t\"docstatus\": 0,\n\t\t\t\"__islocal\": 1,\n\t\t\t(party.doctype.lower()): party.name\n\t\t})\n\n\t\tqdoc.contact_person = party.customer_primary_contact\n\t\tqdoc.contact_email = party.email_id\n\n\t\tqdoc.flags.ignore_permissions = True\n\t\tqdoc.run_method(\"set_missing_values\")\n\t\tapply_cart_settings(party, qdoc)\n\n\treturn qdoc\n\n@frappe.whitelist()\ndef update_cart(party, item_code, qty, reward=False):\n\tquotation = _get_cart_quotation(party)\n\tempty_card = False\n\tqty = flt(qty)\n\tif qty == 0:\n\t\tquotation_items = quotation.get(\"items\", {\"item_code\": [\"!=\", item_code]})\n\t\tif quotation_items:\n\t\t\tquotation.set(\"items\", quotation_items)\n\t\telse:\n\t\t\tempty_card = True\n\n\telse:\n\t\tif not reward:\n\t\t\tquotation_items = quotation.get(\"items\", {\"item_code\": item_code})\n\t\t\tif not quotation_items:\n\t\t\t\tquotation.append(\"items\", {\n\t\t\t\t\t\"doctype\": \"Quotation Item\",\n\t\t\t\t\t\"item_code\": item_code,\n\t\t\t\t\t\"qty\": qty\n\t\t\t\t})\n\t\t\telse:\n\t\t\t\tquotation_items[0].qty = qty\n\t\telse:\n\t\t\tquotation.append(\"items\", {\n\t\t\t\t\"doctype\": \"Quotation Item\",\n\t\t\t\t\"item_code\": item_code,\n\t\t\t\t\"qty\": qty,\n\t\t\t\t\"rate\": 0\n\t\t\t})\n\tapply_cart_settings(party=party, quotation=quotation)\n\n\tquotation.flags.ignore_permissions = True\n\tquotation.payment_schedule = []\n\tif not empty_card:\n\t\tquotation.save()\n\telse:\n\t\tquotation.delete()\n\t\tquotation = None\n\n\t#set_cart_count(quotation=quotation)\n\n\tcontext = get_cart_quotation(party=party,doc=quotation)\n\treturn context\n\t# if cint(with_items):\n\t# \treturn {\n\t# \t\t\"items\": frappe.render_template(\"templates/includes/cart/cart_items.html\",\n\t# \t\t\tcontext),\n\t# \t\t\"taxes\": frappe.render_template(\"templates/includes/order/order_taxes.html\",\n\t# \t\t\tcontext),\n\t# \t}\n\t# else:\n\t# \treturn {\n\t# \t\t'cart_name': context['name'],\n\t# \t\t'cart_details': context\n\t# \t}\n\n@frappe.whitelist()\ndef place_order(party,address,shipping,payment,referer,reward, coupon):\n\tquotation = _get_cart_quotation(party)\n\tquotation.company = frappe.db.get_value(\"Shopping Cart Settings\", None, \"company\")\n\tif not quotation.get(\"customer_address\"):\n\t\t# throw(_(\"{0} is required\").format(_(quotation.meta.get_label(\"customer_address\"))))\n\t\tquotation.customer_address = address.name\n\tquotation.customer = party.name\n\tquotation.customer_name = party.customer_name\n\tquotation.title = party.customer_name\n\tquotation.flags.ignore_permissions = True\n\tquotation.save()\n\tquotation.submit()\n\n\tif quotation.lead:\n\t\t# company used to create customer accounts\n\t\tfrappe.defaults.set_user_default(\"company\", quotation.company)\n\n\tfrom erpnext.selling.doctype.quotation.quotation import _make_sales_order\n\tsales_order = frappe.get_doc(_make_sales_order(quotation.name, ignore_permissions=True))\n\tif shipping == 'expedited':\n\t sales_order.delivery_date = frappe.utils.data.add_days(frappe.utils.data.today(),1)\n\telse:\n\t sales_order.delivery_date = frappe.utils.data.add_days(frappe.utils.data.today(),3)\n\n\tsales_order.payment_terms_template = payment\n\tsales_order.shipping_rule = shipping\n\tsales_order.referer = referer\n\tsales_order.coupon = coupon\n\tif reward:\n\t\tsales_order.reward = reward.name\n\tfor item in sales_order.get(\"items\"):\n\t\titem.reserved_warehouse, is_stock_item = frappe.db.get_value(\"Item\",\n\t\t\titem.item_code, [\"website_warehouse\", \"is_stock_item\"]) or None, None\n\n\t\tif is_stock_item:\n\t\t\titem_stock = get_qty_in_stock(item.item_code, \"website_warehouse\")\n\t\t\tif item.qty > item_stock.stock_qty[0][0]:\n#\t\t\t\tthrow(_(\"Only {0} in stock for item {1}\").format(item_stock.stock_qty[0][0], item.item_code))\n\t\t\t\treturn (\"Sản phẩm {1}\").format(item.item_name) + \" không đủ tồn kho.\"\n\n\tsales_order.flags.ignore_permissions = True\n\tsales_order.run_method(\"apply_shipping_rule\")\n\tsales_order.run_method(\"calculate_taxes_and_totals\")\n\tsales_order.insert()\n\tsales_order.submit()\n\n\tif hasattr(frappe.local, \"cookie_manager\"):\n\t\tfrappe.local.cookie_manager.delete_cookie(\"cart_count\")\n\n\treturn sales_order.name\n\n@frappe.whitelist()\ndef update_cart_address(party,address_fieldname, address_name):\n\tquotation = _get_cart_quotation(party)\n\taddress_display = get_address_display(frappe.get_doc(\"Address\", address_name).as_dict())\n\n\tif address_fieldname == \"shipping_address_name\":\n\t\tquotation.shipping_address_name = address_name\n\t\tquotation.shipping_address = address_display\n\n\t\tif not quotation.customer_address:\n\t\t\taddress_fieldname == \"customer_address\"\n\n\tif address_fieldname == \"customer_address\":\n\t\tquotation.customer_address = address_name\n\t\tquotation.address_display = address_display\n\n\n\tapply_cart_settings(party=party, quotation=quotation)\n\n\tquotation.flags.ignore_permissions = True\n\tquotation.save()\n\n\tcontext = get_cart_quotation(party=party, doc=quotation)\n\treturn {\n\t\t\"taxes\": frappe.render_template(\"templates/includes/order/order_taxes.html\",\n\t\t\tcontext),\n\t\t}\n\n@frappe.whitelist()\ndef apply_shipping_rule(party,shipping_rule):\n\tquotation = _get_cart_quotation(party=party)\n\n\tquotation.shipping_rule = shipping_rule\n\n\tapply_cart_settings(party=party, quotation=quotation)\n\n\tquotation.flags.ignore_permissions = True\n\tquotation.save()\n\n\treturn get_cart_quotation(party=party, doc=quotation)\n\ndef get_party(user):\n\tcontact_name = frappe.db.get_value(\"Contact\", {\"mobile_no\": user})\n\tparty = None\n\n\tif contact_name:\n\t\tcontact = frappe.get_doc('Contact', contact_name)\n\t\tif contact.links:\n\t\t\tparty_doctype = contact.links[0].link_doctype\n\t\t\tparty = contact.links[0].link_name\n\n\tcart_settings = frappe.get_doc(\"Shopping Cart Settings\")\n\n\tdebtors_account = ''\n\n\tif cart_settings.enable_checkout:\n\t\tdebtors_account = get_debtors_account(cart_settings)\n\n\tif party:\n\t\treturn frappe.get_doc(party_doctype, party)\n\telse:\n\t\tif not cart_settings.enabled:\n\t\t\tfrappe.local.flags.redirect_location = \"/contact\"\n\t\t\traise frappe.Redirect\n\t\tcustomer = frappe.new_doc(\"Customer\")\n\t\t#fullname = get_fullname(user)\n\t\tcustomer.update({\n\t\t#\t\"customer_name\": fullname,\n\t\t\t\"customer_type\": \"Individual\",\n\t\t\t\"customer_group\": get_shopping_cart_settings().default_customer_group,\n\t\t\t\"territory\": get_root_of(\"Territory\")\n\t\t})\n\n\t\tif debtors_account:\n\t\t\tcustomer.update({\n\t\t\t\t\"accounts\": [{\n\t\t\t\t\t\"company\": cart_settings.company,\n\t\t\t\t\t\"account\": debtors_account\n\t\t\t\t}]\n\t\t\t})\n\n\t\tcustomer.flags.ignore_mandatory = True\n\t\tcustomer.save(ignore_permissions=True)\n\n\t\tcontact = frappe.new_doc(\"Contact\")\n\t\tcontact.update({\n\t\t#\t\"first_name\": fullname,\n\t\t\t\"mobile_no\": user\n\t\t})\n\t\tcontact.append('links', dict(link_doctype='Customer', link_name=customer.name))\n\t\tcontact.flags.ignore_mandatory = True\n\t\tcontact.save(ignore_permissions=True)\n\n\t\treturn customer","sub_path":"vs/vs/shopping_cart.py","file_name":"shopping_cart.py","file_ext":"py","file_size_in_byte":8364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"329478777","text":"import numpy as np\n\n\ndef DMPerCount(resumeDict):\n numResume = len(resumeDict)\n \n # for each resume, find the number of fake diploma and the percentage of it\n numFakeDiploma = np.zeros((numResume, 1))\n pctFakeDiploma = np.zeros((numResume, 1))\n rankFakeDiploma = np.zeros((numResume, 1))\n titleDiploma = np.zeros((numResume, 1))\n yearDiploma = np.zeros((numResume, 1))\n \n allKeys = resumeDict.keys()\n \n \n for iObs in range(numResume):\n iResume = resumeDict[allKeys[iObs]]\n \n tdVec = iResume['educDM']\n tdIdxNA = np.array(tdVec)>=0\n tdIdxList = list(tdIdxNA)\n degreeTypeVec = iResume['eduDegreeType']\n \n numFakeDiploma[iObs] = np.sum( tdIdxNA)\n pctFakeDiploma[iObs] = np.mean( tdIdxNA )\n # find the rank of the first fake diploma\n rankFakeDiploma[iObs] = tdIdxList.index(1)\n titleDiploma[iObs] = degreeTypeVec[int(rankFakeDiploma[iObs])]\n \n yearDiploma[iObs] = firstDegreeTimeFinder(tdIdxList, iResume['educHistoryEnd'])[0]\n\n return numFakeDiploma, pctFakeDiploma, rankFakeDiploma, titleDiploma, yearDiploma\n\n\n\n\ndef priorWorkExpToFirstOnlistDegree(resumeDict):\n \n numResume = len(resumeDict)\n priorExp = np.zeros((numResume,1))\n priorTitles = np.zeros((numResume,1))\n priorJobs = np.zeros((numResume,1))\n \n allKeys = resumeDict.keys()\n \n \n for iObs in range(numResume):\n iResume = resumeDict[allKeys[iObs]]\n \n # prepare for the analysis\n tdIdxNA = np.array(iResume['educDM'])>=0\n tdIdxList = list(tdIdxNA)\n eduGradTimeVec = iResume['educHistoryEnd']\n jobStartTimeVec = iResume['jobHistoryStart']\n jobCompanyVec = iResume['jobCompanyList']\n \n numJobs = len(jobStartTimeVec)\n # for each resume, first figure out that year is the first degree they obtained from an institution on the list\n gradYear = firstDegreeTimeFinder(tdIdxList, eduGradTimeVec)[0]\n # then figure out what is the start year of their first job\n # no job history, ignore\n if len(jobStartTimeVec)>0:\n \n \n \n # if there is valid job entry \n jobStartYearArray = jobYearCalc(jobStartTimeVec)\n \n # find the first year\n firstJobYear = min(jobStartYearArray)\n # calculate the experience. \n '''\n If the grad Year is later than the first Job year, truncate it to 0.\n It means the observation get the degree while they are on the first job\n '''\n priorExp[iObs] = max(0, gradYear - firstJobYear)\n # find how many prior jobs the observation has\n '''\n Does not use end time because (1) One could start multiple jobs, (2) it miss the \"on the job\" Job\n '''\n priorTitles[iObs] = jobStartYearArray[jobStartYearArray<=gradYear].shape[0]\n '''\n Distinguish between prior title changes and prior company changes\n ''' \n switchCompanyIdx = companySwitchGen(numJobs, jobCompanyVec)\n # 1st job is -1 with \n priorJobs[iObs] = np.sum( abs(switchCompanyIdx[jobStartYearArray<=gradYear]) ) \n # take the difference in years\n # could graduate then first a job\n if priorExp[iObs]>50:\n raise TypeError( 'Error, prior experience is invalid.')\n # find how many jobs they got before the degree\n else:\n priorExp[iObs] = -1\n return priorExp, priorTitles, priorJobs\n\ndef workExpAfterFirstOnlistDegree(resumeDict):\n numResume = len(resumeDict)\n \n changeDuration = np.zeros((numResume,2))\n numAfterTitles = np.zeros((numResume,1)) \n numAfterJobs = np.zeros((numResume,1)) \n \n \n allKeys = resumeDict.keys()\n for iObs in range(numResume):\n iResume = resumeDict[allKeys[iObs]]\n \n # prepare for the analysis\n tdIdxNA = np.array(iResume['educDM'])>=0\n tdIdxList = list(tdIdxNA)\n eduGradTimeVec = iResume['educHistoryEnd']\n jobStartTimeVec = iResume['jobHistoryStart']\n jobEndTimeVec = iResume['jobHistoryEnd']\n jobCompanyVec = iResume['jobCompanyList'] \n \n numJobs = len(jobStartTimeVec)\n \n # find the graduate year month\n\n gradYear, gradMonth = firstDegreeTimeFinder(tdIdxList, eduGradTimeVec)\n gradYearMonth = gradYear*100+gradMonth\n if len(jobStartTimeVec)>0:\n \n '''\n Here loop through all the jobs history. To make a conservative estimation\n If the job start does not specify month, assume starts from Dec\n If the educ does not specify month, assume end in Jan\n This gives the minimum bound of on the job training.\n '''\n \n # find all the job info\n jobStartArray = np.zeros((numJobs,1))\n jobEndArray = np.zeros((numJobs,1))\n switchCompanyIdx = companySwitchGen(numJobs, jobCompanyVec)\n for iJob in range(numJobs):\n temp = yearMonthToYearMonth(jobStartTimeVec[iJob], 1)\n jobStartArray[iJob] = temp[0]*100 + temp[1]\n temp = yearMonthToYearMonth(jobEndTimeVec[iJob], 0)\n jobEndArray[iJob] = temp[0]*100 + temp[1]\n \n \n afterGradJobIdx = jobStartArray>gradYearMonth\n jobAfterGradStartTime = jobStartArray[afterGradJobIdx]\n switchAfterGradIdx = switchCompanyIdx[afterGradJobIdx]\n \n numTitlesAfterGrad = jobAfterGradStartTime.shape[0]\n numJobsAfterGrad = np.sum( abs(switchAfterGradIdx) ) # first job is characterized as -1, which is also a job\n \n # find out if degree is obtained on job\n\n \n if numTitlesAfterGrad>0:\n numAfterTitles[iObs] = numTitlesAfterGrad\n numAfterJobs[iObs] = numJobsAfterGrad\n # find out what it is the duration of the degree and the next job offer\n '''\n use number 9 to signal that it should not come to determin 99 anymore\n '''\n firstJobYear, firstJobMonth = yearMonthToYearMonth(jobAfterGradStartTime[-1], 9)\n duration = firstJobYear*12+firstJobMonth - (gradYear*12+ gradMonth)\n #if duration > 100:\n # print 'longer than expected change duration'\n '''\n The duration could exceed 100 months if they are back to school or they just fake it\n '''\n \n changeDuration[iObs,0] = duration\n if switchAfterGradIdx[-1] == 1:\n changeDuration[iObs,1] = 1\n elif switchAfterGradIdx[-1] == -1:\n # indicate it is their first job!\n changeDuration[iObs,1] = -1\n \n else:\n # no job changes\n changeDuration[iObs,0] = -5\n changeDuration[iObs,1] = -5\n \n \n return numAfterTitles, numAfterJobs, changeDuration \n \n\ndef crisisExp(resumeDict): \n \n numResume = len(resumeDict)\n gotDegreeBefore2008 = np.zeros((numResume,1))\n gotLayoff = np.zeros((numResume,1))\n numTitlesAfter2008 = np.zeros((numResume,1))\n numJobsAfter2008 = np.zeros((numResume,1))\n allKeys = resumeDict.keys()\n \n for iObs in range(numResume):\n iResume = resumeDict[allKeys[iObs]]\n \n tdIdxNA = np.array(iResume['educDM'])>=0\n tdIdxList = list(tdIdxNA)\n eduGradTimeVec = iResume['educHistoryEnd']\n jobStartTimeVec = iResume['jobHistoryStart']\n jobEndTimeVec = iResume['jobHistoryEnd']\n numJobs = len(jobEndTimeVec)\n \n jobCompanyVec = iResume['jobCompanyList'] \n switchCompanyIdx = companySwitchGen(numJobs, jobCompanyVec)\n \n #need to know if they received the degree before 2009\n gradYear = firstDegreeTimeFinder(tdIdxList, eduGradTimeVec)[0]\n if gradYear<2008:\n gotDegreeBefore2008[iObs] = 1\n '''\n need to know if what happened to them in 2009 and 2012\n ''' \n # find the start year and the end year\n jobStartTimeArray = jobYearCalc(jobStartTimeVec)\n jobEndTimeArray = jobYearCalc(jobEndTimeVec) \n \n \n for iJob in range(numJobs):\n # Find as of Jan, 2009, if they are on the job\n if jobStartTimeArray[iJob]<2008 and (jobEndTimeArray[iJob]>=2008 and jobEndTimeArray[iJob]<=2011) and switchCompanyIdx[iJob] == 1:\n gotLayoff[iObs] = 1\n \n # Find how many jobs they got between 2009 and 2011\n if jobStartTimeArray[iJob]>2008 and jobStartTimeArray[iJob]<=2011:\n numTitlesAfter2008[iObs] += 1\n if abs(switchCompanyIdx[iJob]) == 1:\n numJobsAfter2008[iObs] += 1\n \n \n \n return gotDegreeBefore2008, gotLayoff, numTitlesAfter2008, numJobsAfter2008 \n\n\ndef onJobTrain(resumeDict):\n \n numResume = len(resumeDict)\n onJobIdx = np.zeros((numResume,1)) \n allKeys = resumeDict.keys()\n \n for iObs in range(numResume):\n iResume = resumeDict[allKeys[iObs]]\n \n eduGradTimeVec = iResume['educHistoryEnd']\n tdIdxNA = np.array(iResume['educDM'])>=0\n tdIdxList = list(tdIdxNA)\n numDegree = len(eduGradTimeVec)\n \n jobStartTimeVec = iResume['jobHistoryStart']\n jobEndTimeVec = iResume['jobHistoryEnd']\n numJobs = len(jobStartTimeVec)\n \n # for valid identification, the graduation time cannot have \n firstDegreeIdx = (numDegree-1) - tdIdxList[::-1].index(1)\n gradYear = int(eduGradTimeVec[firstDegreeIdx]/100)\n gradMonth = int(eduGradTimeVec[firstDegreeIdx]) - gradYear*100\n \n if gradMonth != 99:\n # for each job, find all years\n for iJob in range(numJobs):\n startYear = int(jobStartTimeVec[iJob]/100)\n endYear = int(jobEndTimeVec[iJob]/100)\n\n \n if startYear <= gradYear and endYear >= gradYear:\n # it is a potential candidate\n # check if start month and end month are 99.\n startMonth = int(jobStartTimeVec[iJob]) - startYear*100\n endMonth = int(jobEndTimeVec[iJob]) - endYear*100 \n if startMonth != 99 or endMonth != 99:\n # now finally, we can go about checking \n if startYear*100+startMonth <= gradYear*100+gradMonth and endYear*100+endMonth >= gradYear*100+gradMonth:\n onJobIdx[iObs] = 1\n else:\n onJobIdx[iObs] = -1\n else:\n onJobIdx[iObs] = -1\n return onJobIdx \n \n''' \n Auxulary Functions\n'''\ndef yearMonthToYear(yearMonth):\n\n year = yearMonth/100\n if year == 9999:\n year = 2013\n return year\n\ndef yearMonthToYearMonth(yearMonth, conservativeIdx):\n # ensure passing in integers!\n yearMonth = int(yearMonth)\n year = yearMonth/100\n month = yearMonth - year*100\n if year == 9999 and month == 99:\n year = 2013\n month = 3\n elif year != 9999 and month == 99:\n if conservativeIdx == 1:\n month = 12\n elif conservativeIdx == 0:\n month = 1\n else:\n raise TypeError('It should not come HERE!')\n \n return year,month \n \ndef firstDegreeTimeFinder(degreeIdx, gradYearList):\n numDegree = len(degreeIdx)\n firstDegreeIdx = (numDegree-1) - degreeIdx[::-1].index(1)\n # conservative index is 1.\n # if the month is not reported for previous years, assume to be 12\n gradYear, gradMonth = yearMonthToYearMonth(gradYearList[firstDegreeIdx], 0) \n \n if gradYear<1950:\n raise TypeError('Invalid graduation date.')\n \n return gradYear, gradMonth\n\ndef jobYearCalc(jobHistoryStart):\n jobYearList = []\n for iJobTime in jobHistoryStart:\n jobYearList.append(yearMonthToYear(iJobTime))\n jobYearArray = np.array(jobYearList)\n \n return jobYearArray\n\ndef companySwitchGen(numJobs, jobCompanyVec):\n \n if numJobs == 0:\n return 0\n \n switchCompanyIdx = np.zeros((numJobs,1))\n # if it is the first job, then fill in -1 as indicator\n switchCompanyIdx[numJobs-1] = -1\n\n \n for iJob in range(numJobs,0,-1):\n if iJob != numJobs:\n if jobCompanyVec[iJob] != jobCompanyVec[iJob-1]:\n switchCompanyIdx[iJob-1] = 1 \n \n return switchCompanyIdx","sub_path":"degreeMill/statsFromObj.py","file_name":"statsFromObj.py","file_ext":"py","file_size_in_byte":13065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"98094622","text":"from __future__ import print_function\nimport operator\nimport codecs\nimport glob\nimport backendDefs as bk\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom time import time\n\nimport numpy as np\nimport sys,os\n\nimport pLSABet\nimport pickle\ndef getRelTweets(newsID,dtpure,tweetPre,tweetIDset,tweetSet):\n t_path = glob.glob(tweetPre+dtpure+\"/\"+str(newsID)+\"_*\")\n if len(t_path) != 1:\n print('no tweets for news ',newsID,'len(t_path)',len(t_path))\n return ([],[])\n if os.path.exists(t_path[0]):\n t = codecs.open(t_path[0], encoding = 'utf-8') \n tweets = []\n tweetsObj = []\n# stupid redundancy\n for line in t:\n fields = line.strip().split(\"\\t\")\n if len(fields) < 24:\n # tweets_log.write(\"not 27:\"+line.strip()+\"\\n\")\n continue\n ID, raw_text, created_at, contained_url, hash_tags, retw_id_str, retw_favorited, retw_favorite_count, is_retweet, retweet_count, \\\n tw_favorited, tw_favorite_count, tw_retweeted, tw_retweet_count, user_id_str, verified, follower_count, statuses_count, friends_count, \\\n favorites_count, user_created_at= fields[:21]\n try:\n ID = int(ID)\n except:\n continue\n try:\n is_retweet=bool(is_retweet)\n except:\n is_retweet=False\n try:\n retweet_count = int(retweet_count)\n except:\n retweet_count = -1\n if \"http\" not in raw_text and \"RT @\" not in raw_text \\\n and ID not in tweetIDset and raw_text not in tweetSet:\n tweet = bk.Tweet(ID,raw_text,created_at,is_retweet,retweet_count,hash_tags)\n tweetsObj.append(tweet)\n tweets.append(raw_text)\n tweetIDset.add(ID)\n tweetSet.add(raw_text)\n t.close()\n return (tweets,tweetsObj)\ndef rankTweets(tweets, tweetsObj, newsVec, vocab, t_topK):\n tweetVectorizer = TfidfVectorizer(max_df=0.5,\n min_df=2, stop_words='english',\n vocabulary=vocab)\n X = tweetVectorizer.fit_transform(tweets)\n scores = X.dot(newsVec)\n tweetsInd = scores.argsort()[::-1][:t_topK]\n topTweetsObj = [tweetsObj[i] for i in tweetsInd]\n topTweetsScore = {}\n for i in tweetsInd:\n topTweetsScore[tweetsObj[i].ID] = scores[i]\n return topTweetsObj,topTweetsScore\n\n\ndef printCluster(X,i,terms,outfile,ind2obj,t_topK,tweetPre,Pw_z,wordInd,docInd):\n print(\"Cluster %d:\" % i, end='')\n outfile.write(\"Cluster %d:\" % i)\n print()\n outfile.write('\\n')\n tweets = []\n tweetsObj = []\n M = 50\n N = 10\n for j in range(M):\n sys.stdout.write('\\t'+terms[wordInd[j,i]])\n sys.stdout.write('\\n')\n for k in range(N):\n news = ind2obj[docInd[i,k]]\n print(news.title)\n\n\n# newsList = [ind2obj[ind] for ind in clus2doc[i]]\n# for news in sorted(newsList, key=operator.attrgetter('created_at')):\n# for ind in clus2doc[i]:\n# news = ind2obj[ind]\n\n# print(str(news.created_at)+\"\\t\"+news.title) #+\"\\t\"+news.raw_text+\"\\t\"+news.source)\n outfile.write(str(news.created_at)+\"\\t\"+news.title+\"\\n\")\n print(\"-------\")\n outfile.write(\"-------\\n\")\n newsID = news.ID\n dtpure = news.dtpure\n tweetIDset = set()\n tweetSet = set()\n #if getRelTweets(newsID,dtpure,tweetPre, tweetIDset,tweetSet):\n addtweets,addtweetsObj = getRelTweets(newsID,dtpure,tweetPre,tweetIDset,tweetSet) \n tweets = tweets + addtweets\n tweetsObj = tweetsObj + addtweetsObj\n # tweets = tweets | getRelTweets(newsID)\n # tweets = list(tweets)\n if tweets:\n newsCenter = Pw_z[:,i]\n #newsCenter = np.squeeze(np.asarray(getNewsCenter(X,clus2doc[i])))\n for term in newsCenter.argsort()[::-1][:20]:\n print(' %s' % terms[term], end='')\n outfile.write(' %s' % terms[term])\n #topTweets = rankTweets(tweets, clusModel.cluster_centers_[i,:], vectorizer.vocabulary_,t_topK)\n topTweetsObj,topTweetsScore = rankTweets(tweets,tweetsObj, newsCenter, terms,t_topK)\n print(\"*******total tweets: \"+str(len(tweets)))\n outfile.write(\"\\n*******top tweets:********total tweets: \" + str(len(tweets))+\"\\n\")\n print(\"top tweets:\")\n for t in sorted(topTweetsObj, key=operator.attrgetter('created_at')):\n print(str(topTweetsScore[t.ID])+\"\\t\"+str(t.created_at)+\"\\t\" + t.raw_text )\n outfile.write(str(topTweetsScore[t.ID])+\"\\t\"+str(t.created_at)+\"\\t\" + t.raw_text+\"\\n\")\n outfile.write('\\n-------\\n')\n print(\"-------\")\n else:\n print(\"no tweets retrieved\")\n outfile.write(\"no tweets retrieved\\n\")\n print(\"=========\")\n outfile.write(\"=========\\n\\n\")\n print()\ndef inittime(DT,K,labels):\n mu = np.zeros(K)\n sigma = np.zeros(K)\n for i in range(K):\n ts = np.array(DT)[labels==i]\n mu[i] = np.mean(ts)\n sigma[i] = np.std(ts)\n return mu,sigma\n \n\n# input args: K display\nwith open('test30.pickle') as f:\n [X,Xp,Xl,Xo,X_all,K,Learn,Pz_d_km,Pw_z_km,Pw_z,Pz_d,Pd,Li,\\\n labels,terms,termsp,termsl,termso,terms_all,DT,ind2obj,clusModel]=pickle.load(f)\nif K!=int(sys.argv[1]):\n km = MiniBatchKMeans(n_clusters=k, init='k-means++', n_init=100,init_size=1000,\n batch_size=1000,verbose=True)\n km.fit(X)\n labels = km.labels_\n centers = km.cluster_centers_\n clus2doc = {}\n for i in range(len(labels)):\n clus2doc[labels[i]] = clus2doc.get(labels[i],set())\n clus2doc[labels[i]].add(i) \n## print number of docs in each cluster \n for i in clus2doc:\n print (str(i+1)+\"\\t\"+str(len(clus2doc[i])))\n\nt0 = time()\nLearn=(1,10)\nselectTime = 1\nnumX = 1\n#K=30\ndata = [X, DT]\nmu_km, sigma_km= inittime(DT,K,labels)\ninits = [Pz_d_km,Pw_z_km,mu_km,sigma_km]\nwt = 0.5\nlambdaB = 0.5\n# data = [Xs,DT]\n# inits = [Pz_d,Pw_z, Pp_z,Pl_z,Po_z,mu,sigma] \nPw_zs,Pz_d,Pd,mu,sigma,Li = pLSABet.pLSABet(selectTime,numX,Learn,data,inits,wt,lambdaB,1)\nprint( \"pLSA done in \"+str(time() - t0))\ntweetPre=\"/home/wtong8/NewsTwitter/tweets/\"\noutfile = codecs.open(sys.argv[3], 'w', encoding = 'utf-8')\nM = 50\nN = 10\nwordInd = Pw_zs[0].argsort(axis=0)[::-1,:]\ndocInd = Pz_d.argsort()[:,::-1]\nt_topK=100\nfor i in range(K): \n printCluster(X,i,terms,outfile,ind2obj,t_topK,tweetPre,Pw_zs[0],wordInd,docInd)\nexit(0)\n###################### split event###########################\ndef weightX(X,Pw_z,Pz_d):\n K = Pz_d.shape[0]\n X = X.tocoo()\n docind,wordind,value = (X.row,X.col,X.data)\n # Pz_do_f = Pz_do.*(Pz_do>(1-lambdaB)/double(K-1))\n Pz_d_f = Pz_d*(Pz_d>0.01)\n Pz_dw_ = Pw_z[wordind,:].T*Pz_d_f[:,docind]\n Pw_d = Pz_dw_.sum(axis=0) # 1 x nnz\n Pz_wd = Pz_dw_[:-1,:]/np.tile(Pw_d,(K-1,1))\n n_wdxPz_wd = np.tile(value,(K-1,1))*Pz_wd\n n_wdxPz_wd = n_wdxPz_wd *(n_wdxPz_wd>0.0001) ####\n return n_wdxPz_wd\n\nn_wdxPz_wds = []\nfor i in range(numX):\n n_wdxPz_wds.append( weightX(data[i],Pw_zs[i],Pz_d) )\nfrom scipy.sparse import coo_matrix\n# get event matrices\ndef selectTopic(Xs,n_wdxPz_wds,event):\n Xevents = [] \n for i in range(len(Xs)):\n X = Xs[i]\n n_wdxPz_wd = n_wdxPz_wds[i]\n nDocs,nWords=X.shape\n docind,wordind,value = (X.row,X.col,X.data) \n value = n_wdxPz_wd[event,:]\n select = (value!=0)\n value_f = value[select]\n row_f = docind[select] # 1 3 3 5 5 6 6 6 \n col_f = wordind[select] \n if i==0:\n dID = np.unique(row_f) # 1 3 5 6\n dID2ind = -np.ones(nDocs) # -1 -1 -1 -1 -1 -1 -1 assume nDocs = 7\n dID2ind[dID] = np.arange(len(dID)) # 0 0 1 0 2 3 0\n row_f_new = dID2ind[row_f] # 0 1 1 2 2 3 3 3\n if i>0:\n select = (row_f_new!=-1)\n Xevent = coo_matrix((value_f[select],(row_f_new[select],col_f[select])),shape=(len(dID),nWords))\n else:\n Xevent = coo_matrix((value_f,(row_f_new,col_f)),shape=(len(dID),nWords))\n Xevents.append(Xevent) \n return Xevents,dID\n###################### step 1 ###############\nevent = 0 # event number\nXevents,dID = selectTopic(data[:numX],n_wdxPz_wds,event)\nDTevent = np.array(DT)[dID]\n#data = Xevents+[DTevent] \n########################## event example ###############\nKevent=5\nkm = KMeans(n_clusters=Kevent, init='k-means++', max_iter=100, n_init=5)\nkm.fit(Xevents[0])\nlabels = km.labels_\ncenters = km.cluster_centers_\n\nnDocs,nWords = Xevents[0].shape\nPz_d_km = np.zeros((Kevent,nDocs))\nfor i in range(nDocs):\n Pz_d_km[labels[i],i] = 1\nPz_d_km = Pz_d_km +0.01;\nPz_d_km = Pz_d_km / np.tile(sum(Pz_d_km),(Kevent,1))\nC = centers.T+1/nWords/nWords\nPw_z_km = C/np.tile(sum(C),(nWords,1))\n\nt0 = time()\nLearn=(1,10)\nselectTime = 1\nnumX = 1\n#K=30\ndata = [Xevents[0], DTevent]\nmu_km, sigma_km= inittime(DTevent,Kevent,labels)\ninits = [Pz_d_km,Pw_z_km,mu_km,sigma_km]\nwt = 0.1\nlambdaB = 0.5\n# data = [Xs,DT]\n# inits = [Pz_d,Pw_z, Pp_z,Pl_z,Po_z,mu,sigma] \nPw_zs,Pz_d,Pd,mu,sigma,Li = pLSABet.pLSABet(selectTime,numX,Learn,data,inits,wt,lambdaB,1)\nprint (\"pLSA done in \"+str(time() - t0))\n#################################################################################\n# print topics\ndisplay = int(sys.argv[2])\nif display == 1:\n M = 50\n N = 10\n wordInd = Pw_zs[0].argsort(axis=0)[::-1,:]\n docInd = Pz_d.argsort()[:,::-1]\n for i in range(Kevent): #\n sys.stdout.write(\"topic \"+str(i))\n for j in range(M):\n sys.stdout.write('\\t'+terms[wordInd[j,i]])\n sys.stdout.write('\\n')\n for k in range(N):\n print(ind2obj[dID[docInd[i,k]]].title) #\n","sub_path":"scripts/dataJesse.py","file_name":"dataJesse.py","file_ext":"py","file_size_in_byte":9904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"199064850","text":"import json\nimport logging\n\nimport venusian\nfrom pyramid.exceptions import ConfigurationError\nfrom pyramid.httpexceptions import HTTPForbidden\nfrom pyramid.httpexceptions import HTTPNotFound\nfrom pyramid.response import Response\nfrom pyramid.security import NO_PERMISSION_REQUIRED\n\nfrom pyramid_rpc.api import MapplyViewMapper\nfrom pyramid_rpc.api import ViewMapperArgsInvalid\n\n\nlog = logging.getLogger(__name__)\n\n\nclass JsonRpcError(Exception):\n code = -32603 # sane default\n message = 'internal error' # sane default\n data = None\n\n def __init__(self, code=None, message=None, data=None):\n if code is not None:\n self.code = code\n if message is not None:\n self.message = message\n if data is not None:\n self.data = data\n\n def as_dict(self):\n \"\"\"Return a dictionary representation of this object for\n serialization in a JSON-RPC response.\"\"\"\n error = dict(code=self.code,\n message=self.message)\n if self.data is not None:\n error['data'] = self.data\n return error\n\n\nclass JsonRpcParseError(JsonRpcError):\n code = -32700\n message = 'parse error'\n\n\nclass JsonRpcRequestInvalid(JsonRpcError):\n code = -32600\n message = 'invalid request'\n\n\nclass JsonRpcMethodNotFound(JsonRpcError):\n code = -32601\n message = 'method not found'\n\n\nclass JsonRpcParamsInvalid(JsonRpcError):\n code = -32602\n message = 'invalid params'\n\n\nclass JsonRpcInternalError(JsonRpcError):\n code = -32603\n message = 'internal error'\n\n\ndef jsonrpc_error_response(error, id=None):\n \"\"\" Marshal a Python Exception into a webob ``Response``\n object with a body that is a JSON string suitable for use as\n a JSON-RPC response with a content-type of ``application/json``\n and return the response.\"\"\"\n\n body = json.dumps({\n 'jsonrpc': '2.0',\n 'id': id,\n 'error': error.as_dict(),\n })\n\n response = Response(body)\n response.content_type = 'application/json'\n response.content_length = len(body)\n return response\n\n\ndef exception_view(exc, request):\n rpc_id = getattr(request, 'rpc_id', None)\n if isinstance(exc, JsonRpcError):\n fault = exc\n log.debug('json-rpc error rpc_id:%s \"%s\"',\n rpc_id, exc.message)\n elif isinstance(exc, HTTPNotFound):\n fault = JsonRpcMethodNotFound()\n log.debug('json-rpc method not found rpc_id:%s \"%s\"',\n rpc_id, request.rpc_method)\n elif isinstance(exc, HTTPForbidden):\n fault = JsonRpcRequestInvalid()\n log.debug('json-rpc method forbidden rpc_id:%s \"%s\"',\n rpc_id, request.rpc_method)\n elif isinstance(exc, ViewMapperArgsInvalid):\n fault = JsonRpcParamsInvalid()\n log.debug('json-rpc invalid method params')\n else:\n fault = JsonRpcInternalError()\n log.exception('json-rpc exception rpc_id:%s \"%s\"', rpc_id, exc)\n\n return jsonrpc_error_response(fault, rpc_id)\n\n\ndef jsonrpc_renderer(info):\n def _render(value, system):\n request = system.get('request')\n if request is not None:\n rpc_id = getattr(request, 'rpc_id', None)\n response = request.response\n\n if rpc_id is None:\n response.status = 204\n del response.content_type\n return ''\n\n ct = response.content_type\n if ct == response.default_content_type:\n response.content_type = 'application/json'\n\n out = {\n 'jsonrpc': '2.0',\n 'id': rpc_id,\n 'result': value,\n }\n return json.dumps(out)\n return _render\n\n\ndef setup_jsonrpc(request):\n try:\n body = request.json_body\n except ValueError:\n raise JsonRpcParseError\n\n request.rpc_id = body.get('id')\n request.rpc_args = body.get('params', ())\n request.rpc_method = body.get('method')\n request.rpc_version = body.get('jsonrpc')\n\n if request.rpc_version != '2.0':\n log.debug('id:%s invalid rpc version %s',\n request.rpc_id, request.rpc_version)\n raise JsonRpcRequestInvalid\n\n if request.rpc_method is None:\n log.debug('id:%s invalid rpc method %s',\n request.rpc_id, request.rpc_method)\n raise JsonRpcRequestInvalid\n\n log.debug('handling id:%s method:%s',\n request.rpc_id, request.rpc_method)\n\n\ndef add_jsonrpc_endpoint(self, name, *args, **kw):\n \"\"\"Add an endpoint for handling JSON-RPC.\n\n name\n\n The name of the endpoint.\n\n A JSON-RPC method also accepts all of the arguments supplied to\n Pyramid's ``add_route`` method.\n\n \"\"\"\n def jsonrpc_endpoint_predicate(info, request):\n # potentially setup either rpc v1 or v2 from the parsed body\n setup_jsonrpc(request)\n\n # Always return True so that even if it isn't a valid RPC it\n # will fall through to the notfound_view which will still\n # return a valid JSON-RPC response.\n return True\n predicates = kw.setdefault('custom_predicates', [])\n predicates.append(jsonrpc_endpoint_predicate)\n self.add_route(name, *args, **kw)\n self.add_view(exception_view, route_name=name, context=Exception,\n permission=NO_PERMISSION_REQUIRED)\n\n\ndef add_jsonrpc_method(self, view, **kw):\n \"\"\"Add a method to a JSON-RPC endpoint.\n\n endpoint\n\n The name of the endpoint.\n\n method\n\n The name of the method.\n\n A JSON-RPC method also accepts all of the arguments supplied to\n Pyramid's ``add_view`` method.\n\n A view mapper is registered by default which will match the\n ``request.rpc_args`` to parameters on the view. To override this\n behavior simply set the ``mapper`` argument to None or another\n view mapper.\n\n \"\"\"\n endpoint = kw.pop('endpoint', kw.pop('route_name', None))\n if endpoint is None:\n raise ConfigurationError(\n 'Cannot register a JSON-RPC endpoint without specifying the '\n 'name of the endpoint.')\n\n method = kw.pop('method', None)\n if method is None:\n raise ConfigurationError(\n 'Cannot register a JSON-RPC method without specifying the '\n '\"method\"')\n\n def jsonrpc_method_predicate(context, request):\n return getattr(request, 'rpc_method', None) == method\n predicates = kw.setdefault('custom_predicates', [])\n predicates.append(jsonrpc_method_predicate)\n kw.setdefault('mapper', MapplyViewMapper)\n kw.setdefault('renderer', 'pyramid_rpc:jsonrpc')\n self.add_view(view, route_name=endpoint, **kw)\n\n\nclass jsonrpc_method(object):\n \"\"\"This decorator may be used with pyramid view callables to enable\n them to respond to JSON-RPC method calls.\n\n If ``method`` is not supplied, then the callable name will be used\n for the method name.\n\n This is the lazy analog to the\n :func:`~pyramid_rpc.jsonrpc.add_jsonrpc_method`` and accepts all of\n the same arguments.\n\n \"\"\"\n def __init__(self, method=None, **kw):\n self.method = method\n self.kw = kw\n\n def __call__(self, wrapped):\n kw = self.kw.copy()\n kw['method'] = self.method or wrapped.__name__\n\n def callback(context, name, ob):\n config = context.config.with_package(info.module)\n config.add_jsonrpc_method(view=ob, **kw)\n\n info = venusian.attach(wrapped, callback, category='pyramid')\n if info.scope == 'class':\n # ensure that attr is set if decorating a class method\n kw.setdefault('attr', wrapped.__name__)\n\n kw['_info'] = info.codeinfo # fbo action_method\n return wrapped\n\n\ndef includeme(config):\n \"\"\" Set up standard configurator registrations. Use via:\n\n .. code-block:: python\n\n config = Configurator()\n config.include('pyramid_rpc.jsonrpc')\n\n Once this function has been invoked, two new directives will be\n available on the configurator:\n\n - ``add_jsonrpc_endpoint``: Add an endpoint for handling JSON-RPC.\n\n - ``add_jsonrpc_method``: Add a method to a JSON-RPC endpoint.\n\n \"\"\"\n config.add_directive('add_jsonrpc_endpoint', add_jsonrpc_endpoint)\n config.add_directive('add_jsonrpc_method', add_jsonrpc_method)\n config.add_renderer('pyramid_rpc:jsonrpc', jsonrpc_renderer)\n config.add_view(exception_view, context=JsonRpcError,\n permission=NO_PERMISSION_REQUIRED)\n","sub_path":"pyramid_rpc/jsonrpc.py","file_name":"jsonrpc.py","file_ext":"py","file_size_in_byte":8449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"283314876","text":"#Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:\n#\t1634 = 1^4 + 6^4 + 3^4 + 4^4\n#\t8208 = 8^4 + 2^4 + 0^4 + 8^4\n#\t9474 = 9^4 + 4^4 + 7^4 + 4^4\n#As 1 = 1^4 is not a sum, it is not included.\n#The sum of these numbers is 1634 + 8208 + 9474 = 19316\n#Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.\nimport time\n\n\ndef dig_pow(n=5):\n sum_n = 0\n for i in xrange(10, (n+1)*(9**n)):\n t_sum = sum(int(str(i)[k])**5 for k in xrange(len(str(i))))\n if t_sum == i:\n sum_n += t_sum\n return sum_n\n\ndef ans(times):\n l = []\n for k in xrange(times):\n start_t = time.time()\n z = dig_pow()\n end_t = time.time()\n time_taken = end_t - start_t\n l.append(time_taken)\n return sorted(l)\n","sub_path":"solved/p30.py","file_name":"p30.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"164631724","text":"#!/usr/bin/env python\n\nimport math\nimport numpy as np\nimport pandas as pd\n\ndef smart_ylims(minval, maxval):\n span = maxval - minval\n ymin = np.ceil( minval - 0.1 * span )\n ymax = np.ceil( maxval + 0.1 * span )\n return (ymin, ymax)\n\ndef round2multiple(target, n):\n if not isinstance(target, int):\n raise ValueError('target must be int')\n if n > 0:\n return np.ceil(n/float(target)) * target;\n elif n < 0:\n return np.floor(n/float(target)) * target;\n else:\n return n\n\n# read csvfile like for JAXA plot parameters\ndef read_plot_params(csvfile):\n \"\"\"read csvfile like for JAXA plot parameters\"\"\"\n df = pd.read_csv(csvfile)\n \n# nice_number(value, round=False) -> float\ndef nice_number(value, round=False):\n \"\"\"nice_number(value, round=False) -> float\"\"\"\n exponent = math.floor(math.log(value, 10))\n fraction = value / 10 ** exponent\n\n if round:\n if fraction < 1.5: nice_fraction = 1.\n elif fraction < 3.: nice_fraction = 2.\n elif fraction < 7.: nice_fraction = 5.\n else: nice_fraction = 10.\n else:\n if fraction <= 1: nice_fraction = 1.\n elif fraction <= 2: nice_fraction = 2.\n elif fraction <= 5: nice_fraction = 5.\n else: nice_fraction = 10.\n\n return nice_fraction * 10 ** exponent\n\n# nice_bounds(axis_start, axis_end, num_ticks=10) -> (nice_axis_start, nice_axis_end, nice_tick_width)\ndef nice_bounds(axis_start, axis_end, num_ticks=10):\n \"\"\"\n nice_bounds(axis_start, axis_end, num_ticks=10) -> tuple\n @return: tuple as (nice_axis_start, nice_axis_end, nice_tick_width)\n \"\"\"\n axis_width = axis_end - axis_start\n if axis_width == 0:\n nice_tick = 0\n else:\n nice_range = nice_number(axis_width)\n nice_tick = nice_number(nice_range / (num_ticks -1), round=True)\n axis_start = math.floor(axis_start / nice_tick) * nice_tick\n axis_end = math.ceil(axis_end / nice_tick) * nice_tick\n nice_axis_start, nice_axis_end, nice_tick_width = axis_start, axis_end, nice_tick\n return nice_axis_start, nice_axis_end, nice_tick_width\n\ndef demo_nice_bounds():\n from wxmplot import PlotApp\n axis_start = 0\n num_ticks = 10\n axis_ends = np.linspace(1, 301, 601)\n nice_axis_ends = []\n nice_tick_widths = []\n for axis_end in axis_ends:\n nb = nice_bounds(axis_start, axis_end, num_ticks=num_ticks)\n #print axis_end, \" -> \", nb\n nice_axis_ends.append(nb[1])\n nice_tick_widths.append(nb[2])\n\n app = PlotApp()\n app.plot(axis_ends, nice_axis_ends, title='WXMPlot Demo', label='AE vs NAE',\n ylabel='nice_axis_ends', xlabel='axis_ends')\n \n app.oplot(axis_ends, nice_tick_widths, y2label='nice_tick_widths', side='right', ymin=0)\n \n app.write_message('Try Help->Quick Reference')\n app.run()\n \nif __name__ == \"__main__\":\n demo_nice_bounds()","sub_path":"gui/plotutils.py","file_name":"plotutils.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"565111769","text":"import base64\nimport string\n\nciphertext = base64.b64decode(\"2xv1pdJYc54wu4Q+YJeRAMc10dOc2Ragr0Fb3YpOv/4=\")\n\nplaintext1 = b'Texp8BQv'\nall_string = string.digits + string.ascii_letters\n\nfor i in all_string:\n for j in all_string:\n for k in all_string:\n iv = key = \"ZeroA\" + i + j + k\n des = DES.new(key, DES.MODE_CBC, iv)\n plaintext = des.decrypt(ciphertext)\n if plaintext.startswith(b'Texp8BQv'):\n print(plaintext)","sub_path":"crypto2_script.py","file_name":"crypto2_script.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"107415110","text":"# Copyright 2015 Rackspace\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom cafe.common.reporting.json_report import JSONReport\nfrom cafe.common.reporting.xml_report import XMLReport\nfrom cafe.common.reporting.subunit_report import SubunitReport\n\n\ndef generate_report(result_type, result, path):\n \"\"\" Creates a report object based on what type is given and generates\n the report in the specified directory.\n \"\"\"\n if result_type == 'json':\n report = JSONReport()\n elif result_type == 'xml':\n report = XMLReport()\n elif result_type == 'subunit':\n report = SubunitReport()\n else:\n return\n report.generate_report(result=result, path=path)\n","sub_path":"cafe/common/reporting/reporter.py","file_name":"reporter.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"129540347","text":"import time\n\nfrom django.core.cache import cache\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass HelloMiddleware(MiddlewareMixin):\n def process_request(self,request):\n print('有个小崽子在访问你,他的IP是:'+request.META.get('REMOTE_ADDR'))\n # request.path能够返回对方访问的url\n # print(request.path)\n # 黑名单配置\n if request.path == '/hello/':\n ip = request.META.get('REMOTE_ADDR')\n # if cache.get(ip):\n # return HttpResponse(\"10S之后再来,一直访问个屁啊\")\n # cache.set(ip,ip,timeout=10)\n # if request.META.get('REMOTE_ADDR') == '10.0.122.202':\n # return HttpResponse('滚犊子')\n black_list = cache.get(ip,[])\n requests = cache.get(ip,[])\n if ip in black_list:\n return HttpResponse('滚')\n else:\n while requests and time.time() - requests[-1] > 60:\n requests.pop()\n requests.insert(0, time.time())\n cache.set(ip,requests, timeout=60)\n if len(requests) > 30:\n black_list.append(ip)\n cache.set(ip,black_list,timeout=60*60*24)\n return HttpResponse('屏蔽了谢谢')\n if len(requests) > 10:\n return HttpResponse('你这也太急了吧')\n\n def process_exception(self,request,exception):\n print(\"出现错误\")\n return render(request,'404.html')\n ","sub_path":"middleware/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"387768309","text":"# Importing necessary libraries\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport urllib\r\nimport re\r\n\r\n# Getting html response in \"response\" variable\r\nresponse = urllib.request.urlopen(\r\n \"http://cs230.stanford.edu/proj-spring-2018.html\")\r\n\r\n# Parsing html response via beautifulsoup\r\nsoup = BeautifulSoup(response, \"lxml\")\r\nsoup.prettify\r\n\r\n# Declaring empty lists to store scraped data\r\nnames, posters, reports, link_reports, link_posters, save_r, save_p = [\r\n], [], [], [], [], [], []\r\n\r\n# Finding all links in \"ul\" class\r\na = soup.findAll(\"ul\")\r\nfor i in a:\r\n b = i.findAll(\"li\")\r\n\r\n# Collecting project names, report urls and poster urls from links\r\nfor i in b:\r\n names.append(i.find(\"strong\").text)\r\n reports.append(i.find(\"a\")[\"href\"].lstrip(\".\"))\r\n try:\r\n posters.append(i.findAll(\"a\")[1][\"href\"].lstrip(\".\"))\r\n except:\r\n pass\r\n# Removing special characters from project names\r\nfor i, j in enumerate(names):\r\n names[i] = re.sub(r\"[^a-zA-Z0-9]\", \"\", j)\r\n\r\n# Joining url and downloading response of each report and poster(pdf)\r\nfor i in reports:\r\n link_reports.append(\"http://cs230.stanford.edu{}\".format(i))\r\nfor i in posters:\r\n link_posters.append(\"http://cs230.stanford.edu{}\".format(i))\r\nfor i in link_reports:\r\n save_r.append(requests.get(i))\r\nfor i in link_posters:\r\n save_p.append(requests.get(i))\r\n\r\n# Writing downloaded response in file format\r\nfor i, j in enumerate(save_r):\r\n with open(\"{}_report.pdf\".format(names[i]), \"wb\") as fp:\r\n fp.write(j.content)\r\nfor i, j in enumerate(save_p):\r\n with open(\"{}_posters.pdf\".format(names[i]), \"wb\") as fp:\r\n fp.write(j.content)\r\n\r\n\r\n \r\n","sub_path":"scraping_stanford.py","file_name":"scraping_stanford.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"212651168","text":"# Performance comparison of RLS channel equalizer\n# for different SNR levels.\n\n\nfrom padapfilt.filters.rls import *\n\n# determine simulation parameters.\nn = 2000 # number of input data samples to the equalizer.\nm1 = 3 # number of taps of channel.\nm2 = 21 # number of taps of equalizer\nl = 100 # number of trials.\ndelay = int(m1 / 2) + int(m2 / 2)\n\n# try the channel model.\nchannel = np.array([0.25, 1.0, -0.25])\n\n# take two figures for the plots\nfig1, ax1 = get_learning_curve_plot() # plots the learning curves.\nfig2, ax2 = get_tap_weights_graph(1) # plots found filter taps.\n\n# construct the channel.\nh = channel\n\n# construct the channel filter\nf1 = BaseFilter(m1, w=h)\n\n# construct two equalizer.\nf2 = RLSFilter(m2, w='zeros', lamda=0.98, delta=0.005)\n\nsigma_a = 0.001\nsigma_b = 0.1\nSNR_a = 10 * np.log10(1.0 / sigma_a)\nSNR_b = 10 * np.log10(1.0 / sigma_b)\n\nJ_a = np.zeros((l, n))\nJ_b = np.zeros((l, n))\nw_a = np.zeros((l, m2))\nw_b = np.zeros((l, m2))\nfor k in range(l):\n # generate the data.\n x = 2 * np.round(np.random.rand(n + m1 + m2 - 2)) - 1\n\n # generate the noise.\n v_a = np.sqrt(sigma_a) * np.random.randn(n + m2 - 1) # 30 dB SNR\n v_b = np.sqrt(sigma_b) * np.random.randn(n + m2 - 1) # 10 dB SNR\n\n # filter the data from the channel.\n data_matrix = input_from_history(x, m1)\n u = np.zeros(data_matrix.shape[0])\n for item in range(data_matrix.shape[0]):\n u[item] = f1.estimate(data_matrix[item])\n u_a = u + v_a\n u_b = u + v_b\n\n # calculate the equalizer output.\n d_vector = x[delay:n + delay:]\n u_matrix_a = input_from_history(u_a, m2)\n u_matrix_b = input_from_history(u_b, m2)\n\n y_a, e_a, w_a[k] = f2.run(d_vector, u_matrix_a)\n # reset the equalizer for the next trial.\n f2.reset() # reset the filter to zero tap-weights.\n y_b, e_b, w_b[k] = f2.run(d_vector, u_matrix_b)\n # reset the equalizer for the next trial.\n f2.reset() # reset the filter to zero tap-weights.\n\n # calculate learning curve.\n J_a[k] = e_a ** 2\n J_b[k] = e_b ** 2\n\n\nJ_avg_a = J_a.mean(axis=0)\nw_avg_a = w_a.mean(axis=0)\nJ_avg_b = J_b.mean(axis=0)\nw_avg_b = w_b.mean(axis=0)\n\nax1.semilogy(J_avg_a, label=r'$SNR = {}dB$'.format(int(SNR_a)))\nax1.semilogy(J_avg_b, label=r'$SNR = {}dB$'.format(int(SNR_b)))\nax1.legend()\n\nax2.stem(w_avg_a, label=r'$SNR = {}dB$'.format(int(SNR_a)))\nax2.stem(w_avg_b, label=r'$SNR = {}dB$'.format(int(SNR_b)), markerfmt='D')\nax2.legend()\n\nplt.show()\n","sub_path":"results/term_project/rls_snr_compare.py","file_name":"rls_snr_compare.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"500326081","text":"#!/usr/bin/python\n# encoding: utf-8\n\n\nimport urllib2\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\n\nclass Result(object):\n def __init__(self, from_lang=None, to_lang=None, translation_tuples=None):\n self.from_lang = from_lang\n self.to_lang = to_lang\n self.translation_tuples = list(translation_tuples) \\\n if translation_tuples else []\n\n @property\n def n_results(self):\n return len(self.translation_tuples)\n\n @property\n def from_words(self):\n return map(lambda tuple: tuple[0], self.translation_tuples)\n\n @property\n def to_words(self):\n return map(lambda tuple: tuple[1], self.translation_tuples)\n\n @property\n def from_words_lowercase(self):\n return map(lambda tuple: tuple[0].lower(), self.translation_tuples)\n\n @property\n def to_words_lowercase(self):\n return map(lambda tuple: tuple[1].lower(), self.translation_tuples)\n\n\nclass Dict(object):\n\n def __init__(self, search_string, from_language, to_language):\n self.search_string = search_string\n self.from_language = from_language\n self.to_language = to_language\n\n @property\n def request_subdomain(self):\n subdomain = self.from_language.subdomain.lower() + self.to_language.subdomain.lower()\n\n if len(subdomain) > 4:\n return \"www\"\n else:\n return subdomain\n\n def translate(self):\n response = self.get_response()\n result = self.parse_response(response.content)\n return self.correct_translation_order(result)\n\n def get_response(self):\n subdomain = self.request_subdomain\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'\n }\n\n params = {\n \"s\": self.search_string\n }\n\n return requests.get(\"https://\" + subdomain + \".dict.cc\", params=params, headers=headers)\n\n def parse_response(self, response_body):\n\n in_list = []\n out_list = []\n\n def sanitize(word):\n return re.sub(\"[\\\\\\\\\\\"]\", \"\", word)\n\n javascript_list_pattern = \"\\\"[^,]+\\\"\"\n\n for line in response_body.split(\"\\n\"):\n if \"var c1Arr\" in line:\n in_list = map(sanitize, re.findall(javascript_list_pattern, line))\n elif \"var c2Arr\" in line:\n out_list = map(sanitize, re.findall(javascript_list_pattern, line))\n\n if not any([in_list, out_list]):\n return Result()\n\n soup = BeautifulSoup(response_body, \"html.parser\")\n\n left_lang = soup.find_all(\"td\", width=\"307\")[0].b.text\n right_lang = soup.find_all(\"td\", width=\"306\")[0].b.text\n\n in_list = map(lambda word: unicode(word, 'utf-8'), in_list)\n out_list = map(lambda word: unicode(word, 'utf-8'), out_list)\n\n return Result(\n from_lang=left_lang,\n to_lang=right_lang,\n translation_tuples=zip(in_list, out_list),\n )\n\n def correct_translation_order(self, result):\n\n if not result.translation_tuples:\n return result\n\n left_occurrences = len(filter(lambda word: word.count(self.search_string.lower()), result.from_words_lowercase))\n right_occurrences = len(filter(lambda word: word.count(self.search_string.lower()), result.to_words_lowercase))\n\n if left_occurrences >= right_occurrences:\n return result\n else:\n return Result(from_lang=result.to_lang,\n to_lang=result.from_lang,\n translation_tuples=zip(result.to_words, result.from_words)\n )\n","sub_path":"dictcc_translator.py","file_name":"dictcc_translator.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"476467077","text":"from stegasawus import eda\n\nfrom stegano.lsbset import generators\n\n\npath = '/home/rokkuran/workspace/stegasawus/'\npath_cover = '{}images/png/cover/'.format(path)\npath_stego = '{}images/png/lenna64_identity/'.format(path)\n# path_stego = '{}images/png/lenna64_eratosthenes/'.format(path)\npath_output = '{}output'.format(path)\n\nfname = 'cat.2.png'\nz = eda.JointImageAnalyser(path_cover + fname, path_stego + fname)\n\n# plot cover and stego images side by side.\nz.plot_images()\n\n# plot difference between cover and stego images.\nz.plot_difference()\n\n# plot colour channels of cover and stego images.\nz.plot_rgb_components()\n\n# Reveal and show hidden image\nz.reveal_image(generators.identity(), show=True)\n\n# Plot wavelet decomposition for a colour channel\neda.plot_wavelet_decomposition(z.I[:, :, 0])\n\n# generate set of histogram/kde plots\neda.generate_feature_distplots(\n filepath_train='{}data/features/train_lenna_identity.csv'.format(path),\n path_output=path_output,\n normalise=False\n)\n\n# generate set of histograms\neda.generate_feature_histograms(\n filepath_train='{}data/features/train_lenna_identity.csv'.format(path),\n path_output=path_output,\n bins=50,\n normalise=False\n)\n\n# generate kernel density estimation plots\neda.generate_feature_kde(\n filepath_train='{}data/features/train_lenna_identity.csv'.format(path),\n path_output=path_output,\n normalise=False\n)\n","sub_path":"examples/image_plots.py","file_name":"image_plots.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"143115135","text":"\"\"\"\n# ! /usr/bin/python3.6\n# -------------------------------------------------------------------\n# file_module.py\n# -------------------------------------------------------------------\n A class which enables you to automate some of file functions easily\n still in development\n tested only on unix\n Read from and write to .csv .txt .docx .pdf files\n Search files in a library\nTODO:the home path should be in your .bashrc file in ~/\n \"\"\"\n# home_path='' # define your home path here\nimport csv\nimport os, sys\nimport glob\nimport click\nimport shutil\nimport pandas as pd\nfrom datetime import datetime\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\nimport json\n\n\nclass FilesError(Exception):\n \"\"\"Base Exception\"\"\"\n pass\n\n\nclass BasicWritingError(FilesError):\n \"\"\"Any error encountered during writing of the files using normal method\"\"\"\n pass\n\n\nclass ReadingError(FilesError):\n \"\"\"Reading errors using normal methods\"\"\"\n pass\n\n\nclass FileError(FilesError):\n \"\"\" basic error in any file operation\"\"\"\n pass\n\n\nclass FileNamingError(FilesError):\n \"\"\" file naming error \"\"\"\n pass\n\n\nclass NoFileFoundError(FileError):\n \"\"\"file not found error\"\"\"\n pass\n\n\nclass FileCopyingError(FileError):\n \"\"\"if any error occurs during copying of files or folders\"\"\"\n pass\n\n\nclass InvalidPathError(FileError):\n \"\"\"Invalid path raise an error\"\"\"\n pass\n\n\ndef path_validator(path):\n global debug\n if os.path.exists(path) and os.path.isfile(path) and os.path.getsize(path) > 0:\n debug = 0 # no error\n else:\n debug = 1\n return debug\n\n\nclass file_Module:\n\n def __init__(self, path_=os.getcwd(), data='', file_name='', mode='r', delimiter_=';'):\n modes = {\"r\": \"r\", \"a\": \"a\", \"w\": \"w\"}\n self.path = path_\n if mode not in modes:\n raise ValueError(\"mode must be either r,w or a\")\n self.mode = mode\n self.data = data\n self.file_name = file_name\n self.delimiter_ = delimiter_\n\n # -----------------------\n # Common File Functions\n # -----------------------\n @staticmethod\n def write_read_files(data='', path=os.getcwd(), file_type='.txt', mode='r'):\n \"\"\"\n write/append data to .txt files or .json files\n :param data: the data you want to write if mode = 'w' default_path=current_dir\n :param path: the path of the file you want to read/write\n :param file_type: .txt\n :param mode: read/write\n :return:\n \"\"\"\n global msg\n try:\n if mode == 'w':\n if os.path.isfile(path):\n \"\"\"such a file exists so just \"\"\"\n if file_type == '.txt':\n with open(path, mode='a') as data:\n data.write('\\n')\n data.write(data)\n msg = 'success'\n print(msg)\n elif file_type == '.json':\n with open(path, mode='a') as json_:\n\n json.dump(json_, data, separators=' ')\n msg = 'success'\n print(msg)\n\n else:\n \"\"\"file does not exist\"\"\"\n if file_type == '.txt':\n with open(path, mode='w') as data:\n data.write(data)\n msg = 'success'\n elif file_type == '.json':\n with open(path, mode='w') as json_:\n json.dump(json_, data, separators=' ')\n msg = 'success'\n print(msg)\n elif mode == 'r':\n \"\"\"read the file\"\"\"\n if os.path.exists(path):\n\n with open(path) as content:\n if content.readable():\n while True:\n content = content.read()\n if content == '':\n break\n print(content)\n print('')\n print('\\ndone reading')\n else:\n raise FilesError(\"the file is not readable\")\n\n else:\n raise FileNotFoundError(f\"The {path} file does not exist \")\n except IOError as e:\n msg = 'failed'\n print(msg)\n if e.errno != e.ENOENT:\n raise\n\n def file_info(self):\n \"\"\"\n give information about a file in a dir\n * The file name\n * The location of the file\n * The size of the file in bytes\n * The creation time: Day example.Mon Month Day in numerals example.11 Hour (24hr system) Minutes Seconds Year\n * Last Accessed Time : Day example.Mon Month Day in numerals example.11 Hour (24hr system) Minutes Seconds Year\n :return str info\"\"\"\n debug = path_validator(self.path)\n if debug is 0:\n\n last_time_accessed = datetime.fromtimestamp(os.path.getatime(self.path)).strftime(\"%c\")\n creation_time = datetime.fromtimestamp(os.path.getctime(self.path)).strftime(\"%c\")\n size_in_bytes = os.path.getsize(self.path)\n \"\"\"df=pd.DataFrame()\n df['file_name']=self.path\n df['creation_time']=creation_time\n df['last_access_time']=last_time_accessed\n df['size_in_bytes']=size_in_bytes\n print(df)\"\"\"\n info = f\"\"\"\n Information about: {os.path.basename(self.path)}\n Location: {self.path}\n Size in bytes: {size_in_bytes} bytes\n Creation time: {creation_time}\n Last Access Time: {last_time_accessed}\n \"\"\"\n print(info)\n return info\n else:\n raise FileError(\"The given path points to a dir not a file or the given path is invalid !!\")\n\n @staticmethod\n def create_folder(path):\n global msg\n try:\n os.makedirs(path)\n msg = 'success'\n print(msg)\n except OSError as e:\n msg = 'failed '\n print(e, file=sys.stderr)\n\n @staticmethod\n def file_sorter(path, file_type='', sort_method='alphabetical'):\n \"\"\"\n takes a path as its param & sorts all of the files in the given dir and print them in their alphabetical order\n file_type: optional param if the user wants to sort specific types of files\n nb:not yet finished\n :param sort_method:alphabetical\n :param path:\n :param file_type:\n :return: list of the sorted files\n \"\"\"\n list_ = []\n\n if os.path.exists(path) and os.path.isdir(path):\n # check whether the path points to an existing\n # dir else raise a FileError\n # scan through the dir\n for entry in os.scandir(path):\n if entry.is_file():\n list_.append(entry.name)\n item = [str(item).capitalize() for item in list_]\n item.sort()\n print(item)\n return item\n\n else:\n raise FileError(\"The given path points to a file not a dir or the given path is invalid !!\")\n\n @staticmethod\n def file_open_default(path: str):\n \"\"\"\n uses the default applications present to launch some files example pdfs ,images, audios & videos\n :param path: path of the file to be opened\n :return:\n \"\"\"\n if os.path.exists(path) and os.path.isfile(path):\n click.launch(path, locate=True)\n else:\n raise FileNotFoundError(\"The file does not exist!\")\n\n @staticmethod\n def file_search(pattern='.*', file_name='', path=os.getcwd()):\n \"\"\"\n search for file in the current dir path : current dir\n pattern: example *.py (any file ending with .py) or .*\n (any file starting with . eg .bashrc patterns *.txt / ?.gif/ .c*\n file_name: name of the file you are looking for\n recursive: False\n :param pattern:\n :param file_name:\n :param path:\n :return:\n \"\"\"\n\n global list_\n with os.scandir(os.getcwd()) as entries:\n for entry in entries:\n list_ = glob.glob(pattern)\n if not list_:\n for entry in os.scandir(os.getcwd()):\n if entry.name == file_name:\n print(entry.name)\n else:\n raise FileNotFoundError('The pattern/filename given does not match any file')\n for file in list_:\n print(file)\n return file\n\n @staticmethod\n def delete_files_folder(path: str):\n \"\"\"\n deletes files or dirs in the given path\n :param path:\n :return: msg success or failure\n \"\"\"\n msg = ''\n if os.path.exists(path) and os.path.isfile(path):\n os.remove(path)\n msg = f'success, {os.path.basename(path)} deleted successfully'\n elif os.path.exists(path) and os.path.isfile(path):\n os.rmdir(path)\n msg = f'{os.path.dirname(path)} deleted successfully !'\n else:\n msg = f\"\"\"an error occurred deletion failed .The {os.path.dirname(\n path)} path does not exist or the {os.path.basename(\n path)} file does not exist or it is already deleted!\"\"\"\n print(msg)\n return msg\n\n @staticmethod\n def copy_files(src: str, dst: str, stat_info=False):\n \"\"\"\n # src is the path of the file whose contents are to be copied\n # dst is the path of he file/ dir where the contents are copied to\n # assert that the path actually exists and the src is not a directory\n # stat_info: False the stat_info of the src file is not shown if True then it is shown\n :param src:\n :param dst:\n :param stat_info:\n :return: msg:success or failure\n \"\"\"\n global msg\n if os.path.isfile(src) and os.path.exists(src) and os.path.getsize(src) > 0 and os.path.exists(dst):\n try:\n if stat_info:\n path_ = shutil.copy(src, dst)\n creation_time = datetime.fromtimestamp(os.path.getctime(path_)).strftime(\"%c\")\n last_access_time = datetime.fromtimestamp(os.path.getatime(path_)).strftime(\"%c\")\n size_in_bytes = os.path.getsize(path_)\n msg = f'''\n Successfully copied to : {path_}\n Information about: {os.path.basename(path_)}\n Creation time: {creation_time}\n Last Acess Time: {last_access_time}\n File_size(bytes): {size_in_bytes}\n '''\n\n print(msg)\n else:\n path_ = shutil.copy2(src, dst)\n msg = f'successfully copied to: {path_}'\n print(msg)\n except shutil.Error as e:\n msg = 'failure'\n print(e, file=sys.stderr)\n else:\n msg = 'failure'\n raise FileCopyingError(f\"The {src} is a directory or the {src}/{dst} do not exist!! \")\n return msg\n\n @staticmethod\n def copy_directory(src: str, dst: str):\n \"\"\"\n # src is the path of the dir whose contents are to be copied\n # dst is the path of the dir where the contents are copied to,\n # note: the dst must not exist\n # assert that the path actually exists and the src is not a directory\n :param src: source path\n :param dst: destination path\n :return: msg:success or failure\n \"\"\"\n global msg\n if os.path.exists(src) and os.path.isdir(src):\n if not os.path.exists(dst):\n try:\n path_ = shutil.copytree(src, dst)\n creation_time = datetime.fromtimestamp(os.path.getctime(path_)).strftime(\"%c\")\n last_access_time = datetime.fromtimestamp(os.path.getatime(path_)).strftime(\"%c\")\n msg = f'''\n Successfully copied to : {path_}\n Information about: {os.path.basename(path_)}\n Creation time: {creation_time}\n Last Acess Time: {last_access_time}\n '''\n print(msg)\n except shutil.Error as e:\n msg = 'failure'\n print(e, file=sys.stderr)\n else:\n raise FileCopyingError(f\"{dst} exist! The destination folder should not exist\")\n else:\n raise FileCopyingError(f\"The {src} does not exist or it is not a dir!!!\")\n\n # -----------------------\n # CSV File Functions\n # -----------------------\n def writing_csv(self):\n \"\"\"create a csv in the path given\n if the given path does not point to an existing csv file create a new csv file\n else append the data given to the existing csv file\n assert that the path exists else raise an os_error\"\"\"\n try:\n if os.path.exists(self.path) and os.path.isfile(self.path):\n # there exists a file in the given path thus\n # just append the data\n with open(self.path, newline='', mode='a') as f:\n appender = csv.writer(f, delimiter=self.delimiter_)\n for line in self.data:\n appender.writerow(line)\n print(\"data written successfully\")\n # end of data\n elif os.path.exists(self.path) and os.path.isdir(self.path):\n # there is no file in the existing dir\n # so create a new csv file\n file_name = self.path + '/' + self.file_name\n if not file_name.endswith('.csv'):\n raise FileNamingError('The filename must end with a .csv')\n # using the wrong suffix raise a FileNamingError else write a new file in the given path\n with open(file_name, newline='', mode='w') as f:\n writer = csv.writer(f, delimiter=self.delimiter_)\n for line in self.data:\n writer.writerow(line)\n print(\"data written successfully\")\n else:\n print(\"failed to write data\", file=sys.stderr)\n raise BasicWritingError(\"The path given is not valid or the path does not point to an existing file\")\n\n except csv.Error as e:\n print(e)\n\n def write_csv_from_dict(self, dic: dict):\n \"\"\"\n create a csv file from a dictionary\n :param dic:\n :return: msg\n \"\"\"\n global msg\n if os.path.exists(self.path):\n try:\n df = pd.DataFrame.from_dict(dic, orient=\"index\")\n df.to_csv(self.path)\n msg = f\"\"\"\n Data :{dic} written successfully\n \"\"\"\n except BasicWritingError as e:\n msg = \"failed\"\n print(e)\n else:\n msg = \"failed\"\n raise InvalidPathError(f\"The path {self.path} given is invalid\")\n return msg\n\n def read_csv_data(self):\n try:\n with open(self.path, newline='') as csv_data:\n content = csv.reader(csv_data, delimiter=self.delimiter_)\n for row in content:\n if row == '':\n break\n print(row)\n print('')\n print(\"data written successfully\")\n except csv.Error as e:\n print(e, file=sys.stderr)\n\n def read_csv_from_dict(self):\n if os.path.exists(self.path) and os.path.isfile(self.path):\n try:\n with open(self.path, newline='') as csv_data:\n reader = csv.DictReader(csv_data)\n for row in reader:\n print(row)\n except csv.Error as e:\n print(e)\n else:\n raise ReadingError(f\"The path : {self.path} given does not point to an existing file or does not exist!\")\n\n def convert_csv_to_dict(self):\n if os.path.isfile(self.path) and os.path.exists(self.path):\n try:\n data = pd.read_csv(self.path)\n data = data.to_dict()\n print(data)\n except csv.Error as e:\n print(e, file=sys.stderr)\n else:\n raise BasicWritingError(f\"The path: {self.path} does not exist or does not point to an existing file\")\n\n # -----------------------\n # PDF File Functions\n # -----------------------\n\n def pdf_reader(self, page_number=0):\n \"\"\"\n nb: This function may not work well with all types of pdf thus is does not open call\n file_open_default\n :param page_number:\n :return:\n \"\"\"\n if os.path.exists(self.path) and os.path.isfile(self.path):\n content = PdfFileReader(self.path)\n content = content.getPage(page_number)\n page_content = content.extractText()\n print(page_content)\n else:\n raise ReadingError(f\"The path : {self.path} given does not point to an existing file or does not exist!\")\n\n def extract_information(self):\n\n if os.path.isfile(self.path) and os.path.exists(self.path):\n with open(self.path, 'rb') as f:\n pdf = PdfFileReader(f)\n information = pdf.getDocumentInfo()\n number_of_pages = pdf.getNumPages()\n txt = f'''\n\n Information about {self.path}: \n Author: {information.author}\n Creator: {information.creator}\n Subject: {information.subject}\n Title: {information.subject}\n Number of pages: {number_of_pages}\n\n '''\n print(txt)\n return information\n else:\n\n raise BasicWritingError(\n f\"The path : {self.path} given does not point to an existing file or does not exist!\")\n\n @staticmethod\n def create_watermark(input_pdf, output, watermark):\n \"\"\"\n\n :param input_pdf:\n :param output:\n :param watermark:\n :return:\n \"\"\"\n watermark_obj = PdfFileReader(watermark)\n watermark_page = watermark_obj.getPage(0)\n pdf_reader = PdfFileReader(input_pdf)\n pdf_writer = PdfFileWriter()\n for page in range(pdf_reader.getNumPages()):\n page = pdf_reader.getPage(page)\n page.mergePage(watermark_page)\n pdf_writer.addPage(page)\n try:\n with open(output, 'wb') as out:\n pdf_writer.write(out)\n except Exception as e:\n msg = \"failed to create a watermark the file \"\n print(msg)\n print(e)\n\n @staticmethod\n def add_encrypt(input_pdf, output_pdf, password):\n \"\"\"\n encrypts a pdf with the password of your choice\n :param input_pdf: the path of the pdf you want to encrypt\n :param output_pdf: the path of where you want to save the pdf,the input_pdf path can be the same as the output_pdf path\n :param password: your desired password\n :return:\n \"\"\"\n pdf_writer = PdfFileWriter()\n pdf_reader = PdfFileReader(input_pdf)\n for page in range(pdf_reader.getNumPages()):\n pdf_writer.addPage(pdf_reader.getPage(page))\n pdf_writer.encrypt(user_pwd=password, owner_pwd='', use_128bit=True)\n try:\n with open(output_pdf, 'wb') as f:\n pdf_writer.write(f)\n msg = \"successfully encrypted\"\n print(msg)\n except Exception as e:\n msg = \"failed to encrypt the file \"\n print(msg)\n print(e)\n","sub_path":"file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":20200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"63811754","text":"\r\n\"\"\"\r\n Copyright (c) 2005-2019 Colin Pearse.\r\n All scripts are free in the binscripts repository but please refer to the\r\n LICENSE file at the top-level directory for the conditions of distribution.\r\n\r\n Name: verbose.py\r\n Description: Implement verbosity. Full description and test at the bottom.\r\n\"\"\"\r\n\r\nfrom __future__ import print_function \r\nimport sys\r\nimport os\r\nimport time\r\nimport datetime\r\n\r\n__author__ = \"Colin Pearse \"\r\n__status__ = \"beta\"\r\n__version__ = \"0.0.1\"\r\n__date__ = \"20 February 2018\"\r\n\r\nvlevels = [1]\r\nvpathname = None\r\nvfh = sys.stderr\r\n\r\n\r\ndef splitLevelsList(levels):\r\n strlevels = [l for l in levels if type(l) is str]\r\n numlevels = [l for l in levels if type(l) is int]\r\n if numlevels == []:\r\n numlevel = None\r\n else:\r\n numlevel = max(numlevels)\r\n return numlevel,strlevels\r\n\r\ndef splitLevelsStr(levels,separator=','):\r\n strlevels = levels.split(separator)\r\n numlevels = [n for n in strlevels if n.isdigit() is True]\r\n strlevels = [n for n in strlevels if n.isdigit() is False]\r\n if numlevels == []:\r\n numlevel = None\r\n else:\r\n numlevels = map(int,numlevels)\r\n numlevel = max(numlevels)\r\n return numlevel,strlevels\r\n\r\ndef splitLevelsInt(level):\r\n return level,[]\r\n\r\n# levels can be a list [2,\"blah\",\"pod\"] or str \"2,blah,pod\" or int 2\r\ndef splitLevels(levels,separator=','):\r\n ''' split verbosity levels into int and strs\r\n\r\n >>> splitLevels([1,\"blah\",\"pod\"])\r\n (1, ['blah', 'pod'])\r\n\r\n >>> splitLevels(\"1,blah,pod\")\r\n (1, ['blah', 'pod'])\r\n\r\n >>> splitLevels(\"1:blah:pod\",separator=':')\r\n (1, ['blah', 'pod'])\r\n\r\n >>> splitLevels(99)\r\n (99, [])\r\n\r\n >>> splitLevels(\"blah,pod,6,9,pie\")\r\n (9, ['blah', 'pod', 'pie'])\r\n\r\n >>> splitLevels(\"info\")\r\n (None, ['info'])\r\n '''\r\n if type(levels) is list:\r\n return splitLevelsList(levels)\r\n elif type(levels) is str:\r\n return splitLevelsStr(levels,separator)\r\n elif type(levels) is int:\r\n return splitLevelsInt(levels)\r\n else:\r\n return 1,[]\r\n\r\n# levels can be a list or str - see splitLevels\r\ndef setLevels(levels,separator=','):\r\n global vlevels\r\n ivlevels,svlevels = splitLevels(levels)\r\n vlevels = [ivlevels] + svlevels\r\n\r\n# if I've already opened a file, close it before setting a new fh\r\ndef setStream(fh):\r\n global vpathname\r\n global vfh\r\n if vpathname is not None:\r\n closeFile()\r\n vfh = fh\r\n\r\n# if I've already opened a file, close it before opening the new one\r\ndef openFile(filename,mode=\"a\"):\r\n global vpathname\r\n global vfh\r\n if vpathname is not None:\r\n closeFile()\r\n vpathname = os.path.abspath(filename)\r\n vfh = open(vpathname,mode)\r\n\r\n# don't close if vpathname is None, implying vfh was not opened by me\r\ndef closeFile():\r\n global vpathname\r\n global vfh\r\n if vpathname is not None:\r\n try:\r\n vfh.close()\r\n vpathname = None\r\n except:\r\n sys.exit(\"cannot close %s\" % (vpathname))\r\n\r\ndef showLabel(labels,dt,mod,func):\r\n label = \"\"\r\n if \"dt\" in labels:\r\n label = label + \"%s: \"%(dt)\r\n if \"mod\" in labels:\r\n label = label + \"%s: \"%(mod)\r\n if \"func\" in labels:\r\n label = label + \"%s: \"%(func)\r\n return label\r\n\r\ndef isLevel(levels):\r\n ilevel,slevels = splitLevels(levels)\r\n ivlevel,svlevels = splitLevels(vlevels)\r\n if (ivlevel is not None and ilevel is not None and ivlevel >= ilevel) or set(slevels) & set(svlevels):\r\n return True\r\n else:\r\n return False\r\n\r\n# NOTE: don't think this label is very useful, but just in case...\r\n# ilevel,slevels = splitLevels(levels)\r\n# showlevels = \"%s\" % (','.join([str(ilevel)] + slevels))\r\ndef verbose(levels,message,tee=None,labels=[\"dt\",\"mod\",\"func\"],teelabels=[\"dt\",\"mod\",\"func\"]):\r\n ts = time.time()\r\n dt = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\r\n mod = os.path.basename(sys._getframe(1).f_code.co_filename)\r\n func = sys._getframe(1).f_code.co_name\r\n if isLevel(levels):\r\n print (\"%s%s\" % (showLabel(labels,dt,mod,func),message), file=vfh)\r\n if tee is not None:\r\n print (\"%s%s\" % (showLabel(teelabels,dt,mod,func),message), file=tee)\r\n\r\n\r\n\"\"\"\r\nDescription:\r\nAllows granular verbose messaging. verbose.verbose() commands can be used everywhere\r\nin the code, but only activated with a specific level or multiple strings.\r\nFor example: myprog.py -v 5,read,boot ... would display all messages level 5 and under\r\nplus those labelled \"read\" and \"boot\" which might be a very specified area of the code\r\nyou wish to debug.\r\n\r\nCode:\r\nimport verbose\r\nverbose.setLevels(vlist) # vlist can be a str: \"2,readcmds,blah\" or list [2,\"readcmds\",\"blah\"]\r\nverbose.openFile(\"log/verbose_test.log\",\"w\") # output to a file (open with truncate); default: sys.stderr output\r\nverbose.verbose([2,\"loop\"],\"message\") # output if verbose level >= 2 or one verbose string is \"loop\"\r\nverbose.verbose([\"info\"],\"message\") # output if one verbose string is \"info\"\r\nverbose.verbose([\"info\"],\"message\",tee=sys.stderr) # as above, but write to stderr too\r\nverbose.verbose([99],\"message\") # output if verbose level >= 99\r\nverbose.verbose(\"99\",\"message\") # output if verbose level >= 99\r\nverbose.verbose(99,\"message\") # output if verbose level >= 99\r\nverbose.isLevel(\"99,blah\") # True if verbose level >= 99 or verbose str is \"blah\"\r\nverbose.setStream(sys.stderr) # will call closeFile() if necessary before redirecting\r\nverbose.closeFile()\r\n\r\nTesting (doctest):\r\npython -m doctest verbose.py -v\r\n\r\nTesting (manual):\r\npython bin/verbose.py 1 # 2 tests below should be displayed\r\npython bin/verbose.py 2 # 3 tests below should be displayed\r\npython bin/verbose.py 3 # 4 tests below should be displayed\r\npython bin/verbose.py 3 show # 5 tests below should be displayed\r\npython bin/verbose.py nothing # no tests below should be displayed\r\n\r\nEg output for \"3 show\":\r\n2018-02-28 19:33:06: myTestFunc: True for test: [1, 'show']\r\n2018-02-28 19:33:06: myTestFunc: True for test: [2, 'func']\r\n2018-02-28 19:33:06: myTestFunc: True for test: [3, 'func']\r\n2018-02-28 19:33:06: myTestFunc: True for test: [1]\r\n2018-02-28 19:33:06: myTestFunc: True for test: ['show']\r\n\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n def myTestFunc():\r\n tests = [[1,\"show\"],\r\n [2,\"func\"],\r\n [3,\"func\"],\r\n 1,\r\n \"show\"]\r\n for test in tests:\r\n print (\"test:\",test)\r\n for test in tests:\r\n verbose(test,\"%s for test: %s\" % (isLevel(test),test))\r\n #verbose(test,\"%s for test: %s\" % (isLevel(test),test), tee=sys.stderr)\r\n\r\n if len(sys.argv) >= 2:\r\n setLevels(sys.argv[1])\r\n #openFile(\"log/verbose_test.log\",\"w\")\r\n #setStream(sys.stdout)\r\n #setStream(sys.stderr)\r\n print (\"vlevels:\",vlevels)\r\n print (\"vpathname:\",vpathname)\r\n myTestFunc()\r\n #closeFile()\r\n\r\n","sub_path":"binpy/verbose.py","file_name":"verbose.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"613490219","text":"# Uses python3\nimport sys\n\ndef get_change(money):\n coins = [1,3,4]\n inf = 1000\n \n if money == 0:\n return 0\n minNumCoins = [inf]*(money+1)\n minNumCoins[0]=0\n for m in range(1,money+1): \n for coin in coins:\n if m >= coin:\n num_coins = minNumCoins[m - coin]\n if (num_coins')[0].split('=')[0].split('<')[0].split('!')[0]\n raw_requirements.add(raw_req)\nfiltered_test_requirements = set()\nfor req in TEST_REQUIREMENTS:\n raw_req = req.split('>')[0].split('=')[0].split('<')[0].split('!')[0]\n if raw_req not in raw_requirements:\n filtered_test_requirements.add(req)\nTEST_REQUIREMENTS = list(filtered_test_requirements)\n\nsetup(\n # -- meta information --------------------------------------------------\n name=__meta__.__package__,\n version=__meta__.__version__,\n description=__meta__.__description__,\n long_description=README + '\\n\\n' + HISTORY,\n author=__meta__.__author__,\n maintainer=__meta__.__maintainer__,\n maintainer_email=__meta__.__email__,\n contact=__meta__.__maintainer__,\n contact_email=__meta__.__email__,\n url=__meta__.__url__,\n platforms=__meta__.__platforms__,\n license=__meta__.__license__,\n keywords=__meta__.__title__ + \", Authentication, AuthN, Birdhouse\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n\n # -- Package structure -------------------------------------------------\n packages=[__meta__.__package__],\n package_dir={__meta__.__package__: __meta__.__package__},\n include_package_data=True,\n install_requires=REQUIREMENTS,\n dependency_links=LINKS,\n zip_safe=False,\n\n # -- self - tests --------------------------------------------------------\n # test_suite='nose.collector',\n # test_suite='tests.test_runner',\n # test_loader='tests.test_runner:run_suite',\n test_suite='tests',\n tests_require=TEST_REQUIREMENTS,\n\n # -- script entry points -----------------------------------------------\n entry_points=\"\"\"\\\n [paste.app_factory]\n main = magpie.app:main\n [console_scripts]\n \"\"\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631579600","text":"import cv2\nimport numpy as np\nimport os\nimport sys\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\n#Total number of categories in your data\nNUM_CATEGORIES=6\n#Resize of your image\nIMG_WIDTH = 400\nIMG_HEIGHT = 400\n#Identifier for your data i.e: if you want to give a more descriptive name \nclass_names = ['Candado', 'Tostadora', 'Tornillo', 'Micro', 'Tanque', 'Hazard']\n#Test percentage to divide into train and validation\nTEST_SIZE=0.5\n\n\ndef main():\n model = tf.keras.models.load_model('modelo.h5')\n images, labels = load_data(\"database\\\\validation\")\n # Split data into training and testing sets\n labels = tf.keras.utils.to_categorical(labels)\n images_test, images_train, labels_test, labels_train = train_test_split(np.array(images), np.array(labels), test_size=TEST_SIZE)\n #Predict all images in images_test\n predictions = model.predict(images_test)\n\n #print('La imagen predecida es: ',np.argmax(predictions[0]))\n #print('La imagen real es: ',np.argmax(labels_test[0]))\n\n #Get just one image from the predicions and plot its results\n #i = 4\n #plt.figure(figsize=(6,3))\n #plt.subplot(1,2,1)\n #plot_image(i, predictions[i], labels_test, images_test)\n #plt.subplot(1,2,2)\n #plot_value_array(i, predictions[i], labels_test)\n #plt.show()\n\n # Plot X test images, their predicted labels, and the true labels.\n # Color correct predictions in Blue and incorrect predictions in Red, Low predictions Gray.\n #Quantity of images to show\n num_rows = 7\n num_cols = 7\n num_images = num_rows*num_cols\n plt.figure(figsize=(4*num_cols, 2*num_rows))\n for i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n plot_image(i, predictions[i], labels_test, images_test)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n plot_value_array(i, predictions[i], labels_test)\n plt.tight_layout()\n plt.show()\n\n#Functions Load Data\ndef load_data(data_dir):\n #Initialize list to store images and labels\n images = []\n labels = []\n #Get the path of the data\n filepath = os.path.abspath(data_dir)\n #Iterate through all folder categories\n for i in range(NUM_CATEGORIES):\n #Join the path of the data with the exact category folder to iterate\n #Change to that NEW path\n os.chdir(os.path.join(filepath, str(i)))\n #Iterate through all the images inside that category\n for image in os.listdir(os.getcwd()):\n #Read that image as an array\n img = cv2.imread(image, cv2.IMREAD_COLOR)\n #If it has data\n if img.size != 0:\n #Resize it accordingly\n img = cv2.resize(img, (IMG_WIDTH, IMG_HEIGHT))\n #Append information of image and category\n images.append(img)\n labels.append(i)\n #Change path to folder to sotre the model on root\n os.chdir(filepath)\n return (images, labels)\n\n#Plot images predicted\ndef plot_value_array(i, predictions_array, true_label):\n predictions_array, true_label = predictions_array, true_label[i]\n plt.grid(False) #Turn off grid\n plt.xticks(range(NUM_CATEGORIES)) #X label with 43 ticks as we have 43 possible categories\n plt.yticks([]) #Without y ticks\n thisplot = plt.bar(range(NUM_CATEGORIES), predictions_array, color=\"#777777\") #Plot the bar\n plt.ylim([0, 1]) #Y label limit from 0 to 1 i.e: 0 no match, 1 fully identified\n predicted_label = np.argmax(predictions_array) #Get the index of the max value\n label = np.argmax(true_label) #Get the index of the max value\n #MAtch the values accordingly if it is a value inside predicted RED, label BLUE\n thisplot[predicted_label].set_color('red')\n thisplot[label].set_color('blue')\n\ndef plot_image(i, predictions_array, true_label, img):\n predictions_array, true_label, img = predictions_array, true_label[i], img[i]\n plt.grid(False) #Trun off grids\n plt.xticks([]) #Without axis\n plt.yticks([])\n\n plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\n #Store de index of the max value i.e: the probable image\n predicted_label = np.argmax(predictions_array) \n #Store de index of the max label i.e: the correct image\n label = np.argmax(true_label) \n #If the image was identified correctly\n if predicted_label == label:\n #Plot it blue\n color = 'blue'\n #If not plot it red\n else:\n color = 'red'\n #The label for the image: The predicted image, the percentage of accuracy, the ID.\n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n 100*np.max(predictions_array),\n class_names[label]),\n color=color)\n\nif __name__ == \"__main__\":\n main()","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"320311542","text":"BASIC_TAX_RATE = 0.011\nSEF_RATE = 0.01\nSH_RATE = 0.5\n\n\ndef compute_discount_rate(month):\n if month == 1:\n discount_rate = 0.2\n elif month <= 3:\n discount_rate = 0.1\n else:\n discount_rate = 0\n return discount_rate\n\n\ndef compute_penalty_rate(curr_date, prev_date):\n penalty_rate = 0\n if curr_date.month > 3:\n for year in range(curr_date.year, prev_date.year - 1, -1):\n # current year\n if year == curr_date.year:\n if curr_date.year == prev_date.year:\n for month in range(1, curr_date.month + 1):\n penalty_rate += 2\n break\n else:\n for month in range(1, 12 + 1):\n penalty_rate += 2\n # previous year\n elif year == prev_date.year:\n for month in range(1, prev_date.month + 1):\n penalty_rate += 2\n # middle years\n else:\n for month in range(1, 12 + 1):\n penalty_rate += 2\n if penalty_rate >= 72:\n penalty_rate = 72\n return penalty_rate / 100\n\n\ndef compute_sh_tax(assessed_value, type, SH_RATE):\n if type == 'LOT' and assessed_value > 50000:\n sh = assessed_value * SH_RATE\n else:\n sh = 0\n return sh\n\n\ndef compute_discount(tax, month):\n discount_rate = compute_discount_rate(month)\n return tax * discount_rate\n\n\ndef classify_query(query):\n import re\n # tax dec no, 2008-10L-1234\n if re.search(r'(^[0-9]{4}-[0-9]{1,2}[BLM]-[0-9]{4}$)', query):\n return 'tax_dec_no'\n # tax dec no, 12B-0123\n if re.search(r'(^[0-9]{1,2}[BLM]-[0-9]{4}$)', query):\n return 'tax_dec_no'\n # PIN No, 123-123-123-123\n if re.search(r'(^[0-9]{3}-([0-9]{3}-)*[0-9]{3}$)', query):\n return 'pin_no'\n return None\n","sub_path":"realty.py","file_name":"realty.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"34430158","text":"import psutil\nimport argparse\nimport datetime\nimport csv\nimport time\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--file',\n help='input file name (required)',\n type=str)\nargs = parser.parse_args()\n\n# pull args out\nfilename = args.file\n\nwith open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n mem_used = 0\n for row in reader:\n mem_row = int(row[4])/1024/1024/1024\n mem_used = max(mem_row,mem_used)\n\n mem_str = \"Max memory used: %.3f GB\" % mem_used\n print(mem_str)\n","sub_path":"profiling/report_max_memory.py","file_name":"report_max_memory.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"453323200","text":"from configparser import ConfigParser\nfrom pattern.counter import Counter\n\nimport pdb\nimport logging\nimport datetime\nimport math\n\n# create logger\ntl_logger = logging.getLogger(__name__)\ntl_logger.setLevel(logging.DEBUG)\n\nclass TradeList(object):\n '''\n Class that represents a list of Trade objects\n\n Class variables\n ---------------\n tlist : list, Required\n List of Trade objects\n settingf : str, Optional\n Path to *.ini file with settings\n settings : ConfigParser object generated using 'settingf'\n Optional\n ser_data_obj : ser_data_obj, Optional\n ser_data_obj with serialized data\n '''\n\n def __init__(self, tlist, settingf=None, settings=None, ser_data_obj=None):\n self.settingf = settingf\n self.tlist = tlist\n self.ser_data_obj = ser_data_obj\n\n if self.settingf is not None:\n # parse settings file (in .ini file)\n parser = ConfigParser()\n parser.read(settingf)\n self.settings = parser\n else:\n self.settings = settings\n\n def analyze(self):\n '''\n Analyze each of the Trade objects in TradeList depending\n on value of settings.get('counter', 'strats') and add the\n calculated attributes to Trade\n\n :returns\n TradeList\n '''\n\n #these are the strategies that will be analysed using the Counter pattern\n tl_logger.info(\"Strategies that will be analysed: {0}\".format(self.settings.get('counter', 'strats')))\n strats = self.settings.get('counter', 'strats').split(\",\")\n trade_list = []\n for t in self.tlist:\n tl_logger.info(\"Processing trade: {0}-{1}\".format(t.pair, t.start))\n if t.strat in strats:\n if t.entered is False and (not hasattr(t, 'outcome') or math.isnan(t.outcome) is True):\n t.run_trade()\n c = Counter(trade=t,\n settingf=self.settingf,\n settings=self.settings,\n ser_data_obj=self.ser_data_obj,\n init_feats=True)\n tl_logger.debug(\"Counter attributes analysed:{0}\".format(self.settings.get('counter', 'attrbs').split(\",\")))\n attrb_ls = self.settings.get('counter', 'attrbs').split(\",\")\n for a in attrb_ls:\n if hasattr(c, a) is True:\n # add 'a' attribute to Trade object\n setattr(t, a, getattr(c, a))\n else:\n tl_logger.warn(\"Attribute {0} is not defined in Counter object. Skipping...\".format(a))\n setattr(t, a, \"n.a.\")\n else:\n tl_logger.debug(\"Trade.strat ({0}) is not within list of trades to analyse. Skipping...\".format(t.strat))\n trade_list.append(t)\n tl_logger.info(\"Done\")\n tl = TradeList(settingf=self.settingf,\n settings=self.settings,\n tlist=trade_list)\n\n return tl\n\n def win_rate(self, strats):\n '''\n Calculate win rate and pips balance\n for this TradeList. If outcome attrb is not\n defined then it will invoke the run_trade method\n on each particular trade\n\n Parameters\n ----------\n strats : str\n Comma-separated list of strategies to analyse: i.e. counter,counter_b1\n\n :return:\n int : number of successes\n int : number of failures\n pips : pips balance in this TradeList\n '''\n\n strat_l = strats.split(\",\")\n number_s = 0\n number_f = 0\n tot_pips = 0\n for t in self.tlist:\n if t.strat not in strat_l:\n continue\n if not hasattr(t, 'outcome'):\n t.run_trade()\n if t.outcome == 'success':\n number_s += 1\n elif t.outcome == 'failure':\n number_f += 1\n tot_pips += t.pips\n tot_pips = round(tot_pips, 2)\n tot_trades = number_s+number_f\n perc_wins = round(number_s*100/tot_trades, 2)\n perc_losses = round(number_f*100/tot_trades, 2)\n print(\"Tot number of trades: {0}\\n-------------\".format(tot_trades))\n print(\"Win trades: {0}; Loss trades: {1}\".format(number_s, number_f))\n print(\"% win trades: {0}; % loss trades: {1}\".format(perc_wins, perc_losses))\n print(\"Pips balance: {0}\".format(tot_pips))\n\n return number_s, number_f, tot_pips\n\n\n\n","sub_path":"trade_journal/trade_list.py","file_name":"trade_list.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"406474344","text":"import numpy as np\nimport random\n\ndef benchMarkFunc(position):\n ## Rosenbrock function\n a = 0\n ## No idea if b value should be set to 100\n b1 = 100\n return (position[0]**2 + (b1 *(position[1] - position[0]**2)**2))\n\n## initialising variables for particle action\nweightAHigh = 0.9\nweightALow = 0.4\nb = 2\nc = 2\n## haven't understood the use of target or targetError\ntarget = 1\ntargetError = 1e-6\nnumOfParticles = 30\nnumOfIterations = 100\n\n## initialising particle position and velocity\nparticlePos = np.array([np.array([(-1)**(bool(random.getrandbits(1))) * random.random()*20,(-1)**(bool(random.getrandbits(1))) * random.random()*20]) for _ in range(numOfParticles)])\nparticleBestPos = particlePos\n## initiating particleBestPosValue with float inf\n## as the minimal value is required\nparticleBestPosValue = np.array([float('inf') for _ in range(numOfParticles)])\nglobalBestPosValue = float('inf')\nglobalBestPos = np.array([float('inf'),float('inf')])\nparticleVel = np.array([np.array([0,0]) for _ in range(numOfParticles)])\n\n## the algorithm for particle swarm optimisation\nfor iterations in range(numOfIterations):\n for i in range(numOfParticles):\n currentFitness = benchMarkFunc(particlePos[i])\n print(currentFitness, ' ', particlePos[i])\n\n if(particleBestPosValue[i] > currentFitness):\n particleBestPosValue[i] = currentFitness\n particleBestPos[i] = particlePos[i]\n\n if(globalBestPosValue > currentFitness):\n globalBestPosValue = currentFitness\n globalBestPos = particlePos[i]\n\n if(abs(globalBestPosValue - target) < targetError):\n break\n if(iterations > 1000):\n a = weightALow\n else:\n a = weightAHigh\n\n for i in range(numOfParticles):\n newVelocity = (a*particleVel[i] + (b * random.random()) * (particleBestPos[i] - particlePos[i]) + (c * random.random()) * (globalBestPos - particlePos[i]))\n particlePos[i] = newVelocity + particlePos[i]\n\nprint(\"Global Best Position: \", globalBestPos, \" with iteration number \", iterations)\n","sub_path":"pso/psov4.py","file_name":"psov4.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"114725889","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tools\n\n\npathcore = 'D:\\studia\\II stopień\\Praca Magisterska\\wyniki\\\\'\n# folders = ['raw_map', 'averaging_filter_3-3', 'averaging_filter_5-5', 'gaussian_filter_k3', 'gaussian_filter_k5', 'gaussian_filter_k7']\nfolders = ['raw_map', 'averaging_filter_3-3', 'averaging_filter_5-5', 'gaussian_filter_k3', 'gaussian_filter_k5', 'gaussian_filter_k7', 'median_filter_k3', 'median_filter_k5', 'median_filter_k7', 'wiener']\nfiles = ['alpha_map', 'alpha_map_err', 'beta_map', 'beta_map_err']\n\nmaps = []\nfor filter in folders:\n with open (tools.get_map(files=filter, directory=pathcore, extension=files[1]), 'rb') as fp:\n maps.append(pickle.load(fp))\nxmap = np.arange(120)\nymap = np.arange(64)\nfig = plt.figure()\n\nfor i, map in enumerate(maps):\n ax = fig.add_subplot(5, 2, i + 1)\n z = np.array(map)\n # narysowanie beta wymaga thresholdu, ponieważ są duże błędy\n mean = z.mean()\n std = np.std(z)\n #threshold do beta_eff\n # mean = z[np.where(np.logical_and(z > 2000, z < 3000))].mean()\n # std=np.std(z[np.where(np.logical_and(z > 2000, z < 3000))])\n # z_out = np.where(np.logical_or(z < 2000, z > 3000))\n # z[z_out] = mean\n #####################\n # threshold do beta_eff_err\n # mean = z[np.where(np.logical_and(z >= 150, z < 700))].mean()\n # std=np.std(z[np.where(np.logical_and(z >= 150, z < 700))])\n # z_out = np.where(np.logical_or(z <= 150, z > 700))\n # z[z_out] = 0\n #####################\n # threshold do alfa\n # mean = z[np.where(np.logical_and(z >= 0.00002, z < 0.00004))].mean()\n # std=np.std(z[np.where(np.logical_and(z >= 0.00002, z < 0.00004))])\n # z_out = np.where(np.logical_or(z <= 0.00002, z > 0.00004))\n # z[z_out] = mean\n #####################\n # threshold do alfa_err\n mean = z[np.where(np.logical_and(z >= 0, z < 0.00002))].mean()\n std=np.std(z[np.where(np.logical_and(z >= 0, z < 0.00002))])\n z_out = np.where(np.logical_or(z <= 0, z > 0.00002))\n z[z_out] = 0\n #####################\n print(folders[i], ': ', mean, '+/-', std)\n ############################################################\n ax.set_title(folders[i])\n cax = ax.pcolormesh(ymap, xmap, z, cmap='inferno')\n fig.colorbar(cax)\n ax.set_xlim([0,63])\n ax.set_ylim([0,119])\n#histogram błędów\n # ax.hist(z[np.where(np.logical_and(z >= 150, z < 700))], bins='scott') #beta\n # ax.hist(z[np.where(np.logical_and(z > 0, z < 0.00002))], bins='scott') #alfa\n # ax.set_xlim([0,0.00002])\n\nplt.show()","sub_path":"LIT_map_comparison.py","file_name":"LIT_map_comparison.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"400603995","text":"import os\nfrom flask import Flask, app, flash, session\nfrom flask_pymongo import PyMongo\nfrom datetime import date, datetime\n\napp = Flask(__name__)\napp.config[\"MONGO_DBNAME\"] = os.getenv('MONGO_DBNAME')\napp.config[\"MONGO_URI\"] = os.getenv('MONGO_URI')\napp.config[\"SECRET_KEY\"] = os.getenv('SECRET_KEY')\n\nmongo = PyMongo(app)\n\n\n\"\"\"Collections\"\"\"\nstories_collection = mongo.db.stories\nusers_collection = mongo.db.users\nfake_collection = None\n\n\n\"\"\"Helper functions\"\"\"\n\n\ndef list_by_type():\n list_by_type = {}\n ratings = []\n genres = []\n fandoms = []\n authors = []\n if session.get('is_adult') == True:\n selection = stories_collection.find()\n else:\n selection = stories_collection.find( {\"rating\": {\"$nin\": [\"R/Adult/NSFW\", \"Adult/NSFW\"]}})\n for story in selection:\n rating = story['rating']\n genres_in_story = story.get('genres')\n if genres_in_story != []:\n for genre in genres_in_story:\n genre\n fandoms_in_story = story.get('fandoms')\n if fandoms_in_story != []:\n for fandom in fandoms_in_story:\n fandom\n else:\n fandom = \"Fandom not added\"\n author = story['author']\n if rating not in ratings:\n ratings.append(rating)\n if genre not in genres:\n genres.append(genre)\n if fandom not in fandoms:\n fandoms.append(fandom)\n if author not in authors:\n authors.append(author)\n list_by_type.update({\"ratings\": ratings, \"genres\": genres,\n \"fandoms\": fandoms, \"authors\": authors})\n return list_by_type\n\n\ndef story_count():\n story_count = []\n ratings_list = list_by_type()[\"ratings\"]\n genres_list = list_by_type()[\"genres\"]\n fandoms_list = list_by_type()[\"fandoms\"]\n authors_list = list_by_type()[\"authors\"]\n for rating in ratings_list:\n count = stories_collection.count_documents({\"rating\": rating})\n count_rating = {\"rating\": rating, \"total\": count}\n story_count.append(count_rating)\n for genre in genres_list:\n count = stories_collection.count_documents({\"genres\": genre})\n count_genre = {\"genre\": genre, \"total\": count}\n story_count.append(count_genre)\n for fandom in fandoms_list:\n count = stories_collection.count_documents({\"fandoms\": fandom})\n count_fandom = {\"fandom\": fandom, \"total\": count}\n story_count.append(count_fandom)\n for author in authors_list:\n count = stories_collection.count_documents({\"author\": author})\n count_author = {\"author\": author, \"total\": count}\n story_count.append(count_author)\n return story_count\n\n\ndef report(item, reason_given, this_story, reported_by):\n stories_collection.find_one_and_update({\"url\": this_story}, {'$push': {\"reports\": {\"item_reported\": item, \"reported_by\": reported_by, \"reason_given\": reason_given}}}, upsert=True)\n return flash(\"Report sent to admins.\")\n\n\ndef calculate_age(born):\n today = date.today()\n bday = datetime.strptime(born, '%Y-%m-%d')\n age = today.year - bday.year - ((today.month, today.day) < (bday.month, bday.day))\n return age","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"608623435","text":"from __future__ import absolute_import, unicode_literals\nfrom __future__ import print_function\n\nfrom builtins import str\nfrom builtins import map\nimport random\nimport time\nimport base64\nimport mimetypes\nimport signal\n\nimport os\nimport time\nfrom celery.decorators import task\nfrom config.settings.config_file_name_to_run import CONFIG_FILE_NAME\nfrom django.conf import settings\nimport datetime\nimport simplejson as json\nimport copy\nfrom api.helper import get_random_model_id, get_mails_from_outlook\nfrom django.contrib.auth.models import User\n\n\n@task(name=\"sum_two_numbers\")\ndef add(x, y):\n print(\"crazy bird {0}{1}\".format(x, y))\n return x + y\n\n\n@task(name=\"multiply_two_numbers\")\ndef mul(x, y):\n total = x * (y * random.randint(3, 100))\n return total\n\n\n@task(name=\"sum_list_numbers\")\ndef xsum(numbers):\n return sum(numbers)\n\n\nimport subprocess\nimport re\nimport requests\nfrom api.models import Job, Dataset, Score, Insight, Trainer, StockDataset, Robo, DatasetScoreDeployment, CustomApps, \\\n OutlookToken\n\n\n@task(name='hum_se_hai_zamana_sara', queue=CONFIG_FILE_NAME)\ndef submit_job_separate_task(command_array, slug):\n import subprocess, os\n my_env = os.environ.copy()\n if settings.HADOOP_CONF_DIR:\n my_env[\"HADOOP_CONF_DIR\"] = settings.HADOOP_CONF_DIR\n my_env[\"HADOOP_USER_NAME\"] = settings.HADOOP_USER_NAME\n\n try:\n cur_process = subprocess.Popen(command_array, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=-1,\n universal_newlines=True, env=my_env)\n print(cur_process)\n except Exception as e:\n from api.helper import get_db_object\n model_instance = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n model_instance.status = \"KILLED\"\n model_instance.message = json.dumps({'message': 'Killed while submitting job',\n 'error': e})\n model_instance.save()\n return \"Failed\"\n\n for line in iter(lambda: cur_process.stdout.readline(), ''):\n print(line.strip())\n line = line.strip()\n match = re.search('Submitted application (.*)$', line)\n if match:\n application_id = match.groups()[0]\n print((\"<------------------------ YARN APPLICATION ID ---------------------->\", application_id))\n print((\"<------------------------ YARN APPLICATION ID ---------------------->\", application_id))\n from api.helper import get_db_object\n\n model_instance = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n model_instance.url = application_id\n model_instance.save()\n # Break statement is commented in order to get the complete log of the subprocess\n # break\n\n\n'''\n time.sleep(10)\n exists = os.path.isfile('/tmp/SparkDriver.log')\n while( exists != True):\n exists = os.path.isfile('/tmp/SparkDriver.log')\n time.sleep(1)\n with open(\"/tmp/SparkDriver.log\") as file:\n data = file.readlines()\n for line in data:\n match = re.search('Submitted application (.*)$', line)\n if match:\n application_id = match.groups()[0]\n print (\"############################## Application ID ################################# \", application_id)\n from api.helper import get_db_object\n model_instance = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n model_instance.url = application_id\n model_instance.save()\n dist_file_name = \"/tmp/\" + str(application_id) + \".driver.log\"\n os.rename(\"/tmp/SparkDriver.log\",dist_file_name)\n break\n'''\n\n\ndef submit_job_separate_task1(command_array, slug):\n import subprocess, os\n my_env = os.environ.copy()\n if settings.HADOOP_CONF_DIR:\n my_env[\"HADOOP_CONF_DIR\"] = settings.HADOOP_CONF_DIR\n my_env[\"HADOOP_USER_NAME\"] = settings.HADOOP_USER_NAME\n cur_process = subprocess.Popen(command_array, stderr=subprocess.PIPE, env=my_env)\n print(cur_process)\n # TODO: @Ankush need to write the error to error log and standard out to normal log\n for line in iter(lambda: cur_process.stderr.readline(), ''):\n # print(line.strip())\n match = re.search('Submitted application (.*)$', line.decode(\"utf-8\"))\n if match:\n application_id = match.groups()[0]\n from api.helper import get_db_object\n\n model_instance = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n model_instance.url = application_id\n model_instance.save()\n break\n\n\n@task(name='write_into_databases', queue=CONFIG_FILE_NAME)\ndef write_into_databases(job_type, object_slug, results):\n from api import helper\n # import json\n from api.helper import get_db_object\n from api.views import chart_changes_in_metadata_chart, add_slugs\n\n if job_type in [\"metadata\", \"subSetting\"]:\n dataset_object = get_db_object(model_name=Dataset.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n dataset_object.status = \"FAILED\"\n dataset_object.save()\n return results\n columnData = results['columnData']\n for data in columnData:\n # data[\"chartData\"] = helper.find_chart_data_and_replace_with_chart_data(data[\"chartData\"])\n card_data = data[\"chartData\"]\n if 'dataType' in card_data and card_data['dataType'] == 'c3Chart':\n chart_data = card_data['data']\n final_chart_data = helper.decode_and_convert_chart_raw_data(chart_data, object_slug=object_slug)\n data[\"chartData\"] = chart_changes_in_metadata_chart(final_chart_data)\n data[\"chartData\"][\"table_c3\"] = []\n\n results['columnData'] = columnData\n # results['possibleAnalysis'] = settings.ANALYSIS_FOR_TARGET_VARIABLE\n da = []\n for d in results.get('sampleData'):\n da.append(list(map(str, d)))\n results['sampleData'] = da\n # results[\"modified\"] = False\n\n dataset_object.meta_data = json.dumps(results)\n dataset_object.analysis_done = True\n dataset_object.status = 'SUCCESS'\n dataset_object.save()\n print(\"Every thing went well. Lets see if more can be done\")\n check_if_dataset_is_part_of_datascore_table_and_do_we_need_to_trigger_score(dataset_object.id)\n #### Check if model job needs to be triggered for email AutoML ###\n check_if_autoML_model_job_needs_to_be_triggered(dataset_object.id)\n return \"Done Succesfully.\"\n elif job_type == \"master\":\n insight_object = get_db_object(model_name=Insight.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n insight_object.status = \"FAILED\"\n insight_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n insight_object.data = json.dumps(results)\n insight_object.analysis_done = True\n insight_object.status = 'SUCCESS'\n insight_object.save()\n return \"Done Succesfully.\"\n elif job_type == \"model\":\n trainer_object = get_db_object(model_name=Trainer.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results or \"model_summary\" not in results:\n trainer_object.status = \"FAILED\"\n trainer_object.save()\n #------------------------------------------------------------------#\n #Sending failure mail on autoML model failure\n if trainer_object.mode == 'autoML':\n outlook_autoML_failure_mail(\n trainer_object_id=trainer_object.id,\n error='ML-failure',\n mail_id=trainer_object.email\n )\n #------------------------------------------------------------------#\n return results\n\n results['model_summary'] = add_slugs(results['model_summary'], object_slug=object_slug)\n trainer_object.data = json.dumps(results)\n trainer_object.analysis_done = True\n trainer_object.status = 'SUCCESS'\n trainer_object.save()\n\n if 'model_management_summary' in results:\n train_algo_details = results['model_management_summary']\n for algo_detail in train_algo_details:\n if len(algo_detail['listOfNodes']) > 1:\n from api.utils import TrainAlgorithmMappingSerializer\n temp_data = dict()\n temp_data['name'] = get_random_model_id(algo_detail['name'])\n temp_data['data'] = json.dumps(add_slugs(algo_detail, object_slug=object_slug))\n temp_data['trainer'] = trainer_object.id\n temp_data['app_id'] = trainer_object.app_id\n temp_data['created_by'] = trainer_object.created_by.id\n temp_config = {}\n for i in results['model_dropdown']:\n if algo_detail['name'] == i['name']:\n temp_config['selectedModel'] = i\n temp_config['variablesSelection'] = {}\n temp_config['app_id'] = trainer_object.app_id\n temp_data['config'] = json.dumps(temp_config)\n\n serializer = TrainAlgorithmMappingSerializer(data=temp_data)\n if serializer.is_valid():\n train_algo_object = serializer.save()\n else:\n print(serializer.errors)\n if \"one_click\" in results:\n trainer_object.fe_config = json.dumps(results[\"one_click\"])\n results[\"one_click\"]={}\n trainer_object.data=json.dumps(results)\n trainer_object.save()\n\n outlook_autoML_success_mail(trainer_object.id)\n return \"Done Succesfully.\"\n elif job_type == 'score':\n score_object = get_db_object(model_name=Score.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n score_object.status = \"FAILED\"\n score_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n score_object.data = json.dumps(results)\n score_object.analysis_done = True\n score_object.status = 'SUCCESS'\n score_object.save()\n return \"Done Succesfully.\"\n elif job_type == 'robo':\n robo_object = get_db_object(model_name=Robo.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n robo_object.status = \"FAILED\"\n robo_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n robo_object.data = json.dumps(results)\n robo_object.robo_analysis_done = True\n robo_object.status = 'SUCCESS'\n robo_object.save()\n return results\n elif job_type == 'stockAdvisor':\n stock_objects = get_db_object(model_name=StockDataset.__name__,\n model_slug=object_slug\n )\n results['name'] = stock_objects.name\n results = add_slugs(results, object_slug=object_slug)\n stock_objects.data = json.dumps(results)\n stock_objects.analysis_done = True\n stock_objects.status = 'SUCCESS'\n stock_objects.save()\n return results\n else:\n print(\"No where to write\")\n\n\ndef write_into_databases1(job_type, object_slug, results):\n from api import helper\n # import json\n from api.helper import get_db_object\n from api.views import chart_changes_in_metadata_chart, add_slugs\n\n if job_type in [\"metadata\", \"subSetting\"]:\n dataset_object = get_db_object(model_name=Dataset.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n dataset_object.status = \"FAILED\"\n dataset_object.save()\n return results\n columnData = results['columnData']\n for data in columnData:\n # data[\"chartData\"] = helper.find_chart_data_and_replace_with_chart_data(data[\"chartData\"])\n card_data = data[\"chartData\"]\n if 'dataType' in card_data and card_data['dataType'] == 'c3Chart':\n chart_data = card_data['data']\n final_chart_data = helper.decode_and_convert_chart_raw_data(chart_data, object_slug=object_slug)\n data[\"chartData\"] = chart_changes_in_metadata_chart(final_chart_data)\n data[\"chartData\"][\"table_c3\"] = []\n\n results['columnData'] = columnData\n # results['possibleAnalysis'] = settings.ANALYSIS_FOR_TARGET_VARIABLE\n da = []\n for d in results.get('sampleData'):\n da.append(list(map(str, d)))\n results['sampleData'] = da\n # results[\"modified\"] = False\n\n dataset_object.meta_data = json.dumps(results)\n dataset_object.analysis_done = True\n dataset_object.status = 'SUCCESS'\n dataset_object.save()\n return results\n elif job_type == \"master\":\n insight_object = get_db_object(model_name=Insight.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n insight_object.status = \"FAILED\"\n insight_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n insight_object.data = json.dumps(results)\n insight_object.analysis_done = True\n insight_object.status = 'SUCCESS'\n insight_object.save()\n return results\n elif job_type == \"model\":\n trainer_object = get_db_object(model_name=Trainer.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results or \"model_summary\" not in results:\n trainer_object.status = \"FAILED\"\n trainer_object.save()\n return results\n\n results['model_summary'] = add_slugs(results['model_summary'], object_slug=object_slug)\n trainer_object.data = json.dumps(results)\n trainer_object.analysis_done = True\n trainer_object.status = 'SUCCESS'\n trainer_object.save()\n\n if 'model_management_summary' in results:\n train_algo_details = results['model_management_summary']\n for algo_detail in train_algo_details:\n if len(algo_detail['listOfNodes']) > 1:\n from api.utils import TrainAlgorithmMappingSerializer\n temp_data = dict()\n temp_data['name'] = algo_detail['name']\n temp_data['data'] = json.dumps(add_slugs(algo_detail, object_slug=object_slug))\n temp_data['trainer'] = trainer_object\n temp_data['created_by'] = trainer_object.created_by.id\n temp_config = {}\n for i in results['model_dropdown']:\n if algo_detail['name'] == i['name']:\n temp_config['selectedModel'] = i\n temp_config['variablesSelection'] = {}\n temp_config['app_id'] = trainer_object.app_id\n temp_data['config'] = json.dumps(temp_config)\n\n serializer = TrainAlgorithmMappingSerializer(data=temp_data)\n if serializer.is_valid():\n train_algo_object = serializer.save()\n else:\n print(serializer.errors)\n return results\n elif job_type == 'score':\n score_object = get_db_object(model_name=Score.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n score_object.status = \"FAILED\"\n score_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n score_object.data = json.dumps(results)\n score_object.analysis_done = True\n score_object.status = 'SUCCESS'\n score_object.save()\n return results\n elif job_type == 'robo':\n robo_object = get_db_object(model_name=Robo.__name__,\n model_slug=object_slug\n )\n\n if \"error_message\" in results:\n robo_object.status = \"FAILED\"\n robo_object.save()\n return results\n\n results = add_slugs(results, object_slug=object_slug)\n robo_object.data = json.dumps(results)\n robo_object.robo_analysis_done = True\n robo_object.status = 'SUCCESS'\n robo_object.save()\n return results\n elif job_type == 'stockAdvisor':\n stock_objects = get_db_object(model_name=StockDataset.__name__,\n model_slug=object_slug\n )\n results['name'] = stock_objects.name\n results = add_slugs(results, object_slug=object_slug)\n stock_objects.data = json.dumps(results)\n stock_objects.analysis_done = True\n stock_objects.status = 'SUCCESS'\n stock_objects.save()\n return results\n else:\n print(\"No where to write\")\n\n\n@task(name='save_results_to_job', queue=CONFIG_FILE_NAME)\ndef save_results_to_job(slug, results):\n from api.helper import get_db_object\n # import json\n\n job = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n\n if isinstance(results, str):\n job.results = results\n elif isinstance(results, dict):\n results = json.dumps(results)\n job.results = results\n job.save()\n\n\n@task(name='save_job_messages', queue=CONFIG_FILE_NAME)\ndef save_job_messages(slug, messages):\n from api.helper import get_db_object\n # import json\n try:\n job = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n\n if isinstance(messages, str):\n job.messages = messages\n elif isinstance(messages, dict):\n results = json.dumps(messages)\n job.messages = messages\n job.save()\n except Exception as err:\n print(err)\n\n\n@task(name='cleanup_logentry', queue=CONFIG_FILE_NAME)\ndef save_results_to_job1(slug, results):\n from api.helper import get_db_object\n # import json\n\n job = get_db_object(model_name=Job.__name__,\n model_slug=slug\n )\n\n if isinstance(results, str):\n job.results = results\n elif isinstance(results, dict):\n results = json.dumps(results)\n job.results = results\n job.save()\n print(\"save hogaya \" * 100)\n\n\n@task(name='cleanup_logentry')\ndef clean_up_logentry():\n from auditlog.models import LogEntry\n from django.contrib.auth.models import User\n\n all_users = User.objects.all()\n\n for user in all_users:\n log_entries = LogEntry.objects.filter(actor=user.id).count()\n LogEntry.objects.all().delete()\n print(\"delete object(s) :- %{0}\".format(log_entries))\n\n\n@task(name='cleanup_on_delete', queue=CONFIG_FILE_NAME)\ndef clean_up_on_delete(slug, model_name):\n from api.models import SaveAnyData, Job, SaveData\n\n job_instance = Job.objects.filter(object_id__contains=slug).first()\n if job_instance:\n job_instance.data = '{}'\n job_instance.save()\n\n sad_instance = SaveAnyData.objects.filter(slug__contains=slug)\n print(len(sad_instance))\n sad_instance.delete()\n\n sd_instance = SaveData.objects.filter(object_slug__contains=slug)\n print(len(sd_instance))\n sd_instance.delete()\n\n\n@task(name='kill_job_using_application_id', queue=CONFIG_FILE_NAME)\ndef kill_application_using_fabric(app_id=None):\n if None == app_id:\n return -1\n from fabric.api import env, run\n from django.conf import settings\n import subprocess\n MODE = settings.MODE\n print((\"MODE\", MODE))\n if MODE == 'docker':\n # HDFS = settings.KILL_JOB\n # BASEDIR = settings.BASE_DIR\n # env.key_filename = settings.PEM_KEY\n # env.host_string = \"{0}@{1}\".format(HDFS[\"user.name\"], HDFS[\"host\"])\n\n try:\n capture = subprocess.Popen(\n \"docker exec -t hadoop_spark_compose_hadoop_1 sh -c '/opt/hadoop/bin/yarn application --kill {0}'\".format(\n app_id), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = capture.communicate()\n if 'finished' in stdout:\n return False\n else:\n return True\n except:\n return True\n else:\n HDFS = settings.HDFS\n BASEDIR = settings.BASE_DIR\n emr_file = BASEDIR + settings.PEM_KEY\n env.key_filename = [emr_file]\n\n if CONFIG_FILE_NAME == 'cwpoc':\n env.host_string = \"{0}@{1}\".format(\"ankush\", HDFS[\"host\"])\n else:\n env.host_string = \"{0}@{1}\".format(HDFS[\"user.name\"], HDFS[\"host\"])\n try:\n capture = run(\"yarn application --kill {0}\".format(app_id))\n if 'finished' in capture:\n return False\n else:\n return True\n except:\n return True\n\n\n@task(name='stock_sense_crawling', queue=CONFIG_FILE_NAME)\ndef stock_sense_crawl(object_slug):\n from api.helper import get_db_object\n print(\"stock_sense_crawl\" * 2)\n stock_dataset_object = get_db_object(model_name=StockDataset.__name__,\n model_slug=object_slug\n )\n stock_dataset_object.generate_meta_data()\n stock_dataset_object.save()\n\n\n@task(name='print_this_every_minute', queue=CONFIG_FILE_NAME)\ndef print_this_every_minute(data):\n print(data)\n\n\n@task(name='call_dataset_then_score', queue=CONFIG_FILE_NAME)\ndef call_dataset_then_score(*args, **kwrgs):\n print(args)\n print(kwrgs)\n # collect all configs\n config = kwrgs\n dataset_details = config['dataset_details']\n # score_details = config['score_details']\n # trainer_details = config['trainer_details']\n modeldeployment_details = config['modeldeployment_details']\n user_details = config['user_details']\n\n # fetch modeldeployment instance\n from api.models import ModelDeployment\n model_deployment_object = ModelDeployment.objects.get(slug=modeldeployment_details['modeldeployment_slug'])\n\n # fetch user instance\n from django.contrib.auth.models import User\n user_object = User.objects.get_by_natural_key(username=user_details['username'])\n\n # fetch trainer model\n # trainer_object = model_deployment_object.deploytrainer.trainer\n dataset_score_deployment_details = {\n 'name': model_deployment_object.name + ' - ' + str(datetime.datetime.now().time()),\n 'deployment': model_deployment_object.id,\n 'created_by': user_object.id,\n 'config': '{}',\n 'data': '{}'\n }\n from api.utils import DatasetScoreDeploymentSerializer\n dataset_score_deployment_serializer = DatasetScoreDeploymentSerializer(data=dataset_score_deployment_details)\n if dataset_score_deployment_serializer.is_valid():\n dataset_score_deployment_object = dataset_score_deployment_serializer.save()\n print(dataset_score_deployment_object)\n else:\n return\n # create dataset\n dataset_details['input_file'] = None\n if 'datasetname' in dataset_details['datasource_details']:\n dataset_details['name'] = dataset_details['datasource_details']['datasetname']\n dataset_details['created_by'] = user_object.id\n from api.datasets.helper import convert_to_string\n from api.datasets.serializers import DatasetSerializer\n\n dataset_details = convert_to_string(dataset_details)\n serializer = DatasetSerializer(data=dataset_details)\n if serializer.is_valid():\n dataset_object = serializer.save()\n dataset_score_deployment_object.dataset = dataset_object\n dataset_score_deployment_object.save()\n print(dataset_object)\n dataset_object.create()\n else:\n print(serializer.errors)\n\n\n'''\nThings to do\n- call dataset object create function (uncomment in above code)\n- Once dataset is completed from ML side they will\n -> call set_result API\n -> which will call write_into_database\n -> where we need to check if database is part of DatasetScore Table\n -> if yes, trigger score object create function\n'''\n\n\ndef check_if_dataset_is_part_of_datascore_table_and_do_we_need_to_trigger_score(dataset_object_id):\n print(('received this dataset_object_id : ', dataset_object_id))\n\n if dataset_object_id is None:\n print(\"No dataset id given found\")\n\n return\n\n from api.models import DatasetScoreDeployment\n\n try:\n dataset_object = Dataset.objects.get(id=dataset_object_id)\n datasetscore_deployment_object = DatasetScoreDeployment.objects.filter(dataset=dataset_object_id).first()\n\n if datasetscore_deployment_object is not None:\n # fetch modeldeployment instance\n print(\"Found the dataset in datasetscoredeployment table.\")\n from api.models import ModelDeployment\n model_deployment_object = datasetscore_deployment_object.deployment\n print(\"Found deployment.\")\n\n # fetch trainer insctance\n trainer_object = model_deployment_object.deploytrainer.trainer\n print(\"Found trainer_object.\")\n\n # fetch user instance\n from django.contrib.auth.models import User\n user_object = dataset_object.created_by\n print(\"Found User\")\n\n # create score\n # import json\n original_meta_data_from_scripts = json.loads(dataset_object.meta_data)\n print(\"Got metedata from dataset\")\n\n if original_meta_data_from_scripts is None:\n uiMetaData = dict()\n if original_meta_data_from_scripts == {}:\n uiMetaData = dict()\n else:\n permissions_dict = {\n 'create_signal': user_object.has_perm('api.create_signal'),\n 'subsetting_dataset': user_object.has_perm('api.subsetting_dataset')\n }\n from api.datasets.helper import add_ui_metadata_to_metadata\n uiMetaData = add_ui_metadata_to_metadata(original_meta_data_from_scripts,\n permissions_dict=permissions_dict)\n print(\"Got uiMetaData from dataset\")\n\n from api.utils import convert_to_string\n # import json\n # config = json.loads(model_deployment_object.config)\n print(\"Got model_deployment_object config\")\n\n # dataset_metadata = json.loads(dataset_object.meta_data)\n score_details = model_deployment_object.get_trainer_details_for_score(\n datasetscore_deployment_object.name + \"_score\")\n score_details['config']['variablesSelection'] = uiMetaData['varibaleSelectionArray']\n score_details['trainer'] = trainer_object.id\n score_details['dataset'] = dataset_object.id\n score_details['created_by'] = user_object.id\n score_details['app_id'] = int(score_details['config']['app_id'])\n score_details = convert_to_string(score_details)\n print(\"Constructed score_details\")\n from api.utils import ScoreSerlializer\n score_serializer = ScoreSerlializer(data=score_details, context={})\n if score_serializer.is_valid():\n score_object = score_serializer.save()\n # we will not call score_object.create() here it will be called in write_into_databases\n datasetscore_deployment_object.score = score_object\n datasetscore_deployment_object.save()\n print(score_object)\n score_object.create()\n else:\n print(score_serializer.errors)\n else:\n print('datasetscore_deployment_object si None.')\n return\n except Exception as err:\n print(err)\n\n\ndef check_if_autoML_model_job_needs_to_be_triggered(dataset_object_id):\n print(('received this dataset_object_id : ', dataset_object_id))\n\n if dataset_object_id is None:\n print(\"No dataset id given found\")\n\n return\n\n from api.models import Trainer\n try:\n dataset_object = Dataset.objects.get(id=dataset_object_id)\n trainer_object = Trainer.objects.filter(dataset=dataset_object_id).first()\n\n if trainer_object is not None:\n # fetch modeldeployment instance\n print(\"Found the dataset in trainer table.\")\n ########### Trigger autoML model job ##############\n create_model_autoML.delay(dataset_object.id)\n else:\n print('Its not a email autoML job.')\n return\n\n except Exception as err:\n outlook_autoML_failure_mail(trainer_object_id=None, error=err)\n print(err)\n\n\nfrom celery.task.schedules import crontab\nfrom celery.decorators import periodic_task\n\n\n@periodic_task(run_every=(crontab(minute='*/10')), name=\"trigger_outlook_periodic_job\", ignore_result=False,\n queue=CONFIG_FILE_NAME)\ndef trigger_outlook_periodic_job():\n\n mails = get_mails_from_outlook()\n if mails is not None:\n mail_id = ''\n if 'status' and 'err' not in list(mails.keys()):\n print(\"All set to proceed to upload dataset.\")\n\n for configkey, configvalue in mails.items():\n data = {}\n for key, value in configvalue.items():\n try:\n print(\"inside try ... \")\n # print key,value\n # value is a dict\n ############# Create config and trigger metadata job for train and test Dataset #################\n if key == 'sub_target':\n data['sub_target'] = value\n if key == 'target':\n data['target'] = value\n if 'train_dataset' in key:\n input_file = value\n data['Traindataset'] = input_file\n data['name'] = input_file\n if 'test_dataset' in key:\n input_file = value\n data['Testdataset'] = input_file\n data['score_name'] = configkey\n if 'emailAddress' in key:\n data['email'] = value['emailAddress']['address']\n mail_id = data['email']\n except Exception as error:\n outlook_autoML_failure_mail(trainer_object_id=None, error=error, mail_id=mail_id)\n print('failure mail sent')\n break\n if len(data) > 0:\n print(\"Here is the collected data\")\n print(data)\n trigger_metaData_autoML.delay(data)\n else:\n print(\"No mails found\")\n break\n ##########################################################################################\n else:\n outlook_autoML_failure_mail(trainer_object_id=None, error=mails['err'], mail_id=mail_id)\n print('failure mail sent')\n else:\n print(\"No mails.\")\n\n '''\n Task1: Look for auth Code, Access Token and Refresh Token : DONE\n Task2: Get mails from outlook\n Task3: Extract Text Data and attachments from mail\n Task4: Put Attachments in HDFS\n Task5: Prepare config for Data Upload.\n Task6: Trigger model Once Task5 is done.\n '''\n\n\n@task(name='trigger_metaData_autoML', queue=CONFIG_FILE_NAME)\ndef trigger_metaData_autoML(data):\n print(\"metaData job triggered for autoML\")\n ###################### User id for Email AutoML ################\n print(data)\n '''\n Create one user with Username \"email\" in order to use email for AutoML model creation.\n\n '''\n from django.contrib.auth.models import User\n user_id = User.objects.get(username=\"email\")\n ###################################################################\n #################### Upload file from local ####################\n from django.core.files import File\n from api.datasets.helper import convert_to_string\n from api.datasets.serializers import DatasetSerializer\n\n fail_log = dict()\n test_dataset_serializer = None\n train_dataset_serializer = None\n\n try:\n ######### Trainer dataset config #########\n train_file = open(settings.BASE_DIR + '/media/datasets/' + data['Traindataset'])\n train_f = File(train_file)\n train_dataset_config = dict()\n train_dataset_config['name'] = data['name']\n train_dataset_config['input_file'] = train_f\n train_dataset_config['datasource_type'] = 'fileUpload'\n train_dataset_config['created_by'] = user_id.id\n train_dataset_details = convert_to_string(train_dataset_config)\n train_dataset_serializer = DatasetSerializer(data=train_dataset_details)\n ###################################################################\n except Exception as err:\n fail_log['train_config_error'] = str(err)\n pass\n try:\n ######### Test dataset config #########\n if 'Testdataset' in data:\n test_file = open(settings.BASE_DIR + '/media/datasets/' + data['Testdataset'])\n test_f = File(test_file)\n test_dataset_config = dict()\n test_dataset_config['name'] = data['score_name'] + '_Test'\n test_dataset_config['input_file'] = test_f\n test_dataset_config['datasource_type'] = 'fileUpload'\n test_dataset_config['created_by'] = user_id.id\n test_dataset_details = convert_to_string(test_dataset_config)\n test_dataset_serializer = DatasetSerializer(data=test_dataset_details)\n ###################################################################\n except Exception as err:\n # fail_log['test_config_error'] = str(err)\n pass\n\n if train_dataset_serializer.is_valid():\n print(\"Saving train dataset Serializer\")\n train_dataset_object = train_dataset_serializer.save()\n print(train_dataset_object)\n ################################ Create config for model object that to be triggered after metadata job ##################\n try:\n model_config = dict()\n model_config['name'] = data['name'].split(\".\")[0] + '_Trainer'\n model_config['app_id'] = 2\n model_config['mode'] = \"autoML\"\n model_config['email'] = data['email']\n model_config['dataset'] = train_dataset_object.id\n model_config['config'] = dict()\n model_config['config']['targetColumn'] = data['target']\n model_config['config']['targetLevel'] = data['sub_target']\n model_config['created_by'] = user_id.id\n\n from api.utils import convert_to_string\n model_config = convert_to_string(model_config)\n print(\"Constructed model_config\")\n print(model_config)\n\n from api.utils import TrainerSerlializer\n trainer_serializer = TrainerSerlializer(data=model_config, context={})\n if trainer_serializer.is_valid():\n print(\"Saving trainer Serializer\")\n trainer_object = trainer_serializer.save()\n try:\n if 'Testdataset' in data:\n if test_dataset_serializer.is_valid():\n print(\"Saving test dataset Serializer\")\n test_dataset_object = test_dataset_serializer.save()\n print(test_dataset_object)\n ################ Create config for Score object that to be triggered after model job ##############\n score_config = dict()\n score_config['name'] = data['name'] + '_Score'\n score_config['app_id'] = 2\n score_config['trainer'] = trainer_object.id\n score_config['dataset'] = test_dataset_object.id\n score_config['created_by'] = user_id.id\n\n from api.utils import ScoreSerlializer\n score_serializer = ScoreSerlializer(data=score_config, context={})\n if score_serializer.is_valid():\n print(\"Saving score Serializer\")\n score_object = score_serializer.save()\n print(score_object)\n test_dataset_object.create()\n else:\n fail_log['score_serializer_error'] = str(score_serializer.errors)\n # print(score_serializer.errors)\n else:\n print(\"There's no test data!\")\n except Exception as err:\n fail_log['score_generation_error'] = str(err)\n pass\n # outlook_autoML_failure_mail(trainer_object_id=None, error=err)\n # print e\n else:\n fail_log['trainer_serializer_error'] = str(trainer_serializer.errors)\n # print(trainer_serializer.errors)\n ######### MODEL OBJECT SAVED ----> GO FOR METADATA CREATE ###########\n print(\"Going for metadata creation!!!\")\n train_dataset_object.create()\n except Exception as err:\n fail_log['model_config_error'] = str(err)\n # outlook_autoML_failure_mail(trainer_object_id=None, error=err)\n pass\n else:\n fail_log['train_dataset_serializer_error'] = str(train_dataset_serializer.errors)\n print(train_dataset_serializer.errors)\n\n if fail_log:\n error = ''\n for i in fail_log:\n error = error + '\\n' + i\n print('fail log >> ', fail_log)\n outlook_autoML_failure_mail(trainer_object_id=None, error=error, mail_id=data['email'])\n print('failure mail sent')\n\n\n@task(name='create_model_autoML', queue=CONFIG_FILE_NAME)\ndef create_model_autoML(dataset_object_id=None, config=None):\n print('##################### Configs for Trainer ##################')\n validationTechnique = {\n \"displayName\": \"K Fold Validation\",\n \"name\": \"kFold\",\n \"value\": 2,\n }\n if config is not None:\n try:\n print(config)\n data = json.loads(config)\n dataset_object = Dataset.objects.get(slug=data['slug'])\n print(dataset_object)\n\n model_config = {\n \"name\": data['model_name'],\n \"app_id\": 2,\n \"mode\": \"autoML\",\n \"email\": data['email'],\n \"config\": {}\n }\n\n original_meta_data_from_scripts = json.loads(dataset_object.meta_data)\n print(\"Got metedata from dataset\")\n\n from django.contrib.auth.models import User\n user_object = dataset_object.created_by\n\n if original_meta_data_from_scripts is None:\n uiMetaData = dict()\n if original_meta_data_from_scripts == {}:\n uiMetaData = dict()\n else:\n permissions_dict = {\n 'create_signal': user_object.has_perm('api.create_signal'),\n 'subsetting_dataset': user_object.has_perm('api.subsetting_dataset')\n }\n from api.datasets.helper import add_ui_metadata_to_metadata\n uiMetaData = add_ui_metadata_to_metadata(original_meta_data_from_scripts,\n permissions_dict=permissions_dict)\n print(\"Got uiMetaData from dataset\")\n\n model_config['dataset'] = dataset_object.id\n model_config['config']['ALGORITHM_SETTING'] = copy.deepcopy(\n settings.AUTOML_ALGORITHM_LIST_CLASSIFICATION['ALGORITHM_SETTING'])\n model_config['config']['targetColumn'] = data['target']\n model_config['config']['targetLevel'] = data['subtarget']\n model_config['config']['variablesSelection'] = uiMetaData['varibaleSelectionArray']\n model_config['config']['validationTechnique'] = validationTechnique\n model_config['created_by'] = user_object.id\n\n from api.utils import convert_to_string\n model_config = convert_to_string(model_config)\n print(\"Constructed model_config\")\n\n from api.utils import TrainerSerlializer\n trainer_serializer = TrainerSerlializer(data=model_config, context={})\n if trainer_serializer.is_valid():\n trainer_object = trainer_serializer.save()\n trainer_object.create()\n else:\n print(trainer_serializer.errors)\n\n except Exception as err:\n print(err)\n else:\n try:\n dataset_object = Dataset.objects.get(id=dataset_object_id)\n original_meta_data_from_scripts = json.loads(dataset_object.meta_data)\n print(\"Got metedata from dataset\")\n\n from django.contrib.auth.models import User\n user_object = dataset_object.created_by\n\n if original_meta_data_from_scripts is None:\n uiMetaData = dict()\n if original_meta_data_from_scripts == {}:\n uiMetaData = dict()\n else:\n permissions_dict = {\n 'create_signal': user_object.has_perm('api.create_signal'),\n 'subsetting_dataset': user_object.has_perm('api.subsetting_dataset')\n }\n from api.datasets.helper import add_ui_metadata_to_metadata\n uiMetaData = add_ui_metadata_to_metadata(original_meta_data_from_scripts,\n permissions_dict=permissions_dict)\n print(\"Got uiMetaData from dataset\")\n try:\n trainer_obj = Trainer.objects.filter(dataset=dataset_object_id).first()\n model_config = {\n \"name\": trainer_obj.name,\n \"app_id\": 2,\n \"mode\": \"autoML\",\n \"email\": trainer_obj.email,\n \"config\": {}\n }\n config = json.loads(trainer_obj.config)\n model_config['dataset'] = dataset_object.id\n model_config['config']['ALGORITHM_SETTING'] = copy.deepcopy(\n settings.AUTOML_ALGORITHM_LIST_CLASSIFICATION['ALGORITHM_SETTING'])\n model_config['config']['validationTechnique'] = validationTechnique\n model_config['config']['targetLevel'] = config['targetLevel']\n model_config['config']['targetColumn'] = config['targetColumn']\n model_config['created_by'] = user_object.id\n model_config['config']['variablesSelection'] = uiMetaData['varibaleSelectionArray']\n except Exception as e:\n print(e)\n\n from api.utils import convert_to_string\n model_config = convert_to_string(model_config)\n print((\"Constructed model_config\", model_config))\n\n from api.utils import TrainerSerlializer\n trainer_serializer = TrainerSerlializer(data=model_config, context={})\n if trainer_serializer.is_valid():\n trainer_object = trainer_serializer.save()\n trainer_object.create()\n else:\n print(trainer_serializer.errors)\n\n except Exception as err:\n print(err)\n\n\n@task(name='outlook_autoML_success_mail', queue=CONFIG_FILE_NAME)\ndef outlook_autoML_success_mail(trainer_object_id=None):\n if trainer_object_id is None:\n return\n else:\n trainer_object = Trainer.objects.get(id=trainer_object_id)\n if trainer_object.mode == 'autoML':\n\n from api.helper import get_outlook_auth\n r = get_outlook_auth(settings.OUTLOOK_AUTH_CODE, settings.OUTLOOK_REFRESH_TOKEN,\n settings.OUTLOOK_DETAILS)\n result = r.json()\n access_token = result['access_token']\n protocol = 'http'\n if settings.USE_HTTPS:\n protocol = 'https'\n\n Result_URL = '{}://{}/api/view_model_summary_autoML/?slug={}'.format(protocol,\n settings.THIS_SERVER_DETAILS['host'],\n trainer_object.slug)\n # content = \"AutoML Dataupload successful. Model is created.\"\n content = Result_URL\n # app_slug = CustomApps.objects.get(app_id=trainer_object.app_id)\n # attachment_path = get_model_summary_pdf(app_slug.slug, trainer_object.slug)\n mail_data = dict()\n mail_data['modelName'] = trainer_object.name\n mail_data['datasetName'] = trainer_object.dataset.name\n mail_data['createdAt'] = trainer_object.created_at\n conf = json.loads(trainer_object.config)\n for i in conf['config']['COLUMN_SETTINGS']['variableSelection']:\n if i['targetColumn']:\n mail_data['variable'] = i['name']\n try:\n if trainer_object.email is not None:\n return_mail_id = trainer_object.email\n # mail('send', access_token=access_token, return_mail_id=return_mail_id,\n # subject='Marlabs-AutoML Success', content=content, attachments=attachment_path)\n mail('send', access_token=access_token, return_mail_id=return_mail_id,\n subject='Marlabs-AutoML Success', content=content, mail_options=mail_data)\n else:\n user_id = trainer_object.created_by_id\n user_object = User.objects.get(id=user_id)\n return_mail_id = user_object.email\n if return_mail_id is not None:\n # mail('send', access_token=access_token, return_mail_id=return_mail_id,\n # subject='Marlabs-AutoML Success', content=content, attachments=attachment_path)\n mail('send', access_token=access_token, return_mail_id=return_mail_id,\n subject='Marlabs-AutoML Success', content=content, mail_options=mail_data)\n\n except Exception as err:\n print(err)\n pass\n else:\n pass\n\n\n@task(name='outlook_autoML_failure_mail', queue=CONFIG_FILE_NAME)\ndef outlook_autoML_failure_mail(trainer_object_id=None, error=None, mail_id=None):\n print(\"Trying to send failure mail\")\n mail_data = dict()\n from api.helper import get_outlook_auth\n r = get_outlook_auth(settings.OUTLOOK_AUTH_CODE, settings.OUTLOOK_REFRESH_TOKEN,\n settings.OUTLOOK_DETAILS)\n result = r.json()\n print(result)\n access_token = result['access_token']\n print(\"got access token\")\n if trainer_object_id is None:\n mail_data['modelName'] = 'UNDEFINED'\n mail_data['datasetName'] = 'UNDEFINED'\n mail_data['createdAt'] = 'UNDEFINED'\n mail_data['variable'] = 'UNDEFINED'\n print(\"mail id : \", mail_id)\n err_mail('send', access_token=access_token, return_mail_id=mail_id,\n subject='Marlabs-AutoML Failure', error=error, mail_options=mail_data)\n else:\n trainer_object = Trainer.objects.get(id=trainer_object_id)\n if trainer_object.mode == 'autoML':\n\n mail_data['modelName'] = trainer_object.name\n mail_data['datasetName'] = trainer_object.dataset.name\n mail_data['createdAt'] = trainer_object.created_at\n conf = json.loads(trainer_object.config)\n for i in conf['config']['COLUMN_SETTINGS']['variableSelection']:\n if i['targetColumn']:\n mail_data['variable'] = i['name']\n try:\n if trainer_object.email is not None:\n return_mail_id = trainer_object.email\n err_mail('send', access_token=access_token, return_mail_id=return_mail_id,\n subject='Marlabs-AutoML Failure', error=error, mail_options=mail_data)\n else:\n user_id = trainer_object.created_by_id\n user_object = User.objects.get(id=user_id)\n return_mail_id = user_object.email\n if return_mail_id is not None:\n err_mail('send', access_token=access_token, return_mail_id=return_mail_id,\n subject='Marlabs-AutoML Failure', error=error, mail_options=mail_data)\n\n except Exception as err:\n print(err)\n pass\n else:\n pass\n\n\ndef mail(action_type=None, access_token=None, return_mail_id=None, subject=None, content=None, mail_options=None):\n # access_token = access_token\n # If there is no token in the session, redirect to home\n if not access_token:\n return HttpResponseRedirect(reverse('tutorial:home'))\n else:\n try:\n messages = send_my_messages(access_token, return_mail_id, subject, content, mail_options)\n if messages[:3] == '202':\n print(\"Mail Sent\")\n except Exception as e:\n print(e)\n print(\"Some issue with mail sending module...\")\n\n\ndef err_mail(action_type=None, access_token=None, return_mail_id=None, subject=None, error=None, mail_options=None):\n # access_token = access_token\n # If there is no token in the session, redirect to home\n if not access_token:\n return HttpResponseRedirect(reverse('tutorial:home'))\n else:\n try:\n messages = send_failure_messages(access_token, return_mail_id, subject, error, mail_options)\n if messages[:3] == '202':\n print(\"Mail Sent\")\n except Exception as e:\n print(e)\n print(\"Some issue with mail sending module...\")\n\n\ndef send_failure_messages(access_token, return_mail_id, subject, error, mail_options):\n get_messages_url = 'https://graph.microsoft.com/v1.0/me/' + '/sendmail'\n\n htmlData = \"\"\"Dear {},

Model creation has failed for some reason! \\\n

Please contact the Admin team for further assistance.

\\\n Sorry for the inconvenience.

Regards,
mAdvisor\"\"\" \\\n .format(return_mail_id.split('@')[0])\n '''\n htmlData = \"\"\"Dear {},

Model creation has failed! \\\n

Details:
Model Name : {}
Created on : {}
Dataset : {}
Target Variable : {}
Reason for failure : {} \\\n



Sorry for the inconvenience.

Regards,
mAdvisor\"\"\" \\\n .format(return_mail_id.split('@')[0],\n mail_options['modelName'],\n mail_options['createdAt'],\n mail_options['datasetName'],\n mail_options['variable'],\n str(error))'''\n\n payload = {\n\n \"Message\": {\n\n \"Subject\": subject,\n \"Body\": {\n\n \"ContentType\": \"HTML\",\n \"Content\": htmlData,\n\n },\n \"ToRecipients\": [\n {\n \"EmailAddress\": {\n \"Address\": return_mail_id\n }\n }\n ],\n # 'Attachments': [attached_files]\n },\n \"SaveToSentItems\": \"true\",\n\n }\n from api.helper import make_api_call\n import requests\n\n r = make_api_call('POST', get_messages_url, access_token, payload=payload)\n if r.status_code == requests.codes.ok:\n print(\"Mail Sent\")\n return r.json()\n else:\n return \"{0}: {1}\".format(r.status_code, r.text)\n\n\ndef send_my_messages(access_token, return_mail_id, subject, content, mail_options):\n '''\n Replies to the mail with attachments\n '''\n # get_messages_url = graph_endpoint.format('/me/messages?$select=sender,subject')\n # get_messages_url = 'https://graph.microsoft.com/v1.0' + '/users/' + settings.OUTLOOK_ID + '/sendmail'\n get_messages_url = 'https://graph.microsoft.com/v1.0/me/' + '/sendmail'\n # Use OData query parameters to control the results\n # - Only first 10 results returned\n # - Only return the ReceivedDateTime, Subject, and From fields\n # - Sort the results by the ReceivedDateTime field in descending order\n '''\n b64_content = base64.b64encode(open(file_to_attach, 'rb').read())\n mime_type = mimetypes.guess_type(file_to_attach)[0]\n mime_type = mime_type if mime_type else ''\n attached_files = {'@odata.type': '#microsoft.graph.fileAttachment',\n 'ContentBytes': b64_content.decode('utf-8'),\n 'ContentType': mime_type,\n 'Name': file_to_attach.split('/')[-1]}\n '''\n htmlData = \"\"\"Dear {},

Model has been successfully created through AutoML.\n

Details:
Model Name : {}
Created on : {}
Dataset : {}
Target Variable :\n {}

Please go through the attached link in order to view your Model Summary.\n


Model Summary

Have a great day ahead.

Regards,
mAdvisor\"\"\" \\\n .format(return_mail_id.split('@')[0],\n mail_options['modelName'],\n mail_options['createdAt'],\n mail_options['datasetName'],\n mail_options['variable'],\n content)\n\n payload = {\n\n \"Message\": {\n\n \"Subject\": subject,\n \"Body\": {\n\n \"ContentType\": \"HTML\",\n \"Content\": htmlData,\n\n },\n \"ToRecipients\": [\n {\n \"EmailAddress\": {\n \"Address\": return_mail_id\n }\n }\n ],\n # 'Attachments': [attached_files]\n },\n \"SaveToSentItems\": \"true\",\n\n }\n from api.helper import make_api_call\n import requests\n\n r = make_api_call('POST', get_messages_url, access_token, payload=payload)\n if r.status_code == requests.codes.ok:\n print(\"Mail Sent\")\n return r.json()\n else:\n return \"{0}: {1}\".format(r.status_code, r.text)\n\n\n'''\ndef send_devtools(driver, cmd, params={}):\n resource = \"/session/%s/chromium/send_command_and_get_result\" % driver.session_id\n url = driver.command_executor._url + resource\n body = json.dumps({'cmd': cmd, 'params': params})\n response = driver.command_executor._request('POST', url, body)\n return response.get('value')\n\n\ndef save_as_pdf(driver, path, options=None):\n if options is None:\n options = {}\n result = send_devtools(driver, \"Page.printToPDF\", options)\n with open(path, 'wb') as f:\n f.write(base64.b64decode(result['data']))\n\n\ndef get_model_summary_pdf(app_slug, model_slug):\n protocol = 'http'\n if settings.USE_HTTPS:\n protocol = 'https'\n\n login_url = '{}://{}'.format(protocol, settings.THIS_SERVER_DETAILS['host'])\n url = '{}/apps/{}/autoML/models/{}'.format(login_url, app_slug, model_slug)\n\n options = webdriver.ChromeOptions()\n options.add_argument(\"--headless\")\n options.add_argument(\"--disable-gpu\")\n\n driver = webdriver.Chrome(chrome_options=options)\n driver.get(login_url)\n driver.find_element_by_id('username').send_keys('email')\n driver.find_element_by_id('password').send_keys('emailuser')\n driver.find_element_by_xpath('//button').click()\n driver.get(url)\n path = '{}/{}.pdf'.format(settings.MODEL_SUMMARY_DOWNLOAD_PATH, model_slug)\n save_as_pdf(driver, path, {'landscape': False})\n return path\n'''\n\n\n@periodic_task(run_every=(crontab(0, 0, day_of_month='1')), name=\"trigger_outlook_token\", ignore_result=False,\n queue=CONFIG_FILE_NAME)\ndef trigger_outlook_token():\n\n outlook_data = settings.OUTLOOK_DETAILS\n token = OutlookToken.objects.first()\n\n post_data_auth_code = {\n 'grant_type': 'authorization_code',\n 'code': token.access_token,\n 'redirect_uri': outlook_data['redirect_uri'],\n 'scope': settings.OUTLOOK_SCOPES,\n 'client_id': outlook_data['client_id'],\n 'client_secret': outlook_data['client_secret']\n }\n post_data_refresh_token = {'grant_type': 'refresh_token',\n 'redirect_uri': outlook_data['redirect_uri'],\n 'scope': 'https://graph.microsoft.com/.default',\n 'refresh_token': token.refresh_token,\n 'client_id': outlook_data['client_id'],\n 'client_secret': outlook_data['client_secret']\n }\n\n if token.refresh_token is not None:\n r = requests.post(settings.OUTLOOK_TOKEN_URL, data=post_data_refresh_token)\n result = r.json()\n outlook_token = OutlookToken(refresh_token=result['refresh_token'], access_token=result['access_token'])\n outlook_token.save()\n else:\n r = requests.post(settings.OUTLOOK_TOKEN_URL, data=post_data_auth_code)\n result = r.json()\n outlook_token = OutlookToken(refresh_token=result['refresh_token'], access_token=result['access_token'])\n outlook_token.save()\n return result\n\n\n\n","sub_path":"api/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":59036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"123940687","text":"from cloudrail.knowledge.context.azure.resources.constants.azure_resource_type import AzureResourceType\nfrom cloudrail.knowledge.context.azure.resources.databases.azure_mssql_server_security_alert_policy import AzureMsSqlServerSecurityAlertPolicy, \\\n AzureMsSqlServerSecurityAlertPolicyState, AzureMsSqlServerSecurityAlertPolicyDisabledAlerts\nfrom cloudrail.knowledge.context.azure.resources_builders.terraform.azure_terraform_builder import AzureTerraformBuilder\nfrom cloudrail.knowledge.utils.enum_utils import enum_implementation\n\n\nclass SqlServerSecurityAlertPolicyBuilder(AzureTerraformBuilder):\n\n def do_build(self, attributes: dict) -> AzureMsSqlServerSecurityAlertPolicy:\n ## Disabled Alerts\n disabled_alerts = []\n for alert in self._get_known_value(attributes, 'disabled_alerts', []):\n disabled_alerts.append(enum_implementation(AzureMsSqlServerSecurityAlertPolicyDisabledAlerts, alert))\n return AzureMsSqlServerSecurityAlertPolicy(server_name=attributes['server_name'],\n state=enum_implementation(AzureMsSqlServerSecurityAlertPolicyState, attributes['state']),\n disabled_alerts=disabled_alerts,\n email_account_admins=self._get_known_value(attributes, 'email_account_admins', False),\n email_addresses=self._get_known_value(attributes, 'email_addresses', []),\n retention_days=self._get_known_value(attributes, 'retention_days', 0),\n storage_account_access_key=self._get_known_value(attributes, 'storage_account_access_key'),\n storage_endpoint=self._get_known_value(attributes, 'storage_endpoint'))\n\n def get_service_name(self) -> AzureResourceType:\n return AzureResourceType.AZURERM_MSSQL_SERVER_SECURITY_ALERT_POLICY\n","sub_path":"cloudrail/knowledge/context/azure/resources_builders/terraform/sql_server_security_alert_policy_builder.py","file_name":"sql_server_security_alert_policy_builder.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"598448705","text":"from keras.layers import Dense, LSTM, Activation, Embedding, Dropout\nfrom keras.models import Sequential\n\nhparams = {\n 'optimizer': 'adma',\n 'loss': 'sparse_categorical_crossentropy',\n 'activation': 'softmax'\n}\n\ndef build_lstm_model(vocab_size, embedding_size, pretrained_weights):\n ''' \n Neural Network Architecture\n '''\n\n model = Sequential()\n model.add(Embedding(input_dim=vocab_size, output_dim=embedding_size, weights=[pretrained_weights]))\n model.add(LSTM(units=embedding_size, return_sequences=True))\n model.add(Dropout(0.4))\n model.add(LSTM(100))\n model.add(Dropout(0.2))\n model.add(Dense(units=vocab_size))\n model.add(Activation(hparams['activation']))\n model.compile(optimizer=hparams['optimizer'], loss=hparams['loss'])\n\n model.summary()\n return model\n\n\n'''\nmodel = Sequential()\nmodel.add(Bidirectional(LSTM(128), input_shape=(SEQUENCE_LEN, len(words))))\nif dropout > 0:\n model.add(Dropout(dropout))\nmodel.add(Dense(len(words)))\nmodel.add(Activation('softmax'))\n'''","sub_path":"Iteration-1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"464111415","text":"import collections\nimport json\nimport logging\nimport sys\nimport time\n\nfrom django import db\nfrom django.core import exceptions as django_exceptions\nfrom django.http import Http404\n\nfrom rest_framework import request as api_request\nfrom ws4redis import publisher, redis_store\n\nfrom . import exceptions\nfrom .connection import get_queryobserver_settings\n\n# Logger.\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n# Observable method options attribute name prefix.\nOBSERVABLE_OPTIONS_PREFIX = 'observable_'\n\n\nclass Options(object):\n \"\"\"\n Query observer options.\n \"\"\"\n\n # Valid change detection types.\n CHANGE_DETECTION_PUSH = 'push'\n CHANGE_DETECTION_POLL = 'poll'\n\n def __init__(self, viewset, viewset_method):\n self._viewset = viewset\n self._viewset_method = viewset_method\n\n # Determine the primary key.\n self.primary_key = self.get_option('primary_key')\n if self.primary_key is None:\n # Primary key attribute is not defined, attempt to autodiscover it from the queryset.\n try:\n self.primary_key = viewset.get_queryset().model._meta.pk.name\n except AssertionError:\n # No queryset is defined.\n raise exceptions.MissingPrimaryKey(\n \"Observable method does not define a primary key and the viewset \"\n \"does not provide a queryset. Define a queryset or use the primary_key \"\n \"decorator.\"\n )\n\n # Determine change detection type.\n self.change_detection = self.get_option('change_detection', Options.CHANGE_DETECTION_PUSH)\n self.poll_interval = self.get_option('poll_interval')\n\n def get_option(self, name, default=None):\n return getattr(self._viewset_method, '{}{}'.format(OBSERVABLE_OPTIONS_PREFIX, name), default)\n\n\nclass QueryObserver(object):\n \"\"\"\n A query observer observes a specific viewset for changes and propagates these\n changes to all interested subscribers.\n \"\"\"\n\n # Valid observer statuses.\n STATUS_NEW = 'new'\n STATUS_INITIALIZING = 'initializing'\n STATUS_OBSERVING = 'observing'\n STATUS_STOPPED = 'stopped'\n\n # Valid message types.\n MESSAGE_ADDED = 'added'\n MESSAGE_CHANGED = 'changed'\n MESSAGE_REMOVED = 'removed'\n\n def __init__(self, pool, request):\n \"\"\"\n Creates a new query observer.\n\n :param pool: QueryObserverPool instance\n :param request: A `queryobserver.request.Request` instance\n \"\"\"\n\n self.status = QueryObserver.STATUS_NEW\n self._pool = pool\n\n # Obtain a serializer by asking the viewset to provide one. We instantiate the\n # viewset with a fake request, so that the viewset methods work as expected.\n viewset = request.viewset_class()\n viewset.request = api_request.Request(request)\n viewset.request.method = request.method\n viewset.format_kwarg = None\n viewset.args = request.args\n viewset.kwargs = request.kwargs\n self._viewset = viewset\n self._request = request\n self._viewset_method = getattr(viewset, request.viewset_method)\n self._meta = Options(viewset, self._viewset_method)\n\n self._evaluating = 0\n self._last_evaluation = None\n self._last_results = collections.OrderedDict()\n self._subscribers = set()\n self._dependencies = set()\n self._initialization_future = None\n self.id = request.observe_id\n\n def add_dependency(self, table):\n \"\"\"\n Registers a new dependency for this query observer.\n\n :param table: Name of the dependent database table\n \"\"\"\n\n if table in self._dependencies:\n return\n\n self._dependencies.add(table)\n self._pool.register_dependency(self, table)\n\n @property\n def stopped(self):\n \"\"\"\n True if the query observer has been stopped.\n \"\"\"\n\n return self.status == QueryObserver.STATUS_STOPPED\n\n @property\n def last_evaluation(self):\n \"\"\"\n Timestamp of last evaluation. May be None if the observer was\n never evaluated.\n \"\"\"\n\n return self._last_evaluation\n\n def evaluate(self, return_full=True, return_emitted=False):\n \"\"\"\n Evaluates the query observer and checks if there have been any changes. This function\n may yield.\n\n :param return_full: True if the full set of rows should be returned\n :param return_emitted: True if the emitted diffs should be returned\n \"\"\"\n\n # Sanity check (should never happen).\n if self._evaluating < 0:\n logger.error(\"Corrupted internal observer state: _evaluating < 0\")\n logger.error(\"Stopping observer: {}\".format(repr(self)))\n self.stop()\n return []\n\n if self._evaluating and not return_full:\n # Ignore evaluate requests if the observer is already being evaluated. Do\n # not ignore requests when full results are requested as in that case we\n # need to wait for the results (the caller needs them).\n return\n\n self._evaluating += 1\n\n try:\n # Increment evaluation statistics counter.\n self._pool._evaluations += 1\n self._pool._running += 1\n settings = get_queryobserver_settings()\n\n # After an update is processed, all incoming requests are batched until\n # the update batch delay passes. Batching is not performed when full\n # results are requested as in that case we want them as fast as possible.\n if self._last_evaluation is not None and not return_full:\n delta = time.time() - self._last_evaluation\n remaining = settings['update_batch_delay'] - delta\n\n if remaining > 0:\n try:\n self._pool._sleeping += 1\n\n # We assume that time.sleep has been patched and will correctly yield.\n time.sleep(remaining)\n finally:\n self._pool._sleeping -= 1\n\n start = time.time()\n result = self._evaluate(return_full, return_emitted)\n duration = time.time() - start\n self._last_evaluation = time.time()\n\n # Log slow observers.\n if duration > settings['warnings']['max_processing_time']:\n # pylint: disable=logging-format-interpolation\n logger.warning(\"Slow observer took {} seconds to evaluate.\".format(duration))\n logger.warning(\"Potentially slow observer is: {}\".format(repr(self)))\n\n # Stop really slow observers.\n if duration > settings['errors']['max_processing_time']:\n # pylint: disable=logging-format-interpolation\n logger.error(\"Stopping slow observer that took {} seconds to evaluate.\".format(duration))\n self.stop()\n\n return result\n except exceptions.ObserverStopped:\n return []\n except: # pylint: disable=bare-except\n # Stop crashing observers.\n self.stop()\n\n # pylint: disable=logging-format-interpolation\n logger.exception(\"Error while evaluating observer: {}\".format(repr(self)))\n return []\n finally:\n self._evaluating -= 1\n self._pool._running -= 1\n\n # Cleanup any leftover connections. This is something that should not be executed\n # during tests as it would terminate the database connection.\n is_testing = sys.argv[1:2] == ['test']\n if not is_testing:\n db.close_old_connections()\n\n def _evaluate(self, return_full=True, return_emitted=False):\n \"\"\"\n Evaluates the query observer and checks if there have been any changes. This function\n may yield.\n\n :param return_full: True if the full set of rows should be returned\n :param return_emitted: True if the emitted diffs should be returned\n \"\"\"\n\n if self.status == QueryObserver.STATUS_STOPPED:\n raise exceptions.ObserverStopped\n\n # Be sure to handle status changes before any yields, so that the other greenlets\n # will see the changes and will be able to wait on the initialization future.\n if self.status == QueryObserver.STATUS_INITIALIZING:\n self._initialization_future.wait()\n elif self.status == QueryObserver.STATUS_NEW:\n self._initialization_future = self._pool.backend.create_future()\n self.status = QueryObserver.STATUS_INITIALIZING\n\n # Evaluate the query (this operation yields).\n tables = set()\n stop_observer = False\n with self._pool.query_interceptor.intercept(tables):\n try:\n response = self._viewset_method(\n self._viewset.request,\n *self._request.args,\n **self._request.kwargs\n )\n\n if response.status_code == 200:\n results = response.data\n\n if not isinstance(results, list):\n if isinstance(results, dict):\n if 'results' in results and isinstance(results['results'], list):\n # Support paginated results.\n results = results['results']\n else:\n results[self._meta.primary_key] = 1\n results = [collections.OrderedDict(results)]\n else:\n raise ValueError(\"Observable views must return a dictionary or a list of dictionaries!\")\n else:\n results = []\n except Http404:\n results = []\n except django_exceptions.ObjectDoesNotExist:\n # The evaluation may fail when certain dependent objects (like users) are removed\n # from the database. In this case, the observer is stopped.\n stop_observer = True\n\n if stop_observer:\n self.stop()\n return []\n\n if self._meta.change_detection == Options.CHANGE_DETECTION_PUSH:\n # Register table dependencies for push observables.\n for table in tables:\n self.add_dependency(table)\n elif self._meta.change_detection == Options.CHANGE_DETECTION_POLL:\n # Register poller.\n self._pool.register_poller(self)\n else:\n raise NotImplementedError(\"Change detection mechanism '{}' not implemented.\".format(\n self._meta.change_detection\n ))\n\n # TODO: Only compute difference between old and new, ideally on the SQL server using hashes.\n new_results = collections.OrderedDict()\n\n if self.status == QueryObserver.STATUS_STOPPED:\n return []\n\n # Log viewsets with too much output.\n if len(results) > get_queryobserver_settings()['warnings']['max_result_length']:\n # pylint: disable=logging-format-interpolation\n logger.warning(\"Observed viewset returned {} results.\".format(len(results)))\n logger.warning(\"Potentially slow observer is: {}\".format(repr(self)))\n\n for order, row in enumerate(results):\n if not isinstance(row, dict):\n raise ValueError(\"Observable views must return a dictionary or a list of dictionaries!\")\n\n row._order = order\n try:\n new_results[row[self._meta.primary_key]] = row\n except KeyError:\n raise KeyError(\"Observable view did not return primary key field '{}'!\".format(self._meta.primary_key))\n\n # Process difference between old results and new results.\n added = []\n changed = []\n removed = []\n for row_id, row in self._last_results.iteritems():\n if row_id not in new_results:\n removed.append(row)\n\n for row_id, row in new_results.iteritems():\n if row_id not in self._last_results:\n added.append(row)\n else:\n old_row = self._last_results[row_id]\n if row != old_row:\n changed.append(row)\n if row._order != old_row._order:\n changed.append(row)\n\n self._last_results = new_results\n\n if self.status == QueryObserver.STATUS_INITIALIZING:\n self.status = QueryObserver.STATUS_OBSERVING\n if self._initialization_future is not None:\n future = self._initialization_future\n self._initialization_future = None\n future.set()\n elif self.status == QueryObserver.STATUS_OBSERVING:\n self.emit(added, changed, removed)\n\n if return_emitted:\n return (added, changed, removed)\n\n if return_full:\n return self._last_results.values()\n\n def emit(self, added, changed, removed):\n \"\"\"\n Notifies all subscribers about query changes.\n\n :param added: A list of rows there were added\n :param changed: A list of rows that were changed\n :param removed: A list of rows that were removed\n \"\"\"\n\n # TODO: Instead of duplicating messages to all subscribers, handle subscriptions within redis.\n for message_type, rows in (\n (QueryObserver.MESSAGE_ADDED, added),\n (QueryObserver.MESSAGE_CHANGED, changed),\n (QueryObserver.MESSAGE_REMOVED, removed),\n ):\n # Make a copy of the subscribers set as the publish operation may yield and modify the set.\n for subscriber in self._subscribers.copy():\n session_publisher = publisher.RedisPublisher(facility=subscriber, broadcast=True)\n for row in rows:\n session_publisher.publish_message(redis_store.RedisMessage(json.dumps({\n 'msg': message_type,\n 'observer': self.id,\n 'primary_key': self._meta.primary_key,\n 'order': getattr(row, '_order', None),\n 'item': row,\n })))\n\n def subscribe(self, subscriber):\n \"\"\"\n Adds a new subscriber.\n \"\"\"\n\n self._subscribers.add(subscriber)\n\n def unsubscribe(self, subscriber):\n \"\"\"\n Unsubscribes a specific subscriber to this query observer. If no subscribers\n are left, this query observer is stopped.\n \"\"\"\n\n try:\n self._subscribers.remove(subscriber)\n except KeyError:\n pass\n\n if not self._subscribers:\n self.stop()\n\n def stop(self):\n \"\"\"\n Stops this query observer.\n \"\"\"\n\n if self.status == QueryObserver.STATUS_STOPPED:\n return\n\n self.status = QueryObserver.STATUS_STOPPED\n self._last_results.clear()\n\n # Unregister all dependencies.\n for dependency in self._dependencies:\n self._pool.unregister_dependency(self, dependency)\n\n # Unsubscribe all subscribers.\n for subscriber in self._subscribers:\n self._pool._remove_subscriber(self, subscriber)\n\n self._pool._remove_observer(self)\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __hash__(self):\n return hash(self.id)\n\n def __repr__(self):\n return ''.format(\n id=self.id,\n request=repr(self._request)\n )\n","sub_path":"rest_framework_reactive/observer.py","file_name":"observer.py","file_ext":"py","file_size_in_byte":15741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"164499204","text":"import tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow.keras as keras\nfrom keras import backend, Model, Input, Sequential\nfrom keras.optimizers import Adam\n\n# ==============================================================================\n# = networks =\n# ==============================================================================\nfrom keras.constraints import max_norm\nfrom keras.initializers import RandomNormal\nfrom keras.layers import UpSampling2D, LeakyReLU, Add, Dense, Reshape, AveragePooling2D, Flatten\n\n\ndef _get_norm_layer(norm):\n if norm == 'none':\n return lambda: lambda x: x\n elif norm == 'batch_norm':\n return keras.layers.BatchNormalization\n elif norm == 'instance_norm':\n return tfa.layers.InstanceNormalization\n elif norm == 'layer_norm':\n return keras.layers.LayerNormalization\n\n\n# pixel-wise feature vector normalization layer\nclass PixelNormalization(keras.layers.Layer):\n # initialize the layer\n def __init__(self, **kwargs):\n super(PixelNormalization, self).__init__(**kwargs)\n\n # perform the operation\n def call(self, inputs):\n # calculate square pixel values\n values = inputs ** 2.0\n # calculate the mean pixel values\n mean_values = backend.mean(values, axis=-1, keepdims=True)\n # ensure the mean is not zero\n mean_values += 1.0e-8\n # calculate the sqrt of the mean squared value (L2 norm)\n l2 = backend.sqrt(mean_values)\n # normalize values by the l2 norm\n normalized = inputs / l2\n return normalized\n\n # define the output shape of the layer\n def compute_output_shape(self, input_shape):\n return input_shape\n\n\n# weighted sum output\nclass WeightedSum(Add):\n # init with default value\n def __init__(self, alpha=0.0, **kwargs):\n super(WeightedSum, self).__init__(**kwargs)\n self.alpha = backend.variable(alpha, name='ws_alpha')\n\n # output a weighted sum of inputs\n def _merge_function(self, inputs):\n # only supports a weighted sum of two inputs\n assert (len(inputs) == 2)\n # ((1-a) * input1) + (a * input2)\n output = ((1.0 - self.alpha) * inputs[0]) + (self.alpha * inputs[1])\n return output\n\n\nclass MinibatchStdev(keras.layers.Layer):\n # initialize the layer\n def __init__(self, **kwargs):\n super(MinibatchStdev, self).__init__(**kwargs)\n\n # perform the operation\n def call(self, inputs):\n # calculate the mean value for each pixel across channels\n mean = backend.mean(inputs, axis=0, keepdims=True)\n # calculate the squared differences between pixel values and mean\n squ_diffs = backend.square(inputs - mean)\n # calculate the average of the squared differences (variance)\n mean_sq_diff = backend.mean(squ_diffs, axis=0, keepdims=True)\n # add a small value to avoid a blow-up when we calculate stdev\n mean_sq_diff += 1e-8\n # square root of the variance (stdev)\n stdev = backend.sqrt(mean_sq_diff)\n # calculate the mean standard deviation across each pixel coord\n mean_pix = backend.mean(stdev, keepdims=True)\n # scale this up to be the size of one input feature map for each sample\n shape = backend.shape(inputs)\n output = backend.tile(mean_pix, (shape[0], shape[1], shape[2], 1))\n # concatenate with the output\n combined = backend.concatenate([inputs, output], axis=-1)\n return combined\n\n # define the output shape of the layer\n def compute_output_shape(self, input_shape):\n # create a copy of the input shape as a list\n input_shape = list(input_shape)\n # add one to the channel dimension (assume channels-last)\n input_shape[-1] += 1\n # convert list to a tuple\n return tuple(input_shape)\n\n\n# add a generator block\ndef add_generator_block(old_model):\n # weight initialization\n init = RandomNormal(stddev=0.02)\n # weight constraint\n const = max_norm(1.0)\n # get the end of the last block\n block_end = old_model.layers[-2].output\n # upsample, and define new block\n upsampling = UpSampling2D()(block_end)\n g = keras.layers(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(upsampling)\n g = PixelNormalization()(g)\n g = LeakyReLU(alpha=0.2)(g)\n g = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(g)\n g = PixelNormalization()(g)\n g = LeakyReLU(alpha=0.2)(g)\n # add new output layer\n out_image = keras.layers.Conv2D(3, (1, 1), padding='same', kernel_initializer=init, kernel_constraint=const)(g)\n # define model\n model1 = Model(old_model.input, out_image)\n # get the output layer from old model\n out_old = old_model.layers[-1]\n # connect the upsampling to the old output layer\n out_image2 = out_old(upsampling)\n # define new output image as the weighted sum of the old and new models\n merged = WeightedSum()([out_image2, out_image])\n # define model\n model2 = Model(old_model.input, merged)\n return [model1, model2]\n\n\n# calculate wasserstein loss\ndef wasserstein_loss(y_true, y_pred):\n return backend.mean(y_true * y_pred)\n\n\n# define generator models\ndef define_generator(latent_dim, n_blocks, in_dim=4):\n # weight initialization\n init = RandomNormal(stddev=0.02)\n # weight constraint\n const = max_norm(1.0)\n model_list = list()\n # base model latent input\n in_latent = Input(shape=(latent_dim,))\n # linear scale up to activation maps\n g = Dense(128 * in_dim * in_dim, kernel_initializer=init, kernel_constraint=const)(in_latent)\n g = Reshape((in_dim, in_dim, 128))(g)\n # conv 4x4, input block\n g = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(g)\n g = PixelNormalization()(g)\n g = LeakyReLU(alpha=0.2)(g)\n # conv 3x3\n g = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(g)\n g = PixelNormalization()(g)\n g = LeakyReLU(alpha=0.2)(g)\n # conv 1x1, output block\n out_image = keras.layers.Conv2D(3, (1, 1), padding='same', kernel_initializer=init, kernel_constraint=const)(g)\n # define model\n model = Model(in_latent, out_image)\n # store model\n model_list.append([model, model])\n # create submodels\n for i in range(1, n_blocks):\n # get prior model without the fade-on\n old_model = model_list[i - 1][0]\n # create new model for next resolution\n models = add_generator_block(old_model)\n # store model\n model_list.append(models)\n return model_list\n\n\ndef add_discriminator_block(old_model, n_input_layers=3):\n # weight initialization\n init = RandomNormal(stddev=0.02)\n # weight constraint\n const = max_norm(1.0)\n # get shape of existing model\n in_shape = list(old_model.input.shape)\n # define new input shape as double the size\n input_shape = (in_shape[-2].value * 2, in_shape[-2].value * 2, in_shape[-1].value)\n in_image = Input(shape=input_shape)\n # define new input processing layer\n d = keras.layers.Conv2D(128, (1, 1), padding='same', kernel_initializer=init, kernel_constraint=const)(in_image)\n d = LeakyReLU(alpha=0.2)(d)\n # define new block\n d = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(d)\n d = LeakyReLU(alpha=0.2)(d)\n d = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(d)\n d = LeakyReLU(alpha=0.2)(d)\n d = AveragePooling2D()(d)\n block_new = d\n # skip the input, 1x1 and activation for the old model\n for i in range(n_input_layers, len(old_model.layers)):\n d = old_model.layers[i](d)\n # define straight-through model\n model1 = Model(in_image, d)\n # compile model\n model1.compile(loss=wasserstein_loss, optimizer=Adam(lr=0.001, beta_1=0, beta_2=0.99, epsilon=10e-8))\n # downsample the new larger image\n downsample = AveragePooling2D()(in_image)\n # connect old input processing to downsampled new input\n block_old = old_model.layers[1](downsample)\n block_old = old_model.layers[2](block_old)\n # fade in output of old model input layer with new input\n d = WeightedSum()([block_old, block_new])\n # skip the input, 1x1 and activation for the old model\n for i in range(n_input_layers, len(old_model.layers)):\n d = old_model.layers[i](d)\n # define straight-through model\n model2 = Model(in_image, d)\n # compile model\n model2.compile(loss=wasserstein_loss, optimizer=Adam(lr=0.001, beta_1=0, beta_2=0.99, epsilon=10e-8))\n return [model1, model2]\n\n\n# define the discriminator models for each image resolution\ndef define_discriminator(n_blocks, input_shape=(4, 4, 3)):\n # weight initialization\n init = RandomNormal(stddev=0.02)\n # weight constraint\n const = max_norm(1.0)\n model_list = list()\n # base model input\n in_image = Input(shape=input_shape)\n # conv 1x1\n d = keras.layers.Conv2D(128, (1, 1), padding='same', kernel_initializer=init, kernel_constraint=const)(in_image)\n d = LeakyReLU(alpha=0.2)(d)\n # conv 3x3 (output block)\n d = MinibatchStdev()(d)\n d = keras.layers.Conv2D(128, (3, 3), padding='same', kernel_initializer=init, kernel_constraint=const)(d)\n d = LeakyReLU(alpha=0.2)(d)\n # conv 4x4\n d = keras.layers.Conv2D(128, (4, 4), padding='same', kernel_initializer=init, kernel_constraint=const)(d)\n d = LeakyReLU(alpha=0.2)(d)\n # dense output layer\n d = Flatten()(d)\n out_class = Dense(1)(d)\n # define model\n model = Model(in_image, out_class)\n # compile model\n model.compile(loss=wasserstein_loss, optimizer=Adam(lr=0.001, beta_1=0, beta_2=0.99, epsilon=10e-8))\n # store model\n model_list.append([model, model])\n # create submodels\n for i in range(1, n_blocks):\n # get prior model without the fade-on\n old_model = model_list[i - 1][0]\n # create new model for next resolution\n models = add_discriminator_block(old_model)\n # store model\n model_list.append(models)\n return model_list\n\n\n# define composite models for training generators via discriminators\ndef define_composite(discriminators, generators):\n model_list = list()\n # create composite models\n for i in range(len(discriminators)):\n g_models, d_models = generators[i], discriminators[i]\n # straight-through model\n d_models[0].trainable = False\n model1 = Sequential()\n model1.add(g_models[0])\n model1.add(d_models[0])\n model1.compile(loss=wasserstein_loss, optimizer=Adam(lr=0.001, beta_1=0, beta_2=0.99, epsilon=10e-8))\n # fade-in model\n d_models[1].trainable = False\n model2 = Sequential()\n model2.add(g_models[1])\n model2.add(d_models[1])\n model2.compile(loss=wasserstein_loss, optimizer=Adam(lr=0.001, beta_1=0, beta_2=0.99, epsilon=10e-8))\n # store\n model_list.append([model1, model2])\n return model_list\n\n\ndef ResnetGenerator(input_shape=(256, 256, 3),\n output_channels=3,\n dim=64,\n n_downsamplings=2,\n n_blocks=9,\n norm='instance_norm'):\n Norm = _get_norm_layer(norm)\n\n def _residual_block(x):\n dim = x.shape[-1]\n h = x\n\n h = tf.pad(h, [[0, 0], [1, 1], [1, 1], [0, 0]], mode='REFLECT')\n h = keras.layers.Conv2D(dim, 3, padding='valid', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.relu(h)\n\n h = tf.pad(h, [[0, 0], [1, 1], [1, 1], [0, 0]], mode='REFLECT')\n h = keras.layers.Conv2D(dim, 3, padding='valid', use_bias=False)(h)\n h = Norm()(h)\n\n return keras.layers.add([x, h])\n\n # 0\n h = inputs = keras.Input(shape=input_shape)\n\n # 1\n h = tf.pad(h, [[0, 0], [3, 3], [3, 3], [0, 0]], mode='REFLECT')\n h = keras.layers.Conv2D(dim, 7, padding='valid', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.relu(h)\n\n # 2\n for _ in range(n_downsamplings):\n dim *= 2\n h = keras.layers.Conv2D(dim, 3, strides=2, padding='same', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.relu(h)\n\n # 3\n for _ in range(n_blocks):\n h = _residual_block(h)\n\n # 4\n for _ in range(n_downsamplings):\n dim //= 2\n h = keras.layers.Conv2DTranspose(dim, 3, strides=2, padding='same', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.relu(h)\n\n # 5\n h = tf.pad(h, [[0, 0], [3, 3], [3, 3], [0, 0]], mode='REFLECT')\n h = keras.layers.Conv2D(output_channels, 7, padding='valid')(h)\n h = tf.tanh(h)\n\n return keras.Model(inputs=inputs, outputs=h)\n\n\ndef ConvDiscriminator(input_shape=(256, 256, 3),\n dim=64,\n n_downsamplings=3,\n norm='instance_norm'):\n dim_ = dim\n Norm = _get_norm_layer(norm)\n\n # 0\n h = inputs = keras.Input(shape=input_shape)\n\n # 1\n h = keras.layers.Conv2D(dim, 4, strides=2, padding='same')(h)\n h = tf.nn.leaky_relu(h, alpha=0.2)\n\n for _ in range(n_downsamplings - 1):\n dim = min(dim * 2, dim_ * 8)\n h = keras.layers.Conv2D(dim, 4, strides=2, padding='same', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.leaky_relu(h, alpha=0.2)\n\n # 2\n dim = min(dim * 2, dim_ * 8)\n h = keras.layers.Conv2D(dim, 4, strides=1, padding='same', use_bias=False)(h)\n h = Norm()(h)\n h = tf.nn.leaky_relu(h, alpha=0.2)\n\n # 3\n h = keras.layers.Conv2D(1, 4, strides=1, padding='same')(h)\n\n return keras.Model(inputs=inputs, outputs=h)\n\n\n# ==============================================================================\n# = learning rate scheduler =\n# ==============================================================================\n\nclass LinearDecay(keras.optimizers.schedules.LearningRateSchedule):\n # if `step` < `step_decay`: use fixed learning rate\n # else: linearly decay the learning rate to zero\n\n def __init__(self, initial_learning_rate, total_steps, step_decay):\n super(LinearDecay, self).__init__()\n self._initial_learning_rate = initial_learning_rate\n self._steps = total_steps\n self._step_decay = step_decay\n self.current_learning_rate = tf.Variable(initial_value=initial_learning_rate, trainable=False, dtype=tf.float32)\n\n def __call__(self, step):\n self.current_learning_rate.assign(tf.cond(\n step >= self._step_decay,\n true_fn=lambda: self._initial_learning_rate * (\n 1 - 1 / (self._steps - self._step_decay) * (step - self._step_decay)),\n false_fn=lambda: self._initial_learning_rate\n ))\n return self.current_learning_rate\n","sub_path":"module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":14924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"52306678","text":"import sqlite3\nimport datetime\n\ntoday = datetime.date.today()\n\n\ndef create_connection(db_file):\n \"\"\" create a database connection to the SQLite database\n specified by the db_file\n :param db_file: database file\n :return: Connection object or None\n \"\"\"\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n\n return None\n\n\ndef delete_task(conn, check_out):\n \"\"\"\n Delete a task by task id\n :param conn: Connection to the SQLite database\n :param id: id of the task\n :return:\n \"\"\"\n sql = 'DELETE FROM user WHERE check_out=?'\n cur = conn.cursor()\n cur.execute(sql, (str(check_out),))\n\n\ndef delete_all_tasks(conn):\n \"\"\"\n Delete all rows in the tasks table\n :param conn: Connection to the SQLite database\n :return:\n \"\"\"\n sql = 'DELETE FROM user'\n cur = conn.cursor()\n cur.execute(sql)\n\n\ndef main():\n database = \"site.db\"\n\n # create a database connection\n conn = create_connection(database)\n with conn:\n delete_task(conn, today)\n # delete_all_tasks(conn);\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ef_palace/filterDB.py","file_name":"filterDB.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185908320","text":"\"\"\"\nauthor : zhancc\nfilename : md5sum.py\ndate : 2020/06/09 16:24:56\ndescription : 计算文件的MD5值,在当前目录生成md5.txt;\n 查找某个目录下的所有特定格式文件,在同目录下生成md5.txt。\n\"\"\"\n\nimport os\nimport codecs\nimport hashlib\nimport argparse\n\n\ndef md5sum(file_path: str):\n \"\"\"\n 计算文件的MD5\n :param file_path: str\n :return: str\n \"\"\"\n if not os.path.exists(file_path):\n raise FileExistsError(\"{0} cannot be found\".format(file_path))\n if not os.path.isfile(file_path):\n raise TypeError(\"{0} is not a file\".format(file_path))\n sh = hashlib.md5()\n with open(file_path, \"rb\") as fp:\n buff = b\"\"\n while True:\n buff = fp.read(4096)\n if buff:\n sh.update(buff)\n else:\n break\n return sh.hexdigest()\n\n\ndef output_to_file(file_path: str, md5_dict: dict):\n \"\"\"\n 将MD5值和文件名输出到同级目录的md5.txt中\n :param file_path:\n :param md5_dict:\n :return:\n \"\"\"\n with codecs.open(file_path, \"w\", \"utf-8\") as fp:\n for key in md5_dict:\n md5_string = \"{0} {1}\".format(key, md5_dict.get(key))\n fp.write(md5_string + \"\\n\")\n print(md5_string)\n\n\ndef find_files(directory: str, formats: tuple = (\"sql\",)):\n \"\"\"\n 递归查找特定格式的文件\n :param directory: str\n :param formats: list\n :return: str\n \"\"\"\n for item in os.listdir(directory):\n path = os.path.join(directory, item)\n if os.path.isfile(path):\n if item.split(\".\")[-1] in formats:\n base_dir = \"\\\\\".join(path.split(\"\\\\\")[:-1])\n md5_path = os.path.join(base_dir, \"md5.txt\")\n output_to_file(md5_path, {item: md5sum(path)})\n else:\n pass\n elif os.path.isdir(path):\n find_files(path, formats)\n\n\ndef get_options():\n parser = argparse.ArgumentParser(\n prog=\"md5sum\", description=\"\", prefix_chars=\"-\",\n add_help=True, allow_abbrev=True, usage=\"\"\"\n python md5sum.py -d directory1 directory2 -t sql\n python md5sum.py -f game1.sql game2.sql\"\"\"\n )\n parser.add_argument(\"-f\", \"--file\", dest=\"files\", nargs=\"+\", help=\"file to md5sum\")\n parser.add_argument(\"-d\", \"--dir\", dest=\"dir\", nargs=\"+\", help=\"dir to md5sum\")\n parser.add_argument(\"-t\", \"--type\", dest=\"type\", nargs=\"+\", default=\"sql\", help=\"default=sql\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = get_options()\n formats = args.type if args.type else []\n if args.dir:\n for directory in args.dir:\n find_files(directory, formats)\n if args.files:\n md5_dict = dict()\n for file in args.files:\n if not os.path.exists(file):\n raise FileExistsError(\"{0} cannot be found\".format(file))\n md5_value = md5sum(file)\n md5_dict.update({md5_value: file})\n output_to_file(\"md5.txt\", md5_dict)\n\n","sub_path":"app/md5sum.py","file_name":"md5sum.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"91565795","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron_lib.callbacks import events\nfrom neutron_lib.callbacks import registry\nfrom neutron_lib.callbacks import resources\nfrom neutron_lib.db import model_base\nfrom oslo_log import log as logging\nfrom oslo_utils import uuidutils\nimport sqlalchemy as sa\nfrom sqlalchemy import and_\n\nfrom neutron.db import api as db_api\nfrom neutron.db.models import segment as segments_model\nfrom neutron.objects import base as base_obj\nfrom neutron.objects import network as network_obj\n\nLOG = logging.getLogger(__name__)\n\nNETWORK_TYPE = segments_model.NetworkSegment.network_type.name\nPHYSICAL_NETWORK = segments_model.NetworkSegment.physical_network.name\nSEGMENTATION_ID = segments_model.NetworkSegment.segmentation_id.name\nNETWORK_ID = segments_model.NetworkSegment.network_id.name\n\n\ndef _make_segment_dict(obj):\n \"\"\"Make a segment dictionary out of an object.\"\"\"\n #NOTE(jrichard) drop change in next rebase.\n return {'id': obj.id,\n NETWORK_TYPE: obj.network_type,\n PHYSICAL_NETWORK: obj.physical_network,\n SEGMENTATION_ID: obj.segmentation_id,\n NETWORK_ID: getattr(obj, 'network_id', None)}\n\n\nclass SubnetSegment(model_base.BASEV2, model_base.HasId):\n \"\"\"Represent persistent state of a subnet segment.\n\n A subnet segment is a portion of a neutron subnet with a\n specific physical realization. A neutron subnet can consist of\n one or more segments.\n \"\"\"\n\n # TODO(alegacy): rename this similar to how the NetworkSegments table was\n # renamed?\n __tablename__ = 'ml2_subnet_segments'\n\n subnet_id = sa.Column(sa.String(36),\n sa.ForeignKey('subnets.id', ondelete=\"CASCADE\"),\n nullable=False)\n network_type = sa.Column(sa.String(32), nullable=False)\n physical_network = sa.Column(sa.String(64))\n segmentation_id = sa.Column(sa.Integer)\n is_dynamic = sa.Column(sa.Boolean, default=False, nullable=False,\n server_default=sa.sql.false())\n segment_index = sa.Column(sa.Integer, nullable=False, server_default='0')\n\n\ndef add_network_segment(context, network_id, segment, segment_index=0,\n is_dynamic=False):\n with db_api.context_manager.writer.using(context):\n netseg_obj = network_obj.NetworkSegment(\n context, id=uuidutils.generate_uuid(), network_id=network_id,\n network_type=segment.get(NETWORK_TYPE),\n physical_network=segment.get(PHYSICAL_NETWORK),\n segmentation_id=segment.get(SEGMENTATION_ID),\n segment_index=segment_index, is_dynamic=is_dynamic)\n netseg_obj.create()\n registry.notify(resources.SEGMENT,\n events.PRECOMMIT_CREATE,\n trigger=add_network_segment,\n context=context,\n segment=netseg_obj)\n segment['id'] = netseg_obj.id\n LOG.info(\"Added segment %(id)s of type %(network_type)s for network \"\n \"%(network_id)s\",\n {'id': netseg_obj.id,\n 'network_type': netseg_obj.network_type,\n 'network_id': netseg_obj.network_id})\n\n\ndef get_network_segments(context, network_id, filter_dynamic=False):\n return get_networks_segments(\n context, [network_id], filter_dynamic)[network_id]\n\n\ndef get_networks_segments(context, network_ids, filter_dynamic=False):\n if not network_ids:\n return {}\n\n with db_api.context_manager.reader.using(context):\n filters = {\n 'network_id': network_ids,\n }\n if filter_dynamic is not None:\n filters['is_dynamic'] = filter_dynamic\n objs = network_obj.NetworkSegment.get_objects(context, **filters)\n result = {net_id: [] for net_id in network_ids}\n for record in objs:\n result[record.network_id].append(_make_segment_dict(record))\n return result\n\n\ndef get_segment_by_id(context, segment_id):\n with db_api.context_manager.reader.using(context):\n net_obj = network_obj.NetworkSegment.get_object(context, id=segment_id)\n if net_obj:\n return _make_segment_dict(net_obj)\n\n\ndef get_dynamic_segment(context, network_id, physical_network=None,\n segmentation_id=None):\n \"\"\"Return a dynamic segment for the filters provided if one exists.\"\"\"\n with db_api.context_manager.reader.using(context):\n filters = {\n 'network_id': network_id,\n 'is_dynamic': True,\n }\n if physical_network:\n filters['physical_network'] = physical_network\n if segmentation_id:\n filters['segmentation_id'] = segmentation_id\n pager = base_obj.Pager(limit=1)\n objs = network_obj.NetworkSegment.get_objects(\n context, _pager=pager, **filters)\n\n if objs:\n return _make_segment_dict(objs[0])\n else:\n LOG.debug(\"No dynamic segment found for \"\n \"Network:%(network_id)s, \"\n \"Physical network:%(physnet)s, \"\n \"segmentation_id:%(segmentation_id)s\",\n {'network_id': network_id,\n 'physnet': physical_network,\n 'segmentation_id': segmentation_id})\n\n\ndef delete_network_segment(context, segment_id):\n \"\"\"Release a dynamic segment for the params provided if one exists.\"\"\"\n with db_api.context_manager.writer.using(context):\n network_obj.NetworkSegment.delete_objects(context, id=segment_id)\n\n\ndef network_segments_exist(session, network_type, physical_network,\n segment_range=None):\n with session.begin(subtransactions=True):\n query = (session.query(segments_model.NetworkSegment).\n filter_by(network_type=network_type,\n physical_network=physical_network))\n if segment_range:\n minimum_id = segment_range['minimum']\n maximum_id = segment_range['maximum']\n query = (query.filter(and_(\n segments_model.NetworkSegment.segmentation_id >= minimum_id,\n segments_model.NetworkSegment.segmentation_id <= maximum_id\n )))\n return bool(query.count() > 0)\n\n\ndef add_subnet_segment(session, subnet_id, segment, segment_index=0,\n is_dynamic=False):\n with session.begin(subtransactions=True):\n record = SubnetSegment(\n id=uuidutils.generate_uuid(),\n subnet_id=subnet_id,\n network_type=segment.get(NETWORK_TYPE),\n physical_network=segment.get(PHYSICAL_NETWORK),\n segmentation_id=segment.get(SEGMENTATION_ID),\n segment_index=segment_index,\n is_dynamic=is_dynamic\n )\n session.add(record)\n LOG.info(\"Added segment %(id)s of type %(network_type)s for subnet\"\n \" %(subnet_id)s\",\n {'id': record.id,\n 'network_type': record.network_type,\n 'subnet_id': record.subnet_id})\n\n\ndef get_subnet_segments(session, subnet_id, filter_dynamic=False):\n return get_subnets_segments(\n session, [subnet_id], filter_dynamic)[subnet_id]\n\n\ndef get_subnets_segments(session, subnet_ids, filter_dynamic=False):\n if not subnet_ids:\n return {}\n with session.begin(subtransactions=True):\n query = (session.query(SubnetSegment).\n filter(SubnetSegment.subnet_id.in_(subnet_ids)).\n order_by(SubnetSegment.segment_index))\n if filter_dynamic is not None:\n query = query.filter_by(is_dynamic=filter_dynamic)\n records = query.all()\n result = {subnet_id: [] for subnet_id in subnet_ids}\n for record in records:\n result[record.subnet_id].append(_make_segment_dict(record))\n return result\n\n\ndef subnet_segments_exist(session, network_type, physical_network,\n segment_range=None):\n with session.begin(subtransactions=True):\n query = (session.query(SubnetSegment).\n filter_by(network_type=network_type,\n physical_network=physical_network))\n if segment_range:\n minimum_id = segment_range['minimum']\n maximum_id = segment_range['maximum']\n query = (query.filter(\n and_(SubnetSegment.segmentation_id >= minimum_id,\n SubnetSegment.segmentation_id <= maximum_id)))\n return bool(query.count() > 0)\n","sub_path":"neutron/db/segments_db.py","file_name":"segments_db.py","file_ext":"py","file_size_in_byte":9045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"583605673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 22 13:02:51 2019\r\n\r\n@author: sidhant\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport tensorflow\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nfrom keras.utils import plot_model\r\nfrom keras.datasets import fashion_mnist\r\nfrom keras.models import Model\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Input,Flatten,Dropout,Activation\r\nfrom sklearn.metrics import r2_score,confusion_matrix\r\nfrom tensorflow.keras import regularizers\r\nfrom keras.utils import np_utils\r\nfrom keras.optimizers import SGD,Adam,Adamax\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC\r\nfrom sklearn import metrics\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\n#\r\ndef metrices(data):\r\n data1=pd.DataFrame(columns=['Car','Still','Train','Walking','Bus','Precision','Recall','F1'])\r\n data1['Car']=data[0]\r\n data1['Still']=data[1]\r\n data1['Train']=data[2]\r\n data1['Walking']=data[3]\r\n data1['Bus']=data[4]\r\n precision=[]\r\n recall=[]\r\n sums=data.sum(axis=0)\r\n\r\n# print(\"preci\",sums)\r\n for i in range(len(sums)):\r\n recall.append(data[i][i]/sums[i])\r\n \r\n\r\n \r\n# print(\"recall\",recall)\r\n sum2=data.sum(axis=1)\r\n for i in range(len(sums)):\r\n precision.append(data[i][i]/sum2[i])\r\n \r\n\r\n# print(precision)\r\n data1['Precision']=precision\r\n data1['Recall']=recall\r\n# print(data1)\r\n data1['F1']=data1.F1.fillna(data1['Precision']*data1['Recall']/(data1['Precision']+data1['Recall']))\r\n \r\n return data1\r\n \r\n\r\n\r\ndef AE_method2(x_train,Ytrain):\r\n model = Sequential()\r\n input_size=x_train.shape[1]\r\n \r\n model.add(Dense(240,input_dim=input_size,activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n model.add(Dense(240,input_dim=input_size,activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n model.add(Dense(200,input_dim=input_size,activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n \r\n model.add(Dropout(0.1))\r\n model.add(Dense(200,input_dim=input_size,activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n \r\n model.add(Dropout(0.1))\r\n# model.add(Dense(32, activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n# model.add(Dropout(0.3))\r\n model.add(Dense(200, activation='relu' ,kernel_regularizer=regularizers.l2(0.01)))\r\n model.add(Dropout(0.1))\r\n# sgd=SGD(lr=0.03,decay=1e-6,momentum=0.5,nesterov=True)\r\n adam=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False) \r\n \r\n model.add(Dense(5))\r\n model.add(Activation('softmax'))\r\n \r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=adam,\r\n metrics=['accuracy'])\r\n return model\r\ndef model_randomForrest(X_train,y_train):\r\n rfclassifier = RandomForestClassifier(n_estimators=90, oob_score=True)\r\n rfclassifier.fit(X_train, y_train)\r\n return rfclassifier\r\n\r\ndata =pd.read_csv('C:\\sidhant\\CA3\\Dataset\\Data.csv')\r\n#print(data.info())\r\ndata=data.drop(['android.sensor.accelerometer#min','android.sensor.accelerometer#max',\r\n 'android.sensor.game_rotation_vector#min','android.sensor.game_rotation_vector#max',\r\n 'android.sensor.gyroscope#min','android.sensor.gyroscope#max',\r\n 'android.sensor.gyroscope_uncalibrated#min','android.sensor.gyroscope_uncalibrated#max',\r\n 'android.sensor.linear_acceleration#min','android.sensor.linear_acceleration#max',\r\n 'android.sensor.orientation#min','android.sensor.orientation#max',\r\n 'android.sensor.rotation_vector#min','android.sensor.rotation_vector#max',\r\n 'sound#min','sound#max','speed#min','speed#max'],axis=1)\r\n\r\ndata['target']=data['target'].astype('category')\r\ndata['target']=data['target'].cat.codes\r\n\r\ndata=data.drop('time',axis=1)\r\nX=data.drop('target',axis=1)\r\ny=data['target']\r\n#dummy_y = np_utils.to_categorical(y)\r\n\r\nXtrain,Xtest,Ytrain,Ytest=train_test_split(X,y,test_size=0.30,random_state=4)\r\n#Xtrain=Xtrain.values\r\n#Xtest=Xtest.values\r\nXtrain=preprocessing.StandardScaler().fit_transform(Xtrain)\r\nXtest=preprocessing.StandardScaler().fit_transform(Xtest)\r\n\r\n\r\n#\r\n#model=AE_method2(Xtrain,Ytrain)\r\n#model.fit(Xtrain, Ytrain, batch_size=40, epochs=70, validation_split=0.3)\r\n#\r\n#\r\n#prediction=model.predict(Xtest)\r\n#result=model.summary()\r\n#result=tensorflow.keras.metrics.Accuracy(Ytest,prediction)\r\n#result=r2_score(Ytest,prediction)\r\n#print(result)\r\n\r\nmodel=model_randomForrest(Xtrain,Ytrain)\r\nprediction=model.predict(Xtest)\r\nresult=metrics.accuracy_score(Ytest,prediction)\r\n#result=r2_score(Ytest,prediction)\r\nconf_matrix=confusion_matrix(Ytest,prediction)\r\nprint(result)\r\ndata=pd.DataFrame(conf_matrix)\r\noutput= metrices(data)\r\nprint(\"confusion matrix with metrices for random forest:\\n\",output)\r\n\r\n\r\n\r\nmodel= DecisionTreeClassifier(max_depth=19)\r\nmodel.fit(Xtrain, Ytrain)\r\nprediction=model.predict(Xtest)\r\nresult=metrics.accuracy_score(Ytest,prediction)\r\n#result=r2_score(Ytest,prediction)\r\nconf_matrix=confusion_matrix(Ytest,prediction)\r\nprint(result)\r\ndata=pd.DataFrame(conf_matrix)\r\noutput= metrices(data)\r\nprint(\"confusion matrix with metrices for decision tree:\\n\",output)\r\n\r\n#model = GaussianNB()\r\n#model.fit(Xtrain,Ytrain)\r\n#prediction=model.predict(Xtest)\r\n#result=metrics.accuracy_score(Ytest,prediction)\r\n#print(result)\r\n#conf_matrix=confusion_matrix(Ytest,prediction)\r\n#data=pd.DataFrame(conf_matrix)\r\n#output= metrices(data)\r\n#print(\"confusion matrix with metrices for naive gaussian:\\n\",output)\r\n\r\n\r\n\r\nsvclassifier = SVC(kernel='rbf', gamma=0.09,C=22,tol=0.9) \r\nsvclassifier.fit(Xtrain,Ytrain)\r\nprediction=svclassifier.predict(Xtest)\r\nprint(svclassifier)\r\nresult1=metrics.accuracy_score(Ytest,prediction)\r\n\r\n#result=r2_score(Ytest,prediction)\r\nprint(result1)\r\nconf_matrix=confusion_matrix(Ytest,prediction)\r\ndata=pd.DataFrame(conf_matrix)\r\noutput= metrices(data)\r\nprint(\"confusion matrix with metrices for SVC:\\n\",output)\r\n\r\n","sub_path":"CA3.py","file_name":"CA3.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"507096616","text":"\r\nimport os, time\r\nimport glob\r\nimport smtplib\r\n\r\nprint('Enter imsgw path directory of your local compilation')\r\npath = input()\r\nprint('Enter your email ID')\r\nemail = input()\r\nTO = [email]\r\nFROM = ['Your_Personal_laptop@nokia.com']\r\nsmtpObj = smtplib.SMTP('dhn-mailrelay.emea.nsn-intra.net',25)\r\n\r\nfor infile in glob.glob( os.path.join(path, 'log*') ):\r\n print ('current file is: ' + infile)\r\n \r\nprint('Tracking compilation')\r\ndef tracker():\r\n if 'IMSGW Build Ended' in open(infile).read():\r\n print('Its finished')\r\n if 'Compilation failure' in open(infile).read():\r\n print('Compilaton done, FAILURE sending mail')\r\n smtpObj.sendmail(FROM, TO, 'Subject: Local Compilation Done!\\nHello,\\n\\n Greetings from your personal Laptop\\n\\n Unfortunately your Local compilation was a FAILURE!! Please check!')\r\n else:\r\n print('Compilaton done, SUCCESS sending mail')\r\n smtpObj.sendmail(FROM, TO, 'Subject: Local Compilation Done!\\nHello,\\n\\n Greetings from your personal Laptop\\n\\n Your Local compilation was a Success!! ')\r\n smtpObj.quit()\r\n\r\n else:\r\n return 'No'\r\n\r\n\r\nwhile tracker() == 'No':\r\n #print('Sleeping for 5 mins and checking again')\r\n time.sleep(300)\r\n\r\n\r\n\r\n\r\n \r\n\r\n \r\n \r\n\r\n \r\n\r\n\r\n\r\n\r\n","sub_path":"find_file.py","file_name":"find_file.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"265273409","text":"#Clase Car recibe informacion de un vehiculo\n\nclass Car():\n \"\"\"A simple attempt to represent a car\"\"\"\n\n def __init__(self,make,model,year):\n \"\"\"Initialize attributes to describe a car.\"\"\"\n self.make = make\n self.model = model\n self.year = year\n self.odometer_reading = 0 #Atributo por default\n\n def get_descriptive_name(self):\n \"\"\"Return a neatly formatted descriptive name.\"\"\"\n long_name = str(self.year) + ' ' + self.make + ' ' + self.model\n return long_name.title()\n \n def read_odometer(self):\n \"\"\"Print a statement showing the car's mileage\"\"\"\n print(\"This car has \" + str(self.odometer_reading) + \" miles on it.\")\n\n def update_odometer(self,mileage):\n \"\"\"Set the odometer reading to the given value.\n Reject the change if it attempts to roll the odometer back.\n \"\"\"\n\n if mileage > self.odometer_reading:\n self.odometer_reading = mileage \n else:\n print(\"You can't rollback an odometer.\")\n\n def increment_odometer(self,miles):\n \"\"\"Add the given amount to the odometer reading\"\"\"\n self.odometer_reading += miles\n\n\n#Creacion de la clase Batery\nclass Battery():\n \"\"\"A simple attempt to model a battery for a electric car.\"\"\"\n\n def __init__(self,battery_size=70):\n \"\"\"Initialize the battery's attributes.\"\"\"\n self.battery_size = battery_size\n\n def describe_battery(self):\n \"\"\"print a statement describing the battery size.\"\"\"\n print(\"This car has a \" + str(self.battery_size) + \" -kWh battery\")\n \n def get_range(self):\n \"\"\"print a statement about the range this battery provides\"\"\"\n if self.battery_size == 70:\n range_ = 240\n elif self.battery_size == 85:\n range_ = 270\n\n message = \"This car can go approximately \" + str(range_)\n message += \" miles on a full charge.\"\n print(message)\n\n\n#Creacion de la clase ElectricCar que hereda de la clase car\nclass ElectricCar(Car):\n \"\"\"Respresent aspect of a car, specific to electric vehicules.\"\"\"\n\n def __init__(self,make,model,year):\n \"\"\"Initialize attributes of the parents class\"\"\"\n super().__init__(make,model,year) #Heredando atributos de car\n self.battery = Battery()\n\n\n\n#Instanciando objetos de las clases creadas\n\nmy_new_car = Car('audi','a4','2016')\nprint(my_new_car.get_descriptive_name())\n\n#Seteando el valor de un atributo desde la instancia\nmy_new_car.odometer_reading = 23\nmy_new_car.read_odometer()\n\n#Modifying an attribute's values throught a method\nmy_new_car.update_odometer(10)\nmy_new_car.read_odometer()\n\n#Increment an attribute's values through a method\nprint(\"\\n\")\nmy_used_car = Car('subaru','impreza','2006')\nprint(my_used_car.get_descriptive_name())\nmy_used_car.increment_odometer(100)\nmy_used_car.read_odometer()\n\n#Instanciando objetos de la clase ElectricCar\nprint(\"\\n\")\nmy_tesla = ElectricCar('tesla','model s','2016')\nprint(my_tesla.get_descriptive_name()) #LLamando a un metodo heredado de la clase Car\n\n#Accesando al atrinuto battery que a su vez es llama al metodo\n#de la clase Battery\nmy_tesla.battery.describe_battery()\nmy_tesla.battery.get_range()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"class_car.py","file_name":"class_car.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"174720389","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, current_app\nfrom keras.models import load_model\nfrom service import utils\n\n\ndef predict(image):\n image_size = current_app.config['IMAGE_SIZE']\n model_path = current_app.config['MODEL_PATH']\n\n model = load_model(model_path)\n\n # useful when testing with full size image\n if image.shape != (image_size, image_size, 3):\n image = utils.resize_with_pad(image, image_size, image_size)\n\n image = image.reshape((1, image_size, image_size, 3))\n image = image.astype('float32')\n image /= 255\n\n result = model.predict_proba(image) # numpy.ndarray\n print(result)\n\n # predictions = result[0].tolist()\n # if predictions[0] > 0.8:\n # return 0 # boss\n # else:\n # return 1 # non boss\n\n result = model.predict_classes(image)\n\n return result[0]\n","sub_path":"service/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"52212923","text":"import os\nimport os.path\nimport shutil\n\nimport psutil\nimport nose.tools\n\n# perform an acpidump as root\ndef test_acpidump(dir_str='./acpi_dump'):\n\n cur_dir = os.path.abspath(os.curdir)\n\n if os.path.exists(dir_str):\n # if file, remove it\n if os.path.isfile(dir_str):\n os.remove(test_dir)\n if os.path.isdir(dir_str):\n shutil.rmtree(dir_str)\n\n os.makedirs(dir_str)\n os.chdir(dir_str)\n proc = psutil.Popen('sudo acpidump -o acpi.bin', shell=True)\n proc.wait()\n\n msg = 'Was not able to dump ACPI tables'\n nose.tools.eq_(os.path.isfile('acpi.bin'), True, msg)\n\n stat = os.stat('acpi.bin')\n msg = 'ACPI Tables File is 0 length'\n nose.tools.eq_(stat.st_size == 0, False, msg)\n\n os.chdir(cur_dir)\n\n\n# perform an acpixtract , extracts files\ndef test_acpixtract(dir_str='./acpi_dump'):\n\n cur_dir = os.path.abspath(os.curdir)\n if os.path.exists(dir_str) is False:\n msg = '{0} is not created'.format(dir_str)\n nose.tools.eq_(True, True, msg)\n\n os.chdir(dir_str)\n proc = psutil.Popen('acpixtract acpi.bin', shell=True)\n proc.wait()\n\n msg = 'Was not able to extract DSDT'\n nose.tools.eq_(os.path.isfile('dsdt.dat'), True, msg)\n\n stat = os.stat('dsdt.dat')\n msg = 'ACPI DSDT is 0 length'\n nose.tools.eq_(stat.st_size == 0, False, msg)\n os.chdir(cur_dir)\n\n\n# perform an iasl decompile, -d dsdt.dat ssdt*.dat\ndef test_iasl_decompile(dir_str='./acpi_dump'):\n\n cur_dir = os.path.abspath(os.curdir)\n if os.path.exists(dir_str) is False:\n msg = '{0} is not created'.format(dir_str)\n nose.tools.eq_(True, True, msg)\n\n os.chdir(dir_str)\n proc = psutil.Popen('iasl -d dsdt.dat ssdt*.dat', shell=True)\n proc.wait()\n\n msg = 'Was not able to Disassmble DSDT'\n nose.tools.eq_(os.path.isfile('dsdt.dsl'), True, msg)\n\n stat = os.stat('dsdt.dsl')\n msg = 'ACPI DSDT Disassembly is 0 length'\n nose.tools.eq_(stat.st_size == 0, False, msg)\n os.chdir(cur_dir)\n\n","sub_path":"testing/tests/test_acpi.py","file_name":"test_acpi.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"322173440","text":"# coding=utf-8\r\nimport tensorflow as tf\r\nimport os\r\nimport numpy as np\r\nfrom tensorflow.python import pywrap_tensorflow\r\nfrom tensorflow.python.tools import inspect_checkpoint as chkp\r\n\r\n\r\nclass Saver(object):\r\n\r\n def __init__(self, sess, param, checkpoint_dir, logger):\r\n \"\"\"\r\n :param sess: session with model graph built\r\n :param param: checkpoint_dir: the path of checkpoint file\r\n max_to_keep: max number of checkpoint to keep during training\r\n input_list: input nodes of model when save to pb model\r\n output_list: output nodes of model when save to pb model\r\n pb_save_path: path to save pb model\r\n pb_name: name to save pb model\r\n mode: whether CBR module is used or not in model\r\n\r\n \"\"\"\r\n self.session = sess\r\n self.logger = logger\r\n self.checkPoint_dir = checkpoint_dir\r\n self.max_to_keep = param[\"max_to_keep\"]\r\n self.input_nodes = param[\"input_list\"]\r\n self.output_nodes = param[\"output_list\"]\r\n self.pb_save_path = param[\"pb_save_path\"]\r\n self.pbModel_name = param[\"pb_name\"]\r\n self.saving_mode = param[\"saving_mode\"]\r\n self.mode = param[\"mode\"]\r\n\r\n self.ckpt = tf.train.latest_checkpoint(self.checkPoint_dir)\r\n self.init_op = tf.global_variables_initializer()\r\n self.step = 0\r\n\r\n with self.session.as_default():\r\n self.init_op.run()\r\n self.var_list = tf.trainable_variables()\r\n g_list = tf.global_variables()\r\n bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name]\r\n bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name]\r\n self.var_list += bn_moving_vars\r\n\r\n if self.saving_mode == \"CBR\":\r\n var_list2 = [v for v in self.var_list if \"bias\" not in v.name or \"CBR\" not in v.name]\r\n self.saver = tf.train.Saver(var_list2, max_to_keep=self.max_to_keep)\r\n else:\r\n self.saver = tf.train.Saver(self.var_list, max_to_keep=self.max_to_keep)\r\n\r\n def load_checkpoint(self):\r\n \"\"\"\r\n Restore session from checkpoint\r\n Used when continue to train\r\n\r\n \"\"\"\r\n if self.ckpt:\r\n self.step = int(self.ckpt.split('-')[1])\r\n print('Restoring from epoch:{}'.format(self.step))\r\n self.logger.info(\"Restoring from {}\".format(self.ckpt))\r\n self.saver.restore(self.session, self.ckpt)\r\n else:\r\n print('Cannot find checkpoint, start with new model')\r\n self.logger.info('Cannot find checkpoint, start with new model')\r\n\r\n def save_checkpoint(self, step):\r\n \"\"\"\r\n Save session to checkpoint during training\r\n \"\"\"\r\n if not os.path.exists(self.checkPoint_dir):\r\n os.makedirs(self.checkPoint_dir)\r\n\r\n self.saver.save(self.session, os.path.join(self.checkPoint_dir, 'ckp'), global_step=+step)\r\n self.logger.info(\"Saved to {}\".format(self.checkPoint_dir+'/ckp-{}'.format(step)))\r\n\r\n def save_pb(self):\r\n \"\"\"\r\n Restore session from checkpoint and save to .pb model\r\n the saving_mode should be set to CBR if the model used CBR module(combine BatchNorm layer with Conv layer in order to speed up inference),\r\n\r\n \"\"\"\r\n if self.saving_mode == \"CBR\":\r\n reader = pywrap_tensorflow.NewCheckpointReader(self.ckpt)\r\n var_to_shape_map = reader.get_variable_to_shape_map()\r\n source_list = [key for key in var_to_shape_map if \"CBR\" in key]\r\n epsilon = 0.001\r\n for key in source_list:\r\n if \"moving_mean\" in key:\r\n mean = np.array(reader.get_tensor(key))\r\n\r\n key_var = key[0:-11] + \"moving_variance\"\r\n var = np.array(reader.get_tensor(key_var))\r\n\r\n key_gamma = key[0:-11] + \"gamma\"\r\n gamma = np.array(reader.get_tensor(key_gamma))\r\n\r\n key_beta = key[0:-11] + \"beta\"\r\n beta = np.array(reader.get_tensor(key_beta))\r\n\r\n key_W = key[0:-14] + \"CBR_Conv2D/kernel\"\r\n W = np.array(reader.get_tensor(key_W))\r\n\r\n alpha = gamma / ((var + epsilon) ** 0.5)\r\n\r\n W_new = W * alpha\r\n\r\n B_new = beta - mean * alpha\r\n\r\n weight = tf.get_default_graph().get_tensor_by_name(key_W + ':0')\r\n\r\n update_weight = tf.assign(weight, W_new)\r\n\r\n bias_name = key_W[0:-6] + 'bias:0'\r\n\r\n bias = tf.get_default_graph().get_tensor_by_name(bias_name)\r\n\r\n update_bias = tf.assign(bias, B_new)\r\n\r\n self.session.run(update_weight)\r\n self.session.run(update_bias)\r\n\r\n else:\r\n self.saver.restore(self.session, self.ckpt)\r\n\r\n output_node_names = self.input_nodes + self.output_nodes\r\n output_graph_def = tf.graph_util.convert_variables_to_constants(self.session,\r\n self.session.graph_def,\r\n output_node_names)\r\n output_graph_def = tf.graph_util.remove_training_nodes(output_graph_def, protected_nodes=None)\r\n\r\n if not os.path.exists(self.pb_save_path):\r\n os.makedirs(self.pb_save_path)\r\n pbpath = os.path.join(self.pb_save_path, self.pbModel_name)\r\n print(\" Saved to {}\".format(pbpath))\r\n with tf.gfile.GFile(pbpath, mode='wb') as f:\r\n f.write(output_graph_def.SerializeToString())\r\n\r\n @staticmethod\r\n def inspect_checkpoint(inspect_checkpoint_path):\r\n \"\"\" Print nodes in checkpoint\"\"\"\r\n chkp.print_tensors_in_checkpoint_file(file_name=inspect_checkpoint_path,\r\n tensor_name=None, # 如果为None,则默认为ckpt里的所有变量\r\n all_tensors=False, # bool 是否打印所有的tensor,这里打印出的是tensor的值,一般不推荐这里设置为False\r\n all_tensor_names=False) # bool 是否console.WriteLine(files1[i]);打印所有的tensor的name\r\n\r\n @staticmethod\r\n def count_checkpoint_parameter(inspect_checkpoint_path):\r\n \"\"\" Count the parameter number of model \"\"\"\r\n ckpt = tf.train.get_checkpoint_state(inspect_checkpoint_path).model_checkpoint_path\r\n saver = tf.train.import_meta_graph(ckpt + '.meta')\r\n variables = tf.trainable_variables()\r\n total_parameters = 0\r\n for variable in variables:\r\n shape = variable.get_shape()\r\n variable_parameters = 1\r\n for dim in shape:\r\n # print(dim)\r\n variable_parameters *= dim.value\r\n # print(variable_parameters)\r\n total_parameters += variable_parameters\r\n print(\"the total number of parameter is {}\".format(total_parameters))\r\n\r\n","sub_path":"saver.py","file_name":"saver.py","file_ext":"py","file_size_in_byte":7182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"162304786","text":"from flask import Flask, request, render_template, jsonify, flash, redirect\nfrom handlers import handle_amount, handle_firstCurr, handle_secondCurr\nfrom flashers import flash_conversion, flash_errors\n\n\n# the main app for the currency converter\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'currency12$$'\n\n\n# render index.html when in the root route\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n# make a post request with the convertFrom, convertTo & amount values from the form.\n\n@app.route('/conversion', methods=['POST'])\ndef convert():\n errors = []\n\n firstCurr = request.form.get('convertFrom')\n secondCurr = request.form.get('convertTo')\n amount = request.form.get('amount')\n\n # check to see if all values are valid - if not, redirect and flash appropriate error message(s).\n handle_amount(errors, amount)\n handle_firstCurr(errors, firstCurr)\n handle_secondCurr(errors, secondCurr)\n\n # if all values are valid, redirect and flash the new converted value.\n if len(errors) > 0:\n flash_errors(errors)\n else:\n flash_conversion(firstCurr, secondCurr, amount)\n return redirect('/')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"607127260","text":"class Solution: \n \"\"\" \n @param numbers : An array of Integer \n @param target : target = numbers[index1] + numbers[index2] \n @return : [index1 + 1, index2 + 1] (index1 < index2) \n Space: O(N)\n Time: O(N)\n \"\"\" \n\n def twoSum(self, numbers, target): \n\n result = []\n # Create hash_map: [numbers[i], i]\n hash_map = dict()\n # sorted_array:\n sorted_array = sorted(numbers)\n\n # Create hash_map\n for i in range(len(numbers)):\n hash_map[numbers[i]] = i+1\n\n front = 0\n end = len(numbers)-1\n\n while front < end :\n if sorted_array[front]+sorted_array[end] < target:\n front += 1\n elif sorted_array[front]+sorted_array[end] > target:\n end -=1 \n else:\n # Real index is stored in hash_map\n first = hash_map[sorted_array[front]]\n second = hash_map[sorted_array[end]]\n if first < second:\n result.append(first)\n result.append(second)\n else:\n result.append(second)\n result.append(first)\n \n return result\n","sub_path":"downloads/code/LintCode/Two-Sum2.py","file_name":"Two-Sum2.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"459201263","text":"import os\nimport json\nimport luigi\n\nfrom .cluster_tasks import WorkflowBase\nfrom .watershed import WatershedWorkflow\nfrom .graph import GraphWorkflow\n# TODO more features and options to choose which features to choose\nfrom .features import EdgeFeaturesWorkflow\nfrom .costs import EdgeCostsWorkflow\nfrom .multicut import MulticutWorkflow\nfrom .decomposition_multicut import DecompositionWorkflow\nfrom .debugging import CheckSubGraphsWorkflow\nfrom . import write as write_tasks\n\n\nclass MulticutSegmentationWorkflow(WorkflowBase):\n input_path = luigi.Parameter()\n input_key = luigi.Parameter()\n # where to save the watersheds\n ws_path = luigi.Parameter()\n ws_key = luigi.Parameter()\n # where to save the multicut problems\n problem_path = luigi.Parameter()\n # where to save the node labels\n node_labels_path = luigi.Parameter()\n node_labels_key = luigi.Parameter()\n # where to save the resulting segmentation\n output_path = luigi.Parameter()\n output_key = luigi.Parameter()\n # number of scales\n n_scales = luigi.IntParameter()\n # optional path to mask\n mask_path = luigi.Parameter(default='')\n mask_key = luigi.Parameter(default='')\n # number of jobs used in feature merging\n max_jobs_merge_features = luigi.IntParameter(default=1)\n # number of jobs used for sub multicuts\n max_jobs_multicut = luigi.IntParameter(default=1)\n # use decomposer workflow\n skip_ws = luigi.BoolParameter(default=False)\n # path to random forest (if available)\n rf_path = luigi.Parameter(default='')\n # run some sanity checks for sub-results\n sanity_checks = luigi.BoolParameter(default=False)\n # TODO list to skip jobs\n\n def _get_mc_wf(self, dep):\n # hard-coded keys\n mc_wf = MulticutWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs_multicut,\n config_dir=self.config_dir,\n target=self.target,\n dependency=dep,\n problem_path=self.problem_path,\n n_scales=self.n_scales,\n assignment_path=self.node_labels_path,\n assignment_key=self.node_labels_key)\n return mc_wf\n\n # TODO implement mechanism to skip existing dependencies\n def requires(self):\n # hard-coded keys\n graph_key = 's0/graph'\n features_key = 'features'\n costs_key = 's0/costs'\n if self.skip_ws:\n assert os.path.exists(os.path.join(self.ws_path, self.ws_key)), \"%s:%s\" % (self.ws_path,\n self.ws_key)\n dep = self.dependency\n else:\n dep = WatershedWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n target=self.target,\n dependency=self.dependency,\n input_path=self.input_path,\n input_key=self.input_key,\n output_path=self.ws_path,\n output_key=self.ws_key,\n mask_path=self.mask_path,\n mask_key=self.mask_key)\n # TODO in the current implementation, we can only compute the\n # graph with n_scales=1, otherwise we will clash with the\n # multicut merged graphs\n dep = GraphWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n target=self.target,\n dependency=dep,\n input_path=self.ws_path,\n input_key=self.ws_key,\n graph_path=self.problem_path,\n output_key=graph_key,\n n_scales=1)\n if self.sanity_checks:\n graph_block_prefix = os.path.join(self.problem_path,\n 's0', 'sub_graphs', 'block_')\n dep = CheckSubGraphsWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n target=self.target,\n ws_path=self.ws_path,\n ws_key=self.ws_key,\n graph_block_prefix=graph_block_prefix,\n dependency=dep)\n # TODO add options to choose which features to use\n dep = EdgeFeaturesWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n target=self.target,\n dependency=dep,\n input_path=self.input_path,\n input_key=self.input_key,\n labels_path=self.ws_path,\n labels_key=self.ws_key,\n graph_path=self.problem_path,\n graph_key=graph_key,\n output_path=self.problem_path,\n output_key=features_key,\n max_jobs_merge=self.max_jobs_merge_features)\n dep = EdgeCostsWorkflow(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n target=self.target,\n dependency=dep,\n features_path=self.problem_path,\n features_key=features_key,\n output_path=self.problem_path,\n output_key=costs_key,\n rf_path=self.rf_path)\n dep = self._get_mc_wf(dep)\n write_task = getattr(write_tasks, self._get_task_name('Write'))\n dep = write_task(tmp_folder=self.tmp_folder,\n max_jobs=self.max_jobs,\n config_dir=self.config_dir,\n dependency=dep,\n input_path=self.ws_path,\n input_key=self.ws_key,\n output_path=self.output_path,\n output_key=self.output_key,\n assignment_path=self.node_labels_path,\n assignment_key=self.node_labels_key,\n identifier='multicut')\n return dep\n\n @staticmethod\n def get_config():\n config = {**WatershedWorkflow.get_config(),\n **GraphWorkflow.get_config(),\n **EdgeFeaturesWorkflow.get_config(),\n **EdgeCostsWorkflow.get_config(),\n **MulticutWorkflow.get_config()}\n return config\n","sub_path":"cluster_tools/workflows.py","file_name":"workflows.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"653327023","text":"import numpy as np\nimport copy\n\nfrom pommerman import constants\nfrom pommerman import utility\n\nSTEP_COUNT_POS = 0\nDONE_POS = 1\nAMMO_POS = 0\nBLAST_STRENGTH_POS = 1\nCAN_KICK_POS = 2\nALIVE_POS = 3\nROW_POS = 4\nCOL_POS = 5\n\n\nclass EnvSimulator:\n\n @staticmethod\n def get_initial_game_data(obs, my_id, max_steps=1000):\n board_size = len(obs['board'])\n\n game_data = EnvSimulator.get_board(board_size, obs['board'])\n agent_0_pos = EnvSimulator.get_position(game_data, 0, True)\n agent_1_pos = EnvSimulator.get_position(game_data, 1, True)\n\n game_info = np.zeros((1, board_size)).astype(np.uint16)\n game_info[0, STEP_COUNT_POS] = int(obs['step_count'])\n game_info[0, DONE_POS] = 0\n player1row = np.zeros((1, board_size)).astype(np.uint16)\n player1row[0, AMMO_POS] = int(obs['ammo'])\n player1row[0, BLAST_STRENGTH_POS] = int(obs['blast_strength'])\n player1row[0, CAN_KICK_POS] = int(obs['can_kick'])\n player1row[0, ALIVE_POS] = 1\n player1row[0, ROW_POS] = agent_0_pos[0]\n player1row[0, COL_POS] = agent_0_pos[1]\n player2row = np.zeros((1, board_size)).astype(np.uint16)\n player2row[0, AMMO_POS] = 1\n player2row[0, BLAST_STRENGTH_POS] = constants.DEFAULT_BLAST_STRENGTH\n player2row[0, CAN_KICK_POS] = False\n player2row[0, ALIVE_POS] = 1\n player2row[0, ROW_POS] = agent_1_pos[0]\n player2row[0, COL_POS] = agent_1_pos[1]\n bomb = np.zeros((1, board_size)).astype(np.uint16)\n game_data = np.vstack([game_data, game_info, player1row, player2row])\n\n return game_data\n\n @staticmethod\n def update(game_data, obs, my_id):\n enemy_id = 0\n if my_id == 0:\n enemy_id = 1\n\n step_count = EnvSimulator._get_game_value(game_data, STEP_COUNT_POS)\n\n if game_data.shape[1] != len(obs['board']):\n raise ValueError('Invalid update: boardsize different!')\n if step_count + 1 != int(obs['step_count']) and (step_count != 0 or int(obs['step_count']) != 0):\n raise ValueError('Invalid update: missed step count!')\n EnvSimulator._set_game_value(game_data, STEP_COUNT_POS, obs['step_count'])\n\n new_board = EnvSimulator._get_game_data_from_obs(obs)\n\n new_board = EnvSimulator.get_board(game_data.shape[1], obs['board'])\n new_bomb_life = EnvSimulator.get_board(game_data.shape[1], obs['bomb_life'], 0)\n\n # get actions\n actions = {}\n for agent_id in [10, 11]:\n old_pos = EnvSimulator.get_position(game_data, agent_id, True)\n new_pos = EnvSimulator.get_position(new_board, agent_id + 10, True)\n\n if old_pos != new_pos:\n actions[agent_id] = EnvSimulator.get_direction(old_pos, new_pos).value\n elif new_bomb_life[new_pos] == constants.DEFAULT_BOMB_LIFE:\n actions[agent_id] = constants.Action.Bomb.value\n else:\n actions[agent_id] = constants.Action.Stop.value\n\n EnvSimulator.act(game_data, actions)\n\n reset = False\n\n # compare boards\n if not EnvSimulator.boards_equal(EnvSimulator.get_game_data_board(game_data), new_board, True):\n a1bomb, a2bomb, kick, flame = EnvSimulator.get_boards_differences(\n EnvSimulator.get_game_data_board(game_data), new_board)\n #print(a1bomb, a2bomb, kick, flame)\n if a1bomb and my_id != 0:\n ammo = EnvSimulator._get_agent_value(game_data, 0, AMMO_POS)\n EnvSimulator._set_agent_value(game_data, 0, AMMO_POS, ammo+1)\n elif a2bomb and my_id != 1:\n ammo = EnvSimulator._get_agent_value(game_data, 1, AMMO_POS)\n EnvSimulator._set_agent_value(game_data, 1, AMMO_POS, ammo + 1)\n elif kick and EnvSimulator._get_agent_value(game_data, my_id, CAN_KICK_POS) == int(obs['can_kick']):\n EnvSimulator._set_agent_value(game_data, enemy_id, CAN_KICK_POS, 1)\n elif flame and EnvSimulator._get_agent_value(game_data, my_id, BLAST_STRENGTH_POS) == int(obs['blast_strength']):\n blast = EnvSimulator._get_agent_value(game_data, enemy_id, BLAST_STRENGTH_POS)\n EnvSimulator._set_agent_value(game_data, enemy_id, BLAST_STRENGTH_POS, blast+1)\n reset = True\n\n EnvSimulator._set_agent_value(game_data, enemy_id, AMMO_POS, int(obs['ammo']))\n EnvSimulator._set_agent_value(game_data, enemy_id, BLAST_STRENGTH_POS, int(obs['blast_strength']))\n EnvSimulator._set_agent_value(game_data, enemy_id, CAN_KICK_POS, int(obs['can_kick']))\n\n # update board because of items\n game_data[0:game_data.shape[1], 0:game_data.shape[1]] = new_board\n\n return game_data, actions, reset\n\n @staticmethod\n def _get_game_data_from_obs(obs):\n board_size = len(obs['board'])\n board = EnvSimulator.get_board(board_size, obs['board'])\n blast_strength = obs['bomb_blast_strength']\n bomb_life = obs['bomb_life']\n\n for row in range(len(board)):\n for col in range(len(board[0])):\n if (board[row, col] == 10 or board[row, col] == 11) and blast_strength[row, col] > 0.0:\n # agent over bomb\n value = 10000 + (board[row, col]-7)*1000 + int(blast_strength[row, col])*10 + int(bomb_life[row, col])\n board[row, col] = value\n if board[row, col] == 3: # bomb\n agent_id = 0\n value = 10000 + (board[row, col]-7)*1000 + int(blast_strength[row, col])*10 + int(bomb_life[row, col])\n\n return\n\n @staticmethod\n def get_game_data_board(game_data):\n return game_data[0:game_data.shape[1], 0:game_data.shape[1]]\n\n @staticmethod\n def act(game_data, actions):\n MIN_FIRE = 20\n AGENT_0 = 10\n AGENT_1 = 11\n\n if EnvSimulator.get_done(game_data):\n return\n\n #print(game_data, actions)\n\n # move objects\n pos_agent0_prev = None\n pos_agent0 = None\n pos_agent1_prev = None\n pos_agent1 = None\n pos_bomb_prev = []\n for row in range(game_data.shape[1]):\n for col in range(game_data.shape[1]):\n if EnvSimulator._is_fire(game_data, (row, col)):\n game_data[row, col] -= 1\n if game_data[row, col] == MIN_FIRE:\n game_data[row, col] = 0\n elif game_data[row, col] == AGENT_1 or game_data[row, col] >= 14000:\n pos_agent1_prev = (row, col)\n pos_agent1 = EnvSimulator.handle_agent_move(game_data, 1, row, col, actions[1])\n elif game_data[row, col] == AGENT_0 or game_data[row, col] >= 13000:\n pos_agent0_prev = (row, col)\n pos_agent0 = EnvSimulator.handle_agent_move(game_data, 0, row, col, actions[0])\n if game_data[row, col] >= 10000:\n pos_bomb_prev.append((row, col))\n\n if pos_agent0 == pos_agent1:\n pos_agent0 = pos_agent0_prev\n pos_agent1 = pos_agent1_prev\n\n # move bombs\n pos_bomb = []\n change = False\n invalid_values = [constants.Item.Rigid.value, constants.Item.Wood.value, constants.Item.Kick,\n constants.Item.IncrRange, constants.Item.ExtraBomb]\n for bomb_pos in pos_bomb_prev:\n bomb = game_data[bomb_pos]\n direction = int((bomb % 1000) / 100)\n if direction == 0 and bomb_pos == pos_agent0:\n if pos_agent0 != pos_agent0_prev: # kick bomb\n direction = EnvSimulator.get_direction(pos_agent0_prev, pos_agent0).value\n elif int((bomb % 10000) / 1000) != 1 and int((bomb % 10000) / 1000) != 3:\n raise ValueError(\"Fatal Error\")\n elif direction == 0 and bomb_pos == pos_agent1:\n if pos_agent1 != pos_agent1_prev: # kick bomb\n direction = EnvSimulator.get_direction(pos_agent1_prev, pos_agent1).value\n elif int((bomb % 10000) / 1000) != 2 and int((bomb % 10000) / 1000) != 4:\n raise ValueError(\"Fatal Error\")\n\n new_bomb_pos = bomb_pos\n if direction > 0:\n change = True\n row, col = bomb_pos\n if EnvSimulator._is_valid_direction(game_data, row, col, direction, invalid_values):\n new_bomb_pos = utility.get_next_position(bomb_pos, constants.Action(direction))\n if (row, col) == pos_agent0 or (row, col) == pos_agent1:\n new_bomb_pos = bomb_pos\n\n pos_bomb.append(new_bomb_pos)\n\n while change:\n change = False\n # bomb <-> bomb\n for i in range(len(pos_bomb)):\n pos = pos_bomb[i]\n for j in range(len(pos_bomb)):\n if i != j and pos == pos_bomb[j]:\n pos_bomb[i] = pos_bomb_prev[i]\n pos_bomb[j] = pos_bomb_prev[j]\n change = True\n if pos_bomb[i] == pos_agent0 and (pos_bomb[i] != pos_bomb_prev[i] or pos_agent0 != pos_agent0_prev):\n pos_agent0 = pos_agent0_prev\n pos_bomb[i] = pos_bomb_prev[i]\n change = True\n elif pos_bomb[i] == pos_agent1 and (pos_bomb[i] != pos_bomb_prev[i] or pos_agent1 != pos_agent1_prev):\n pos_agent1 = pos_agent1_prev\n pos_bomb[i] = pos_bomb_prev[i]\n change = True\n\n for i in range(len(pos_bomb)):\n cur_value = game_data[pos_bomb_prev[i]]\n life = int(cur_value % 10) - 1\n if 20 < game_data[pos_bomb[i]] < 30:\n life = 0\n strength = int((cur_value % 100) / 10)\n direction = EnvSimulator.get_direction(pos_bomb[i], pos_bomb_prev[i]).value\n player = int((cur_value % 10000) / 1000)\n if player > 2:\n player -= 2\n if pos_agent0 == pos_bomb[i] or pos_agent1 == pos_bomb[i]:\n player += 2\n\n game_data[pos_bomb_prev[i]] = 0\n game_data[pos_bomb[i]] = 10000 + player * 1000 + direction * 100 + strength * 10 + life\n\n # set agent\n #print(pos_agent0, pos_agent1)\n EnvSimulator._agent_collect(game_data, 0, pos_agent0)\n EnvSimulator._agent_collect(game_data, 1, pos_agent1)\n\n if pos_agent0_prev != pos_agent0:\n if game_data[pos_agent0_prev] < 10000:\n game_data[pos_agent0_prev] = 0\n if EnvSimulator._is_fire(game_data, pos_agent0):\n EnvSimulator._agent_died(game_data, 0)\n else:\n game_data[pos_agent0] = AGENT_0\n\n if pos_agent1_prev != pos_agent1:\n if game_data[pos_agent1_prev] < 10000:\n game_data[pos_agent1_prev] = 0\n if EnvSimulator._is_fire(game_data, pos_agent1):\n EnvSimulator._agent_died(game_data, 1)\n else:\n game_data[pos_agent1] = AGENT_1\n\n # fire bombs\n fire = True\n while fire:\n fire = False\n for bomb in pos_bomb:\n bomb_value = game_data[bomb]\n if int(bomb_value % 10) == 0:\n strength = int((bomb_value % 100) / 10)\n EnvSimulator._set_fire(game_data, bomb[0], bomb[1], True)\n EnvSimulator._fire_bomb(game_data, bomb[0], bomb[1], 0, 1, strength - 1) # right\n EnvSimulator._fire_bomb(game_data, bomb[0], bomb[1], 0, -1, strength - 1) # left\n EnvSimulator._fire_bomb(game_data, bomb[0], bomb[1], 1, 0, strength - 1) # down\n EnvSimulator._fire_bomb(game_data, bomb[0], bomb[1], -1, 0, strength - 1) # up\n fire = True\n\n #print('result: ', game_data)\n\n @staticmethod\n def handle_agent_move(game_data, agent_id, row, col, action):\n if action == constants.Action.Stop.value:\n return row, col\n elif action == constants.Action.Bomb.value:\n ammo = EnvSimulator._get_agent_value(game_data, agent_id, AMMO_POS)\n if game_data[row, col] < 10000 and ammo > 0:\n game_data[row, col] = 10009 + (agent_id + 3) * 1000 + EnvSimulator._get_agent_value(game_data, agent_id, BLAST_STRENGTH_POS) * 10\n EnvSimulator._set_agent_value(game_data, agent_id, AMMO_POS, ammo-1)\n return row, col\n else:\n invalid_values = [constants.Item.Rigid.value, constants.Item.Wood.value]\n if EnvSimulator._is_valid_direction(game_data, row, col, action, invalid_values):\n return utility.get_next_position((row, col), constants.Action(action))\n else:\n return row, col\n\n @staticmethod\n def _agent_collect(game_data, agent_id, pos):\n item = game_data[pos]\n if item == constants.Item.Kick.value:\n EnvSimulator._set_agent_value(game_data, agent_id, CAN_KICK_POS, 1)\n elif item == constants.Item.ExtraBomb.value:\n cur_ammo = EnvSimulator._get_agent_value(game_data, agent_id, AMMO_POS)\n EnvSimulator._set_agent_value(game_data, agent_id, AMMO_POS, cur_ammo + 1)\n elif item == constants.Item.IncrRange.value:\n cur_range = EnvSimulator._get_agent_value(game_data, agent_id, BLAST_STRENGTH_POS)\n EnvSimulator._set_agent_value(game_data, agent_id, BLAST_STRENGTH_POS, cur_range + 1)\n\n @staticmethod\n def _position_on_board(game_data, row, col):\n return all([game_data.shape[1] > row, game_data.shape[1] > col, row >= 0, col >= 0])\n\n @staticmethod\n def _is_fire(game_data, pos):\n return 20 < game_data[pos] < 30\n\n @staticmethod\n def _fire_bomb(game_data, row, col, row_off, col_off, strength):\n if strength <= 0:\n return\n next_row = row + row_off\n next_col = col + col_off\n if not EnvSimulator._position_on_board(game_data, next_row, next_col):\n return\n if utility.position_in_items(game_data, (next_row, next_col), [constants.Item.Rigid, constants.Item.Wood]):\n return\n\n EnvSimulator._set_fire(game_data, next_row, next_col, False)\n\n EnvSimulator._fire_bomb(game_data, next_row, next_col, row_off, col_off, strength - 1)\n\n @staticmethod\n def _set_fire(game_data, row, col, first):\n prev_value = game_data[row, col]\n if prev_value > 14000 or prev_value == 11:\n EnvSimulator._agent_died(game_data, 1)\n if prev_value > 13000 or prev_value == 10:\n EnvSimulator._agent_died(game_data, 0)\n if not first and prev_value > 10000:\n prev_value -= int(prev_value % 10)\n else:\n if first and prev_value > 10000:\n # increase ammo\n player = int((prev_value % 10000) / 1000)\n if player == 1 or player == 3:\n player = 0\n else:\n player = 1\n ammo = EnvSimulator._get_agent_value(game_data, player, AMMO_POS)\n EnvSimulator._set_agent_value(game_data, player, AMMO_POS, ammo+1)\n game_data[row, col] = 22\n\n @staticmethod\n def _agent_died(game_data, agent_id):\n EnvSimulator._set_agent_value(game_data, agent_id, ALIVE_POS, 0)\n EnvSimulator._set_game_value(game_data, DONE_POS, 1)\n\n @staticmethod\n def _is_valid_direction(board, row, col, direction, invalid_values=None):\n if invalid_values is None:\n invalid_values = [item.value for item in [constants.Item.Rigid, constants.Item.Wood]]\n\n if constants.Action(direction) == constants.Action.Stop:\n return True\n\n if constants.Action(direction) == constants.Action.Up:\n return row - 1 >= 0 and board[row - 1][col] not in invalid_values\n\n if constants.Action(direction) == constants.Action.Down:\n return row + 1 < len(board) and board[row + 1][col] not in invalid_values\n\n if constants.Action(direction) == constants.Action.Left:\n return col - 1 >= 0 and board[row][col - 1] not in invalid_values\n\n if constants.Action(direction) == constants.Action.Right:\n return col + 1 < len(board[0]) and board[row][col + 1] not in invalid_values\n\n raise constants.InvalidAction(\"We did not receive a valid direction: \", direction)\n\n @staticmethod\n def get_direction(position, next_position):\n if position == next_position:\n return constants.Action.Stop\n\n x, y = position\n next_x, next_y = next_position\n if x == next_x:\n if y < next_y:\n return constants.Action.Right\n else:\n return constants.Action.Left\n elif y == next_y:\n if x < next_x:\n return constants.Action.Down\n else:\n return constants.Action.Up\n raise constants.InvalidAction(\n \"We did not receive a valid position transition.\")\n\n @staticmethod\n def _get_agent_value(game_data, agent_id, value):\n return game_data[game_data.shape[0] - 2 + agent_id, value]\n\n @staticmethod\n def _set_agent_value(game_data, agent_id, value, val):\n game_data[game_data.shape[0] - 2 + agent_id, value] = val\n\n @staticmethod\n def _get_game_value(game_data, value):\n return game_data[game_data.shape[0] - 3, value]\n\n @staticmethod\n def _set_game_value(game_data, value, val):\n game_data[game_data.shape[0] - 3, value] = val\n\n @staticmethod\n def get_done(game_data):\n return bool(EnvSimulator._get_game_value(game_data, DONE_POS))\n\n @staticmethod\n def get_alive(game_data):\n alive = {0: bool(game_data[game_data.shape[0] - 2, ALIVE_POS]),\n 1: bool(game_data[game_data.shape[0] - 1, ALIVE_POS])}\n return alive\n\n @staticmethod\n def get_board(board_size, board_array, init_value=constants.Item.Passage.value):\n board = np.ones((board_size, board_size)).astype(np.uint16)\n board *= init_value\n for x in range(board_size):\n for y in range(board_size):\n board[x, y] = board_array[x][y]\n return board\n\n @staticmethod\n def get_position(board, item, is_single_pos):\n pos = np.where(board == item)\n pos = list(zip(pos[0], pos[1]))\n if is_single_pos:\n if len(pos) != 1:\n raise ValueError(\"Invalid pos count!\")\n return pos[0]\n else:\n return pos\n\n @staticmethod\n def get_valid_actions(board, flames, bombs, agent, actions):\n return actions\n\n @staticmethod\n def boards_equal(board1, board2, ignore_items):\n if ignore_items:\n board1 = copy.deepcopy(board1)\n board2 = copy.deepcopy(board2)\n board1[board1 == constants.Item.ExtraBomb.value] = constants.Item.Passage.value\n board1[board1 == constants.Item.IncrRange.value] = constants.Item.Passage.value\n board1[board1 == constants.Item.Kick.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.ExtraBomb.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.IncrRange.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.Kick.value] = constants.Item.Passage.value\n\n comparison = (board1 == board2)\n return comparison.all()\n\n @staticmethod\n def get_boards_differences(board1, board2):\n board1 = copy.deepcopy(board1)\n board2 = copy.deepcopy(board2)\n board1[board1 == constants.Item.ExtraBomb.value] = constants.Item.Passage.value\n board1[board1 == constants.Item.IncrRange.value] = constants.Item.Passage.value\n board1[board1 == constants.Item.Kick.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.ExtraBomb.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.IncrRange.value] = constants.Item.Passage.value\n board2[board2 == constants.Item.Kick.value] = constants.Item.Passage.value\n\n a1bomb = a2bomb = kick = flame = False\n comparison = (board1 == board2)\n diffs = np.where(comparison is False)\n if len(diffs) >= 2:\n diffs = list(zip(diffs[0], diffs[1]))\n for diff in diffs:\n prev_item = board1[diff]\n new_item = board2[diff]\n if prev_item is constants.Item.Agent1 and new_item is constants.Item.Bomb:\n a1bomb = True\n elif prev_item is constants.Item.Agent2 and new_item is constants.Item.Bomb:\n a2bomb = True\n elif prev_item is constants.Item.Passage and new_item is constants.Item.Bomb:\n kick = True\n elif new_item is constants.Item.Flames:\n flame = True\n else:\n raise ValueError('Invalid difference between maps.')\n else:\n print(comparison, \"diffs: \", diffs)\n\n return a1bomb, a2bomb, kick, flame\n\n @staticmethod\n def get_game_state(game_data):\n return game_data, EnvSimulator.get_done(game_data)\n\n @staticmethod\n def get_game_data(game_state):\n return copy.deepcopy(game_state)\n","sub_path":"pommerman/agents/env_simulator_fast.py","file_name":"env_simulator_fast.py","file_ext":"py","file_size_in_byte":21498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"332488372","text":"import struct\nfrom typing import Optional\nfrom binascii import hexlify, unhexlify\n\nfrom torba.client.baseheader import BaseHeaders\nfrom torba.client.util import ArithUint256\nfrom torba.client.hash import sha512, double_sha256, ripemd160\n\n\nclass Headers(BaseHeaders):\n\n header_size = 112\n chunk_size = 10**16\n\n max_target = 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n genesis_hash = b'9c89283ba0f3227f6c03b70216b9f665f0118d5e0fa729cedf4fb34d6a34f463'\n target_timespan = 150\n\n @property\n def claim_trie_root(self):\n return self[self.height]['claim_trie_root']\n\n @staticmethod\n def serialize(header):\n return b''.join([\n struct.pack(' ArithUint256:\n # https://github.com/lbryio/lbrycrd/blob/master/src/lbry.cpp\n if previous is None and current is None:\n return max_target\n if previous is None:\n previous = current\n actual_timespan = current['timestamp'] - previous['timestamp']\n modulated_timespan = self.target_timespan + int((actual_timespan - self.target_timespan) / 8)\n minimum_timespan = self.target_timespan - int(self.target_timespan / 8) # 150 - 18 = 132\n maximum_timespan = self.target_timespan + int(self.target_timespan / 2) # 150 + 75 = 225\n clamped_timespan = max(minimum_timespan, min(modulated_timespan, maximum_timespan))\n target = ArithUint256.from_compact(current['bits'])\n new_target = min(max_target, (target * clamped_timespan) / self.target_timespan)\n return new_target\n\n @classmethod\n def get_proof_of_work(cls, header_hash: bytes):\n return super().get_proof_of_work(\n cls.header_hash_to_pow_hash(header_hash)\n )\n\n @staticmethod\n def header_hash_to_pow_hash(header_hash: bytes):\n header_hash_bytes = unhexlify(header_hash)[::-1]\n h = sha512(header_hash_bytes)\n pow_hash = double_sha256(\n ripemd160(h[:len(h) // 2]) +\n ripemd160(h[len(h) // 2:])\n )\n return hexlify(pow_hash[::-1])\n\n\nclass UnvalidatedHeaders(Headers):\n validate_difficulty = False\n max_target = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n genesis_hash = b'6e3fcf1299d4ec5d79c3a4c91d624a4acf9e2e173d95a1a0504f677669687556'\n","sub_path":"lbry/lbry/wallet/header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"397962169","text":"######################################\r\n################# SVR ################\r\n######################################\r\ntest = df_rf\r\ntest =test.dropna()\r\ny = pd.DataFrame(test.marketshare)\r\nX = test\r\nX['frequency'] = X['frequency'].astype('category')\r\nX = X.drop(columns=['marketshare','study','is_want'], axis=1)\r\nX.isna().sum()\r\nX = (sc.fit_transform(X))\r\n\r\nrandom.seed(963)\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3 , random_state=30)\r\n# #############################################################################\r\n# Fit regression model\r\nsvr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=.1)\r\nsvr_lin = SVR(kernel='linear', C=100, gamma='auto')\r\nsvr_poly = SVR(kernel='poly', C=100, gamma='auto', degree=3, epsilon=.1,\r\n coef0=1)\r\n\r\nsvr_rbf.fit(X_train,y_train)\r\nsvr_lin.fit(X_train,y_train)\r\nsvr_poly.fit(X_train,y_train)\r\n# #############################################################################\r\n# Look at the results NOT POSSIBLE< NOT LINEAR\r\n\r\ny=np.array(y)\r\n\r\n#RBF\r\npredictions = svr_rbf.predict(X_train)\r\n# Calculate the absolute errors\r\nerrors = abs(predictions - np.array(y_train))\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-rbf-IS:', round(np.mean(errors), 2)) # 0.08\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape = abs((y_train - predictions)/y_train)\r\nmape = mape[np.isfinite(mape)]\r\n# Calculate and display accuracy\r\naccuracy = 100 - np.mean(mape)\r\nprint('Accuracy-rbf-IS:', round(accuracy, 2), '%.') #45.87\r\n\r\n# Use the svr's predict method on the test data\r\npredictions = svr_rbf.predict(X_test)\r\n# Calculate the absolute errors\r\nerrors = abs(predictions - np.array(y_test))\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-rbf-OOS:', round(np.mean(errors), 2)) #0.07\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape = abs((y_test - predictions)/y_test)\r\nmape = mape[np.isfinite(mape)]\r\n# Calculate and display accuracy\r\naccuracy = 100 - np.mean(mape)\r\nprint('Accuracy-rbf-OOS:', round(accuracy, 2), '%.') #62.76\r\n\r\n#LIN\r\npredictions2 = svr_lin.predict(X_train)\r\n# Calculate the absolute errors\r\nerrors2 = abs(predictions2 - y_train)\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-lin-OOS:', round(np.mean(errors2), 2)) #0.06\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape2 = abs((y_train - predictions2)/y_train)\r\nmape2 = mape2[np.isfinite(mape2)]\r\n# Calculate and display accuracy\r\naccuracy2 = 100 - np.mean(mape2)\r\nprint('Accuracy-lin-OOS:', round(accuracy2, 2), '%.') #65.97\r\n\r\npredictions2 = svr_lin.predict(X_test)\r\n# Calculate the absolute errors\r\nerrors2 = abs(predictions2 - y_test)\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-lin-OOS:', round(np.mean(errors2), 2)) #0.05\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape2 = abs((y_test - predictions2)/y_test)\r\nmape2 = mape2[np.isfinite(mape2)]\r\n# Calculate and display accuracy\r\naccuracy2 = 100 - np.mean(mape2)\r\nprint('Accuracy-lin-OOS:', round(accuracy2, 2), '%.') #77.11\r\n\r\n#poly\r\n\r\npredictions3 = svr_poly.predict(X_train)\r\n# Calculate the absolute errors\r\nerrors3 = abs(predictions3 - y_train)\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-poly-IS:', round(np.mean(errors3), 2)) #0.04\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape3 = abs((y_train - predictions3)/y_train)\r\nmape3 = mape3[np.isfinite(mape3)]\r\n# Calculate and display accuracy\r\naccuracy3 = 100 - np.mean(mape3)\r\nprint('Accuracy-poly-IS:', round(accuracy3, 2), '%.') #71.2\r\n\r\npredictions3 = svr_poly.predict(X_test)\r\n# Calculate the absolute errors\r\nerrors3 = abs(predictions3 - y_test)\r\n# Print out the mean absolute error (mae)\r\nprint('Mean Absolute Error-poly-OOS:', round(np.mean(errors3), 2)) #0.04\r\n# Calculate mean absolute percentage error (MAPE)\r\nmape3 = abs((y_test - predictions3)/y_test)\r\nmape3 = mape3[np.isfinite(mape3)]\r\n# Calculate and display accuracy\r\naccuracy3 = 100 - np.mean(mape3)\r\nprint('Accuracy-poly-OOS:', round(accuracy3, 2), '%.') #78.47\r\n\r\n\r\n#y_pred = regressor.predict(6.5)\r\n#y_pred = sc_y.inverse_transform(y_pred) \r\n\r\n","sub_path":"7svm.py","file_name":"7svm.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"553195605","text":"# You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n\n# You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. \n# DO NOT allocate another 2D matrix and do the rotation.\n\n\n# This can be achived by creating a transpose of the matrix and then reflection of the transposed matrix\n\nclass Solution:\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n n = len(matrix)\n \n # Create Transpose of the Matrix\n for i in range(n):\n for j in range(i,n):\n # Swapping values\n matrix[i][j],matrix[j][i] = matrix[j][i], matrix[i][j]\n \n # Reflect the Transposed Matrix\n for i in range(n):\n for j in range(n//2):\n # Swapping values\n matrix[i][j],matrix[i][-j-1]=matrix[i][-j-1],matrix[i][j]","sub_path":"src/RotateImage.py","file_name":"RotateImage.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"81011409","text":"#lda_2(关于均值有点问题还没有弄清楚)\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfilename = \"c:\\\\tfmodels\\\\dataset2_data_mining_course.csv\"\n\ndef make_matrix(filename):\n matrix = np.loadtxt(open(filename,\"rb\"), delimiter=\",\", skiprows=0)\n return matrix\n\ndef lda(x_raw, x_raw_1, x_raw_2, x_raw_3 ,d):#x_in为输入矩阵(n*p),d为维数\n with tf.name_scope(\"lda\"):\n #得到矩阵的大小\n x_in = tf.convert_to_tensor(x_raw)\n x_in = tf.cast(x_in, tf.float32)\n x_in_1 = tf.convert_to_tensor(x_raw_1)\n x_in_1 = tf.cast(x_in_1, tf.float32)#A类\n x_in_2 = tf.convert_to_tensor(x_raw_2)\n x_in_2 = tf.cast(x_in_2, tf.float32)#B类\n x_in_3 = tf.convert_to_tensor(x_raw_3)\n x_in_3 = tf.cast(x_in_3, tf.float32)#C类\n\n n = tf.to_float(x_in.get_shape()[0]),tf.to_int32(x_in.get_shape()[1])\n #总样本均值和各类均值\n mean = tf.reduce_mean(x_in, axis=1)\n mean_1 = tf.reduce_mean(x_in_1, axis=1)\n mean_2 = tf.reduce_mean(x_in_2, axis=1)\n mean_3 = tf.reduce_mean(x_in_3, axis=1)\n mean_total = x_in - tf.reshape(mean,(-1,1))\n mean_1_tmp = x_in_1 - tf.reshape(mean_1, (-1,1))\n mean_2_tmp = x_in_2 - tf.reshape(mean_2, (-1,1))\n mean_3_tmp = x_in_3 - tf.reshape(mean_3, (-1,1))\n mean_diff = tf.concat([mean_1_tmp, mean_2_tmp], 0)\n mean_diff = tf.concat([mean_diff, mean_3_tmp], 0)\n #计算类内散度矩阵Sw\n Sw_mean = x_in - mean_diff\n Sw = tf.matmul(Sw_mean, Sw_mean, transpose_a=True)\n #计算类间散度矩阵Sb\n St_mean = x_in - mean_total\n St = tf.matmul(St_mean, St_mean, transpose_a=True)#全局散度\n Sb = St - Sw\n cov = tf.matmul(tf.matrix_inverse(Sw), Sb)\n #特征值分解\n e, v = tf.linalg.eigh(cov)\n #对得到的特征值中取前d个最大的\n e_index = tf.math.top_k(e, sorted=True, k =d)[1]\n #取前d个最大特征向量\n v_lda = tf.gather(v, indices=e_index)\n #得到lda结果矩阵\n x_lda = tf.matmul(x_in, v_lda, transpose_b=True) \n sess = tf.Session()\n #转为numpy矩阵\n x_lda_np = x_lda.eval(session=sess)\n return x_lda_np\n\nx_raw = make_matrix(filename)\nd = int(input(\"输入维度\"))\nx_raw1 = x_raw[0:100,:]\nx_raw2 = x_raw[100:300,:]\nx_raw3 = x_raw[300:500,:]\nresult = lda(x_raw, x_raw1, x_raw2, x_raw3, d)\n\ndef showmodel():\n if (d == 2):#二维分布 \n result_1 = result[0:100,:]\n result_2 = result[100:300,:]\n result_3 = result[300:500,:]\n plt.scatter(result_1[:,0], result_1[:,1], c='blue')\n plt.scatter(result_2[:,0], result_2[:,1], c='orange')\n plt.scatter(result_3[:,0], result_3[:,1], c='red')\n plt.show()\n elif (d == 1):#一维分布\n result_1 = result[0:100,:]\n result_2 = result[100:300,:]\n result_3 = result[300:500,:]\n plt.scatter(result_1[:,0], np.zeros(100), c='blue')\n plt.scatter(result_2[:,0], np.zeros(200), c='orange')\n plt.scatter(result_3[:,0], np.zeros(200), c='red')\n plt.show()\n else:#原始3d分布\n result_1 = x_raw[0:100,0:3]\n result_2 = x_raw[100:300,0:3]\n result_3 = x_raw[300:500,0:3]\n model = plt.subplot(111, projection='3d')\n plt.scatter(result_1[:,0], result_1[:,1], result_1[:,2], c='blue')\n plt.scatter(result_2[:,0], result_2[:,1], result_2[:,2], c='orange')\n plt.scatter(result_3[:,0], result_3[:,1], result_3[:,2], c='red')\n plt.show()\n\nshowmodel()\n\n","sub_path":"Tensorflow/LDA_2.py","file_name":"LDA_2.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"340228128","text":"from glob import glob\nimport cv2\nimport os\nimport numpy as np\nimport re\n#import pyson.vision as pv\nimport numpy as np\n#import pyson.utils as pu\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nfrom tqdm import tqdm\nimport json\nREGEX = re.compile('.*(\\d{4})-(.+)-(\\d{1,4}).png')\n\n\n \n \ndef read_image(path, output_channels=3, resize_factor=1):\n if output_channels == 3:\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n else:\n img = cv2.imread(path, 0)\n \n if resize_factor !=1 :\n img = cv2.resize(img, (0, 0), fx=resize_factor, fy=resize_factor)\n return img\n\ndef get_text_boundingboxes(label_text, ex_border, resize_factor=1):\n ex_border = cv2.morphologyEx(ex_border, cv2.MORPH_CLOSE, np.ones([1, int(50*resize_factor)]))\n ex_border = cv2.morphologyEx(ex_border, cv2.MORPH_CLOSE, np.ones([int(10*resize_factor), 1]))\n\n dilating = cv2.morphologyEx(label_text, cv2.MORPH_CLOSE, np.ones([int(5*resize_factor), int(300*resize_factor)]))\n \n idxs = np.where(ex_border> 0) \n dilating[idxs] = 0\n\n #cnts, hiers = pv.findContours(dilating)\n ret, thresh = cv2.threshold(dilating, 127, 255, 0)\n im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n bb = []\n mask = np.zeros_like(dilating)\n # Split by excell\n mask = np.zeros_like(dilating)\n #for cnt in cnts:\n for cnt in contours:\n x,y,w,h = cv2.boundingRect(cnt)\n pad = label_text[y:y+h, x:x+w]\n if pad.mean() > 0:\n idxs = np.vstack(np.where(pad==255))\n min_y = idxs[0].min()\n max_y = idxs[0].max()\n min_x = idxs[1].min()\n max_x = idxs[1].max()\n\n ay = y+min_y\n ax = x + min_x\n by = y+max_y\n bx = x + max_x\n a, b = (ax,ay), (bx, by)\n bb.append((a, b))\n cv2.rectangle(mask, a, b, 255, -1)\n # merge over cell\n mask_merge = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones([1, int(10*resize_factor)]))\n #cnts, _ = pv.findContours(mask_merge)\n ret, thresh1 = cv2.threshold(mask_merge, 127, 255, 0)\n im3, cnts, hierarchy1 = cv2.findContours(thresh1,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n# pv.show(mask_merge, dpi=300, size=10)\n return [cv2.boundingRect(cnt) for cnt in cnts]\n\ndef get_bb_from_dict_path(dict_path, resize_factor):\n# input = read_image(dict_path['input'], 3, resize_factor)\n label_exborder = read_image(dict_path['label-ex_border'], 1, resize_factor)\n label_text = read_image(dict_path['label-text'], 1, resize_factor)\n \n boxes = get_text_boundingboxes(label_text, label_exborder, resize_factor)\n \n for (x, y, w, h) in boxes:\n a = (x, y)\n b = (x+w, y+h)\n return boxes\n\ndef perform(paths, multithread=4):\n input_paths = [path for path in paths if '-input-' in path]\n trainval_set = []\n \n for input_path in input_paths:\n mo = REGEX.search(input_path)\n m1 = mo.group(1)\n m3 = mo.group(3)\n d = {\n 'input': input_path,\n #'label-image': input_path.replace('-input-{}'.format(m3), '-image'),\n 'label-ex_border': input_path.replace('-input-{}'.format(m3), '-ex_border'),\n 'label-text': input_path.replace('-input-', '-text-'),\n }\n \n trainval_set.append(d)\n \n for path in d.values(): assert(os.path.exists(path)), path\n \n# for dict_path in tqdm(trainval_set):\n def fn(dict_path):\n input_path = dict_path['input']\n input_image = read_image(input_path, 1, 1)\n mask = np.zeros_like(input_image)\n boxes = get_bb_from_dict_path(dict_path, 1)\n for (x,y,w,h) in boxes:\n cv2.rectangle(mask, (x, y), (x+w, y+h), 255, 2)\n\n\n #### Huynh modify ######\n i = 0\n boxes_mod = {}\n for (x,y,w,h) in boxes:\n #boxes_mod.append((x,y,x+w, y+h)) \n boxes_mod[str(i)] = {'x': x, 'width': w, 'y':y, 'height':h}\n i = i+1\n\n file_name_ext = input_path.split('/')[-1]\n file_name = file_name_ext.split('.')[0] + '.json'\n file_path = os.path.dirname(input_path)\n json_fullpath = os.path.join(file_path,file_name)\n with open(json_fullpath,'w') as outfile:\n json.dump(boxes_mod,outfile)\n ########################\n #out_path_text_box = input_path.replace('-input-', '-textbox-')\n #cv2.imwrite(out_path_text_box, mask)\n #np.save(out_path_text_box.replace('.png', '.npy'), np.array(boxes))\n #return out_path_text_box\n \n if multithread>1:\n with tqdm(total=len(trainval_set), desc=\"Executing Pipeline\", unit=\" Samples\") as progress_bar:\n with ThreadPoolExecutor(max_workers=multithread) as executor:\n for result in executor.map(fn, trainval_set):\n progress_bar.set_description(\"Processing %s\" % result)\n progress_bar.update(1)\n else:\n with tqdm(total=len(trainval_set), desc=\"Executing Pipeline\", unit=\" Samples\") as progress_bar:\n for dict_path in trainval_set:\n result =fn(dict_path)\n progress_bar.set_description(\"Processing %s\" % result)\n progress_bar.update(1)","sub_path":"build_text_bb.py","file_name":"build_text_bb.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"258463708","text":"import numpy as np\nfrom scipy.spatial.distance import pdist, squareform, cosine\nfrom tqdm import tqdm\nimport pickle\n\n\ndef save_obj(obj, name):\n with open(name, 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n\n\ndef load_obj(name):\n with open(name, 'rb') as f:\n return pickle.load(f)\n\n\nclass NeGraph(object):\n def __init__(self, graph, value, similarity_matrix):\n self.graph = graph\n self.value = value\n self.similarity_matrix = similarity_matrix\n self.pr = []\n for item in range(len(self.graph)):\n self.pr.append(1/len(self.graph))\n\n def calculate_pr(self, d):\n modify_sum = []\n for modify_idx in range(len(self.similarity_matrix)):\n modify_sum.append(np.sum(self.similarity_matrix[modify_idx]))\n temp_pr = self.pr.copy()\n for item in self.graph:\n # 确定节点序号\n item_idx = self.graph[item]\n # 首先计算一个偏置值\n item_bias = (1 - d) * self.value[item_idx]\n modify_value = 0.0\n for temp_idx in range(len(self.similarity_matrix[item_idx])):\n if item_idx == temp_idx or modify_sum[temp_idx] == 0.0:\n # 不计算自己\n continue\n modify_value = modify_value + self.similarity_matrix[item_idx][temp_idx]/modify_sum[temp_idx] * \\\n temp_pr[temp_idx]\n if modify_value == 0.0:\n self.pr[item_idx] = item_bias\n continue\n self.pr[item_idx] = item_bias + d * self.value[item_idx] * modify_value\n\n\n def calculate_pr_times(self, d, times):\n for i in range(times):\n self.calculate_pr(d)\n\n def calculate_pr_converge(self, d, threshold):\n if len(self.graph) >= 2:\n count_number = 0\n changes = np.array([100.0] * len(self.graph))\n while (changes > threshold).any() and count_number <= 100:\n old_pr = self.pr.copy()\n self.calculate_pr(d)\n for i in range(len(changes)):\n changes[i] = abs(self.pr[i] - old_pr[i])\n count_number = count_number + 1\n\n def get_final_pr_score_dic(self):\n temp_pr_score = {}\n final_pr_score = {}\n for item in self.graph:\n item_idx = self.graph[item]\n temp_pr_score[item] = self.pr[item_idx]\n final_pr_score_list = sorted(temp_pr_score.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)\n for i in final_pr_score_list:\n final_pr_score[i[0]] = i[1]\n return final_pr_score\n\n\ndef test(graph_list_file, graph_embedding_list_file, graph_value_list_file, output_final_pr_file):\n graph_list = load_obj(graph_list_file)\n graph_embedding_list = load_obj(graph_embedding_list_file)\n graph_value_list = load_obj(graph_value_list_file)\n final_phrase = []\n for idx in tqdm(range(len(graph_list))):\n if len(graph_list[idx]) == 0:\n final_phrase.append({})\n continue\n temp_similarity = pdist(graph_embedding_list[idx], metric='cosine')\n temp_similarity_matrix = squareform(temp_similarity)\n # 算相似度矩阵\n temp_ones = np.ones((len(graph_list[idx]), len(graph_list[idx])), dtype='float64')\n used_similarity_matrix = temp_ones - temp_similarity_matrix\n graph_score = NeGraph(graph_list[idx], graph_value_list[idx], used_similarity_matrix)\n graph_score.calculate_pr_converge(0.85, 0.0001)\n final_phrase.append(graph_score.get_final_pr_score_dic())\n save_obj(final_phrase, output_final_pr_file)\n\n\nif __name__ == '__main__':\n graph_list_file = 'patent/title/title_graph/title_graph_list.pkl'\n graph_embedding_list_file = 'patent/title/title_graph/title_graph_embedding_list.pkl'\n graph_value_list_file = 'patent/title/title_score/title_influence_phrase_list_normalized_score.pkl'\n test_file = 'patent/title/title_rank/ranked_title_influence_phrase_score.pkl'\n test(graph_list_file, graph_embedding_list_file, graph_value_list_file, test_file)\n","sub_path":"patent/title/title_rank/title_rank.py","file_name":"title_rank.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"140332141","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 27 22:40:12 2021\n\n@author: junyanee\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# 코인데스크 사이트에서 다운로드한 1년치 비트코인 가격 데이터 읽기\nf = open('BTC_USD_2020-05-28_2021-05-27-CoinDesk.csv', 'r')\ncoindesk_data = pd.read_csv(f, header = 0)\nseq = coindesk_data[['Closing Price (USD)']].to_numpy() #종가만 취함\nprint('데이터 길이:', len(seq),'\\n앞쪽 5개 값:', seq[0:5])\n\n# 그래프로 데이터 확인\nplt.plot(seq, color = 'red')\nplt.title('Bitcoin Prices (1 year from 2019-02-28)')\nplt.xlabel('Days'); plt.ylabel('Price in USD')\nplt.show()\n\n# 시계열 데이터를 위도우 단위로 자르는 함수\ndef seq2dataset(seq, window, horizon):\n X = []; Y = []\n for i in range(len(seq) - (window + horizon) + 1):\n x = seq[i : (i + window)]\n y = (seq[i + window + horizon - 1])\n X.append(x); Y.append(y);\n return np.array(X), np.array(Y)\n \nw = 7 #윈도우 크기\nh = 1 #수평선 계수\n\nX, Y = seq2dataset(seq, w, h)\nprint(X.shape, Y.shape)\nprint(X[0], Y[0]); print(X[-1], Y[-1])","sub_path":"1_year_price_from_coindesk.py","file_name":"1_year_price_from_coindesk.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"33644324","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\n\nfrom openerp import api, fields, models, _, tools, release\nfrom datetime import datetime\nimport time\nfrom openerp import SUPERUSER_ID\nimport time\nimport dateutil\nimport dateutil.parser\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime, date\nfrom openerp.exceptions import UserError, RedirectWarning, ValidationError\nfrom openerp.tools import float_compare, float_round\n\nimport sys\nreload(sys) \nsys.setdefaultencoding('utf8')\n\nimport sys\nreload(sys) \nsys.setdefaultencoding('utf8')\n\n### HERENCIA A CLIENTES PARA IGNORAR VENCIMIENTO ###\n\nclass AccountMoveLine(models.Model):\n _name = 'account.move.line'\n _inherit ='account.move.line'\n\n\n @api.model\n def create(self, values):\n context = self._context\n\n res = super(AccountMoveLine, self).create(values)\n if res.product_id:\n product_accounts = res.product_id.product_tmpl_id._get_product_accounts()\n expense_account = product_accounts['expense']\n stock_output = product_accounts['stock_output']\n # if res.account_id.id in (expense_account.id, stock_output.id):\n if res.account_id.id == stock_output.id:\n #res.name = res.name+\"\\nAqui la Analitica\"\n if 'active_model' in context:\n active_model = context['active_model']\n if active_model == 'sale.order':\n if 'active_ids' in context:\n active_ids = context['active_ids']\n analytic_account_ids = []\n\n self.env.cr.execute(\"\"\"\n select project_id from sale_order where id in %s\n \"\"\", (tuple(active_ids),))\n cr_res = self.env.cr.fetchall()\n if cr_res:\n analytic_account_ids = [x[0] for x in cr_res]\n res.analytic_account_id = analytic_account_ids[0]\n\n analytic_tag_ids = []\n self.env.cr.execute(\"\"\"\n select account_analytic_tag_id from \n account_analytic_tag_sale_order_line_rel\n where sale_order_line_id in (select id from sale_order_line \n where order_id in %s and product_id=%s)\n \"\"\", (tuple(active_ids), res.product_id.id))\n cr_res = self.env.cr.fetchall()\n analytic_tag_ids = [x[0] for x in cr_res]\n if cr_res:\n res.analytic_tag_ids = [(6,0,analytic_tag_ids)]\n elif 'invoice' in context:\n invoice_record = context['invoice']\n\n if 'type' in context:\n type_invoice = context['type']\n if type_invoice == 'out_invoice':\n invoice_line_ids = [x.id for x in invoice_record.invoice_line_ids]\n self.env.cr.execute(\"\"\"\n select sale_order.id\n from sale_order join sale_order_line\n on sale_order_line.order_id = sale_order.id\n join sale_order_line_invoice_rel\n on sale_order_line_invoice_rel.order_line_id = sale_order_line.id\n and sale_order_line_invoice_rel.invoice_line_id in %s;\n \"\"\",(tuple(invoice_line_ids),))\n cr_res = self.env.cr.fetchall()\n sale_ids = [x[0] for x in cr_res if x]\n analytic_account_ids = []\n\n self.env.cr.execute(\"\"\"\n select project_id from sale_order where id in %s\n \"\"\", (tuple(sale_ids),))\n cr_res = self.env.cr.fetchall()\n if cr_res:\n analytic_account_ids = [x[0] for x in cr_res]\n res.analytic_account_id = analytic_account_ids[0]\n\n analytic_tag_ids = []\n self.env.cr.execute(\"\"\"\n select account_analytic_tag_id from \n account_analytic_tag_sale_order_line_rel\n where sale_order_line_id in (select id from sale_order_line \n where order_id in %s and product_id=%s)\n \"\"\", (tuple(sale_ids), res.product_id.id))\n cr_res = self.env.cr.fetchall()\n analytic_tag_ids = [x[0] for x in cr_res]\n if cr_res:\n res.analytic_tag_ids = [(6,0,analytic_tag_ids)]\n\n # else:\n # res.analytic_account_id = False\n \n return res\n\n\nclass StockMove(models.Model):\n _inherit = \"stock.move\"\n\n def _prepare_account_move_line(self, qty, cost, credit_account_id, debit_account_id):\n context = self._context\n res = super(StockMove, self)._prepare_account_move_line(qty, cost, credit_account_id, debit_account_id)\n return res\n\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n @api.multi\n def action_move_create(self):\n context = self._context\n res = super(AccountInvoice, self).action_move_create()\n return res\n\n### Tabla que relaciona las lineas de pedido con las lineas de factura\n### sale_order_line_invoice_rel\n### _get_product_accounts = Metodo de Producto que trae las cuentas del mismo\n### account_analytic_tag_sale_order_line_rel | sale_order_line_id | account_analytic_tag_id ","sub_path":"account_analytic_in_cost/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":7083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"289749886","text":"import multiprocessing as mp\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom time import time\r\n\r\ndef simulate_geometric_brownian_motion(p):\r\n M, I = p\r\n # time steps, paths\r\n S0 = 100; r = 0.05; sigma = 0.2; T = 1.0\r\n # model parameters\r\n dt = T / M\r\n paths = np.zeros((M + 1, I))\r\n paths[0] = S0\r\n for t in range(1, M + 1):\r\n paths[t] = paths[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt +\r\n sigma * math.sqrt(dt) * np.random.standard_normal(I))\r\n return paths\r\n\r\nif __name__ == '__main__':\r\n I = 10000 # number of paths\r\n M = 50 # number of time steps\r\n t = 20 # number of tasks/simulations\r\n \r\n times = []\r\n process_ = range(1,10)\r\n for w in process_:\r\n t0 = time()\r\n pool = mp.Pool(processes=w)\r\n # the pool of workers\r\n result = pool.map(simulate_geometric_brownian_motion, t * [(M, I), ])\r\n # the mapping of the function to the list of parameter tuples\r\n t_=time()-t0\r\n times.append(t_)\r\n print(t_)\r\n \r\n \r\n plt.plot(process_, times)\r\n plt.plot(process_, times, 'ro')\r\n plt.grid(True)\r\n plt.xlabel('number of processes')\r\n plt.ylabel('time in seconds')\r\n plt.title('%d Monte Carlo simulations' % t)\r\n plt.show() \r\n \r\n \r\n \r\n \r\n ","sub_path":"Ejercicios/Brownian_Paths_mp.py","file_name":"Brownian_Paths_mp.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"297235226","text":"# -*- coding: utf-8 -*-\n# ~license~\n# ------------------------------------------------------------------------------\nfrom DateTime import DateTime\n\nfrom appy.px import Px\nfrom appy.model.fields import Field\n\n# ------------------------------------------------------------------------------\nINVALID_MULTILINGUAL_VALUE = 'Multilingual field \"%s\" accepts a dict whose ' \\\n 'keys are in field.languages and whose values are strings.'\n\n# ------------------------------------------------------------------------------\nclass Multilingual:\n '''Mixin class injected into any Field whose content can be multilingual'''\n\n # Default values to render when field values are empty\n emptyDefault = {'view': '-', 'edit': ''}\n # Default top space (in pixels) to apply in pxLanguage\n lgTop = {'view': 1, 'edit': 3}\n\n # Note that multilinguality is a dynamic feature: field values can be\n # unilingual or multilingual, depending on some condition on the container\n # object itself, or on some site-specific configuration.\n\n # PX displaying the language code and name besides the part of the\n # multilingual field storing content in this language.\n pxLanguage = Px('''\n \n :lg.upper()\n ''')\n\n # PX acting as a substitute for the field pxView. This PX determines if the\n # field content is multilingual or not. If the field is unilingual, it\n # simply calls a PX named \"Uni\" on the field. Else, it renders\n # such a PX for every supported language, calling \"Uni\" for\n # every language, and assembling the result according to the \"languages\n # layout\". The \"Uni\" PX receives the current language as variable \"lg\". If\n # the field is unilingual, the received \"lg\" variable is None.\n view = edit = cell = Px('''\n \n\n \n :pxUni\n\n \n \n\n \n \n :field.pxLanguage\n \n
:pxUni
\n\n \n \n \n :field.pxLanguage\n \n
:pxUni
\n
\n
''')\n\n def __init__(self, languages, languagesLayouts):\n '''Inject multilingual-specific attributes on p_self'''\n # If \"languages\" holds more than one language, the field will be\n # multi-lingual and several widgets will allow to edit/visualize the\n # field content in all the supported languages. The field is also used\n # by the CK spell checker.\n self.languages = languages\n # When content exists in several languages, how to render them? Either\n # horizontally (one below the other), or vertically (one besides the\n # other). Specify here a dict whose keys are layouts (\"edit\", \"view\")\n # and whose values are either \"horizontal\" or \"vertical\".\n self.languagesLayouts = languagesLayouts\n\n def isMultilingual(self, o, dontKnow=False):\n '''Is this field multilingual ? If we don't know, say p_dontKnow'''\n if not o:\n if callable(self.languages):\n # In that case, it is impossible to know\n return dontKnow\n else: return len(self.languages) > 1\n return len(self.getAttribute(o, 'languages')) > 1\n\n def getLanguagesLayout(self, layout):\n '''Gets the way to render a multilingual field on p_layoutType.'''\n if self.languagesLayouts and (layout in self.languagesLayouts):\n return self.languagesLayouts[layout]\n # Else, return a default value that depends of the format\n return self.defaultLanguagesLayouts[layout]\n\n def getCopyValue(self, o):\n '''A value being multilingual is stored in a dict. For such a value,\n standard method Field.getCopyValue must return a distinct copy of the\n value as stored on p_obj.'''\n r = self.getValue(o)\n if isinstance(r, dict): r = r.copy()\n return r\n\n def valueIsInRequest(self, o, req, name=None, layout='view'):\n '''Multilingual values are stored in specific input fields with\n specific names.'''\n # If we are on the search layout, p_obj, if not None, is certainly not\n # the p_obj we want here (can be a home object).\n if layout == 'search':\n return Field.valueIsInRequest(self, o, req, name, layout)\n languages = self.getAttribute(o, 'languages')\n if len(languages) == 1:\n return Field.valueIsInRequest(self, o, req, name, layout)\n # Is is sufficient to check that at least one of the language-specific\n # values is in the request.\n return ('%s_%s' % (name, languages[0])) in req\n\n def getRequestValue(self, o, requestName=None):\n '''The request value may be multilingual'''\n req = o.req\n name = requestName or self.name\n languages = self.getAttribute(o, 'languages')\n # A unilingual field\n if len(languages) == 1: return req[name]\n # A multilingual field\n r = {}\n for language in languages:\n r[language] = req['%s_%s' % (name, language)]\n return r\n\n def isEmptyValue(self, o, value):\n '''Returns True if the p_value must be considered as an empty value'''\n if not isinstance(value, dict):\n return Field.isEmptyValue(self, o, value)\n # p_value is a dict of multilingual values. For such values, as soon\n # as a value is not empty for a given language, the whole value is\n # considered as not being empty.\n for v in value.values():\n if not Field.isEmptyValue(self, o, v): return\n return True\n\n def isCompleteValue(self, o, value):\n '''Returns True if the p_value must be considered as complete. For a\n unilingual field, being complete simply means not being empty. For a\n multilingual field, being complete means that a value is present for\n every language.'''\n if not self.isMultilingual(o):\n return Field.isCompleteValue(self, o, value)\n # As soon as a given language value is empty, the global value is not\n # complete.\n if not value: return True\n for v in value.values():\n if Field.isEmptyValue(self, o, v): return\n return True\n\n def getFormattedValue(self, o, value, layout='view', showChanges=False,\n language=None):\n '''The multilingual and unilingual variants of p_value's formatted\n version differ.'''\n # Note that p_language represents the UI language, while variable\n # \"languages\" below represents the content language(s) of this field.\n languages = self.getAttribute(o, 'languages')\n uni = self.getUniFormattedValue\n if (len(languages) == 1) or isinstance(value, str):\n # Normally, p_value should not be a string if there is a single\n # language. This can happen in exceptional cases, ie, in a\n # object's history (data change), when an object was transmitted\n # from one App1 to App2, where a field is unilingual in App1 and\n # multilingual in App2.\n return uni(o, value, layout, showChanges, language=language)\n # Return the dict of values whose individual, language-specific values\n # have been formatted via m_getUniFormattedValue.\n if not value and not showChanges: return value\n r = {}\n for lg in languages:\n if not value: val = ''\n else: val = value[lg]\n r[lg] = uni(o, val, layout, showChanges,\n language=language, contentLanguage=lg)\n return r\n\n def getShownValue(self, o, value, layout='view', showChanges=False,\n language=None):\n '''For a multilingual field, this method only shows one specific\n language part.'''\n # Be careful: p_language represents the UI language, while variable\n # \"languages\" below represents the content language(s) of this field.\n languages = self.getAttribute(o, 'languages')\n uni = self.getUniFormattedValue\n if len(languages) == 1:\n return uni(o, value, layout, showChanges, language=language)\n if not value: return value\n # Try to propose the part that is in the user language, or the part of\n # the first content language else.\n lg = o.guard.userLanguage\n if lg not in value: lg = languages[0]\n return uni(o, value[lg], layout, showChanges, language=lg)\n\n def getIndexValue(self, o):\n '''Multilingual variant of Field::getIndexValue. Language parts must be\n concatenated into a single value to be indexed.'''\n r = Field.getIndexValue(self, o)\n if r is None: return\n # Manage multilinguality\n if isinstance(r, dict):\n r = ' '.join([self.getUniIndexValue(o, v) for v in r.values()])\n else:\n r = self.getUniIndexValue(o, r)\n return r\n\n def getStorableValue(self, o, value, complete=False):\n languages = self.getAttribute(o, 'languages')\n if len(languages) == 1:\n return self.getUniStorableValue(o, value)\n # A multilingual value is stored as a dict whose keys are ISO 2-letters\n # language codes and whose values are strings storing content in the\n # language ~{s_language: s_content}~.\n if not value: return\n for lg in languages:\n value[lg] = self.getUniStorableValue(o, value[lg])\n return value\n\n def store(self, o, value):\n '''Stores p_value on p_o for this field'''\n languages = self.getAttribute(o, 'languages')\n if (len(languages) > 1) and value and \\\n (not isinstance(value, dict) or (len(value) != len(languages))):\n raise Exception(INVALID_MULTILINGUAL_VALUE % self.name)\n Field.store(self, o, value)\n\n def storeFromAjax(self, o):\n '''Stores the new field value from an Ajax request, or do nothing if\n the action was canceled.'''\n req = o.req\n if req.cancel == 'True': return\n requestValue = req.fieldContent\n # Remember previous value if the field is historized\n isHistorized = self.getAttribute(o, 'historized')\n previousData = None\n if isHistorized: currentValues = o.history.getCurrentValues(self)\n if self.isMultilingual(o):\n if isHistorized:\n # We take a copy of current values because it is mutable (dict)\n data = currentValues[self.name]\n if data is not None: data = data.copy()\n currentValues[self.name] = data\n # We get a partial value, for one language only\n language = req.languageOnly\n v = self.getUniStorableValue(o, requestValue)\n o.values[self.name][language] = v\n part = ' (%s)' % language\n else:\n self.store(o, self.getStorableValue(o, requestValue))\n part = ''\n # Update the object history when relevant\n if isHistorized and currentValues: obj.history.historize(currentValues)\n # Update p_o's last modification date\n o.history.modified = DateTime()\n o.reindex()\n o.log('ajax-edited %s%s on %s.' % (self.name, part, o.id))\n# ------------------------------------------------------------------------------\n","sub_path":"appy/model/fields/multilingual.py","file_name":"multilingual.py","file_ext":"py","file_size_in_byte":12578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"394665222","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\nclass AccountPayment(models.Model):\n _inherit = \"account.payment\"\n\n unmatched_amount = fields.Monetary(\n compute='_compute_matched_amounts', currency_field='currency_id')\n\n @api.multi\n @api.depends('state', 'payment_group_id', 'amount',\n 'payment_group_id.matched_move_line_ids.payment_group_matched_amount')\n def _compute_matched_amounts(self):\n for rec in self:\n if rec.state != 'posted':\n continue\n rec.unmatched_amount = 0.0\n if rec.payment_group_id:\n rec.matched_amount = rec.payment_group_matched_amount(rec.payment_group_id.matched_move_line_ids)\n rec.unmatched_amount = rec.amount - rec.matched_amount\n\n def payment_group_matched_amount(self, matched_move_line_ids):\n payment_move_lines = self.mapped('move_line_ids')\n payment_partial_lines = self.env['account.partial.reconcile'].search([\n '|', ('credit_move_id', 'in', payment_move_lines.ids),\n ('debit_move_id', 'in', payment_move_lines.ids)])\n payment_group_matched_amount = 0.0\n for matched_move_line_id in matched_move_line_ids:\n matched_amount = 0.0\n for pl in (matched_move_line_id.matched_debit_ids + matched_move_line_id.matched_credit_ids):\n if pl in payment_partial_lines:\n matched_amount += pl.amount\n payment_group_matched_amount += matched_amount\n return payment_group_matched_amount\n","sub_path":"moogah_development_extra_arg/partner_transaction_report/models/account_payment.py","file_name":"account_payment.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"466397498","text":"import time\nfrom seleniumbase import BaseCase\n\n\nclass MyTestClass(BaseCase):\n\n def test_proxy(self):\n self.open('https://ipinfo.io/')\n ip_address = self.get_text(\"div.home-ip-details span.value\")[1:-1]\n print(\"\\n\\nMy IP Address = %s\\n\" % ip_address)\n print(\"Displaying Host Info:\")\n print(self.get_text('div.home-ip-details').split('asn: ')[0])\n print(\"\\nThe browser will close automatically in 7 seconds...\")\n time.sleep(7)\n","sub_path":"examples/proxy_test.py","file_name":"proxy_test.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"337812794","text":"import os\nfrom unittest import mock\n\nfrom django.test import TestCase\n\nfrom kino.kinoparser.afisha_parser import (\n CinemaListParser,\n CinemaPageParser,\n MovieListParser,\n MovieShowtimeParser,\n CinemaIdNameMetro)\n\n\nclass KinoAfishaParseCase(TestCase):\n\n def setUp(self):\n pass\n\n def read_data_file(self, file_path_in_data):\n path = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(path, 'data', file_path_in_data)\n with open(path) as f:\n return f.read()\n\n def test_cinema_list_parsing(self):\n parser = CinemaListParser()\n\n content = self.read_data_file('afisha_cinema_list.html')\n\n with mock.patch.object(parser, 'get_movies_page', return_value=content) as patched_method:\n cinema_list = parser.parse()\n\n movie_1 = CinemaIdNameMetro(8168846, 'Балтика', 'Сходненская')\n movie_2 = CinemaIdNameMetro(8325961, 'Тула', None)\n movie_3 = CinemaIdNameMetro(1714544, 'Юность', 'Октябрьское поле')\n\n self.assertIn(movie_1, cinema_list)\n self.assertIn(movie_2, cinema_list)\n self.assertIn(movie_3, cinema_list)\n\n def test_cinema_full_info_parsing(self):\n parser = CinemaPageParser()\n\n content = self.read_data_file('afisha_cinema_info.html')\n\n with mock.patch.object(parser, 'get_cinema_page', return_value=content) as p_method:\n cinema_info = parser.parse(1234567)\n\n self.assertAlmostEqual(7.8, cinema_info.rating)\n self.assertEqual(550, cinema_info.votes)\n\n def test_movie_list_parsing(self):\n parser = MovieListParser()\n\n content = self.read_data_file('afisha_films_list.html')\n\n with mock.patch.object(parser, 'get_movie_list', return_value=content) as patched_method:\n movie_list = parser.parse('some_date')\n\n movie_first = movie_list[0]\n movie_last = movie_list[-1]\n\n self.assertEqual(movie_first.name, 'Гоголь. Страшная месть')\n self.assertEqual(movie_first.movie_id, '8330075')\n\n self.assertEqual(movie_last.name, 'Болото')\n self.assertEqual(movie_last.movie_id, '8355150')\n\n def test_movie_info_parsing(self):\n parser = MovieShowtimeParser()\n\n content = self.read_data_file('afisha_film_info.html')\n\n with mock.patch.object(parser, 'get_movie_page', return_value=content) as p_method:\n movie_info = parser.parse(1234567)\n\n for raw_cinema in movie_info:\n self.assertEqual(raw_cinema.name, 'Loft Cinema')\n self.assertEqual(len(movie_info[raw_cinema]), 1)\n self.assertEqual(movie_info[raw_cinema][0].time, '03:10')\n break\n","sub_path":"kino/kinoparser/tests/tests_afisha_parsing.py","file_name":"tests_afisha_parsing.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225289969","text":"import matplotlib.pyplot as plt\nimport numpy as np\nlabel=['week days', 'weekend']\ntweet_count=[148657, 57078]\n\ncolors = ['#ff9999', '#66b3ff']\n\nfig1, ax1 = plt.subplots()\nax1.pie(tweet_count, colors=colors, labels=label, autopct='%1.1f%%', startangle=90)\n# draw circle\ncentre_circle = plt.Circle((0, 0), 0.70, fc='white')\nfig = plt.gcf()\nfig.gca().add_artist(centre_circle)\n# Equal aspect ratio ensures that pie is drawn as a circle\nax1.axis('equal')\nplt.tight_layout()\nplt.show()","sub_path":"phase2/visualization/query4.py","file_name":"query4.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"263409996","text":"import data, analysis\n\n# Handle data\ndata_obj = data.Data()\ndata_obj.parse_csv('ongo.csv')\ndata_obj.format_dataset()\n\nlifelines_dataset = data_obj.dataset\n\n# Handle reporting\nconfiguration = {}\nreport = analysis.Analysis(lifelines_dataset, configuration)\n\n# reports\ndata = report.dataset\n\nreport.fit_data()\nmedian = report.return_median()\nsurvival_function = report.return_survival_function()\nhazard_function = report.return_hazard_function()\n\n# handle display\nprint(data)\nprint('MEDIAN ', median)\nprint('SURVIVAL ', survival_function)\nprint('HAZARD ', hazard_function)\n\n# operations\n# subtract\n\n# graphs\nlifetime_plot = report.return_lifetimes()\nkmf_plot = report.plot_kmf()\nnaf_plot = report.plot_naf()\nreport.show_plots()\n\n# groups\nkmf_plot_2 = report.plot_kmf(config = ['it'])\nreport.show_plots()\n\nkmf_plot_4 = report.plot_kmf(config = ['manager'])\nreport.show_plots()\n\nkmf_plot_4 = report.plot_kmf(config = ['hardware'])\nreport.show_plots()\n\nkmf_plot_3 = report.plot_kmf(config = ['it', 'manager'])\nreport.show_plots()\n\nkmf_plot_3 = report.plot_kmf(config = ['it', 'manager', 'hardware'])\nreport.show_plots()\n\n# groups\nnaf_plot_2 = report.plot_naf(config = ['it'])\nreport.show_plots()\n\nnaf_plot_4 = report.plot_naf(config = ['manager'])\nreport.show_plots()\n\nnaf_plot_4 = report.plot_naf(config = ['hardware'])\nreport.show_plots()\n\nnaf_plot_3 = report.plot_naf(config = ['it', 'manager'])\nreport.show_plots()\n\nnaf_plot_3 = report.plot_naf(config = ['it', 'manager', 'hardware'])\nreport.show_plots()\n\nreport.show_plots()","sub_path":"Survival/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"631866988","text":"# ANT - Cadence, Speed Sensor AND Heart Rate Monitor - Example\n#\n# Copyright (c) 2012, Gustav Tiger \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import absolute_import, print_function\n\nfrom ant.easy.node import Node\nfrom ant.easy.channel import Channel\nfrom ant.base.message import Message\n\nimport logging\nimport struct\nimport threading\nimport sys\nimport time\nimport math\nfrom pymongo import MongoClient\n\nNETWORK_KEY= [0xb9, 0xa5, 0x21, 0xfb, 0xbd, 0x72, 0xc3, 0x45]\n\nclass Monitor():\n def __init__(self):\n self.crank_revs = 0\n self.speed = \"n/a\"\n self.cadence = 0\n self.session_length = 0\n self.last_data_time = 0\n #time reported by sensor (in 1/1024ths of a second)\n self.device_time = 0\n self.session_start_time = 0\n\n #when we last got an update from the device\n self.last_device_time = 0\n\n def on_data_speed(self, data):\n self.speed = str(data[7]*256 + data[6])\n self.display()\n\n def on_data_cadence(self, data):\n old_crank_revs = self.crank_revs\n old_device_time = self.device_time\n current_time = time.time()\n \n\n #parse data from device\n self.crank_revs = data[7]*256 + data[6]\n self.device_time = data[5]*256 + data[4]\n\n revdiff = self.crank_revs - old_crank_revs\n timediff = self.device_time - old_device_time\n\n #try to calculate the cadence\n if (timediff == 0):\n pass\n else:\n self.cadence = (60 * 1024 / timediff) * revdiff\n\n \n\n #if it's been more than 2 seconds since we heard from the device, new session\n if self.last_data_time + 2 < current_time:\n self.new_session()\n else:\n #has the device time changed?\n if self.device_time != old_device_time:\n self.update_session()\n self.last_device_time = current_time\n else:\n #how long has it been?\n if self.last_device_time + 2 > current_time:\n self.update_session()\n else:\n self.new_session()\n \n #update our saved times\n self.last_data_time = current_time\n \n \n self.display()\n\n def new_session(self):\n self.session_length = 0\n self.session_start_time = time.time()\n\n #it's a new session so start a new record \n result = self.db.sessions.insert_one(\n {\n \"start_time\" : self.session_start_time,\n \"merits_earned\" : self.session_length,\n \"last_updated\" : self.session_start_time,\n \"cadence\" : self.cadence\n }\n )\n\n #save the session Id for now\n self.session_id = result\n\n def update_session(self):\n current_time = time.time()\n\n self.session_length = current_time - self.session_start_time\n \n #update our mongo record\n self.db.sessions.update_one(\n {\n '_id' : self.session_id.inserted_id\n },\n {\n \"$set\" : {\n \"merits_earned\" : self.session_length,\n \"last_updated\" : current_time,\n \"cadence\" : self.cadence\n }\n }\n\n\n )\n\n def display(self):\n merits = math.floor(self.session_length)\n string = \" Pedal revolutions: \" + str(self.crank_revs) + \" Cadence: \" + str(self.cadence) + \" Merits this session: \" + str(merits)\n\n sys.stdout.write(string)\n sys.stdout.flush()\n sys.stdout.write(\"\\b\" * len(string))\n\n\ndef main():\n # logging.basicConfig()\n\n mongo = MongoClient()\n\n monitor = Monitor()\n monitor.db = mongo.test2\n\n\n node = Node()\n node.set_network_key(0x00, NETWORK_KEY)\n\n channel = node.new_channel(Channel.Type.BIDIRECTIONAL_RECEIVE)\n\n channel.on_broadcast_data = monitor.on_data_speed\n channel.on_burst_data = monitor.on_data_speed\n\n channel.set_period(8188)\n channel.set_search_timeout(255)\n channel.set_rf_freq(57)\n channel.set_id(0, 123, 0)\n\n channel_cadence_speed = node.new_channel(Channel.Type.BIDIRECTIONAL_RECEIVE)\n\n channel_cadence_speed.on_broadcast_data = monitor.on_data_cadence\n channel_cadence_speed.on_burst_data = monitor.on_data_cadence\n\n channel_cadence_speed.set_period(8102)\n channel_cadence_speed.set_search_timeout(255)\n channel_cadence_speed.set_rf_freq(57)\n channel_cadence_speed.set_id(0, 122, 0)\n\n try:\n channel.open()\n channel_cadence_speed.open()\n node.start()\n print(\"after start\")\n finally:\n node.stop()\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"501444700","text":"'''\n\nAni Ambroladze\n\nNumber Maze\n\n'''\n\nimport numpy as np\nfrom collections import defaultdict\nimport math\n\nclass PuzzleBoard(object):\n def __init__(self, size, myboard = None):\n\n self.boardSize = size\n \n if myboard is None: \n myboard = np.random.randint(1,size-1, size = (size, size))\n self.myboard = myboard\n \n else:\n self.myboard = myboard\n \n self.myMatrix = np.zeros(((self.boardSize**2),(self.boardSize**2)))\n self.V = self.boardSize**2\n \n self.graph = defaultdict(list)\n self.Po = np.zeros(((self.boardSize**2),(4)))\n \n for a in range(self.boardSize):\n for b in range(self.boardSize):\n cValue = myboard[a][b]\n cPos = a*self.boardSize+b\n\n if a >= cValue:\n posRow = a - cValue\n posCol = b\n \n self.Po[cPos][0] = 1\n posPos = posRow*self.boardSize+posCol\n \n self.myMatrix[cPos][posPos] = 1\n self.addEdge(cPos,posPos)\n\n if self.boardSize-1-a >= cValue:\n posRow = a + cValue\n posCol = b\n \n self.Po[cPos][2] = 1\n posPos = posRow*self.boardSize + posCol\n \n self.myMatrix[cPos][posPos] = 1\n self.addEdge(cPos,posPos)\n \n if b >= cValue:\n posRow=a\n posCol=b-cValue\n \n self.Po[cPos][3] = 1\n posPos = posRow*self.boardSize + posCol\n \n self.myMatrix[cPos][posPos] = 1\n self.addEdge(cPos,posPos)\n \n if self.boardSize-1-b>=cValue:\n posRow = a\n posCol = b + cValue\n \n self.Po[cPos][1] = 1 \n posPos = posRow*self.boardSize + posCol\n \n self.myMatrix[cPos][posPos] = 1\n self.addEdge(cPos,posPos)\n \n self.currA = 0\n self.currB = 0\n self.current = 0\n self.paths = []\n\n def makeMove(self,direction):\n \n self.current = self.currA*self.boardSize + self.currB\n\n if direction == 0 and self.Po[self.current][0]:\n \n self.currA = self.currA-myboard[self.currA][self.currB]\n return True\n \n elif direction == 1 and self.Po[self.current][1]:\n \n self.currB = self.currB+myboard[self.currA][self.currB]\n return True\n \n elif direction == 2 and self.Po[self.current][2]:\n \n self.currA = self.currA+myboard[self.currA][self.currB]\n return True\n\n elif direction == 3 and self.Po[self.current][3]:\n \n self.currB = self.currB-myboard[self.currA][self.currB]\n return True\n \n else:\n return False\n \n \n \n def __str__(self):\n return str(self.myboard)\n \n\n def printMatrix(self):\n print(\"My Matrix: \")\n print(self.myMatrix)\n \n\n def printPosition(self):\n print('Position: ')\n print(self.currA,' ',self.currB)\n \n \n def getResult(self):\n if self.currA == self.boardSize-1 and self.currB == self.boardSize-1:\n return True\n else: \n return False\n \n \n def addEdge(self,u,v):\n self.graph[u].append(v)\n \n\n def getAll(self, u, d, visited, path, result):\n visited[u]= True\n path.append(u)\n\n if u==d:\n result.append(list(path))\n\n else:\n for a in self.graph[u]:\n if visited[a] == False:\n self.getAll(a, d, visited, path, result)\n path.pop()\n visited[u]= False\n return result\n \n \n def getAllPaths(self,s, d):\n visited =[False]*(self.V)\n path = []\n result = []\n result = self.getAll(s, d,visited, path, result)\n\n return result\n \n\n def solve(self):\n paths = self.getAllPaths(0,self.V-1)\n \n if not paths:\n return -1\n else:\n mIndex = 0\n mini =len(paths[0])\n for a in range(len(paths)):\n if len(paths[a]) <= mini:\n mIndex=a\n mini = len(paths[a])\n \n print('The shortest path to solve the problem: ')\n print(paths[mIndex])\n \n return mini\n \n \nmyboard=[[1,2,1,3], [2,3,3,2], [3,1,2,2],[2,1,1,1]]\n\npuzz = PuzzleBoard(len(myboard),myboard)\nprint(\"My Puzzleboard:\")\nprint(puzz)\nprint('')\n\npuzz.printMatrix()\nprint('')\n\npuzz.printPosition()\n\npuzz.makeMove(2)\npuzz.printPosition()\n\npuzz.makeMove(2)\npuzz.printPosition()\n\npuzz.makeMove(1)\npuzz.printPosition()\n\npuzz.makeMove(1)\npuzz.printPosition()\n\nprint('')\nprint(puzz.getResult())\n\nprint('')\npaths = puzz.solve()\n\nprint('')\nprint('The minimum number of moves to solve the problem: ')\nprint(paths)\n\n\n#Source code: getAllPaths implementation -> www.geeksforgeeks.org\n","sub_path":"maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"425181294","text":"# Alternative implementation of Rect that uses floats rather than just integers\n\n\n# Constants needed for my direct translation of SDL_IntersectRectAndLine\nCODE_BOTTOM = 1\nCODE_TOP = 2\nCODE_LEFT = 4\nCODE_RIGHT = 8\n\n\nclass Rect:\n def __init__(self, *args):\n if len(args) == 2:\n if len(args[0]) == 2 and len(args[1]) == 2:\n l = [*args[0], *args[1]]\n else:\n raise TypeError(\"Argument must be rect style object\")\n elif len(args) == 4:\n l = [*args]\n elif len(args) == 1:\n if len(args[0]) == 2:\n l = [*args[0][0], *args[0][1]]\n elif len(args[0]) == 4:\n l = list(args[0])\n else:\n raise TypeError(\n f\"sequence argument takes 2 or 4 items ({len(args[0])} given)\"\n )\n\n else:\n raise TypeError(\"Argument must be rect style object\")\n\n self.__dict__[\"_rect\"] = l\n\n getattr_dict = {\n \"x\": lambda x: x._rect[0],\n \"y\": lambda x: x._rect[1],\n \"top\": lambda x: x._rect[1],\n \"left\": lambda x: x._rect[0],\n \"bottom\": lambda x: x._rect[1] + x._rect[3],\n \"right\": lambda x: x._rect[0] + x._rect[2],\n \"topleft\": lambda x: (x._rect[0], x._rect[1]),\n \"bottomleft\": lambda x: (x._rect[0], x._rect[1] + x._rect[3]),\n \"topright\": lambda x: (x._rect[0] + x._rect[2], x._rect[1]),\n \"bottomright\": lambda x: (x._rect[0] + x._rect[2], x._rect[1] + x._rect[3]),\n \"midtop\": lambda x: (x._rect[0] + x._rect[2] / 2, x._rect[1]),\n \"midleft\": lambda x: (x._rect[0], x._rect[1] + x._rect[3] / 2),\n \"midbottom\": lambda x: (x._rect[0] + x._rect[2] / 2, x._rect[1] + x._rect[3]),\n \"midright\": lambda x: (x._rect[0] + x._rect[2], x._rect[1] + x._rect[3] / 2),\n \"center\": lambda x: (x._rect[0] + x._rect[2] / 2, x._rect[1] + x._rect[3] / 2),\n \"centerx\": lambda x: x._rect[0] + x._rect[2] / 2,\n \"centery\": lambda x: x._rect[1] + x._rect[3] / 2,\n \"size\": lambda x: (x._rect[2], x._rect[3]),\n \"width\": lambda x: x._rect[2],\n \"height\": lambda x: x._rect[3],\n \"w\": lambda x: x._rect[2],\n \"h\": lambda x: x._rect[3],\n }\n\n def __getattr__(self, name):\n try:\n return Rect.getattr_dict[name](self)\n except KeyError:\n raise AttributeError(\n f\"'{self.__class__.__name__}' object has no attribute 'name'\"\n )\n\n def __setattr__(self, name, value):\n if name == \"x\":\n self._rect[0] = value\n return\n\n if name == \"y\":\n self._rect[1] = value\n return\n\n if name == \"top\":\n self._rect[1] = value\n return\n\n if name == \"left\":\n self._rect[0] = value\n return\n\n if name == \"bottom\":\n self._rect[1] += value - self.bottom\n return\n\n if name == \"right\":\n self._rect[0] += value - self.right\n return\n\n if name == \"topleft\":\n self._rect[0], self._rect[1] = value\n return\n\n if name == \"bottomleft\":\n self._rect[0], self.bottom = value\n return\n\n if name == \"topright\":\n self.right, self._rect[1] = value\n return\n\n if name == \"bottomright\":\n self.right, self.bottom = value\n return\n\n if name == \"midtop\":\n self.centerx, self._rect[1] = value\n return\n\n if name == \"midleft\":\n self._rect[0], self.centery = value\n return\n\n if name == \"midbottom\":\n self.centerx, self.bottom = value\n return\n\n if name == \"midright\":\n self.right, self.centery = value\n return\n\n if name == \"center\":\n self.centerx, self.centery = value\n return\n\n if name == \"centerx\":\n self._rect[0] += value - self.centerx\n return\n\n if name == \"centery\":\n self._rect[1] += value - self.centery\n return\n\n if name == \"size\":\n self._rect[2], self._rect[3] = value\n return\n\n if name == \"width\":\n self._rect[2] = value\n return\n\n if name == \"height\":\n self._rect[3] = value\n return\n\n if name == \"w\":\n self._rect[2] = value\n return\n\n if name == \"h\":\n self._rect[3] = value\n return\n\n self.__dict__[name] = value\n\n def __getitem__(self, index):\n return self._rect[index]\n\n def __setitem__(self, index, value):\n self._rect[index] = value\n\n def __len__(self):\n return 4\n\n def __str__(self):\n return f\"\"\n\n def __repr__(self):\n return self.__str__()\n\n def __eq__(self, other):\n try:\n return self._rect == self.__class__(other)._rect\n except:\n return False\n\n def __bool__(self):\n return self._rect[2] != 0 and self._rect[3] != 0\n\n def copy(self):\n return self.__class__(self._rect)\n\n def move(self, x, y):\n c = self.copy()\n c.move_ip(x, y)\n return c\n\n def move_ip(self, x, y):\n self._rect[0] += x\n self._rect[1] += y\n\n def inflate(self, x, y):\n c = self.copy()\n c.inflate_ip(x, y)\n return c\n\n def inflate_ip(self, x, y):\n self._rect[0] -= x / 2\n self._rect[2] += x\n\n self._rect[1] -= y / 2\n self._rect[3] += y\n\n def update(self, *args):\n self.__init__(*args)\n\n def clamp(self, argrect):\n c = self.copy()\n c.clamp_ip(argrect)\n return c\n\n def clamp_ip(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n if self._rect[2] >= argrect.w:\n x = argrect.x + argrect.w / 2 - self._rect[2] / 2\n elif self._rect[0] < argrect.x:\n x = argrect.x\n elif self._rect[0] + self._rect[2] > argrect.x + argrect.w:\n x = argrect.x + argrect.w - self._rect[2]\n else:\n x = self._rect[0]\n\n if self._rect[3] >= argrect.h:\n y = argrect.y + argrect.h / 2 - self._rect[3] / 2\n elif self._rect[1] < argrect.y:\n y = argrect.y\n elif self._rect[1] + self._rect[3] > argrect.y + argrect.h:\n y = argrect.y + argrect.h - self._rect[3]\n else:\n y = self._rect[1]\n\n self._rect[0] = x\n self._rect[1] = y\n\n def clip(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n # left\n if self.x >= argrect.x and self.x < argrect.x + argrect.w:\n x = self.x\n elif argrect.x >= self.x and argrect.x < self.x + self.w:\n x = argrect.x\n else:\n return self.__class__(self.x, self.y, 0, 0)\n\n # right\n if self.x + self.w > argrect.x and self.x + self.w <= argrect.x + argrect.w:\n w = self.x + self.w - x\n elif (\n argrect.x + argrect.w > self.x and argrect.x + argrect.w <= self.x + self.w\n ):\n w = argrect.x + argrect.w - x\n else:\n return self.__class__(self.x, self.y, 0, 0)\n\n # top\n if self.y >= argrect.y and self.y < argrect.y + argrect.h:\n y = self.y\n elif argrect.y >= self.y and argrect.y < self.y + self.h:\n y = argrect.y\n else:\n return self.__class__(self.x, self.y, 0, 0)\n\n # bottom\n if self.y + self.h > argrect.y and self.y + self.h <= argrect.y + argrect.h:\n h = self.y + self.h - y\n elif (\n argrect.y + argrect.h > self.y and argrect.y + argrect.h <= self.y + self.h\n ):\n h = argrect.y + argrect.h - y\n else:\n return self.__class__(self.x, self.y, 0, 0)\n\n return self.__class__(x, y, w, h)\n\n def clipline(self, *args):\n # arg1 = arg2 = arg3 = arg4 = None\n x1 = y1 = x2 = y2 = 0\n\n if len(args) == 1:\n if len(args[0]) == 2:\n x1, y1 = args[0][0]\n x2, y2 = args[0][1]\n elif len(args[0]) == 4:\n x1, y1, x2, y2 = args[0]\n else:\n raise TypeError(\n f\"sequence argument takes 2 or 4 items ({len(args[0])} given)\"\n )\n\n elif len(args) == 2:\n x1, y1 = args[0]\n x2, y2 = args[1]\n\n elif len(args) == 4:\n x1, y1, x2, y2 = args\n\n else:\n raise TypeError(\n f\"clipline() takes 1, 2, or 4 arguments ({len(args)}) given\"\n )\n\n rect = self.__class__(self.__dict__[\"_rect\"].copy())\n rect.normalize()\n\n # fun fact, I went into SDl's source code to write this\n rectx1 = rect.x\n recty1 = rect.y\n rectx2 = rect.right - 1\n recty2 = rect.bottom - 1\n\n # Check to see if entire line is inside rect\n if (\n rectx1 <= x1 <= rectx2\n and rectx1 <= x2 <= rectx2\n and recty1 <= y1 <= recty2\n and recty1 <= y2 <= recty2\n ):\n return ((x1, y1), (x2, y2))\n\n # Check to see if entire line is to one side of rect\n if (\n (x1 < rectx1 and x2 < rectx1)\n or (x1 > rectx2 and x2 > rectx2)\n or (y1 < recty1 and y2 < recty1)\n or (y1 > recty2 and y2 > recty2)\n ):\n return ()\n\n if y1 == y2:\n # Horizontal line, easy to clip\n if x1 < rectx1:\n x1 = rectx1\n elif x1 > rectx2:\n x1 = rectx2\n if x2 < rectx1:\n x2 = rectx1\n elif x2 > rectx2:\n x2 = rectx2\n return ((x1, y1), (x2, y2))\n\n if x1 == x2:\n # Vertical line, easy to clip\n if y1 < recty1:\n y1 = recty1\n elif y1 > recty2:\n y1 = recty2\n if y2 < recty1:\n y2 = recty1\n elif y2 > recty2:\n y2 = recty2\n return ((x1, y1), (x2, y2))\n\n # More complicated Cohen-Sutherland algorithm\n outcode1 = self._compute_outcode(rect, x1, y1)\n outcode2 = self._compute_outcode(rect, x2, y2)\n while outcode1 or outcode2:\n if outcode1 & outcode2:\n return ()\n\n if outcode1:\n if outcode1 & CODE_TOP:\n y = recty1\n x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1)\n elif outcode1 & CODE_BOTTOM:\n y = recty2\n x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1)\n elif outcode1 & CODE_LEFT:\n x = rectx1\n y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1)\n elif outcode1 & CODE_RIGHT:\n x = rectx2\n y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1)\n x1 = x\n y1 = y\n outcode1 = self._compute_outcode(rect, x, y)\n else:\n if outcode2 & CODE_TOP:\n y = recty1\n x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1)\n elif outcode2 & CODE_BOTTOM:\n y = recty2\n x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1)\n elif outcode2 & CODE_LEFT:\n assert x2 != x1 # if equal: division by zero.\n x = rectx1\n y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1)\n elif outcode2 & CODE_RIGHT:\n assert x2 != x1 # if equal: division by zero.\n x = rectx2\n y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1)\n x2 = x\n y2 = y\n outcode2 = self._compute_outcode(rect, x, y)\n\n return ((x1, y1), (x2, y2))\n\n def _compute_outcode(self, rect, x, y):\n code = 0\n if y < rect.y:\n code |= CODE_TOP\n elif y >= rect.y + rect.h:\n code |= CODE_BOTTOM\n if x < rect.x:\n code |= CODE_LEFT\n elif x >= rect.x + rect.w:\n code |= CODE_RIGHT\n return code\n\n def union(self, argrect):\n c = self.copy()\n c.union_ip(argrect)\n return c\n\n def union_ip(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n x = min(self.x, argrect.x)\n y = min(self.y, argrect.y)\n w = max(self.x + self.w, argrect.x + argrect.w) - x\n h = max(self.y + self.h, argrect.y + argrect.h) - y\n\n self._rect = [x, y, w, h]\n\n def unionall(self, argrects):\n c = self.copy()\n c.unionall_ip(argrects)\n return c\n\n def unionall_ip(self, argrects):\n for i, argrect in enumerate(argrects):\n try:\n argrects[i] = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n x = min([self.x] + [r.x for r in argrects])\n y = min([self.y] + [r.y for r in argrects])\n w = max([self.right] + [r.right for r in argrects]) - x\n h = max([self.bottom] + [r.bottom for r in argrects]) - y\n\n self._rect = [x, y, w, h]\n\n def fit(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n xratio = self.w / argrect.w\n yratio = self.h / argrect.h\n maxratio = max(xratio, yratio)\n\n w = self.w / maxratio\n h = self.h / maxratio\n\n x = argrect.x + (argrect.w - w) / 2\n y = argrect.y + (argrect.h - h) / 2\n\n return Rect(x, y, w, h)\n\n def normalize(self):\n if self._rect[2] < 0:\n self._rect[0] += self._rect[2]\n self._rect[2] = -self._rect[2]\n\n if self._rect[3] < 0:\n self._rect[1] += self._rect[3]\n self._rect[3] = -self._rect[3]\n\n def contains(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n if self._rect[0] <= argrect[0] and argrect[0] + argrect[2] <= self.right:\n if self._rect[1] <= argrect[1] and argrect[1] + argrect[3] <= self.bottom:\n return True\n return False\n\n def collidepoint(self, *args):\n if len(args) == 1:\n point = args[0]\n elif len(args) == 2:\n point = tuple(args)\n else:\n raise TypeError(\"argument must contain two numbers\")\n\n # conforms with no collision on right / bottom edge behavior of pygame Rects\n if self._rect[0] <= point[0] < self.right:\n if self._rect[1] <= point[1] < self.bottom:\n return True\n return False\n\n def colliderect(self, argrect):\n try:\n argrect = Rect(argrect)\n except:\n raise TypeError(\"Argument must be rect style object\")\n\n if any(0 == d for d in [self.w, self.h, argrect.w, argrect.h]):\n return False\n\n return (\n min(self.x, self.x + self.w) < max(argrect.x, argrect.x + argrect.w)\n and min(self.y, self.y + self.h) < max(argrect.y, argrect.y + argrect.h)\n and max(self.x, self.x + self.w) > min(argrect.x, argrect.x + argrect.w)\n and max(self.y, self.y + self.h) > min(argrect.y, argrect.y + argrect.h)\n )\n\n def collidelist(self, argrects):\n for i, argrect in enumerate(argrects):\n if self.colliderect(argrect):\n return i\n\n return -1\n\n def collidelistall(self, argrects):\n out = []\n\n for i, argrect in enumerate(argrects):\n if self.colliderect(argrect):\n out.append(i)\n\n return out\n\n def collidedict(self, rects_dict, use_values=0):\n for key in rects_dict:\n if use_values == 0:\n argrect = key\n else:\n argrect = rects_dict[key]\n\n if self.colliderect(argrect):\n return (key, rects_dict[key])\n\n return None # explicit rather than implicit\n\n def collidedictall(self, rects_dict, use_values=0):\n out = []\n\n for key in rects_dict:\n if use_values == 0:\n argrect = key\n else:\n argrect = rects_dict[key]\n\n if self.colliderect(argrect):\n out.append((key, rects_dict[key]))\n\n return out\n","sub_path":"PyFlap/pgx/Rect.py","file_name":"Rect.py","file_ext":"py","file_size_in_byte":16845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"121633459","text":"from collections import namedtuple\n\nfrom infra.models import DynamicCursor\nfrom infra.fixtures.set_audit_user import set_audit_user\nfrom infra.fixtures.dynamic_cursor import DynamicCursorTuple, load_cursors\nfrom infra.fixtures.app_parameter_set import ParameterTuple, load_parameters\nfrom infra.fixtures.app_report import AppReportTuple, load_reports\nfrom infra.fixtures.menu_item import MenuItemTuple, load_menus\nfrom infra.fixtures.role_access_list import RoleAccessTuple\nfrom infra.fixtures.resource_description import ResourceDescriptionTuple\nfrom infra.fixtures.menu_description import MenuDescriptionTuple\nfrom infra.fixtures.parameter_label import ParameterLabelTuple\n\nset_audit_user()\n\"\"\"\n Data Extraction as text (CSV or TEXT)\n 1) dup the cursor below for your model. You can have parent-child but row has to be flattened.\n Use model_to_dict or QuerySet.values() to yield a dict (to be used by text_engine)\n 2) dup the template in infra/reports/text. You need to specify the fields in the dict returned by cursor above.\n 3) Add the app parameter set, report and menu item below\n\"\"\"\n\n# Dynamic Cursor List of infra data extractions\ndata_cursors = (\n DynamicCursorTuple(cursor_code='VALUE-SET-PY', cursor_description='Value Set Data Extraction using python', cursor_type='python', \n code_snippet=\"\"\"from infra.models import ValueSet, ValueSetMember\nfrom django.forms.models import model_to_dict\ndef yield_rows(pos_params, named_params, filter_predicates, limit):\n qs = ValueSet.objects.filter(**filter_predicates)\n for vs in qs:\n vm = vs.valuesetmember_set.all()\n for row in vm.values():\n # Add ValueSet fields\n row.update(model_to_dict(vs))\n yield dict(row)\n\"\"\"),\n DynamicCursorTuple(cursor_code='APP-REGISTRY-PY', cursor_description='App Registry Data Extraction using python', cursor_type='python', \n code_snippet=\"\"\"from infra.models import AppRegistry\nfrom django.forms.models import model_to_dict\ndef yield_rows(pos_params, named_params, filter_predicates, limit):\n for row in AppRegistry.objects.filter(**filter_predicates):\n yield model_to_dict(row)\n\"\"\"),\n DynamicCursorTuple(cursor_code='TASK-QUEUE-PY', cursor_description='Task Queue Data Extraction using python', cursor_type='python', \n code_snippet=\"\"\"from infra.models import TaskQueue\nfrom django.forms.models import model_to_dict\ndef yield_rows(pos_params, named_params, filter_predicates, limit):\n for row in TaskQueue.objects.filter(**filter_predicates):\n # Turn model instance into dict\n row_dict = model_to_dict(row)\n # Add the Env Parameter Code\n row_dict['env_parameter_set_code'] = row.env_parameter_set.parameter_set_code\n yield row_dict\n\"\"\"),\n )\n\nload_cursors(data_cursors)\n\n# Parameter Sets for infra Data Extractions\ndata_parameters = (\n ('VALUE-SET-DATA', 'Value Set Data Extraction', (\n ParameterTuple(parameter_sequence=10, parameter_name='value_set_code', prompt_label='Value Set Code by selected Operator', \n data_type='C', is_prompted=True, is_required=True, \n parameter_value='000-zzz', formula_code=None, choice_code=None, \n default_operator='RG', allowed_operators='CT,EQ,EW,RG,SW',\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Kod Set Nilai yang dipilih dengan Pengendali'),\n )\n ),\n ParameterTuple(parameter_sequence=20, parameter_name='OUTPUT-FORMAT', prompt_label='Output Format', \n data_type='C', is_prompted=True, is_required=False, \n parameter_value='CSV', formula_code=None, choice_code='REPORT-OUTPUT-FORMATS', \n default_operator=None, allowed_operators=None,\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Bentuk Output'),\n )\n ),\n )\n ),\n ('APP-REGISTRY-DATA', 'App Registry Data Extraction', (\n ParameterTuple(parameter_sequence=10, parameter_name='registry_key', prompt_label='Registry Key by selected Operator', \n data_type='C', is_prompted=True, is_required=True, \n parameter_value='000-zzz', formula_code=None, choice_code=None, \n default_operator='RG', allowed_operators='CT,EQ,EW,RG,SW',\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Kekunci Daftar yang dipilih dengan Pengendali'),\n )\n ),\n ParameterTuple(parameter_sequence=20, parameter_name='OUTPUT-FORMAT', prompt_label='Output Format', \n data_type='C', is_prompted=True, is_required=False, \n parameter_value='CSV', formula_code=None, choice_code='REPORT-OUTPUT-FORMATS', \n default_operator=None, allowed_operators=None,\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Bentuk Output'),\n )\n ),\n )\n ),\n ('TASK-QUEUE-DATA', 'Task Queue Data Extraction', (\n ParameterTuple(parameter_sequence=10, parameter_name='queue_code', prompt_label='Task Queue Code by selected Operator', \n data_type='C', is_prompted=True, is_required=True, \n parameter_value='000-zzz', formula_code=None, choice_code=None, \n default_operator='RG', allowed_operators='CT,EQ,EW,RG,SW',\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Kod Pengilir Tugas-tugas yang dipilih dengan Pengendali'),\n )\n ),\n ParameterTuple(parameter_sequence=20, parameter_name='OUTPUT-FORMAT', prompt_label='Output Format', \n data_type='C', is_prompted=True, is_required=False, \n parameter_value='CSV', formula_code=None, choice_code='REPORT-OUTPUT-FORMATS', \n default_operator=None, allowed_operators=None,\n parameter_label_tuple= (\n ParameterLabelTuple('ms', u'Bentuk Output'),\n )\n ),\n )\n ),\n)\nload_parameters(data_parameters)\n\n# Reports for infra data extractions\ndata_reports = (\n AppReportTuple(resource_code='VALUE-SET-DATA', resource_description='Value Set Data Extraction', minimum_access_level=100, \n parameter_set_code='VALUE-SET-DATA', engine_code='TEXT', cursor_code='VALUE-SET-PY',\n report_url=None, template_path=\"infra/reports/text/value_set_data.fld\",\n queue_code=None, command_code=None, to_archive=False, execute_immediately=False,\n default_output_format='CSV', queueing_priority=100, filter_model='infra.ValueSet',\n role_access_tuple=None,\n resource_description_tuple=(\n ResourceDescriptionTuple('ms', u'Mengeluarkan Data Set Nilai-nilai'),\n )\n ),\n AppReportTuple(resource_code='APP-REGISTRY-DATA', resource_description='App Registry Data Extraction', minimum_access_level=100, \n parameter_set_code='APP-REGISTRY-DATA', engine_code='TEXT', cursor_code='APP-REGISTRY-PY',\n report_url=None, template_path=\"infra/reports/text/app_registry_data.fld\",\n queue_code=None, command_code=None, to_archive=False, execute_immediately=False,\n default_output_format='CSV', queueing_priority=100, filter_model='infra.AppRegistry',\n role_access_tuple=None,\n resource_description_tuple=(\n ResourceDescriptionTuple('ms', u'Mengeluarkan Data Daftar Konfigurasi Sistem'),\n )\n ),\n AppReportTuple(resource_code='TASK-QUEUE-DATA', resource_description='Task Queue Data Extraction', minimum_access_level=100, \n parameter_set_code='TASK-QUEUE-DATA', engine_code='TEXT', cursor_code='TASK-QUEUE-PY',\n report_url=None, template_path=\"infra/reports/text/task_queue_data.fld\",\n queue_code=None, command_code=None, to_archive=False, execute_immediately=False,\n default_output_format='CSV', queueing_priority=100, filter_model='infra.TaskQueue',\n role_access_tuple=None,\n resource_description_tuple=(\n ResourceDescriptionTuple('ms', u'Mengeluarkan Data Penggilir Tugas-tugas'),\n )\n ),\n )\n\nload_reports(data_reports)\n\n# Menu for data extractions\ndata_menus = (\n MenuItemTuple(item_description=\"Extract Infrastructure Master Data\", parent_menu_name=\"Infrastructure Module\", display_sequence=40, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Pengeluaran Data Fail-fail Induk Infrastruktur'),\n )\n ),\n MenuItemTuple(item_description=\"Application Configuration and Setup\", \n parent_menu_name=\"Extract Infrastructure Master Data|Infrastructure Module\", display_sequence=10, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Konfigurasi dan Penyediaan Sistem'),\n )\n ),\n MenuItemTuple(item_description=\"Application Executables\", \n parent_menu_name=\"Extract Infrastructure Master Data|Infrastructure Module\", display_sequence=20, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Objek-objek boleh dilaksana Sistem'),\n )\n ),\n MenuItemTuple(item_description=\"Application Security and Access Control\", \n parent_menu_name=\"Extract Infrastructure Master Data|Infrastructure Module\", display_sequence=30, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Keselamatan dan Kawalan Pencapaian Sistem'),\n )\n ),\n MenuItemTuple(item_description=\"Application Messaging and Workflow\", \n parent_menu_name=\"Extract Infrastructure Master Data|Infrastructure Module\", display_sequence=40, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Pesanan dan Aliran Kerja'),\n )\n ),\n # Menu Items\n MenuItemTuple(item_description=\"Value Set Data\", \n parent_menu_name=\"Application Configuration and Setup|Extract Infrastructure Master Data\", display_sequence=10, resource_code='VALUE-SET-DATA',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Application Registry Data\", \n parent_menu_name=\"Application Configuration and Setup|Extract Infrastructure Master Data\", display_sequence=20, resource_code='APP-REGISTRY-DATA',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Task Queue Data\", \n parent_menu_name=\"Application Configuration and Setup|Extract Infrastructure Master Data\", display_sequence=40, resource_code='TASK-QUEUE-DATA',\n menu_description_tuple=None\n ),\n )\n\nload_menus(data_menus)\n","sub_path":"infra/fixtures/data_extraction.py","file_name":"data_extraction.py","file_ext":"py","file_size_in_byte":11558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"31977672","text":"\"\"\"Boating Example.\n2010, Tobias Kuester\n\nAnother well-known Planning Problem. Three brothers want to pass a river, one of\nwhich is fat, the other two are slim, and there is only one boat which can hold\nonly either the fat guy or both the slim ones.\n\nThis problem may require rethinking the matching of NOT conditions.\n\"\"\"\n\nfrom knowledge import *\nfrom reasoning import *\nfrom planning import *\n\n\n# define shortcuts for expressing common beliefs\nSlim = lambda subj: Belief(\"Slim\", subj)\nFat = lambda subj: Belief(\"Fat\", subj)\nBoat = lambda subj: Belief(\"Boat\", subj)\nSide = lambda subj: Belief(\"Side\", subj)\nIn = lambda subj, obj: Belief(\"In\", subj, obj)\nAt = lambda subj, obj: Belief(\"At\", subj, obj)\n\n# define shortcuts for some variables\nx, y, z, w, v, _ = \"x\", \"y\", \"z\", \"w\", \"v\", \"*\"\n\n\n# define available actions\nenter = Action(\"Enter\",\n\t\t\t\tpre=And(Boat(y), At(y, z), At(x, z)),\n\t\t\t\teff=And(In(x, y), Not(At(x, z))))\nexit = Action(\"Exit\",\n\t\t\t\tpre=And(Boat(y), In(x, y), At(y, z)),\n\t\t\t\teff=And(At(x, z), Not(In(x, y))))\nride = Action(\"Ride\",\n\t\t\t\tpre=And(Boat(x), At(x, z), Side(w), In(y, x)),\n\t\t\t\teff=And(At(x, w), Not(At(x, z))))\n\nactions = [enter, exit, ride]\n\n\nif __name__ == \"__main__\":\n\n\tfrom test import *\n\n\t# abbreviations for objects\n\tS1, S2, F, B, U1, U2 = \"Slim 1\", \"Slim 2\", \"Fat\", \"Boat\", \"Side 1\", \"Side 2\"\n\n\t# create initial beliefs\n\tbeliefs = (\n\t\tSlim(S1), Slim(S2), Fat(F), Boat(B), Side(U1), Side(U2),\n\t\tAt(S1, U1), At(S2, U1), At(F, U1), At(B, U1)\n\t)\n\tprint_all(\"Initial Beliefs\", beliefs)\n\t\n\t# Get all brothers to the other side\n\tgoal = And(At(S1, U2), At(S2, U2), At(F, U2))\n\tplan = search_plan(goal, beliefs, actions, False, True)\n\tif plan != None:\n\t\tprint_all(\"Plan sequence for goal %s\" % goal, [ (a.name, m) for (a, m) in plan])\n\t\tfor (action, match) in plan:\n\t\t\tbeliefs = update(beliefs, action.eff, match)\n\t\tprint_all(\"After plan execution\", beliefs)\n\telse:\n\t\tprint(\"No Plan Sequence found for goal %s\" % goal)\n\n\n","sub_path":"Planner/boating.py","file_name":"boating.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"422881447","text":"#!/usr/bin/env python\n#\n# -*- coding: utf-8 -*-\n#\n# eventdatacomparison.py\n#\n# Copyright 2020 CU*Answers Integrations \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n\nimport traceback\nimport gevent\n\nfrom compysition.actor import Actor\nimport operator\n\nclass EventDataCompare(Actor):\n '''**Comparison operators against data in the events**\n Initially this is going to test if values are equal to each other.\n Eventually we can add the remaining comparison operators.\n\n Parameters:\n\n name (str):\n | Name of the instance\n left (str):\n | Left comparison value.\n right (str):\n | Right comparison value\n\n '''\n def __init__(self, name, left, right, *args, **kwargs):\n super(EventDataCompare, self).__init__(name, *args, **kwargs)\n self.left = left\n self.right = right\n\n def consume(self, event, *args, **kwargs):\n #event.data.compare_result = operator.eq(event.data.get(self.left), event.data.get(self.right))\n self.logger.info(\"Preparing to compare: {0} with: {1}\".format(self.left, self.right), event=event)\n try:\n event.data[\"comparison_result\"] = operator.eq(event.data.get(self.left), event.data.get(self.right))\n except Exception as err:\n self.logger.error(\"Could not compare results. Reason {0}\".format(err), event=event)\n self.send_event(event)","sub_path":"compysition/actors/eventdatacomparison.py","file_name":"eventdatacomparison.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"5271738","text":"class LibPngPackage (SourceForgeXzPackage):\n\tdef __init__ (self):\n\t\tSourceForgeXzPackage.__init__ (self, 'libpng', 'libpng', '1.6.17', configure_flags = ['--enable-shared'])\n\n\t\t# If we are on OS X this package likes to be a fat binary\n\t\tif Package.profile.name == 'darwin':\n\t\t\tif Package.profile.m64 == True:\n\t\t\t\tself.fat_build = True\n\nLibPngPackage()","sub_path":"packages/libpng.py","file_name":"libpng.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"389947675","text":"import sys, os.path, traceback\nsys.path.append(os.path.join(*(3 * ['..'])))\n\nfrom Communication.tcp import Client\n\ntcp = Client('localhost', 1234, timeout = 2, encoding = 'utf8', decoding = None)\n\nprint('Connected')\n\ntcp.write([0, 128, 255])\ntcp.write('ahoj')\n\nwhile 1:\n try:\n read = tcp.read()\n if read:\n tcp.write(read)\n print(read)\n except KeyboardInterrupt:\n break\n except Exception:\n print(\"Exception in user code:\")\n print(\"-\"*60)\n traceback.print_exc(file=sys.stdout)\n print(\"-\"*60)\ntcp.close()\nprint('\\n\\nclosed')\n","sub_path":"examples/echo/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"158606994","text":"\"\"\"trivial3\n\nRevision ID: 990db0844728\nRevises: 191b892bb787\nCreate Date: 2019-06-18 05:25:39.256337\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '990db0844728'\ndown_revision = '191b892bb787'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('answer', sa.Column('answerer_name', sa.String(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('answer', 'answerer_name')\n # ### end Alembic commands ###\n","sub_path":"allaamus/migrations/versions/990db0844728_trivial3.py","file_name":"990db0844728_trivial3.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"78486625","text":"from zoundry.appframework.constants import IZAppNamespaces\r\nfrom zoundry.appframework.services.spellcheck.dictionariesio import ZSpellCheckDictionaryLanguage\r\nfrom zoundry.appframework.services.spellcheck.spellcheck import IZSpellChecker\r\nfrom zoundry.base.util.classloader import ZClassLoader\r\nfrom zoundry.base.util.collections import ZListenerSet\r\nfrom zoundry.base.zdom.dom import ZDom\r\nimport os\r\nimport string\r\n\r\n# -------------------------------------------------------------------------------------\r\n# Deserializes a spell checker. Takes a path to the spell checker directory, and\r\n# returns an ZSpellChecker object.\r\n# -------------------------------------------------------------------------------------\r\nclass ZSpellCheckerDeserializer:\r\n \r\n def deserialize(self, path):\r\n u\"\"\"deserialize(string) -> ZSpellChecker\"\"\" #$NON-NLS-1$\r\n fpath = os.path.join(path, u\"spellchecker.xml\") #$NON-NLS-1$\r\n dom = ZDom()\r\n dom.load(fpath)\r\n dom.setNamespaceMap({ u\"ns\" : IZAppNamespaces.RAVEN_SPELLCHECKER_NAMESPACE }) #$NON-NLS-1$\r\n spellcheckerElem = dom.documentElement\r\n \r\n dictionaryLanguage = self._deserializeDictionaryLanguage(spellcheckerElem)\r\n provider = self._deserializeProvider(spellcheckerElem, dictionaryLanguage)\r\n personalWordList = self._deserializePersonalDictionary(spellcheckerElem)\r\n autoCorrections = self._deserializeAutoCorrections(spellcheckerElem)\r\n \r\n return ZSpellChecker(path, dictionaryLanguage, provider, personalWordList, autoCorrections)\r\n # end deserialize()\r\n \r\n def _deserializeDictionaryLanguage(self, spellcheckerElem):\r\n languageElem = spellcheckerElem.selectSingleNode(u\"ns:language\") #$NON-NLS-1$\r\n langCode = languageElem.getAttribute(u\"lang-code\") #$NON-NLS-1$\r\n dictHandler = languageElem.getAttribute(u\"handler\") #$NON-NLS-1$\r\n dictType = languageElem.getAttribute(u\"type\") #$NON-NLS-1$\r\n dispName = languageElem.getAttribute(u\"display-name\") #$NON-NLS-1$\r\n url = languageElem.getAttribute(u\"url\") #$NON-NLS-1$\r\n return ZSpellCheckDictionaryLanguage(langCode, dispName, dictHandler, dictType, url)\r\n # end _deserializeDictionaryLanguage()\r\n \r\n def _deserializeProvider(self, spellcheckerElem, dictionaryLanguage):\r\n providerElem = spellcheckerElem.selectSingleNode(u\"ns:provider\") #$NON-NLS-1$\r\n providerClassname = providerElem.getText()\r\n providerClass = ZClassLoader().loadClass(providerClassname)\r\n return providerClass(dictionaryLanguage)\r\n # end _deserializeProvider()\r\n \r\n def _deserializePersonalDictionary(self, spellcheckerElem):\r\n personalWordList = []\r\n\r\n personalDictionaryWordElems = spellcheckerElem.selectNodes(u\"ns:personal-dictionary/ns:word\") #$NON-NLS-1$\r\n for wordElem in personalDictionaryWordElems:\r\n word = wordElem.getText()\r\n personalWordList.append(word)\r\n \r\n return personalWordList\r\n # end _deserializePersonalDictionary()\r\n \r\n def _deserializeAutoCorrections(self, spellcheckerElem):\r\n autoCorrections = {}\r\n \r\n autoCorrectionElems = spellcheckerElem.selectNodes(u\"ns:auto-corrections/ns:auto-correction\") #$NON-NLS-1$\r\n for acElem in autoCorrectionElems:\r\n key = acElem.getAttribute(u\"word\") #$NON-NLS-1$\r\n value = acElem.getText()\r\n autoCorrections[key] = value\r\n \r\n return autoCorrections\r\n # end _deserializeAutoCorrections()\r\n \r\n# end ZSpellCheckerDeserializer\r\n\r\n\r\n# -------------------------------------------------------------------------------------\r\n# Serializes a spell checker to file. Takes a ZSpellChecker object and a path to the \r\n# spell checker directory, and saves the spell checker to that directory.\r\n# -------------------------------------------------------------------------------------\r\nclass ZSpellCheckerSerializer:\r\n \r\n def serialize(self, spellChecker, path):\r\n u\"\"\"serialize(ZSpellChecker, string) -> None\r\n Serializes a spell checker to a string. The path is a directory.\"\"\" #$NON-NLS-1$\r\n dom = ZDom()\r\n dom.loadXML(u\"\"\"\"\"\" % IZAppNamespaces.RAVEN_SPELLCHECKER_NAMESPACE) #$NON-NLS-1$\r\n spellCheckerElem = dom.documentElement\r\n self._serializeDictionaryLanguage(spellCheckerElem, spellChecker.dictionaryLang)\r\n self._serializeProvider(spellCheckerElem, spellChecker.provider)\r\n self._serializePersonalDictionary(spellCheckerElem, spellChecker.personalWordList)\r\n self._serializeAutoCorrections(spellCheckerElem, spellChecker.autoCorrections)\r\n \r\n if not os.path.isdir(path):\r\n os.makedirs(path)\r\n filePath = os.path.join(path, u\"spellchecker.xml\") #$NON-NLS-1$\r\n dom.save(filePath, True)\r\n # end serialize()\r\n\r\n def _serializeDictionaryLanguage(self, parentElem, dictionaryLang):\r\n languageElem = self._createElement(parentElem, u\"language\") #$NON-NLS-1$\r\n languageElem.setAttribute(u\"lang-code\", dictionaryLang.getLanguageCode()) #$NON-NLS-1$\r\n languageElem.setAttribute(u\"handler\", dictionaryLang.getDictionaryHandler()) #$NON-NLS-1$\r\n languageElem.setAttribute(u\"type\", dictionaryLang.getDictionaryType()) #$NON-NLS-1$\r\n languageElem.setAttribute(u\"display-name\", dictionaryLang.getDisplayName()) #$NON-NLS-1$\r\n languageElem.setAttribute(u\"url\", dictionaryLang.getDictionaryUrl()) #$NON-NLS-1$\r\n parentElem.appendChild(languageElem)\r\n # end _serializeDictionaryLanguage()\r\n\r\n def _serializeProvider(self, parentElem, provider):\r\n providerElem = self._createElement(parentElem, u\"provider\") #$NON-NLS-1$\r\n providerElem.setText(unicode(provider.__class__))\r\n parentElem.appendChild(providerElem)\r\n # end _serializeProvider()\r\n\r\n def _serializePersonalDictionary(self, parentElem, personalWordList):\r\n personalDictElem = self._createElement(parentElem, u\"personal-dictionary\") #$NON-NLS-1$\r\n for word in personalWordList:\r\n wordElem = self._createElement(personalDictElem, u\"word\") #$NON-NLS-1$\r\n wordElem.setText(word)\r\n personalDictElem.appendChild(wordElem)\r\n parentElem.appendChild(personalDictElem)\r\n # end _serializePersonalDictionary()\r\n \r\n def _serializeAutoCorrections(self, parentElem, autoCorrections):\r\n autoCorrectionsElem = self._createElement(parentElem, u\"auto-corrections\") #$NON-NLS-1$\r\n for acKey in autoCorrections:\r\n acValue = autoCorrections[acKey]\r\n autoCorrectionElem = self._createElement(autoCorrectionsElem, u\"auto-correction\") #$NON-NLS-1$\r\n autoCorrectionElem.setAttribute(u\"word\", acKey) #$NON-NLS-1$\r\n autoCorrectionElem.setText(acValue)\r\n autoCorrectionsElem.appendChild(autoCorrectionElem)\r\n parentElem.appendChild(autoCorrectionsElem)\r\n # end _serializeAutoCorrections()\r\n\r\n def _createElement(self, parentElem, tagName):\r\n return parentElem.ownerDocument.createElement(tagName, IZAppNamespaces.RAVEN_SPELLCHECKER_NAMESPACE)\r\n # end _createElement()\r\n \r\n# end ZSpellCheckerSerializer\r\n\r\n\r\n# ---------------------------------------------------------------------------------------\r\n# Implementation of a IZSpellChecker. This class uses a spell check provider in order\r\n# to supply the implementation of the check() and suggest() methods.\r\n# ---------------------------------------------------------------------------------------\r\nclass ZSpellChecker(IZSpellChecker):\r\n\r\n def __init__(self, directoryPath, dictionaryLang, provider, personalWordList = None, autoCorrections = None):\r\n self.directoryPath = directoryPath\r\n self.listeners = ZListenerSet()\r\n self.builtInDictionary = []\r\n self.dictionaryLang = dictionaryLang # An IZSpellCheckDictionaryLanguage\r\n self.provider = provider # An IZSpellCheckProvider\r\n self.personalWordList = personalWordList # A List of strings\r\n self.autoCorrections = autoCorrections # A Map of string -> string\r\n \r\n if self.personalWordList is None:\r\n self.personalWordList = []\r\n if self.autoCorrections is None:\r\n self.autoCorrections = {}\r\n # end __init__()\r\n\r\n def addListener(self, listener):\r\n self.listeners.append(listener)\r\n # end addListener()\r\n\r\n def removeListener(self, listener):\r\n self.listeners.remove(listener)\r\n # end removeListener()\r\n \r\n def setBuiltInDictionary(self, builtInDictionary):\r\n self.builtInDictionary = builtInDictionary\r\n # end setBuiltInDictionary()\r\n\r\n def check(self, word):\r\n lword = string.lower(word)\r\n \r\n # Check the built-in dictionary\r\n if lword in self.builtInDictionary:\r\n return True\r\n # Check the personal dictionary\r\n if lword in self.personalWordList:\r\n return True\r\n \r\n # Use the provider\r\n return self.provider.check(word)\r\n # end check()\r\n\r\n def suggest(self, word):\r\n return self.provider.suggest(word)\r\n # end suggest()\r\n \r\n def autoCorrect(self, word):\r\n lword = string.lower(word)\r\n if lword in self.autoCorrections:\r\n newWord = self.autoCorrections[lword]\r\n if self._isCapitalized(word):\r\n newWord = string.capitalize(newWord)\r\n return newWord\r\n return None\r\n # end autoCorrect()\r\n\r\n def destroy(self):\r\n self.provider.destroy()\r\n # end destroy()\r\n\r\n def addAutoCorrection(self, word, replacement):\r\n self.autoCorrections[string.lower(word)] = replacement\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onAutoCorrectionAdded(word, replacement)\r\n # end addAutoCorrection()\r\n\r\n def removeAutoCorrection(self, word):\r\n lword = string.lower(word)\r\n if lword in self.autoCorrections:\r\n del self.autoCorrections[lword]\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onAutoCorrectionRemoved(word)\r\n # end removeAutoCorrection()\r\n\r\n def getAutoCorrections(self):\r\n return self.autoCorrections\r\n # end getAutoCorrections()\r\n\r\n def getAutoCorrection(self, word):\r\n lword = string.lower(word)\r\n if lword in self.autoCorrections:\r\n return self.autoCorrections[lword]\r\n return None\r\n # end getAutoCorrection()\r\n\r\n def clearAutoCorrections(self):\r\n self.autoCorrections = {}\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onAutoCorrectionsCleared()\r\n # end clearAutoCorrections()\r\n\r\n def addWord(self, word):\r\n lword = string.lower(word)\r\n if not lword in self.personalWordList:\r\n self.personalWordList.append(lword)\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onPersonalDictionaryWordAdded(word)\r\n # end addWord()\r\n \r\n def addWords(self, words):\r\n for word in words:\r\n lword = string.lower(word)\r\n if not lword in self.personalWordList:\r\n self.personalWordList.append(lword)\r\n for listener in self.listeners:\r\n listener.onPersonalDictionaryWordAdded(word)\r\n self._save()\r\n # end addWords()\r\n\r\n def removeWord(self, word):\r\n lword = string.lower(word)\r\n if not lword in self.personalWordList:\r\n del self.personalWordList[lword]\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onPersonalDictionaryWordRemoved(word)\r\n # end removeWord()\r\n\r\n def getWords(self):\r\n return self.personalWordList\r\n # end getWords()\r\n\r\n def clearPersonalDictionary(self):\r\n self.personalWordList = []\r\n self._save()\r\n for listener in self.listeners:\r\n listener.onPersonalDictionaryCleared()\r\n # end clearPersonalDictionary()\r\n\r\n def _save(self):\r\n serializer = ZSpellCheckerSerializer()\r\n serializer.serialize(self, self.directoryPath)\r\n # end _save()\r\n \r\n def _isCapitalized(self, word):\r\n return word == string.capitalize(word)\r\n # end _isCapitalized()\r\n\r\n# end ZSpellChecker\r\n","sub_path":"src/python/zoundry/appframework/services/spellcheck/spellcheckerimpl.py","file_name":"spellcheckerimpl.py","file_ext":"py","file_size_in_byte":12414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"171331167","text":"from datetime import datetime\nclass Employee:\n def __init__(self, name, age, salary, employment_year):\n self.name = name\n self.age = age\n self.salary = salary\n self.employment_year = employment_year\n\n def get_working_years(self):\n return datetime.now().year - self.employment_year\n\n def __str__(self):\n return \"name: %s age: %s salary: %s employment year %s \" % (self.name, self.age, self.salary, self.employment_year)\n\n\nclass Manager(Employee):\n def __init__(self, name, age, salary, employment_year, bonus_percentage):\n Employee.__init__(self, name, age, salary, employment_year)\n self.bonus_percentage = bonus_percentage\n\n def get_working_years(self):\n return datetime.now().year - self.employment_year\n\n def get_bonus(self):\n return self.bonus_percentage * self.salary\n\n def __str__(self):\n return \"name: %s age: %s salary: %s employment year %s bonus percentage %s \" % (self.name, self.age, self.salary, self.employment_year, self.bonus_percentage)\n\n\n\ndef main():\n elist = []\n mlist = []\n while 0 == 0:\n print(\"----------------------\\n\\n----------------------\\nWelcome to HR Pro 2020\\n\\n\")\n print(\"Options: \\n\\n 1. Show Employees \\n 2. Show Managers \\n 3. Add An Employee \\n 4. Add A Manager \\n 5. Exit\")\n option = input(\"\\n\\nWhat would you like to do?\")\n if option == \"1\":\n print(\"Employees\")\n for emp in elist:\n print(emp)\n elif option == \"2\":\n print(\"Managers\")\n for mngr in mlist:\n print (mngr)\n elif option == \"3\":\n name = input(\"name: \")\n age = input(\"age: \")\n salary = input(\"salary: \")\n employment_year = input(\"Employement year: \")\n e = Employee(name, age, salary, employment_year)\n elist.append(e)\n print(\"Employee added succesfully\")\n elif option == \"4\":\n name = input(\"name: \")\n age = input(\"age: \")\n salary = input(\"salary: \")\n employment_year = input(\"Employement year: \")\n bonus_percentage = input(\"bonus percentage: \")\n m = Manager(name, age, salary, employment_year, bonus_percentage)\n mlist.append(m)\n print(\"Manager added succesfully\")\n elif option == \"5\":\n exit()\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hr_pro.py","file_name":"hr_pro.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"457631948","text":"import math \nd=list(map(int,input().split()))\nc=50\nh=30\ne=[]\nfor i in d:\n\tq=pow((2*c*i/h),0.5)\n\te.append(q)\nprint(e)\n\n","sub_path":"sample1q4.py","file_name":"sample1q4.py","file_ext":"py","file_size_in_byte":118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"323266397","text":"#-*-coding:utf-8-*-\nimport os\nimport os.path as osp\nimport torch\nfrom torch.autograd import Variable\nfrom utils.MyBCEWithLogitsLoss import BCEWithLogitsLoss as MyBCEWithLogitsLoss\nfrom tqdm import tqdm\n\ndef GetTrueLabel(label):\n index = []\n for s_label in label:\n temp = []\n temp = [m for m,j in enumerate(s_label) if j==1]\n index.append(temp)\n true_label = []\n for i in index:\n temp = []\n for j in i:\n if j in range(0,14):\n temp.append([0, j])\n elif j in range(14,23,1):\n temp.append([1, j-14])\n elif j in range(23,100,1):\n temp.append([2, j-23])\n elif j in range(100,107,1):\n temp.append([3, j-100])\n elif j in range(107,115,1):\n temp.append([4, j-107])\n elif j in range(115,141,1):\n temp.append([5, j-115])\n elif j in range(141,162,1):\n temp.append([6, j-141])\n elif j in range(162,169,1):\n temp.append([7, j-162])\n elif j in range(169,184,1):\n temp.append([8, j-169])\n elif j in range(184,223,1):\n temp.append([9, j-184])\n elif j in range(223,235,1):\n temp.append([10, j-223])\n elif j in range(235,245,1):\n temp.append([11, j-235])\n elif j in range(245,254,1):\n temp.append([12, j-245])\n elif j in range(254,262,1):\n temp.append([13, j-254])\n elif j in range(262,273,1):\n temp.append([14, j-262])\n elif j in range(273,285,1):\n temp.append([15, j-273])\n elif j in range(285,292,1):\n temp.append([16, j-285])\n elif j in range(292,303,1):\n temp.append([17, j-292])\n true_label.append(temp)\n return true_label\n\n########### for sigmoid_cross_entropy_with_logits ##########\n\n# change +1 to torch.FloatTensor(1) and -1 into torch.FloatTensor()\ndef change_label(label):\n true_label = []\n for s_label in label:\n temp = [1 if i==1 else 0 for i in s_label]\n true_label.append(temp)\n \n return Variable(torch.FloatTensor(true_label).cuda()) # N X C\n\n#### single branch\ndef sigmoid_train_batch(model, criterion, optimizer, batch_label):\n optimizer.zero_grad() #\n C = batch_label[0][0].shape[0]\n H = batch_label[0][0].shape[1]\n W = batch_label[0][0].shape[2]\n batch = torch.cat((batch_label[i][0] for i in range(len(batch_label))),0).view(-1,C,H,W) # N C H W\n input = Variable(batch.cuda())\n label = [batch_label[i][1] for i in range(len(batch_label))]\n target = change_label(label)\n output = model(input)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n return loss.data\n\ndef sigmoid_train_epoch(model, num_batches, train_loader, print_freq, optimizer=None):\n criterion = torch.nn.BCEWithLogitsLoss()\n for batch_label in train_loader:\n loss = sigmoid_train_batch(model, criterion, optimizer, batch_label)\n if num_batches%print_freq == 0:\n print('%23s%-9s%-13s'%('the '+str(num_batches)+'th batch, ','loss is: ',str(round(loss[0],8))))\n num_batches +=1\n return num_batches\n\n#### multi branch\n# no category branch\nAttr_Num_dict = {'category':23, 'length_of_upper_body_clothes':5, 'length_of_trousers':5, 'length_of_dresses':5, 'length_of_sleeves':8,\\\n'fitness_of_clothes':5, 'design_of_dresses':10, 'type_of_sleeves':10, 'type_of_trousers':7, 'type_of_dresses':12,\\\n'type_of_collars':10, 'type_of_waistlines':7, 'type_of_clothes_buttons':7, 'thickness_of_clothes':4, 'fabric_of_clothes':20,\\\n'style_of_clothes':23, 'part_details_of_clothes':72, 'graphic_elements_texture':47}\n\nAttr = ['length_of_upper_body_clothes', 'length_of_trousers', 'length_of_dresses', 'length_of_sleeves', 'fitness_of_clothes',\\\n'design_of_dresses', 'type_of_sleeves', 'type_of_trousers', 'type_of_dresses', 'type_of_collars', 'type_of_waistlines', \\\n'type_of_clothes_buttons', 'thickness_of_clothes', 'fabric_of_clothes', 'style_of_clothes', \\\n'part_details_of_clothes', 'graphic_elements_texture']\n\n# input: labels, Each_Attr_id\n# labels = [1,+1,-1,-1,+1,+1,...]*batch_size\n# out branch_ids: [[0,1,2],[1,3],...] branch_label: [[1,0,1,0,0,0,1..],[1,0,0,1,1,0,...]...]\ndef get_branch(Each_Attr_id, labels):\n branch_label = []\n branch_ids = []\n index1_index0 = {}\n Attr_ids = []\n for key in Attr:\n Attr_ids.append(Each_Attr_id[key])\n index1 = 0\n for index0, label in enumerate(labels):\n temp = []\n temp1 = []\n cur_ids = []\n for i,j in enumerate(label):\n if j==1:\n for m, ids in enumerate(Attr_ids):\n if i in ids and m not in temp:\n temp.append(m)\n cur_ids += ids \n if len(cur_ids)!=0:\n index1_index0[index1] = index0 # index0 is smaple id in batch, index1 is the out sample id(has at least one attr)\n branch_ids.append(temp)\n branch_label.append(Variable(torch.unsqueeze(torch.FloatTensor([label[k] for k in cur_ids]), dim=0).cuda()))\n index1+=1\n\n return index1_index0, branch_ids, branch_label\n\n## only multi label\ndef multi_task_train_batch(model, Each_Attr_id, criterion, optimizer, batch_label):\n optimizer.zero_grad() #\n C = batch_label[0][0].shape[0]\n H = batch_label[0][0].shape[1]\n W = batch_label[0][0].shape[2]\n batch = torch.cat((batch_label[i][0] for i in range(len(batch_label))),0).view(-1,C,H,W) # N C H W\n input = Variable(batch.cuda())\n\n labels = [batch_label[i][1] for i in range(len(batch_label))] # [[1,-1..],[1,1,-1..]]\n for i, label in enumerate(labels):\n labels[i] = [1 if j==1 else 0 for j in label]\n index1_index0, branch_ids, branch_label = get_branch(Each_Attr_id, labels)\n\n output = model(input) # [NxC1, NxC2, NxC3, NxC4, NxC5, ..., NxC17]\n\n loss = []\n for i,(branch_id,label) in enumerate(zip(branch_ids, branch_label)):\n index0 = index1_index0[i]\n if len(branch_id)>=1:\n cur_output = torch.unsqueeze(torch.cat(tuple((output[j][index0] for j in branch_id)),0), dim=0)\n else:\n cur_output = output[branch_id[0]][index0]\n loss.append(criterion(cur_output, label))\n\n total_loss = sum(loss)/len(loss)\n total_loss.backward() \n optimizer.step()\n\n return total_loss.data\n\ndef multi_task_train_epoch(model, Each_Attr_id, num_batches, train_loader, print_freq, optimizer=None):\n criterion = torch.nn.BCEWithLogitsLoss()\n for batch_label in train_loader:\n loss = multi_task_train_batch(model, Each_Attr_id, criterion, optimizer, batch_label)\n if num_batches%print_freq == 0:\n print('%23s%-9s%-13s'%('the '+str(num_batches)+'th batch, ','loss is: ',str(round(loss[0],8))))\n num_batches +=1\n return num_batches\n\n\n## multi_class + multi_label training\n# ignore category\n# 'length_of_upper_body_clothes':0,\n# 'length_of_trousers':0,\n# 'length_of_dresses':0,\n# 'length_of_sleeves':1,\n# 'fitness_of_clothes':1,\n# 'design_of_dresses':1,\n# 'type_of_sleeves':0,\n# 'type_of_trousers':1,\n# 'type_of_dresses':0,\n# 'type_of_collars':0,\n# 'type_of_waistlines':1,\n# 'type_of_clothes_buttons':1,\n# 'thickness_of_clothes':0,\n# 'fabric_of_clothes':1,\n# 'style_of_clothes':1,\n# 'part_details_of_clothes':1,\n# 'graphic_elements_texture':1\ndef mix_multi_task_train_batch(model, Each_Attr_id, multi_label, multi_class, optimizer, batch_label):\n multi_class_indexs = [0,1,2,6,8,9,12]\n multi_label_indexs = [3,4,5,7,10,11,13,14,15,16]\n num_each_attr = [5, 5, 5, 8, 5, 10, 10, 7, 12, 10, 7, 7, 4, 20, 23, 72, 47]\n if optimizer is None:\n pass\n else:\n optimizer.zero_grad() #\n C = batch_label[0][0].shape[0]\n H = batch_label[0][0].shape[1]\n W = batch_label[0][0].shape[2]\n batch = torch.cat((batch_label[i][0] for i in range(len(batch_label))),0).view(-1,C,H,W) # N C H W\n input = Variable(batch.cuda())\n\n labels = [batch_label[i][1] for i in range(len(batch_label))] # [[1,-1..],[1,1,-1..]]\n for i, label in enumerate(labels):\n labels[i] = [1 if j==1 else 0 for j in label]\n index1_index0, branch_ids, _ = get_branch(Each_Attr_id, labels)\n\n output = model(input) # [NxC1, NxC2, NxC3, NxC4, NxC5, ..., NxC17]\n\n loss = []\n for i,(branch_id,label) in enumerate(zip(branch_ids, labels)):\n index0 = index1_index0[i]\n for index in branch_id:\n if index in multi_class_indexs:\n cur_output = torch.unsqueeze(output[index][index0], dim=0)\n if index==0:\n start = 23\n else:\n start = sum(num_each_attr[0:index])+23\n end = num_each_attr[index]+start\n for tt,qq in enumerate(label[start:end]):\n if qq==1:\n cur_label = Variable(torch.LongTensor([tt])).cuda()\n loss.append(multi_class(cur_output, cur_label))\n break\n elif index in multi_label_indexs:\n if index==0:\n start = 23\n else:\n start = sum(num_each_attr[0:index])+23\n end = num_each_attr[index]+start\n cur_output = torch.unsqueeze(output[index][index0], dim=0)\n cur_label = Variable(torch.unsqueeze(torch.FloatTensor(label[start:end]), dim=0).cuda())\n loss.append(multi_label(cur_output, cur_label))\n \n\n total_loss = sum(loss)/len(loss)\n total_loss.backward()\n if optimizer is None:\n pass\n else:\n optimizer.step()\n\n return total_loss.data\n\ndef mix_multi_task_train_epoch(csvfile, writer, model, Each_Attr_id, num_batches, train_loader, print_freq, optimizer=None):\n multi_label = MyBCEWithLogitsLoss()\n multi_class = torch.nn.CrossEntropyLoss()\n for batch_label in train_loader:\n loss = mix_multi_task_train_batch(model, Each_Attr_id, multi_label, multi_class, optimizer, batch_label)\n if num_batches%print_freq == 0:\n print('%23s%-9s%-13s'%('the '+str(num_batches)+'th batch, ','loss is: ',str(round(loss[0],8))))\n num_batches +=1\n return num_batches\n\n\n########### get sample loss ###########\n\ndef mix_multi_task_test_loss_batch(csvfile, writer, jpg_folders, model, Each_Attr_id, multi_label, multi_class, batch_label):\n multi_class_indexs = [0,1,2,6,8,9,12]\n multi_label_indexs = [3,4,5,7,10,11,13,14,15,16]\n num_each_attr = [5, 5, 5, 8, 5, 10, 10, 7, 12, 10, 7, 7, 4, 20, 23, 72, 47]\n\n C = batch_label[0][0].shape[0]\n H = batch_label[0][0].shape[1]\n W = batch_label[0][0].shape[2]\n batch = torch.cat((batch_label[i][0] for i in range(len(batch_label))),0).view(-1,C,H,W) # N C H W\n input = Variable(batch.cuda())\n\n labels = [batch_label[i][1] for i in range(len(batch_label))] # [[1,-1..],[1,1,-1..]]\n for i, label in enumerate(labels):\n labels[i] = [1 if j==1 else 0 for j in label]\n index1_index0, branch_ids, _ = get_branch(Each_Attr_id, labels)\n\n output = model(input) # [NxC1, NxC2, NxC3, NxC4, NxC5, ..., NxC17]\n\n loss = []\n sample_loss = [0.0]*len(batch_label)\n for i,(branch_id,label) in enumerate(zip(branch_ids, labels)):\n index0 = index1_index0[i]\n for index in branch_id:\n if index in multi_class_indexs:\n cur_output = torch.unsqueeze(output[index][index0], dim=0)\n if index==0:\n start = 23\n else:\n start = sum(num_each_attr[0:index])+23\n end = num_each_attr[index]+start\n for tt,qq in enumerate(label[start:end]):\n if qq==1:\n cur_label = Variable(torch.LongTensor([tt])).cuda()\n sample_loss[i]+=float(multi_class(cur_output, cur_label).cpu().data)\n loss.append(multi_class(cur_output, cur_label))\n break\n elif index in multi_label_indexs:\n if index==0:\n start = 23\n else:\n start = sum(num_each_attr[0:index])+23\n end = num_each_attr[index]+start\n cur_output = torch.unsqueeze(output[index][index0], dim=0)\n cur_label = Variable(torch.unsqueeze(torch.FloatTensor(label[start:end]), dim=0).cuda())\n sample_loss[i]+=float(multi_label(cur_output, cur_label).cpu().data)\n loss.append(multi_label(cur_output, cur_label))\n\n for test_loss, folder in zip(sample_loss, jpg_folders):\n writer.writerow({'img path': folder, \\\n 'total loss': round(test_loss,8)})\n\n\n\ndef mix_multi_task_test_loss_epoch(csvfile, writer, model, Each_Attr_id, data_loader):\n multi_label = torch.nn.BCEWithLogitsLoss()\n multi_class = torch.nn.CrossEntropyLoss()\n for (batch_label,indexs) in tqdm(data_loader,desc='Test loss',ncols=100):\n jpg_folders = [data_loader.dataset.samples[index][0] for index in indexs]\n loss = mix_multi_task_test_loss_batch(csvfile, writer, jpg_folders, model, Each_Attr_id, multi_label, multi_class, batch_label)\n \n\n########### for sigmoid_cross_entropy_with_logits ##########\n\n\n########### for softmax_cross_entropy_with_logits ##########\ndef train_batch(model, optimizer, batch_label):\n optimizer.zero_grad() #\n C = batch_label[0][0].shape[0]\n H = batch_label[0][0].shape[1]\n W = batch_label[0][0].shape[2]\n batch = torch.cat((batch_label[i][0] for i in range(len(batch_label))),0).view(-1,C,H,W)\n label = [batch_label[i][1] for i in range(len(batch_label))]\n input = Variable(batch.cuda())\n output = [i for i in model(input)]\n criterion = torch.nn.CrossEntropyLoss()\n loss = []\n true_label = GetTrueLabel(label)\n for i,j in enumerate(true_label):\n for Attr, Attr_Value in j:\n cur_output = torch.unsqueeze(output[Attr][i], dim=0)\n target = Variable(torch.LongTensor([Attr_Value]).cuda())\n loss.append(criterion(cur_output, target))\n Avg_loss = sum(loss)/input.shape[0] # you should calcu each sample loss, and get a mean value\n Avg_loss.backward()\n\n optimizer.step()\n return Avg_loss.data\n\ndef train_epoch(model, num_batches, train_loader, print_freq, optimizer=None):\n for batch_label in train_loader:\n loss = train_batch(model, optimizer, batch_label)\n if num_batches%print_freq == 0:\n print('%23s%-9s%-13s'%('the '+str(num_batches)+'th batch, ','loss is: ',str(round(loss[0],8))))\n num_batches +=1\n return num_batches\n\n\n########### for softmax_cross_entropy_with_logits ##########","sub_path":"FashionBeta/classify/consumer/utils/train_Components.py","file_name":"train_Components.py","file_ext":"py","file_size_in_byte":14875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"559669982","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom urllib import request\nfrom bs4 import BeautifulSoup\n\nimport requests\nimport xlwt\nimport bs4\n\nurl = \"https://www.zhipin.com/\"\n\ndef get_job_info(index):\n params = {\n \"query\":\"index\",\n \"city\":100010000\n }\n request_url = url + \"/job_detail/?\" + urlencode(params)\n print(\"请求的URL:{}\".format(request_url))\n post_infos = []\n flip_flag = True\n while flip_flag:\n print(\"[DEBUG INFO]: 请求网址:{}\".format(request_url))\n try:\n soup = bs4.BeautifulSoup(request.get(request_url).text,\"lxml\")\n job_list = soup.find(\"div\",{\"class\":\"job-box\"}).find(\"div\",{\"class\":\"job-list\"})\n except:\n print(\"没有查询到相关记录\")\n break\n for job in job_list:\n job_primary = job.find(\"div\",{\"class\":\"job-primary\"})\n info_primary = job_primary.find(\"div\",{\"class\":\"info-primary\"})\n info_company = job_primary.find(\"div\",{\"class\":\"info-company\"})\n info_publis = job_primary.find(\"div\", {\"class\": \"info_publis\"})\n\n\n","sub_path":"pacong/boss直聘.py","file_name":"boss直聘.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"10542340","text":"from .swa import SWA_class\nfrom .ewma import EWMA_class\nfrom .linearregression import LR_class\nfrom .arima import Arima_class\nfrom .PredictModel import PredictModel\n\nclass SamplePredictRes:\n def __init__(self,predictmethond):\n self.predictmethod = predictmethond\n\n\n def predictres(self,**kwargs):\n e = PredictModel(**kwargs)\n\n if (self.predictmethod == 'MA'):\n e = SWA_class(**kwargs)\n\n elif (self.predictmethod == 'EWMA'):\n e = EWMA_class(**kwargs)\n\n elif (self.predictmethod == 'LR'):\n e = LR_class(**kwargs)\n\n elif (self.predictmethod == 'ARIMA'):\n e = Arima_class(**kwargs)\n\n e.createdata()\n predf = e.predict()\n return predf\n\n","sub_path":"algorithm/univariate_predictor/SamplePredict.py","file_name":"SamplePredict.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"233105112","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Go through a dump finding links to nonexistent pages.\n\nimport pywikibot, re, sys, argparse, codecs\n\nimport blib\nfrom blib import getparam, rmparam, msg, site\nfrom collections import defaultdict\n\nblib.getLanguageData()\n\ntemplates_to_check = {}\nfor template in [\n \"l\", \"link\",\n \"m\", \"mention\",\n \"m+\",\n \"cog\", \"cognate\",\n \"nc\", \"ncog\", \"noncog\", \"noncognate\",\n]:\n templates_to_check[template] = [\"1\", \"2\"]\nfor template in [\"inh\", \"inherited\", \"bor\", \"borrowed\", \"der\", \"derived\"]:\n templates_to_check[template] = [\"2\", \"3\"]\n\ndef zh_l(t, note):\n for page in getparam(t, \"1\").split(\"/\"):\n note(\"zh\", page)\n\ndef ko_l(t, note):\n for param in [\"1\", \"2\", \"3\", \"4\"]:\n # Yuck yuck yuck! The following is from [[Module:ko]], which allows\n # Hanja, Hangul, translit and gloss params in any order and has a complex\n # algorithm to disambiguate them.\n # FIXME: This needs changing for Python 3.\n val = getparam(t, param)\n if re.search(\"[가-힣㐀-䶵一-鿌\\uF900-\\uFADF𠀀-𯨟]\", val):\n note(\"ko\", val)\n\ndef ja_l(t, note):\n note(\"ja\", getparam(t, \"1\").replace(\"%\", \"\"))\n\ndef vi_l(t, note):\n note(\"vi\", getparam(t, \"1\"))\n note(\"vi\", getparam(t, \"2\"))\n\ndef vi_link(t, note):\n note(\"vi\", getparam(t, \"1\"))\n\ntemplates_to_check.update({\n \"zh-l\": zh_l,\n \"zh-m\": zh_l,\n \"ko-l\": ko_l,\n \"ja-l\": ja_l,\n \"ja-r\": ja_l,\n \"vi-l\": vi_l,\n \"vi-link\": vi_link,\n})\n\ndef read_existing_pages(filename):\n pages_with_langs = {}\n for line in codecs.getreader(\"utf-8\")(gzip.open(filename, \"rb\"), errors=\"replace\"):\n line = line.rstrip(\"\\n\")\n if re.search(\"^Page [0-9]+ .*: WARNING: .*\", line):\n msg(\"Skipping warning: %s\" % line)\n else:\n m = re.search(\"^Page [0-9-]+ (.*): Langs=(.*?)$\", line)\n if not m:\n msg(\"WARNING: Unrecognized line: %s\" % line)\n else:\n pages_with_langs[m.group(1)] = set(m.group(2).split(\",\"))\n return pages_with_langs\n\nunrecognized_pages_by_lang_with_count = {}\nunrecognized_pages_by_lang_with_source_pages = {}\n\ndef process_text_on_page(index, pagetitle, pagetext):\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n def note_unrecognized_link(lang, page):\n if lang not in unrecognized_pages_by_lang_with_count:\n unrecognized_pages_by_lang_with_count[lang] = defaultdict(int)\n unrecognized_pages_by_lang_with_count[lang][page] += 1\n if lang not in unrecognized_pages_by_lang_with_source_pages:\n unrecognized_pages_by_lang_with_source_pages[lang] = {}\n if page not in unrecognized_pages_by_lang_with_source_pages[lang]:\n unrecognized_pages_by_lang_with_source_pages[lang][page] = set()\n else:\n unrecognized_pages_by_lang_with_source_pages[lang][page].add(pagetitle)\n\n def note_link(lang, page):\n if not page:\n return\n if not lang and page not in pages_with_langs:\n note_unrecognized_link(lang, page)\n elif lang and (page not in pages_with_langs or lang not in pages_with_langs[page]):\n note_unrecognized_link(lang, page)\n\n # Look for raw links.\n for m in re.finditer(r\"\\[\\[(.*?)\\]\\]\", pagetext):\n linkparts = m.group(1).split(\"|\")\n if linkparts > 2:\n pagemsg(\"WARNING: Link has more than two parts: %s\" % m.group(0))\n else:\n page = linkparts[0]\n if \"#\" in page:\n page, anchor = page.split(\"#\", 1)\n if anchor in blib.languages_byCanonicalName:\n note_link(blib.languages_byCanonicalName[anchor][\"code\"], page)\n else:\n note_link(None, page)\n else:\n note_link(None, page)\n\n # Look for templated links.\n for t in blib.parse_text(pagetext).filter_templates():\n pass\n\nparser = blib.create_argparser(\"Find red links\", include_pagefile=True, include_stdin=True)\nparser.add_argument(\"--existing-pages\", help=\"Gzipped file containing existing pages by language\",\n required=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\npages_with_langs = read_existing_pages(args.existing_pages)\n\nblib.do_pagefile_cats_refs(args, start, end, process_text_on_page, stdin=True)\n","sub_path":"find_wanted_pages.py","file_name":"find_wanted_pages.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"78823043","text":"#Ordering tools\nimport json\nimport numpy as np, treelog\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib import collections\n# import matplotlib.pyplot as plt\nimport seaborn as sns;\n\nfrom files.myModellib import get_welldata\n\nsns.set()\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport math\nimport matplotlib.style as style\nstyle.use('seaborn-paper')\nsns.set_context(\"paper\")\nsns.set_style(\"whitegrid\")\n\n## Parameters txt file reader\ndef read_from_txt ( filename ):\n\n # Open the parameter file to read\n with open(filename, 'r') as json_file:\n data = json.load(json_file)\n\n return data['aquifer'][0], data['well'][0]\n\n## Generates a Parameters txt file\ndef generate_txt( filename):\n import json\n\n data = {}\n data['aquifer'] = []\n data['aquifer'].append({\n 'H': 70,\n 'dtop': 2387,\n 'dbasis': 2528,\n 'dpump': 710,\n 'dsensor': 2196,\n 'labda': 0.032,\n 'Tsurface': 20+273,\n 'porosity': 0.2, #'porosity': 0.046,\n 'permeability': 9e-10,\n 'rhof': 996.9,\n 'rhos': 2400,\n 'viscosity': 0.0003142,\n 'K': 4e-13,\n 'cpf' : 4183,\n 'cps' : 2650, #870\n 'labdas' : 4.2, # thermal conductivity solid [W/mK]\n 'labdaf': 0.663, # thermal conductivity fluid [W/mK]\n 'saltcontent': 0.155, # [kg/l]\n 'pref': 222.5e5,\n 'Tref': 90 + 273,\n 'g' : 9.81,\n 'rw': 0.1, #0.126\n 'rmax': 1000,\n 'Q': 250 / 3600,\n 'L': 1000,\n 'Tinj': 30 + 273,\n 'patm' : 1e5,\n 'ε' : 1.2, # tubing roughness [m]\n 'ct' : 1e-10, # total compressibility\n\n })\n data['well'] = []\n data['well'].append({\n 'Q': 250/3600,\n })\n\n with open(filename, 'w') as outfile:\n json.dump(data, outfile)\n\n## Using map() and lambda\ndef listOfTuples(l1, l2):\n return list(map(lambda x, y: (x, y), l1, l2))\n\n## Plot the solution on a finite element mesh\ndef plot_solution(sol, outfile, title=None ):\n import plotly.figure_factory as ff\n import plotly.express as px\n\n p_inlet = sol[0]\n T_prod = sol[1]\n\n df = pd.DataFrame(listOfTuples(permeability, porosity), columns=[\"Permeability\", \"Porosity\"])\n\n # fig = px.histogram(df, x=\"Permeability\", y=\"Porosity\",\n # marginal=\"box\", # or violin, rug\n # hover_data=df.columns)\n # fig.show()\n\n # sns.jointplot(x=\"Permeability\", y=\"Porosity\", data=df, kind=\"kde\", n_levels=10);\n #\n # f, ax = plt.subplots(figsize=(6, 6))\n #\n # sns.kdeplot(df.Permeability, df.Porosity, n_levels=10, ax=ax)\n # sns.rugplot(df.Permeability, color=\"g\", ax=ax)\n # sns.rugplot(df.Porosity, vertical=True, ax=ax)\n #\n # df2 = pd.DataFrame(listOfTuples(T_prod, p_inlet), columns=[\"T_prod\", \"p_inlet\"])\n # print(\"df2\", df2)\n #\n # sns.jointplot(x=\"T_prod\", y=\"p_inlet\", data=df2, kind=\"kde\", n_levels=10);\n #\n # f, ax = plt.subplots(figsize=(6, 6))\n #\n # sns.kdeplot(df2.T_prod, df2.p_inlet, n_levels=10, ax=ax)\n # sns.rugplot(df2.T_prod, color=\"g\", ax=ax)\n # sns.rugplot(df2.p_inlet, vertical=True, ax=ax)\n\n\n\n #Plotting\n #plt....\n #plt....\n if title:\n plt.title(title)\n\n #Plot configuration\n # sns.set(color_codes=True)\n\n #Save the figure to the output file\n plt.savefig( outfile )\n plt.show()\n print( 'Output written to {}'.format( outfile ) )\n\ndef show_seaborn_plot( filename, label):\n print('filename', filename)\n with open(filename, 'rb') as file:\n data = np.transpose(np.load(file))\n\n df = pd.DataFrame(data[0:, 0:], columns=['f' + str(i) for i in range(data.shape[1])])\n\n draw_df = df.reset_index().melt(id_vars=['index'], var_name='col')\n\n # pass custom palette:\n sns.set_palette(\"Spectral\")\n ax = sns.lineplot(x='index',\n y='value',\n ci=95,\n #style=True,\n dashes=[(2,2)],\n legend=\"brief\",\n palette=(\"Blues_d\"), #sns.color_palette('Greys')\n hue_norm=mpl.colors.LogNorm(),\n data=draw_df)\n plt.legend([label])\n\ndef show_uniform_plot():\n Qpdf = Q = np.random.uniform(low=0.1, high=1.0, size=50)\n\n fig, ax = plt.subplots(1, 1,\n figsize=(10, 7),\n tight_layout=True)\n\n ax.set(xlabel=r'$Q [m^3/s]$', ylabel='Probability')\n ax.hist(Q, density=True, histtype='stepfilled', alpha=0.2, bins=20)\n plt.show()\n\n# show_seaborn_plot('pnode8.npy', \"node8\")\n# plt.show()\n\ndef show_realdata_plot():\n print('Posterior distributions real data')\n plt.figure(figsize=(8, 2))\n for param in ['TBH', 'TESP']:\n samples = get_welldata(param)\n x = get_welldata('CORRECTED_TIME')/60\n y = samples\n plt.plot(x, y)\n plt.xlabel(\"t [min]\", size=14)\n plt.ylabel(\"T(t) [K]\", size=14)\n plt.axvline(x=10320/60, c='k')\n plt.figure(figsize=(8, 2))\n for param in ['PBH', 'PESP']:\n samples = get_welldata(param)/1e6\n x = get_welldata('CORRECTED_TIME') / 60\n y = samples\n plt.plot(x, y)\n plt.xlabel(\"t [min]\", size=14)\n plt.ylabel(\"p(t) [MPa]\", size=14)\n plt.axvline(x=10320/60, c='k')\n # secay = ax.secondary_yaxis('top', functions=(deg2rad, rad2deg))\n # secax.set_ylabel('angle [rad]')\n plt.show()\n plt.tight_layout();\n\n plt.show()\n\n# for node in range(len(pnodelist)):\n# with open('pnode' + str(node+2) + '.npy', 'wb') as f:\n# np.save(f, pnodelist[node])\n# show_seaborn_plot('pnode' + str(node+2) + '.npy', str(node+2))\n# # plt.legend(str(node+2))\n\n","sub_path":"files/myIOlib.py","file_name":"myIOlib.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"354537257","text":"import printTableFunctions # this imports the other file we've created, printTableFunctions.py\n\n# this is the table we'd like to print that was given in the textbook\ntableData = [\n ['apples', 'oranges', 'cherries', 'banana'],\n ['Alice', 'Bob', 'Carol', 'David'],\n ['dogs', 'cats', 'moose', 'goose']\n ]\n\n#this calls the printTable function within the printTableFunctions program, and passes in the parameters 'tableData' into the function\nprintTableFunctions.printTable( tableData )\n\n# i wanted to test our function with different data, so 'newTable' is a set of new data that is used to test the function later on\nnewTable = [\n # notice the 'split()' methods, refer to the textbook if you'd like to know how that works\n 'your code will first have to'.split(),\n 'find the longest string in each'.split(),\n 'of the inner lists so that'.split(),\n 'the whole column can be wide'.split()\n ]\n\n#this calls the printTable function again, but this time with our newTable as the parameter\nprintTableFunctions.printTable( newTable )","sub_path":"ch6/print-table-runner.py","file_name":"print-table-runner.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"36254961","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'tasks'\n\nurlpatterns = [\n path('get_tasks//', views.get_tasks_for_language, name='get_tasks'),\n path('get_task_details///', views.get_task_details, name='get_task_details'),\n path('send_result_audio///', views.send_result_audio, name='send_result_audio'),\n path('send_result_text///', views.send_result_text, name='send_result_text'),\n path('get_task_results//', views.get_task_results, name='get_task_results'),\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name='logout'),\n path('register/', views.register, name='register'),\n path('user_info/', views.user_info, name=\"user_info\"),\n path('languages/', views.languages, name='languages'),\n path('profile_image_upload/', views.profile_image_upload, name=\"profile_image_upload\")\n]","sub_path":"tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"306916912","text":"#P6 E13 - JOSE MIGUEL RIVAS MENDEZ - DAM - PROGRAMACIÓN\n#Desarrolla de nuevo el ejercicio de la práctica anterior\n#de los números primos, con while. Reflexiona y escribe en\n#el propio programa en forma de comentario, qué opción es mejor y por qué.\n\"\"\"numero=int(input(\"Dame un número: \"))\nresto=1\nfor i in range(numero):\n if ((i!=0)and(i!=1)and(numero%i==0)):\n resto=0\nif (resto==0):\n print(\"El número \",numero,\"no es primo\")\nelse:\n print(\"El número \",numero,\"es primo\")\"\"\"\nnumero=int(input(\"Dame un número: \"))\nresto=1\nmod=1\nwhile(resto!=0):\n mod+=1\n resto=numero%mod\nif (mod==numero):\n print(\"El número\",numero,\"es primo\")\nelse:\n print(\"El número\",numero,\"no es primo\")\n\n#Es mejor utilizar un while porque si el número es muy grande,\n#ya diviendo entre 2 se da cuenta el programa que no es primo, mientras\n#que con un for haría todas las divisiones.\n","sub_path":"P6/P6E13.py","file_name":"P6E13.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"72942353","text":"import requests\nimport json\nimport re\nimport time\nimport random\n\n\nclass People:\n id = \"\",\n name = \"\"\n level = \"\"\n\n def __init__(self, id, name, level):\n self.id = id\n self.name = name\n self.level = str(level)\n\n def getJson(self):\n return {\"id\": self.id, \"name\": self.name, \"symbolSize\": \"10\", \"level\": self.level}\n\n\nclass Link:\n sourceId = \"\",\n targetId = \"\"\n\n def __init__(self, sourceId, targetId):\n self.sourceId = sourceId\n self.targetId = targetId\n\n def getJson(self):\n return {\"source\": self.sourceId, \"target\": self.targetId}\n\n\nclass PreLink:\n sourceName = \"\",\n targetId = \"\"\n\n def __init__(self, sourceName, targetId):\n self.sourceName = sourceName\n self.targetId = targetId\n\n def isSource(self, name):\n return self.sourceName == name\n\n\ndef getMonth(month):\n if month == \"Apr\":\n return \"4\"\n else:\n if month == \"Mar\":\n return \"3\"\n else:\n print(month)\n return \"2\"\n\n\ndef getIdByName(name, headers):\n if name == \"\":\n print(\"name error\")\n return \"-1\"\n else:\n try:\n url = 'https://m.weibo.cn/n/{}'.format(name)\n response = requests.head(url).headers\n return response['location'].replace('/u/', '')\n except:\n url = 'https://m.weibo.cn/api/container/getIndex'\n params = {\n 'containerid': '100103type=3&q={}'.format(name),\n 'page_type': 'searchall'\n }\n response = requests.get(url, headers=random.choice(headers), params=params)\n print(response.text)\n while response.status_code != 200:\n time.sleep(3*60)\n response = requests.get(url, headers=random.choice(headers), params=params)\n response_json = json.loads(response.text)\n times = 0\n while response_json['ok'] != 1:\n times += 1\n if times > 1:\n break\n time.sleep(3 * 60)\n response = requests.get(url, headers=random.choice(headers), params=params)\n print(response.text)\n response_json = json.loads(response.text)\n if times > 1:\n return name\n id = response_json['data']['cards'][1]['card_group'][0]['user']['id']\n return str(id)\n\n\ndef getOnePage(response_json, peopleList, links, newsid, preLinks, levelList, peopleIdList, repostTime_dict):\n datas = response_json['data']['data']\n repeat = 0\n for data in datas:\n id = str(data['user']['id'])\n if id not in peopleIdList:\n repostTime_date = data['created_at']\n repostTime_dates = repostTime_date.split(\" \")\n repostYear = repostTime_dates[5]\n repostMonth = getMonth(repostTime_dates[1])\n repostDay = repostTime_dates[2]\n repostDate = \"{}年{}月{}日\".format(repostYear, repostMonth, repostDay)\n print(repostDate)\n peopleIdList.append(id)\n name = data['user']['screen_name']\n content = data['raw_text']\n print(data['raw_text'])\n for preLink in preLinks:\n if preLink.isSource(name):\n link = Link(id, preLink.targetId)\n links.append(link)\n preLinks.remove(preLink)\n content = content.replace(\":\", \":\")\n items = re.findall('//@(.*?):', content)\n if items:\n if len(items) > 5:\n continue\n if repostDate in repostTime_dict.keys():\n repostTime_dict[repostDate] += 1\n print(repostTime_dict[repostDate])\n else:\n repostTime_dict[repostDate] = 1\n print(\"新添加主键:{}\".format(repostDate))\n levelList[len(items)] = str(int(levelList[len(items)]) + 1)\n print(\"该用户等级为\" + str(len(items) + 1))\n item = items[0]\n print(items)\n preLinks.append(PreLink(item, id))\n people = People(id, name, len(items)+1)\n else:\n links.append(Link(str(newsid), id))\n levelList[0] = str(int(levelList[0]) + 1)\n print(\"该用户等级为1\")\n if repostDate in repostTime_dict.keys():\n repostTime_dict[repostDate] += 1\n else:\n repostTime_dict[repostDate] = 1\n people = People(id, name, 1)\n peopleList.append(people)\n else:\n repeat += 1\n if repeat == len(datas):\n return False\n else:\n return True\n\n\ndef getOneNew(weibo_id, name, peopleList, links, newsid, news, levelList, peopleIdList, repostTime_dict):\n url = 'https://m.weibo.cn/api/statuses/repostTimeline?id={}&page=1'.format(weibo_id)\n headers = [{\n 'Cookie': '_ALF=1619262243; SCF=AvS6HupuL_1KkWxlafVcVyhPIZaKxVangJBjtREdcgAY98g1joNY2swIl9kLiAo5-zI2ASFjCWqgIRLQSsv6G6g.; SUB=_2A25NWB5zDeRhGeBI6loT8i3JzjqIHXVuoqI7rDV6PUJbktAfLWbzkW1NRot20TO5flZgAj7zP-QE9XwazxZCo31m; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WheurEb4cKqvylaRF0NMCmz5JpX5K-hUgL.FoqceKnEeoefSKq2dJLoI7RLxKnLB.qLBoM4ShM4e5tt; _T_WM=19725237635; XSRF-TOKEN=b4c3bf; WEIBOCN_FROM=1110006030; MLOGIN=1; M_WEIBOCN_PARAMS=luicode%3D10000011%26lfid%3D231522type%253D1%2526t%253D10%2526q%253D%2523%25E6%2596%25B0%25E5%2586%25A0%25E7%2597%2585%25E6%25AF%2592%25E7%2596%25AB%25E8%258B%2597%25E5%2585%25A8%25E6%25B0%2591%25E5%2585%258D%25E8%25B4%25B9%2523%26uicode%3D20000061%26fid%3D4588175568407059%26oid%3D4588175568407059',\n 'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64;rv: 86.0) Gecko / 20100101Firefox / 86.0'\n },\n {\n 'Cookie': 'ALF=1619892355; SCF=AvS6HupuL_1KkWxlafVcVyhPIZaKxVangJBjtREdcgAYeJh7yvZ_pH_j9WuN4KYNdG87Bruc4OM8Y-BvbQO6foY.; _T_WM=80943054270; SUB=_2A25NYnvTDeRhGeBI6loT8i3JzjqIHXVurQWbrDV6PUJbktAKLVrZkW1NRot20RT5Hy1aMc_Uvg5hVAlPDOfknaTl; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WheurEb4cKqvylaRF0NMCmz5JpX5K-hUgL.FoqceKnEeoefSKq2dJLoI7RLxKnLB.qLBoM4ShM4e5tt; XSRF-TOKEN=0867fa; WEIBOCN_FROM=1110006030; MLOGIN=1; M_WEIBOCN_PARAMS=luicode%3D10000011%26lfid%3D100103type%253D1%2526q%253D%25E6%2596%25B0%25E5%2586%25A0%25E7%2597%2585%25E6%25AF%2592',\n 'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64;rv: 86.0) Gecko / 20100101Firefox / 86.0'\n },\n {\n 'Cookie': '_T_WM=51445041497; WEIBOCN_FROM=1110006030; XSRF-TOKEN=91e8c6; loginScene=102003; SUB=_2A25NYgq1DeRhGeFL41YX-SjFyjmIHXVurJb9rDV6PUJbktAfLWvmkW1NfY0erHDa4_j2145zQOi2WiFiivFmFXHw; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5LgfZD7w4Azw1IZam6GTM15JpX5KzhUgL.FoMf1hBc1Kq4eK-2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMNSKnXSo.c1K2f; SSOLoginState=1617328869; MLOGIN=1; M_WEIBOCN_PARAMS=oid%3D4620459935269257%26luicode%3D10000011%26lfid%3D100103type%253D1%2526q%253D%25E6%2596%25B0%25E5%2586%25A0%25E7%2597%2585%25E6%25AF%2592; BAIDU_SSP_lcr=https://login.sina.com.cn/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'\n }]\n preLinks = []\n response = requests.get(url, headers=random.choice(headers))\n response_json = json.loads(response.text)\n while response_json['ok'] != 1:\n print(\"出错了\")\n print(response_json)\n time.sleep(3 * 60)\n response = requests.get(url, headers=random.choice(headers))\n response_json = json.loads(response.text)\n max = response_json['data']['max']\n print(max)\n getOnePage(response_json, peopleList, links, newsid, preLinks, levelList, peopleIdList, repostTime_dict)\n i = 2\n while i < max + 1:\n try:\n url = 'https://m.weibo.cn/api/statuses/repostTimeline?id={}&page={}'.format(weibo_id, i)\n response = requests.get(url, headers=random.choice(headers))\n if response.status_code != 200:\n time.sleep(3 * 60)\n i -= 1\n continue\n response_json = json.loads(response.text)\n # print(response_json)\n max = response_json['data']['max']\n if getOnePage(response_json, peopleList, links, newsid, preLinks, levelList, peopleIdList, repostTime_dict):\n print(\"共{}页\".format(max))\n print(\"第{}页爬取完成\".format(i))\n else:\n print(\"后面均已爬取\")\n break\n except:\n print(response_json)\n print(\"有一个页面出现错误:第{}页\".format(i))\n i += 1\n time.sleep(3)\n nonPeople = []\n nonPeopleId = []\n print(len(preLinks))\n for preLink in preLinks:\n print(preLink.sourceName)\n print(preLink.targetId)\n if preLink.sourceName not in nonPeople:\n print(preLink.sourceName)\n print(nonPeople)\n j = getIdByName(preLink.sourceName, headers)\n print(j)\n nonPeopleId.append(j)\n nonPeople.append(preLink.sourceName)\n if j not in peopleIdList:\n print(\"新出现的人\")\n peopleIdList.append(j)\n people = People(j, preLink.sourceName, 1)\n peopleList.append(people)\n levelList[0] = str(int(levelList[0]) + 1)\n links.append(Link(str(newsid), j))\n else:\n j = nonPeopleId[nonPeople.index(preLink.sourceName)]\n print(j)\n links.append(Link(j, preLink.targetId))\n print(len(preLinks))\n news.append({\"name\": name, \"url\": \"https://m.weibo.cn/detail/{}\".format(weibo_id)})\n return True\n\n\ndef getPreData(repostTime_dict, levelList):\n level_f = open(\"level.json\", \"r+\", encoding=\"utf-8\")\n level_content = level_f.read()\n if not level_content == \"\":\n level_json = json.loads(level_content)\n levelList[0] = level_json['1']\n levelList[1] = level_json['2']\n levelList[2] = level_json['3']\n levelList[3] = level_json['4']\n levelList[4] = level_json['5']\n levelList[5] = level_json['6']\n level_f.close()\n startDate_f = open(\"repostSum.json\", \"r+\", encoding=\"utf-8\")\n startDate = startDate_f.read()\n if not startDate == \"\":\n startDate_json = json.loads(startDate)\n startDate_time = startDate_json['Date']\n startDate_sum = startDate_json['data']\n for i in range(0, len(startDate_time)):\n repostTime_dict[startDate_time[i]] = startDate_sum[i]\n startDate_f.close()\n\n\ndef getOnePreDate(peopleList, links, peopleIdList, newsId):\n peopleList.clear()\n links.clear()\n peopleIdList.clear()\n id_f = open(\"newsSpread{}.json\".format(newsId), \"r+\", encoding=\"utf-8\")\n newsSpread = id_f.read()\n if not newsSpread == \"\":\n newsSpread_json = json.loads(newsSpread)\n nodes = newsSpread_json['nodes']\n for node in nodes:\n one_id = node['id']\n one_name = node['name']\n one_level = node['level']\n peopleIdList.append(one_id)\n peopleList.append(People(one_id, one_name, one_level))\n startLinks = newsSpread_json['links']\n for startLink in startLinks:\n links.append(Link(startLink['source'], startLink['target']))\n id_f.close()\n\n\ndef writeToFile(levels, repost_dict):\n level_Json = {\n \"1\": str(levels[0]),\n \"2\": str(levels[1]),\n \"3\": str(levels[2]),\n \"4\": str(levels[3]),\n \"5\": str(levels[4]),\n \"6\": str(levels[5])\n }\n level_f = open('level.json', 'w+', encoding='utf-8')\n level_f.write(json.dumps(level_Json, ensure_ascii=False))\n level_f.close()\n repostDate_f = open('repostSum.json', 'w+', encoding='utf-8')\n keys = []\n values = []\n for key in repost_dict:\n keys.append(str(key))\n values.append(repost_dict[key])\n repostDate = {\n \"Date\": keys,\n \"data\": values\n }\n repostDate_f.write(json.dumps(repostDate, ensure_ascii=False))\n repostDate_f.close()\n\n\ndef writeOneToFile(peopleList, links, newsId):\n peopleJsonList = []\n linkJsonList = []\n for people in peopleList:\n peopleJsonList.append(people.getJson())\n for link in links:\n linkJsonList.append(link.getJson())\n total_json = {\n \"nodes\": peopleJsonList,\n \"links\": linkJsonList\n }\n f = open('newsSpread{}.json'.format(newsId), 'w+', encoding='utf-8')\n f.write(json.dumps(total_json, ensure_ascii=False))\n f.close()\n\n\nif __name__ == '__main__':\n weiboList = [\n {\n \"id\": 4620578218577363,\n \"name\": \"华南海鲜市场不是新冠疫情最初来源\"\n },\n {\n \"id\": 4620219815037861,\n \"name\": \"李梓萌不由自主把打疫苗标语唱了出来\"\n },\n {\n \"id\": 4621235869452542,\n \"name\": \"建议60岁及以上人群接种新冠疫苗\"\n },\n {\n \"id\": 4621074911988625,\n \"name\": \"为什么应尽快接种新冠疫苗\"\n },\n {\n \"id\": 4620749769540859,\n \"name\": \"哪些人不能打新冠疫苗\"\n }\n ]\n repostTime_dict = {}\n peopleList = []\n links = []\n news = []\n peopleIdList = []\n levelList = [0, 0, 0, 0, 0, 0]\n getPreData(repostTime_dict, levelList)\n newsid = 0\n for weibo in weiboList:\n print(weiboList.index(weibo))\n getOnePreDate(peopleList, links, peopleIdList, newsid)\n getOneNew(weibo['id'], weibo['name'], peopleList, links, newsid, news, levelList, peopleIdList, repostTime_dict)\n writeOneToFile(peopleList, links, newsid)\n newsid += 1\n print(repostTime_dict)\n writeToFile(levelList, repostTime_dict)\n","sub_path":"微博/repost.py","file_name":"repost.py","file_ext":"py","file_size_in_byte":13890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"112639609","text":"#!/usr/bin/env python3.7\n\n# module(s)\nimport sys\nfrom itertools import chain, combinations, product\nfrom parseJFLAP import *\n\n# algorithm defined in more-itertools\ndef powerSet(mainSet):\n s = list(mainSet)\n return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\ndef buildState(mainTuple):\n sortedTuple = sorted(mainTuple)\n state = str()\n\n for member in sortedTuple:\n state = state + member\n\n return state\n\ndef computeStates(nfa):\n states = list(powerSet(nfa.states))\n return states\n\n result = set()\n\n for member in states:\n tempState = tuple()\n\n for tupleMember in member:\n tempState = tempState + (tupleMember, )\n\n result.add(buildState(tempState))\n\n print(result)\n return result\n\ndef computeStateTransition(stateTuple, dfaTransitions, alphabet):\n newTrans = dict()\n\n for symbol in alphabet:\n destination = tuple()\n\n for member in stateTuple:\n # iterate through states in state set\n for state, stateTrans in dfaTransitions.items():\n if member == state:\n if symbol in stateTrans:\n for element in stateTrans[symbol]:\n if element not in destination:\n destination = destination + (element, )\n\n newTrans[symbol] = destination\n\n return newTrans\n\ndef computeTransitions(nfa, states):\n dfaTransitions = dict()\n transitions = nfa.transitions\n\n # initialize transition\n for state in states:\n dfaTransitions[state] = dict()\n\n # build from previous states\n for state, stateTrans in transitions.items():\n newTrans = dict()\n\n if stateTrans:\n # dictionary not empty\n for symbol, symbolTrans in stateTrans.items():\n toState = tuple()\n\n for symbolState in symbolTrans:\n toState = toState + (symbolState, )\n\n # symbol built\n newTrans[symbol] = toState\n\n dfaTransitions[state] = newTrans\n\n # build from new states\n for stateTuple, stateTrans in dfaTransitions.items():\n if isinstance(stateTuple, tuple):\n newTrans = computeStateTransition(stateTuple, dfaTransitions, nfa.input_symbols)\n\n # add new transitions to state\n if dfaTransitions[stateTuple]:\n # dictionary is not empty\n dfaTransitions[stateTuple].update(newTrans)\n else:\n dfaTransitions[stateTuple] = newTrans\n\n return dfaTransitions\n\ndef computeFinalStates(nfa, dfaStates):\n finals = set()\n\n # add base final states\n for state in nfa.final_states:\n finals.add(state)\n\n for state in nfa.final_states:\n for dfaState in dfaStates:\n if state in dfaState:\n finals.add(buildState(dfaState))\n\n return finals\n\ndef NFAtoDFA(nfa):\n dfaStates = list()\n dfaSymbols = set()\n dfaTransitions = dict()\n\n # build the set of states\n dfaStates = computeStates(nfa)\n\n # set the symbols\n dfaSymbols = nfa.input_symbols\n\n # set transitions\n dfaTransitions = computeTransitions(nfa, dfaStates)\n\n # set initial state\n dfaInitialState = nfa.initial_state\n\n # set final state\n dfaFinalStates = computeFinalStates(nfa, dfaStates)\n\n # format states\n formatStates = set()\n for member in dfaStates:\n formatStates.add(buildState(member))\n\n formatTransitions = dict()\n\n # initialize keys\n for state, stateTrans in dfaTransitions.items():\n if isinstance(state, tuple):\n tempTrans = dict()\n for symbol, symbolTrans in stateTrans.items():\n tempTrans[symbol] = buildState(symbolTrans)\n\n if isinstance(state, tuple):\n formatTransitions[buildState(state)] = tempTrans\n\n # build DFA\n dfa = DFA(\n states = formatStates,\n input_symbols = dfaSymbols,\n transitions = formatTransitions,\n initial_state = dfaInitialState,\n final_states = dfaFinalStates\n )\n\n return dfa\n\ndef to_complement(dfa):\n accepted = set()\n rejected = set()\n\n # build accepted states set\n for state in dfa.final_states:\n accepted.add(state)\n\n # build rejected state set\n for state in dfa.states:\n if state not in dfa.final_states:\n rejected.add(state)\n\n # build complement DFA\n comp_dfa = DFA(\n states = dfa.states,\n input_symbols = dfa.input_symbols,\n transitions = dfa.transitions,\n initial_state = dfa.initial_state,\n final_states = rejected\n )\n\n return comp_dfa\n\ndef remove_braces(string):\n result = str()\n\n for character in string:\n if character != '{' and character != '}':\n result = result + character\n\n return \"{\" + result + \"}\"\n\ndef cross_states(spc_states, sys_states):\n states = list()\n\n for state in product(spc_states, sys_states):\n if state not in states:\n states.append(state)\n\n # remove repeating sets\n size = len(states)\n for i in range(0, size):\n for j in range(i, size):\n if i != j and set(states[i]).issubset(states[j]):\n states.remove(states[i])\n size = size - 1\n break # break second for loop (nested)\n\n # add deadlock state\n states.append((\"{}\", \"{}\"))\n\n # build set\n result = set()\n for state in states:\n # build string\n temp = str()\n\n for member in state:\n temp = temp + member\n\n # add string to set\n result.add(temp)\n\n return result\n\ndef cross_transitions(spc_trans, sys_trans, states):\n transitions = dict()\n\n # build base dictionary\n for state in states:\n transitions.update({state: None})\n\n # build transitions\n for spc_key, spc_val in spc_trans.items():\n for spc_val_key, spc_val_val in spc_val.items():\n for sys_key, sys_val in sys_trans.items():\n temp_trans = dict()\n for sys_val_key, sys_val_val in sys_val.items():\n if spc_val_key == sys_val_key:\n temp_trans[spc_val_key] = spc_val_val + sys_val_val\n\n # add transition functions to state\n if transitions[spc_key + sys_key] != None:\n transitions[spc_key + sys_key] = {**(transitions[spc_key + sys_key]), **temp_trans}\n else:\n transitions[spc_key + sys_key] = temp_trans\n\n return transitions\n\ndef cross_finals(spc_finals, sys_finals):\n finals = set()\n\n for spc_state in spc_finals:\n for sys_state in sys_finals:\n finals.add(spc_state + sys_state)\n\n return finals\n\ndef to_intersection(spc_dfa, sys_dfa):\n # build cartesian product of states\n inter_states = cross_states(spc_dfa.states, sys_dfa.states)\n\n # build transitions\n inter_transitions = cross_transitions(spc_dfa.transitions, sys_dfa.transitions, inter_states)\n\n # set initial state\n inter_initial = spc_dfa.initial_state + sys_dfa.initial_state\n\n # set final states\n inter_finals = cross_finals(spc_dfa.final_states, sys_dfa.final_states)\n\n # build intersection DFA\n inter_dfa = DFA(\n states = inter_states,\n input_symbols = spc_dfa.input_symbols,\n transitions = inter_transitions,\n initial_state = inter_initial,\n final_states = inter_finals\n )\n\n return inter_dfa\n\ndef convert_graph(comp):\n graph = dict()\n\n # build base state(s)\n for state in comp.transitions:\n graph.update({state: list()})\n\n # add transition state(s)\n for state in graph:\n for key, value in comp.transitions.items():\n if(state == key):\n for curr_key, curr_val in value.items():\n graph[state].append({curr_key: curr_val})\n\n return graph\n\n\n# find_path method implementation used from\n# https://www.python.org/doc/essays/graphs/\n# with some variation\n\ndef find_path(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return path\n if not start in graph:\n return None\n for trans, node in graph[start].items():\n if node not in path:\n newpath = find_path(graph, node, end, path)\n if newpath:\n return newpath\n\n return None\n\ndef path_to_string(path, dfa):\n string = \"\"\n\n if len(path) > 1:\n for i in range(len(path) - 1):\n state = path[i]\n transitions = dfa.transitions[state]\n\n for symbol in transitions:\n if transitions[symbol] == path[i + 1]:\n string = string + symbol\n else:\n string = \"EPS\"\n\n return string\n\ndef write_DFA(dfa, filename):\n with open(filename, \"w\") as f:\n f.write(\"% Input alphabet\\n\")\n\n for symbol in dfa.input_symbols:\n f.write(symbol + '\\n')\n\n f.write(\"% Intersectional Language\\n\")\n\n f.write(\"% Transition function\\n\")\n for state, transitions in dfa.transitions.items():\n for symbol, toState in transitions.items():\n f.write(state + \" \" + symbol + \" \" + toState + \"\\n\")\n\n f.write(\"% Initial state\\n\")\n f.write(dfa.initial_state + '\\n')\n\n f.write(\"% Final states\\n\")\n for state in dfa.final_states:\n f.write(state + '\\n')\n\ndef rename_deadlocks(dfa):\n replacement = \"{}\"\n\n if \"\" in dfa.states:\n dfa.states.add(replacement)\n dfa.states.remove(\"\")\n\n for state, transitions in dfa.transitions.items():\n for symbol in transitions:\n if transitions[symbol] == \"\":\n transitions[symbol] = replacement\n\n if \"\" in dfa.transitions.keys():\n dfa.transitions[replacement] = dfa.transitions.pop(\"\")\n\ndef is_subset(spec, sys):\n # find the complement of the first automaton\n comp_automaton = to_complement(spec)\n\n # find the intersection of the complement and system automaton\n inter_automaton = to_intersection(comp_automaton, sys)\n\n # convert transitions to graph\n inter_graph = convert_graph(inter_automaton)\n\n # find shortest path to accepting state\n for final_state in inter_automaton.final_states:\n path = find_path(inter_automaton.transitions, inter_automaton.initial_state, final_state)\n\n if(path != None):\n break;\n\n if path != None:\n result = path_to_string(path, inter_automaton)\n else:\n result = None\n\n return result\n\ndef main(args):\n # read the arguments\n if(len(args) > 2):\n specAutomata = args[1]\n systemAutomata = args[2]\n\n spc_nfa = parseFA(specAutomata, 'q')\n sys_nfa = parseFA(systemAutomata, 's')\n\n # convert specification automaton to DFA\n spc_dfa = NFAtoDFA(spc_nfa)\n sys_dfa = NFAtoDFA(sys_nfa)\n\n # rename deadlock state\n rename_deadlocks(spc_dfa)\n rename_deadlocks(sys_dfa)\n\n sys_result = is_subset(spc_dfa, sys_dfa)\n spc_result = is_subset(sys_dfa, spc_dfa)\n\n if sys_result == None and spc_result == None:\n print(\"PASS\" + \";\" + \"None\" + \";\" \"None\", end='')\n elif sys_result == None and spc_result != None:\n print(\"FAIL\" + \";\" + spc_result + \";\" + \"None\", end='')\n elif sys_result != None and spc_result == None:\n print(\"FAIL\" + \";\" + \"None\" + \";\" + sys_result, end='')\n elif sys_result != None and spc_result != None:\n print(\"FAIL\" + \";\" + spc_result + \";\" + sys_result, end='');\n else:\n print(\"FAIL\" + \";\" + \"None\" + \";\" + \"None\", end='')\n\nmain(sys.argv)\n","sub_path":"scripts/compareFA.py","file_name":"compareFA.py","file_ext":"py","file_size_in_byte":11664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"391585243","text":"\"\"\"\n\nFunctions to pull features for a small set\nof images.\n\n\n\"\"\"\n\nimport db_core_functions as db\nimport sys\nsys.path.insert(0, '/home/sam/thesisOutput/')\nfrom utility import clean_phash\n\n\ndef load_extraction_table(pHashes):\n \"\"\"Load a list of pHashes to temp table.\"\"\"\n\n pHashDics = [{'bigint0' : pHash} for pHash in pHashes]\n db.load_dictionaries(pHashDics, 'utility$extraction_ids', truncate = True)\n\n\ndef pull_image_features(pHashes, featureTable):\n \"\"\"\n Return features of images in pHashes list from featureTable.\n\n \"\"\"\n\n pHashSet = {clean_phash(x) for x in pHashes}\n load_extraction_table(pHashSet)\n\n queryString = \"SELECT t0.* FROM %s t0 JOIN utility$extraction_ids t1 \"\\\n \"ON t0.phash = t1.bigint0;\" % featureTable\n\n return db.query(queryString)\n\ndef pull_image_features_by_mod(modSize, remainderValue, featureTable):\n \"\"\"Pull image features for a swath of phashes.\"\"\"\n\n queryString = \"SELECT * FROM {0} WHERE abs(phash)%{1!s} = {2!s};\".format(featureTable, modSize, remainderValue)\n\n return db.query(queryString)\n\n \n","sub_path":"postgres/image_feature_retrieval.py","file_name":"image_feature_retrieval.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"613711793","text":"\n\nclass Parameter:\n \"\"\" Stores parameter info for assemble\n\n Parameters\n ----------\n name : str\n Name of the part\n param : str\n Name of the field\n index : int\n Index of the field.\n\n Attributes\n ----------\n name : str\n Name of the part\n param : str\n Name of the field\n index : int, optional\n Index of the field (the default is None)\n\n \"\"\"\n def __init__(self, name, param, index=None):\n self.name = name\n self.param = param\n self.index = index\n\n def to_list(self):\n \"\"\" Returns the parameter info as a list\n\n Returns\n -------\n lst\n List containing name and param, and index if valid\n\n \"\"\"\n lst = [self.name, self.param]\n if self.index is not None:\n lst.append(self.index)\n return lst\n\n def __str__(self):\n s = \"Parameter: {0}:{1}\".format(self.name, self.param)\n if self.index is not None:\n s += \":\" + str(self.index)\n return s\n\n\ndef get_external(external):\n \"\"\" Constructs a Parameter object from a list\n\n Parameters\n ----------\n external : list\n List containing name, param, and index (optional)\n\n Returns\n -------\n Parameter\n\n \"\"\"\n return Parameter(*external)\n\n\ndef get_internal(internal):\n \"\"\" Constructs Parameter objects from internal list\n\n This function constructs a source and a destination from a list.\n\n Parameters\n ----------\n internal : list\n List containing source name, source param name, source index (optional),\n destination name, destination param name, destination index (optional)\n\n Returns\n -------\n Parameter, Parameter\n Source and destination Parameter objects\n\n \"\"\"\n source_index = None\n des_index = None\n\n # No indices\n if len(internal) == 4:\n source, source_param, des, des_param = internal\n elif len(internal) == 5:\n\n # Source index\n if isinstance(internal[2], int):\n source, source_param, source_index, des, des_param = internal\n\n # Destination index\n else:\n source, source_param, des, des_param, des_index = internal\n else:\n source, source_param, source_index, des, des_param, des_index = internal\n\n return Parameter(source, source_param, source_index), Parameter(\n des, des_param, des_index)\n\n\ndef make_internal(source, des):\n \"\"\" Creates list from source and destination Parameter objects\n\n Parameters\n ----------\n source : Parameter\n Parameter object for source\n des : Parameter\n Parameter object for destination\n \n Returns\n -------\n list\n List for connection, parameter for get_internal\n\n See Also\n --------\n get_internal\n\n \"\"\"\n internal = source.to_list() + des.to_list()\n return internal\n","sub_path":"IoTPy/tools/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"585484554","text":"from datetime import datetime\nfrom typing import Union, Generator, List\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.base import Engine\nfrom sqlalchemy.sql import text\n\nfrom . import queries\nfrom .config import DBConfig as config\n\n\ndef create_alchemy_engine() -> Engine:\n \"\"\"\n Creates an sqlalchemy engine.\n :return: The sqlalchemy engine.\n \"\"\"\n return create_engine(config.DATABASE_URL)\n\n\ndef fetch_records(engine: Engine, query: Union[text, str], values: dict = {}) -> Generator:\n \"\"\"\n Executes sql query and yields rows.\n :param engine: The sqlalchemy engine.\n :param query: The sql query to execute.\n :param values: The values to inject.\n :return: The rows of the results.\n \"\"\"\n for row in engine.execute(query, values):\n yield dict(row)\n\n\ndef calculate_ocr(engine: Engine, start_date: datetime, end_date: datetime, interval: str) -> List[dict]:\n \"\"\"\n Executes OCR query for a given date range and interval.\n :param engine: The sqlalchemy engine.\n :param start_date: Specifies the start date of the report.\n :param end_date: Specifies the end date of the report.\n :param interval: Specifies the breakdown time interval e.g. hour, day, month, year.\n :return: Report results.\n \"\"\"\n\n start_unix_timestamp = int(datetime.timestamp(start_date))\n end_unix_timestamp = int(datetime.timestamp(end_date))\n\n records = fetch_records(\n engine=engine,\n query=text(queries.OCR_QUERY),\n values={\n 'since': start_unix_timestamp,\n 'until': end_unix_timestamp,\n 'interval': config.INTERVAL_MAPPING[interval]['format']\n }\n )\n return list(records)\n\n\ndef calculate_ocr_breakdown(engine: Engine, start_date: datetime, end_date: datetime, interval: str) -> List[dict]:\n \"\"\"\n Executes OCR Breakdown query for a given date range and interval.\n :param engine: The sqlalchemy engine.\n :param start_date: Specifies the start date of the report.\n :param end_date: Specifies the end date of the report.\n :param interval: Specifies the breakdown time interval e.g. hour, day, month, year.\n :return: Report results.\n \"\"\"\n start_unix_timestamp = int(datetime.timestamp(start_date))\n end_unix_timestamp = int(datetime.timestamp(end_date))\n\n records = fetch_records(\n engine=engine,\n query=text(queries.OCR_BREAKDOWN_QUERY),\n values={\n 'since': start_unix_timestamp,\n 'until': end_unix_timestamp,\n 'interval': config.INTERVAL_MAPPING[interval]['format']\n }\n )\n return list(records)\n\n\ndef fetch_visitor_sessions(engine: Engine, visitor_id: str) -> List[dict]:\n \"\"\"\n Fetches the list of session for a given visitor.\n :param engine: The sqlalchemy engine.\n :param visitor_id: The ID for a specific visitor.\n :return: the visitor sessions\n \"\"\"\n records = fetch_records(\n engine=engine,\n query=text(queries.FETCH_VISITOR_SESSIONS),\n values={\n 'visitor_id': visitor_id\n }\n )\n return list(records)\n","sub_path":"efood/db/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"185162406","text":"from django import forms\nfrom .models import Tickets\n\nclass ContactForm(forms.Form):\n name = forms.CharField()\n course = forms.ChoiceField(choices=[('121', '121'), ('other', 'Other')])\n\n\nclass TicketsForm(forms.ModelForm):\n\n class Meta:\n model = Tickets\n fields = ('name','course','question')\n","sub_path":"ptcticket/tickets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"259018885","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 20 23:51:06 2021\n\n@author: anahi\n\"\"\"\n\nimport numpy as np\nimport math \nimport matplotlib.pyplot as plt\nimport tkinter as tk \nimport pandas as pd\n\nventana= tk.Tk()\nventana.title(\"Calculo de voltaje y potencial\")\nventana.geometry('700x400')\nventana.configure(background='blue')\nvar=tk.StringVar()\n\n\ngs =tk.Label(ventana,text=\"GRADIENTE SALINO\",\n bg=\"red\",fg=\"yellow\")\ngs.place(x=10,y=10, width=690, height=50)\n\nNm =tk.Label(ventana,text=\"Ingrese el número de membranas pares:\",bg=\"black\",fg=\"white\")\nNm.place(x=25,y=70, width=300, height=30)\nentrada1=tk.Entry(ventana)\nentrada1.place(x=80,y=105, width=200, height=30)\n\nAri =tk.Label(ventana,text=\"Ingrese el area de las membranas (m^2):\",bg=\"black\",fg=\"white\")\nAri.place(x=380,y=70, width=300, height=30)\nentrada2=tk.Entry(ventana)\nentrada2.place(x=430,y=105, width=200, height=30)\n\nConc =tk.Label(ventana,text=\"Ingrese la concentración concentrada:\",bg=\"black\",fg=\"white\")\nConc.place(x=25,y=145, width=300, height=30)\nentrada3=tk.Entry(ventana)\nentrada3.place(x=80,y=180, width=200, height=30)\n\nCond =tk.Label(ventana,text=\"Ingrese la concentración diluida:\",bg=\"black\",fg=\"white\")\nCond.place(x=380,y=145, width=300, height=30)\nentrada4=tk.Entry(ventana)\nentrada4.place(x=430,y=180, width=200, height=30)\n\n#DATOS DE LAS MEMBRANAS\nPcem = float(0.99)\nPaem = float(0.95)\nRaem = float(0.017)\nRcem = float(0.02)\nT = float(25+273.15) #temperatura en grados Kelvin\nR = float(8.314) #Constante universal de los gases J/molK\nCF = float(96485.3365) #Constante de Faraday C/mol\nz = float(1**2) #valencia\nEs = float(0.0003) # Espaciamiento de membranas \nRe =np.array([92,47,22,10,6.8,5.6,4.7,3.3,2.2,1.8,1.2,0.56,0.39,0.22,0.1,0])\n\n\n# coeficiente de actividad \nANa = 450 #radio de efectividad del ion hidratado \nACl = 300\n\ndef Ecell():\n \n Ai = float(entrada2.get())\n Cc = float(entrada3.get())\n Cd = float(entrada4.get())\n N = int(entrada1.get())\n \n Ccm=Cc/58.44 #g/mol\n Cdm=Cd/58.44\n gnac = math.exp((-0.5*z*math.sqrt(Ccm))/(1+(ANa/305)*math.sqrt(Ccm)))\n gnad = math.exp((-0.5*z*math.sqrt(Cdm))/(1+(ANa/305)*math.sqrt(Cdm)))\n gclc = math.exp((-0.5*z*math.sqrt(Ccm))/(1+(ACl/305)*math.sqrt(Ccm)))\n gcld = math.exp((-0.5*z*math.sqrt(Cdm))/(1+(ACl/305)*math.sqrt(Cdm)))\n\n acem = math.log((gnac*Ccm)/(gnad*Cdm))\n aaem = math.log((gclc*Ccm)/(gcld*Cdm))\n \n#Calculo de la resistencia \n\n fo = 1.8\n \n Rl = fo*(1/0.7)*(Es/Ai)\n Rh = fo*(1/5)*(Es/Ai)\n r = Raem+Rcem+Rh+Rl\n Rel = 0.54\n Ri = N*r+Rel\n \n #calculo de voltaje \n Ecem = Pcem*((R*T)/(z*CF))*acem\n Eaem = Paem*((R*T)/(z*CF))*aaem\n Ecell = N*(Ecem+Eaem)\n\n# intensidad \n i = Ri+Re\n I = Ecell/i #corriente electrica \n\n#Potencia \n Pgross = (I**2)*Re\n Pd = Pgross/(N*Ai)\n#Voltaje \n Ec = Pgross/I\n \n df = pd.DataFrame({'Ri (ohms)': Ri,'Re (ohms)':Re,'Potencia (W)':Pgross,\n 'DPotencia (W/m^2)':Pd,'CE (A)':I,'Voltaje (V)':Ec})\n\n#Graficas\n fig = plt.figure(figsize=(15,15))\n fig.tight_layout()\n ax1 = fig.add_subplot(1,3,1)\n ax2 = fig.add_subplot(1,3,2)\n ax3 = fig.add_subplot(1,3,3)\n ax1.plot(I,Pgross,'ro')\n ax2.plot(I,Ec,marker='*')\n ax3.plot(I,Pd,'g+')\n ax1.set_xlabel('Intensidad')\n ax1.set_ylabel('Potencia')\n ax2.set_xlabel('Intensidad')\n ax2.set_ylabel('Voltaje')\n ax3.set_xlabel('Intensidad')\n ax3.set_ylabel('potencia/Área')\n ax1.set_title('Potencial maximo')\n ax2.set_title('Intensidad vs Voltaje')\n ax1.grid()\n ax2.grid()\n ax3.grid()\n\n plt.show()\n \n return var.set(Ecell)\n\ndef cerrar ():\n ventana.destroy() \n \nbotonaceptar=tk.Button(ventana, text=\"Aceptar\",fg=\"red\",bg=\"yellow\",command=Ecell)\nbotonaceptar.place(x=310,y=220, width=80, height=30)\n\nEcellf=tk.Label(ventana,text=\"Voltaje máxima:\",bg=\"dark turquoise\",fg=\"black\")\nEcellf.place(x=100,y=260, width=500, height=30)\nEf=tk.Label(ventana,bg=\"white\",textvariable=var)\nEf.place(x=200,y=300, width=300, height=30)\n\nbotoncierra=tk.Button(ventana,text=\"Cerrar\",fg=\"red\",bg=\"yellow\",command=cerrar)\nbotoncierra.place(x=310,y=340, width=80, height=30)\n\nventana.mainloop() ","sub_path":"Codigo_GS_C.py","file_name":"Codigo_GS_C.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"296528563","text":"from comet_ml import Optimizer\nimport yaml\nimport models\nfrom tensorflow.keras.optimizers import Adam, Nadam\nfrom tensorflow.keras.layers import Input\nfrom callbacks import all_callbacks\nfrom tensorflow.keras import callbacks\nfrom train import get_features\nfrom sklearn.metrics import roc_auc_score\nfrom tensorflow_model_optimization.python.core.sparsity.keras import prune, pruning_callbacks, pruning_schedule\nfrom tensorflow_model_optimization.sparsity.keras import strip_pruning\n\nparameters = open(\"NNparameters.yml\")\nyamlparameters = yaml.load(parameters,Loader=yaml.FullLoader)\n\nconfig = {\n # We pick the Bayes algorithm:\n \"algorithm\": \"bayes\",\n\n # Declare your hyperparameters in the Vizier-inspired format:\n \"parameters\": {\n\n\n \"learning_rate\": { \"type\": \"float\", \"mu\": yamlparameters[\"Training_learning_rate\"], \"sigma\": 0.0001, \"scalingType\": \"normal\"},\n \"Regularization\": { \"type\": \"float\", \"min\": 0.0001, \"max\": 0.01, \"scalingType\": \"uniform\"},\n \"pruning_begin_epoch\":{\"type\": \"int\", \"min\": 50, \"max\": 200, \"scalingType\": \"uniform\"},\n \"pruning_end_epoch\": {\"type\": \"int\", \"min\": 100, \"max\": 800, \"scalingType\": \"uniform\"},\n \"pruning_lr_factor_1\":{\"type\": \"float\", \"min\": 0.0, \"max\": 1.0, \"scalingType\": \"uniform\"},\n \"pruning_lr_factor_2\":{\"type\": \"float\", \"min\": 0.0, \"max\": 1.0, \"scalingType\": \"uniform\"},\n \"pruning_lr_factor_3\":{\"type\": \"float\", \"min\":-10.0, \"max\": 10.0, \"scalingType\": \"uniform\"},\n\n\n },\n\n # Declare what we will be optimizing, and how:\n \"spec\": {\n \"metric\": \"ROC\",\n \"objective\": \"maximize\",\n },\n}\n\n\n\n\nopt = Optimizer(config, api_key=yamlparameters[\"comet_api_key\"], project_name=\"NNqhmv6\",auto_metric_logging=True)\n\nX_train, X_test, y_train, y_test = get_features(yamlparameters[\"DataDir\"])\n \n\nfor experiment in opt.get_experiments():\n steps_per_epoch = int(len(X_train)/yamlparameters[\"Training_batch_size\"])\n\n pruning_params = {\"pruning_schedule\" : pruning_schedule.PolynomialDecay(initial_sparsity=0.0,\n final_sparsity=yamlparameters[\"Sparsity\"],\n begin_step=experiment.get_parameter(\"pruning_begin_epoch\")*steps_per_epoch, \n end_step=experiment.get_parameter(\"pruning_end_epoch\")*steps_per_epoch)}\n keras_model = models.qdense_model(Input(shape=X_train.shape[1:]), \n l1Reg=experiment.get_parameter(\"Regularization\"),\n bits=yamlparameters[\"Layer_bits\"],\n ints=yamlparameters[\"Layer_ints\"])\n keras_model = prune.prune_low_magnitude(keras_model, **pruning_params)\n\n startlearningrate=experiment.get_parameter(\"learning_rate\")\n\n adam = Adam(lr=startlearningrate,\n beta_1=yamlparameters[\"Training_learning_beta1\"],\n beta_2=yamlparameters[\"Training_learning_beta2\"],\n amsgrad=True)\n\n keras_model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['binary_accuracy'])\n\n callbacks=all_callbacks(stop_patience=yamlparameters[\"Training_early_stopping\"], \n initial_lr=experiment.get_parameter(\"learning_rate\"),\n lr_factor=yamlparameters[\"Training_lr_factor\"],\n lr_patience=yamlparameters[\"Training_lr_patience\"],\n lr_epsilon=yamlparameters[\"Training_lr_min_delta\"], \n lr_cooldown=yamlparameters[\"Training_lr_cooldown\"], \n lr_minimum=yamlparameters[\"Training_lr_minimum\"],\n Prune_begin=experiment.get_parameter(\"pruning_begin_epoch\"),\n Prune_end=experiment.get_parameter(\"pruning_end_epoch\"),\n prune_lrs=[experiment.get_parameter(\"pruning_lr_factor_1\"),\n experiment.get_parameter(\"pruning_lr_factor_2\"),\n experiment.get_parameter(\"pruning_lr_factor_3\")],\n outputDir=yamlparameters[\"TrainDir\"])\n\n callbacks.callbacks.append(pruning_callbacks.UpdatePruningStep())\n\n keras_model.fit(X_train, y_train, \n batch_size = experiment.get_parameter(\"batch_size\"), \n epochs = experiment.get_parameter(\"epochs\"),\n validation_split = yamlparameters[\"Training_validation_split\"], \n shuffle = True, \n callbacks =callbacks.callbacks,\n verbose=0)\n \n model = strip_pruning(keras_model)\n model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['binary_accuracy'])\n\n y_predict = model.predict(X_test,verbose=0)\n loss,binary_accuracy = keras_model.evaluate(X_test, y_test,verbose=0)\n auc = roc_auc_score(y_test,y_predict)\n print(\"AUC:\",auc)\n print(\"ACC:\",binary_accuracy)\n\n experiment.log_metric(\"ROC\",auc)\n experiment.log_metric(\"Loss\",loss)\n experiment.log_metric(\"Binary_Accuracy\",binary_accuracy)\n\n","sub_path":"pruningoptimiser.py","file_name":"pruningoptimiser.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"129781522","text":"# pylint:disable=missing-docstring,line-too-long\n\n__author__ = 'Chintan Shah'\n\nfrom scrapy import Spider\nfrom spiders.others.epa.items import EPAItem\nfrom helpers.string_processor import process_string\nfrom urlparse import urljoin\n\n\nclass OARTechPublications(Spider):\n\n name = \"epa-oar-techpublications\"\n allowed_domains = [\"epa.gov\"]\n start_urls = [\"http://www.epa.gov/ttn/atw/publicat.html\",]\n\n def parse(self, response):\n elements = response.xpath(\"//table/tr[not(position()=1)]\")\n for each_elem in elements:\n item = EPAItem()\n item['url'] = response.url\n title = each_elem.css(\"td:nth-child(2) ::text\").extract()\n item['title'] = process_string(\"\".join(title))\n url = each_elem.css(\"a::attr(href)\").extract()\n bad_url = each_elem.css(\"a[href*='disclaim']::attr(href)\").extract()\n if url and not bad_url:\n item['url'] = urljoin(response.url, url[0])\n item['type'] = \"Technical Publications\"\n yield item\n","sub_path":"spiders/others/epa/OARTechPublications.py","file_name":"OARTechPublications.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"307273870","text":"from RPM.Helpers import Helpers\nfrom RPM.MainMenu import MainMenu\nfrom RPM.Options import Options\nfrom RPM.Main import Main\n\n\nclass OptionsUI:\n def options_menu(self):\n print(\"\\n~~~~~~~~~~~~~~~\\n\"\n \" OPTIONS\\n\"\n \"~~~~~~~~~~~~~~~\\n\"\n \"[1] Emails\\n\"\n \"[2] Usernames\\n\"\n \"[3] Length\\n\"\n \"[4] Range\\n\"\n \"[5] Punctuation\\n\"\n \"~~~~~~~~~~~~~~~\\n\"\n \"[6] Main Menu\\n\"\n \"~~~~~~~~~~~~~~~\\n\")\n options = {\n \"1\": self.email_options,\n \"2\": self.username_options,\n \"3\": self.length_options,\n \"4\": self.range_options,\n \"5\": self.punctuation_options,\n \"6\": MainMenu,\n }\n i = \"dummy\"\n while i not in options:\n i = input()\n options[i]()\n self.options_menu() # loop until [Main Menu]\n\n def email_options(self):\n Helpers().display_list(Options.emails, \"emails\")\n options = {\n \"\": self.options_menu,\n \"a\": self.__add_email__,\n \"d\": self.__del_email__,\n \"e\": self.__edit_email__,\n \"s\": self.__default_email__,\n }\n i = \"dummy\"\n while i not in options:\n i = input(\"[enter] Options menu\\n\"\n \"[a] Add\\n\"\n \"[d] Delete\\n\"\n \"[e] Edit\\n\"\n \"[s] Set default\\n\")\n options[i]()\n self.email_options() # loop email options until [enter]\n\n def username_options(self):\n Helpers().display_list(Options.usernames, \"usernames\")\n options = {\n \"\": self.options_menu,\n \"a\": self.__add_username__,\n \"d\": self.__del_username__,\n \"e\": self.__edit_username__,\n \"s\": self.__default_username__,\n }\n i = \"dummy\"\n while i not in options:\n i = input(\"[enter] Options menu\\n\"\n \"[a] Add\\n\"\n \"[d] Delete\\n\"\n \"[e] Edit\\n\"\n \"[s] Set default\\n\")\n options[i]()\n self.username_options() # loop username options until [enter]\n\n def length_options(self):\n print(f\"\\nCurrent length is {Options.length} characters\")\n ln = input(\"[enter] Options menu\\n\"\n \"[length]\\n\")\n if ln != \"\": # not [enter] (\"\")\n try:\n ln = int(ln)\n assert ln > 0\n Options.length = ln\n Main.oshelf[\"length\"] = ln\n print(f\"Length set to {ln} characters\")\n except (ValueError, AssertionError): # bad input Try again\n print(\"Length must be a positive integer\")\n self.length_options()\n\n def range_options(self):\n print(f\"\\nRange to randomize p.w. length\\n\"\n f\"\\tE.g. range 2 and length 15\\n\"\n f\"\\trandomizes p.w. length between 13 to 17 characters\\n\"\n f\"Current range is {Options.lrange}\")\n try:\n r = input(\"[enter] Options menu\\n\"\n \"Set range\\n\")\n if r != \"\": # not [enter] (\"\")\n r = int(r)\n assert r >= 0\n Options.lrange = r\n Main.oshelf[\"lrange\"] = r\n print(f\"Range set to +/- {r} characters\")\n except (ValueError, AssertionError): # bad input Try again\n print(\"Range must be a non-negative integer\")\n self.range_options()\n\n @staticmethod\n def punctuation_options():\n print(f\"\\nCurrent punctuation is {Options.punctuation}\")\n print(\"\"\"\n [enter] Options menu\n [a] All !#$%&()*+,-./:;<=>?@[]^_{|}~\n [s] Some %+-./:=@_\n [l] Limited @._-\n [n] None\n \"\"\")\n pn = {\"a\": \"all\", \"s\": \"some\", \"l\": \"limited\", \"n\": \"none\"}\n i = \"input string\"\n while i and (i not in pn):\n i = input() # loop if bad input\n if i in pn:\n Options.punctuation = pn[i]\n Main.oshelf[\"punctuation\"] = Options.punctuation\n print(f\"Punctuation set to {Options.punctuation}\")\n\n def __add_email__(self):\n ok, e = Helpers().add_entry(Options.emails, Main.oshelf, \"emails\")\n Helpers().display_list(Options.emails, \"emails\")\n if ok:\n i = input(\"Saved\\n\"\n \"[enter] Email options\\n\"\n \"[a] Add another\\n\")\n else:\n i = input(f\"Already have '{e}' saved\\n\"\n f\"[enter] Email options\\n\"\n f\"[t] Try again\\n\")\n if i in (\"a\", \"t\"):\n self.__add_email__() # Add another/Try again\n\n def __add_username__(self):\n ok, u = Helpers().add_entry(\n Options.usernames, Main.oshelf, \"usernames\")\n Helpers().display_list(Options.usernames, \"usernames\")\n if ok:\n i = input(\"Saved\\n\"\n \"[enter] Username options\\n\"\n \"[a] Add another\\n\")\n else:\n i = input(f\"Already have '{u}' saved\\n\"\n f\"[enter] Username options\\n\"\n f\"[t] Try again\\n\")\n if i in (\"a\", \"t\"):\n self.__add_username__() # add another/Try again\n\n def __default_email__(self):\n if len(Options.emails) == 1:\n input(\"Add an email first\\n\"\n \"[enter] Go back\\n\")\n self.email_options() # back to email options\n print(\"[enter] Email options\\n\"\n \"[number] Set default email\")\n number = Helpers().valid_number(Options.emails)\n if number == 0:\n if input(\"Cannot set 'no email' as default\\n\"\n \"[enter] Email options\\n\"\n \"[t] Try again\\n\") == \"t\":\n self.__default_email__() # Try again\n elif number in (\"\", \"*\"):\n self.email_options() # back to email options\n else:\n d = Options.emails.pop(number) # remove from list, assign to 'd'\n # put back as [1]\n temp = [Options.emails[0], d] + Options.emails[1:]\n Options.emails = temp\n Main.oshelf[\"emails\"] = temp\n input(f\"'{d}' Saved as default\\n\"\n f\"[enter]...\\n\")\n self.email_options()\n\n def __default_username__(self):\n if len(Options.usernames) == 1:\n input(\"Add a username first\\n\"\n \"[enter] Go back...\\n\")\n self.username_options() # back to username options\n print(\"[enter] Username options\\n\"\n \"[number] Set default username\\n\")\n number = Helpers().valid_number(Options.usernames)\n if number == 0:\n if input(\"Cannot set 'no username' as default\\n\"\n \"[enter] Username options\\n\"\n \"[t] Try again\\n\") == \"t\":\n self.__default_username__() # Try again\n elif number in (\"\", \"*\"):\n self.username_options() # back to username options\n else:\n d = Options.usernames.pop(number) # remove from list, assign to 'd'\n temp = [Options.usernames[0], d] + Options.usernames[1:] # user[1]\n Options.usernames = temp\n Main.oshelf[\"usernames\"] = temp\n input(f\"'{d}' Saved as default\\n\"\n f\"[enter]...\\n\")\n\n def __del_email__(self):\n if len(Options.emails) == 1:\n input(\"No emails to delete\\n\"\n \"[enter]...\\n\")\n self.email_options() # back to email options\n print(\"[enter] Email options\\n\"\n \"[number] Remove email\"),\n number = Helpers().valid_number(Options.emails)\n if number == 0:\n if input(\"Cannot delete 'no email'\\n\"\n \"[enter] Email options\\n\"\n \"[t] Try again\\n\") == \"t\":\n self.__del_email__() # Try again\n elif number not in (\"\", \"*\"):\n email = Options.emails[number] # number is valid\n if input(f\"Remove {email} ?\\n\"\n f\"[y] Yes\\n\"\n f\"[n] No\\n\") == \"y\":\n temp = Options.emails[:]\n temp.pop(number)\n Options.emails = temp\n Main.oshelf[\"emails\"] = temp\n input(f\"'{email}' deleted\\n\"\n f\"[enter]...\\n\")\n else: # abort remove\n input(\"Nothing deleted\\n\"\n \"[enter]...\\n\")\n\n def __del_username__(self):\n if len(Options.emails) == 1:\n input(\"No usernames to delete\\n\"\n \"[enter]...\\n\")\n self.username_options() # back to username options\n print(\"[enter] Username options\\n\"\n \"[number] Remove username\"),\n number = Helpers().valid_number(Options.usernames)\n if number == 0:\n if input(\"Cannot delete 'no username'\\n\"\n \"[enter] Username options\\n\"\n \"[t] Try again\\n\") \\\n == \"t\":\n self.__del_username__() # Try again\n elif number not in (\"\", \"*\"):\n username = Options.usernames[number] # number is valid\n if input(f\"Remove {username} ?\\n\"\n f\"[y] Yes\\n\"\n f\"[n] No\\n\") == \"y\":\n temp = Options.usernames[:]\n temp.pop(number)\n Options.usernames = temp\n Main.oshelf[\"usernames\"] = temp\n input(f\"'{username}' deleted\\n\"\n f\"[enter]...\\n\")\n else: # abort remove\n input(\"Nothing deleted\\n\"\n \"[enter]...\\n\")\n\n def __edit_email__(self):\n if len(Options.emails) == 1:\n input(\"No emails to edit\\n\"\n \"[enter] Email options\\n\")\n self.email_options() # options\n print(\"[enter] Email options\\n\"\n \"[number] Edit email\\n\")\n if self.__edit_list__(Options.emails, \"emails\"):\n Helpers().display_list(Options.emails, \"emails\")\n i = input(\"[enter] Email options\\n\"\n \"[e] Edit another\\n\")\n else:\n i = input(\"[enter] Email options\\n\"\n \"[t] Try again\\n\")\n if i in (\"e\", \"t\"): # edit another/Try again\n self.__edit_email__()\n\n def __edit_list__(self, mylist, key):\n ind = Helpers().valid_number(mylist)\n if not ind:\n if key == \"emails\":\n self.email_options()\n elif key == \"usernames\":\n self.username_options()\n elif ind == 0:\n print(f\"0 is no {key}\")\n return False\n entry = input(\"Email:\\n\") if key == \"emails\" else input(\"Username:\\n\")\n if entry in mylist:\n print(f\"Already have {entry} saved\")\n return False\n mylist[ind] = entry\n Main.oshelf[key][ind] = entry\n Helpers().display_list(mylist, key)\n return True\n\n def __edit_username__(self):\n if len(Options.emails) == 1:\n input(\"No usernames to edit\\n\"\n \"[enter]...\\n\")\n return # options\n print(\"[enter] Options menu\\n\"\n \"[number] Edit username\\n\")\n if self.__edit_list__(Options.usernames, \"usernames\"):\n Helpers().display_list(Options.usernames, \"usernames\")\n i = input(\"[enter] Username options\\n\"\n \"[e] Edit another\\n\")\n else:\n i = input(\"[enter] Username options\\n\"\n \"[t] Try again\\n\")\n if i in (\"e\", \"t\"): # edit another/Try again\n self.__edit_username__()\n","sub_path":"RPM/OptionsUI.py","file_name":"OptionsUI.py","file_ext":"py","file_size_in_byte":11794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"479443766","text":"import pytest\n\nfrom rest_framework import status\n\nfrom api.searches.serializers import SearchSerializer\nfrom constants import content_types\nfrom constants.urls import API_V1\nfrom db.models.searches import Search\nfrom factories.factory_projects import ProjectFactory\nfrom factories.factory_searches import SearchFactory\nfrom tests.utils import BaseViewTest\n\n\n@pytest.mark.search_mark\nclass BaseTestSearchListView(BaseViewTest):\n DISABLE_RUNNER = True\n HAS_AUTH = True\n model_class = Search\n factory_class = SearchFactory\n serializer_class = SearchSerializer\n entity = ''\n content_type = ''\n num_objects = 3\n\n def setUp(self):\n super().setUp()\n self.project = ProjectFactory(user=self.auth_client.user)\n self.other_project = ProjectFactory()\n self.url = '/{}/searches/{}/{}/{}'.format(API_V1,\n self.project.user.username,\n self.project.name,\n self.entity)\n self.other_url = '/{}/searches/{}/{}/{}'.format(API_V1,\n self.other_project.user.username,\n self.other_project.name,\n self.entity)\n self.objects = [\n self.factory_class(user=self.auth_client.user,\n project=self.project,\n content_type=self.content_type) for _ in range(self.num_objects)]\n\n # Other objects that do not belong to the filter\n self.factory_class(project=self.other_project, content_type=self.content_type)\n self.queryset = self.model_class.objects.filter(project=self.project)\n self.queryset = self.queryset.order_by('-updated_at')\n\n def test_get(self):\n resp = self.auth_client.get(self.url)\n assert resp.status_code == status.HTTP_200_OK\n\n assert resp.data['next'] is None\n assert resp.data['count'] == len(self.objects)\n\n data = resp.data['results']\n assert len(data) == self.queryset.count()\n assert data == self.serializer_class(self.queryset, many=True).data\n\n resp = self.auth_client.get(self.other_url)\n assert resp.status_code == status.HTTP_200_OK\n assert resp.data['count'] == 0\n\n def test_create(self):\n data = {}\n resp = self.auth_client.post(self.url, data)\n assert resp.status_code == status.HTTP_400_BAD_REQUEST\n\n data = {'query': {'query': 'project.id: 1|2', 'sort': '-created_at'}}\n resp = self.auth_client.post(self.url, data)\n\n assert resp.status_code == status.HTTP_201_CREATED\n assert self.queryset.count() == self.num_objects + 1\n\n # Test other\n resp = self.auth_client.post(self.other_url, data)\n assert resp.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)\n\n\n@pytest.mark.search_mark\nclass BaseTestSearchDeleteView(BaseViewTest):\n DISABLE_RUNNER = True\n HAS_AUTH = True\n model_class = Search\n factory_class = SearchFactory\n serializer_class = SearchSerializer\n entity = ''\n content_type = ''\n\n def get_url(self, obj):\n return '/{}/searches/{}/{}/{}/{}'.format(API_V1,\n self.project.user.username,\n self.project.name,\n self.entity,\n obj.id)\n\n def setUp(self):\n super().setUp()\n self.project = ProjectFactory(user=self.auth_client.user)\n some_object = self.factory_class(project=self.project,\n content_type=self.content_type)\n self.url = self.get_url(some_object)\n\n def test_delete(self):\n assert Search.objects.count() == 1\n resp = self.auth_client.delete(self.url)\n assert resp.status_code == status.HTTP_404_NOT_FOUND\n obj = self.factory_class(user=self.auth_client.user,\n project=self.project,\n content_type=self.content_type)\n assert Search.objects.count() == 2\n resp = self.auth_client.delete(self.get_url(obj))\n assert resp.status_code == status.HTTP_204_NO_CONTENT\n assert Search.objects.count() == 1\n\n\n@pytest.mark.search_mark\nclass TestExperimentSearchCreateView(BaseTestSearchListView):\n entity = 'experiments'\n content_type = content_types.EXPERIMENT\n\n\n@pytest.mark.search_mark\nclass TestExperimentSearchDeleteView(BaseTestSearchDeleteView):\n entity = 'experiments'\n content_type = content_types.EXPERIMENT\n\n\n@pytest.mark.search_mark\nclass TestExperimentGroupSearchCreateView(BaseTestSearchListView):\n entity = 'groups'\n content_type = content_types.EXPERIMENT_GROUP\n\n\n@pytest.mark.search_mark\nclass TestExperimentGroupSearchDeleteView(BaseTestSearchDeleteView):\n entity = 'groups'\n content_type = content_types.EXPERIMENT_GROUP\n\n\n@pytest.mark.search_mark\nclass TestJobSearchCreateView(BaseTestSearchListView):\n entity = 'jobs'\n content_type = content_types.JOB\n\n\n@pytest.mark.search_mark\nclass TestJobSearchDeleteView(BaseTestSearchDeleteView):\n entity = 'jobs'\n content_type = content_types.JOB\n\n\n@pytest.mark.search_mark\nclass TestBuildSearchCreateView(BaseTestSearchListView):\n entity = 'builds'\n content_type = content_types.BUILD_JOB\n\n\n@pytest.mark.search_mark\nclass TestBuildSearchDeleteView(BaseTestSearchDeleteView):\n entity = 'builds'\n content_type = content_types.BUILD_JOB\n\n\ndel BaseTestSearchListView\ndel BaseTestSearchDeleteView\n","sub_path":"tests/test_searches/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"590629660","text":"\"\"\"\nGiven a collection of intervals, merge all overlapping intervals.\n\nFor example,\nGiven [1,3],[2,6],[8,10],[15,18],\nreturn [1,6],[8,10],[15,18].\n\n\"\"\"\n\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\n\"\"\"\nS1: \n 如果[]有序则比较简单, add时 只要看前一个即可.\n 1. 利用python list.sort() 对指定关键字排序 L.sort(key=lambda x:(x[1],x[0])) tuple先比较第一个在比较第二个\n 2. for 只要判断ans 最后一个 判断是否合并即可\n\n\"\"\"\nclass Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n if len(intervals) ==0 :\n return []\n intervals.sort(key = lambda x:(x.start,x.end)) #sort 先按照start 再end\n ans = [intervals[0]]\n for i in range(1,len(intervals)):\n if intervals[i].start > ans[-1].end : \n ans.append(intervals[i])\n else :\n #ans[-1].start = min(ans[-1].start,intervals[i].start) # 可以去掉无用\n ans[-1].end = max(ans[-1].end,intervals[i].end)\n return ans","sub_path":"56_Merge Intervals.py","file_name":"56_Merge Intervals.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"221369883","text":"import time\nimport numpy as np\nfrom GA_lib import GA\nfrom GA_lib import evaluate as eval\nfrom GA_lib import oper as op\nfrom pdp_lib import preprocessing\nfrom pdp_lib import processing\nfrom pdp_lib import util\n\n'''\nfilename='pdp_instances/LiLim/pdp_100/lrc207.txt'\nnodes = preprocessing.load_node(filename)\nutil.draw_original_nodes(nodes)\nutil.print_nodes(nodes)\nutil.print_requests(requests)\nutil.draw_requests(requests)\n\nutil.print_distances(distances)\n\n'''\n\n\nstart_time = time.time()\n# use 'relative path' in filename\n#filename = 'pdp_instances/Worse2Worst/dummy01.txt'\nfilename = 'pdp_instances/LiLim/pdp_100/lc102.txt'\nnodes = preprocessing.load_node(filename)\nrequests = preprocessing.generate_request(nodes)\ndistances = processing.create_distance_table(nodes)\ndurations = processing.create_duration_table(nodes,speed=1)\nclusters = processing.clustering_requests_only_first(requests)\ndepots=processing.make_depots(nodes)\nprocessing.assign_depot(clusters,depots,nodes)\nadded_nodes=processing.add_depots_to_nodes(nodes, depots)\n#util.draw_requests(requests)\n\nprint(\" processing time --- %s seconds ---\" % (time.time() - start_time))\n\n\n# solving the problems !!!!\nstart_time = time.time()\n\ncouples = GA.requests_to_couples(requests)\n\nstart_time = time.time()\np_vehicles = GA.create_p_vehicles(couples,N=10)\nprint(\" p vehicle time --- %s seconds ---\" % (time.time() - start_time))\nstart_time = time.time()\np_couples = GA.create_p_couples(couples,N=10)\nprint(\" p couple time --- %s seconds ---\" % (time.time() - start_time))\nstart_time = time.time()\np_couples_vehicles = GA.create_p_couples_vehicles(p_couples,p_vehicles)\nprint(\" p couple-vehicle time --- %s seconds ---\" % (time.time() - start_time))\nstart_time = time.time()\np_tours = GA.create_p_tours(p_couples_vehicles,nodes,durations, N=10)\nprint(\" p tours time --- %s seconds ---\" % (time.time() - start_time))\n\n\n# tour = [5, 7, 9, 4, 6, 2, 8, 10]\n# violated = GA.time_violated_nodes(tour,durations,couples,nodes)\n# print ('violated ='+str(violated))\n# print('new tour' +str(tour))\n############################################################################\n\n\n\n\nbest = eval.select_best_populations(p_tours,distances,depots[0],nodes)\ndepots = [depots[0]]\ndist = eval.tours_distance(best[0],distances,depots[0],nodes)\nprint(\"eval time --- %s seconds ---\" % (time.time() - start_time))\n\nbest_lc102 = [[ 20 ,22 ,24 ,25 ,27 ,29 ,28 ,103 ,26 ,23 ,21 ,43 ,41 ,40 ,42 ,44 ,48 ,51 ,50 ,106 ,47 ,46 ,45 ,55 ,57 ,60 ,54 ,53 ,56 ,58 ,59 ,68 ,102 ,90 ,87 ,86 ,83 ,82 ,84 ,85 ,88 ,89 ,91 ,98 ,95 ,100 ,97 ,101 ,96 ,94 ,92 ,93 ,99 ,1 ,75 ,5 ,8 ,9 ,6 ,2 ,4 ,3 ,7 ,10 ,11 ,13 ,12 ,16 ,14 ,17 ,18 ,19 ,15 ,30 ,32 ,33 ,31 ,35 ,37 ,39 ,104 ,38 ,36 ,34 ,52 ,49 ,67 ,65 ,62 ,66 ,61 ,72 ,81 ,78 ,105 ,76 ,71 ,70 ,73 ,77 ,79 ,80 ,74 ,64 ,63 ,69 ]]\n\nprint (processing.unoptimized_distance(requests,depots))\ncouples.sort(key=lambda x: x[0])\nprint(dist)\nutil.draw_tours(best[0],nodes,depots[0])\nutil.draw_tours(best_lc102,nodes,depots[0])\n\n\n\n\n\n\n\nutil.draw_requests(requests)\n# util.draw_original_nodes(nodes)\n#\ndef precedence_violated(tour, couples):\n visited = []\n for i in range(len(tour)):\n v = tour[i]\n couple = [item for item in couples if v in item][0]\n pickup = couple[0] # pickup node\n delivery = couple[1] # delivery node\n if (v == delivery): # v is delivery\n if (not pickup in visited): # the pickup node is not visited\n pickup_index = tour.index(pickup)\n tour.pop(pickup_index)\n tour.insert(i, pickup)\n visited.append(pickup)\n visited.append(v)\n return True\n else: # the sibling is visited\n visited.append(v)\n else: # v is pickup\n visited.append(v)\n return False\nprint(eval.tours_distance(best_lc102,distances,depots[0],nodes))\nprint(precedence_violated(best_lc102[0],couples))","sub_path":"oldCodes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"282679903","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import Model, Input\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom tensorflow.keras.activations import softmax\nfrom tensorflow.keras.metrics import SparseCategoricalAccuracy\n\nfrom graphgallery.nn.layers.tf_layers import GraphConvolution, Gather\nfrom graphgallery.nn.models import SemiSupervisedModel\nfrom graphgallery.sequence import SBVATSampleSequence\nfrom graphgallery.utils.sample import find_4o_nbrs\nfrom graphgallery.utils.bvat_utils import get_normalized_vector, kl_divergence_with_logit, entropy_y_x\nfrom graphgallery.utils.decorators import EqualVarLength\nfrom graphgallery import transforms as T\n\n\nclass SBVAT(SemiSupervisedModel):\n \"\"\"\n Implementation of sample-based Batch Virtual Adversarial Training\n Graph Convolutional Networks (SBVAT).\n `Batch Virtual Adversarial Training for Graph Convolutional Networks\n `\n Tensorflow 1.x implementation: \n\n\n \"\"\"\n\n def __init__(self, *graph, n_samples=50,\n adj_transform=\"normalize_adj\", attr_transform=None,\n device='cpu:0', seed=None, name=None, **kwargs):\n \"\"\"Create a sample-based Batch Virtual Adversarial Training\n Graph Convolutional Networks (SBVAT) model.\n\n This can be instantiated in several ways:\n\n model = SBVAT(graph)\n with a `graphgallery.data.Graph` instance representing\n A sparse, attributed, labeled graph.\n\n model = SBVAT(adj_matrix, attr_matrix, labels)\n where `adj_matrix` is a 2D Scipy sparse matrix denoting the graph,\n `attr_matrix` is a 2D Numpy array-like matrix denoting the node\n attributes, `labels` is a 1D Numpy array denoting the node labels.\n\n\n Parameters:\n ----------\n graph: An instance of `graphgallery.data.Graph` or a tuple (list) of inputs.\n A sparse, attributed, labeled graph.\n n_samples (Positive integer, optional):\n The number of sampled subset nodes in the graph where the length of the\n shortest path between them is at least `4`. (default :obj: `50`)\n adj_transform: string, `transform`, or None. optional\n How to transform the adjacency matrix. See `graphgallery.transforms`\n (default: :obj:`'normalize_adj'` with normalize rate `-0.5`.\n i.e., math:: \\hat{A} = D^{-\\frac{1}{2}} A D^{-\\frac{1}{2}})\n attr_transform: string, `transform`, or None. optional\n How to transform the node attribute matrix. See `graphgallery.transforms`\n (default :obj: `None`)\n device: string. optional\n The device where the model is running on. You can specified `CPU` or `GPU`\n for the model. (default: :str: `CPU:0`, i.e., running on the 0-th `CPU`)\n seed: interger scalar. optional\n Used in combination with `tf.random.set_seed` & `np.random.seed`\n & `random.seed` to create a reproducible sequence of tensors across\n multiple calls. (default :obj: `None`, i.e., using random seed)\n name: string. optional\n Specified name for the model. (default: :str: `class.__name__`)\n kwargs: other customized keyword Parameters.\n \"\"\"\n super().__init__(*graph, device=device, seed=seed, name=name, **kwargs)\n\n self.adj_transform = T.get(adj_transform)\n self.attr_transform = T.get(attr_transform)\n self.n_samples = n_samples\n self.process()\n\n def process_step(self):\n graph = self.graph\n adj_matrix = self.adj_transform(graph.adj_matrix)\n attr_matrix = self.attr_transform(graph.attr_matrix)\n self.neighbors = find_4o_nbrs(adj_matrix)\n\n self.feature_inputs, self.structure_inputs = T.astensors(\n attr_matrix, adj_matrix, device=self.device)\n\n # use decorator to make sure all list arguments have the same length\n @EqualVarLength()\n def build(self, hiddens=[16], activations=['relu'], dropout=0.5,\n lr=0.01, l2_norm=5e-4, use_bias=False, p1=1., p2=1.,\n n_power_iterations=1, epsilon=0.03, xi=1e-6):\n\n with tf.device(self.device):\n\n x = Input(batch_shape=[None, self.graph.n_attrs],\n dtype=self.floatx, name='attr_matrix')\n adj = Input(batch_shape=[None, None],\n dtype=self.floatx, sparse=True, name='adj_matrix')\n index = Input(batch_shape=[None],\n dtype=self.intx, name='node_index')\n\n GCN_layers = []\n dropout_layers = []\n for hidden, activation in zip(hiddens, activations):\n GCN_layers.append(GraphConvolution(hidden, activation=activation, use_bias=use_bias,\n kernel_regularizer=regularizers.l2(l2_norm)))\n dropout_layers.append(Dropout(rate=dropout))\n\n GCN_layers.append(GraphConvolution(\n self.graph.n_classes, use_bias=use_bias))\n self.GCN_layers = GCN_layers\n self.dropout_layers = dropout_layers\n\n logit = self.forward(x, adj)\n output = Gather()([logit, index])\n model = Model(inputs=[x, adj, index], outputs=output)\n\n self.model = model\n self.train_metric = SparseCategoricalAccuracy()\n self.test_metric = SparseCategoricalAccuracy()\n self.loss_fn = SparseCategoricalCrossentropy(from_logits=True)\n self.optimizer = Adam(lr=lr)\n\n self.p1 = p1 # Alpha\n self.p2 = p2 # Beta\n self.xi = xi # Small constant for finite difference\n # Norm length for (virtual) adversarial training\n self.epsilon = epsilon\n self.n_power_iterations = n_power_iterations # Number of power iterations\n\n def forward(self, x, adj, training=True):\n h = x\n for dropout_layer, GCN_layer in zip(self.dropout_layers, self.GCN_layers[:-1]):\n h = GCN_layer([h, adj])\n h = dropout_layer(h, training=training)\n h = self.GCN_layers[-1]([h, adj])\n return h\n\n @tf.function\n def train_step(self, sequence):\n\n with tf.device(self.device):\n self.train_metric.reset_states()\n\n for inputs, labels in sequence:\n x, adj, index, adv_mask = inputs\n with tf.GradientTape() as tape:\n logit = self.forward(x, adj)\n output = tf.gather(logit, index)\n loss = self.loss_fn(labels, output)\n entropy_loss = entropy_y_x(logit)\n vat_loss = self.virtual_adversarial_loss(\n x, adj, logit=logit, adv_mask=adv_mask)\n loss += self.p1 * vat_loss + self.p2 * entropy_loss\n\n self.train_metric.update_state(labels, output)\n\n trainable_variables = self.model.trainable_variables\n gradients = tape.gradient(loss, trainable_variables)\n self.optimizer.apply_gradients(\n zip(gradients, trainable_variables))\n\n return loss, self.train_metric.result()\n\n @tf.function\n def test_step(self, sequence):\n\n with tf.device(self.device):\n self.test_metric.reset_states()\n\n for inputs, labels in sequence:\n x, adj, index, _ = inputs\n logit = self.forward(x, adj, training=False)\n output = tf.gather(logit, index)\n loss = self.loss_fn(labels, output)\n self.test_metric.update_state(labels, output)\n\n return loss, self.test_metric.result()\n\n def virtual_adversarial_loss(self, x, adj, logit, adv_mask):\n d = tf.random.normal(shape=tf.shape(x), dtype=self.floatx)\n\n for _ in range(self.n_power_iterations):\n d = get_normalized_vector(d) * self.xi\n logit_p = logit\n with tf.GradientTape() as tape:\n tape.watch(d)\n logit_m = self.forward(x + d, adj)\n dist = kl_divergence_with_logit(logit_p, logit_m, adv_mask)\n grad = tape.gradient(dist, d)\n d = tf.stop_gradient(grad)\n\n r_vadv = get_normalized_vector(d) * self.epsilon\n logit_p = tf.stop_gradient(logit)\n logit_m = self.forward(x + r_vadv, adj)\n loss = kl_divergence_with_logit(logit_p, logit_m, adv_mask)\n return tf.identity(loss)\n\n def train_sequence(self, index):\n index = T.asintarr(index)\n labels = self.graph.labels[index]\n\n sequence = SBVATSampleSequence([self.feature_inputs, self.structure_inputs,\n index], labels,\n neighbors=self.neighbors,\n n_samples=self.n_samples, device=self.device)\n\n return sequence\n\n def test_sequence(self, index):\n index = T.asintarr(index)\n labels = self.graph.labels[index]\n\n sequence = SBVATSampleSequence([self.feature_inputs, self.structure_inputs,\n index], labels,\n neighbors=self.neighbors,\n n_samples=self.n_samples,\n resample=False, device=self.device)\n\n return sequence\n\n def predict_step(self, sequence):\n with tf.device(self.device):\n for inputs, _ in sequence:\n x, adj, index, adv_mask = inputs\n output = self.forward(x, adj, training=False)\n logit = tf.gather(output, index)\n\n if tf.is_tensor(logit):\n logit = logit.numpy()\n return logit\n","sub_path":"graphgallery/nn/models/semisupervised/sbvat.py","file_name":"sbvat.py","file_ext":"py","file_size_in_byte":10014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"15677552","text":"\"\"\"value_error.py\n\nCollection of functions useful in parsing ValueError messages and\nproviding a more detailed explanation.\n\"\"\"\n\nimport inspect\nimport re\n\nfrom ..my_gettext import current_lang, no_information, internal_error\nfrom .. import info_variables\nfrom .. import debug_helper\nfrom .. import token_utils\nfrom .. import utils\n\nconvert_type = info_variables.convert_type\nMESSAGES_PARSERS = []\n\n\ndef add_message_parser(func):\n \"\"\"A simple decorator that adds a function to parse a specific message\n to the list of known parsers.\"\"\"\n MESSAGES_PARSERS.append(func)\n\n\ndef get_cause(value, frame, tb_data):\n try:\n return _get_cause(value, frame, tb_data)\n except Exception as e: # pragma: no cover\n debug_helper.log_error(e)\n return {\"cause\": internal_error(), \"suggest\": internal_error()}\n\n\ndef _get_cause(value, frame, tb_data):\n _ = current_lang.translate\n\n message = str(value)\n for parser in MESSAGES_PARSERS:\n cause = parser(message, frame, tb_data)\n if cause:\n return cause\n cause = unrecognized_message(value, frame, tb_data)\n if cause:\n return cause\n return {\"cause\": no_information()}\n\n\ndef _unpacking():\n _ = current_lang.translate\n return _(\n \"Unpacking is a convenient way to assign a name,\\n\"\n \"to each item of an iterable.\\n\"\n )\n\n\ndef get_iterable(code, frame):\n \"\"\"gets an iterable object and its type as a string.\"\"\"\n try:\n # As a ValueError exception has been raised, Python has already evaluated\n # all the relevant code parts. Thus, using eval should be completely safe.\n obj = utils.eval_expr(code, frame)\n # obj = eval(code, frame.f_globals, frame.f_locals)\n except Exception: # noqa\n return None, None\n\n if isinstance(obj, dict):\n iterable = \"dict\"\n elif isinstance(obj, list):\n iterable = \"list\"\n elif isinstance(obj, set):\n iterable = \"set\"\n elif isinstance(obj, str):\n iterable = \"str\"\n elif isinstance(obj, tuple):\n iterable = \"tuple\"\n else:\n iterable = None\n return obj, iterable\n\n\n@add_message_parser\ndef not_enough_values_to_unpack(message, frame, tb_data):\n _ = current_lang.translate\n pattern1 = re.compile(r\"not enough values to unpack \\(expected (\\d+), got (\\d+)\\)\")\n match1 = re.search(pattern1, message)\n pattern2 = re.compile(\n r\"not enough values to unpack \\(expected at least (\\d+), got (\\d+)\\)\"\n )\n match2 = re.search(pattern2, message)\n if match1 is None and match2 is None:\n return {}\n\n match = match1 if match2 is None else match2\n\n nb_names = match.group(1)\n length = match.group(2)\n\n if tb_data.bad_line.count(\"=\") != 1:\n cause = _unpacking() + _(\n \"In this instance, there are more names ({nb_names})\\n\"\n \"than {length}, the length of the iterable.\\n\"\n ).format(nb_names=nb_names, length=length)\n return {\"cause\": cause}\n\n _lhs, rhs = tb_data.bad_line.split(\"=\")\n obj, iterable = get_iterable(rhs, frame)\n if obj is None or iterable is None:\n cause = _unpacking() + _(\n \"In this instance, there are more names ({nb_names})\\n\"\n \"than {length}, the length of the iterable.\\n\"\n ).format(nb_names=nb_names, length=length)\n return {\"cause\": cause}\n\n cause = _unpacking() + _(\n \"In this instance, there are more names ({nb_names})\\n\"\n \"than the length of the iterable, {iter_type} of length {length}.\\n\"\n ).format(nb_names=nb_names, iter_type=convert_type(iterable), length=length)\n return {\"cause\": cause}\n\n\n@add_message_parser\ndef too_many_values_to_unpack(message, frame, tb_data):\n _ = current_lang.translate\n pattern = re.compile(r\"too many values to unpack \\(expected (\\d+)\\)\")\n match = re.search(pattern, message)\n if match is None:\n return {}\n\n nb_names = match.group(1)\n\n if tb_data.bad_line.count(\"=\") != 1:\n cause = _unpacking() + _(\n \"In this instance, there are fewer names ({nb_names})\\n\"\n \"than the length of the iterable.\\n\"\n ).format(nb_names=nb_names)\n return {\"cause\": cause}\n\n _lhs, rhs = tb_data.bad_line.split(\"=\")\n\n obj, iterable = get_iterable(rhs, frame)\n if obj is None or iterable is None or not hasattr(obj, \"__len__\"):\n cause = _unpacking() + _(\n \"In this instance, there are fewer names ({nb_names})\\n\"\n \"than the length of the iterable.\\n\"\n ).format(nb_names=nb_names)\n return {\"cause\": cause}\n\n cause = _unpacking() + _(\n \"In this instance, there are fewer names ({nb_names})\\n\"\n \"than the length of the iterable, {iter_type} of length {length}.\\n\"\n ).format(nb_names=nb_names, iter_type=convert_type(iterable), length=len(obj))\n return {\"cause\": cause}\n\n\n# TODO: complete the work below; note noqa to be removed\n\n\n@add_message_parser\ndef invalid_literal_for_int(message, *_args):\n _ = current_lang.translate\n pattern = re.compile(r\"invalid literal for int\\(\\) with base (\\d+): '(.*)'\")\n match = re.search(pattern, message)\n if match is None:\n return {}\n base, value = int(match.group(1)), match.group(2).strip()\n if base == 10:\n try:\n _value = float(value) # noqa\n return _convert_to_float(value)\n except ValueError:\n pass\n\n return {}\n\n\ndef _convert_to_float(value):\n _ = current_lang.translate\n\n hint = _(\"You need to convert to a float first.\\n\")\n cause = _(\n \"The string `'{value}'` needs to be first converted using `float()`\\n\"\n \"before the result can be converted into an integer using `int()`.\\n\"\n ).format(value=value)\n return {\"cause\": cause, \"suggest\": hint}\n\n\n@add_message_parser\ndef date_month_must_be_between_1_and_12(message, *_args):\n _ = current_lang.translate\n\n if message != \"month must be in 1..12\":\n return {}\n\n hint = _(\"Did you specify an invalid month?\\n\")\n cause = _(\n \"I am guessing that you specify an invalid value for a month\\n\"\n \"in a `date` object. Valid values are integers, from 1 to 12.\\n\"\n )\n return {\"cause\": cause, \"suggest\": hint}\n\n\ndef unrecognized_message(_value, frame, tb_data):\n \"\"\"This attempts to provide some help when a message is not recognized.\"\"\"\n _ = current_lang.translate\n bad_line = tb_data.bad_line.strip()\n if bad_line.startswith(\"raise \") or bad_line.startswith(\"raise\\t\"):\n try:\n name = inspect.getframeinfo(frame).function\n fn_obj = frame.f_globals[name]\n except Exception:\n return {}\n else:\n all_objects = info_variables.get_all_objects(bad_line, frame)[\"name, obj\"]\n callables = []\n for name, obj in all_objects:\n if callable(obj):\n callables.append((name, obj))\n if not callables:\n return {}\n\n tokens = token_utils.get_significant_tokens(tb_data.bad_line)\n name, fn_obj = callables[0]\n if name != tokens[0]:\n return {}\n\n cause = _(\n \"I do not recognize this error message.\\n\"\n \"I am guessing that the problem is with the function `{name}`.\\n\"\n ).format(name=name)\n\n if hasattr(fn_obj, \"__doc__\") and fn_obj.__doc__ is not None:\n cause += _(\"Its docstring is:\\n\\n`'''{docstring}'''`\\n\").format(\n docstring=fn_obj.__doc__\n )\n else:\n cause += _(\"I have no more information.\\n\")\n return {\"cause\": cause}\n","sub_path":"friendly/runtime_errors/value_error.py","file_name":"value_error.py","file_ext":"py","file_size_in_byte":7523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"285440311","text":"class AircraftManufacturer:\n def run(dbc, pl, plgo):\n print(\"Aircraft manufacturer:\")\n print(\" Calculating...\")\n\n # Select Manufacturer column from Aircraft table where Manufacturer is not empty\n dbc.execute('SELECT Manufacturer FROM Aircraft WHERE Manufacturer <> \"\"')\n manufacturerRows = dbc.fetchall()\n\n manufacturers = []\n counts = []\n\n # Number of manufacturers to include in the pie chart\n nHighest = 9\n\n # Loop through selected rows\n for index, value in enumerate(manufacturerRows):\n try:\n # Check if the manufacturer is in the list\n manufacturers.index(value)\n except ValueError:\n # Add it if not\n manufacturers.append(value)\n\n # Increment the counter for the manufacturer\n try:\n counts[manufacturers.index(value)] += 1\n except IndexError:\n # If the counter does not exist, add it\n counts.append(1)\n\n highestManufacturers = []\n highestCounts = []\n\n # Collect nHighest manufacturers into new lists\n for x in range(nHighest):\n maxValue = max(counts)\n maxIndex = counts.index(maxValue)\n maxManufacturer = manufacturers[maxIndex]\n\n highestCounts.append(max(counts))\n highestManufacturers.append(maxManufacturer)\n counts[maxIndex] = -1\n\n # Send data to Plotly\n print(\" Plotting...\")\n trace = plgo.Pie(\n labels=highestManufacturers,\n values=highestCounts\n )\n data = [trace]\n layout = plgo.Layout(\n title='Manufacturers',\n )\n figure = plgo.Figure(data=data, layout=layout)\n pl.plot(figure, filename='Manufacturer count', auto_open=False)\n\n print(\" Done!\")\n","sub_path":"charts/aircraft_manufacturer.py","file_name":"aircraft_manufacturer.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"68149063","text":"import os\n\npath = os.getcwd()\n\n\ndef Del(path):\n if os.path.isfile(path):\n name = os.path.splitext(path)\n if name[1] == '.o' or name[1] == '.exe':\n print(f\"clean --- {path}\")\n os.remove(path)\n elif path.find('.') == -1:\n for file in os.listdir(path):\n Del(f\"{path}/{file}\")\n\nif __name__ == '__main__':\n Del(path)\n\n","sub_path":"clean_exe.py","file_name":"clean_exe.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"299755358","text":"from django.shortcuts import render_to_response\nfrom django.http import HttpResponse\n\ndef holaMundo(request):\n\thtml = \"Muerte a los Murlocks!\"\n\treturn HttpResponse(html)\n\t\ndef suma(request,num1,num2):\n\top1 = int(num1)\n\top2 = int(num2)\n\tresponse=render_to_response('suma.html',{'result': op1+op2})\n\treturn response\n","sub_path":"prueba/vistas/vista.py","file_name":"vista.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"362576466","text":"import json\r\nimport tornado.web\r\n\r\nfrom nbconvert.preprocessors.execute import executenb\r\nfrom nbconvert import HTMLExporter\r\nfrom notebook.base.handlers import IPythonHandler\r\n\r\nclass NoInputHandler(IPythonHandler):\r\n\r\n def initialize(self, config=None, nbconvert_template_path=None):\r\n self.template_path = nbconvert_template_path\r\n self.exporter_config = config\r\n\r\n @tornado.web.authenticated\r\n @tornado.gen.coroutine\r\n def get(self, path=None):\r\n\r\n if path is None:\r\n raise tornado.web.HTTPError(404, 'notebook not found')\r\n\r\n model = self.contents_manager.get(path)\r\n\r\n if 'content' not in model:\r\n raise tornado.web.HTTPError(404, 'notebook not found')\r\n\r\n # notebook = model['content']\r\n\r\n # if 'metadata' not in notebook:\r\n # raise tornado.web.HTTPError(404, 'notebook not found')\r\n\r\n # kernel_name = notebook.metadata.get('kernelspec', {}).get('name', self.kernel_manager.default_kernel_name)\r\n # kernel_id = yield tornado.gen.maybe_future(self.kernel_manager.start_kernel(kernel_name=kernel_name))\r\n # km = self.kernel_manager.get_kernel(kernel_id)\r\n # result = executenb(notebook, km=km)\r\n\r\n # exporter = HTMLExporter(\r\n # template_file='noinput.tpl',\r\n # template_path=self.template_path,\r\n # config=self.exporter_config\r\n # )\r\n\r\n # exporter.exclude_input = True\r\n # exporter.exclude_output_prompt = True\r\n # exporter.exclude_input_prompt = True\r\n\r\n # html, resources = exporter.from_notebook_node(result, resources={\r\n # 'kernel_id': kernel_id,\r\n # 'base_url': self.base_url,\r\n # 'nbextensions': []\r\n # })\r\n\r\n # self.set_header('Content-Type', 'text/html')\r\n # self.set_header('Content-Security-Policy', 'frame-ancestors *')\r\n # #self.set_header('Content-Security-Policy', 'frame-ancestors * http://localhost:8080')\r\n # self.write(html)\r\n\r\n # data = json.dumps(model)\r\n\r\n html = \"\"\"\r\n \r\n \r\n \r\n Notebook\r\n \r\n \r\n \r\n \r\n
\r\n \r\n \r\n \r\n \"\"\"\r\n\r\n self.write(html)","sub_path":"nb_noinput/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"374248552","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils.datetime_safe import datetime\n\nfrom api.enums import IssueImportance, IssueStatus\nfrom api.models import Crawl, CrawlIssue, PageIssue, WebsiteIssue, Page\n\n\ndef recalculate_website_issues(page_issue):\n website_issues = WebsiteIssue.objects.filter(issue=page_issue.issue)\n if website_issues.count() == 0:\n WebsiteIssue.objects.create(issue=page_issue.issue,\n website=page_issue.page.website,\n pages=1,\n status=IssueStatus.NEW.value,\n importance=IssueImportance.M.value,\n visits=page_issue.page.hits\n )\n else:\n for website_issue in website_issues:\n website_issue.recalculate()\n\n\n@receiver(post_save, sender=PageIssue)\ndef update_website_issues_after_page_issues_save(sender, instance=None, created=False, **kwargs):\n if created:\n page = Page.objects.get(id=instance.page.id)\n page.healthy = False\n page.save()\n recalculate_website_issues(instance)\n\n\ndef recalculate_page_issues(crawl_issue):\n page_issues = PageIssue.objects.filter(issue=crawl_issue.issue, page=crawl_issue.crawl.page)\n if page_issues.count() == 0:\n PageIssue.objects.create(issue=crawl_issue.issue,\n page=crawl_issue.crawl.page,\n status=IssueStatus.NEW.value,\n importance=IssueImportance.M.value,\n )\n\n\n@receiver(post_save, sender=CrawlIssue)\ndef update_page_issues_after_crawl_issue_save(sender, instance=None, created=False, **kwargs):\n if created:\n recalculate_page_issues(instance)\n\n\n@receiver(post_save, sender=Crawl)\ndef update_page_issues_after_crawl_save(sender, instance=None, created=False, **kwargs):\n if created:\n instance.page.last_crawled = datetime.now()\n instance.save()\n\n\n","sub_path":"api/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"154093239","text":"import pandas as pd\n\nimport pdb\n\n#Functions from NSA Are called from shell because they run in Python3\nimport subprocess\nimport os\nimport pickle\nimport csv\n\n\nimport umap\nimport json\n\nfrom topic_extractor import topic_extractor\nfrom classes.document_class import Document\nfrom classes.encoder_class import Encoder\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n#TO load UMAP SESS MOdel\nimport joblib\n\n#Session\nclass Session:\n \"\"\"Session Class\"\"\"\n def __init__(self, session_id):\n self.id = session_id\n self.sess_folder = './sessData/' + session_id\n self.documents = False\n self.topics = False\n self.topic_params = False\n self.authorList = False\n self.words = False\n self.UMAP = False\n self.topic_UMAP = False\n self.text_min_lenght = 0\n self.topic_min_length = 0\n self.abstract_conclusion_min_length = 0\n self.vectors2D = False\n self.vectors2D_topics = False\n self.encoder = False\n self.text_max_length = 0;\n #Initialize Values, now I always initialize session from scratch but store things in global so I load global\n if session_id == 'globalSess':\n try:\n # self.documents = pd.read_csv(self.sess_folder + '/documents.csv',encoding='utf-8',index_col='index')\n self.documents = pd.read_json(self.sess_folder + '/documents.json')\n # self.documents = self.read_csv()\n except ValueError:\n self.documents = pd.DataFrame()\n else:\n self.documents = pd.DataFrame()\n ##LOAD THE REST OF THE DATA MAYBE I DONT NEED THIS NEED TO THINK ABOUT IT I STORE EVERYTHING IN DOCS EXCEPT THE SESS TOPICS THAT I CALCULATE EVERY TIME\n try:\n self.topics = pd.read_csv(self.sess_folder + '/topics.csv',encoding='utf-8')\n except IOError:\n self.topics = pd.DataFrame()\n try:\n self.authorList = pd.read_csv(self.sess_folder + '/authors.csv',encoding='utf-8',index_col='index')\n except IOError:\n self.authorList = pd.DataFrame()\n try:\n self.words = pd.read_csv(self.sess_folder + '/words.csv',encoding='utf-8')\n except IOError:\n self.words = pd.DataFrame()\n\n def addDoc(self, doc):\n \"\"\" Function to add a new document to the session \"\"\"\n doc_to_add = doc.create_document_msg()\n document = pd.DataFrame([doc_to_add],columns=doc_to_add.keys(),index=[doc_to_add['globalID']])\n self.documents = self.documents.append(document)\n\n def storeSessData(self):\n '''Store Session'''\n try:\n self.documents.to_json(self.sess_folder + '/documents.json')\n except ValueError:\n print('')\n pdb.set_trace()\n def returnDoc(self,doc):\n \"\"\"Returns a specific document from a session\"\"\"\n return self.documents.loc[doc]\n \n def returnDocsBy(self, type):\n \"\"\"Returns the documents of session ordered by type passed (authors and years) \"\"\"\n docs_by_array = []\n if type == 'author':\n if isinstance(self.authorList.index,list):\n for each_author in self.authorList.index:\n element = {\n 'author':each_author,\n 'Paper_Ids': self.authorList.loc[each_author]['Paper_Ids'] \n }\n docs_by_array.append(element)\n else: #Only one paper\n element = {\n 'author':self.authorList.index,\n 'Paper_Ids': self.authorList.loc[self.authorList.index]['Paper_Ids'] \n }\n docs_by_array.append(element)\n return docs_by_array\n\n \n def docInSess(self,doc):\n \"\"\"Aux function to show if a document is already in a session\"\"\"\n try:\n is_doc_in_sess = self.documents['globalID'].isin([doc]).any()\n except KeyError:\n is_doc_in_sess = False\n return is_doc_in_sess\n\n def addDocTopics(self, doc):\n for topic in doc.topics:\n self.topics.append(topic)\n \n def addAuthor(self, author,doc_id):\n \"\"\"Function to add author to session authorList\"\"\"\n try:\n papers_in_collection = author['Papers_in_collection']\n self.authorList.loc[author.Author, 'Papers_in_collection'] = papers_in_collection + 1\n paper_id_array = []\n paper_id_array.append(self.authorList.loc[author.Author, 'Paper_Ids'])\n paper_id_array.append(doc_id)\n self.authorList.loc[author.Author, 'Paper_Ids'] = paper_id_array.append(doc_id)\n\n except KeyError:\n author['Papers_in_collection'] = 1\n author['Paper_Ids'] = [doc_id]\n self.authorList = self.authorList.append(author)\n \n def searchAuthor(self, author):\n \"\"\" Aux Function to search for an author in the session returns True if in Session and False if not\"\"\"\n # pdb.set_trace()\n try:\n self.authorList.loc[author]\n is_author = True\n except KeyError:\n is_author = False\n return is_author\n\n def returnAuthor(self, author):\n author_name = author['firstName'] + ' ' + author['lastName']\n return self.authorList.loc[author_name]\n \n \n def get_topics_by(self,data,organized_by):\n \"\"\"Calculates the topics of the session organized by authors or years\"\"\"\n if organized_by == 'author':\n df = pd.DataFrame()\n #Get papers for each author\n # pdb.set_trace()\n for each_author in data:\n for each_paper in each_author['Paper_Ids']:\n # pdb.set_trace()\n df = df.append(self.returnDoc(each_paper))\n return self.get_topics(df)\n\n\n def get_topics(self,doc_dictionary): #Good One\n \"\"\"Returns Topics object and Words Object from documents df passed\"\"\"\n topics_data = topic_extractor(doc_dictionary,'session')\n self.topics = topics_data['topics']\n self.topic_params = topics_data['topic_params']\n self.words = topics_data['lvls_df']\n return {'topics':self.topics,'words':self.words}\n \n \"\"\"Function to calculate 2D projections of Paper Vectors in session\"\"\"\n def train_fit_UMAP_2D(self,doc_dictionary):\n if self.UMAP == False:\n self.UMAP = umap.UMAP(n_neighbors=3, n_components=2, metric='euclidean')\n self.topic_UMAP = umap.UMAP(n_neighbors=3, n_components=2, metric='euclidean')\n #Filter False Values\n clean_bert_vectors = doc_dictionary['abstract_vector'][doc_dictionary['abstract_vector']!= False]\n # clean_bert_abstracts= doc_dictionary['abstract_vector'][doc_dictionary['abstract_vector']!= False]\n # clean_bert_conclusions = doc_dictionary['conclusion_vector'][doc_dictionary['conclusion_vector']!= False]\n clean_topic_vectors = doc_dictionary['topics_vector'][doc_dictionary['topics_vector']!=False]\n #Since text are different sizes we need to set them to the same size. We extend smaller vectors to the size of the longest by duplicating its content.\n if self.text_max_length == 0:\n text_lenght = clean_bert_vectors.apply(lambda x: len(x))\n self.text_max_length = text_lenght.max()\n for index, doc_vector in clean_bert_vectors.iteritems():\n if len(doc_vector) > self.text_max_length:\n print (\"document\" + index + \"has a longer size than any in previous\")\n doc_vector = doc_vector[:self.text_max_length]\n if len(doc_vector) != self.text_max_length:\n while True:\n \n size_to_extend = self.text_max_length - len(doc_vector)\n doc_vector.extend(doc_vector[:size_to_extend])\n if len(doc_vector) == self.text_max_length:\n break\n #topics have different sizes too\n if self.topic_min_length == 0:\n topic_length = clean_topic_vectors.apply(lambda x: len(x))\n self.topic_min_length = topic_length.min()\n clean_topic_vectors = clean_topic_vectors.apply(lambda x: x[:self.topic_min_length])\n #since abstract and conclusions are different sizes I need to set them all to same size I find smallest and cut the rest\n # if self.abstract_conclusion_min_length == 0:\n # abstract_lenght = clean_bert_abstracts.apply(lambda x: len(x))\n # conclusion_length = clean_bert_conclusions.apply(lambda x: len(x))\n # abstract_min_length = abstract_lenght.min()\n # conclusion_min_length = conclusion_length.min()\n # self.abstract_conclusion_text_min_length = min([abstract_min_length,conclusion_min_length])\n # clean_bert_abstracts = clean_bert_abstracts.apply(lambda x: x[:self.abstract_conclusion_text_min_length])\n # clean_bert_conclusions = clean_bert_conclusions.apply(lambda x: x[:self.abstract_conclusion_text_min_length])\n #Calculate Vectors\n # pdb.set_trace()\n if self.encoder == False :\n print('Encoder has not been trained yet so Using UMAP for fitting')\n vectors_list = clean_bert_vectors.values.tolist()\n topics_list = clean_topic_vectors.values.tolist()\n self.UMAP = self.UMAP.fit(vectors_list)\n self.topic_UMAP = self.topic_UMAP.fit(topics_list)\n vec_2d = self.UMAP.transform(vectors_list)\n vec_topic_2d = self.topic_UMAP.transform(topics_list)\n else:\n print('Using Enconder to Fit')\n papers_to_fit_indexes = doc_dictionary[doc_dictionary.isna().any(axis=1)].index.values.tolist()\n papers_to_fit = clean_bert_vectors.loc[papers_to_fit_indexes]\n # pdb.set_trace()\n try:\n new_projections = self.encoder.transform(np.array(papers_to_fit.values.tolist()))\n # pdb.set_trace()\n except ValueError:\n print('error')\n pdb.set_trace()\n vec_2d = np.append(self.vectors2D,new_projections,axis=0)\n papers_to_fit_topics = clean_topic_vectors.loc[papers_to_fit_indexes]\n new_projections = self.topic_UMAP.transform(papers_to_fit_topics.values.tolist())\n vec_topic_2d = np.append(self.vectors2D_topics,new_projections,axis=0)\n # vec_2d = self.UMAP.transform(clean_bert_vectors.values.tolist())\n # vec_topic_2d = self.topic_UMAP.transform(clean_topic_vectors.values.tolist())\n #Store values for subsequent runs\n self.vectors2D = vec_2d\n self.vectors2D_topics = vec_topic_2d\n # SECTIONS PART COMMENTED RIGHT NOW I HAVE TO SEE IF I WILL USE THIS OR NOT\n # #put abstract and conclusion together to project \n # abstract_and_conclusion_to_project = clean_bert_abstracts.append(clean_bert_conclusions)\n # #convert to DataFrame to keep indexes when I merge below\n # pdb.set_trace()\n # abstract_and_conclusion_to_project_df = pd.DataFrame(abstract_and_conclusion_to_project, columns=['original_vector'])\n # abstract_and_conclusion_2D = fit.fit_transform(abstract_and_conclusion_to_project.values.tolist()) \n # #add to Dataframe \n # abstract_and_conclusion_to_project_df['2D'] = abstract_and_conclusion_2D.tolist()\n # #separate them to put back into pandas\n # abstract_vec_2d = abstract_and_conclusion_to_project_df['2D'].iloc[ :len(clean_bert_abstracts)]\n # conclusion_vec_2d = abstract_and_conclusion_to_project_df['2D'].iloc[len(clean_bert_abstracts): ]\n #add to pandas columns\n doc_dictionary['vec_2d'] = vec_2d.tolist()\n doc_dictionary['vec_topic_2d']= vec_topic_2d.tolist()\n # doc_dictionary['abstract_2d'] = abstract_vec_2d\n # doc_dictionary['conclusion_2d'] = conclusion_vec_2d\n #change NA for false\n doc_dictionary['vec_2d'].fillna(False)\n doc_dictionary['vec_topic_2d'].fillna(False)\n # doc_dictionary['abstract_2d'].fillna(False)\n # doc_dictionary['conclusion_2d'].fillna(False)\n return doc_dictionary\n\n # conclusion_vec_2d.tolist()\n \n def get_years(self):\n return self.documents.groupby('year')['year'].count()\n\n def assign_topics_to_documents(self):\n \"\"\"Function to assign session topics to doc topics\"\"\"\n def calculate_cosine_similarity(vect1,vect2,size):\n vect1 = np.array(vect1).reshape(1,size)\n vect2 = np.array(vect2).reshape(1,size)\n return cosine_similarity(vect1,vect2)\n \n sess_topic_params = self.topic_params\n # pdb.set_trace()\n for each_document in self.documents.iterrows():\n doc_topic_params_df = pd.DataFrame(each_document[1]['topic_params'])\n similarity_vector = []\n for each_topic in doc_topic_params_df.iterrows():\n #We compare each topic in paper with session_topics if its above a threshold we assign the topic to paper\n # pdb.set_trace()\n similarity = sess_topic_params['vector300'].apply(calculate_cosine_similarity,vect2=each_topic[1]['vector300'],size=300)\n #apply threshold\n similarity = similarity.apply(lambda x: x[0][0] > 0.7) #returns true false vectors\n similarity_vector.append(similarity)\n # pdb.set_trace()\n #sum(similarity_vector) collapses Trues and Falses but several trues are summed. I changed those to be 1.\n collapsed_similarity = sum(similarity_vector)\n collapsed_similarity = collapsed_similarity.where(collapsed_similarity==0,1) #Returns vector of ceros and ones\n sess_topic_params[each_document[1]['globalID']] = collapsed_similarity * sess_topic_params['weight']\n # pdb.set_trace()\n\n def update_model(self,new_data):\n self.already_encoded_papers = new_data\n # pdb.set_trace()\n #loop list of papers\n for index, row in new_data.iterrows():\n #Get from paper in session\n this_paper = self.documents.loc[row['key']]\n #Set new x,y coordinates from paper in session\n this_paper.vec_2d[0] = new_data['x'][index]\n this_paper.vec_2d[1] = new_data['y'][index]\n #Get 300Vectors and 2D Vectors\n clean_bert_vectors = self.documents['abstract_vector']\n #Since text are different sizes we need to set them to the same size. We extend smaller vectors to the size of the longest by duplicating its content.\n # text_lenght = clean_bert_vectors.apply(lambda x: len(x))\n # self.text_max_length = text_lenght.max()\n # for index, doc_vector in clean_bert_vectors.iteritems():\n # if len(doc_vector) > self.text_max_length:\n # print (\"document\" + index + \"has a longer size than any in previous\")\n # doc_vector = doc_vector[:self.text_max_length]\n # # pdb.set_trace()\n # if len(doc_vector) != self.text_max_length:\n # while True:\n # # pdb.set_trace()\n # size_to_extend = self.text_max_length - len(doc_vector)\n # doc_vector.extend(doc_vector[:size_to_extend])\n # if len(doc_vector) == self.text_max_length:\n # break\n vec_2d = np.array(self.documents['vec_2d'].values.tolist())\n self.train_encoder(clean_bert_vectors,vec_2d)\n # pdb.set_trace()\n \n def train_encoder(self,vectors,vec_2d):\n vectors_list = np.array(vectors.values.tolist())\n #Train Encoder\n vector_size = self.text_max_length\n self.encoder = Encoder(vector_size,2)\n self.encoder.fit(vectors_list,vec_2d)\n new_vec_2d = self.encoder.transform(vectors_list)\n # pdb.set_trace()\n #add to pandas columns\n # self.documents.loc[self.already_encoded_papers['key']]['vec_2d'] = new_vec_2d.tolist()\n self.documents['vec_2d'] = new_vec_2d.tolist()\n self.vectors2D = new_vec_2d\n\n ","sub_path":"classes/session_class.py","file_name":"session_class.py","file_ext":"py","file_size_in_byte":16190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"560137313","text":"# -*- coding: utf-8 -*-\n\n# prod/dev/test\nENV = 'prod'\n\nimport importlib\nenv = importlib.import_module('config.env_{}'.format(ENV)).env\n\n# MYSQL_CONFIG\n# MYSQL_CONFIG = {\n# 'user': env['mysql']['user'],\n# 'password': env['mysql']['password'],\n# 'host': env['mysql']['host'],\n# 'database': env['mysql']['database']\n# }\n\n# REDIS_CONFIG\nREDIS_CONFIG = {\n 'host' : env['redis']['host'],\n 'port' : env['redis']['port'],\n 'db' : env['redis']['db']\n}\n\nEXPIRE_TIME = 3600\n\n# MONGO_CONFIG\nMONGO_CONFIG = {\n 'host': env['mongo']['host'],\n 'port': env['mongo']['port'],\n 'db': env['mongo']['db'],\n 'collection': env['mongo']['collection']\n}\n","sub_path":"config/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"225470644","text":"def convert_to_numeric(catagorical):\n classes = catagorical.unique()\n classes_mapping = {cls: i for i, cls in enumerate(classes)}\n classes_inv_mapping = {i: cls for i, cls in enumerate(classes)}\n classes_numeric = catagorical.apply(lambda cls: classes_mapping[cls])\n return classes_numeric, classes_inv_mapping\n\nfig, ax = plt.subplots(figsize=(6, 6))\n\ncatagorical = balance_non_zero[\"Student\"]\ny = balance_non_zero['Balance']\n\nnumeric, classes_mapping = convert_to_numeric(catagorical)\n\nnoise = np.random.uniform(-0.3, 0.3, size=len(catagorical))\nax.scatter(numeric + noise, y, color=\"grey\", alpha=0.5)\n\nbox_data = list(y.groupby(catagorical))\nax.boxplot([data for _, data in box_data], positions=range(len(box_data)))\nax.set_xticks(list(classes_mapping))\nax.set_xticklabels(list(catagorical.unique()))\n\nax.set_xlabel(\"Student?\")\nax.set_ylabel(\"Balance\")\nax.set_title(\"Univariate Effect of Student? on Bank Balance\")\n","sub_path":"dsi-practical-linear-regression/src/categorical_plot.py","file_name":"categorical_plot.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"217495168","text":"'''\nCreated on Oct 21, 2012\n\n@author: olehp\n'''\n\nclass Entry(object):\n '''\n classdocs\n '''\n \n entry_id = None\n source = None\n time = None\n quotes = []\n links = [] \n callbacks = []\n\n def __init__(self, entry_id, source, time, quotes, links):\n '''\n Initializes dataset entry.\n '''\n self.entry_id = int(entry_id)\n self.source = source\n self.time = time\n self.quotes = quotes\n self.links = links\n \n def toXml(self):\n string = \"\"\n string+= \"\"+ self.source +\"\"\n string+= \"\"\n for quote in self.quotes:\n string+=\"\"+quote+\"\"\n for link in self.links:\n string+=\"\"+link+\"\"\n string+=\"\"\n return string\n \n \n def addCallback(self, func):\n '''\n Adds callback function to entry.\n ''' \n self.callbacks.append(func)","sub_path":"lab1/Memetracker/Entry.py","file_name":"Entry.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"305706014","text":"\n\nfrom xai.brain.wordbase.verbs._vindicate import _VINDICATE\n\n#calss header\nclass _VINDICATES(_VINDICATE, ):\n\tdef __init__(self,): \n\t\t_VINDICATE.__init__(self)\n\t\tself.name = \"VINDICATES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"vindicate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_vindicates.py","file_name":"_vindicates.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"72882093","text":"import json\n\n\ndef parse_win_chassis_specs(the_dir: str):\n with open(f\"{the_dir}/chassis.win\", \"r\") as file:\n data = json.load(file)\n object = [\n {\n \"features\": {\n \"brand\": data[\"Manufacturer\"],\n \"sn\": data[\"SerialNumber\"],\n },\n \"type\": \"case\",\n }\n ]\n return object\n\n\ndef parse_win_cpu_specs(the_dir: str):\n architectures = {\n 0: \"x86-32\",\n 1: \"mips\",\n 2: \"alpha\",\n 3: \"powerpc\",\n 6: \"ia64\",\n 9: \"x86-64\",\n }\n object = []\n with open(f\"{the_dir}/lscpu.win\", \"r\") as file:\n data = json.load(file)\n object.append(\n {\n \"brand\": data[\"Manufacturer\"],\n \"model\": data[\"Name\"],\n \"features\": {\n \"type\": \"cpu\",\n \"isa\": architectures[data[\"Architecture\"]],\n \"core-n\": data[\"NumberOfCores\"],\n \"thread-n\": data[\"ThreadCount\"],\n \"frequency-hertz\": int(data[\"MaxClockSpeed\"]) * 1000000,\n },\n \"type\": \"cpu\",\n }\n )\n with open(f\"{the_dir}/graphics.win\", \"r\") as file:\n data = json.load(file)\n for entry in data:\n if \"Service\" in entry and entry[\"Service\"] == \"igfx\":\n object[0][\"features\"][\"integrated-graphics-brand\"] = entry[\"Manufacturer\"]\n object[0][\"features\"][\"integrated-graphics-model\"] = entry[\"Name\"]\n break\n return object\n\n\ndef parse_win_ram_specs(the_dir: str):\n with open(f\"{the_dir}/dimms.win\", \"r\") as file:\n data = json.load(file)\n object = []\n for entry in data:\n object.append(\n {\n \"brand\": entry[\"Manufacturer\"],\n \"model\": entry[\"PartNumber\"],\n \"features\": {\n \"frequency-hertz\": entry[\"Speed\"] * 1000000,\n \"capacity-byte\": entry[\"Capacity\"],\n \"ram-type\": \"\",\n \"ram-ecc\": \"\",\n \"ram-timings\": \"\",\n \"sn\": entry[\"SerialNumber\"],\n },\n \"type\": \"ram\",\n }\n )\n return object\n\n\ndef parse_win_motherboard_specs(the_dir: str):\n with open(f\"{the_dir}/baseboard.win\", \"r\") as file:\n data = json.load(file)\n object = [\n {\n \"brand\": data[\"Manufacturer\"],\n \"model\": data[\"Product\"],\n \"features\": {\n \"parallel-ports-n\": 0,\n \"usb-ports-n\": 0,\n \"mini-jack-ports-n\": 0,\n \"vga-ports-n\": 0,\n \"serial-ports-n\": 0,\n \"sata-ports-n\": 0,\n \"ide-ports-n\": 0,\n \"ps2-ports-n\": 0,\n \"ethernet-ports-1000m-n\": 0,\n },\n \"type\": \"motherboard\",\n }\n ]\n with open(f\"{the_dir}/lspci.win\", \"r\") as file:\n data = json.load(file)\n for entry in data:\n pnp_class = entry[\"PNPClass\"]\n if pnp_class == \"USB\":\n object[0][\"features\"][\"usb-ports-n\"] += 1\n continue\n elif pnp_class == \"USB\":\n object[0][\"features\"][\"usb-ports-n\"] += 1\n continue\n elif pnp_class == \"AudioEndpoint\":\n object[0][\"features\"][\"mini-jack-ports-n\"] += 1\n continue\n elif pnp_class == \"DiskDrive\":\n object[0][\"features\"][\"sata-ports-n\"] += 1\n continue\n return object\n","sub_path":"parsers/windows_parser.py","file_name":"windows_parser.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"235289069","text":"'''\n\tThis is the NHL crawler. \n\nScattered throughout are TODO tips on what to look for.\n\nAssume this job isn't expanding in scope, but pretend it will be pushed into production to run \nautomomously. So feel free to add anywhere (not hinted, this is where we see your though process..)\n * error handling where you see things going wrong. \n * messaging for monitoring or troubleshooting\n * anything else you think is necessary to have for restful nights\n'''\nimport logging\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass\nimport boto3\nimport requests\nimport pandas as pd\nfrom botocore.config import Config\nfrom dateutil.parser import parse as dateparse\nimport sys\n\n\nlogging.basicConfig(level=logging.INFO)\nLOG = logging.getLogger(__name__)\n\nclass NHLApi:\n SCHEMA_HOST = \"https://statsapi.web.nhl.com/\"\n VERSION_PREFIX = \"api/v1\"\n\n def __init__(self, base=None):\n self.base = base if base else f'{self.SCHEMA_HOST}/{self.VERSION_PREFIX}'\n\n\n def schedule(self, start_date: datetime, end_date: datetime) -> dict:\n ''' \n returns a dict tree structure that is like\n \"dates\": [ \n {\n \" #.. meta info, one for each requested date \",\n \"games\": [\n { #.. game info },\n ...\n ]\n },\n ...\n ]\n '''\n return self._get(self._url('schedule'), {'startDate': start_date.strftime('%Y-%m-%d'), 'endDate': end_date.strftime('%Y-%m-%d')})\n\n def boxscore(self, game_id):\n '''\n returns a dict tree structure that is like\n \"teams\": {\n \"home\": {\n \" #.. other meta \",\n \"players\": {\n $player_id: {\n \"person\": {\n \"id\": $int,\n \"fullName\": $string,\n #-- other info\n \"currentTeam\": {\n \"name\": $string,\n #-- other info\n },\n \"stats\": {\n \"skaterStats\": {\n \"assists\": $int,\n \"goals\": $int,\n #-- other status\n }\n #-- ignore \"goalieStats\"\n }\n }\n },\n #...\n }\n },\n \"away\": {\n #... same as \"home\" \n }\n }\n\n See tests/resources/boxscore.json for a real example response\n '''\n url = self._url(f'game/{game_id}/boxscore')\n return self._get(url)\n\n def _get(self, url, params=None):\n try:\n response = requests.get(url, params=params)\n response.raise_for_status()\n except requests.exceptions.HTTPError as ehtp:\n print (\"Http Error: \",ehtp)\n raise SystemExit(ehtp)\n except requests.exceptions.ConnectionError as econ:\n print (\"Connection Error: \",econ)\n raise SystemExit(econ)\n except requests.exceptions.Timeout as etim:\n print (\"Timeout Error: \",etim)\n raise SystemExit(etim)\n except requests.exceptions.RequestException as ex:\n print (\"Error in API Request: \",ex)\n raise SystemExit(ex)\n return response.json()\n\n def _url(self, path):\n return f'{self.base}/{path}'\n\n@dataclass\nclass StorageKey():\n def __init__(self, gameid, gamedate):\n self._gameid = gameid\n self._gamedate = gamedate.strftime('%Y%m%d')\n\n def key(self):\n ''' renders the s3 key for the given set of properties '''\n return f'{self._gamedate}_{self._gameid}.csv'\n\nclass Storage():\n def __init__(self, dest_bucket, s3_client):\n self._s3_client = s3_client\n self.bucket = dest_bucket\n\n def store_game(self, key: StorageKey, game_data) -> bool:\n self._s3_client.put_object(Bucket=self.bucket, Key=key.key(), Body=game_data)\n return True\n\nclass Crawler():\n def __init__(self, api: NHLApi, storage: Storage):\n self.api = api\n self.storage = storage\n\n def crawl(self, startdate: datetime, enddate: datetime) -> None:\n '''\n Crawl for player scoring stats.\n Writes CSV files to S3 Bucket for NHL Games in date range specified (inclusive).\n Files partitioned by Date and Game ID.\n '''\n schedule = self.api.schedule(startdate, enddate)\n \n ##iterate over game dates to properly partition\n if schedule is not None:\n for day in schedule.get(\"dates\"):\n gamedate = datetime.strptime(day.get(\"date\"),'%Y-%m-%d')\n\n logging.info(f'Processing games for {gamedate}')\n games_df = pd.DataFrame()\n games_df = games_df.append(pd.json_normalize(day.get(\"games\")), ignore_index = True)\n \n column_names = [\"player_person_id\", \"player_person_currentTeam_name\", \"player_person_fullName\", \"player_stats_skaterStats_assists\", \"player_stats_skaterStats_goals\", \"side\"]\n\n for index, row in games_df.iterrows():\n gameid = row[\"gamePk\"]\n\n stats = self.api.boxscore(gameid)\n stats_df = pd.DataFrame()\n\n for side in ('home','away'):\n teamname = stats.get(\"teams\").get(side).get(\"team\")[\"name\"]\n players = stats.get(\"teams\").get(side).get(\"players\").keys()\n\n for p in players:\n if stats.get(\"teams\").get(side).get(\"players\").get(f'{p}').get(\"stats\").get(\"skaterStats\") is not None:\n playername = stats.get(\"teams\").get(side).get(\"players\").get(f'{p}').get(\"person\").get(\"fullName\")\n goals,assists = [stats.get(\"teams\").get(side).get(\"players\").get(f'{p}').get(\"stats\").get(\"skaterStats\").get(k) for k in [\"goals\",\"assists\"]]\n \n playerstats = pd.Series([p.replace('ID',''),teamname,playername,assists,goals,side], index=column_names)\n stats_df = stats_df.append(playerstats, ignore_index=True)\n \n s3Key = StorageKey(gameid,gamedate)\n \n logging.info(f'Writing file: {s3Key.key()}')\n\n self.storage.store_game(s3Key, stats_df[column_names].to_csv(index=False))\n else:\n logging.info(f'No games found for date range {startdate} - {enddate}')\n\n \ndef main():\n import os\n import argparse\n\n parser = argparse.ArgumentParser(description='NHL Stats crawler')\n parser.add_argument('--start_date',\n required=True,\n type=str,\n help='Set start date to begin to retrieve data (inclusive). Format: yyyymmdd')\n parser.add_argument('--end_date',\n required=True,\n type=str,\n help='Set end date to stop retrieving data (inclusive). Format: yyyymmdd')\n args = vars(parser.parse_args())\n\n dest_bucket = os.environ.get('DEST_BUCKET', 'output')\n start_date = dateparse(args['start_date'])\n end_date = dateparse(args['end_date'])\n\n api = NHLApi()\n s3client = boto3.client('s3', config=Config(signature_version='s3v4'), endpoint_url=os.environ.get('S3_ENDPOINT_URL'))\n storage = Storage(dest_bucket, s3client)\n crawler = Crawler(api, storage)\n crawler.crawl(start_date, end_date)\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as ex:\n print(f'exception: {ex}')\n sys.exit(1)\n\n","sub_path":"nhldata/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"458262207","text":"import p1_loadData as data\nimport p6_mostSimilarityUsers as msUsers\nimport pandas as pd\nimport numpy as np\nimport time\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport performance as pf\n\n#用于求取推荐电影函数\n#user为目标用户,n为相似用户数量(从前n个最相似的用户中获得推荐信息),m为获取的推荐电影数量\ndef getRecommendMovies(user,movieData,ratingsData,situation,n=4,m=10):\n\n n = 10 #取前n位最相似的用户用于推荐电影\n topN = msUsers.getMostSimilarUsers(user,n,ratingsData,situation) #调用getFiveMostSimilarUsers接口获取具体相似度最高的前n位用户\n\n candidateMoviesSet = {\"Rating\":[],\"MovieID\":[]} #通过这n位相似用户观看过的电影推荐给此用户\n for i in topN.index:\n simi_user = topN.loc[i][\"UserID\"]\n commonMovie = topN.loc[i][\"commonMovieID\"] #获取到当前用户和当前相似用户所观看过的相同电影\n simi_user_data = ratingsData[ratingsData['UserID'] == simi_user] # 获取用户i的评级数据\n\n for movie in commonMovie: #从推荐用户所观看过的电影中删除当前用户已经观看过的电影(不能向用户推荐其已经观看过的电影)\n simi_user_data = simi_user_data.drop(simi_user_data[simi_user_data[\"MovieID\"]==movie].index)\n\n simi_user_data[\"Rating\"]*=topN.loc[i][\"degree\"] #将每个推荐用户对当前用户没有观看过的电影所打的评级乘上两个用户的相似度,最后用于所有电影项用户推荐顺序的依据\n\n #recommendMoviesDataSet用于收集待推荐电影数据\n candidateMoviesSet[\"Rating\"] = np.append(candidateMoviesSet[\"Rating\"],simi_user_data[\"Rating\"].values)\n candidateMoviesSet[\"MovieID\"] = np.append(candidateMoviesSet[\"MovieID\"],simi_user_data[\"MovieID\"].values)\n\n candidateMoviesSet = pd.DataFrame(candidateMoviesSet)\n\n m = 10 #只取排名前m的电影推荐给用户\n candidateMoviesSet = candidateMoviesSet.sort_values(by=\"Rating\",ascending=False)[:m]\n\n #recommendMoviesSet用于保存最终确定的要推荐的电影的所有信息\n recommendMoviesSet = movieData[movieData[\"MovieID\"]==candidateMoviesSet[\"MovieID\"].values[0]]\n for movieID in candidateMoviesSet[\"MovieID\"].values[1:]: #从电影数据中得到相应MovieID的所有信息\n set = movieData[movieData[\"MovieID\"]==movieID]\n recommendMoviesSet = recommendMoviesSet.append(set)\n\n recommendMoviesSet.index = np.arange(0,m,1)\n return recommendMoviesSet,candidateMoviesSet[\"Rating\"].values\n\n#接口测试\nif __name__ == \"__main__\":\n #user = int(input(\"Please input the user ID: \")) # 输入用户\n\n movieData = data.getSourceData(\"movieData\") # 获取电影数据\n ratingsData = data.getSourceData(\"ratingsData\") # 获取电影评级数据\n\n start = time.time()\n\n T_WC = []\n T_CC = []\n T_Cover = []\n count = 0\n uus = np.arange(50,151,1)#np.random.randint(1, 6040, size=100)\n for situation in [\"r\",\"rp\",\"rd\",\"rpd\"]:\n WC = []\n CC = []\n Cover = []\n\n for u in uus:#range(100,201):\n recommondMovies,rating = getRecommendMovies(u,movieData,ratingsData,situation)\n\n user_rd = ratingsData[ratingsData[\"UserID\"] == u]\n\n user_rd = user_rd[user_rd[\"Rating\"] > 3]\n\n user_rd.index = np.arange(0, user_rd.shape[0])\n\n movies = pd.DataFrame({\"MovieID\": [], \"Title\": [], \"Genres\": []})\n for m in user_rd[\"MovieID\"].values:\n mo = movieData[movieData[\"MovieID\"] == m]\n movies = movies.append(mo)\n\n movies.index = np.arange(0, movies.shape[0])\n ori_x = []\n ori_y = []\n for i in range(user_rd.shape[0]):\n for g in movies[\"Genres\"][i].split(\"|\"):\n if not g in ori_x:\n ori_x.append(g)\n ori_y.append(user_rd[\"Rating\"][i])\n else:\n index = ori_x.index(g)\n ori_y[index] += user_rd[\"Rating\"][i]\n\n res_x = []\n res_y = []\n for i in range(recommondMovies.shape[0]):\n for g in recommondMovies[\"Genres\"][i].split(\"|\"):\n if not g in res_x:\n res_x.append(g)\n res_y.append(rating[i])\n else:\n index = res_x.index(g)\n res_y[index] += rating[i]\n\n res_y = list(np.array(res_y) / np.max(res_y))\n\n wc, cover, cc = pf.getPerformance(res_x,res_y,ori_x,ori_y)\n\n WC.append(wc)\n CC.append(cc)\n Cover.append(cover)\n print(u)\n\n print(\"--------\",count,\"---------\")\n count+=1\n\n T_WC.append(WC)\n T_CC.append(CC)\n T_Cover.append(Cover)\n\n print(\"WC:\",np.mean(T_WC,axis=1))\n print(\"CC:\",np.mean(T_CC,axis=1))\n print(\"Cover:\",np.mean(T_Cover,axis=1))\n # plt.bar(genres, score,color=\"w\",edgecolor=\"k\",hatch=\"/////\")\n # plt.xlabel(\"电影类别\", fontsize=19)\n # plt.ylabel(\"总得分\", fontsize=19)\n # plt.tick_params(labelsize=12.5)\n # plt.rcParams['font.sans-serif'] = ['SimHei']\n # plt.rcParams['axes.unicode_minus'] = False\n # plt.show()","sub_path":"MovieRecommendation/p7_recommendMovies.py","file_name":"p7_recommendMovies.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"483582637","text":"from webargs import fields\n\nfrom project.api.models import db, WebsiteDuplicated\nfrom project.api.schemas import OneOf, length_validator\nfrom project.api.exceptions.customs import RecordNotFound\n\n\ndef id_in_db(id):\n if not db.session.query(WebsiteDuplicated).filter_by(id=id).first():\n raise RecordNotFound('无此数据')\n\n\ndelete_args = {\n 'ids': fields.List(fields.Int(validate=id_in_db), required=True)\n}\n\nrestore_args = {\n 'ids': fields.List(fields.Int(validate=id_in_db), required=True)\n}\n\nquery_args = {\n 'page': fields.Int(missing=0),\n 'size': fields.Int(missing=25, validate=length_validator),\n 'order': fields.Nested({\n 'field': fields.Str(missing='create_time'),\n 'direction': fields.Str(missing='desc', validate=OneOf(['asc', 'desc']))\n }, missing={}),\n 'filter': fields.Nested({\n 'url': fields.Str(),\n 'title': fields.Str(),\n 'effective_url': fields.Str()\n }, missing={})\n}\n","sub_path":"project/api/schemas/website_duplicated.py","file_name":"website_duplicated.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"79924369","text":"# Documentation is like sex.\n# When it's good, it's very good.\n# When it's bad, it's better than nothing.\n# When it lies to you, it may be a while before you realize something's wrong.\n# https://github.com/quentinsf/qhue\n\nfrom typing import Callable, Optional\n\nfrom qhue import Bridge, QhueException, create_new_username\n\n# the IP address of your bridge\nBRIDGE_IP = \"192.168.1.51\"\n\n# the path for the username credentials file\nCRED_FILE_PATH = r\"D:\\Lesko\\workspace\\householdHub\\scrambledeggs\\qhue_username.txt\"\n\n\nclass Hue:\n\n def __init__(self, bridge_ip: str, credentials: Optional[str] = None):\n self.bridge_ip = bridge_ip\n self.credentials = credentials\n\n self.bridge = None\n self.__lights = {}\n\n def register_hue(self, save_credentials_cb: Optional[Callable] = None):\n if self.credentials is None:\n while True:\n try:\n self.credentials = create_new_username(BRIDGE_IP)\n if save_credentials_cb is not None:\n save_credentials_cb(self.credentials)\n break\n except QhueException as err:\n print(\"Error occurred while creating a new username: {}\".format(err))\n\n def __create_bridge(self):\n if self.bridge is None:\n self.bridge = Bridge(self.bridge_ip, self.credentials)\n\n def __find_all_lights(self):\n self.__create_bridge()\n lights = self.bridge.lights\n for key, val in lights().items():\n self.__lights[int(key)] = lights[key]\n\n @property\n def lights(self) -> dict:\n self.__find_all_lights()\n return self.__lights\n\n def list_devices(self):\n for hue_num, light in self.lights.items():\n print(f\"{hue_num} - {light}\")\n for key, val in light().items():\n print(f\"\\t{key} - {val}\")\n\n\nif __name__ == \"__main__\":\n with open(CRED_FILE_PATH, \"r\") as cred_file:\n username = cred_file.read()\n\n\n def p(tes):\n print(tes)\n\n\n h = Hue(BRIDGE_IP, credentials=username)\n\n h.list_devices()\n","sub_path":"app/common/hue/hue.py","file_name":"hue.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"364260926","text":"import random\n\ndef find_fake(lst,start,end):\n if end - start == 1:\n return [start,end]\n if start == end:\n return end\n length = end-start+1\n half = length//2\n aver = lst[end] * half\n if length % 2 == 0:\n weight1 = sum(lst[start:start+half])\n weight2 = sum(lst[start+half:end+1])\n if aver == weight2:\n return find_fake(lst,start,start+half-1)\n else:\n return find_fake(lst,start+half,end)\n else:\n weight1 = sum(lst[start:start+half])\n weight2 = sum(lst[start+half:end])\n if weight1 == weight2:\n return end\n else:\n if weight1 == aver:\n return find_fake(lst,start+half,end)\n else:\n return find_fake(lst,start,start+half-1)\n\n\n\n\ndef main():\n L = []\n for i in range(0,100):\n L.append(10)\n temp = random.randint(0,99)\n L[temp] = 9\n print(temp)\n\n x = find_fake(L,0,99)\n\n if type(x) == int:\n print(x)\n elif len(L) == 2:\n print(\"Error\")\n else:\n for i in range(len(L)):\n if i != x[0] and i != x[1]:\n if L[i] == L[x[0]]:\n print(x[1])\n break\n else:\n print(x[0])\n break\n\nmain()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"310028120","text":"import os\nfrom datetime import datetime\n\nfrom django.core.validators import FileExtensionValidator\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models import Sum\nfrom django.dispatch import receiver\nfrom django.utils.translation import gettext as _\n\nfrom _main.utils import build_filename, rename_file, delete_file, h_encode\nfrom master.models import Pegawai, Status, Provinsi, Kabupaten, Kecamatan, Kelurahan\n\nATAS_NAMA = (\n ('PN Yang Bersangkutan', 'PN Yang Bersangkutan'),\n ('Pasangan / Anak', 'Pasangan / Anak'),\n ('Lainnya', 'Lainnya'),\n)\n\nASAL_USUL = (\n ('Hasil Sendiri', 'Hasil Sendiri'),\n ('Warisan', 'Warisan'),\n ('Hibah dengan Akta', 'Hibah dengan Akta'),\n ('Hibah Tanpa Akta', 'Hibah Tanpa Akta'),\n ('Hadiah', 'Hadiah'),\n ('Lainnya', 'Lainnya'),\n)\n\nNAMA_MODEL = ('HartaSurat', 'HartaKas', 'HartaLainnya', 'PelaporanFile')\n\n\ndef rename_upload_file(instance, filename):\n nip = instance.pelaporan.pegawai.nip\n return os.path.join(f'lhkasn/', build_filename(nip, filename))\n\n\n@receiver(models.signals.pre_save)\ndef auto_delete_file_on_change(sender, instance, **kwargs):\n model = type(instance)\n nama = model.__name__\n\n if nama in NAMA_MODEL:\n if not instance.pk:\n return False\n\n try:\n file_lama = None\n file_baru = None\n obj = model.objects.get(pk=instance.pk)\n if hasattr(obj, 'bukti_dokumen'):\n file_lama = obj.bukti_dokumen\n file_baru = instance.bukti_dokumen\n elif hasattr(obj, 'filepath'):\n file_lama = obj.filepath\n file_baru = instance.filepath\n except model.DoesNotExist:\n return False\n else:\n rename_file(file_lama=file_lama, file_baru=file_baru)\n\n\n@receiver(models.signals.post_delete)\ndef auto_delete_file_on_delete(sender, instance, **kwargs):\n model = type(instance)\n nama = model.__name__\n\n if nama in NAMA_MODEL:\n if hasattr(instance, 'bukti_dokumen'):\n if instance.bukti_dokumen:\n delete_file(path=instance.bukti_dokumen.path)\n elif hasattr(instance, 'filepath'):\n if instance.filepath:\n delete_file(path=instance.filepath.path)\n\n\nclass PelaporanManager(models.Manager):\n def get_no_pelaporan(self):\n lhkasn = 0\n if self.exists():\n lhkasn = self.latest('id').id\n\n nomor = str(lhkasn + 1).zfill(6)\n tahun = datetime.now().year - 1\n return f'{nomor}/LHKASN-{tahun}'\n\n def get_jumlah_pelaporan(self, pegawai):\n jml = self.filter(pegawai=pegawai).count() + 1\n return jml\n\n def get_jumlah_verifikasi(self):\n menunggu = self.filter(isactive=True, isverify=False, status__id=2).count()\n disetujui = self.filter(isactive=True, isverify=True, status__id=3).count()\n dikembalikan = self.filter(isactive=True, isverify=False, status__id=4).count()\n jumlah = {\n 'menunggu': menunggu,\n 'disetujui': disetujui,\n 'dikembalikan': dikembalikan,\n }\n\n return jumlah\n\n\nclass Pelaporan(models.Model):\n no_pelaporan = models.CharField(max_length=100)\n pegawai = models.ForeignKey(to=Pegawai, on_delete=models.CASCADE, related_name='pegawai_pelaporan')\n status = models.ForeignKey(to=Status, on_delete=models.PROTECT, related_name='status_pelaporan')\n tanggal_lapor = models.DateField()\n tanggal_submit = models.DateField(null=True)\n pelaporan_ke = models.PositiveSmallIntegerField(default=1)\n isactive = models.BooleanField(default=True)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.CharField(max_length=255, null=True)\n\n isverify = models.BooleanField(default=False)\n verified = models.DateTimeField(null=True)\n verified_by = models.CharField(max_length=255, null=True)\n remarks = models.CharField(max_length=255, verbose_name='Alasan penolakan', null=True)\n h1 = models.BooleanField(default=False, verbose_name='Harta - Tanah dan Bangunan')\n h2 = models.BooleanField(default=False, verbose_name='Harta - Alat Transportasi dan Mesin')\n h3 = models.BooleanField(default=False, verbose_name='Harta - Harta Bergerak Lainnya')\n h4 = models.BooleanField(default=False, verbose_name='Harta - Surat Berharga')\n h5 = models.BooleanField(default=False, verbose_name='Harta - Kas dan Setara Kas')\n h6 = models.BooleanField(default=False, verbose_name='Harta - Harta Lainnya')\n h7 = models.BooleanField(default=False, verbose_name='Hutang')\n h8 = models.BooleanField(default=False, verbose_name='Penerimaan Kas')\n h9 = models.BooleanField(default=False, verbose_name='Pengeluaran Kas')\n\n objects = PelaporanManager()\n\n class Meta:\n permissions = (('verify_pelaporan', 'Can verify LHKASN'), )\n\n @property\n def is_harta(self):\n if self.hartatnbg_set.exists():\n return True\n elif self.hartamesin_set.exists():\n return True\n elif self.hartahbl_set.exists():\n return True\n elif self.hartasurat_set.exists():\n return True\n elif self.hartakas_set.exists():\n return True\n elif self.hartalainnya_set.exists():\n return True\n elif self.hartahutang_set.exists():\n return True\n else:\n return False\n\n @property\n def is_penerimaan(self):\n if hasattr(self, 'penerimaan'):\n return True\n else:\n return False\n\n @property\n def is_pengeluaran(self):\n if hasattr(self, 'pengeluaran'):\n return True\n else:\n return False\n\n def get_rekap_harta(self):\n # ============== harta\n harta_tdkbergerak = self.hartatnbg_set.all().aggregate(jml=Sum('nilai_estimasi')).get('jml') or 0\n harta_bergerak = self.hartamesin_set.all().aggregate(jml=Sum('nilai_estimasi')).get('jml') or 0\n harta_bergerak_lain = self.hartahbl_set.all().aggregate(jml=Sum('nilai_estimasi')).get('jml') or 0\n harta_surat = self.hartasurat_set.all().aggregate(jml=Sum('nilai_estimasi')).get('jml') or 0\n harta_kas = self.hartakas_set.all().aggregate(jml=Sum('nilai_saldo')).get('jml') or 0\n harta_lainnya = self.hartalainnya_set.all().aggregate(jml=Sum('nilai_estimasi')).get('jml') or 0\n harta_hutang = self.hartahutang_set.all().aggregate(jml=Sum('nilai_saldo')).get('jml') or 0\n sub_total_harta = (harta_tdkbergerak + harta_bergerak + harta_bergerak_lain + harta_surat + harta_kas +\n harta_lainnya)\n total_harta = sub_total_harta - harta_hutang\n harta = {\n 'harta_tdkbergerak': harta_tdkbergerak,\n 'harta_bergerak': harta_bergerak,\n 'harta_bergerak_lain': harta_bergerak_lain,\n 'harta_surat': harta_surat,\n 'harta_kas': harta_kas,\n 'harta_lainnya': harta_lainnya,\n 'sub_total_harta': sub_total_harta,\n 'harta_hutang': harta_hutang,\n 'total_harta': total_harta,\n }\n\n # ============== penerimaan\n penerimaan_pekerjaan = penerimaan_usaha = penerimaan_lainnya = 0\n if self.is_penerimaan:\n penerimaan_pekerjaan = (self.penerimaan.pk_gaji_asn + self.penerimaan.pk_gaji_psn +\n self.penerimaan.pk_profesi_asn + self.penerimaan.pk_profesi_psn +\n self.penerimaan.pk_honorarium_asn + self.penerimaan.pk_honorarium_psn +\n self.penerimaan.pk_bonus_asn + self.penerimaan.pk_bonus_psn +\n self.penerimaan.pk_lainnya_asn + self.penerimaan.pk_lainnya_psn)\n penerimaan_usaha = (self.penerimaan.pu_investasi + self.penerimaan.pu_sewa + self.penerimaan.pu_bunga +\n self.penerimaan.pu_penjualan + self.penerimaan.pu_lainnya)\n penerimaan_lainnya = (self.penerimaan.pl_hutang + self.penerimaan.pl_warisan + self.penerimaan.pl_hibah +\n self.penerimaan.pl_lainnya)\n\n total_penerimaan = penerimaan_pekerjaan + penerimaan_usaha + penerimaan_lainnya\n penerimaan = {\n 'pekerjaan': penerimaan_pekerjaan,\n 'usaha': penerimaan_usaha,\n 'lainnya': penerimaan_lainnya,\n 'total': total_penerimaan,\n }\n\n # ============== pengeluaran\n pengeluaran_umum = pengeluaran_harta = pengeluaran_lain = 0\n if self.is_pengeluaran:\n pengeluaran_umum = (self.pengeluaran.rutin_rt + self.pengeluaran.rutin_sosial + self.pengeluaran.rutin_pajak +\n self.pengeluaran.rutin_lainnya)\n pengeluaran_harta = (self.pengeluaran.harta_pembelian + self.pengeluaran.harta_pemeliharaan +\n self.pengeluaran.harta_lainnya)\n pengeluaran_lain = (self.pengeluaran.lainnya_hibah + self.pengeluaran.lainnya_angsuran +\n self.pengeluaran.lainnya_lainnya)\n\n total_pengeluaran = pengeluaran_umum + pengeluaran_harta + pengeluaran_lain\n pengeluaran = {\n 'umum': pengeluaran_umum,\n 'harta': pengeluaran_harta,\n 'lain': pengeluaran_lain,\n 'total': total_pengeluaran,\n }\n\n penerimaan_bersih = total_penerimaan - total_pengeluaran\n rekap = {\n 'harta': harta,\n 'penerimaan': penerimaan,\n 'pengeluaran': pengeluaran,\n 'penerimaan_bersih': penerimaan_bersih,\n }\n\n return rekap\n\n def get_hashid(self):\n return h_encode(self.id)\n\n\nclass HartaTnbg(models.Model):\n JENIS = (\n ('Sertifikat', 'Sertifikat'),\n ('Akta Jual Beli', 'Akta Jual Beli'),\n )\n PEMANFAATAN = (\n ('Tempat Tinggal', 'Tempat Tinggal'),\n ('Disewakan', 'Disewakan'),\n ('Pertanian / Perikanan / Perkebunan / Pertambangan', 'Pertanian / Perikanan / Perkebunan / Pertambangan'),\n ('Lainnya', 'Lainnya'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n prov = models.ForeignKey(to=Provinsi, on_delete=models.PROTECT, verbose_name='Provinsi')\n kab = models.ForeignKey(to=Kabupaten, on_delete=models.PROTECT, verbose_name='Kabupaten / kota')\n kec = models.ForeignKey(to=Kecamatan, on_delete=models.PROTECT, verbose_name='Kecamatan')\n kel = models.ForeignKey(to=Kelurahan, on_delete=models.PROTECT, verbose_name='Kelurahan/Desa', null=True,\n blank=True)\n jalan = models.TextField(verbose_name='Nama jalan dan nomor')\n luas_tanah = models.BigIntegerField(verbose_name='Luas tanah (dalam meter persegi)')\n luas_bangunan = models.BigIntegerField(verbose_name='Luas bangunan (dalam meter persegi)')\n jenis_bukti = models.CharField(max_length=100, choices=JENIS, verbose_name='Jenis bukti')\n nomor_bukti = models.CharField(max_length=100)\n atasnama = models.CharField(max_length=100, choices=ATAS_NAMA)\n salsul = models.CharField(max_length=100, choices=ASAL_USUL, verbose_name='Asal usul harta')\n pemanfaatan = models.CharField(max_length=200, choices=PEMANFAATAN)\n nilai_perolehan = models.BigIntegerField(verbose_name='Nilai perolehan (Rp)')\n nilai_estimasi = models.BigIntegerField(verbose_name='Nilai estimasi saat pelaporan (Rp)')\n tahun_perolehan = models.IntegerField()\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaMesin(models.Model):\n JENIS = (\n ('Mobil', 'Mobil'),\n ('Motor', 'Motor'),\n ('Alat Produksi', 'Alat Produksi'),\n ('Mesin Lainnya', 'Mesin Lainnya'),\n )\n\n BUKTI = (\n ('BPKB', 'BPKB'),\n ('Kuitansi Pembelian', 'Kuitansi Pembelian'),\n ('Lain-lain', 'Lain-lain'),\n )\n\n PEMANFAATAN = (\n ('Digunakan Sendiri', 'Digunakan Sendiri'),\n ('Disewakan', 'Disewakan'),\n ('Lainnya', 'Lainnya'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n jenis = models.CharField(max_length=100, choices=JENIS)\n merek = models.CharField(max_length=255)\n model = models.CharField(max_length=255, verbose_name='Tipe / model')\n tahun_pembuatan = models.IntegerField()\n nomor_registrasi = models.CharField(max_length=100, verbose_name='No pol. / registrasi')\n jenis_bukti = models.CharField(max_length=50, choices=BUKTI)\n tahun_perolehan = models.IntegerField()\n atasnama = models.CharField(max_length=100, choices=ATAS_NAMA)\n salsul = models.CharField(max_length=255, choices=ASAL_USUL, verbose_name='Asal usul harta')\n pemanfaatan = models.CharField(max_length=200, choices=PEMANFAATAN)\n nilai_perolehan = models.BigIntegerField(verbose_name='Nilai perolehan (Rp)')\n nilai_estimasi = models.BigIntegerField(verbose_name='Nilai estimasi saat pelaporan (Rp)')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaHbl(models.Model):\n JENIS = (\n ('Perabotan Rumah Tangga', 'Perabotan Rumah Tangga'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n jenis = models.CharField(max_length=200, choices=JENIS)\n jumlah = models.PositiveSmallIntegerField()\n satuan = models.CharField(max_length=255)\n keterangan = models.CharField(max_length=255)\n tahun_perolehan = models.IntegerField()\n salsul = models.CharField(max_length=255, choices=ASAL_USUL, verbose_name='Asal usul harta')\n nilai_perolehan = models.BigIntegerField(verbose_name='Nilai perolehan (Rp)')\n nilai_estimasi = models.BigIntegerField(verbose_name='Nilai estimasi saat pelaporan (Rp)')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaSurat(models.Model):\n JENIS = (\n ('Efek Diperdagangkan di Bursa', 'Efek Diperdagangkan di Bursa'),\n ('Surat Berharga Lainnya', 'Surat Berharga Lainnya'),\n )\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n nomor_rekening = models.CharField(max_length=100, verbose_name='Nomor rekening / nomor nasabah')\n bukti_dokumen = models.FileField(upload_to=rename_upload_file,\n validators=[FileExtensionValidator(['pdf', 'jpg', 'jpeg', 'png'])],\n verbose_name='Bukti dokumen / rekening (pdf/jpg/png/jpeg)')\n jenis = models.CharField(max_length=100, choices=JENIS)\n atasnama = models.CharField(max_length=100, choices=ATAS_NAMA)\n nilai_perolehan = models.BigIntegerField(verbose_name='Nilai perolehan (Rp)')\n nilai_estimasi = models.BigIntegerField(verbose_name='Nilai estimasi saat pelaporan (Rp)')\n penerbit = models.CharField(max_length=100, verbose_name='Penerbit / perusahaan')\n sekuritas = models.CharField(max_length=100, verbose_name='Custodian / sekuritas')\n tahun_perolehan = models.IntegerField()\n salsul = models.CharField(max_length=100, choices=ASAL_USUL, verbose_name='Asal usul harta')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaKas(models.Model):\n JENIS = (\n ('Tabungan', 'Tabungan'),\n ('Deposito', 'Deposito'),\n ('Kas', 'Kas'),\n )\n MATA_UANG = (\n ('IDR', 'RUPIAH (IDR)'),\n ('USD', 'US DOLLAR (USD)'),\n ('JPY', 'JAPAN YEN (JPY)'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n jenis = models.CharField(max_length=100, choices=JENIS)\n bukti_dokumen = models.FileField(upload_to=rename_upload_file,\n validators=[FileExtensionValidator(['pdf', 'jpg', 'jpeg', 'png'])],\n verbose_name='Bukti dokumen / rekening (pdf/jpg/png/jpeg)')\n nama_bank = models.CharField(max_length=100, verbose_name='Nama bank / lembaga keuangan')\n nomor_rekening = models.CharField(max_length=100)\n tahun_buka = models.IntegerField(verbose_name='Tahun buka rekening')\n atasnama = models.CharField(max_length=255, choices=ATAS_NAMA)\n salsul = models.CharField(max_length=255, choices=ASAL_USUL, verbose_name='Asal usul harta')\n jenis_mata_uang = models.CharField(max_length=100, choices=MATA_UANG)\n nilai_saldo = models.BigIntegerField()\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaLainnya(models.Model):\n JENIS = (\n ('Piutang', 'Piutang'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n jenis = models.CharField(max_length=255, choices=JENIS)\n bukti_dokumen = models.FileField(upload_to=rename_upload_file,\n validators=[FileExtensionValidator(['pdf', 'jpg', 'jpeg', 'png'])],\n verbose_name='Bukti dokumen / rekening (pdf/jpg/png/jpeg)')\n keterangan = models.TextField()\n tahun_perolehan = models.IntegerField()\n nilai_perolehan = models.BigIntegerField(verbose_name='Nilai perolehan (Rp)')\n nilai_estimasi = models.BigIntegerField(verbose_name='Nilai estimasi saat pelaporan (Rp)')\n salsul = models.CharField(max_length=255, choices=ASAL_USUL, verbose_name='Asal usul harta')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass HartaHutang(models.Model):\n JENIS = (\n ('Hutang Konsumtif (KPR, Kendaraan, Kartu Kredit, Multiguna)',\n 'Hutang Konsumtif (KPR, Kendaraan, Kartu Kredit, Multiguna)'),\n )\n\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n jenis = models.CharField(max_length=100, choices=JENIS, verbose_name='Jenis hutang')\n atasnama = models.CharField(max_length=100, choices=ATAS_NAMA)\n kreditur = models.CharField(max_length=255, verbose_name='Nama kreditur')\n bentuk_agunan = models.CharField(max_length=255)\n nilai_awal = models.BigIntegerField(verbose_name='Nilai awal hutang (Rp)')\n nilai_saldo = models.BigIntegerField(verbose_name='Nilai saldo hutang (Rp)')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass Penerimaan(models.Model):\n pelaporan = models.OneToOneField(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n pk_gaji_asn = models.BigIntegerField(verbose_name='Gaji dan Tunjangan (ASN)')\n pk_gaji_psn = models.BigIntegerField(default=0, verbose_name='Gaji dan Tunjangan (Pasangan)', blank=True)\n pk_profesi_asn = models.BigIntegerField(verbose_name='Penghasilan dari Profesi/Keahlian (ASN)')\n pk_profesi_psn = models.BigIntegerField(default=0, verbose_name='Penghasilan dari Profesi/Keahlian (Pasangan)',\n blank=True)\n pk_honorarium_asn = models.BigIntegerField(verbose_name='Honorarium (ASN)')\n pk_honorarium_psn = models.BigIntegerField(default=0, verbose_name='Honorarium (Pasangan)', blank=True)\n pk_bonus_asn = models.BigIntegerField(verbose_name='Tantiem, Bonus, Jasa Produksi, THR (ASN)')\n pk_bonus_psn = models.BigIntegerField(default=0, verbose_name='Tantiem, Bonus, Jasa Produksi, THR (Pasangan)',\n blank=True)\n pk_lainnya_asn = models.BigIntegerField(verbose_name='Penerimaan Pekerjaan Lainnya (ASN)')\n pk_lainnya_psn = models.BigIntegerField(default=0, verbose_name='Penerimaan Pekerjaan Lainnya (Pasangan)',\n blank=True)\n pu_investasi = models.BigIntegerField(verbose_name='Hasil Investasi dalam Surat Berharga')\n pu_sewa = models.BigIntegerField(verbose_name='Hasil Usaha/Sewa')\n pu_bunga = models.BigIntegerField(verbose_name='Bunga Tabungan/Deposito dan Lainnya')\n pu_penjualan = models.BigIntegerField(verbose_name='Penjualan atau Pelepasan Harta')\n pu_lainnya = models.BigIntegerField(verbose_name='Penerimaan Lainnya')\n pl_hutang = models.BigIntegerField(verbose_name='Penerimaan Hutang')\n pl_warisan = models.BigIntegerField(verbose_name='Penerimaan Warisan')\n pl_hibah = models.BigIntegerField(verbose_name='Penerimaan Hibah/Hadiah')\n pl_lainnya = models.BigIntegerField(verbose_name='Lainnya ')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass Pengeluaran(models.Model):\n pelaporan = models.OneToOneField(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n rutin_rt = models.BigIntegerField(verbose_name='Biaya rumah tangga', help_text=_(\n 'Termasuk transportasi, pendidikan, kesehatan, rekreasi, pembayaran kartu kredit'))\n rutin_sosial = models.BigIntegerField(verbose_name='Biaya sosial',\n help_text=_('Antara lain keagamaan, zakat, infaq, sumbangan lain'))\n rutin_pajak = models.BigIntegerField(verbose_name='Pembayaran pajak',\n help_text=_('Antara lain PBB, Kendaraan, pajak daerah, pajak lain'))\n rutin_lainnya = models.BigIntegerField(verbose_name='Pengeluaran rutin lainnya',\n help_text=_('Pengeluaran rutin akumulasi per-Tahun'))\n harta_pembelian = models.BigIntegerField(verbose_name='Pembelian / Perolehan Harta Baru')\n harta_pemeliharaan = models.BigIntegerField(verbose_name='Pemeliharaan / Modifikasi / Rehabilitasi Harta')\n harta_lainnya = models.BigIntegerField(verbose_name='Pengeluaran Non Rutin Lainnya')\n lainnya_hibah = models.BigIntegerField(verbose_name='Biaya Pengurusan Waris/Hibah/Hadiah')\n lainnya_angsuran = models.BigIntegerField(verbose_name='Pelunasan/Angsuran Hutang')\n lainnya_lainnya = models.BigIntegerField(verbose_name='Pengeluaran Lainnya')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n updated_by = models.IntegerField(null=True, editable=False)\n\n\nclass PelaporanFile(models.Model):\n pelaporan = models.ForeignKey(to=Pelaporan, on_delete=models.CASCADE, editable=False)\n deskripsi = models.CharField(max_length=255)\n filepath = models.FileField(upload_to=rename_upload_file,\n validators=[FileExtensionValidator(['pdf', 'jpg', 'jpeg', 'png'])],\n verbose_name='Softcopy file')\n isactive = models.BooleanField(default=True, editable=False)\n\n created = models.DateTimeField(auto_now_add=True)\n","sub_path":"simpanan_berharga/lhkasn/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":23787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"57463067","text":"'''\nThis is a program used to see how different values filled into the\nparameters of \"findLines\" affected the lines drawn onto the image\n'''\n\nimport SimpleCV\nfrom SimpleCV import Camera\nimport time\n\nimages = [None,None]\nimages[0] = SimpleCV.Image('Image File Here')\n\n\n\nimg=images[0].scale(.2)\n\nimg = img.smooth()\nimg = img.dilate()\nimg = img.erode()\n\nlines=img.findLines(threshold=2,maxlinegap=9,cannyth1=50,cannyth2=75) #edit these parameters\nlines=lines.filter(abs(lines.angle())<100.0)\nlines=lines.filter(80.0>abs(lines.angle()))\nfor line in lines:\n line.draw(color=SimpleCV.Color.GREEN,width=2)\n\nimg.show()\n\n\n","sub_path":"ParameterTest.py","file_name":"ParameterTest.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"654435544","text":"from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QFile, QFileInfo\nfrom PyQt5.QtGui import QIcon, QColor\nfrom PyQt5.QtWidgets import QAction\nfrom qgis.core import *\nfrom qgis.utils import iface\n\nimport os, shutil, glob, subprocess, fnmatch\nimport numpy as np\n\nfrom collections import defaultdict\nfrom osgeo import gdal, ogr, osr\nfrom pyproj import Proj, transform\nfrom skimage.io import imsave, imread\nfrom skimage.transform import resize\n\nDRY_RUN = 0\nnodata_threshold = 0.25\ncloud_threshold = 0.15\n#Clouds are 5th bit in 16 bit BQA image\nmaskClouds = 0b0000000000010000\n\ndef domainInRaster(rasterLayer: QgsRasterLayer, domainLayer: QgsVectorLayer) -> bool:\n\t\"\"\"Returns bool if domain is within bounds of geotiff in rasterLayer\n\t:param rasterLayer: QgsRasterLayer\n\t:param domainLayer: QgsVectorLayer\n\t\"\"\"\n\t# Get basic file name information on geotiff, raster image, masked raster subset image, and masked vector subset shp file\n\tfileSource = rasterLayer.source()\n\tfileInfo = QFileInfo(fileSource)\n\tfileName = fileInfo.baseName()\n\trowPath = fileName.split('_')[3]\n\t# Load geotiff and get domain layer/bounding box of area to mask\n\tgeotiff = gdal.Open(fileSource)\n\tfeature = domainLayer.getFeature(0)\n\tdomain = feature.geometry().boundingBox()\n\tprj = geotiff.GetProjection()\n\tsrs = osr.SpatialReference(wkt=prj)\n\tif srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1)\n\telif srs.GetAttrValue(\"AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"AUTHORITY\", 1)\n\telse:\n\t\tepsgCode = str(32621)\n\trasterCRS = \"EPSG:\" + epsgCode\n\t\n\tcrs = rasterLayer.crs()\n\tcrs.createFromId(int(epsgCode))\n\t\n\tdomainCRS = domainLayer.crs().authid()\n\tbounds = geotiffWorldToPixelCoords(geotiff, domain, rasterCRS, domainCRS)\n\t\n\t#Gather BQA info\n\tfileSourceBQA = fileSource[:-7] + '_BQA.TIF'\n\t#Save BQA subset\n\tgeotiffBQA = gdal.Open(fileSourceBQA)\n\t\n\tminX = int(round(bounds.yMinimum()))\n\tmaxX = int(round(bounds.yMaximum()))\n\tminY = int(round(bounds.xMinimum()))\n\tmaxY = int(round(bounds.xMaximum())) \n\t\n\tif minX < 0 or maxX > geotiff.RasterXSize or maxX > geotiffBQA.RasterXSize or minY < 0 or maxY > geotiff.RasterYSize or maxY > geotiffBQA.RasterYSize:\n\t\treturn False\n\telse:\n\t\t#Check image is above Nodata percentage threshold\n\t\tband = geotiff.GetRasterBand(1)\n\t\tnoDataValue = 0.0\n\t\timg = band.ReadAsArray(minX, minY, maxX - minX, maxY - minY).astype(np.uint16)\n\t\tnoDataCount = np.sum(img == noDataValue)\n\t\tpercentNoData = noDataCount / img.size\n\t\t\n\t\tif percentNoData > nodata_threshold:\n\t\t\tgeotiff = None\n\t\t\tgeotiffBQA = None\n\t\t\tprint('Skipping: Nodata percentage above threshold:', percentNoData, ' > ', nodata_threshold)\n\t\t\treturn False\n\t\t\n\t\t#Check image is above cloud percentage threshold\n\t\tbandBQA = geotiffBQA.GetRasterBand(1)\n\t\timgBQA = bandBQA.ReadAsArray(minX, minY, maxX - minX, maxY - minY).astype(np.uint16)\n\t\tmasked = imgBQA & maskClouds\n\t\tcloudCount = np.sum(masked)\n\t\tpercentCloud = cloudCount / 16.0 / imgBQA.size\n\t\tif percentCloud > cloud_threshold:\n\t\t\tgeotiff = None\n\t\t\tgeotiffBQA = None\n\t\t\tprint('Skipping: Cloud percentage above threshold:', percentCloud, ' > ', cloud_threshold)\n\t\t\treturn False\n\tgeotiff = None\n\tgeotiffBQA = None\n\treturn True\n\ndef geotiffBounds(geotiff) -> QgsRectangle:\n\t\"\"\"Returns QgsRectangle representing bounds of geotiff in projection coordinates\n\t\n\t:geotiff: geotiff\n\t:bounds: QgsRectangle\n\t\"\"\"\n\tgeoTransform = geotiff.GetGeoTransform()\n\t\n\txMin = geoTransform[0]\n\tyMax = geoTransform[3]\n\txMax = xMin + geoTransform[1] * geotiff.RasterXSize\n\tyMin = yMax + geoTransform[5] * geotiff.RasterYSize\n\t\n\treturn QgsRectangle(float(xMin), float(yMin), float(xMax), float(yMax))\n\ndef geotiffWorldToPixelCoords(geotiff, rectDomain:QgsRectangle, rasterCRS:str, domainCRS:str) -> QgsRectangle:\n\t\"\"\"Transforms QgsRectangle coordinates into geotiff image pixel coordinates\n\n\t:geotiff: geotiff\n\t:rect: QgsRectangle\n\t\"\"\"\n\t\n\t# Transform and scale rect by width/height to obtain normalized image coordiantes\n\trectRef = geotiffBounds(geotiff)\n\trectRefCenter = rectRef.center()\n\t\n\trectRefWidth = rectRef.width()\n\trectRefHeight = rectRef.height()\n\t\n\tdomainX = [rectDomain.xMinimum(), rectDomain.xMaximum()]\n\tdomainY = [rectDomain.yMinimum(), rectDomain.yMaximum()]\n\tinProj = Proj(init=domainCRS)\n\toutProj = Proj(init=rasterCRS)\n\t#print(inProj, outProj, domainCRS, rasterCRS)\n\trasterCRSDomainX, rasterCRSDomainY = transform(inProj, outProj, domainX, domainY)\n\t#print(rasterCRSDomainX, rasterCRSDomainY)\n\t\n\txMin = (rasterCRSDomainX[0] - rectRef.xMinimum()) / rectRefWidth\n\txMax = (rasterCRSDomainX[1] - rectRef.xMinimum()) / rectRefWidth\n\tyMin = (rasterCRSDomainY[0] - rectRef.yMinimum()) / rectRefHeight\n\tyMax = (rasterCRSDomainY[1] - rectRef.yMinimum()) / rectRefHeight\n\t\n\t# Scale by image dimensions to obtain pixel coordinates\n\txMin = xMin * geotiff.RasterXSize\n\txMax = xMax * geotiff.RasterXSize\n\tyMin = (1.0 - yMin) * geotiff.RasterYSize\n\tyMax = (1.0 - yMax) * geotiff.RasterYSize\n\t\n\t#print(rasterCRS, domainCRS)\n\t\n\t#Return pixel coordinates\n\trectOut = QgsRectangle(xMin, yMin, xMax, yMax)\n\treturn rectOut\n\ndef arrayToRaster(array:np.ndarray, geotiff, subset:QgsRectangle, destinationPath:str) -> ('Driver', 'Dataset'):\n\t\"\"\"Array > Raster\n\tSave a raster from a C order array.\n\t\n\t:param array: ndarray\n\t\"\"\"\n\tgeoBounds = geotiffBounds(geotiff)\n\tgeoTransform = geotiff.GetGeoTransform()\n\t\n\t# TODO: Fix X/Y coordinate mismatch and use ns/ew labels to reduce confusion. Also, general cleanup and refactoring.\n\th, w = array.shape[:2]\n\tx_pixels = w # number of pixels in x\n\ty_pixels = h # number of pixels in y\n\tx_pixel_size = geoTransform[1] # size of the pixel...\t\t\n\ty_pixel_size = geoTransform[5] # size of the pixel...\t\t\n\tx_min = geoTransform[0] \n\ty_max = geoTransform[3] # x_min & y_max are like the \"top left\" corner.\n\t\n\tx_subset_percentage = 1.0 - (float(subset.yMinimum()) / float(geotiff.RasterYSize))\n\ty_subset_percentage = (float(subset.xMinimum()) / float(geotiff.RasterXSize))\n\t\n\ty_coordinate_range = geoBounds.width()\n\tx_coordinate_range = geoBounds.height()\n\t\n\tx_offset = x_subset_percentage * x_coordinate_range\n\ty_offset = y_subset_percentage * y_coordinate_range\n\t\n\tx_min = geoBounds.xMinimum() + int(y_offset)\n\ty_max = geoBounds.yMinimum() + int(x_offset)\n\t\n\tdriver = gdal.GetDriverByName('GTiff')\n\t\n\tdataset = driver.Create(\n\t\tdestinationPath,\n\t\tx_pixels,\n\t\ty_pixels,\n\t\t1,\n\t\tgdal.GDT_Float32, )\n\t\n\tdataset.SetGeoTransform((\n\t\tx_min,\t# 0\n\t\tx_pixel_size, # 1\n\t\tgeoTransform[2],\t\t\t\t\t # 2\n\t\ty_max,\t# 3\n\t\tgeoTransform[4],\t\t\t\t\t # 4\n\t\ty_pixel_size)) #6\n\t\n\tdataset.SetProjection(geotiff.GetProjection())\n\tdataset.GetRasterBand(1).WriteArray(array)\n\tdataset.FlushCache() # Write to disk.\n\treturn dataset, dataset.GetRasterBand(1) #If you need to return, remenber to return also the dataset because the band don`t live without dataset.\n\ndef vectorizeRaster(rasterPath:str, outLineShp:str, lineName:str, outPolygonShp:str, polygonName:str) -> (QgsVectorLayer, QgsVectorLayer):\n\t\"\"\"Description: Creates a vector layer from a raster using processing:polygonize.\n\t\tMake sure to save the shapefile, as it will be deleted otherwise! \n\t\tInput: string rasterPath - path to raster image to polygonize\n\t\t\t\tstring outLineShp - file name to give new line shapefile\n\t\t\t\tstring lineName - layer name to give new line vector layer\n\t\t\t\tstring outLineShp - file name to give new closed polygon shapefile\n\t\t\t\tstring polygonName - layer name to give new closed polygon vector layer\n\t\tOutput: QgsVectorLayer, QgsVectorLayer - object referencing the new line and polygon vector layers\n\t\"\"\"\n\t# this allows GDAL to throw Python Exceptions\n\tgdal.UseExceptions()\n\t\n\t# Get raster datasource\n\tsrc_ds = gdal.Open(rasterPath)\n\tsrcband = src_ds.GetRasterBand(1)\n\tprj = src_ds.GetProjection()\n\traster_srs = osr.SpatialReference(wkt = prj)\n\t\n\t# Create output datasource\n\tdrv = ogr.GetDriverByName(\"ESRI Shapefile\")\n\t# Remove output shapefile if it already exists)\n\tif os.path.exists(outLineShp):\n\t\toutShapefileBase = outLineShp[0:-4]\n\t\tfor filename in glob.glob(outShapefileBase + \"*\"):\n\t\t\tos.remove(filename)\n\t\n\tdrv = None\n\tdrv = ogr.GetDriverByName(\"ESRI Shapefile\")\n\t\n\tprocessing.run(\"gdal:contour\",\n\t\t{\"INPUT\":rasterPath,\n\t\t\"BAND\":1,\n\t\t\"INTERVAL\":255,\n\t\t\"FIELD_NAME\":\"ELEV\",\n\t\t\"CREATE_3D\":False, #Bilinear\n\t\t\"IGNORE_NODATA\":False,\n\t\t\"NODATA\":None,\n\t\t\"OFFSET\":0,\n\t\t\"OUTPUT\":outLineShp[0:-4] + '_tmp.shp'\n\t\t})\n\t\n\tprocessing.run(\"native:simplifygeometries\",\n\t\t{\"INPUT\":outLineShp[0:-4] + '_tmp.shp',\n\t\t\"METHOD\": 0, #Distance (Douglas-Peucker)\n\t\t\"TOLERANCE\": 20, #20 meter tolerance (Landsat B5 resolution: 30m\n\t\t\"OUTPUT\":outLineShp\n\t\t})\n\t\n\tprocessing.run(\"qgis:linestopolygons\",\n\t\t{\"INPUT\":outLineShp,\n\t\t\"OUTPUT\":outPolygonShp\n\t\t})\n\t\n\tfor filename in glob.glob(outLineShp[0:-4] + '_tmp*'):\n\t\tos.remove(filename)\n\t#src_ds = None\n\t#srcband = None\n\t#dst_ds = None\n\t#dst_layer = None\n\t#drv = None\n\t#\n\t## If area is less than inMinSize or if it isn't forest, remove polygon \n\t#ioShpFile = ogr.Open(outShapefile, update = 1)\n\t#layer = ioShpFile.GetLayerByIndex(0)\n\t#\t\t\n\t#layer.ResetReading()\n\t#for feature in layer:\n\t#\tprint('feature', feature.GetFID(), feature.GetField('Class'))\n\t#\tlayer.SetFeature(feature)\n\t#\tif feature.GetField('Class')==0:\n\t#\t\tlayer.DeleteFeature(feature.GetFID())\t\t\n\t#ioShpFile.Destroy()\n\t#ioShpFile = None\n\t\n\treturn QgsVectorLayer(outLineShp, lineName, 'ogr'), QgsVectorLayer(outPolygonShp, polygonName, 'ogr')\n\ndef layerResize(rasterLayer:QgsRasterLayer, domainLayer:QgsVectorLayer, name:str, resolution:(int, int)) -> None:\n\t\"\"\"Description: Processes a raster image into a vector polygon ocean/land mask.\n\t\tMake sure to save the shapefile, as it will be deleted otherwise! \n\t\tInput: QgsRasterLayer rasterLayer - layer that contains the raster image to process\n\t\t\t\tQgsVectorLayer domainLayer - layer that contains a polygon specifying the bounds of the raster image to process\n\t\t\t\tQgsVectorLayer outputLayer - layer to save vector layer in. Warning: not supported yet. \n\t\tOutput: QgsRasterLayer, QgsVectorLayer - objects referencing the new mask layers\n\t\"\"\"\n\t\n\tpath = resolve('landsat_raw/' + domainLayer.name() + '/' + name + '.png')\n\timg = imread(path)\n\timg = resize(img, resolution)\n\tprint(img.shape, path)\n\tif not DRY_RUN:\n\t\timsave(path, img)\n\ndef layerWarp(rasterNode:QgsLayerTreeGroup, domainLayer:QgsVectorLayer) -> None:\n\t\"\"\"Description: Reprojects a raster if not already in the desired CRS.\n\t\tMake sure to save the shapefile, as it will be deleted otherwise! \n\t\tInput: QgsLayerTreeGroup rasterNode - node that contains the raster image to process\n\t\t\t\tQgsVectorLayer domainLayer - layer that contains a polygon specifying the bounds of the raster image to process\n\t\"\"\"\n\t\n\trasterLayer = rasterNode.layer()\n\tfileSource = rasterLayer.source()\n\tgeotiff = gdal.Open(fileSource)\n\tprj = geotiff.GetProjection()\n\tsrs = osr.SpatialReference(wkt=prj)\n\tdomainCRS = domainLayer.crs().authid()\n\tif srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1)\n\telif srs.GetAttrValue(\"AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"AUTHORITY\", 1)\n\telse:\n\t\tepsgCode = str(32621)\n\trasterCRS = \"EPSG:\" + epsgCode\n\tif (rasterCRS != domainCRS):\n\t\tprint('warping...', rasterCRS, domainCRS)\n\t\tif not DRY_RUN:\n\t\t\tparent = rasterNode.parent()\n\t\t\trasterName = rasterLayer.name()\n\t\t\t\n\t\t\toutSource = fileSource[0:-4] + \"_\" + domainCRS[5:] + \".tif\"\n\t\t\t#processing.algorithmHelp(\"gdal:warpreproject\")\n\t\t\tprint(fileSource, outSource)\n\t\t\tprocessing.run(\"gdal:warpreproject\",\n\t\t\t\t# {\"INPUT\":fileSource,\n\t\t\t\t# \"SOURCE_SRS\":rasterCRS,\n\t\t\t\t# \"TARGET_CRS\":domainCRS,\n\t\t\t\t# \"RESAMPLING\":1, #Bilinear\n\t\t\t\t# \"NO_DATA\":0,\n\t\t\t\t# \"DATA_TYPE\":5, #Float32\n\t\t\t\t# \"MULTITHREADING\":True,\n\t\t\t\t# \"OUTPUT\":outSource})\n\t\t\t\t{'DATA_TYPE': 5,#Float32\n\t\t\t\t'INPUT': rasterName,\n\t\t\t\t'MULTITHREADING': True,\n\t\t\t\t'NODATA': 0.0,\n\t\t\t\t'OPTIONS': '',\n\t\t\t\t'OUTPUT': outSource,\n\t\t\t\t'RESAMPLING': 1, #Bilinear\n\t\t\t\t'SOURCE_CRS': rasterCRS,\n\t\t\t\t'TARGET_CRS': domainCRS,\n\t\t\t\t'TARGET_EXTENT': None,\n\t\t\t\t'TARGET_EXTENT_CRS': None,\n\t\t\t\t'TARGET_RESOLUTION': None})\n\t\t\tprint('hello')\n\t\t\tQgsProject.instance().removeMapLayer(rasterLayer.id())\n\t\t\tgeotiff = None\n\t\t\tshutil.copy2(outSource, fileSource)\n\t\t\tos.remove(outSource)\n\t\t\trasterLayer = QgsRasterLayer(fileSource, rasterName)\n\t\t\tQgsProject.instance().addMapLayer(rasterLayer, False)\n\t\t\trasterNode = parent.insertLayer(0, rasterLayer)\n\t\t\treturn rasterNode\n\treturn rasterNode\n\ndef getVectorNames(fileName:str, domainName:str):\n\t\"\"\"Description: Processes a raster image into a vector polygon ocean/land mask.\n\t\tGet a standardized vector name from a Landsat raster file name.\n\t\tInput: str fileName - Landsat raster file name.\n\t\t\t\tstr domainName - Domain vector file name.\n\t\tOutput: str lineName, str polygonName - vector file names.\n\t\"\"\"\n\t\n\tdate = fileName.split('_')[2]\n\tlineName = '_'.join(['cf', domainName, date, 'closed'])\n\tpolygonName = '_'.join([lineName, 'polygon'])\n\treturn lineName, polygonName\n\ndef getSavePaths(fileName:str, domainLayer:QgsVectorLayer, typeDir:str):\n\t\"\"\"Description: Processes a raster image into a vector polygon ocean/land mask.\n\t\tGet a standardized vector name from a Landsat raster file name.\n\t\tInput: str fileName - Landsat raster file name.\n\t\t\t\tstr glacierName - Root vector file name.\n\t\t\t\tstr typeDir - name of the type subdirectory.\n\t\tOutput: str path - file save paths.\n\t\"\"\"\n\t\n\tdate = fileName.split('_')[2]\n\tyear = date.split('-')[0]\n\t\n\t# if (rootGroup.parent().name().startswith('2') or rootGroup.parent().name().startswith('1')):\n\t\t# rootGroup = rootGroup.parent()\n\t\n\tpath = resolve('CalvingFronts')\n\tif (not os.path.exists(path)):\n\t\tos.mkdir(path)\n\tpath = os.path.join(path, typeDir)\n\tif (not os.path.exists(path)):\n\t\tos.mkdir(path)\n\tpath = os.path.join(path, domainLayer.name())\n\tif (not os.path.exists(path)):\n\t\tos.mkdir(path)\n\tpath = os.path.join(path, year)\n\tif (not os.path.exists(path)):\n\t\tos.mkdir(path)\n\t\n\treturn path\n\ndef postprocess(image:np.ndarray) -> np.ndarray:\n\t\"\"\"Description: Postprocesses mask layer to remove small features.\n\t\"\"\"\n\timage = np.where(image > 127, 255, 0)\n\t# Close edges to join them and dilate them before removing small components\n\tkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n\tclosing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)\n\tdilated = cv2.dilate(closing, kernel, iterations = 1)\n\tlargeComponents = removeSmallComponents(dilated, 0, 255)\n\t# largeComponents = dilated\n\t\n\t# Remove small components inside floodfill area\n\tlargeComponentsInverted = 255 - largeComponents\n\tlargeComponentsInverted = removeSmallComponents(largeComponentsInverted, 0, 255)\n\tlargeComponentsInverted2 = 255 - largeComponentsInverted\n\t\n\t# Reverse initial morphological operators to retrieve original edge mask\n\teroded = cv2.erode(largeComponentsInverted2, kernel, iterations = 1)\n\topening = cv2.morphologyEx(eroded, cv2.MORPH_OPEN, kernel)\n\t\n\tresult = removeSmallComponents(opening, 0, 255)\n\t\n\treturn result\n\ndef layerSubsetLoad(rasterLayer:QgsRasterLayer, domainLayer:QgsVectorLayer, rootGroup:QgsLayerTreeGroup, name:str) -> (QgsRasterLayer, QgsVectorLayer):\n\t\"\"\"Description: Processes a raster image into a vector polygon ocean/land mask.\n\t\tMake sure to save the shapefile, as it will be deleted otherwise! \n\t\tInput: QgsRasterLayer rasterLayer - layer that contains the raster image to process\n\t\t\t\tQgsVectorLayer domainLayer - layer that contains a polygon specifying the bounds of the raster image to process\n\t\t\t\tQgsLayerTreeGroup rootGroup - layer that contains the root name of the glacier\n\t\t\t\tstr name - name of file.\n\t\tOutput: QgsRasterLayer, QgsVectorLayer - objects referencing the new mask layers\n\t\"\"\"\n\t\n\t# Get basic file name information on geotiff, raster image, masked raster subset image, and masked vector subset shp file\n\t#print('Get basic file name information on geotiff, raster image, masked raster subset image, and masked vector subset shp file')\n\tfileSource = rasterLayer.source()\n\tfileInfo = QFileInfo(fileSource)\n\tfilePath = fileInfo.absolutePath()\n\tfileName = fileInfo.baseName()\n\tfileQASource = filePath + '/' + fileName[:fileName.rfind('_B')] + '_BQA.TIFF'\n\tmaskName = fileName + '_masked'\n\tmaskPath = filePath + '/' + maskName + '.tif'\n\tlineMaskName, polyMaskName = getVectorNames(fileName, domainLayer.name())\n\tvectorPath = getSavePaths(fileSource, domainLayer, 'shp')\n\ttifPath = getSavePaths(fileSource, domainLayer, 'tif')\n\tlineMaskPath = vectorPath + '/' + lineMaskName + '.shp'\n\tpolyMaskPath = vectorPath + '/' + polyMaskName + '.shp'\n\trawTifPath = tifPath + '/' + name + '.tif'\n\t\n\tif os.path.exists(lineMaskPath):\n\t\tlayers = QgsProject.instance().mapLayersByName(lineMaskName)\n\t\tif (len(layers) > 0):\n\t\t\tfor layer in layers:\n\t\t\t\tQgsProject.instance().removeMapLayer(layer.id())\n\tif os.path.exists(polyMaskPath):\n\t\tlayers = QgsProject.instance().mapLayersByName(polyMaskName)\n\t\tif (len(layers) > 0):\n\t\t\tfor layer in layers:\n\t\t\t\tQgsProject.instance().removeMapLayer(layer.id())\n\t\n\t# Load geotiff and get domain layer/bounding box of area to mask\n\t#print('Load geotiff and get domain layer/bounding box of area to mask')\n\tgeotiff = gdal.Open(fileSource)\n\tfeature = domainLayer.getFeature(0)\n\tdomain = feature.geometry().boundingBox()\n\trasterCRS = rasterLayer.crs().authid()\n\tdomainCRS = domainLayer.crs().authid()\n\tbounds = geotiffWorldToPixelCoords(geotiff, domain, rasterCRS, domainCRS)\n\t\n\t#print(\"mask = imread(resolve('landsat_preds/' + name + '_pred.png'))\")\n\ttry:\n\t\t# raw = imread(resolve('landsat_preds/' + domainLayer.name() + '/' + name + '_raw.png'))\n\t\t# arrayToRaster(raw, geotiff, bounds, rawTifPath)\n\t\t\n\t\tmask = imread(resolve('landsat_preds/' + domainLayer.name() + '/' + name + '_mask.png'))\n\t\t# mask = postprocess(mask)\n\t\t# Save results to files and layers\n\t\t#print('Save results to files and layers')\n\t\tarrayToRaster(mask, geotiff, bounds, maskPath)\n\t\trasterLayer = QgsRasterLayer(maskPath, maskName)\n\t\tlineLayer, polygonLayer = vectorizeRaster(maskPath, lineMaskPath, lineMaskName, polyMaskPath, polyMaskName)\n\t\t\n\t\tgeotiff = None\n\t\treturn lineLayer, polygonLayer\n\texcept:\n\t\tprint(resolve('landsat_preds/' + domainLayer.name() + '/' + name + '_mask.png'), 'not found - skipping.')\n\t\treturn None, None\n\ndef layerSubsetSave(rasterLayer:QgsRasterLayer, domainLayer:QgsVectorLayer, subsetName:str) -> None:\n\t\"\"\"Description: Processes a raster image into a vector polygon ocean/land mask.\n\t\tMake sure to save the shapefile, as it will be deleted otherwise! \n\t\tInput: QgsRasterLayer rasterLayer - layer that contains the raster image to process\n\t\t\t\tQgsVectorLayer domainLayer - layer that contains a polygon specifying the bounds of the raster image to process\n\t\t\t\tstring name - output file name.\n\t\tOutput: QgsRasterLayer, QgsVectorLayer - objects referencing the new mask layers\n\t\"\"\"\n\t\n\t# Get basic file name information on geotiff, raster image, masked raster subset image, and masked vector subset shp file\n\tfileSource = rasterLayer.source()\n\tfileInfo = QFileInfo(fileSource)\n\tfileName = fileInfo.baseName()\t\n\tsavePaths = getSavePaths(fileSource, domainLayer, 'tif') \n\tsubsetPath = savePaths + '/' + subsetName + '.tif'\n\t\n\t# Load geotiff and get domain layer/bounding box of area to mask\n\tgeotiff = gdal.Open(fileSource)\n\tfeature = domainLayer.getFeature(0)\n\tdomain = feature.geometry().boundingBox()\n\tprj = geotiff.GetProjection()\n\tsrs = osr.SpatialReference(wkt=prj)\n\tif srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"PROJCS|AUTHORITY\", 1)\n\telif srs.GetAttrValue(\"AUTHORITY\", 1) is not None:\n\t\tepsgCode = srs.GetAttrValue(\"AUTHORITY\", 1)\n\telse:\n\t\tepsgCode = str(32621)\n\trasterCRS = \"EPSG:\" + epsgCode\n\t\n\tcrs = rasterLayer.crs()\n\tcrs.createFromId(int(epsgCode))\n\trasterLayer.setCrs(crs)\n\trasterLayer.triggerRepaint()\n\t\n\t#rasterCRS = rasterLayer.crs().authid()\n\tdomainCRS = domainLayer.crs().authid()\n\tbounds = geotiffWorldToPixelCoords(geotiff, domain, rasterCRS, domainCRS)\n\t\n\timg = geotiff.GetRasterBand(1)\n\timg = img.ReadAsArray(0,0,geotiff.RasterXSize,geotiff.RasterYSize)\n\timg = img[int(round(bounds.yMinimum())):int(round(bounds.yMaximum())), int(round(bounds.xMinimum())):int(round(bounds.xMaximum()))]\n\timg = (img.astype(np.float32) / img.max() * 65535).astype(np.uint16)\n\t\n\t# print('Save subset:', subsetPath, resolve('landsat_raw/' + domainLayer.name() + '/' + subsetName + '.png'))\n\tif not DRY_RUN:\n\t\tarrayToRaster(img, geotiff, bounds, subsetPath)\n\t\timsave(resolve('landsat_raw/' + domainLayer.name() + '/' + subsetName + '.png'), img)\n\t\t# imsave(resolve('small/' + domainLayer.name() + '/' + subsetName + '.png'), img)\n\t\t# imsave(os.path.join(r'../reprocessing\\images_1024', domainLayer.name(), subsetName + '.png'), img)\n\ttry:\n\t\t#Gather BQA info\n\t\tfileSourceBQA = fileSource[:-7] + '_BQA.TIF'\n\t\tfileInfoBQA = QFileInfo(fileSourceBQA)\n\t\tfileNameBQA = fileInfoBQA.baseName()\n\t\tsubsetNameBQA = fileNameBQA + '_' + domainLayer.name()\n\t\tsubsetPathBQA = savePaths + '/' + subsetNameBQA + '.tif'\n\t\t#Save BQA subset\n\t\tgeotiffBQA = gdal.Open(fileSourceBQA)\n\t\timgBQA = geotiffBQA.GetRasterBand(1)\n\t\timgBQA = imgBQA.ReadAsArray(0,0,geotiffBQA.RasterXSize,geotiffBQA.RasterYSize).astype(np.uint16)\n\t\timgBQA = imgBQA[int(round(bounds.yMinimum())):int(round(bounds.yMaximum())), int(round(bounds.xMinimum())):int(round(bounds.xMaximum()))]\n\t\t# print('Save BQA subset:', subsetPathBQA, resolve('landsat_raw/' + domainLayer.name() + '/' + subsetName + '_bqa.png'))\n\t\tif not DRY_RUN:\n\t\t\t# arrayToRaster(imgBQA, geotiffBQA, bounds, subsetPathBQA)\n\t\t\t# print(fileSourceBQA, geotiffBQA.RasterXSize, geotiffBQA.RasterYSize)\n\t\t\t# print(int(round(bounds.yMinimum())), int(round(bounds.yMaximum())), int(round(bounds.xMinimum())), int(round(bounds.xMaximum())))\n\t\t\timsave(resolve('landsat_raw/' + domainLayer.name() + '/' + subsetName + '_bqa.png'), imgBQA)\n\t\t\n\t\t#Gather MTL info\n\t\tfileSourceMTL = fileSource[:-7] + '_MTL.txt'\n\t\tfileInfoMTL = QFileInfo(fileSourceMTL)\n\t\tfileNameMTL = fileInfoMTL.baseName()\n\t\tsubsetNameMTL = fileNameMTL + '_' + domainLayer.name()\n\t\tsubsetPathMTL = savePaths + '/' + subsetNameMTL + '.txt'\n\t\t#Save MTL subset\t\n\t\tif not DRY_RUN:\n\t\t\timage_feats = ['']*6\n\t\t\twith open(fileSourceMTL, 'r') as image_feats_source_file:\t\n\t\t\t\tlines = image_feats_source_file.readlines()\n\t\t\t\tfor line in lines:\n\t\t\t\t\tif 'SUN_AZIMUTH =' in line:\n\t\t\t\t\t\timage_feats[0] = line.strip()\n\t\t\t\t\telif 'SUN_ELEVATION =' in line:\n\t\t\t\t\t\timage_feats[1] = line.strip()\n\t\t\t\t\telif 'CLOUD_COVER ' in line:\n\t\t\t\t\t\timage_feats[2] = line.strip()\n\t\t\t\t\telif 'CLOUD_COVER_LAND ' in line:\n\t\t\t\t\t\timage_feats[3] = line.strip()\n\t\t\t\t\telif 'DATE_ACQUIRED =' in line:\n\t\t\t\t\t\timage_feats[4] = line.strip()\n\t\t\t\t\telif 'GRID_CELL_SIZE_REFLECTIVE =' in line:\n\t\t\t\t\t\timage_feats[5] = line.strip()\n\t\t\tsavePath = resolve('landsat_raw/' + domainLayer.name() + '/' + subsetName + '_mtl.txt')\n\t\t\twith open(savePath, 'w') as image_feats_dest_file:\n\t\t\t\tfor line in image_feats:\n\t\t\t\t\timage_feats_dest_file.write(str(line) + '\\n')\n\texcept:\n\t\tprint('No BQA/MTL found for:', subsetName)\n\t\n\treturn img.shape\n\ndef perform_subsetting(rasterLayers, rasterPrefix, domainLayers):\n\tprint('Performing subsetting...')\n\t\n\t#Make directories if not already existing\n\tfor domainLayer in domainLayers:\n\t\tdomainLayer = domainLayer.layer()\n\t\traw_path = resolve('landsat_raw/' + domainLayer.name())\n\t\tmask_path = resolve('landsat_preds/' + domainLayer.name())\n\t\tif not os.path.exists(raw_path):\n\t\t\tos.mkdir(raw_path)\n\t\tif not os.path.exists(mask_path):\n\t\t\tos.mkdir(mask_path)\n\t\n\t\t# Clear data from any previous runs\n\t\t# files = glob.glob(raw_path + '/*')\n\t\t# for f in files:\n\t\t\t# if os.path.isfile(f):\n\t\t\t\t# os.remove(f)\n\t\t# files = glob.glob(mask_path + '/*')\n\t\t# for f in files:\n\t\t\t# if os.path.isfile(f):\n\t\t\t\t# os.remove(f)\n\t\n\tresolutions = warpAndSaveSubsets(rasterLayers, rasterPrefix, domainLayers)\n\tresizeandSaveSubsets(rasterLayers, rasterPrefix, domainLayers, resolutions)\n\ndef warpAndSaveSubsets(rasterLayers, rasterPrefix, domainLayers) -> list:\n\t# Perform subsetting for each layer, extracting each subset for every domain in domainGroup\n\tresolutions = defaultdict(list)\n\trasterLen = len(rasterLayers)\n\tdomainLen = len(domainLayers)\n\ttotal = rasterLen * domainLen\n\tfor i in range(rasterLen):\n\t\trasterLayerNode = rasterLayers[i]\n\t\trasterLayer = rasterLayerNode.layer()\n\t\tprint('Raster (number):', rasterLayer.source())#, ' Progress:', str(i) + '/' + str(total), '(' + str((i * rasterLen) / total) + '%)')\n\t\tfor j in range(domainLen):\n\t\t\tdomainLayer = domainLayers[j]\n\t\t\tdomainLayer = domainLayer.layer()\n\t\t\trasterLayers[i] = layerWarp(rasterLayerNode, domainLayer)\n\t\t\trasterLayerNode = rasterLayers[i]\n\t\t\trasterLayer = rasterLayerNode.layer() #Reload layer in case of warping\n\t\t\tsubset_name = domainLayer.name() + \"_\" + rasterLayer.name()\n\t\t\tprint('Domain: ', domainLayer.name())#, ' Progress:', str((i * rasterLen + j) / total) + '%')\n\t\t\tresolution = layerSubsetSave(rasterLayer, domainLayer, subset_name)\n\t\t\tresolutions[domainLayer.name()].append(resolution)\n\t\n\t# Calculate the median resolutions for each domain\t\n\tmedian_resolutions = []\n\tfor i in range(len(domainLayers)):\n\t\tdomainLayer = domainLayers[i]\n\t\tresolution = np.median(resolutions[domainLayer.name()], axis=0)\n\t\tprint('domainLayer (#):', i, domainLayer.name(), ' resolution:', resolution)\n\t\tmedian_resolutions.append(resolution)\n\t\n\treturn median_resolutions\n\ndef resizeandSaveSubsets(rasterLayers, rasterPrefix, domainLayers, resolutions) -> list:\n\t# Resize the images to the median size to account for reprojection differences\n\trasterLen = len(rasterLayers)\n\tdomainLen = len(domainLayers)\n\ttotal = rasterLen * domainLen\n\tfor i in range(rasterLen):\n\t\trasterLayerNode = rasterLayers[i]\n\t\trasterLayer = rasterLayerNode.layer()\n\t\tif rasterLayer.name()[-2:] in rasterPrefix:\n\t\t\tfor j in range(domainLen):\n\t\t\t\tdomainLayer = domainLayers[j]\n\t\t\t\tresolution = resolutions[j]\n\t\t\t\tdomainLayer = domainLayer.layer()\n\t\t\t\tprint('Resizing subsets to', resolution)#, ' Progress:', str((i * rasterLen + j) / total) + '%')\n\t\t\t\tif domainInRaster(rasterLayer, domainLayer):\n\t\t\t\t\tsubset_name = domainLayer.name() + \"_\" + rasterLayer.name()\n\t\t\t\t\tlayerResize(rasterLayer, domainLayer, subset_name, resolution)\n\ndef perform_saving(rasterLayers, rasterPrefix, domainLayers):\n\t#Save for training\n\tfor domainNode in domainLayers:\n\t\tdomainLayer = domainNode.layer()\n\t\tsource_path_base = resolve('landsat_raw/' + domainLayer.name())\n\t\tdest_path_base = r'D:/Daniel/Documents/GitHub/ultrasound-nerve-segmentation/landsat_raw/train_full/' + domainLayer.name()\n\t\tif not os.path.exists(dest_path_base):\n\t\t\tos.mkdir(dest_path_base)\n\t\tfor rasterLayer in rasterLayers:\n\t\t\trasterLayer = rasterLayer.layer()\n\t\t\tif rasterLayer.name()[-2:] in rasterPrefix:\n\t\t\t\tname = domainLayer.name() + \"_\" + rasterLayer.name() + '.png'\n\t\t\t\tsource_path = os.path.join(source_path_base, name)\n\t\t\t\tdest_path = os.path.join(dest_path_base, name)\n\t\t\t\tif not DRY_RUN:\n\t\t\t\t\tshutil.copy2(source_path, dest_path)\n\ndef processLayers(domainLayers, check_masking, check_saving, check_postprocessing):\n\tprint('Performing masking...')\n\tfor domainNode in domainLayers:\n\t\tlaunchcommand = r'C:\\Users\\Daniel\\AppData\\Roaming\\QGIS\\QGIS3\\profiles\\default\\python\\plugins\\calvingfrontmachine\\cfm.bat'\n\t\tcheck_masking = str(int(check_masking))\n\t\tcheck_postprocessing = str(int(check_postprocessing))\n\t\tcheck_saving = str(int(check_saving))\n\t\targuments = [launchcommand, domainNode.name(), check_masking, check_saving, check_postprocessing]\n\t\tprint(arguments)\n\t\tp = subprocess.Popen(arguments, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NEW_CONSOLE)\n\t\twhile True:\n\t\t\tline = p.stdout.readline()\n\t\t\tprint(str(line))\n\t\t\tif p.poll() != None:\n\t\t\t\tprint('exit code: ', p.poll())\n\t\t\t\tbreak\n\t\tp.kill()\n\ndef perform_vectorization(rasterLayers, domainLayers, rasterPrefix, check_vectorization, check_adding):\n\tfor rasterLayer in rasterLayers:\n\t\tfor domainLayer in domainLayers:\n\t\t\ttry:\n\t\t\t\tif rasterLayer.name()[-2:] in rasterPrefix:\n\t\t\t\t\tif check_vectorization:\n\t\t\t\t\t\tlineLayer, polygonLayer = layerSubsetLoad(rasterLayer.layer(), domainLayer.layer(), rasterGroup, domainLayer.name() + \"_\" + rasterLayer.name())\n\t\t\t\t\tif check_adding:\n\t\t\t\t\t\t# step 1: add the layer to the registry, False indicates not to add to the layer tree\n\t\t\t\t\t\tQgsProject.instance().addMapLayer(lineLayer, False)\n\t\t\t\t\t\tQgsProject.instance().addMapLayer(polygonLayer, False)\n\t\t\t\t\t\t# step 2: append layer to the root group node\n\t\t\t\t\t\trasterLayer.parent().insertLayer(0, lineLayer)\n\t\t\t\t\t\trasterLayer.parent().insertLayer(0, polygonLayer)\n\t\t\t\t\t\t# step 3: Add transparency slider to polygon layers\n\t\t\t\t\t\t#polygonLayer.setCustomProperty(\"embeddedWidgets/count\", 1)\n\t\t\t\t\t\t#polygonLayer.setCustomProperty(\"embeddedWidgets/0/id\", \"transparency\")\n\t\t\t\t\t\t# Alter fill style for vector layers\n\t\t\t\t\t\tpolygonSymbol = polygonLayer.renderer().symbol()\n\t\t\t\t\t\tlineSymbol = lineLayer.renderer().symbol()\n\t\t\t\t\t\tpolygonSymbol.setColor(lineSymbol.color())\n\t\t\t\t\t\tpolygonSymbol.setOpacity(0.25)\n\t\t\t\t\t\t# Redraw canvas and save variable to global context\n\t\t\t\t\t\tiface.layerTreeView().refreshLayerSymbology(lineLayer.id())\n\t\t\t\t\t\tiface.layerTreeView().refreshLayerSymbology(polygonLayer.id())\n\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\ndef resolve(name, basepath='C:/Users/Daniel/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/calvingfrontmachine'):\n\tif not os.path.exists(basepath):\n\t\tbasepath = os.path.dirname(os.path.realpath(__file__))\n\treturn os.path.join(basepath, name)\n\ndef findGroups(root:QgsLayerTree):\n\t\"\"\"Return a string list of groups.\"\"\"\n\tresult = []\n\tfor child in root.children():\n\t\tif isinstance(child, QgsLayerTreeGroup):\n\t\t\tresult.append(child.name())\n\t\t\tresult.extend(findGroups(child))\n\treturn result\t\n\ndef findChildren(root:QgsLayerTree, matchString:str):\n\t\"\"\"Return a string list of groups.\"\"\"\n\tresult = []\n\tmatchStringParts = matchString.split('/', 1)\n\tfor child in root.children():\n\t\tif fnmatch.fnmatch(child.name(), matchStringParts[0]):\n\t\t\tif isinstance(child, QgsLayerTreeGroup):\n\t\t\t\tif child.name().startswith(('1', '2')): \n\t\t\t\t\t\n\t\t\t\t\tif int(child.name()) < 1985:\n\t\t\t\t\t\tresult.extend(findChildren(child, matchStringParts[1]))\n\t\t\t\telse:\n\t\t\t\t\tprint(child.name())\n\t\t\t\t\tresult.extend(findChildren(child, matchStringParts[1]))\n\t\t\telse:\n\t\t\t\tresult.append(child)\n\treturn result\n\n\nproject = QgsProject.instance()\nroot = project.layerTreeRoot()\nrasterPrefix = ['B5', 'B4', 'B7']\ngroups = findGroups(root)\n\n# Get layer objects based on selection string values\nrasterGroupName = 'CalvingFronts/Rasters/*/*/*'\nrasterGroup = root.findGroup(rasterGroupName)\nrasterLayers = findChildren(root, rasterGroupName)\ndomainGroupName = 'CalvingFronts/Domains/*'\ndomainGroup = root.findGroup(domainGroupName)\ndomainLayers = findChildren(root, domainGroupName)\n\n# Get layer objects based on selection string values\n# rasterGroupName = 'CalvingFronts/Rasters/Upernavik/*/*'\n# rasterGroup = root.findGroup(rasterGroupName)\n# rasterLayers = findChildren(root, rasterGroupName)\n# domainGroupName = 'CalvingFronts/Domains/Upernavik*'\n# domainGroup = root.findGroup(domainGroupName)\n# domainLayers = findChildren(root, domainGroupName)\n\nrasterLayers\ncheck_subsetting = True\ncheck_saving = False\ncheck_masking = False\ncheck_postprocessing = False\ncheck_vectorization = False\ncheck_adding = False\n\n#Save subsets of raster source files using clipping domain\nif check_subsetting:\n\tperform_subsetting(rasterLayers, rasterPrefix, domainLayers)\n","sub_path":"preprocessing/calvingfrontmachine/calving_front_machine_standalone.py","file_name":"calving_front_machine_standalone.py","file_ext":"py","file_size_in_byte":31357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"604754120","text":"import fresh_tomatoes\nimport media\n\n# Data inputs for class instances of \"movie\"\n\nbrazil = media.Movie(\n \"Brazil\",\n \"A bureaucrat in a retro-future world tries to correct an\\\n administrative error and himself becomes an enemy of the\\\n state.\",\n \"http://assets.flicks.co.nz/images/movies/poster/89/8973ba741e7bd6450d8023552f43728e_500x735.jpg\", # noqa\n \"https://www.youtube.com/watch?v=EvBF3Lxla98\")\n\n\nnightmare_before_christmas = media.Movie(\n \"The Nightmare Before Christmas\",\n \"Jack Skellington, king of Halloween Town,\\\n discovers Christmas Town, but doesn't quite\\\n understand the concept.\",\n \"http://ecx.images-amazon.com/images/I/51frysl%2BZzL._SX940_.jpg\", # noqa\n \"https://www.youtube.com/watch?v=wr6N_hZyBCk\")\n\nbernie = media.Movie(\n \"Bernie\",\n \"In small-town Texas, an affable mortician strikes up a\\\n friendship with a wealthy widow, though when she starts to\\\n become controlling, he goes to great lengths to separate\\\n himself from her grasp.\",\n \"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTj_-UpQ3isf6NjY3RBlkp-wJOF4fDs75Rd0gu-9mUv8I8RWdwcvg\", # noqa\n \"https://www.youtube.com/watch?v=YJuhWKcY_6U\")\n\nparanorman = media.Movie(\n \"Paranorman\",\n \"A misunderstood boy takes on ghosts, zombies and\\\n grown-ups to save his town from a centuries-old curse.\",\n \"http://www.iceposter.com/thumbs/MOV_81d2f3d4_b.jpg\",\n \"https://www.youtube.com/watch?v=QJaIeGrg6YY\")\n\ncoraline = media.Movie(\n \"Coraline\",\n \"An adventurous girl finds another world that is a\\\n strangely idealized version of her frustrating home,\\\n but it has sinister secrets.\",\n \"https://s-media-cache-ak0.pinimg.com/236x/e6/de/1d/e6de1d31cdfb9a82932b1a82a1c1ed0f.jpg\", # noqa\n \"https://www.youtube.com/watch?v=LO3n67BQvh0\")\n\nbrick = media.Movie(\n \"Brick\",\n \"A teenage loner pushes his way into the underworld of a\\\n high school crime ring to investigate the disappearance of\\\n his ex-girlfriend.\",\n \"https://weekdaymatinee.files.wordpress.com/2011/06/brick_movie_poster_painted_by_jam_bad.jpg\", # noqa\n \"https://www.youtube.com/watch?v=4Zfw8__A7ps\")\n\ncorpsebride = media.Movie(\n \"Corpsebride\",\n \"When a shy groom practices his wedding vows in the\\\n inadvertent presence of a deceased young woman, she rises\\\n from the grave assuming he has married her.\",\n \"http://www.impawards.com/2005/posters/corpse_bride.jpg\",\n \"https://www.youtube.com/watch?v=G9boDkpEyvc\")\n\nboxtrolls = media.Movie(\n \"Boxtrolls\",\n \"A young orphaned boy raised by underground cave-dwelling\\\n trash collectors tries to save his friends from an evil\\\n exterminator.\",\n \"https://s-media-cache-ak0.pinimg.com/736x/a5/04/43/a5044340e12073a122862085ea565c68.jpg\", # noqa\n \"https://www.youtube.com/watch?v=Q2dFVnp5K0o\")\n\n# Build a list of movies\nmovies = [brazil, nightmare_before_christmas, bernie, paranorman, coraline,\n brick, corpsebride, boxtrolls]\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"563489342","text":"import sys\n#import threading\n#import random\nimport time\n#import logging\nimport os\n\n#sys.path.append('.')\nimport rem_server\n\n#import rem.connmanager\n#import rem.scheduler\n#import rem.job\n#import rem.osspec\n#from rem.packet import PacketState\n\n#sys.path.append(\n #os.path.abspath(os.path.dirname(rem_server.__file__)) + '/client')\n\n#rem.osspec.reg_signal_handler = lambda *args: None\n\nimport tempfile\nimport shutil\n\nclass NamedTemporaryDir(object):\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n\n def __enter__(self):\n self.name = tempfile.mkdtemp(*self._args, **self._kwargs)\n print >>sys.stderr, self.name\n return self.name\n\n def __exit__(self, e, t, bt):\n shutil.rmtree(self.name)\n self.name = None\n\ndef produce_config(out, work_dir, hostname):\n print >>out, \"\"\"\n[DEFAULT]\nproject_dir = {project_dir}\n\n[store]\npck_dir = %(project_dir)s/packets\nrecent_tags_file = %(project_dir)s/backups/recent_tags.db\ntags_db_file = %(project_dir)s/backups/tags.db\nremote_tags_db_file = %(project_dir)s/backups/tags-remote.db\nbackup_dir = %(project_dir)s/backups\nbackup_period = 300\nbackup_count = 10\nbackup_child_max_working_time = 900\njournal_lifetime = 3600\nbinary_dir = %(project_dir)s/bin\nbinary_lifetime = 86400\nerror_packet_lifetime = 604800\nsuccess_packet_lifetime = 259200\ncloud_tags_server = localhost:17773\ncloud_tags_masks = file://%(project_dir)s/cloud_tags.masks\n\n[log]\ndir = %(project_dir)s/log\nwarnlevel = debug\nfilename = rem.log\nrollcount = 8\n\n[run]\nsetup_script = %(project_dir)s/setup_env.sh\npoolsize = 100\nxmlrpc_poolsize = 20\nreadonly_xmlrpc_poolsize = 10\n\n[server]\nport = 8104\nreadonly_port = 8103\nsystem_port = 8105\nnetwork_topology = local://%(project_dir)s/network_topology.cfg\nnetwork_hostname = {network_hostname}\nsend_emails = yes\nsend_emergency_emails = no\nuse_memory_profiler = no\n\"\"\".format(\n project_dir=work_dir,\n network_hostname=hostname,\n )\n\ndef create_scheduler(work_dir):\n config_filename = work_dir + \"/rem.cfg\"\n\n with open(config_filename, \"w\") as conf:\n produce_config(conf, work_dir, hostname='foobar')\n\n import rem.context\n ctx = rem.context.Context(config_filename, \"start\")\n\n rem_server._init_fork_locking(ctx)\n\n #import json\n #print json.dumps(ctx.__dict__, indent=3)\n\n with open(work_dir + '/cloud_tags.masks', 'w') as out:\n print >>out, '_cloud_.*'\n\n with open(work_dir + '/network_topology.cfg', 'w') as out:\n print >>out, '[servers]'\n print >>out, 'foobar = http://localhost:8884, http://localhost:8885'\n\n return rem_server.CreateScheduler(ctx)\n\nclass Scheduler(object):\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n self._sched = None\n\n def __enter__(self):\n self._sched = create_scheduler(*self._args, **self._kwargs)\n self._sched.Start()\n return self._sched\n\n def __exit__(self, e, t, bt):\n sched = self._sched\n self._sched = None\n sched.Stop()\n\nif __name__ == '__main__':\n #print >>sys.stderr, 'helpers.py pid =', os.getpid()\n #sched, join_daemon = start(with_daemon=True)\n #join_daemon()\n\n def remove_if(dir, cond):\n for item in os.listdir(dir):\n if cond(item):\n os.unlink(dir + '/' + item)\n\n def remove_backups(work_dir):\n remove_if(work_dir + '/backups', lambda file : file.startswith('sched-'))\n\n def remove_journal(work_dir):\n remove_if(work_dir + '/backups', lambda file : file.startswith('recent_tags.db'))\n\n print >>sys.stderr, os.getpid()\n\n def test_01(do_intermediate_backup=False,\n do_final_backup=False,\n do_remove_journal=False,\n do_remove_backups=False):\n\n #print do_intermediate_backup, do_final_backup, do_remove_journal, do_remove_backups\n\n def get_updates():\n return sched.tagRef._safe_cloud.get_state_updates()\n\n def backup():\n sched.RollBackup()\n time.sleep(1.5) # hack for same-timestamp-in-journal-filename problem\n\n with NamedTemporaryDir(prefix='remd-') as work_dir:\n with Scheduler(work_dir) as sched:\n tags = sched.tagRef\n\n assert get_updates() == []\n\n tags.AcquireTag('_cloud_tag_01').Reset('message01')\n assert len(get_updates()) == 1\n\n if do_intermediate_backup:\n backup()\n #print os.listdir(work_dir + '/backups')\n\n tags.AcquireTag('_cloud_tag_02').Reset('message02')\n\n all_updates = get_updates()\n assert len(all_updates) == 2\n\n if do_final_backup:\n backup()\n #print os.listdir(work_dir + '/backups')\n\n if do_remove_journal:\n remove_journal(work_dir)\n\n if do_remove_backups:\n remove_backups(work_dir)\n\n #print \"-----------------------------------------------\"\n with Scheduler(work_dir) as sched:\n #print os.listdir(work_dir + '/backups')\n updates = get_updates()\n\n if do_remove_journal and do_remove_backups:\n assert updates == []\n\n elif do_remove_backups:\n assert updates == all_updates\n\n elif do_remove_journal:\n if do_final_backup:\n assert updates == all_updates\n elif do_intermediate_backup:\n assert updates == all_updates[0:1]\n else:\n assert updates == []\n\n for do_intermediate_backup in [True, False]:\n for do_final_backup in [True, False]:\n for do_remove_journal in [True, False]:\n for do_remove_backups in [True, False]:\n test_01(\n do_intermediate_backup=do_intermediate_backup,\n do_final_backup=do_final_backup,\n do_remove_journal=do_remove_journal,\n do_remove_backups=do_remove_backups,\n )\n","sub_path":"server/rem/test_safe_cloud.py","file_name":"test_safe_cloud.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"564477196","text":"# coding=utf8\n#\n# linter.py\n# Part of SublimeLinter3, a code checking framework for Sublime Text 3\n#\n# Written by Ryan Hileman and Aparajita Fishman\n# Change for CudaLint: Alexey T.\n#\n# Project: https://github.com/SublimeLinter/SublimeLinter3\n# License: MIT\n#\n\nimport os\nimport re\nimport shlex\nfrom numbers import Number\n\nimport cudatext as app\nfrom . import util\nfrom .options import KIND_ERROR, KIND_WARN, KIND_INFO\n\nWARNING = 'warning'\nERROR = 'error'\n\n#\n# Private constants\n#\nARG_RE = re.compile(r'(?P@|--?)?(?P[@\\w][\\w\\-]*)(?:(?P[=:])(?:(?P.)(?P\\+)?)?)?')\n\n# Colors of bookmarks\n\nlinter_classes = {}\n\nclass LinterMeta(type):\n\n def __init__(cls, name, bases, attrs):\n \"\"\"\n Initialize a Linter class.\n\n When a Linter subclass is loaded by Sublime Text, this method is called.\n We take this opportunity to do some transformations:\n\n - Compile regex patterns.\n - Convert strings to tuples where necessary.\n - Add a leading dot to the tempfile_suffix if necessary.\n - Build a map between defaults and linter arguments.\n - Add '@python' as an inline setting to PythonLinter subclasses.\n\n Finally, the class is registered as a linter for its configured syntax.\n\n \"\"\"\n\n if bases:\n setattr(cls, 'disabled', False)\n\n if name in ('PythonLinter', 'RubyLinter'):\n return\n\n cmd = attrs.get('cmd')\n\n if isinstance(cmd, str):\n setattr(cls, 'cmd', shlex.split(cmd))\n\n syntax = attrs.get('syntax')\n\n try:\n if isinstance(syntax, str) and syntax[0] == '^':\n setattr(cls, 'syntax', re.compile(syntax))\n except re.error as err:\n print(\n 'ERROR: {} disabled, error compiling syntax: {}'\n .format(name.lower(), str(err))\n )\n setattr(cls, 'disabled', True)\n\n if not cls.disabled:\n for regex in ('regex', 'comment_re', 'word_re', 'version_re'):\n attr = getattr(cls, regex)\n\n if isinstance(attr, str):\n if regex == 'regex' and cls.multiline:\n setattr(cls, 're_flags', cls.re_flags | re.MULTILINE)\n\n try:\n setattr(cls, regex, re.compile(attr, cls.re_flags))\n except re.error as err:\n print(\n 'ERROR: {} disabled, error compiling {}: {}'\n .format(name.lower(), regex, str(err))\n )\n setattr(cls, 'disabled', True)\n\n if not cls.disabled:\n if not cls.syntax or (cls.cmd is not None and not cls.cmd) or not cls.regex:\n print('ERROR: {} disabled, not fully implemented'.format(name.lower()))\n setattr(cls, 'disabled', True)\n\n for attr in ('inline_settings', 'inline_overrides'):\n if attr in attrs and isinstance(attrs[attr], str):\n setattr(cls, attr, (attrs[attr],))\n\n cls.reinitialize()\n\n global linter_classes\n linter_classes[name] = cls\n\nclass Linter(metaclass=LinterMeta):\n\n \"\"\"\n The base class for linters.\n\n Subclasses must at a minimum define the attributes syntax, cmd, and regex.\n\n \"\"\"\n\n #\n # Public attributes\n #\n\n # The syntax that the linter handles. May be a string or\n # list/tuple of strings. Names should be all lowercase.\n syntax = ''\n\n # A string, list, tuple or callable that returns a string, list or tuple, containing the\n # command line (with arguments) used to lint.\n cmd = ''\n\n # If the name of the executable cannot be determined by the first element of cmd\n # (for example when cmd is a method that dynamically generates the command line arguments),\n # this can be set to the name of the executable used to do linting.\n #\n # Once the executable's name is determined, its existence is checked in the user's path.\n # If it is not available, the linter is disabled.\n executable = None\n\n # If the executable is available, this is set to the full path of the executable.\n # If the executable is not available, it is set an empty string.\n # Subclasses should consider this read only.\n executable_path = None\n\n # Some linter plugins have version requirements as far as the linter executable.\n # The following three attributes can be defined to define the requirements.\n # version_args is a string/list/tuple that represents the args used to get\n # the linter executable's version as a string.\n version_args = None\n\n # A regex pattern or compiled regex used to match the numeric portion of the version\n # from the output of version_args. It must contain a named capture group called\n # \"version\" that captures only the version, including dots but excluding a prefix\n # such as \"v\".\n version_re = None\n\n # A string which describes the version requirements, suitable for passing to\n # the distutils.versionpredicate.VersionPredicate constructor, as documented here:\n # http://pydoc.org/2.5.1/distutils.versionpredicate.html\n # Only the version requirements (what is inside the parens) should be\n # specified here, do not include the package name or parens.\n version_requirement = None\n\n # A regex pattern used to extract information from the executable's output.\n regex = ''\n\n # Set to True if the linter outputs multiline error messages. When True,\n # regex will be created with the re.MULTILINE flag. Do NOT rely on setting\n # the re.MULTILINE flag within the regex yourself, this attribute must be set.\n multiline = False\n\n # If you want to set flags on the regex *other* than re.MULTILINE, set this.\n re_flags = 0\n\n # The default type assigned to non-classified errors. Should be either\n # ERROR or WARNING.\n default_type = WARNING\n\n # Linters usually report errors with a line number, some with a column number\n # as well. In general, most linters report one-based line numbers and column\n # numbers. If a linter uses zero-based line numbers or column numbers, the\n # linter class should define this attribute accordingly.\n line_col_base = (0, 0)\n\n # If the linter executable cannot receive from stdin and requires a temp file,\n # set this attribute to the suffix of the temp file (with or without leading '.').\n # If the suffix needs to be mapped to the syntax of a file, you may make this\n # a dict that maps syntax names (all lowercase, as used in the syntax attribute),\n # to tempfile suffixes. The syntax used to lookup the suffix is the mapped\n # syntax, after using \"syntax_map\" in settings. If the view's syntax is not\n # in this map, the class' syntax will be used.\n #\n # Some linters can only work from an actual disk file, because they\n # rely on an entire directory structure that cannot be realistically be copied\n # to a temp directory (e.g. javac). In such cases, set this attribute to '-',\n # which marks the linter as \"file-only\". That will disable the linter for\n # any views that are dirty.\n tempfile_suffix = None\n\n # Linters may output to both stdout and stderr. By default stdout and sterr are captured.\n # If a linter will never output anything useful on a stream (including when\n # there is an error within the linter), you can ignore that stream by setting\n # this attribute to the other stream.\n error_stream = util.STREAM_BOTH\n\n # Many linters look for a config file in the linted file?s directory and in\n # all parent directories up to the root directory. However, some of them\n # will not do this if receiving input from stdin, and others use temp files,\n # so looking in the temp file directory doesn?t work. If this attribute\n # is set to a tuple of a config file argument and the name of the config file,\n # the linter will automatically try to find the config file, and if it is found,\n # add the config file argument to the executed command.\n #\n # Example: config_file = ('--config', '.jshintrc')\n #\n config_file = None\n\n # Tab width\n tab_width = 1\n\n # If a linter can be used with embedded code, you need to tell SublimeLinter\n # which portions of the source code contain the embedded code by specifying\n # the embedded scope selectors. This attribute maps syntax names\n # to embedded scope selectors.\n #\n # For example, the HTML syntax uses the scope `source.js.embedded.html`\n # for embedded JavaScript. To allow a JavaScript linter to lint that embedded\n # JavaScript, you would set this attribute to {'html': 'source.js.embedded.html'}.\n selectors = {}\n\n # If a linter reports a column position, SublimeLinter highlights the nearest\n # word at that point. You can customize the regex used to highlight words\n # by setting this to a pattern string or a compiled regex.\n word_re = None\n\n # If you want to provide default settings for the linter, set this attribute.\n # If a setting will be passed as an argument to the linter executable,\n # you may specify the format of the argument here and the setting will\n # automatically be passed as an argument to the executable. The format\n # specification is as follows:\n #\n # [[+]]\n #\n # - : Either empty, '@', '-' or '--'.\n # - : The name of the setting.\n # - : Either '=' or ':'. If is empty or '@', is ignored.\n # Otherwise, if '=', the setting value is joined with by '=' and\n # passed as a single argument. If ':', and the value are passed\n # as separate arguments.\n # - : If the argument accepts a list of values, specifies\n # the character used to delimit the list (usually ',').\n # - +: If the setting can be a list of values, but each value must be\n # passed as a separate argument, terminate the setting with '+'.\n #\n # After the format is parsed, the prefix and suffix are removed and the\n # setting is replaced with .\n defaults = None\n\n # Linters may define a list of settings that can be specified inline.\n # As with defaults, you can specify that an inline setting should be passed\n # as an argument by using a prefix and optional suffix. However, if\n # the same setting was already specified as an argument in defaults,\n # you do not need to use the prefix or suffix here.\n #\n # Within a file, the actual inline setting name is '-setting', where \n # is the lowercase name of the linter class.\n inline_settings = None\n\n # Many linters allow a list of options to be specified for a single setting.\n # For example, you can often specify a list of errors to ignore.\n # This attribute is like inline_settings, but inline values will override\n # existing values instead of replacing them, using the override_options method.\n inline_overrides = None\n\n # If the linter supports inline settings, you need to specify the regex that\n # begins a comment. comment_re should be an unanchored pattern (no ^)\n # that matches everything through the comment prefix, including leading whitespace.\n #\n # For example, to specify JavaScript comments, you would use the pattern:\n # r'\\s*/[/*]'\n # and for python:\n # r'\\s*#'\n comment_re = None\n\n # Some linters may want to turn a shebang into an inline setting.\n # To do so, set this attribute to a callback which receives the first line\n # of code and returns a tuple/list which contains the name and value for the\n # inline setting, or None if there is no match.\n shebang_match = None\n\n #\n # Internal class storage, do not set\n #\n env = None\n disabled = False\n executable_version = None\n\n @classmethod\n def initialize(cls):\n \"\"\"\n Perform class-level initialization.\n\n If subclasses override this, they should call super().initialize() first.\n\n \"\"\"\n pass\n\n @classmethod\n def reinitialize(cls):\n \"\"\"\n Perform class-level initialization after plugins have been loaded at startup.\n\n This occurs if a new linter plugin is added or reloaded after startup.\n Subclasses may override this to provide custom behavior, then they must\n call cls.initialize().\n\n \"\"\"\n cls.initialize()\n\n def __init__(self, view):\n self.view = view\n self.code = ''\n\n @property\n def filename(self):\n \"\"\"Return the view's file path or '' of unsaved.\"\"\"\n return self.view.get_filename()\n\n @property\n def name(self):\n \"\"\"Return the class name lowercased.\"\"\"\n return self.__class__.__name__.lower()\n\n def find_errors(self, output):\n \"\"\"\n A generator which matches the linter's regex against the linter output.\n\n If multiline is True, split_match is called for each non-overlapping\n match of self.regex. If False, split_match is called for each line\n in output.\n\n \"\"\"\n\n if self.multiline:\n errors = self.regex.finditer(output)\n\n if errors:\n for error in errors:\n yield self.split_match(error)\n else:\n yield self.split_match(None)\n else:\n for line in output.splitlines():\n yield self.split_match(self.regex.match(line.rstrip()))\n\n def split_match(self, match):\n \"\"\"\n Split a match into the standard elements of an error and return them.\n\n If subclasses need to modify the values returned by the regex, they\n should override this method, call super(), then modify the values\n and return them.\n\n \"\"\"\n\n if match:\n items = {'line': None, 'col': None, 'error': None, 'warning': None, 'message': '', 'near': None}\n items.update(match.groupdict())\n line, col, error, warning, message, near = [\n items[k] for k in ('line', 'col', 'error', 'warning', 'message', 'near')\n ]\n\n if line is not None:\n line = int(line) - self.line_col_base[0]\n\n if col is not None:\n if col.isdigit():\n col = int(col) - self.line_col_base[1]\n else:\n col = len(col) + 1\n\n return match, line, col, error, warning, message, near\n else:\n return match, None, None, None, None, '', None\n\n\n def get_cmd(self):\n \"\"\"\n Calculate and return a tuple/list of the command line to be executed.\n\n The cmd class attribute may be a string, a tuple/list, or a callable.\n If cmd is callable, it is called. If the result of the method is\n a string, it is parsed into a list with shlex.split.\n\n Otherwise the result of build_cmd is returned.\n\n \"\"\"\n if callable(self.cmd):\n cmd = self.cmd()\n\n if isinstance(cmd, str):\n cmd = shlex.split(cmd)\n\n return self.insert_args(cmd)\n else:\n return self.build_cmd()\n\n def build_cmd(self, cmd=None):\n \"\"\"\n Return a tuple with the command line to execute.\n\n We start with cmd or the cmd class attribute. If it is a string,\n it is parsed with shlex.split.\n\n If the first element of the command line matches [script]@python[version],\n and '@python' is in the aggregated view settings, util.which is called\n to determine the path to the script and given version of python. This\n allows settings to override the version of python used.\n\n Otherwise, if self.executable_path has already been calculated, that\n is used. If not, the executable path is located with util.which.\n\n If the path to the executable can be determined, a list of extra arguments\n is built with build_args. If the cmd contains '*', it is replaced\n with the extra argument list, otherwise the extra args are appended to\n cmd.\n\n \"\"\"\n\n cmd = cmd or self.cmd\n if cmd is None: return\n\n if isinstance(cmd, str):\n cmd = shlex.split(cmd)\n else:\n cmd = list(cmd)\n\n which = cmd[0]\n have_path, path = self.context_sensitive_executable_path(cmd)\n\n if have_path:\n # Returning None means the linter runs code internally\n if path == '':\n return None\n elif self.executable_path:\n path = self.executable_path\n\n if isinstance(path, (list, tuple)) and None in path:\n path = None\n else:\n path = self.which(which)\n\n if not path:\n persist.printf('ERROR: {} cannot locate \\'{}\\''.format(self.name, which))\n return ''\n\n cmd[0:1] = util.convert_type(path, [])\n return self.insert_args(cmd)\n\n def context_sensitive_executable_path(self, cmd):\n \"\"\"\n Calculate the context-sensitive executable path, return a tuple of (have_path, path).\n\n Subclasses may override this to return a special path.\n\n \"\"\"\n return False, None\n\n def lint(self):\n \"\"\"\n Perform the lint, retrieve the results, and add marks to the view.\n\n The flow of control is as follows:\n\n - Get the command line. If it is an empty string, bail.\n - Run the linter.\n - If the view has been modified since the original hit_time, stop.\n - Parse the linter output with the regex.\n - Highlight warnings and errors.\n\n \"\"\"\n\n error_count = 0\n\n if self.filename:\n cwd = os.getcwd()\n os.chdir(os.path.dirname(self.filename))\n\n if self.cmd is None:\n cmd = None\n else:\n settings = {}\n args_map = {}\n if not self.defaults is None:\n for name, value in self.defaults.items():\n match = ARG_RE.match(name)\n\n if match:\n name = match.group('name')\n args_map[name] = match.groupdict()\n\n settings[name] = value\n\n args = list()\n for setting, arg_info in args_map.items():\n prefix = arg_info['prefix']\n\n if setting not in settings or setting[0] == '@' or prefix is None:\n continue\n\n values = settings[setting]\n\n if values is None:\n continue\n elif isinstance(values, (list, tuple)):\n if values:\n # If the values can be passed as a single list, join them now\n if arg_info['sep'] and not arg_info['multiple']:\n values = [str(value) for value in values]\n values = [arg_info['sep'].join(values)]\n else:\n continue\n elif isinstance(values, str):\n if values:\n values = [values]\n else:\n continue\n elif isinstance(values, Number):\n if values is False:\n continue\n else:\n values = [values]\n else:\n # Unknown type\n continue\n\n for value in values:\n if prefix == '@':\n args.append(str(value))\n else:\n arg = prefix + arg_info['name']\n joiner = arg_info['joiner']\n\n if joiner == '=':\n args.append('{}={}'.format(arg, value))\n elif joiner == ':':\n args.append(arg)\n args.append(str(value))\n\n if callable(self.cmd):\n cmd = self.cmd()\n else:\n cmd = self.cmd\n if isinstance(cmd, str):\n cmd = shlex.split(cmd)\n else:\n cmd = list(cmd)\n\n which = cmd[0]\n have_path, path = self.context_sensitive_executable_path(cmd)\n\n if have_path:\n # Returning None means the linter runs code internally\n if path == '':\n return 0\n elif which is None or self.executable_path is None:\n executable = ''\n\n if not callable(self.cmd):\n if isinstance(self.cmd, (tuple, list)):\n executable = (self.cmd or [''])[0]\n elif isinstance(self.cmd, str):\n executable = self.cmd\n\n if not executable and self.executable:\n executable = self.executable\n\n if executable:\n path = util.which(executable) or ''\n\n if (\n path is None or\n (isinstance(path, (tuple, list)) and None in path)\n ):\n path = ''\n else:\n path = None\n elif self.executable_path:\n path = self.executable_path\n\n if isinstance(path, (list, tuple)) and None in path:\n path = None\n else:\n path = util.which(which)\n\n if not path:\n print('ERROR: {} cannot locate \\'{}\\''.format(self.name, which))\n return 0\n\n cmd[0:1] = util.convert_type(path, [])\n\n if '*' in cmd:\n i = cmd.index('*')\n\n if args:\n cmd[i:i + 1] = args\n else:\n cmd.pop(i)\n else:\n cmd += args\n\n if cmd is not None and not cmd:\n return 0\n\n output = self.run(cmd, self.view.get_text_all())\n\n self.view.bookmark(app.BOOKMARK_CLEAR_ALL, 0)\n if not output:\n return 0\n\n if self.filename:\n os.chdir(cwd)\n\n # app.app_log(app.LOG_SET_PANEL, app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_CLEAR, '', panel=app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_SET_FILENAME, self.filename, panel=app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_SET_LINE_ID, '1', panel=app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_SET_COL_ID, '2', panel=app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_SET_ZEROBASE, '0', panel=app.LOG_PANEL_VALIDATE)\n app.app_log(app.LOG_SET_REGEX, 'Line (\\d+) Col (\\d+):.+', panel=app.LOG_PANEL_VALIDATE)\n\n m = []\n error_list = self.find_errors(output)\n for match, line, col, error, warning, message, near in error_list:\n if match and message and line is not None:\n m.append((line, col, message, error, warning))\n\n error_count = 0\n if m:\n m = sorted(m, key = lambda m: m[0])\n bm = dict()\n for line, col, message, error, warning in m:\n if error:\n bm_kind = KIND_ERROR\n elif warning:\n bm_kind = KIND_WARN\n else:\n if self.default_type == ERROR:\n bm_kind = KIND_ERROR\n elif self.default_type == WARNING:\n bm_kind = KIND_WARN\n else:\n bm_kind = KIND_INFO\n\n if col is None:\n col = 1\n app.app_log(app.LOG_ADD,\n 'Line {} Col {}: {}'.format(line, col, message),\n panel=app.LOG_PANEL_VALIDATE)\n\n bm[line] = (line-1, bm_kind, message)\n error_count += 1\n\n self.view.bookmark(app.BOOKMARK_CLEAR_ALL, 0)\n for line in bm:\n self.view.bookmark(app.BOOKMARK_SET, bm[line][0], bm[line][1], -1, bm[line][2])\n\n return error_count\n\n\n def run(self, cmd, code):\n \"\"\"\n Execute the linter's executable or built in code and return its output.\n\n If a linter uses built in code, it should override this method and return\n a string as the output.\n\n If a linter needs to do complicated setup or will use the tmpdir\n method, it will need to override this method.\n\n \"\"\"\n\n if self.tempfile_suffix:\n if self.tempfile_suffix != '-':\n return self.tmpfile(cmd, code, suffix=self.get_tempfile_suffix())\n else:\n return self.communicate(cmd)\n else:\n return self.communicate(cmd, code)\n\n def get_tempfile_suffix(self):\n \"\"\"Return the mapped tempfile_suffix.\"\"\"\n if self.tempfile_suffix:\n if not isinstance(self.tempfile_suffix, dict):\n suffix = self.tempfile_suffix\n\n if suffix and suffix[0] != '.':\n suffix = '.' + suffix\n\n return suffix\n else:\n return ''\n\n # popen wrappers\n\n def communicate(self, cmd, code=''):\n \"\"\"Run an external executable using stdin to pass code and return its output.\"\"\"\n if '@' in cmd:\n cmd[cmd.index('@')] = self.filename\n elif not code:\n cmd.append(self.filename)\n\n res = util.communicate(\n cmd,\n code,\n output_stream=self.error_stream,\n env=self.env)\n #print('Communucate result-')\n #print(res)\n return res\n\n def tmpfile(self, cmd, code, suffix=''):\n \"\"\"Run an external executable using a temp file to pass code and return its output.\"\"\"\n return util.tmpfile(\n cmd,\n code,\n suffix or self.get_tempfile_suffix(),\n output_stream=self.error_stream,\n env=self.env)\n\n def tmpdir(self, cmd, files, code):\n \"\"\"Run an external executable using a temp dir filled with files and return its output.\"\"\"\n return util.tmpdir(\n cmd,\n files,\n self.filename,\n code,\n output_stream=self.error_stream,\n env=self.env)\n\n def popen(self, cmd, env=None):\n \"\"\"Run cmd in a subprocess with the given environment and return the output.\"\"\"\n return util.popen(\n cmd,\n env=env,\n extra_env=self.env,\n output_stream=self.error_stream)\n","sub_path":"linter.py","file_name":"linter.py","file_ext":"py","file_size_in_byte":26786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"368038289","text":"from pymongo import Connection\n\nConnection=Connection('mongo.stuycs.org')\ndb = Connection.admin\nres=db.authenticate('ml7','ml7')\ndb = Connection['BathroomRating']\n\nAccounts = db.Accounts\nToiletRatings = db.ToiletRatings\nToiletSeatRatings = db.ToiletSeatRatings\nToiletPaperRatings = db.ToiletPaperRatings\nLegRoomRatings = db.LegRoomRatings\nFlusherRatings = db.FlusherRatings\nSmellRatings = db.SmellRatings\nAestheticsRatings = db.AestheticsRatings\nComments = db.Comments\n\ndef register(username,password):\n if Accounts.find({'usernames':username}).count() == 0:\n Accounts.insert({'usernames':username,'passwords':password})\n return True\n else:\n return False\n\ndef verify(username,password):\n if Accounts.find({'usernames':username,'passwords':password}).count() != 0:\n return True\n else:\n return False\n\ndef returnAllAccounts():\n accounts = []\n for account in Accounts.find():\n accounts.append('Username: '+str(account['usernames'])+'Password: '+str(account['passwords']))\n return accounts\n\ndef dropAccounts():\n Accounts.remove({})\n\ndef addToiletRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"toiletList\" not in account:\n toiletList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletList':toiletList}})\n else:\n toiletList = account['toiletList']\n if toiletList == None:\n toiletList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletList':toiletList}})\n else:\n toiletList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'toiletList':toiletList}})\n\n\ndef addToiletRating(username,lat,lng,rating):\n addToiletRatingByUser(username,lat,lng,rating)\n ratingList = ToiletRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n ToiletRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n ToiletRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getToiletRating(lat,lng):\n tmp= ToiletRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\ndef addToiletSeatRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"toiletSeatList\" not in account:\n toiletSeatList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletSeatList':toiletSeatList}})\n else:\n toiletSeatList = account['toiletSeatList']\n if toiletSeatList == None:\n toiletSeatList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletSeatList':toiletSeatList}})\n else:\n toiletSeatList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'toiletSeatList':toiletSeatList}})\n\n\ndef addToiletSeatRating(username,lat,lng,rating):\n addToiletSeatRatingByUser(username,lat,lng,rating)\n ratingList = ToiletSeatRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n ToiletSeatRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n ToiletSeatRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getToiletSeatRating(lat,lng):\n tmp= ToiletSeatRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\n\n\ndef addToiletPaperRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"toiletPaperList\" not in account:\n toiletPaperList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletPaperList':toiletPaperList}})\n else:\n toiletPaperList = account['toiletPaperList']\n if toiletPaperList == None:\n toiletPaperList = [temp]\n Accounts.update({'usernames':username},{'$set':{'toiletPaperList':toiletPaperList}})\n else:\n toiletPaperList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'toiletPaperList':toiletPaperList}})\n\n\ndef addToiletPaperRating(username,lat,lng,rating):\n addToiletPaperRatingByUser(username,lat,lng,rating)\n ratingList = ToiletPaperRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n ToiletPaperRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n ToiletPaperRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getToiletPaperRating(lat,lng):\n tmp= ToiletPaperRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\n\ndef addLegRoomRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"LegRoomList\" not in account:\n LegRoomList = [temp]\n Accounts.update({'usernames':username},{'$set':{'LegRoomList':LegRoomList}})\n else:\n LegRoomList = account['LegRoomList']\n if LegRoomList == None:\n LegRoomList = [temp]\n Accounts.update({'usernames':username},{'$set':{'LegRoomList':LegRoomList}})\n else:\n LegRoomList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'LegRoomList':LegRoomList}})\n\n\ndef addLegRoomRating(username,lat,lng,rating):\n addLegRoomRatingByUser(username,lat,lng,rating)\n ratingList = LegRoomRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n LegRoomRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n LegRoomRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getLegRoomRating(lat,lng):\n tmp= LegRoomRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\n\ndef addFlusherRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"FlusherList\" not in account:\n FlusherList = [temp]\n Accounts.update({'usernames':username},{'$set':{'FlusherList':FlusherList}})\n else:\n FlusherList = account['FlusherList']\n if FlusherList == None:\n FlusherList = [temp]\n Accounts.update({'usernames':username},{'$set':{'FlusherList':FlusherList}})\n else:\n FlusherList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'FlusherList':FlusherList}})\n\n\ndef addFlusherRating(username,lat,lng,rating):\n addFlusherRatingByUser(username,lat,lng,rating)\n ratingList = FlusherRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n FlusherRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n FlusherRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getFlusherRating(lat,lng):\n tmp= FlusherRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\n\ndef addSmellRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"SmellList\" not in account:\n SmellList = [temp]\n Accounts.update({'usernames':username},{'$set':{'SmellList':SmellList}})\n else:\n SmellList = account['SmellList']\n if SmellList == None:\n SmellList = [temp]\n Accounts.update({'usernames':username},{'$set':{'SmellList':SmellList}})\n else:\n SmellList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'SmellList':SmellList}})\n\n\ndef addSmellRating(username,lat,lng,rating):\n addSmellRatingByUser(username,lat,lng,rating)\n ratingList = SmellRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n SmellRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n SmellRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getSmellRating(lat,lng):\n tmp= SmellRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\n\ndef addAestheticsRatingByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"AestheticsList\" not in account:\n AestheticsList = [temp]\n Accounts.update({'usernames':username},{'$set':{'AestheticsList':AestheticsList}})\n else:\n AestheticsList = account['SmellList']\n if AestheticsList == None:\n AestheticsList = [temp]\n Accounts.update({'usernames':username},{'$set':{'AestheticsList':AestheticsList}})\n else:\n AestheticsList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'AestheticsList':AestheticsList}})\n\n\ndef addAestheticsRating(username,lat,lng,rating):\n addAestheticsRatingByUser(username,lat,lng,rating)\n ratingList = AestheticsRatings.find_one({'latitude':lat,'longitude':lng})\n if ratingList == None:\n AestheticsRatings.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n ratingList = ratingList['rating']\n ratingList.append(rating)\n AestheticsRatings.update({'latitude':lat,'longitude':lng},{'$set':{'rating':ratingList}})\n\ndef getAestheticsRating(lat,lng):\n tmp= AestheticsRatings.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n\ndef addCommentByUser(username,lat,lng,rating):\n temp = lat,lng,rating\n account = Accounts.find_one({'usernames':username})\n if \"CommentList\" not in account:\n CommentList = [temp]\n Accounts.update({'usernames':username},{'$set':{'CommentList':CommentList}})\n else:\n CommentList = account['CommentList']\n if CommentList == None:\n CommentList = [temp]\n Accounts.update({'usernames':username},{'$set':{'CommentList':CommentList}})\n else:\n CommentList.append(temp)\n Accounts.update({'usernames':username},{'$set':{'CommentList':CommentList}})\n\n\ndef addComment(username,lat,lng,rating):\n addCommentByUser(username,lat,lng,rating)\n CommentList = Comments.find_one({'latitude':lat,'longitude':lng})\n if CommentList == None:\n Comments.insert({'latitude':lat,'longitude':lng,'rating':[rating]})\n else:\n CommentList = CommentList['rating']\n CommentList.append(rating)\n Comments.update({'latitude':lat,'longitude':lng},{'$set':{'rating':CommentList}})\n\ndef getComments(lat,lng):\n tmp = Comments.find_one({'latitude':lat,'longitude':lng})\n if tmp:\n return tmp[\"rating\"]\n else:\n return []\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":11361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"370786481","text":"def main():\n skills = [\"programming\", \"teamwork\", \"swimming\", \"running\", \"boxing\", \"hiking\"]\n cv = {}\n uname = input(\"Enter your name: \")\n cv[\"name\"] = uname\n uage = input(\"Enter your age: \")\n cv[\"age\"] = int(uage)\n uexperience = input(\"Enter years of experience: \")\n cv[\"experience\"] = int(uexperience)\n cv[\"skills\"] = []\n print(\"1.\"+skills[0]+\" 2.\"+skills[1]+\" 3.\"+skills[2]+\" 4.\"+skills[3]+\" 5.\"+skills[4]+\" 6.\"+skills[5])\n choice1 = input(\"Choose a skill from above by entering its number: \")\n if choice1 == \"1\":\n cv[\"skills\"]= \"programming\"\n elif choice1 == \"2\":\n cv[\"skills\"]= \"teamwork\"\n elif choice1 == \"3\":\n cv[\"skills\"]= \"swimming\"\n elif choice1 == \"4\":\n cv[\"skills\"]= \"running\"\n elif choice1 == \"5\":\n cv[\"skills\"]= \"boxing\"\n elif choice1 == \"6\":\n cv[\"skills\"]= \"hiking\"\n\n choice2 = input(\"Choose another skill from above by entering its number: \")\n if choice2 == \"1\":\n cv[\"skills\"]= \"programming\"\n elif choice2 == \"2\":\n cv[\"skills\"]= \"teamwork\"\n elif choice2 == \"3\":\n cv[\"skills\"]= \"swimming\"\n elif choice2 == \"4\":\n cv[\"skills\"]= \"running\"\n elif choice2 == \"5\":\n cv[\"skills\"]= \"boxing\"\n elif choice2 == \"6\":\n cv[\"skills\"]= \"hiking\"\n\n if cv[\"age\"] > 24 and cv[\"age\"] < 41:\n if cv[\"experience\"] > 4:\n if \"hiking\" in cv[\"skills\"]:\n print(\"Congratulations \"+uname+ \" you were Accepted!\")\n else:\n print(\"Sorry \"+uname+ \" you were Rejected\")\n\n else:\n print(\"Sorry \"+uname+ \" you were Rejected\")\n\n else:\n print(\"Sorry \"+uname+ \" you were Rejected\")\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"recruitment.py","file_name":"recruitment.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"299172779","text":"import unittest\nfrom unittest import mock\nfrom uuid import uuid4\n\nfrom jose import JWTError\n\nfrom frontstage import app\nfrom frontstage.common.authorisation import jwt_authorization\nfrom frontstage.common.session import Session\nfrom frontstage.exceptions.exceptions import JWTValidationError\n\nvalid_jwt = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0eV9pZCI6ImY5NTZlOGFlLTZ\" \\\n \"lMGYtNDQxNC1iMGNmLWEwN2MxYWEzZTM3YiIsImV4cGlyZXNfYXQiOiIxMDAxMjM0NTY\" \\\n \"3ODkiLCJyb2xlIjoicmVzcG9uZGVudCIsInVucmVhZF9tZXNzYWdlX2NvdW50Ijp7InZh\" \\\n \"bHVlIjowLCJyZWZyZXNoX2luIjozMjUyNzY3NDAwMC4wfSwiZXhwaXJlc19pbiI6MzI1M\" \\\n \"jc2NzQwMDAuMH0.m94R50EPIKTJmE6gf6PvCmCq8ZpYwwV8PHSqsJh5fnI\"\nexpired_jwt = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZWZyZXNoX3Rva2VuIjoiNGYzMmI0YjQtNGUwYS00NTUyLThiOTYtODIzNjRjO\" \\\n \"Dk2ZjFiIiwiYWNjZXNzX3Rva2VuIjoiMWMxNGJhOGMtOTlhMS00NjBjLTllYmUtMTFlY2U4NGY1ZTAzIiwic2NvcGUiOlsiIl0sImV\" \\\n \"4cGlyZXNfYXQiOjk0NjY4ODQ2MS4wLCJ1c2VybmFtZSI6InRlc3R1c2VyQGVtYWlsLmNvbSIsInJvbGUiOiJyZXNwb25kZW50Iiwic\" \\\n \"GFydHlfaWQiOiJkYjAzNmZkNy1jZTE3LTQwYzItYThmYy05MzJlN2MyMjgzOTcifQ.ro95XUJ2gqgz7ecF2r3guSi-kh4wI_XYTgUF\" \\\n \"8IZFHDA\"\nno_expiry_jwt = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZWZyZXNoX3Rva2VuIjoiMGE0NGQ4YzYtZWEzYy00ZTMzLTg4MDctNjJkYmV\" \\\n \"iOTNlMzZhIiwiYWNjZXNzX3Rva2VuIjoiYWVmZTkyYjAtNTYxYi00ZWM0LTljNTYtMTYwZGZhNGIzNzY0Iiwicm9sZSI6InJlc3B\" \\\n \"vbmRlbnQiLCJwYXJ0eV9pZCI6IjU2NWJjMDc5LWVkMDItNDk0MS04ODgyLWRhZTZmYzE4NWEzZCJ9.unskbEm5dWQfCTvE25cxrO\" \\\n \"hAf1_Ii8ZXiLhBioQq8OE\"\n\n\nclass TestJWTAuthorization(unittest.TestCase):\n\n def setUp(self):\n self.app = app.test_client()\n self.app.testing = True\n self.session = Session.from_party_id(\"test\")\n\n def tearDown(self):\n self.session.delete_session()\n\n @staticmethod\n def decorator_test(request):\n @jwt_authorization(request)\n def test_function(session):\n pass\n test_function()\n\n def test_jwt_authorization_success(self):\n self.session.encoded_jwt_token = valid_jwt\n self.session.session_key = str(uuid4())\n self.session.save()\n request = mock.MagicMock(cookies={\"authorization\": self.session.session_key})\n\n # If this function runs without exceptions the test is considered passed\n self.decorator_test(request)\n\n def test_jwt_authorization_expired_jwt(self):\n self.session.encoded_jwt_token = expired_jwt\n self.session.session_key = str(uuid4())\n self.session.save()\n request = mock.MagicMock(cookies={\"authorization\": self.session.session_key})\n\n with self.assertRaises(JWTValidationError):\n self.decorator_test(request)\n\n def test_jwt_authorization_no_expiry(self):\n self.session.encoded_jwt_token = no_expiry_jwt\n self.session.session_key = str(uuid4())\n self.session.save()\n request = mock.MagicMock(cookies={\"authorization\": self.session.session_key})\n\n with self.assertRaises(JWTValidationError):\n self.decorator_test(request)\n\n @mock.patch('frontstage.common.authorisation.decode')\n def test_jwt_authorization_decode_failure(self, mock_decode):\n self.session.encoded_jwt_token = valid_jwt\n self.session.session_key = str(uuid4())\n self.session.save()\n request = mock.MagicMock(cookies={\"authorization\": self.session.session_key})\n mock_decode.side_effect = JWTError\n\n with self.assertRaises(JWTValidationError):\n self.decorator_test(request)\n","sub_path":"tests/integration/test_jwt_authorization.py","file_name":"test_jwt_authorization.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"250572920","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 20 22:26:08 2016\r\n\r\n@author: jean\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\ntry:\r\n import cPickle as pickle\r\nexcept:\r\n import pickle\r\nfrom point import *\r\n\r\n\r\nclass Line:\r\n e_par_km = 1 * 10**8\r\n e_par_station = 3 * 10**7\r\n e_par_train = 1 * 10**7\r\n \r\n ###\r\n ### PROPERTIES\r\n ###\r\n \r\n def __init__(self, lid, network, name=None):\r\n self.lid = lid\r\n self.station = dict()\r\n self.where = dict() #inverse de station\r\n self.stop_time = 15 / 3600 #30 s en h\r\n self.speed = 50\r\n self.f = 30 #nb par heures\r\n \r\n self.network = network\r\n if name == None : self.name = \"L\" + str(self.lid)\r\n else : selt.name = name\r\n \r\n self.direct = None\r\n self.indirect = None\r\n \r\n def __repr__(self):\r\n print(\"Line\", self.lid, \":\")\r\n print(self.station)\r\n return \"\"\r\n def __len__(self): return len(self.station)\r\n def __getitem__(self, idx): return self.station[idx]\r\n def __setitem__(self, idx, val): self.station[idx] = val\r\n\r\n def times(self):\r\n t = []\r\n for s1, s2 in self.pairs():\r\n t.append(self.network.time(s1, s2))\r\n t.append(self.network.time(s2, s1))\r\n return t\r\n \r\n def dists(self) :\r\n d = []\r\n for s1, s2 in self.pairs():\r\n d.append(s1.dist(s2))\r\n d.append(s2.dist(s1))\r\n return d\r\n \r\n def trains(self):\r\n return self.f * sum(self.times())\r\n \r\n def pairs(self) :\r\n for i in self.station :\r\n if i > 0 :\r\n yield self[i-1], self[i]\r\n ###\r\n ### FILES\r\n ###\r\n \r\n def import_points(file):\r\n with open(file, \"rb\") as file :\r\n mon_pickler = pickle.Unpickler(file)\r\n points = mon_pickler.load()\r\n \r\n return points\r\n \r\n \r\n def export_points(self):\r\n points = []\r\n for s in self.station.values() :\r\n points.append([s.X, s.Y])\r\n return points\r\n \r\n ###\r\n ### BUILD\r\n ###\r\n \r\n def add(self, station, where=None):\r\n \"\"\"Ajoute une station à la ligne, par défaut à la fin\"\"\"\r\n if where == None :\r\n where = len(self)\r\n #décalage de toutes les station :\r\n for i in np.arange(len(self), where, -1) :\r\n #on fait de la place\r\n self[i] = self[i-1]\r\n self.where[self[i]] = i\r\n #on rompt le lien entre i et i-1 si on insère en i\r\n if where > 0 and where + 1 < len(self.station) :\r\n self[where].unlink(self[where - 1])\r\n #insertion\r\n self.station[where] = station\r\n self.where[station] = where\r\n #Ajout des voisins\r\n if where > 0 :\r\n station.link(self[where - 1])\r\n if where + 1 < len(self.station) :\r\n station.link(self[where + 1])\r\n return self.station\r\n \r\n def remove(self, station):\r\n \"\"\"Enlève une station à la ligne\"\"\"\r\n #Variable à partir de quand enlever 1\r\n remove_one = False\r\n for i in range(len(self.station)) :\r\n #On décale qu'APRES la station\r\n if remove_one : \r\n self.station[i - 1] = self.station[i]\r\n self.where[self.station[i - 1]] = i - 1\r\n if self[i].pid == station.pid :\r\n #1 On déconnecte les voisins\r\n if i > 0 :\r\n station.unlink(self[i - 1])\r\n if i + 1 < len(self.station) :\r\n station.unlink(self[i + 1])\r\n #2 on les connecte entre eux si on est pas une extrémité\r\n if i > 0 and i + 1 < len(self.station) :\r\n self[i - 1].link(self[i + 1]) \r\n #On indique qu'il faut à présent enlever 1 à tous ceux après\r\n remove_one = True\r\n self.where.pop(station)\r\n #Il reste qu'une valeur à enlever : la dernière qui est en double\r\n self.station.pop(len(self.station) - 1)\r\n return self.station\r\n \r\n \r\n def plot(self, plt, points=True, edges=False):\r\n X = []\r\n Y = []\r\n for n, station in self.station.items():\r\n X.append(station.X)\r\n Y.append(station.Y)\r\n plt = station.plot(plt, point=points, edges=edges, zorder=20)\r\n plt.plot(X, Y, label=self.lid, marker=\"o\", zorder=0)\r\n return plt\r\n \r\n ###\r\n ### WORK\r\n ###\r\n \r\n def load(self, load):\r\n self.direct = load[0]\r\n self.indirect = load[1]\r\n \r\n def costs(self):\r\n rails = sum(self.dists()) / 2 * self.e_par_km #construction\r\n \r\n stations = len(self) * self.e_par_station #stations\r\n \r\n trains = self.trains() * self.e_par_train #trains\r\n \r\n return [rails, stations, trains]\r\n \r\n\r\n#%%\r\n ","sub_path":"line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"105025438","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\nfrom operator import *\n\n\nram = [0] * 256\nregisters = [0] * 8 # [0, 0, 0, 0, 0, 0, 0, 0]\n\nregisters[7] = 255 #hex(255)\n\nIR = 0 # contains copy of currently executing command\nHLT = 1\n\n## ALU ops\n \nADD = 10100000 \nSUB = 10100001 \nMUL = 10100010 \nDIV = 10100011 \nMOD = 10100100 \nINC = 1100101 \nDEC = 1100110 \nCMP = 10100111 \nAND = 10101000 \nNOT = 1101001 \nOR = 10101010 \nXOR = 10101011 \nSHL = 10101100 \nSHR = 10101101 \n\n## Other\n\nNOP = 0\nLDI = 10000010\nLD = 10000011\nST = 10000100 \nPUSH = 1000101\nPOP = 1000110\nPRN = 1000111\nPRA = 1001000\n\n## PC mutators\n\nCALL = 1010000\nRET = 10001\nINT = 1010010\nIRET = 10011\nJMP = 1010100 \nJEQ = 1010101 \nJNE = 1010110 \nJGT = 1010111 \nJLT = 1011000 \nJLE = 1011001\nJGE = 1011010 \n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n self.registers = [0] * 8 # [0, 0, 0, 0, 0, 0, 0, 0]\n self.PC = 0\n self.FL = 0\n self.SP = 0xF3\n self.SP = self.registers[7] # STACK POINTER (SP) R7\n self.IS = self.registers[6] # INTERRUPT STATUS (IS) R6\n self.IM = self.registers[5] # INTERRUPT MASK (IM) R5\n \n def ram_read(self, mar):\n mdr = ram[mar]\n return mdr\n \n def ram_write(self, mar, mdr): \n ram[mar] = mdr\n\n # RETURNS A 8BIT BINARY\n def p8(self, v):\n return \"{:08b}\".format(v)\n\n # use this to print letters\n def get_ascii(self, binary_in):\n \n print(\"binary_in: \", binary_in)\n n = int(str(binary_in), 2)\n n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()\n return n\n\n def load_memory(self, ram, filename):\n address = 0\n try:\n with open(filename) as file:\n for line in file:\n comment_split = line.split('#')\n possible_number = comment_split[0]\n if possible_number == '' or possible_number == '\\n':\n continue\n instruction = int(possible_number)\n ram[address] = instruction \n address += 1\n return ram\n except IOError: #FileNotFoundError\n print('I cannot find that file, check the name')\n sys.exit(2)\n\n # print the register values, only for debugging\n def print_registers(self):\n print(\"registers[0]: \", self.registers[0])\n print(\"registers[1]: \", self.registers[1])\n print(\"registers[2]: \", self.registers[2])\n print(\"registers[3]: \", self.registers[3])\n print(\"registers[4]: \", self.registers[4])\n print(\"registers[5]: \", self.registers[5])\n print(\"registers[6]: \", self.registers[6])\n print(\"registers[7]: \", self.registers[7])\n\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.PC,\n #self.SP,\n #self.ie,\n self.ram_read(self.PC),\n self.ram_read(self.PC + 1),\n self.ram_read(self.PC + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.registers[i], end='')\n\n print() \n\n def run(self, ram):\n \"\"\"Run the CPU.\"\"\"\n running = True\n IR = 0\n self.PC = 0\n self.registers[7] = 0xF3\n self.SP = self.registers[7]\n self.ram_read(self.PC)\n \n while running:\n \n #self.print_registers()\n #self.trace()\n #print(\"ram: \", ram)\n command = ram[self.PC]\n \n if command == HLT:\n running = False\n \n elif command == LD:\n # Loads registerA with the value at the memory address stored in registerB\n # get the two register addresses a and b \n\n # take the value of register b and store it in register a \n register_address_a = ram[self.PC + 1]\n register_address_b = ram[self.PC + 2]\n \n self.registers[register_address_a] = self.registers[register_address_b]\n\n self.PC += 3\n\n elif command == LDI:\n op = ram[self.PC]\n register = int(str(ram[self.PC + 1]), 2)\n value = ram[self.PC + 2] \n self.registers[register] = int(value)\n self.PC += 3 \n \n elif command == PRA:\n # read the register number\n register = int(str(ram[self.PC + 1]), 2)\n # get the value that is at this register\n value = self.registers[register]\n # print the value\n letter = self.get_ascii(value)\n print(letter)\n self.PC += 2\n\n elif command == PRN:\n # read the register number\n register = int(str(ram[self.PC + 1]), 2)\n # get the value that is at this register\n value = self.registers[register]\n # print the value\n print(int(str(value), 2))\n self.PC += 2\n\n elif command == AND: \n pass\n print(\"AND:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n test = bin(int(str(value_a), 2)) \n test2 = bin(int(str(value_b), 2))\n self.PC += 3\n\n elif command == OR: \n pass\n print(\"OR:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n print(bin(value_a))\n print(bin(value_b))\n self.PC += 3\n\n elif command == XOR: \n pass\n print(\"XOR:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n print(bin(value_a))\n print(bin(value_b))\n self.PC += 3\n\n elif command == NOT: \n pass\n print(\"NOT:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n print(bin(value_a))\n print(bin(value_b))\n self.PC += 3\n\n elif command == SHL:\n pass \n print(\"SHL:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n print(bin(value_a))\n print(bin(value_b))\n self.PC += 3\n\n elif command == SHR: \n pass\n print(\"SHR:\")\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n print(bin(value_a))\n print(bin(value_b))\n self.PC += 3 \n \n elif command == ADD:\n # get the address for both of the values \n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n # using the address retrieve the integer values then add them \n sum = int(str(self.registers[first_register]), 2) + int(str(self.registers[second_register]), 2)\n sum = (bin(sum))[2:]\n # save the sum to the first register\n self.registers[first_register] = sum\n self.PC += 3\n \n elif command == ST:\n # store the value in register b in the address stored in register a\n # get the two register addresses from the PC\n register_address_a = ram[self.PC + 1]\n register_address_b = ram[self.PC + 2]\n self.registers[register_address_a] = self.registers[register_address_b]\n self.PC += 3\n \n elif command == SUB:\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n diff = self.registers[first_register] - self.registers[second_register]\n self.registers[first_register] = diff\n self.PC += 3\n\n elif command == MUL:\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n # Multiply the first register by the second register\n prod = self.registers[first_register] * self.registers[second_register]\n # save the product to the first register\n self.registers[first_register] = prod\n self.PC += 3\n\n elif command == CMP:\n # get the two register values\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n # compare the values if reg_a is less than reg_b set FL to 00000100\n if value_a < value_b:\n self.FL = 100\n # compare the values if reg_a is greater than reg_b set FL to 00000010\n elif value_a > value_b:\n self.FL = 10\n # compare the values if reg_a is equal to reg_b set FL to 00000001\n else:\n self.FL = 1\n # advance the program counter\n self.PC += 3 \n \n elif command == DIV:\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n # make sure we arent trying to divide by zero\n if value_b > 0:\n value = value_a // value_b\n self.registers[first_register] = value\n # advance the program counter\n self.PC += 3\n else:\n print(\"Unable to divide by zero\")\n running = False\n\n elif command == PUSH:\n self.registers[7] = ( self.registers[7] - 1 ) % 255\n self.SP = self.registers[7]\n register_address = ram[self.PC + 1]\n value = self.registers[register_address]\n ram[self.SP] = value \n self.PC += 2\n\n elif command == POP:\n self.SP = self.registers[7]\n value = ram[self.SP]\n register_address = int(str(ram[self.PC + 1]), 2)\n self.registers[register_address] = value\n self.registers[7] = ( self.SP + 1 ) % 255\n self.PC += 2\n\n elif command == MOD:\n first_register = ram[self.PC + 1]\n second_register = ram[self.PC + 2]\n value_a = self.registers[first_register]\n value_b = self.registers[second_register]\n # make sure we arent trying to divide by zero\n if value_b > 0:\n value = value_a // value_b\n self.registers[first_register] = value\n # advance the program counter\n self.PC += 3\n else:\n print(\"Unable to divide by zero\")\n running = False\n \n elif command == INC:\n register = ram[self.PC + 1]\n value = self.registers[register]\n value = hex(value)\n self.registers[register] = value\n self.PC += 2\n\n elif command == JEQ: \n # If `equal` flag is set (true), jump to the address stored in the given register. \n if self.FL == 1:\n register = ram[self.PC + 1]\n register = int(str(register), 2)\n value = self.registers[register]\n self.PC = int(str(value), 2) \n # if the values are not equal advance the program counter\n else:\n self.PC += 2 \n \n elif command == JNE: \n # If `E` flag is clear (false, 0), jump to the address stored in the given register. \n if self.FL == 100 or self.FL == 10:\n register = ram[self.PC + 1]\n register = int(str(register), 2) \n value = self.registers[register]\n self.PC = int(str(value), 2) \n # if the values are not equal advance the program counter\n else:\n self.PC += 2 \n \n elif command == JMP:\n register_address = ram[self.PC + 1]\n register_address = int(str(register_address), 2)\n address_to_jump_to = self.registers[register_address]\n address_to_jump_to = int(str(address_to_jump_to), 2)\n self.PC = address_to_jump_to \n \n elif command == CALL:\n # push address of instruction after CALL to stack\n # get the register address from ram\n register_address = ram[self.PC + 1]\n # check contents for the address we are going to jump to\n register_address = int(str(register_address), 2)\n address_to_jump_to = self.registers[register_address] \n # save the next instruction address for the RETurn\n next_instruction_address = bin(self.PC + 2)\n next_instruction_address = int(next_instruction_address[2:]) \n self.registers[7] = (self.registers[7] - 1) % 255\n # update the stack pointer\n self.SP = self.registers[7]\n # write the next instruction address to the stack in ram\n ram[self.SP] = next_instruction_address\n # move program counter to new location\n self.PC = int(str(address_to_jump_to), 2)\n \n elif command == RET:\n # get the location of our return_to_address\n self.SP = self.registers[7]\n # save the address from the stack\n address_to_return_to = ram[self.SP]\n # update thestack pointer\n self.registers[7] = ( self.SP + 1 ) % 255\n # set the program counter to its new location address\n self.PC = int(address_to_return_to)\n self.PC = int(str(self.PC), 2)\n else:\n running = False \n","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":15505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"64188938","text":"import random\nimport json\nimport pickle\nimport numpy as np\nimport nltk\n\n\nfrom nltk.stem import WordNetLemmatizer\nfrom tensorflow.keras.models import load_model\nnltk.download('wordnet')\nlemmatizer = WordNetLemmatizer()\nintents = json.loads(open(\"intents.json\").read())\n\nwords = pickle.load(open('words.pkl', 'rb')) #contains words\nclasses = pickle.load(open('classes.pkl', 'rb')) #contains classes\nmodel = load_model('speakModel.h5')\n\ndef clean_up_sentence(sentence):\n sentence_words = nltk.word_tokenize(sentence)\n sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]\n print(sentence_words)\n return sentence_words\n\ndef bag_of_words(sentence, words):\n sentence_words = clean_up_sentence(sentence)\n bag = [0]*len(words)\n for w in sentence_words:\n for i, words in enumerate(words):\n if words == w:\n bag[i] = 1\n \n return (np.array(bag))\n\ndef predict_class(sentence, model):\n bow = bag_of_words(sentence, words)\n res = model.predict(np.array([bow]))[0]\n ERROR_THERSHOLD = 0.20\n results = [[i, r] for i, r in enumerate(res) if r > ERROR_THERSHOLD]\n\n results.sort(key=lambda x: x[1], reverse=True)\n return_list = []\n for r in results:\n return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})\n print(return_list)\n return return_list\n\ndef get_response(intent_list, intent_json):\n tag = intent_list[0]['intent']\n list_of_intents = intent_json['intents']\n for i in list_of_intents:\n if i['tag'] == tag:\n result = random.choice(i['responses'])\n break\n return result\n\nprint(\"[+] Speak is running.\")\n\nwhile True:\n message = input('')\n ints = predict_class(message, model)\n res = get_response(ints, intents)\n print('[*] '+res)","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"487903283","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport calendar\nimport configparser\nimport csv\nimport datetime\nimport json\nimport sys\nimport pyinstaller\n\nimport time\nfrom time import strftime, localtime\nfrom urllib.request import urlopen\n\nimport openpyxl\n\n\n# 打印当前时间\ndef getNowTime():\n nowTime = strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n return nowTime\n\n\n'''\n获取临时的结果,结果从大到小排序\ntype:In 获取in流量,Out获取out流量\n'''\n\n\ndef getListByInOrOut(type=\"In\", device=\"\", interface=\"\", ):\n tempList = []\n try:\n if (type == \"In\"):\n url = param.InOctets2bps\n else:\n url = param.OutOctets2bps\n startTime = int(time.mktime(datetime.datetime.strptime(param.startTime, '%Y%m%d').timetuple()))\n endTime = int(time.mktime(datetime.datetime.strptime(param.endTime, '%Y%m%d').timetuple()))\n stepFrequency = int((endTime - startTime) / 10009)\n url = url.replace(\"device\", device)\n url = url.replace(\"interface\", interface)\n url = url.replace(\"startTime\", str(startTime))\n url = url.replace(\"endTime\", str(endTime))\n url = url.replace(\"stepFrequency\", str(stepFrequency))\n tempResult = get_result_page(url)\n values = json.loads(tempResult)['data']['result'][0]['values']\n for i in range(0, list(values).__len__()):\n temparr = [values[i][0], int(float(values[i][1]))]\n tempList.append(temparr)\n tempList = sorted(tempList, key=(lambda x: x[1]), reverse=True)\n except Exception as e:\n print(\"url:\" + url)\n raise\n return tempList\n\n\n'''\n根据list结果获取95%最大值最小值 平均数\n'''\n\n\ndef getAvgMinMaxByList(list):\n byList = {}\n nsum = 0\n for i in range(0, list.__len__()):\n nsum += list[i][1]\n byList[\"avg\"] = round(nsum / list.__len__() / 1000 / 1024, 2)\n byList[\"min\"] = round(list[round(list.__len__() * 0.95)][1] / 1000 / 1024, 2)\n byList[\"max\"] = round(list[list.__len__() - round(list.__len__() * 0.95)][1] / 1000 / 1024, 2)\n return byList\n\n\n'''\n根据 接口和设备获取参数\n'''\n\n\ndef getResult(bandwidth=\"\", device=\"\", interface=\"\"):\n result = []\n inList = getListByInOrOut(type=\"In\", device=device, interface=interface)\n outList = getListByInOrOut(type=\"Out\", device=device, interface=interface)\n inListR = getAvgMinMaxByList(inList)\n outListR = getAvgMinMaxByList(outList)\n result.append(inListR[\"avg\"])\n result.append(outListR[\"avg\"])\n result.append(inListR[\"max\"])\n result.append(outListR[\"max\"])\n imax95 = round(float(inListR[\"max\"]) * 100 / int(bandwidth), 2)\n omax95 = round(float(outListR[\"max\"]) * 100 / int(bandwidth), 2)\n result.append(imax95)\n result.append(omax95)\n if (imax95 >= omax95):\n result.append(imax95)\n else:\n result.append(omax95)\n return result\n\n\n# 读取execl 改变excel内容\ndef readExcel(filename):\n wb = openpyxl.load_workbook(filename)\n ws = wb.active\n for i in range(1, ws.max_row + 1):\n bandwidth = ws.cell(row=i, column=3).value\n device = ws.cell(row=i, column=4).value\n interface = ws.cell(row=i, column=5).value\n if (bandwidth != None and device != None and interface != None and str(bandwidth).isdigit()):\n try:\n print(\"device:\" + device + \"\\tinterface:\" + interface)\n result = getResult(bandwidth=bandwidth, device=device, interface=interface)\n except Exception as e:\n # print(e)\n continue\n ws.cell(row=i, column=6, value=str(result[0]))\n ws.cell(row=i, column=7, value=str(result[1]))\n ws.cell(row=i, column=8, value=str(result[2]))\n ws.cell(row=i, column=9, value=str(result[3]))\n ws.cell(row=i, column=10, value=str(result[4]))\n ws.cell(row=i, column=11, value=str(result[5]))\n ws.cell(row=i, column=12, value=str(result[6]))\n wb.save(filename)\n wb.close()\n\n\n# 访问\ndef get_result_page(url):\n res = urlopen(url).read()\n return str(res, 'utf-8')\n\n\n## 加载conf里面的配置\ndef getConfig(configName='config.conf'):\n config = configparser.ConfigParser()\n config.read(configName, encoding='UTF-8-sig')\n param.startTime = str(config.get('time_config', 'startTime'))\n param.endTime = str(config.get('time_config', 'endTime'))\n param.excelFileName = str(config.get('excel_config', 'excelFileName'))\n param.InOctets2bps = str(config.get('default_config', 'InOctets2bps')[1:-1])\n param.OutOctets2bps = str(config.get('default_config', 'OutOctets2bps')[1:-1])\n\n\nclass confParam:\n startTime = \"\"\n endTime = \"\"\n excelFileName = \"\"\n InOctets2bps = \"\"\n OutOctets2bps = \"\"\n\n\n'''\n获取上一个周五的日期\n'''\n\n\ndef getLastFriday(nowDate=\"\"):\n oneday = datetime.timedelta(days=1)\n if (nowDate == \"\"):\n lastFriday = datetime.date.today()\n else:\n lastFriday = datetime.datetime.strptime(nowDate, '%Y%m%d')\n if (lastFriday.weekday() == calendar.FRIDAY):\n lastFriday -= oneday\n while lastFriday.weekday() != calendar.FRIDAY:\n lastFriday -= oneday\n return lastFriday.strftime('%Y%m%d')\n\n\nclass Logger(object):\n def __init__(self, filename='log.txt', stream=sys.stdout):\n self.terminal = stream\n self.log = open(filename, 'a', encoding='utf8')\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n\nsys.stdout = Logger('log.txt', sys.stdout)\nsys.stderr = Logger('log.txt', sys.stderr)\n\nif __name__ == '__main__':\n param = confParam()\n getConfig()\n # print(\"excelFileName:\"+param.excelFileName)\n # print(\"InOctets2bps:\"+param.InOctets2bps)\n # print(\"OutOctets2bps:\"+param.OutOctets2bps)\n if (param.endTime == \"\"):\n param.endTime = getLastFriday()\n param.startTime = getLastFriday(param.endTime)\n readExcel(param.excelFileName)\n","sub_path":"IP_transit_report/report/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"17920905","text":"# Name:  Luke Harrison Date Assigned: Sep 24, 2015    \n# Name: Mitchell Gressett\n# \n# Course:  CSE 1284 Sec 13 Date Due:  Sep 24, 2015  \n#\n# File name:  llh281_mdg249_progressreport.py\n#\n# Program Description:  Calculate progress report.\n\n#get years\nyear = int(input('How many years do you wish to input? '))\nprint('Input the average rainfall for each year and month')\n\n\n#set globals\nmost_rainfall = 0\nnum_month = 0\ntotal = 0\n\n#get rainfall stats\nfor each in range(year):\n\n for month in ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'):\n num_month += 1\n\n \n\n print('Year', each + 1,' ', month,': ', end = '')\n rainfall = float(input()) \n total += rainfall\n\n if rainfall > most_rainfall:\n\n\n most_rainfall = rainfall\n most_year = each + 1\n most_month = month\n print('\\n')\n\n#calculations\ntotal = round(total, 3)\naverage = round(total/num_month, 3)\n\n#print results\nprint('Total rainfall: ', total)\nprint('Average rainfall: ', average)\nprint('The most rainfall ocurred in', most_month, 'of', 'year', most_year, 'and was ', most_rainfall, '.')\n\n","sub_path":"labs/rainfall.py","file_name":"rainfall.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"215213714","text":"#############################################################################\n##\n## Copyright (C) 2019 The Qt Company Ltd.\n## Contact: http://www.qt.io/licensing/\n##\n## This file is part of the Qt for Python examples of the Qt Toolkit.\n##\n## $QT_BEGIN_LICENSE:BSD$\n## You may use this file under the terms of the BSD license as follows:\n##\n## \"Redistribution and use in source and binary forms, with or without\n## modification, are permitted provided that the following conditions are\n## met:\n## * 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\n## the documentation and/or other materials provided with the\n## distribution.\n## * Neither the name of The Qt Company Ltd nor the names of its\n## contributors may be used to endorse or promote products derived\n## from this software without specific prior written permission.\n##\n##\n## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n## \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n##\n## $QT_END_LICENSE$\n##\n#############################################################################\n\nfrom PySide2.QtSql import QSqlDatabase, QSqlQuery\nfrom datetime import date\n\ndef add_book(q, title, year, authorId, genreId, rating):\n q.addBindValue(title)\n q.addBindValue(year)\n q.addBindValue(authorId)\n q.addBindValue(genreId)\n q.addBindValue(rating)\n q.exec_()\n\n\ndef add_genre(q, name):\n q.addBindValue(name)\n q.exec_()\n return q.lastInsertId()\n\n\ndef add_author(q, name, birthdate):\n q.addBindValue(name)\n q.addBindValue(str(birthdate))\n q.exec_()\n return q.lastInsertId()\n\nBOOKS_SQL = \"\"\"\n create table books(id integer primary key, title varchar, author integer,\n genre integer, year integer, rating integer)\n \"\"\"\nAUTHORS_SQL = \"\"\"\n create table authors(id integer primary key, name varchar, birthdate text)\n \"\"\"\nGENRES_SQL = \"\"\"\n create table genres(id integer primary key, name varchar)\n \"\"\"\nINSERT_AUTHOR_SQL = \"\"\"\n insert into authors(name, birthdate) values(?, ?)\n \"\"\"\nINSERT_GENRE_SQL = \"\"\"\n insert into genres(name) values(?)\n \"\"\"\nINSERT_BOOK_SQL = \"\"\"\n insert into books(title, year, author, genre, rating)\n values(?, ?, ?, ?, ?)\n \"\"\"\n\ndef init_db():\n \"\"\"\n init_db()\n Initializes the database.\n If tables \"books\" and \"authors\" are already in the database, do nothing.\n Return value: None or raises ValueError\n The error value is the QtSql error instance.\n \"\"\"\n def check(func, *args):\n if not func(*args):\n raise ValueError(func.__self__.lastError())\n db = QSqlDatabase.addDatabase(\"QSQLITE\")\n db.setDatabaseName(\":memory:\")\n\n check(db.open)\n\n q = QSqlQuery()\n check(q.exec_, BOOKS_SQL)\n check(q.exec_, AUTHORS_SQL)\n check(q.exec_, GENRES_SQL)\n check(q.prepare, INSERT_AUTHOR_SQL)\n\n asimovId = add_author(q, \"Isaac Asimov\", date(1920, 2, 1))\n greeneId = add_author(q, \"Graham Greene\", date(1904, 10, 2))\n pratchettId = add_author(q, \"Terry Pratchett\", date(1948, 4, 28))\n\n check(q.prepare,INSERT_GENRE_SQL)\n sfiction = add_genre(q, \"Science Fiction\")\n fiction = add_genre(q, \"Fiction\")\n fantasy = add_genre(q, \"Fantasy\")\n\n check(q.prepare,INSERT_BOOK_SQL)\n add_book(q, \"Foundation\", 1951, asimovId, sfiction, 3)\n add_book(q, \"Foundation and Empire\", 1952, asimovId, sfiction, 4)\n add_book(q, \"Second Foundation\", 1953, asimovId, sfiction, 3)\n add_book(q, \"Foundation's Edge\", 1982, asimovId, sfiction, 3)\n add_book(q, \"Foundation and Earth\", 1986, asimovId, sfiction, 4)\n add_book(q, \"Prelude to Foundation\", 1988, asimovId, sfiction, 3)\n add_book(q, \"Forward the Foundation\", 1993, asimovId, sfiction, 3)\n add_book(q, \"The Power and the Glory\", 1940, greeneId, fiction, 4)\n add_book(q, \"The Third Man\", 1950, greeneId, fiction, 5)\n add_book(q, \"Our Man in Havana\", 1958, greeneId, fiction, 4)\n add_book(q, \"Guards! Guards!\", 1989, pratchettId, fantasy, 3)\n add_book(q, \"Night Watch\", 2002, pratchettId, fantasy, 3)\n add_book(q, \"Going Postal\", 2004, pratchettId, fantasy, 3)\n","sub_path":"venv/Lib/site-packages/PySide2/examples/sql/books/createdb.py","file_name":"createdb.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"262330372","text":"import pandas as pd\n\ndf = pd.read_csv(\"https://www.sololearn.com/uploads/ca-covid.csv\")\n\ndf.drop('state', axis=1, inplace=True)\n\ndf['month'] = pd.to_datetime(df['date'], format=\"%d.%m.%y\").dt.month_name()\n\ndf.set_index('date', inplace=True)\n\nprint(df.head())","sub_path":"3. Pandas/CreatingColumns.py","file_name":"CreatingColumns.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"299112497","text":"import numpy as np\nimport sys\n\nwith open('input') as f:\n ages = [int(v) for v in f.read().split(',')]\n\ndef tick(ages):\n n = len(ages)\n for i in range(n):\n ages[i] -= 1\n if ages[i] < 0:\n ages[i] = 6\n ages.append(8)\n\nfor day in range(80 + 1):\n #print('After %d days (%d fishes): %s' % (day, len(ages), str(ages)))\n print('After %d days (%d fishes)' % (day, len(ages)))\n tick(ages)\n","sub_path":"2021/6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"493756625","text":"# Copyright 2008-2015 Nokia Networks\n# Copyright 2016- Robot Framework Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\n\nfrom robotide.lib.robot.output import LOGGER\nfrom robotide.lib.robot.utils import JYTHON, Utf8Reader, prepr\n\n\nNBSP = u'\\xa0'\n\n\nclass RobotReader(object):\n _space_splitter = re.compile(u'[ \\t\\xa0]{2,}|\\t+')\n _pipe_splitter = re.compile(u'[ \\t\\xa0]+\\|(?=[ \\t\\xa0]+)')\n _pipe_starts = ('|', '| ', '|\\t', u'|\\xa0')\n _pipe_ends = (' |', '\\t|', u'\\xa0|')\n\n def read(self, file, populator, path=None):\n path = path or getattr(file, 'name', '')\n process = False\n for lineno, line in enumerate(Utf8Reader(file).readlines(), start=1):\n cells = self.split_row(line.rstrip())\n cells = list(self._check_deprecations(cells, path, lineno))\n if cells and cells[0].strip().startswith('*') and \\\n populator.start_table([c.replace('*', '').strip()\n for c in cells]):\n process = True\n elif process:\n populator.add(cells)\n return populator.eof()\n\n @classmethod\n def split_row(cls, row):\n if row[:2] in cls._pipe_starts:\n row = row[1:-1] if row[-2:] in cls._pipe_ends else row[1:]\n return [cls._strip_whitespace(cell)\n for cell in cls._pipe_splitter.split(row)]\n return cls._space_splitter.split(row)\n\n def _check_deprecations(self, cells, path, line_number):\n for original in cells:\n normalized = self._normalize_whitespace(original)\n if normalized != original:\n if len(normalized) != len(original):\n msg = 'Collapsing consecutive whitespace'\n else:\n msg = 'Converting whitespace characters to ASCII spaces'\n LOGGER.warn(\"%s during parsing is deprecated. Fix %s in file \"\n \"'%s' on line %d.\"\n % (msg, prepr(original), path, line_number))\n yield normalized\n\n # Jython has issues with non-ASCII spaces https://bugs.jython.org/issue2772\n if JYTHON:\n\n _whitespace = re.compile(u'\\\\s+', re.UNICODE)\n _trailing_whitespace = re.compile(u'\\\\s+$', re.UNICODE)\n\n @classmethod\n def _strip_whitespace(cls, string):\n match = cls._whitespace.match(string)\n if match:\n string = string[match.end():]\n match = cls._trailing_whitespace.search(string)\n if match:\n string = string[:match.start()]\n return string\n\n def _normalize_whitespace(self, string):\n return ' '.join(self._whitespace.split(string))\n\n else:\n\n @classmethod\n def _strip_whitespace(cls, string):\n return string.strip()\n\n def _normalize_whitespace(self, string):\n return ' '.join(string.split())\n","sub_path":"src/robotide/lib/robot/parsing/robotreader.py","file_name":"robotreader.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"285199735","text":"# Leetcode 153. Find Minimum in Rotated Sorted Array\n\n# Time Complexity : O(m+n) where m,n are the length of the two lists\n\n# Space Complexity : O(1) \n\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n\n# Approach: Calculate length of the two lists using to pointers, Move the pointer of the larger list by\n# the difference of both lists so that they reach the intersection at same time while moving at 1x speed.\n# Once the pointers point to same node, then intersection is found and return any pointer.\n\n# Your code here along with comments explaining your approach\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n lenA = 0\n lenB = 0\n # Pointer to calculate the len of list A\n curr = headA\n while curr:\n curr = curr.next\n lenA += 1\n # reset Pointer to calculate the len of list B \n curr = headB\n while curr:\n curr = curr.next\n lenB += 1\n # Using len adjust the head of larger list to match the len of smaller list \n while lenA > lenB:\n headA = headA.next\n lenA -= 1\n while lenA < lenB:\n headB = headB.next\n lenB -= 1\n # Move heads of both lists until they match and give point of intersection and return any head\n while headA != headB:\n headA = headA.next\n headB = headB.next\n return headA","sub_path":"linked_List_Intersection.py","file_name":"linked_List_Intersection.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"442659050","text":"#! /usr/bin/env python\n# coding:utf8\n\nfrom django.http import Http404\nfrom django.core.exceptions import PermissionDenied\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView, set_rollback\nfrom rest_framework.exceptions import APIException, NotAuthenticated, AuthenticationFailed, Throttled\n\nfrom .resp_code import SUCCESS\nfrom .exception import UnAuthorizationExc\n\n\nclass TriDrfApiView(APIView):\n\tdef initial(self, request, *args, **kwargs):\n\t\tif request.path.startswith(\"/api\"):\n\t\t\trequest._SET_COOKIE = False\n\t\t\trequest._DEL_COOKIE = False\n\t\t\t\"\"\"\n\t\t\tMake decrypt for each request view here.\n\t\t\t\"\"\"\n\t\treturn super(TriDrfApiView, self).initial(request, *args, **kwargs)\n\n\tdef finalize_response(self, request, response, *args, **kwargs):\n\t\tif not response:\n\t\t\tresponse = \"\"\n\n\t\tif isinstance(response, (dict, list, str)):\n\t\t\tresponse = Response({\n\t\t\t\t\"code\": SUCCESS, \"message\": \"\", \"data\": response\n\t\t\t})\n\n\t\tif request._SET_COOKIE:\n\t\t\tresponse.set_cookie(\"AUTHORIZATION\", \"Token {}\".format(request._SET_COOKIE), max_age=86400 * 7)\n\t\telif request._DEL_COOKIE:\n\t\t\tresponse.delete_cookie(\"AUTHORIZATION\")\n\t\treturn super(TriDrfApiView, self).finalize_response(request, response, *args, **kwargs)\n\n\tdef handle_exception(self, exc):\n\t\tset_rollback()\n\n\t\tresponse = None\n\t\tif isinstance(exc, UnAuthorizationExc):\n\t\t\tresponse = Response({\n\t\t\t\t\"code\": exc.code, \"message\": exc.message,\n\t\t\t})\n\t\t\tresponse.delete_cookie(\"AUTHORIZATION\")\n\t\telif isinstance(exc, NotAuthenticated):\n\t\t\tresponse = Response({\"code\": exc.default_code, \"message\": exc.detail}, exception=True)\n\t\telif isinstance(exc, AuthenticationFailed):\n\t\t\tresponse = Response({\"code\": exc.default_code, \"message\": exc.detail}, exception=True)\n\t\telif isinstance(exc, Throttled):\n\t\t\tresponse = Response({\"code\": exc.default_code, \"message\": exc.detail}, exception=True)\n\t\telif isinstance(exc, APIException):\n\t\t\tresponse = Response({\"code\": exc.default_code, \"message\": exc.detail}, exception=True)\n\t\telif isinstance(exc, Http404):\n\t\t\tresponse = Response({\"code\": 404, \"message\": \"404 Not Found\"}, status=404, exception=True)\n\t\telif isinstance(exc, PermissionDenied):\n\t\t\tresponse = Response({\"code\": 403, \"message\": \"403 Forbidden\"}, status=403, exception=True)\n\n\t\tif not response:\n\t\t\tself.raise_uncaught_exception(exc)\n\t\telse:\n\t\t\texc.__traceback__ = None\n\t\t\treturn response\n","sub_path":"utils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"524069912","text":"from sys import argv\n\nfrom Emergency import Emergency\n\nclass Simulation:\n\n def __init__(self, args):\n self.run(args)\n\n def run(self,config):\n runs = int(config[1]) if len(config) > 1 else 50\n for _ in range(runs):\n Emergency('docs/config.txt')\n\nif __name__ == '__main__':\n Simulation(argv)\n","sub_path":"Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"333166333","text":"import sys\r\n\r\nprices_file = open (\"sys.argv[1]\", \"r\")\r\nshopping_list_file = open (\"sys.argv[2]\", \"r\")\r\noutput = open (\"sys.argv[3]\", \"w\")\r\nprices={}\r\n\r\nfor line in prices_file.readlines():\r\n line = line.rstrip(\"\\n\")\r\n entry = line.split(\":\")\r\n prices [entry[0]] = entry[1][2]\r\n\r\nshopping_list ={}\r\n\r\n\r\ntry:\r\n for line in shopping_list_file.readlines():\r\n line = line.rstrip(\"\\n\")\r\n entry = line.split(\"\\n\")\r\n\r\nexcept:\r\n check_line = entry[1].replace(\" \", \"\")\r\n if not check_line.isalpha():\r\n shopping_list[entry[0]] = entry[1]\r\n\r\n\r\ntotal_amount_to_pay = 0\r\nmissing_items =[]\r\n\r\nfor item in prices.item():\r\n print(\"You want to buy {} kg of {}\" .format(prices[0], prices[1]))\r\n if item in prices:\r\n total_amount_to_pay += float(prices[1])*float(prices[2])\r\n else:\r\n missing_items.append(item)\r\n\r\nif len(missing_items)>0:\r\n print(\"fruit that were not avaible\")\r\n for item in missing_items:\r\n print(item)\r\n\r\n print(\"The total cost for your fruit is\", total_amount_to_pay, \"TL\")\r\n\r\nprices_file.close()\r\nshopping_list_file.close()","sub_path":"quiz4.py","file_name":"quiz4.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"272156095","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## DEEPER MULTILAYER PERCEPTRON WITH DROPOUT\n\n# In[1]:\n\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# # LOAD MNIST\n\n# In[2]:\n\n\nmnist = input_data.read_data_sets('data/', one_hot=True)\n\n\n# # DEFINE MODEL\n\n# In[3]:\n\n\n# NETWORK TOPOLOGIES\nn_input = 784 # MNIST data input (img shape: 28*28)\nn_hidden_1 = 512 # 1st layer num features\nn_hidden_2 = 512 # 2nd layer num features\nn_hidden_3 = 256 # 3rd layer num features\nn_classes = 10 # MNIST total classes (0-9 digits)\n# INPUT AND OUTPUT\nx = tf.placeholder(\"float\", [None, n_input])\ny = tf.placeholder(\"float\", [None, n_classes])\ndropout_keep_prob = tf.placeholder(\"float\")\n# VARIABLES\nstddev = 0.05\nweights = {\n 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),\n 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),\n 'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3], stddev=stddev)),\n 'out': tf.Variable(tf.random_normal([n_hidden_3, n_classes], stddev=stddev))\n}\nbiases = {\n 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n 'b3': tf.Variable(tf.random_normal([n_hidden_3])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}\nprint (\"NETWORK READY\")\n\n\n# In[4]:\n\n\ndef multilayer_perceptron(_X, _weights, _biases, _keep_prob):\n x_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))\n layer_1 = x_1\n x_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))\n layer_2 = x_2\n x_3 = tf.nn.relu(tf.add(tf.matmul(layer_2, _weights['h3']), _biases['b3']))\n layer_3 = tf.nn.dropout(x_3, _keep_prob) \n return (tf.matmul(layer_3, _weights['out']) + _biases['out'])\n\n\n# # DEFINE FUNCTIONS\n\n# In[5]:\n\n\n# PREDICTION\npred = multilayer_perceptron(x, weights, biases, dropout_keep_prob)\n\n# LOSS AND OPTIMIZER\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) \noptm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) \ncorr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) \naccr = tf.reduce_mean(tf.cast(corr, \"float\"))\n\n# INITIALIZER\ninit = tf.initialize_all_variables()\nprint (\"FUNCTIONS READY\")\n\n\n# # RUN\n\n# In[6]:\n\n\n# PARAMETERS\ntraining_epochs = 20\nbatch_size = 100\ndisplay_step = 4\n# LAUNCH THE GRAPH\nsess = tf.Session()\nsess.run(init)\n# OPTIMIZE\nfor epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(mnist.train.num_examples/batch_size)\n # ITERATION\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n feeds = {x: batch_xs, y: batch_ys, dropout_keep_prob: 0.6}\n sess.run(optm, feed_dict=feeds)\n feeds = {x: batch_xs, y: batch_ys, dropout_keep_prob: 1.0}\n avg_cost += sess.run(cost, feed_dict=feeds)\n avg_cost = avg_cost / total_batch\n # DISPLAY\n if (epoch+1) % display_step == 0:\n print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))\n feeds = {x: batch_xs, y: batch_ys, dropout_keep_prob: 1.0}\n train_acc = sess.run(accr, feed_dict=feeds)\n print (\"TRAIN ACCURACY: %.3f\" % (train_acc))\n feeds = {x: mnist.test.images, y: mnist.test.labels, dropout_keep_prob: 1.0}\n test_acc = sess.run(accr, feed_dict=feeds)\n print (\"TEST ACCURACY: %.3f\" % (test_acc))\nprint (\"OPTIMIZATION FINISHED\")\n\n","sub_path":"etc/tf_tutorial/Tensorflow-101-master/mlp_mnist_deeper.py","file_name":"mlp_mnist_deeper.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"441606083","text":"# Importing functions which allows data to be extracted\nfrom lxml import html\nimport requests\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport os\n\ndef graph(weather, location):\n temprange = plt.axes()\n # Alpha gives the colour density\n # Decimals control spacing between bars\n temprange.bar([1.5, 2.5, 3.5, 4.5, 5.5], weather['Min'], width=0.5, alpha=0.4)\n # if statement to control the issue of any missing data\n if len(weather['Max']) == 4:\n temprange.bar([1, 2, 3, 4], weather['Max'], width=0.5, alpha=0.4)\n elif len(weather['Max']) == 5:\n temprange.bar([1, 2, 3, 4, 5], weather['Max'], width=0.5, alpha=0.4)\n # x axis (days)\n temprange.set_xticklabels(weather['Day'])\n # y axis, auto sets from min value to max value temp\n weather=np.ma.masked_array(weather, mask=(weather==-999), fill_value=0)\n # prints the graph\n plt.show()\n\ndef weather_report(URL):\n # Pulls the desired website\n page = requests.get(URL)\n # Extracting HTML\n data = html.fromstring(page.content)\n # Extacting data from BBC weather for days, min & max temp\n day = data.xpath('//*[@id=\"blq-content\"]/div[7]/div[2]/ul/li/a/div/h3/span/text()')\n max_temp = data.xpath('//*[@id=\"blq-content\"]/div[7]/div[2]/ul/li/a/span[2]/span/span[1]/text()')\n min_temp = data.xpath('//*[@id=\"blq-content\"]/div[7]/div[2]/ul/li/a/span[3]/span/span[1]/text()')\n location = data.xpath('//*[@id=\"blq-content\"]/div[1]/h1/span/text()')\n print (location[0] + \" five day forecast\")\n# When max temp for nightime is missing...\n if len(max_temp) == 4:\n weather=-999*np.ones((5,3), dtype='object') # Deals with the missing data issue, sets any missing temp as -999\n weather[:,0] = day\n # Note that this is different from the elif statement below: [1:,1] instead of [:,1]. Handling the missing data issue\n weather[1:,1] = [int(i) for i in max_temp]\n weather[:,2] = [int(i) for i in min_temp]\n # If the length of max list is 5 (i.e. it's daytime) do this:\n elif len(max_temp) == 5:\n weather=np.zeros((5,3), dtype='object')\n weather[:,0] = day\n weather[:,1] = [int(i) for i in max_temp]\n weather[:,2] = [int(i) for i in min_temp]\n # Masks any -999 in weather, fill value means to blank them out\n weather=np.ma.masked_array(weather, mask=(weather==-999), fill_value=0)\n weather = pd.DataFrame(weather, columns=['Day', 'Max', 'Min']) # Labels the columns\n\n #root = \"/home/grace/Desktop/Web Scraper Project/\"\n #weather = pd.DataFrame(weather, columns=['Day', 'Max', 'Min']) # Labels the columns\n #filename = city[0] + \".csv\"\n #with open(root + filename, \"a\") as f:\n # weather.to_csv(f, header=False) # Appending so that we can collect data over time\n #weather.to_csv(city[0] + \".csv\") Magic one line code for making a csv file\n #make_graph(weather, city)\n\n root = \"/home/sylke/Desktop/webscraper/\"\n filename = location[0] + \".csv\"\n with open(root + filename, \"a\") as d:\n weather.to_csv(d, header=False)\n # weather.to_csv = location[0] + \".csv\")\n print (weather)\n # graph(weather, location)\n\nLas_vegas_temp = 'http://www.bbc.co.uk/weather/5506956'\nPurley_temp = 'http://www.bbc.co.uk/weather/2639842'\nAmsterdam_temp = 'http://www.bbc.co.uk/weather/2759794'\n\nweather_report(Las_vegas_temp)\nweather_report(Purley_temp)\nweather_report(Amsterdam_temp)\n","sub_path":"webscraper/webscrape.py","file_name":"webscrape.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"125936820","text":"\"\"\"\n在经过像素级裁剪的图像中进一步裁剪出包含笔石区域的最小矩形框,尽量保证笔石的长宽比不变,并且在四周随机留白\n\"\"\"\nimport random\nimport cv2 as cv\nimport numpy as np\nfrom pathlib import Path\nimport time\nfrom concurrent.futures import ProcessPoolExecutor\n\ncategory_list1 = [ # set100-10\n '1Dicellograptus bispiralis', # re1\n '1Dicellograptus caduceus', # re1\n '1Dicellograptus divaricatus salopiensis',\n '1Dicellograptus smithi', # re1, re2\n '1Dicellograptus undatus',\n '1Dicranograptus irregularis', # re1\n '1Dicranograptus sinensis', # re1\n '1Didymograptus jiangxiensis', # re1\n '1Didymograptus latus tholiformis', # re1\n '1Didymograptus miserabilis'\n]\ncategory_list2 = [ # set100-20\n '2Amplexograptus acusiformis', # re1\n '2Amplexograptus fusiformis',\n '2Cryptograptus arcticus sinensis', # re1\n '2Cryptograptus gracilicornis', # re1\n '2Dicellograptus divaricatus',\n '2Dicranograptus nicholsoni parvangulus',\n '2Dicranograptus ramosus',\n '2Didymograptus euodus',\n '2Didymograptus linearis longus',\n '2Didymograptus saerganensis'\n]\ncategory_list3 = [ # set100-30\n '3Climacograptus pauperatus', # re1, re2\n '3Cryptograptus arcticus', # re1\n '3Cryptograptus marcidus',\n '3Cryptograptus tricornis', # re1, re2\n '3Glossograptus briaros',\n '3Glossograptus robustus',\n '3Glyptograptus plurithecatus wuningensis', # re1\n '3Glyptograptus teretiusculus siccatus', # re1\n '3Pseudoclimacograptus parvus jiangxiensis', # re1\n '3Pseudoclimacograptus wannanensis' # re1, re2, re3\n]\ncategory_list4 = [ # set100-40\n '4Diplograptus proelongatus', # re1\n '4Glyptograptus teretiusculus', # re1\n '4Jiangxigraptus inculus',\n '4Jishougraptus mui',\n '4Leptograptus flaccidus trentonensis',\n '4Monoclimacis neimengolensis',\n '4Pseudoclimacograptus angulatus',\n '4Pseudoclimacograptus longus',\n '4Pseudoclimacograptus modestus',\n '4Pseudoclimacograptus parvus'\n]\ncategory_list5 = [ # set100-50\n '5Amplexograptus disjunctus yangtzensis',\n '5Amplexograptus suni', # re1\n '5Climacograptus miserabilis', # re1\n '5Climacograptus supernus', # re1\n '5Dicellograptus ornatus', # re1, re2\n '5Diplograptus modestus',\n '5Glyptograptus incertus',\n '5Petalolithus elongatus',\n '5Petalolithus folium',\n '5Streptograptus runcinatus'\n]\ncategory_list6 = [ # set100-60\n '6Dicellograptus szechuanensis',\n '6Diplograptus bohemicus',\n '6Glyptograptus austrodentatus', # re1, re2\n '6Glyptograptus gracilis', # re1\n '6Glyptograptus lungmaensis',\n '6Glyptograptus tamariscus', # re1\n '6Glyptograptus tamariscus linealis',\n '6Glyptograptus tamariscus magnus',\n '6Reteograptus uniformis',\n '6Retiolites geinitzianus'\n]\ncategory_list7 = [ # set100-70\n '7Amplexograptus orientalis',\n '7Climacograptus angustatus', # re1\n '7Climacograptus leptothecalis', # re1\n '7Climacograptus minutus', # re1\n '7Climacograptus normalis',\n '7Climacograptus tianbaensis',\n '7Colonograptus praedeubeli',\n '7Diplograptus angustidens',\n '7Diplograptus diminutus',\n '7Rectograptus pauperatus'\n]\ncategory_list8 = [ # set100-80\n '8Amplexograptus confertus',\n '8Climacograptus angustus', # re1\n '8Climacograptus textilis yichangensis', # re1\n '8Colonograptus deubeli',\n '8Dicellograptus cf. complanatus',\n '8Diplograptus concinnus',\n '8Pristiograptus variabilis',\n '8Pseudoclimacograptus demittolabiosus',\n '8Pseudoclimacograptus formosus',\n '8Rectograptus abbreviatus'\n]\ncategory_list9 = [ # set100-90\n '9Akidograptus ascensus',\n '9Amplexograptus cf. maxwelli',\n '9Cardiograptus amplus',\n '9Climacograptus bellulus',\n '9Climacograptus hastatus',\n '9Glyptograptus dentatus',\n '9Glyptograptus elegans',\n '9Glyptograptus elegantulus',\n '9Orthograptus calcaratus',\n '9Trigonograptus ensiformis'\n]\ncategory_list10 = [ # set100-96\n '10Demirastrites triangulatus',\n '10Dicellograptus tumidus',\n '10Dicellograptus turgidus',\n '10Paraorthograptus pacificus', # re1\n '10Paraorthograptus simplex',\n '10Spirograptus turriculatus'\n]\ncategory_list11 = [ # set100\n '11Appendispinograptus venustus', # re1\n '11Nicholsonograptus fasciculatus',\n '11Nicholsonograptus praelongus',\n '11Paraorthograptus longispinus'\n]\ncategory_list12 = [ # set105\n '12Cryptograptus tricornis (Juvenile)',\n '12Phyllograptus anna',\n '12Rastrites guizhouensis', # re1, re2\n '12Tangyagraptus typicus', # re1\n '12Yinograptus grandis'\n]\ncategory_list13 = [ # set110\n '13Coronograptus cyphus', # re1\n '13Cystograptus vesiculosus', # re1\n '13Normalograptus extraordinarius', # re1, re2\n '13Normalograptus persculptus', # re1, re2\n '13Parakidograptus acuminatus'\n]\ncategory_list14 = [ # set114\n '14Diceratograptus mirus',\n '14Lituigraptus convolutus',\n '14Paraplegmatograptus connectus', # re1\n '14Pararetiograptus regularis',\n]\ncategory_list = category_list1 + category_list2 + category_list3 + category_list4 + category_list5 + category_list6 + \\\n category_list7 + category_list8 + category_list9 + category_list10 + category_list11 + category_list12 +\\\n category_list13 + category_list14\ncategory_paths = [Path(r'D:\\set113_ori\\annotated_images_550') / category for category in category_list]\n\n\n# 在纯色背景图像中裁剪出包含前景信息的最小矩形框,保持长宽比并在四周留白\ndef find_smallest_rectangle(dir_path):\n output_size = 448\n for path in dir_path.iterdir():\n if path.suffix == '.jpg':\n img_path = str(path)\n img_name = path.name\n img = cv.imdecode(np.fromfile(img_path), -1)\n img_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)\n h, w = img_gray.shape\n if h == w == output_size:\n continue\n # bk_color = img_gray[0, 0]\n bk_color = 255 # 白色\n\n # 以背景色为阈��,遍历出图像中笔石区域的边界\n step = 5\n leftmost = w\n for i in range(0, h, step):\n for j in range(0, w, step):\n if img_gray[i, j] != bk_color:\n if j < leftmost:\n leftmost = j\n break\n rightmost = 0\n for i in range(0, h, step):\n for j in range(w - 1, -1, -step):\n if img_gray[i, j] != bk_color:\n if j > rightmost:\n rightmost = j\n break\n highest = h\n for i in range(0, w, step):\n for j in range(0, h, step):\n if img_gray[j, i] != bk_color:\n if j < highest:\n highest = j\n break\n lowest = 0\n for i in range(0, w, step):\n for j in range(h - 1, -1, -step):\n if img_gray[j, i] != bk_color:\n if j > lowest:\n lowest = j\n break\n # 笔石区域的高和宽\n new_width = abs(rightmost - leftmost)\n new_high = abs(lowest - highest)\n margin = int(abs(new_width - new_high))\n\n # 笔石区域的高>宽\n if new_high > new_width:\n mid = abs(rightmost - new_width / 2)\n # 左右边距均足,则将margin平分\n if mid - (new_width / 2 + margin / 2) >= 0 and mid + (new_width / 2 + margin / 2) / 2 <= w:\n new_img = img[highest:lowest,\n int(mid - (new_width / 2 + margin / 2)):int(mid + (new_width / 2 + margin / 2))]\n # 左边距不足,则从最左端开始切片,并尽量将剩余margin全部分配给右半部分(若右也不足则取最右)\n elif mid - (new_width / 2 + margin / 2) < 0 and mid + (new_width / 2 + margin / 2) / 2 <= w:\n left_margin = int(mid - new_width / 2)\n right_margin = margin - left_margin\n new_img = img[\n highest:lowest,\n 0:int(mid + (new_width / 2 + right_margin)) if int(\n mid + (new_width / 2 + right_margin)) <= w else w\n ]\n # 右边距不足,则切片至图像最右端,并尽量将剩余margin全部分配给左半部分(若左也不足则取最左端)\n elif mid - (new_width / 2 + margin / 2) >= 0 and mid + (new_width / 2 + margin / 2) / 2 > w:\n right_margin = int(w - rightmost)\n left_margin = margin - right_margin\n new_img = img[\n highest:lowest,\n int(mid - (new_width / 2 + left_margin)) if int(\n mid - (new_width / 2 + left_margin)) >= 0 else 0:w\n ]\n # 左右边距均不足,则横向切片取全部\n else:\n new_img = img[highest:lowest, :]\n\n # 笔石区域的高<宽\n elif new_high < new_width:\n mid = abs(lowest - new_high / 2)\n # 上下边距均足, 则将margin平分\n if mid - (new_high / 2 + margin / 2) >= 0 and mid + (new_high / 2 + margin / 2) <= h:\n new_img = img[int(mid - (new_high / 2 + margin / 2)):int(mid + (new_high / 2 + margin / 2)),\n leftmost:rightmost]\n # 上边距不足,则从最上端开始切片,并尽量将剩余margin全部分配给下半部分(若下也不足则取最下端)\n elif mid - (new_high / 2 + margin / 2) < 0 and mid + (new_high / 2 + margin / 2) <= h:\n up_margin = int(mid - new_high / 2)\n bottom_margin = margin - up_margin\n new_img = img[\n 0:int(mid + (new_high / 2 + bottom_margin)) if int(\n mid + (new_high / 2 + bottom_margin)) <= h else h,\n leftmost:rightmost\n ]\n # 下边距不足,则切片至图像最下端,并尽量将剩余margin全部分配给上半部分(若上也不足则取最上端)\n elif mid - (new_high / 2 + margin / 2) >= 0 and mid + (new_high / 2 + margin / 2) > h:\n bottom_margin = int(h - lowest)\n up_margin = margin - bottom_margin\n new_img = img[\n int(mid - (new_high / 2 + up_margin)) if int(\n mid - (new_high / 2 + up_margin)) >= 0 else 0:h,\n leftmost:rightmost\n ]\n # 上下边距���不足,则纵向切片取全部\n else:\n new_img = img[:, leftmost:rightmost]\n # 笔石区域的高宽刚好相等\n else:\n new_img = img[highest:lowest, leftmost:rightmost]\n\n # 为图像四周留白,大小为笔石区域的边长×0.2\n white_margin = 30\n half_white_margin = int(white_margin / 2)\n new_img = np.pad(new_img, ((half_white_margin, half_white_margin),\n (half_white_margin, half_white_margin),\n (0, 0)), 'constant', constant_values=255)\n\n # 随机缩放至size_list中的任一尺寸\n size_list = [300, 330, 370, 400]\n random_index = random.randint(0, len(size_list) - 1)\n random_size = size_list[random_index]\n new_img = cv.resize(new_img, (random_size, random_size))\n\n # 横纵随机填充至output_size\n padding = output_size - random_size\n w_padding = random.randint(5, padding-5)\n half_w_padding = padding - w_padding\n h_padding = random.randint(5, padding-5)\n half_h_padding = padding - h_padding\n new_img = np.pad(new_img, ((w_padding, half_w_padding),\n (h_padding, half_h_padding),\n (0, 0)), 'constant', constant_values=255)\n\n # new_img_mask = np.zeros((output_size, output_size, 3))\n # new_img = new_img + new_img_mask\n\n new_img = cv.resize(new_img, (output_size, output_size))\n is_success, im_buf_arr = cv.imencode('.jpg', new_img)\n im_buf_arr.tofile(img_path)\n print(\"reshape: \", img_path, new_img.shape)\n assert (new_img.shape[0] == new_img.shape[1] == output_size)\n else:\n continue\n print(\"类别 %s 裁剪完毕\" % str(dir_path).split(\"\\\\\")[-1])\n\n\nif __name__ == '__main__':\n t1 = time.time()\n with ProcessPoolExecutor(2) as executor:\n results = executor.map(find_smallest_rectangle, category_paths)\n print(time.time() - t1)\n","sub_path":"processing/4_crop_by_square.py","file_name":"4_crop_by_square.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"62204691","text":"#/usr/bin/python\n#\n\nfrom ebase import MyPeak\nimport os\n\ndef get_peaks(filename):\n\n # get lines from output file about processed peaks\n f = open(filename)\n lines = f.readlines()\n f.close()\n\n all_peaks = {}\n peaks = []\n \n last_file=\"\"\n\n selected_lines = [ line for line in lines if '\"G,' in line or '\"B,' in line ]\n for line in selected_lines:\n\n items = line.split(',')\n if items[2] != last_file and last_file != \"\":\n all_peaks[last_file] = peaks\n peaks=[]\n last_file = items[2]\n elif last_file==\"\":\n peakd=[]\n last_file = items[2]\n \n size_bp = float(items[3]) if items[3].strip()!=\"\" else -1\n height = int(items[4])\n area_s = items[5]\n area_bp = items[6]\n size_s = int(items[7])\n dye = items[0][1]\n\n peak = MyPeak(dye, size_s, size_bp, height)\n peaks.append(peak)\n\n if last_file != \"\" and len(peaks)>0:\n all_peaks[last_file] = peaks\n \n return all_peaks\n\n\nfileroot = \"trace-Jul-25-2013-Jul26-13-32-28_full\"\npeaks_table_file_name = \"GL8-044.csv\"\n\npeaks_peakscanner = get_peaks(fileroot+\"/GL8-044.csv\")\n\npeaks_fatools = get_peaks(fileroot+\"/\"+fileroot+\".out\")\n\ndef good_ladder(peak):\n return (peak.dye=='G' and peak.height>=100.)\n\ndef good_nonladder(peak):\n return (peak.dye=='B' and peak.height>=100.)\n\n#for file in peaks_peakscanner.keys():\nf = open(\"peak_performance_summary.out\", \"w\")\nf.write(' \\t | \\tsize_s\\t \\t | \\tsize_bp\\t \\t |\\trfu \\t |\\n')\nf.write(' FILE \\tPEAK | \\tPS \\tFA \\t |DIFF| | \\tPS \\t FA\\t |DIFF| |\\tPS \\tFA |\\n')\nfor file in peaks_fatools.keys():\n\n print(\"\\nfile: \", file)\n peaks_ps = [peak for peak in peaks_peakscanner[file] if good_nonladder(peak) ]\n peaks_fa = [peak for peak in peaks_fatools[file] if good_nonladder(peak)]\n\n # match pairs of peaks\n matched_pairs = []\n extra_peaks_ps = []\n for peak_ps in peaks_ps:\n \n best_size_diff = 999\n best_j = -1\n for j in range(len(peaks_fa)):\n peak_fa = peaks_fa[j]\n\n size_diff = abs(peak_ps.size_s - peak_fa.size_s) \n if size_diff < best_size_diff:\n best_j = j\n best_size_diff = size_diff\n\n if best_size_diff < 5:\n matched_pairs.append((peak_ps, peaks_fa[best_j]))\n del peaks_fa[best_j]\n else:\n extra_peaks_ps.append(peak_ps)\n\n npeaks = 0\n for (ps,fa) in matched_pairs:\n npeaks += 1\n f.write(\"%20s\\t%2i |\\t%4i\\t%4i\\t%2i |\\t%4i\\t%4i\\t%4i |\\t%5i\\t%5i |\\n\" %\n (file if npeaks==1 else \"\",npeaks,\n ps.size_s, fa.size_s, abs(ps.size_s - fa.size_s),\n ps.size_bp, fa.size_bp, abs(ps.size_bp - fa.size_bp),\n ps.height, fa.height))\n \n for ps in extra_peaks_ps:\n npeaks += 1\n f.write(\"%20s\\t%2i |\\t%4i\\t -- \\t-- |\\t%4i\\t -- \\t -- |\\t%5i\\t -- |\\n\" %\n (file if npeaks==1 else \"\",npeaks,ps.size_s,ps.size_bp,ps.height))\n\n for fa in peaks_fa:\n npeaks += 1\n f.write(\"%20s\\t%2i |\\t -- \\t%4i\\t-- |\\t --\\t%4i\\t -- |\\t -- \\t%5i |\\n\" %\n (file if npeaks==1 else \"\",npeaks,fa.size_s,fa.size_bp,fa.height))\n \n f.write(\"\\n\")\n \nf.close()\n","sub_path":"fatools/scripts/ebase_analyzeOutput.py","file_name":"ebase_analyzeOutput.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"260999452","text":"from http.cookies import SimpleCookie\n\nfrom scrapy.exceptions import DropItem\nfrom scrapy import Request\nfrom scrapy.spiders import CrawlSpider\nfrom scrapy.utils.request import request_fingerprint\n\nfrom mpn_scraper.spiders.spider_helpers import get_spider_data, filter_links\n\n\nclass MpnSpider(CrawlSpider):\n name = \"mpn_spider\"\n cookies = SimpleCookie(\"\")\n source = \"\"\n allowed_domains = []\n\n # https://stackoverflow.com/a/15618520/5441099\n def __init__(self, **kwargs):\n spider_data = get_spider_data(self.__class__, **kwargs,)\n for k, v in spider_data.items():\n self.__setattr__(k, v)\n if not self.start_urls:\n raise ValueError(\"Missing start_urls in spider or constructor arguments.\")\n if not self.allowed_domains:\n raise ValueError(\"Missing allowed_domains in spider.\")\n if not self.source:\n raise ValueError(\"Missing source in spider.\")\n\n super().__init__(**{k: v for k, v in kwargs.items() if not hasattr(self, k)})\n\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url, dont_filter=True, cookies=self.cookies)\n\n def filter_links(self, links):\n return filter_links(links)\n\n def add_cookies(self, request, response):\n for k, v in self.cookies.items():\n request.cookies[k] = v.value\n return request\n\n def finish_item(self, response, loader=None, item=None):\n extra_values = {\n \"provenance\": self.source,\n \"url\": response.url,\n \"url_fingerprint\": request_fingerprint(response.request),\n }\n if loader:\n for k, v in extra_values.items():\n loader.add_value(k, v)\n loader.add_css(\n \"canonical_url\",\n \"link[rel=canonical]::attr(href), meta[property='og:url']::attr(content)\",\n )\n return loader.load_item()\n elif item:\n for k, v in extra_values.items():\n if not item.get(k):\n item[k] = v\n if not item.get(\"canonical_url\"):\n canonical_url = response.css(\n \"link[rel=canonical]::attr(href), meta[property='og:url']::attr(content)\"\n ).extract_first()\n item[\"canonical_url\"] = canonical_url\n return item\n else:\n raise DropItem(\"Finish item has neither loader not item\")\n","sub_path":"mpn_scraper/spiders/mpn_spider.py","file_name":"mpn_spider.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"606219976","text":"import serial\n\n# Set the port and baudrate to the ones you're using, Rafael/João Лорем.\n# Likely COM[something] in your case.\nser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600)\n\n# In this next few lines, the files are created.\n# Do not forget to create the files you think you'll need.\ndata = open('/files/data.csv', 'w')\ntemp = open('/files/temp.txt', 'w')\npress = open('/files/press.txt', 'w')\n\n# You should go read about slicing notation. Ok?\ndef parser(string, start=None, end = None):\n \"\"\"\n Returns the parts of the string you want.\n \"\"\"\n try:\n return string[start - 1:end + 0]\n except:\n try:\n return string[start - 1:end]\n except:\n return string[start:end]\n\n# Again, please do add the necessary files below. They don't create themselves.\n# Or, they could. I could make them create themselves. But, it would be unecessary labour.\n# Nobody likes unecessary labour, am I correct, João? I'm not.\nwhile True:\n \"\"\"\n This writes things to the files. Having non-empty files is fun.\n \"\"\"\n\n ## Change values to sooth your needs.\n dataString = str(ser.readline())[:-5][2:]\n\n# Start by declaring the strings you want to use.\n# Later on, you should use the paser() function defined above.\n temperature = parser(dataString, end=4) # Change the arguments according to your needs.\n pressure = parser(dataString, 4) # Change the arguments according to your needs.\n\n print(dataString)\n\n# Everything should be written to this file,\n# i.e, you should add a data.write([the things you want to write] + \",\")\n# for every data point.\n# Please illucidate yourself on how csv files work. It isn't hard.\n data = open('/files/data.csv', 'a')\n data.write(temperature + \",\")\n data.write(pressure + \"\\n\")\n\n# This should remain as is.\n# Unless, of course, you'd like to include the time the data was read.\n# I don't think that'd be a bad idea.\n# But, since you're the ones with the hardware, that's your job to do.\n# You're smart. You can figure it out.\n temp = open('/files/temp.txt', 'a')\n temp.write(temperature + \"\\n\")\n temp.close()\n\n press = open('/files/press.txt', 'a')\n press.write(pressure + \"\\n\")\n press.close()\n\n# Please do create more files, as we're going to need more information than this.\n","sub_path":"Data Processing/Ground Station/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"611618714","text":"##############################################################################\n#\n# Copyright (c) 2008 Vanguardistas LLC.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\nimport os\nimport unittest\nfrom doctest import DocFileSuite\n\nfrom van.testing.layer import zcml_layer\n\nclass ZCMLLayer:\n zcml = os.path.join(os.path.dirname(__file__), 'ftesting.zcml')\nzcml_layer(ZCMLLayer)\n\nhave_zpt = True\ntry:\n import zope.app.pagetemplate\nexcept ImportError:\n have_zpt = False\n\ndef test_suite():\n suite = unittest.TestSuite()\n test = DocFileSuite('README.txt')\n test.layer = ZCMLLayer\n suite.addTest(test)\n if have_zpt:\n zpt_test = DocFileSuite('zpt.txt')\n zpt_test.layer = ZCMLLayer\n suite.addTest(zpt_test)\n return suite\n\n\n","sub_path":"van.timeformat/tags/1.0.0/van/timeformat/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"248885124","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.3'\n# jupytext_version: 0.8.6\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\nimport tidy_data\nimport numpy as np\nimport bebi103\nimport scipy\n\n# +\ndef conf_int_means(df):\n \"\"\"\n get 95% confidence intervals for labeled and unlabeled \n mean catastrophe times\n \n Inputs:\n df : dataframe of gardner_time_to_catastrophe_dic_tidy.csv dataset\n Outputs:\n (\n bs_unlabeled_mean_conf, \n bs_labeled_mean_conf\n )\n \"\"\"\n #Labeled data\n labeled_data = df.loc[df['labeled'] == True, 'time to catastrophe (s)'].values\n\n #Unlabeled data\n unlabeled_data = df.loc[df['labeled'] == False, 'time to catastrophe (s)'].values\n \n # get bootstrap replicates\n bs_labeled_means = bebi103.bootstrap.draw_bs_reps(labeled_data, np.mean, size=10000)\n bs_unlabeled_means = bebi103.bootstrap.draw_bs_reps(unlabeled_data, np.mean, size=10000)\n\n # calculate 95% confidence interval for labeled\n bs_labeled_mean_conf = np.percentile(bs_labeled_means, [2.5, 97.5])\n\n # calculate 95% confidence interval for unlabeled\n bs_unlabeled_mean_conf = np.percentile(bs_unlabeled_means, [2.5, 97.5])\n \n return (bs_unlabeled_mean_conf, bs_labeled_mean_conf)\n\n#output\n# Mean unlabeled conf int: [353.105, 477.475]\n# Mean labeled conf int: [402.275, 481.303]\n\n# +\ndef diff_means(df):\n \"\"\"\n get test statistic and and p-value for \n difference of mean catastrophe times.\n Null hypothesis that the two distributions are the same\n and thus the means are also the same\n \n Inputs:\n df : dataframe of gardner_time_to_catastrophe_dic_tidy.csv dataset\n Outputs:\n (diff_mean, p_val)\n \"\"\"\n \n #Labeled data\n labeled_data = df.loc[df['labeled'] == True, 'time to catastrophe (s)'].values\n\n #Unlabeled data\n unlabeled_data = df.loc[df['labeled'] == False, 'time to catastrophe (s)'].values\n \n # Compute test statistic for original data set\n diff_mean = np.mean(labeled_data) - np.mean(unlabeled_data)\n\n # Draw permutation replicates\n perm_reps = bebi103.bootstrap.draw_perm_reps(\n labeled_data, unlabeled_data, bebi103.bootstrap.diff_of_means, size = 10000\n )\n\n # Compute p-value\n p_val = np.sum(perm_reps >= diff_mean) / len(perm_reps)\n return (diff_mean, p_val)\n\n#Output\n# Experimental difference of means: 28.185\n# p-value = 0.229\n\n# +\ndef diff_means_student(df):\n \"\"\"\n get test statistic and and p-value for \n difference of mean catastrophe times, assuming\n student t distribution. Takes into account std\n \n Null hypothesis that the two distributions are the same\n and thus the means are also the same\n \n Inputs:\n df : dataframe of gardner_time_to_catastrophe_dic_tidy.csv dataset\n Outputs:\n (diff_mean_studentized, p_val_studentized)\n Notes: \n Uses bebi103.bootstrap.studentized_diff_of_means\n \"\"\"\n \n #Labeled data\n labeled_data = df.loc[df['labeled'] == True, 'time to catastrophe (s)'].values\n\n #Unlabeled data\n unlabeled_data = df.loc[df['labeled'] == False, 'time to catastrophe (s)'].values\n \n diff_mean_studentized = bebi103.bootstrap.studentized_diff_of_means(\n labeled_data, unlabeled_data\n )\n\n # Draw permutation replicates\n perm_reps_studentized = bebi103.bootstrap.draw_perm_reps(\n labeled_data, unlabeled_data, \n bebi103.bootstrap.studentized_diff_of_means, size = 10000\n )\n\n # Compute p-value\n p_val_studentized = np.sum(\n perm_reps_studentized >= diff_mean_studentized\n ) / len(perm_reps_studentized)\n \n return (diff_mean_studentized, p_val_studentized)\n\n#Output\n# Experimental studentized difference of means: 0.752\n# p-value = 0.239\n\n\n# +\ndef conf_int_means_normal(df):\n \"\"\"\n get 95% confidence intervals for labeled and unlabeled \n mean catastrophe times assuming normal distribution;\n interval over which 95% of the probability mass of the normal distribution lies \n \n Inputs:\n df : dataframe of gardner_time_to_catastrophe_dic_tidy.csv dataset\n Outputs:\n (\n conf_int_unlabeled,\n conf_int_labeled\n )\n \"\"\"\n #Labeled data\n labeled_data = df.loc[df['labeled'] == True, 'time to catastrophe (s)'].values\n\n #Unlabeled data\n unlabeled_data = df.loc[df['labeled'] == False, 'time to catastrophe (s)'].values\n\n # mean of labeled\n labeled_mean = np.mean(labeled_data)\n\n # mean of unlabled\n unlabeled_mean = np.mean(unlabeled_data)\n\n # CI of labeled\n conf_int_labeled = scipy.stats.norm.interval(0.95, loc=labeled_mean, scale=np.std(labeled_data)/np.sqrt(len(labeled_data)))\n \n # CI of unlabeled\n conf_int_unlabeled = scipy.stats.norm.interval(0.95, loc=unlabeled_mean, scale=np.std(unlabeled_data)/np.sqrt(len(unlabeled_data)))\n \n return (conf_int_unlabeled, conf_int_labeled)\n\n# #output\n# Mean unlabeled conf int: [351.165, 473.888]\n# Mean labeled conf int: [400.836, 480.586]\n\n# +\ndef main():\n df = tidy_data.tidy_dic()\n bs_unlabeled_mean_conf, bs_labeled_mean_conf = conf_int_means(df)\n\n print(\n \"\"\"\n Mean unlabeled conf int: [{0:.3f}, {1:.3f}]\n \"\"\".format(\n *tuple(bs_unlabeled_mean_conf)\n )\n )\n \n print(\n \"\"\"\n Mean labeled conf int: [{0:.3f}, {1:.3f}]\n \"\"\".format(\n *tuple(bs_labeled_mean_conf)\n )\n )\n \n print('\\n\\n')\n \n diff_mean, p_val = diff_means(df)\n \n print(f'Experimental difference of means: {diff_mean:.3f}')\n print(f'p-value = {p_val:.3f}')\n \n print('\\n\\n')\n \n diff_mean_studentized, p_val_studentized = diff_means_student(df)\n \n print(f'Experimental studentized difference of means: {diff_mean_studentized:.3f}')\n print(f'p-value = {p_val_studentized:.3f}')\n \n print('\\n\\n')\n \n normal_conf_int_unlabeled, normal_conf_int_labeled = conf_int_means_normal(df)\n \n print(\n \"\"\"\n Mean unlabeled conf int: [{0:.3f}, {1:.3f}]\n \"\"\".format(\n *tuple(normal_conf_int_unlabeled)\n )\n )\n \n print(\n \"\"\"\n Mean labeled conf int: [{0:.3f}, {1:.3f}]\n \"\"\".format(\n *tuple(normal_conf_int_labeled)\n )\n )\n return True\n \nif __name__ == '__main__': main()\n\n# +\n#!jupytext --to python controls.ipynb\n","sub_path":"sandbox_code/controls.py","file_name":"controls.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"5971103","text":"import re\nimport math\nfrom collections import defaultdict\nfrom datetime import datetime\n\n#-------------- REGEX ---------------\nPID = r'Id:\\s*(\\d+)'\nASIN = r'ASIN:\\s*\\d+'\nCID = r'cutomer:\\s*(\\w+)'\nDISC = r'discontinued product'\nCSIZE = r'total:\\s*(\\d+)'\n#-------------- ---------------------\nMAX_CLIENTS = 5486\ntotal_capacity = 0\n#pid_temp\namazon_data = defaultdict(list) #client has many products\n\n\n\nf = open('../amazon-meta.txt', 'r')\nflog = open('log.txt', 'w')\nfgraph = open('graph.in', 'w')\n\n\nstime = datetime.now()\nsearchProduct = True\nreviews = 0\nproduct_reviews = {}\ntotal_reviews = 0\nfor line in f:\n\t#Esta procurando ou por produto ou por cliente\n\tif searchProduct:\n\t\tpid_temp = re.search(PID, line)\n\t\tif pid_temp:\n\t\t\tsearchProduct = False #Assim que encontra produto, eh hora de encontrar cliente\n\t\t\tindex = int(pid_temp.group(1))\n\telse:\n\t\tpid_temp2 = re.search(PID, line)\n\t\tif pid_temp2:\n\t\t\t pid_temp = pid_temp2 #discontinued product case. o produto nao tinha review portando pulou para o proximo produto\n\t\t\t index = int(pid_temp.group(1))\n\n\t\treview = re.search(CSIZE,line)\n\t\tif review:\n\t\t\treviews = int(review.group(1))\n\t\t\tif reviews > 0:\n\t\t\t\tproduct_reviews[pid_temp.group(1)] = reviews\n\t\t\t\ttotal_reviews += reviews\n\n\t\tcid = re.search(CID, line)\n\t\tif cid:\n\t\t\t#print pid_temp.group(1),cid.group(1)\n\t\t\tif not pid_temp.group(1) in amazon_data[cid.group(1)]: #do not repeat items on list\n\t\t\t\tamazon_data[cid.group(1)].append(pid_temp.group(1))\n\t\t\tif len(amazon_data) > MAX_CLIENTS:\n\t\t\t\tindex = int(pid_temp.group(1))\n\t\t\t\tbreak\n\n\n#index = 548551 #last product_id is 548551\n#1% is about 5486 clients\n#index = 200\n\n#source and sink\nfgraph.write('%s %d\\n' % (0,index+len(amazon_data) +1))\n\nfor k,v in amazon_data.iteritems():\n\tindex += 1\n\tfor p in v:\n\t\tfgraph.write('%s %s %d\\n' % (index,p,1))\n\t#40% of client reviews\n\tcapacity = math.ceil(0.4 * len(v))\n\tfgraph.write('%s %s %d\\n' % (0,index,capacity))\n\ttotal_capacity += capacity\n\n\n#60% product reviews\nfor k,v in product_reviews.iteritems():\n\tfgraph.write('%s %s %d\\n' % (k,index+1,v))\n\n\nflog.write(\"start time: %s\\n\" % stime)\nflog.write(\"end time: %s\\n\" % datetime.now())\nflog.write(\"number of users: %d\\n\" % index)\nflog.write(\"number of products: %d\\n\" % len(product_reviews))\nflog.write(\"total of reviews: %d\\n\" % total_reviews)\nflog.write(\"total capacity: %d\\n\" % total_capacity)\n\nflog.close()\nf.close()\nfgraph.close()\n\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"454118995","text":"import csv, urllib\nfrom flask import request\n\n\n\ndef getHistory(symbol):\n \"\"\"Look up quote for symbol.\"\"\"\n\n # reject symbol if it starts with caret\n if symbol.startswith(\"^\"):\n return None\n\n # reject symbol if it contains comma\n if \",\" in symbol:\n return None\n\n # query Yahoo for quote\n # http://stackoverflow.com/a/21351911\n try:\n url = \"http://ichart.finance.yahoo.com/table.csv?\" + \"s={}\".format(symbol) + \"&a={}\".format(1) + \"&b={}\".format(1) + \"&c={}\".format(2017) + \"&g=d\"\n print(str(url))\n \"\"\" \n num2str(startMonth - 1), ... % Start Month - 1\n num2str(startDay), ... % Start Day\n num2str(startYear), ... % Start Year\n sFreq]; % Frequency(d->daily, w->weekly, m->monthly\n url = \"http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={}\".format(symbol)\n \"\"\"\n\n webpage = urllib.request.urlopen(url)\n datareader = csv.reader(webpage.read().decode(\"utf-8\").splitlines())\n row = next(datareader)\n print(str(row))\n except:\n return None\n\n # ensure stock exists\n try:\n price = float(row[2])\n except:\n return None\n\n # return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)\n return {\n \"name\": row[1],\n \"price\": price,\n \"symbol\": row[0].upper()\n }\n\ngetHistory(\"USD\")","sub_path":"symbol.py","file_name":"symbol.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"90"} +{"seq_id":"128809608","text":"import os\n\nclass IntegTestSuite:\n def __init__(self, name, repo):\n self.name = name\n self.repo = repo\n\n def execute(self, cluster):\n script = self.repo.dir + \"/integtest.sh\"\n if (os.path.exists(script)):\n print(f'sh {script} -b {cluster.endpoint()} -p {cluster.port()}')\n self.repo.execute(f'sh {script} -b {cluster.endpoint()} -p {cluster.port()}')\n else:\n print(f'{script} does not exist. Skipping integ tests for {self.name}')\n","sub_path":"bundle-workflow/python/test_workflow/integ_test_suite.py","file_name":"integ_test_suite.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"363711365","text":"'''\nTools for extracting info, timestamps, and frames from mkv files\n'''\nimport os\nimport subprocess\nimport numpy as np\n\n\ndef get_mkv_info(fileloc, stream=1):\n stream_features = [\"width\", \"height\", \"r_frame_rate\", \"pix_fmt\"]\n\n outs = {}\n for _feature in stream_features:\n command = [\n \"ffprobe\",\n \"-select_streams\",\n \"v:{}\".format(int(stream)),\n \"-v\",\n \"fatal\",\n \"-show_entries\",\n \"stream={}\".format(_feature),\n \"-of\",\n \"default=noprint_wrappers=1:nokey=1\",\n fileloc,\n \"-sexagesimal\",\n ]\n ffmpeg = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = ffmpeg.communicate()\n if err:\n print(err)\n outs[_feature] = out.decode(\"utf-8\").rstrip(\"\\n\")\n\n # need to get duration and nframes the old fashioned way\n outs[\"duration\"] = get_mkv_duration(fileloc)\n timestamps = get_mkv_timestamps(fileloc,stream)\n outs[\"nframes\"] = len(timestamps)\n\n return (\n {\n \"file\": fileloc,\n \"dims\": (int(outs[\"width\"]), int(outs[\"height\"])),\n \"fps\": float(outs[\"r_frame_rate\"].split(\"/\")[0])\n / float(outs[\"r_frame_rate\"].split(\"/\")[1]),\n \"duration\": outs[\"duration\"],\n \"pixel_format\": outs[\"pix_fmt\"],\n \"nframes\": outs[\"nframes\"],\n },\n timestamps,\n )\n\ndef get_mkv_duration(fileloc, stream=1):\n command = [\n \"ffprobe\",\n \"-v\",\n \"fatal\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"default=noprint_wrappers=1:nokey=1\",\n fileloc,\n ]\n\n ffmpeg = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = ffmpeg.communicate()\n if err:\n print(err)\n return float(out.decode(\"utf-8\").rstrip(\"\\n\"))\n\n\ndef get_mkv_timestamps(fileloc, stream=1,threads=8):\n command = [\n \"ffprobe\",\n \"-select_streams\",\n \"v:{}\".format(int(stream)),\n \"-v\",\n \"fatal\",\n \"-threads\", str(threads),\n \"-show_entries\",\n \"frame=pkt_pts_time\",\n \"-of\",\n \"csv=p=0\",\n fileloc,\n ]\n\n ffmpeg = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = ffmpeg.communicate()\n if err:\n print(err)\n timestamps = out.decode(\"utf-8\").rstrip(\"\\n\").split(\"\\n\")\n timestamps = np.array([float(_) for _ in timestamps])\n return timestamps\n\ndef get_mkv_stream_names(fileloc):\n stream_tag = \"title\"\n\n outs = {}\n command = [\n \"ffprobe\",\n \"-v\",\n \"fatal\",\n \"-show_entries\",\n \"stream_tags={}\".format(stream_tag),\n \"-of\",\n \"default=noprint_wrappers=1:nokey=1\",\n fileloc,\n ]\n ffmpeg = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = ffmpeg.communicate()\n if err:\n print(err)\n out = out.decode(\"utf-8\").rstrip(\"\\n\").split(\"\\n\")\n \n \n ## !! changed the key/value order here from what JM had: (i.e. so the string name is the key, the stream is the value)\n return dict(list(zip(out,np.arange(len(out)))))\n\n\ndef get_mkv_stream_tag(fileloc, stream=1, tag=\"K4A_START_OFFSET_NS\"):\n\n command = [\n \"ffprobe\",\n \"-v\",\n \"fatal\",\n \"-show_entries\",\n \"format_tags={}\".format(tag),\n \"-of\",\n \"default=noprint_wrappers=1:nokey=1\",\n fileloc,\n ]\n ffmpeg = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n out, err = ffmpeg.communicate()\n if err:\n print(err)\n out = out.decode(\"utf-8\").rstrip(\"\\n\")\n return out","sub_path":"build/lib/moseq2_ephys_sync/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"175781470","text":"\ncomprobar=True\nwhile comprobar == True:\n\tn1=int(input(\"Ingrese un numero entero positivo:\"))\n\tn2=int(input(\"Ingrese un numero entero positivo:\"))\n\ta=0\n\tif n1>0 and n2>0 and n1!=n2:\n\t\tcomprobar=False\n\t\tif n1>n2:\n\t\t\tn1^=n2\n\t\t\tn2^=n1\n\t\t\tn1^=n2\n\n\t\tfor i in range(n1,n2):\n\t\t\tcreciente=2\n\t\t\tes_Primo= True\n\n\t\t\twhile es_Primo and creciente 0:\n # HPが残っていたら追加攻撃する\n hit = ceil(h / A)\n ans += hit\n damage = hit * A\n damage_sum += damage\n # (有効期限、そのモンスターに与えたダメージ)\n q.append((x + 2 * D, damage))\n\nprint(ans)\n","sub_path":"abc/153/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"166867363","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom channel.models import Channel, Category\nfrom channel.serializers import ChannelSerializer, CategorySerializer\nfrom .models import ApiImplementation\n\n\ndef docs(request):\n '''\n @docs: List all API Calls\n '''\n docs = ApiImplementation.objects.all()\n return render(request, 'api_doc.html', {'docs': docs})\n\n\ndef doc_view(request, doc_id):\n '''\n @doc_view: View all Infos\n '''\n api = ApiImplementation.objects.get(id=doc_id)\n template_data = {'api': api}\n return render(request, 'api_view_modal.html', template_data)\n\n\n@api_view(['GET', 'POST'])\ndef channels(request):\n \"\"\"\"\n @channels: Method to List or Create a Channel according the\n HTTP Request, GET and POST\n \"\"\"\n if request.method == 'GET':\n # Pega uma listagem de Produtos\n channels = Channel.objects.all()\n serializer = ChannelSerializer(channels, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = ChannelSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n else:\n return HttpResponse('Unauthorized', status=401)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef channel(request, channel_id):\n \"\"\"\n @channel: Method to GET, UPDATE or DELETE a Channel according\n the HTTP Request\n \"\"\"\n try:\n channel = Channel.objects.get(id=channel_id)\n except Channel.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = ChannelSerializer(channel)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = ChannelSerializer(channel, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n else:\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n channel.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET', 'POST'])\ndef categories(request):\n \"\"\"\"\n @categories: Method to List or Create a Channel according the\n HTTP Request, GET and POST\n \"\"\"\n if request.method == 'GET':\n categories = Category.objects.all()\n serializer = CategorySerializer(categories, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = CategorySerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n else:\n return HttpResponse('Unauthorized', status=401)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef category(request, category_id):\n \"\"\"\n @category: Method to GET, UPDATE or DELETE a Channel according\n the HTTP Request\n \"\"\"\n try:\n category = Category.objects.get(id=category_id)\n except Category.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = CategorySerializer(category)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = CategorySerializer(category, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n else:\n return Response(\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n category.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n","sub_path":"work-at-olist/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"649139547","text":"# Calculate Plot the GCV function and find its minimum.\n#\n# [reg_min,G,reg_param] = gcv(U,s,b,method)\n#\n# Calculates the GCV-function\n# || A*x - b ||^2\n# G = -------------------\n# (trace(I - A*A_I)^2\n# as a function of the regularization parameter reg_param.\n# Here, A_I is a matrix which produces the regularized solution.\n# and x is the solution calculated with Tikhonov regularization\n# using the regularization parameter reg_param.\n#\n# If any output arguments are specified, then the minimum of G is\n# identified and the corresponding reg. parameter reg_min is returned.\n\n# Per Christian Hansen, IMM, Dec. 16, 2003.\n\n# Reference: G. Wahba, \"Spline Models for Observational Data\",\n# SIAM, 1990.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import optimize\n\nfrom typing import Tuple\n\nfrom numba import njit\n\ndef gcv_blockdiag(\n U: np.ndarray, s: np.ndarray, b: np.ndarray, lambdarange: np.ndarray, plot: bool = False\n) -> Tuple[float, float, np.ndarray, np.ndarray]:\n npoints = lambdarange.size\n\n p = s.size\n beta = blkmul_adj(U, b)\n\n # Vector of regularization parameters.\n reg_param = np.zeros(npoints)\n G = np.copy(reg_param) # very important to copy here!!!\n s2 = s ** 2\n reg_param = np.copy(lambdarange)\n\n # Vector of GCV-function values.\n for i in range(npoints):\n G[i] = gcvfun(reg_param[i], s2, beta[:p], 0., 0) # , delta0, m - n)\n\n minGi = G.argmin(0) # Initial guess.\n reg_min = optimize.fmin(\n gcvfun,\n x0=reg_param[np.max([minGi, 0])],\n args=(s2, beta[:p], 0., 0), # delta0, m - n),\n disp=0,\n )[0]\n minG = gcvfun(reg_min, s2, beta[:p], 0., 0) # delta0, m - n) # Minimum of GCV function.\n\n if plot:\n # Plot GCV function.\n plt.plot(reg_param, G, \"-\")\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.xlabel(r\"$\\lambda$\")\n plt.ylabel(r\"$G(\\lambda)$\")\n plt.plot([reg_min], [minG], \"*r\")\n plt.plot([reg_min, reg_min], [minG / 1000, minG], \":r\")\n plt.title(r\"GCV function, minimum at $\\lambda = %.2e$\" % reg_min)\n plt.show()\n return float(reg_min), float(minG), G, reg_param\n\n\ndef gcvfun(lmbda, s2, beta, delta0, mn):\n # Auxiliary routine for gcv. PCH, IMM, Feb. 24, 2008.\n # Note: f = 1 - filter-factors.\n\n f = (lmbda ** 2) / (s2 + lmbda ** 2)\n G = (np.linalg.norm(f * beta) ** 2 + delta0) / (mn + np.sum(f)) ** 2\n return G\n\n\ndef blkmul_adj(mat: np.ndarray, v: np.ndarray) -> np.ndarray:\n \"\"\" Calculate (mat.H) @ v \"\"\"\n a, b, c = mat.shape\n assert ((a * b,) == v.shape)\n assert (a >= 1)\n MT0 = mat[0].T.conjugate()\n out0 = MT0 @ v[:c]\n out = np.empty(a * c, dtype=out0.dtype)\n out[:c] = out0\n for i in range(1, a):\n MT = mat[i].T.conjugate()\n out[i * c:i * c + c] = MT @ v[i * b:i * b + b]\n return out\n","sub_path":"src/TFM/FTTC3d/gcv_block.py","file_name":"gcv_block.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"430633660","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtMultimedia import QSound\nfrom settings import *\nimport sys\n\nclass MyWindow(QWidget):\n def __init__(self):\n super(MyWindow, self).__init__()\n self.initGUI()\n\n def NoAccess(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setWindowTitle(\"Windows Security\")\n msg.setText(\"Access is denied.\")\n msg.setInformativeText(\"\"\"\nYou require permission from the computer's administrator to make changes to this program. \nGo to Settings to manage user administrator options.\n\"\"\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n\n\n def UAC(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"User Account Control\")\n msg.setInformativeText(\"Do you want to allow the program from an unkown publisher to make changes to this computer?\")\n msg.setWindowTitle(\"User Account Control\")\n msg.setDetailedText(\"User Account Control helps prevent potentially harmful programs from making changes to your computer. (We at Windows think the user is stupid.) \")\n msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n msg.buttonClicked.connect(self.NoAccess)\n msg.exec_()\n\n def UAC2(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"User Account Control\")\n msg.setInformativeText(\"Do you really want to run this app?\")\n msg.setWindowTitle(\"User Account Control\")\n msg.setDetailedText(\"User Account Control helps prevent potentially harmful programs from making changes to your computer. (We at Windows think the user is stupid.) \")\n msg.setStandardButtons(QMessageBox.Yes)\n msg.buttonClicked.connect(self.UAC3)\n msg.exec_()\n\n def UAC3(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"User Account Control\")\n msg.setInformativeText(\"Are you sure?\")\n msg.setWindowTitle(\"User Account Control\")\n msg.setDetailedText(\"User Account Control helps prevent potentially harmful programs from making changes to your computer. (We at Windows think the user is stupid.) \")\n msg.setStandardButtons(QMessageBox.Yes)\n msg.buttonClicked.connect(self.UAC4)\n msg.exec_()\n\n def UAC4(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"User Account Control\")\n msg.setInformativeText(\"Windows does not recommend to run this app.\")\n msg.setWindowTitle(\"User Account Control\")\n msg.setDetailedText(\"User Account Control helps prevent potentially harmful programs from making changes to your computer. (We at Windows think the user is stupid.) \")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n\n def Blocked(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setWindowTitle(\"Windows Security\")\n msg.setText(\"This app has been blocked for you protection.\")\n msg.setInformativeText(\"\"\"\nAn administrator has blocked you from running this app. \nFor more information, contact the administrator:\nwww.windows.com\nGood luck! \n\"\"\")\n msg.setStandardButtons(QMessageBox.Close)\n msg.exec_()\n \n def ShutDown(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Question)\n msg.setWindowTitle(\"Windows Update\")\n msg.setText(\"Your PC needs to finish intstalling updates before shutting down.\")\n msg.setInformativeText(\"Would you like to wait?\")\n msg.setStandardButtons(QMessageBox.Yes)\n msg.exec_()\n\n def Settings(self):\n self.win = MyMainWindow()\n\n def SoundPlay(self):\n self.sound = QSound(\"sounds/pushme.wav\")\n self.sound.play()\n\n def initGUI(self):\n self.setGeometry(0, 30, 1000, 600)\n self.setWindowTitle(\"Start Menu\")\n self.setObjectName(\"main\")\n self.setStyleSheet(\"\"\"\n QWidget#main {\n background-color: #191919\n } \n \"\"\")\n\n\n self.powerbutton = QPushButton(self)\n self.powerbutton.resize(17, 17)\n self.powerbutton.setObjectName(\"powerbutton\")\n self.powerbutton.setStyleSheet(\"\"\"\n QPushButton#powerbutton {\n background-image: url('img/power.png');\n }\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.powerbutton.move(10, 550)\n self.powerbutton.clicked.connect(self.ShutDown)\n\n self.settings = QPushButton(self)\n self.settings.resize(17, 17)\n self.settings.setObjectName(\"settings\")\n self.settings.setStyleSheet(\"\"\"\n QPushButton#settings {\n background-image: url('img/settings2.png');\n }\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.settings.move(10, 500)\n self.settings.clicked.connect(self.Settings) \n\n self.explorer = QPushButton(self)\n self.explorer.resize(17, 17)\n self.explorer.setObjectName(\"explorer\")\n self.explorer.setStyleSheet(\"\"\"\n QPushButton#explorer {\n background-image: url('img/explorer.png');\n }\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.explorer.move(10, 450)\n self.explorer.clicked.connect(self.SoundPlay)\n\n self.header1 = QLabel(self)\n self.header1.setText(\"Leisure\")\n self.header1.setStyleSheet(\"\"\"\n QLabel {\n color: #D9D9D9\n }\n \"\"\")\n self.header1.move(205, 10) #x, y\n\n self.tile11 = QPushButton(self)\n self.tile11.resize(100, 100)\n self.tile11.setObjectName(\"netflix\") #incorrect sRGB\n self.tile11.setStyleSheet(\"\"\"\n QPushButton#netflix {\n background-image: url('img/netflix.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile11.move(200, 30)\n self.tile11.clicked.connect(self.UAC)\n\n self.tile12 = QPushButton(self)\n self.tile12.resize(100, 100)\n self.tile12.setObjectName(\"spotify\")\n self.tile12.setStyleSheet(\"\"\"\n QPushButton#spotify {\n background-image: url('img/spotify.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n\n \"\"\")\n self.tile12.move(310, 30)\n self.tile12.clicked.connect(self.NoAccess)\n\n self.tile13 = QPushButton(self)\n self.tile13.resize(100, 100)\n self.tile13.setObjectName(\"music\") #incorrect sRGB\n self.tile13.setStyleSheet(\"\"\"\n QPushButton#music {\n background-image: url('img/music.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n\n \"\"\")\n self.tile13.move(420, 30)\n self.tile13.clicked.connect(self.UAC2)\n\n self.header2 = QLabel(self)\n self.header2.setText(\"Office\")\n self.header2.setStyleSheet(\"\"\"\n QLabel {\n color: #D9D9D9\n }\n \"\"\")\n self.header2.move(205, 150)\n\n self.tile21 = QPushButton(self)\n self.tile21.resize(100, 100)\n self.tile21.setObjectName(\"word\")\n self.tile21.setStyleSheet(\"\"\"\n QPushButton#word {\n background-image: url('img/word.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile21.move(200, 170)\n self.tile21.clicked.connect(self.Blocked)\n\n self.tile22 = QPushButton(self)\n self.tile22.resize(100, 100)\n self.tile22.setObjectName(\"excel\")\n self.tile22.setStyleSheet(\"\"\"\n QPushButton#excel {\n background-image: url('img/excel.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile22.move(310, 170)\n self.tile22.clicked.connect(self.NoAccess)\n\n self.tile23 = QPushButton(self)\n self.tile23.resize(100, 100)\n self.tile23.setObjectName(\"powerpoint\")\n self.tile23.setStyleSheet(\"\"\"\n QPushButton#powerpoint {\n background-image: url('img/powerpoint.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile23.move(420, 170)\n self.tile23.clicked.connect(self.NoAccess)\n\n self.tile24 = QPushButton(self)\n self.tile24.resize(100, 100)\n self.tile24.setObjectName(\"sway\")\n self.tile24.setStyleSheet(\"\"\"\n QPushButton#sway {\n background-image: url('img/sway.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile24.move(200, 280)\n self.tile24.clicked.connect(self.Blocked)\n\n self.tile25 = QPushButton(self)\n self.tile25.resize(100, 100)\n self.tile25.setObjectName(\"reader\")\n self.tile25.setStyleSheet(\"\"\"\n QPushButton#reader {\n background-image: url('img/reader.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile25.move(310, 280)\n self.tile25.clicked.connect(self.UAC) \n\n self.tile26 = QPushButton(self)\n self.tile26.resize(100, 100)\n self.tile26.setObjectName(\"onenote\")\n self.tile26.setStyleSheet(\"\"\"\n QPushButton#onenote {\n background-image: url('img/onenote.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n }\n \"\"\")\n self.tile26.move(420, 280)\n self.tile26.clicked.connect(self.UAC2) \n\n\n self.header3 = QLabel(self)\n self.header3.setText(\"Creative\")\n self.header3.setStyleSheet(\"\"\"\n QLabel {\n color: #D9D9D9\n }\n \"\"\")\n self.header3.move(565, 10)\n\n self.tile31 = QPushButton(self)\n self.tile31.resize(100, 100)\n self.tile31.setObjectName(\"photoshop\")\n self.tile31.setStyleSheet(\"\"\"\n QPushButton#photoshop {\n background-image: url('img/photoshop.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile31.move(560, 30)\n self.tile31.clicked.connect(self.Blocked) \n\n self.tile32 = QPushButton(self)\n self.tile32.resize(100, 100)\n self.tile32.setObjectName(\"bridge\")\n self.tile32.setStyleSheet(\"\"\"\n QPushButton#bridge {\n background-image: url('img/bridge.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile32.move(670, 30)\n self.tile32.clicked.connect(self.UAC) \n\n self.tile33 = QPushButton(self)\n self.tile33.resize(100, 100)\n self.tile33.setObjectName(\"cubase\")\n self.tile33.setStyleSheet(\"\"\"\n QPushButton#cubase {\n background-image: url('img/cubase.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile33.move(780, 30)\n self.tile33.clicked.connect(self.NoAccess) \n\n self.header4 = QLabel(self)\n self.header4.setText(\"System\")\n self.header4.setStyleSheet(\"\"\"\n QLabel {\n color: #D9D9D9\n }\n \"\"\")\n self.header4.move(565, 150)\n\n self.tile41 = QPushButton(self)\n self.tile41.resize(100, 100)\n self.tile41.setObjectName(\"settings\")\n self.tile41.setStyleSheet(\"\"\"\n QPushButton#settings {\n background-image: url('img/settings.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile41.move(560, 170)\n self.tile41.clicked.connect(self.Settings) \n\n self.tile42 = QPushButton(self)\n self.tile42.resize(100, 100)\n self.tile42.setObjectName(\"explorer\")\n self.tile42.setStyleSheet(\"\"\"\n QPushButton#explorer {\n background-image: url('img/explorer3.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile42.move(670, 170)\n self.tile42.clicked.connect(self.NoAccess) \n\n self.tile43 = QPushButton(self)\n self.tile43.resize(100, 100)\n self.tile43.setObjectName(\"powershell\")\n self.tile43.setStyleSheet(\"\"\"\n QPushButton#powershell {\n background-image: url('img/powershell.png');\n }\n\n QPushButton {\n border: 1px #4682B4;\n }\n QPushButton:hover {\n border: 1px solid #D9D9D9;\n } \n \"\"\")\n self.tile43.move(780, 170)\n self.tile43.clicked.connect(self.Blocked) \n\n self.header5 = QLabel(self)\n self.header5.setText(\"All Applications\")\n self.header5.setStyleSheet(\"\"\"\n QLabel {\n color: #D9D9D9\n }\n \"\"\")\n self.header5.move(45, 10)\n\n self.listwidget = QListWidget(self)\n self.listwidget.addItem(\"A\")\n self.listwidget.addItem(\"Access 2016\")\n self.listwidget.addItem(\"Acrobat Reader\")\n self.listwidget.addItem(\"Adobe Bridge\")\n self.listwidget.addItem(\"Adobe Photoshop\")\n self.listwidget.addItem(\"Alarm & Clock\")\n self.listwidget.addItem(\"Anaconda2\")\n self.listwidget.addItem(\"Arduino\")\n self.listwidget.addItem(\"Audacity\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"B\")\n self.listwidget.addItem(\"Blender\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"C\")\n self.listwidget.addItem(\"Calender\")\n self.listwidget.addItem(\"Camera\")\n self.listwidget.addItem(\"Canon Utilities\")\n self.listwidget.addItem(\"Cortana\")\n self.listwidget.addItem(\"Cubase\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"D\")\n self.listwidget.addItem(\"Dropbox\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"E\")\n self.listwidget.addItem(\"Excel\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"F\")\n self.listwidget.addItem(\"Feedback-Hub\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"G\")\n self.listwidget.addItem(\"Github\")\n self.listwidget.addItem(\"Google Chrome\")\n self.listwidget.addItem(\"Groove-Music\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"M\")\n self.listwidget.addItem(\"Mail\")\n self.listwidget.addItem(\"Microsoft Edge\")\n self.listwidget.addItem(\"Mozilla Firefox\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"N\")\n self.listwidget.addItem(\"Netflix\")\n self.listwidget.addItem(\"News\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"O\")\n self.listwidget.addItem(\"OneNote\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"P\")\n self.listwidget.addItem(\"PowerPoint\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"S\")\n self.listwidget.addItem(\"Spotify\")\n self.listwidget.addItem(\"Sway\")\n self.listwidget.addItem(\"\")\n self.listwidget.addItem(\"W\")\n self.listwidget.addItem(\"Word\")\n\n\n self.listwidget.setStyleSheet(\"\"\"\n QListWidget {\n font-family: \"Monaco\", \"Andale Mono\", monospace;\n font-size: 14px;\n color: #D9D9D9;\n background-color: #191919\n }\n QScrollBar:vertical {\n border: 2px solid white;\n background: solid black;\n width: 40px;\n margin: 60px 0 0 0\n }\n \"\"\")\n self.listwidget.resize(150, 570)\n self.listwidget.move(40, 30)\n\n self.show()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n win = MyWindow()\n sys.exit(app.exec_())\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":17770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"242369116","text":"import numpy as np\nimport mujoco_py\nfrom .hex_all import quat_to_rpy,rpy_to_quat,to_tensor\n# import hex_all as my_utils\nimport time\nimport os\nimport cv2\nimport math\nfrom math import sqrt, acos, fabs, ceil\nfrom opensimplex import OpenSimplex\nfrom collections import namedtuple\nfrom scipy import ndimage\nfrom gym.utils import seeding\n\nEnv_config = namedtuple('Env_config', [\n 'name',\n 'ground_roughness',\n 'pit_gap',\n 'stump_width', 'stump_height', 'stump_float',\n 'stair_height', 'stair_width', 'stair_steps'\n])\n\n_HEIGHTFIELD_ID = 0\n_TERRAIN_SMOOTHNESS = 0.15 # 0.0: maximally bumpy; 1.0: completely smooth.\n_TERRAIN_BUMP_SCALE = 2 # Spatial scale of terrain bumps (in meters).\n_DEFAULT_VALUE_AT_MARGIN = 0.1\n\nSCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well\n\nVIEWPORT_W = 600\nVIEWPORT_H = 400\n\nTERRAIN_STEP = 14 / SCALE\nTERRAIN_LENGTH = 100000 # in steps\nTERRAIN_HEIGHT = VIEWPORT_H / SCALE / 4\n# TERRAIN_HEIGHT = 1.0\nTERRAIN_GRASS = 10 # low long are grass spots, in steps\nTERRAIN_STARTPAD = 120 # in steps\n\nimport random\nimport string\n#\n# import gym\n# from gym import spaces\n# from gym.utils import seeding\n\nclass Hexapod():\n MODELPATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"assets/hexapod_trossen_all.xml\")\n\n def __init__(self, env_list=None, max_n_envs=6, specific_env_len=30, s_len=200, walls=True):\n # print(\"Trossen hexapod envs: {}\".format(env_list))\n\n # if env_list is None:\n # self.env_list = [\"flat\"]\n # else:\n # self.env_list = env_list\n\n # self.ID = '_'.join(self.env_list)\n # self.specific_env_len = specific_env_len\n # self.env_scaling = self.specific_env_len / 38.\n\n # self.modelpath = Hexapod.MODELPATH\n # self.n_envs = np.minimum(max_n_envs, len(self.env_list))\n # self.s_len = s_len\n # self.max_steps = int(self.n_envs * self.s_len * 0.7)\n self.max_steps = 5000\n # self.env_change_prob = 0.2\n # self.env_width = 20\n # self.cumulative_environment_reward = None\n # self.walls = walls\n\n self.rnd_init_yaw = True\n # self.replace_envs = True\n\n # self.joints_rads_low = np.array([-0.4, -1.2, -1.0] * 6)\n # self.joints_rads_high = np.array([0.4, 0.2, 0.6] * 6)\n self.joints_rads_low = np.array([-0.6, -1.4, -0.8] * 6)\n self.joints_rads_high = np.array([0.6, 0.4, 0.8] * 6)\n self.joints_rads_diff = self.joints_rads_high - self.joints_rads_low\n\n self.use_HF = False\n self.HF_width = 5\n self.HF_length = 5\n\n self.env_config = None\n self.env_params = None\n self.env_seed = None\n self._seed()\n\n self.step_ctr = 0\n self.sum_reward = 0.0\n self.reward_threshold = 3000.0\n # self.over = 0\n self.wrong_dir_count = 0\n\n self.hf_offset_x = 17\n self.hf_offset_y = 20\n self.finish = False\n\n self.vel_sum = 0\n self.viewer = None\n path = Hexapod.MODELPATH\n # path = Hexapod.MODELPATH + \"{}.xml\".format(self.ID)\n\n while True:\n try:\n self.model = mujoco_py.load_model_from_path(path)\n break\n except Exception:\n pass\n\n self.sim = mujoco_py.MjSim(self.model)\n self.model.opt.timestep = 0.02\n\n # Environment dimensions\n self.q_dim = self.sim.get_state().qpos.shape[0]\n self.qvel_dim = self.sim.get_state().qvel.shape[0]\n\n if self.use_HF:\n self.obs_dim = 18 * 2 + 6 + 4 + 6 + 1 + 26\n else:\n self.obs_dim = 18 * 2 + 6 + 4 + 6 + 1\n self.act_dim = self.sim.data.actuator_length.shape[0]\n\n # self.generate_hybrid_env(self.n_envs, self.specific_env_len * self.n_envs)\n self.reset()\n\n #self.observation_space = spaces.Box(low=-1, high=1, dtype=np.float32, shape=(self.obs_dim,))\n #self.action_space = spaces.Box(low=-1, high=1, dtype=np.float32, shape=(self.act_dim,))\n\n def seed(self, seed=None):\n return self._seed(seed)\n\n def _seed(self, seed=None):\n self.env_seed = seed\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def set_env_config(self, env_config):\n self.config = env_config\n\n def augment(self, params):\n self.env_params = params\n\n def setupcam(self):\n self.viewer = mujoco_py.MjViewer(self.sim)\n self.viewer.cam.distance = self.model.stat.extent * .3\n self.viewer.cam.lookat[0] = 2.\n self.viewer.cam.lookat[1] = 0.3\n self.viewer.cam.lookat[2] = 0.9\n self.viewer.cam.elevation = -30\n self.viewer.cam.azimuth = -10\n\n def scale_joints(self, joints):\n return joints\n\n # sjoints = np.array(joints)\n # sjoints = ((sjoints - self.joints_rads_low) / self.joints_rads_diff) * 2 - 1\n # return sjoints\n\n\n def scale_action(self, action):\n return (np.array(action) * 0.5 + 0.5) * self.joints_rads_diff + self.joints_rads_low\n\n\n def scale_inc(self, action):\n action *= (self.joints_rads_diff / 2.)\n joint_list = np.array(self.sim.get_state().qpos.tolist()[7:7 + self.act_dim])\n joint_list += action\n ctrl = np.clip(joint_list, self.joints_rads_low, self.joints_rads_high)\n return ctrl\n\n\n def scale_torque(self, action):\n return action\n\n\n def get_obs(self):\n qpos = self.sim.get_state().qpos.tolist()\n qvel = self.sim.get_state().qvel.tolist()\n a = qpos + qvel\n return np.asarray(a, dtype=np.float32)\n\n\n def get_obs_dict(self):\n od = {}\n # Intrinsic parameters\n for j in self.sim.model.joint_names:\n od[j + \"_pos\"] = self.sim.data.get_joint_qpos(j)\n od[j + \"_vel\"] = self.sim.data.get_joint_qvel(j)\n\n # Contacts:\n od['contacts'] = (np.abs(np.array(self.sim.data.cfrc_ext[[4, 7, 10, 13, 16, 19]])).sum(axis=1) > 0.05).astype(np.float32)\n\n return od\n\n\n def get_state(self):\n return self.sim.get_state()\n\n\n def set_state(self, qpos, qvel=None):\n qvel = np.zeros(self.q_dim) if qvel is None else qvel\n old_state = self.sim.get_state()\n new_state = mujoco_py.MjSimState(old_state.time, qpos, qvel,\n old_state.act, old_state.udd_state)\n self.sim.set_state(new_state)\n self.sim.forward()\n\n\n def render(self, human=True):\n if self.viewer is None:\n self.viewer = mujoco_py.MjViewer(self.sim)\n\n self.viewer.render()\n\n\n def step(self, ctrl):\n obs_p = self.get_obs()\n ctrl = np.clip(ctrl, -1, 1)\n #ctrl_pen = np.square(ctrl).mean()\n torques = self.sim.data.actuator_force\n ctrl_pen = np.square(torques).mean()\n ctrl = self.scale_action(ctrl)\n\n self.sim.data.ctrl[:] = ctrl\n self.sim.forward()\n self.sim.step()\n self.step_ctr += 1\n\n obs = self.get_obs()\n\n # Angle deviation\n x, y, z, qw, qx, qy, qz = obs[:7]\n xd, yd, zd, thd, phid, psid = self.sim.get_state().qvel.tolist()[:6]\n #xa, ya, za, tha, phia, psia = self.sim.data.qacc.tolist()[:6]\n\n self.vel_sum += xd\n\n # Reward conditions\n target_vel = 0.4\n\n velocity_rew = 1. / (abs(xd - target_vel) + 1.) - 1. / (target_vel + 1.)\n velocity_rew = velocity_rew * (1/(1 + 30 * np.square(yd)))\n\n roll, pitch, _ = quat_to_rpy([qw,qx,qy,qz])\n #yaw_deviation = np.min((abs((yaw % 6.183) - (0 % 6.183)), abs(yaw - 0)))\n\n q_yaw = 2 * acos(qw)\n\n yaw_deviation = np.min((abs((q_yaw % 6.183) - (0 % 6.183)), abs(q_yaw - 0)))\n y_deviation = y\n\n # y 0.2 stable, q_yaw 0.5 stable\n r_neg = np.square(y) * 0.1 + \\\n np.square(q_yaw) * 0.1 + \\\n np.square(pitch) * 0.5 + \\\n np.square(roll) * 0.5 + \\\n ctrl_pen * 0.0001 + \\\n np.square(zd) * 0.7\n\n\n r_pos = velocity_rew * 6 + (abs(self.prev_deviation) - abs(yaw_deviation)) * 10 + (abs(self.prev_y_deviation) - abs(y_deviation)) * 10\n r = r_pos - r_neg\n\n self.prev_deviation = yaw_deviation\n self.prev_y_deviation = y_deviation\n\n # obs_c = self.get_agent_obs()\n # if np.sum(obs_p[-6:]) == -6 and np.sum(obs_c[-6:]) == -6:\n # self.over += 1\n # else:\n # self.over = 0\n\n bonus = 0.0\n x_cor, y_cor = self.get_local_cor(x, y)\n if x_cor > self.model.hfield_ncol[_HEIGHTFIELD_ID] - 5:\n self.finish = True\n bonus = 500\n if x - obs_p[0] <= 0:\n self.wrong_dir_count += 1\n else:\n self.wrong_dir_count = 0\n\n r = r + bonus\n\n # Reevaluate termination condition\n # done = self.step_ctr > self.max_steps #or abs(y) > 0.3 or abs(roll) > 1.4 or abs(pitch) > 1.4\n done = z < -(self.model.hfield_size[0, 2] + self.model.hfield_size[0, 3]) or self.step_ctr > self.max_steps \\\n or self.finish or self.wrong_dir_count > 500 # or self.over > 100\n\n contacts = (np.abs(np.array(self.sim.data.cfrc_ext[[4, 7, 10, 13, 16, 19]])).sum(axis=1) > 0.05).astype(np.float32)\n\n if self.use_HF:\n obs = np.concatenate([self.scale_joints(self.sim.get_state().qpos.tolist()[7:]),\n self.sim.get_state().qvel.tolist()[6:],\n self.sim.get_state().qvel.tolist()[:6],\n [qw, qx, qy, qz, y],\n contacts, self.get_local_hf(x,y).flatten(), [np.var(self.get_local_hf(x,y))]])\n else:\n obs = np.concatenate([self.scale_joints(self.sim.get_state().qpos.tolist()[7:]),\n self.sim.get_state().qvel.tolist()[6:],\n self.sim.get_state().qvel.tolist()[:6],\n [qw, qx, qy, qz, y],\n contacts])\n\n info = {\n 'finish': self.finish,\n 'level': np.var(self.get_local_hf(x, y)),\n }\n\n return obs, r, done, info\n\n\n def reset(self, init_pos = None):\n\n # if np.random.rand() < self.env_change_prob:\n # self.generate_hybrid_env(self.n_envs, self.specific_env_len * self.n_envs)\n # time.sleep(0.3)\n\n self.distroy_terrains()\n self.gen_terrains()\n\n #if self.use_HF:\n # self.obs_dim += self.HF_width * self.HF_length\n\n # Reset env variables\n self.step_ctr = 0\n self.episodes = 0\n\n self.viewer = None\n self.over = 0\n self.sum_reward = 0.0\n self.finish = False\n self.wrong_dir_count = 0\n\n # Sample initial configuration\n init_q = np.zeros(self.q_dim, dtype=np.float32)\n init_q[0] = np.random.randn() * 0.1 + 0.0 # np.random.rand() * 4 - 4\n init_q[1] = np.random.randn() * 0.1 + 0.0 # np.random.rand() * 8 - 4\n init_q[2] = np.random.randn() * 0.1 + 0.18\n init_qvel = np.random.randn(self.qvel_dim).astype(np.float32) * 0.1\n\n if init_pos is not None:\n init_q[0:3] += init_pos\n\n self.vel_sum = 0\n\n # Init_quat\n if self.rnd_init_yaw:\n self.rnd_yaw = np.random.rand() * 1.6 - 0.8\n else:\n self.rnd_yaw = 0\n\n rnd_quat = rpy_to_quat(0,0,self.rnd_yaw)\n init_q[3:7] = rnd_quat\n\n self.prev_deviation = np.min((abs((self.rnd_yaw % 6.183) - (0 % 6.183)), abs(self.rnd_yaw - 0)))\n self.prev_y_deviation = 0\n\n # Set environment state\n self.set_state(init_q, init_qvel)\n\n for i in range(20):\n self.sim.forward()\n self.sim.step()\n\n obs, _, _, _ = self.step(np.zeros(self.act_dim))\n\n return obs\n\n def get_local_cor(self, x, y):\n x_coord = int((x + self.hf_offset_x) * 5)\n y_coord = int((y + self.hf_offset_y) * 5)\n # print(x,y,x_coord,y_coord)\n return x_coord, y_coord\n\n def get_local_hf(self, x, y):\n x_coord, y_coord = self.get_local_cor(x, y)\n # return self.hf_grid_aug[y_coord - int(0.35*5): y_coord + int(0.35*5),\n # x_coord - int(0.4*5): x_coord + int(0.65*5)]\n return self.hf_grid_aug[y_coord - 2: y_coord + 3,\n x_coord - 2: x_coord + 3]\n\n def distroy_terrains(self):\n import glfw\n if self.viewer is not None:\n glfw.destroy_window(self.viewer.window)\n self.viewer = None\n res = self.model.hfield_nrow[_HEIGHTFIELD_ID]\n assert res == self.model.hfield_ncol[_HEIGHTFIELD_ID]\n start_idx = self.model.hfield_adr[_HEIGHTFIELD_ID]\n self.model.hfield_data[start_idx:start_idx+res*self.model.hfield_ncol[_HEIGHTFIELD_ID]] = np.zeros((res, res)).ravel()\n\n def gen_terrains(self):\n if self.model.hfield_size[0, 2] <= 2.2:\n self.model.hfield_size[0, 2] += 0.001\n level = np.random.uniform(0.5, self.model.hfield_size[0, 2]+0.5, 1)\n res = self.model.hfield_nrow[_HEIGHTFIELD_ID]\n assert res == self.model.hfield_ncol[_HEIGHTFIELD_ID]\n # Sinusoidal bowl shape.\n row_grid, col_grid = np.ogrid[-1:1:res*1j, -1:1:res*1j]\n radius = np.clip(np.sqrt(col_grid**2 + row_grid**2), .04, 1)\n bowl_shape = level - np.cos(2*np.pi*radius)/2\n # Random smooth bumps.\n terrain_size = 2 * self.model.hfield_size[_HEIGHTFIELD_ID, 0]\n bump_res = int(terrain_size / _TERRAIN_BUMP_SCALE)\n bumps = np.random.uniform(_TERRAIN_SMOOTHNESS, 1, (bump_res, bump_res))\n smooth_bumps = ndimage.zoom(bumps, res / float(bump_res))\n terrain_bowl = bowl_shape * smooth_bumps\n if self.env_params is not None:\n # Terrain is elementwise product.\n terrain_bowl = (terrain_bowl - np.min(terrain_bowl)) / (np.max(terrain_bowl) - np.min(terrain_bowl)) * \\\n (self.model.hfield_size[_HEIGHTFIELD_ID, 2] - 0.0) + 0.0\n terrain = terrain_bowl * 0.3 + self._generate_terrain() * 0.7\n # terrain = self._generate_terrain()\n else:\n terrain = bowl_shape * smooth_bumps\n # terrain = self._generate_terrain()\n terrain = (terrain - np.min(terrain)) / (np.max(terrain) - np.min(terrain)) * (self.model.hfield_size[_HEIGHTFIELD_ID, 2] - 0.0) + 0.0\n\n # self.difficulty_meassure(terrain)\n\n start_idx = self.model.hfield_adr[_HEIGHTFIELD_ID]\n self.model.hfield_data[start_idx:start_idx+res*self.model.hfield_ncol[_HEIGHTFIELD_ID]] = terrain.ravel()\n # print('variance: ', np.var(terrain.ravel()))\n\n self.hf_data = self.model.hfield_data\n self.hf_ncol = self.model.hfield_ncol[0]\n self.hf_nrow = self.model.hfield_nrow[0]\n self.hf_size = self.model.hfield_size[0]\n self.hf_grid = self.hf_data.reshape((self.hf_nrow, self.hf_ncol))\n self.hf_grid_aug = np.zeros((self.hf_nrow * 2, self.hf_ncol * 2))\n self.hf_grid_aug[:self.hf_nrow, :self.hf_ncol] = self.hf_grid\n self.hf_m_per_cell = float(self.hf_size[1]) / self.hf_nrow\n self.rob_dim = 0.5\n self.hf_res = int(self.rob_dim / self.hf_m_per_cell)\n self._healthy_z_range = (0.2, 0.5 + np.max(self.model.hfield_data))\n\n # # Height field\n # self.hf_column_meters = self.model.hfield_size[0][0] * 2\n # self.hf_row_meters = self.model.hfield_size[0][1] * 2\n # self.hf_height_meters = self.model.hfield_size[0][2]\n # self.pixels_per_column = self.hf_ncol / float(self.hf_column_meters)\n # self.pixels_per_row = self.hf_nrow / float(self.hf_row_meters)\n # self.hf_grid = self.hf_data.reshape((self.hf_nrow, self.hf_ncol))\n # local_grid = self.hf_grid[45:55, 5:15]\n # max_height = np.max(local_grid) * self.hf_height_meters\n\n def _generate_terrain(self):\n# self.genstairs()\n velocity = 0.0\n z_norm = 0.0\n terrain_z = []\n nrows = self.model.hfield_nrow[_HEIGHTFIELD_ID]\n ncols = self.model.hfield_ncol[_HEIGHTFIELD_ID]\n TERRAIN_HEIGHT = self.model.hfield_size[_HEIGHTFIELD_ID, 2] / 2\n z = TERRAIN_HEIGHT\n for y in range(nrows):\n for x in range(ncols):\n # nx = x\n # ny = y\n nx = x/5 - self.hf_offset_x\n ny = y/5 - self.hf_offset_y\n # nx = x * TERRAIN_STEP\n # ny = y * TERRAIN_STEP\n # nx = x / nrows - 0.5\n # ny = y / ncols - 0.5\n velocity = 0.8 * velocity + 0.08 * np.sign(TERRAIN_HEIGHT - z)\n if self.env_params is not None and self.env_params.altitude_fn is not None:\n z += velocity\n if x < TERRAIN_STARTPAD:\n # y_ = (ny + self.hf_offset_y)/20 -1\n # x_ = (nx + self.hf_offset_x)/20 -1\n mid = 12\n y_ = (ny - mid) * np.pi / mid\n x_ = (nx - mid) * np.pi / mid\n # y_ = ny/(200*TERRAIN_STEP) * 2 - 1\n # x_ = nx/(200*TERRAIN_STEP) * 2 - 1\n z = TERRAIN_HEIGHT + self.env_params.altitude_fn((x_, y_))[0]\n if y == TERRAIN_STARTPAD - 10 and x == TERRAIN_STARTPAD - 10:\n z_norm = self.env_params.altitude_fn((x_, y_))[0]\n z -= z_norm\n\n # print(self.env_params.altitude_fn((x_, y_))[0])\n # # print('dd: ', .5 - np.cos(2 * np.pi * (np.sqrt(x_ ** 2 + y_ ** 2))) / 2)\n\n # z = (1.00 * (self.env_params.altitude_fn((1 * nx, 1 * ny))[0] / 2 + 0.5)\n # + 0.50 * self.env_params.altitude_fn((2 * nx, 2 * ny))[0]\n # + 0.25 * self.env_params.altitude_fn((4 * nx, 4 * ny))[0]\n # + 0.13 * self.env_params.altitude_fn((8 * nx, 8 * ny))[0]\n # + 0.06 * self.env_params.altitude_fn((16 * nx, 16 * ny))[0]\n # + 0.03 * self.env_params.altitude_fn((32 * nx, 32 * ny))[0])\n # z = z / (1.00 + 0.50 + 0.25 + 0.13 + 0.06 + 0.03)\n # if y == TERRAIN_STARTPAD + 1 or x == TERRAIN_STARTPAD + 1:\n # z_norm = self.env_params.altitude_fn((nx, ny))[0]\n else:\n if x < TERRAIN_STARTPAD:\n velocity += np.random.uniform(-1, 1) / SCALE\n z += _TERRAIN_SMOOTHNESS * velocity\n terrain_z.append(z)\n terrain_z = np.array(terrain_z).reshape(nrows,ncols)\n # terrain = terrain_z\n # print(np.var(terrain))\n terrain = (terrain_z - np.min(terrain_z)) / (np.max(terrain_z) - np.min(terrain_z)) * (self.model.hfield_size[_HEIGHTFIELD_ID,2] - 0.2) + 0.2\n return terrain\n\n def difficulty_meassure(self, terrain):\n data = terrain[99,60:]\n dist = np.abs(np.diff(data))\n with open(\"level.txt\", \"a+\") as file:\n # with open(\"/home/fang/project/thesis/ant_poet/poet/poet_distributed/niches/box2d/ant_terrain_mjc/level.txt\", \"a+\") as file:\n file.seek(0)\n tmp = file.read(100)\n if len(tmp) > 0:\n file.write(\"\\n\")\n file.write(str(np.max(dist)))\n file.close()\n\n def genstairs(self):\n N = 200\n M = 200\n # filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n # \"assets/stairs.png\")\n # Generate stairs\n mat = np.zeros((M, N))\n\n stair_height = 20\n stair_width = 3\n current_height = 0\n\n for i in range(6):\n mat[:, 10 + i * stair_width: 10 + i * stair_width + stair_width] = current_height\n current_height += stair_height\n\n for i in range(3):\n mat[:, 28 + i * stair_width: 28 + i * stair_width + stair_width] = current_height\n\n for i in range(4):\n mat[:, 37 + i * stair_width: 37 + i * stair_width + stair_width] = current_height\n current_height -= stair_height\n\n for i in range(2):\n mat[:, 49 + i * stair_width: 49 + i * stair_width + stair_width] = current_height\n\n for i in range(3):\n mat[:, 55 + i * stair_width: 55 + i * stair_width + stair_width] = current_height\n current_height -= stair_height\n\n # ---\n for i in range(12):\n mat[:, 55 + 10 + i * stair_width: 55 + 10 + i * stair_width + stair_width] = current_height\n current_height += stair_height\n\n for i in range(15):\n mat[:, 70 + 28 + i * stair_width: 70 + 28 + i * stair_width + stair_width] = current_height\n\n mat[0, :] = 255\n mat[:, 0] = 255\n mat[-1, :] = 255\n mat[:, -1] = 255\n mat = (mat - np.min(mat)) / (np.max(mat) - np.min(mat)) * (\n self.model.hfield_size[_HEIGHTFIELD_ID, 2] - 0.2) + 0.2\n start_idx = self.model.hfield_adr[_HEIGHTFIELD_ID]\n self.model.hfield_data[start_idx:start_idx + M * self.model.hfield_ncol[_HEIGHTFIELD_ID]] = mat.ravel()\n\n self.hf_data = self.model.hfield_data\n self.hf_ncol = self.model.hfield_ncol[0]\n self.hf_nrow = self.model.hfield_nrow[0]\n self.hf_size = self.model.hfield_size[0]\n self.hf_grid = self.hf_data.reshape((self.hf_nrow, self.hf_ncol))\n self.hf_grid_aug = np.zeros((self.hf_nrow * 2, self.hf_ncol * 2))\n self.hf_grid_aug[:self.hf_nrow, :self.hf_ncol] = self.hf_grid\n self.hf_m_per_cell = float(self.hf_size[1]) / self.hf_nrow\n self.rob_dim = 0.5\n self.hf_res = int(self.rob_dim / self.hf_m_per_cell)\n # self.hf_offset_x = 16.5\n # self.hf_offset_y = 20\n self._healthy_z_range = (0.2, 0.5 + np.max(self.model.hfield_data))\n # import matplotlib.pyplot as plt\n # plt.imshow(mat, cmap='terrain')\n # plt.show()\n # cv2.imwrite(filename, mat)\n\n def perlin(self):\n from opensimplex import OpenSimplex\n oSim = OpenSimplex(seed=int(time.time()))\n\n height = 200\n\n M = self.model.hfield_ncol[0]\n N = self.model.hfield_nrow[0]\n mat = np.zeros((M, N))\n\n scale_x = np.random.randint(30, 100)\n scale_y = np.random.randint(30, 100)\n octaves = 4 # np.random.randint(1, 5)\n persistence = np.random.rand() * 0.3 + 0.3\n lacunarity = np.random.rand() + 1.5\n\n for i in range(M):\n for j in range(N):\n for o in range(octaves):\n sx = scale_x * (1 / (lacunarity ** o))\n sy = scale_y * (1 / (lacunarity ** o))\n amp = persistence ** o\n mat[i][j] += oSim.noise2d(i / sx, j / sy) * amp\n\n wmin, wmax = mat.min(), mat.max()\n mat = (mat - wmin) / (wmax - wmin) * height\n\n if np.random.rand() < 0.3:\n num = np.random.randint(50, 120)\n mat = np.clip(mat, num, 200)\n if np.random.rand() < 0.3:\n num = np.random.randint(120, 200)\n mat = np.clip(mat, 0, num)\n\n # Walls\n mat[0, 0] = 255.\n mat = (mat - np.min(mat))/(np.max(mat) - np.min(mat)) * (self.model.hfield_size[_HEIGHTFIELD_ID,2] - 0.2) + 0.2\n start_idx = self.model.hfield_adr[_HEIGHTFIELD_ID]\n self.model.hfield_data[start_idx:start_idx + M * self.model.hfield_ncol[_HEIGHTFIELD_ID]] = mat.ravel()\n\n self.hf_data = self.model.hfield_data\n self.hf_ncol = self.model.hfield_ncol[0]\n self.hf_nrow = self.model.hfield_nrow[0]\n self.hf_size = self.model.hfield_size[0]\n self.hf_grid = self.hf_data.reshape((self.hf_nrow, self.hf_ncol))\n self.hf_grid_aug = np.zeros((self.hf_nrow * 2, self.hf_ncol * 2))\n self.hf_grid_aug[:self.hf_nrow, :self.hf_ncol] = self.hf_grid\n self.hf_m_per_cell = float(self.hf_size[1]) / self.hf_nrow\n self.rob_dim = 0.5\n self.hf_res = int(self.rob_dim / self.hf_m_per_cell)\n # self.hf_offset_x = 16.5\n # self.hf_offset_y = 20\n self._healthy_z_range = (0.2, 0.5 + np.max(self.model.hfield_data))\n\n\n #def get_local_hf(self, x, y):\n # x_coord = int((x + self.x_offset) * self.pixels_per_column)\n # y_coord = int((y + self.y_offset) * self.pixels_per_row)\n\n # Get heighfield patch\n # patch = self.hf_grid_aug[self.hf_nrow + (y_coord - int(0.35 * self.pixels_per_row)):self.hf_nrow + y_coord + int(0.35 * self.pixels_per_row),\n # self.hf_ncol + x_coord - int(0.4 * self.pixels_per_column):self.hf_ncol + x_coord + int(0.65 * self.pixels_per_column)]\n\n # Resize patch to correct dims\n # patch_rs = cv2.resize(patch, (self.HF_length, self.HF_width), interpolation=cv2.INTER_NEAREST)\n #return patch_rs\n\n\n def generate_hybrid_env(self, n_envs, steps):\n #self.env_list = [\"tiles\", \"pipe\", \"pipe\"]\n envs = np.random.choice(self.env_list, n_envs, replace=self.replace_envs)\n\n if n_envs == 1:\n size_list = [steps]\n scaled_indeces_list = [0]\n else:\n size_list = []\n raw_indeces = np.linspace(0, 1, n_envs + 1)[1:-1]\n current_idx = 0\n scaled_indeces_list = []\n for idx in raw_indeces:\n idx_scaled = int(steps * idx) + np.random.randint(0, int(steps/6)) - int(steps/12)\n scaled_indeces_list.append(idx_scaled)\n size_list.append(idx_scaled - current_idx)\n current_idx = idx_scaled\n size_list.append(steps - sum(size_list))\n\n maplist = []\n current_height = 0\n for m, s in zip(envs, size_list):\n hm, current_height = self.generate_heightmap(m, s, current_height)\n maplist.append(hm)\n total_hm = np.concatenate(maplist, 1)\n heighest_point = np.max(total_hm)\n height_SF = max(heighest_point / 255., 1)\n total_hm /= height_SF\n total_hm = np.clip(total_hm, 0, 255).astype(np.uint8)\n\n #Smoothen transitions\n bnd = 2\n if self.n_envs > 1:\n for s in scaled_indeces_list:\n total_hm_copy = np.array(total_hm)\n for i in range(s - bnd, s + bnd):\n total_hm_copy[:, i] = np.mean(total_hm[:, i - bnd:i + bnd], axis=1)\n total_hm = total_hm_copy\n\n if self.walls:\n total_hm[0, :] = 255\n total_hm[:, 0] = 255\n total_hm[-1, :] = 255\n total_hm[:, -1] = 255\n else:\n total_hm[0, 0] = 255\n\n cv2.imwrite(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"assets/{}.png\".format(self.ID)), total_hm)\n\n with open(Hexapod.MODELPATH + \"template.xml\", \"r\") as in_file:\n buf = in_file.readlines()\n\n with open(Hexapod.MODELPATH + self.ID + \".xml\", \"w\") as out_file:\n for line in buf:\n if line.startswith(' \\n '.format(self.ID, self.env_scaling * self.n_envs, 0.6 * height_SF))\n elif line.startswith(' '.format(self.env_scaling * self.n_envs * 0.7))\n else:\n out_file.write(line)\n\n return envs, size_list, scaled_indeces_list\n\n\n def generate_heightmap(self, env_name, env_length, current_height):\n if env_name == \"flat\":\n hm = np.ones((self.env_width, env_length)) * current_height\n\n if env_name == \"tiles\":\n sf = 3\n hm = np.random.randint(0, 55,\n size=(self.env_width // sf, env_length // sf)).repeat(sf, axis=0).repeat(sf, axis=1)\n hm_pad = np.zeros((self.env_width, env_length))\n hm_pad[:hm.shape[0], :hm.shape[1]] = hm\n hm = hm_pad + current_height\n\n if env_name == \"pipe\":\n pipe_form = np.square(np.linspace(-1.2, 1.2, self.env_width))\n pipe_form = np.clip(pipe_form, 0, 1)\n hm = 255 * np.ones((self.env_width, env_length)) * pipe_form[np.newaxis, :].T\n hm += current_height\n\n if env_name == \"holes\":\n hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"assets/holes1.png\"))\n h, w, _ = hm.shape\n patch_y = 14\n patch_x = int(14 * self.s_len / 150.)\n rnd_h = np.random.randint(0, h - patch_x)\n rnd_w = np.random.randint(0, w - patch_y)\n hm = hm[rnd_w:rnd_w + patch_y, rnd_h:rnd_h + patch_x]\n hm = np.mean(hm, axis=2)\n hm = hm * 1.0 + 255 * 0.3\n hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC) / 2.\n\n if env_name == \"inverseholes\":\n hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"assets/holes1.png\"))\n h, w, _ = hm.shape\n patchsize = 10\n while True:\n rnd_h = np.random.randint(0, h - patchsize)\n rnd_w = np.random.randint(0, w - patchsize)\n hm_tmp = hm[rnd_w:rnd_w + patchsize, rnd_h:rnd_h + patchsize]\n #assert hm.shape == (10,10,3)\n if np.min(hm_tmp[:, :2, :]) > 160: break\n\n hm = np.mean(hm_tmp, axis=2)\n hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC)\n hm = 255 - hm\n hm *= 0.5\n hm += 127\n\n if env_name == \"bumps\":\n hm = cv2.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"assets/bumps2.png\"))\n h, w, _ = hm.shape\n patchsize = 50\n rnd_h = np.random.randint(0, h - patchsize)\n rnd_w = np.random.randint(0, w - patchsize)\n hm = hm[rnd_w:rnd_w + patchsize, rnd_h:rnd_h + patchsize]\n hm = np.mean(hm, axis=2)\n hm = cv2.resize(hm, dsize=(env_length, self.env_width), interpolation=cv2.INTER_CUBIC) / 2. + 127\n\n if env_name == \"stairs\":\n hm = np.ones((self.env_width, env_length)) * current_height\n stair_height = 45\n stair_width = 4\n\n initial_offset = 0\n n_steps = math.floor(env_length / stair_width) - 1\n\n for i in range(n_steps):\n hm[:, initial_offset + i * stair_width: initial_offset + i * stair_width + stair_width] = current_height\n current_height += stair_height\n\n hm[:, n_steps * stair_width:] = current_height\n\n\n if env_name == \"verts\":\n wdiv = 4\n ldiv = 14\n hm = np.random.randint(0, 75,\n size=(self.env_width // wdiv, env_length // ldiv),\n dtype=np.uint8).repeat(wdiv, axis=0).repeat(ldiv, axis=1)\n hm[:, :50] = 0\n hm[hm < 50] = 0\n hm = 75 - hm\n\n\n if env_name == \"triangles\":\n cw = 10\n # Make even dimensions\n M = math.ceil(self.env_width)\n N = math.ceil(env_length)\n hm = np.zeros((M, N), dtype=np.float32)\n M_2 = math.ceil(M / 2)\n\n # Amount of 'tiles'\n Mt = 2\n Nt = int(env_length / 10.)\n obstacle_height = 50\n grad_mat = np.linspace(0, 1, cw)[:, np.newaxis].repeat(cw, 1)\n template_1 = np.ones((cw, cw)) * grad_mat * grad_mat.T * obstacle_height\n template_2 = np.ones((cw, cw)) * grad_mat * obstacle_height\n\n for i in range(Nt):\n if np.random.choice([True, False]):\n hm[M_2 - cw: M_2, i * cw: i * cw + cw] = np.rot90(template_1, np.random.randint(0, 4))\n else:\n hm[M_2 - cw: M_2, i * cw: i * cw + cw] = np.rot90(template_2, np.random.randint(0, 4))\n\n if np.random.choice([True, False]):\n hm[M_2:M_2 + cw:, i * cw: i * cw + cw] = np.rot90(template_1, np.random.randint(0, 4))\n else:\n hm[M_2:M_2 + cw:, i * cw: i * cw + cw] = np.rot90(template_2, np.random.randint(0, 4))\n\n hm += current_height\n\n\n if env_name == \"perlin\":\n oSim = OpenSimplex(seed=int(time.time()))\n\n height = 100\n\n M = math.ceil(self.env_width)\n N = math.ceil(env_length)\n hm = np.zeros((M, N), dtype=np.float32)\n\n scale_x = 20\n scale_y = 20\n octaves = 4 # np.random.randint(1, 5)\n persistence = 1\n lacunarity = 2\n\n for i in range(M):\n for j in range(N):\n for o in range(octaves):\n sx = scale_x * (1 / (lacunarity ** o))\n sy = scale_y * (1 / (lacunarity ** o))\n amp = persistence ** o\n hm[i][j] += oSim.noise2d(i / sx, j / sy) * amp\n\n wmin, wmax = hm.min(), hm.max()\n hm = (hm - wmin) / (wmax - wmin) * height\n hm += current_height\n\n\n return hm, current_height\n\n\n def demo(self):\n self.reset()\n\n for i in range(1000):\n #self.step(np.random.randn(self.act_dim))\n for i in range(100):\n self.step(np.zeros((self.act_dim)))\n self.render()\n for i in range(100):\n self.step(np.array([0., -1., 1.] * 6))\n self.render()\n for i in range(100):\n self.step(np.ones((self.act_dim)) * 1)\n self.render()\n for i in range(100):\n self.step(np.ones((self.act_dim)) * -1)\n self.render()\n\n\n def info(self):\n self.reset()\n for i in range(100):\n a = np.ones((self.act_dim)) * 0\n obs, _, _, _ = self.step(a)\n print(obs[[3, 4, 5]])\n self.render()\n time.sleep(0.01)\n\n print(\"-------------------------------------------\")\n print(\"-------------------------------------------\")\n\n\n def test_record(self, policy, ID):\n episode_states = []\n episode_acts = []\n for i in range(10):\n s = self.reset()\n cr = 0\n\n states = []\n acts = []\n\n for j in range(self.max_steps):\n states.append(s)\n action = policy(to_tensor(s, True)).detach()[0].numpy()\n acts.append(action)\n s, r, done, od, = self.step(action)\n cr += r\n\n episode_states.append(np.concatenate(states))\n episode_acts.append(np.concatenate(acts))\n\n print(\"Total episode reward: {}\".format(cr))\n\n np_states = np.concatenate(episode_states)\n np_acts = np.concatenate(episode_acts)\n\n np.save(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"data/{}_states.npy\".format(ID)) , np_states)\n np.save(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"data/{}_acts.npy\".format(ID)), np_acts)\n\n\n def setseed(self, seed):\n np.random.seed(seed)\n\n\n def test(self, policy, render=True, N=30, seed=None):\n if seed is not None:\n self.setseed(seed)\n self.env_change_prob = 1\n rew = 0\n vel_rew = 0\n dist_rew = 0\n for i in range(N):\n obs = self.reset()\n cr = 0\n vr = 0\n dr = 0\n for j in range(int(self.max_steps)):\n action = policy(to_tensor(obs, True)).detach()\n obs, r, done, (r_v, r_d) = self.step(action[0].numpy())\n cr += r\n vr += r_v\n dr = max(dr, r_d)\n time.sleep(0.000)\n if render:\n self.render()\n rew += cr\n vel_rew += vr\n dist_rew += dr\n if render:\n print(\"Total episode reward: {}\".format(cr))\n if render:\n print(\"Total average reward = {}\".format(rew / N))\n return rew / N, vel_rew / N, dist_rew / N\n\n\n def test_recurrent(self, policy, render=True, N=30, seed=None):\n if seed is not None:\n np.random.seed(seed)\n self.env_change_prob = 1\n\n rew = 0\n vel_rew = 0\n dist_rew = 0\n for i in range(N):\n obs = self.reset()\n h = None\n cr = 0\n vr = 0\n dr = 0\n for j in range(self.max_steps):\n action, h = policy((to_tensor(obs, True).unsqueeze(0), h))\n obs, r, done, (r_v, r_d) = self.step(action[0].detach().numpy())\n cr += r\n vr += r_v\n dr = max(dr, r_d)\n\n time.sleep(0.000)\n if render:\n self.render()\n\n rew += cr\n vel_rew += vr\n dist_rew += dr\n\n if render:\n print(\"Total episode reward: {}\".format(cr))\n\n return rew / N, vel_rew / N, dist_rew / N\n\n\n def test_adapt(self, p1, p2, ID):\n self.env_list = [\"flatpipe\"]\n\n episode_states = []\n episode_acts = []\n ctr = 0\n while ctr < 1000:\n print(\"Iter: {}\".format(ctr))\n current_policy_name = \"p1\"\n rnd_x = - 0.1 + np.random.rand() * 0.3 + np.random.randint(0,2) * 1.2\n s = self.reset(init_pos = np.array([rnd_x, 0, 0]))\n cr = 0\n states = []\n acts = []\n\n policy = p1\n\n for j in range(self.max_steps):\n x = self.sim.get_state().qpos.tolist()[0]\n\n if 2.2 > x > 0.8 and current_policy_name == \"p1\":\n policy = p2\n current_policy_name = \"p2\"\n print(\"Policy switched to p2\")\n\n if not (2.2 > x > 0.8) and current_policy_name == \"p2\":\n policy = p1\n current_policy_name = \"p1\"\n print(\"Policy switched to p1\")\n\n states.append(s)\n action = policy(to_tensor(s, True)).detach()[0].numpy()\n acts.append(action)\n s, r, done, od, = self.step(action)\n cr += r\n\n #self.render()\n\n if cr < 50:\n continue\n ctr += 1\n\n episode_states.append(np.stack(states))\n episode_acts.append(np.stack(acts))\n\n print(\"Total episode reward: {}\".format(cr))\n\n np_states = np.stack(episode_states)\n np_acts = np.stack(episode_acts)\n\n np.save(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"data/states_{}.npy\".format(ID)), np_states)\n np.save(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"data/acts_{}.npy\".format(ID)), np_acts)\n\n\n def test_record_hidden(self, policy):\n self.reset()\n h_episodes = []\n for i in range(10):\n h_list = []\n obs = self.reset()\n h = None\n cr = 0\n for j in range(self.max_steps * 2):\n action, h = policy((to_tensor(obs, True), h))\n obs, r, done, od, = self.step(action[0].detach().numpy())\n cr += r\n time.sleep(0.001)\n self.render()\n h_list.append(h[0].detach().numpy())\n print(\"Total episode reward: {}\".format(cr))\n h_arr = np.concatenate(h_list)\n h_episodes.append(h_arr)\n\n h_episodes_arr = np.stack(h_episodes)\n\n # Save hidden states\n filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"data/{}_states.npy\".format(self.env_name))\n np.save(filename, h_episodes_arr)\n\n\n\nif __name__ == \"__main__\":\n ant = Hexapod()\n print(ant.obs_dim)\n print(ant.act_dim)\n ant.demo()\n","sub_path":"poet_distributed/niches/box2d/ant_terrain_mjc/hexapod_trossen_terrain_all.py","file_name":"hexapod_trossen_terrain_all.py","file_ext":"py","file_size_in_byte":40613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"651391596","text":"# -*- coding: utf-8 -*-\n\nimport xml.etree.cElementTree as ET\nimport sys\nimport codecs\n\nif len(sys.argv) == 7:\n\n input = sys.argv[1]\n output = sys.argv[2]\n attribute = sys.argv[3]\n ancestor = sys.argv[4]\n elem = sys.argv[5]\n attr = sys.argv[6]\nelse:\n print(\"python pyaddatt.py input output attributeToAdd ancestor element attr\")\n print(\"The value - can be used as 'don't care' value for ancestor, element and attr\")\n exit\n\ntree = ET.ElementTree(file=input)\nroot = tree.getroot()\nif ancestor == '-':\n ancestorNode = root\nelse:\n ancestorNode = root.find(ancestor)\n if ancestorNode == None:\n ancestorNode = root\n\nfor i,elm in enumerate(ancestorNode):\n if elem == '-' or elm.tag == elem:\n if attr == '-':\n elm.set(attribute,\"\")\n else:\n att = elm.get('{http://www.w3.org/XML/1998/namespace}'+attr)\n if att == None:\n att = elm.get(attr)\n if att == None:\n att = elm.get('{http://www.tei-c.org/ns/1.0}'+attr)\n if att != None:\n elm.set(attribute,\"\")\n\ntree.write(output, encoding=\"utf-8\")\n\n","sub_path":"CST-lemma/pyaddatt.py","file_name":"pyaddatt.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"188082327","text":"# coding=utf-8\n\"\"\"Code pertaining to www.fanfiction.net (except parsing their HTML).\"\"\"\n\nimport re\n\nfrom apiphany.api.views.jsonview import JsonView\nfrom apiphany.api.apis.ff.parser.ffnetparser import FanfictionNetParser\n\n\nURL_REGEX = r\".*fanfiction.net/s/.*\"\nURL_ID_REGEX = r\".*fanfiction.net/s/(\\d+)\"\n\n\nclass FanfictionNetSite(object):\n \"\"\"Object representing www.fanfiction.net.\"\"\"\n def __init__(self, story_html_request):\n self.url_regex = re.compile(URL_REGEX)\n self.url_id_regex = re.compile(URL_ID_REGEX)\n self.internet = story_html_request\n\n def can_handle_url(self, url):\n \"\"\"Does the given URL represent a story on this site?\"\"\"\n if self.url_regex.match(url):\n return True\n else:\n return False\n\n def parse_story(self, url):\n \"\"\"Download HTML fron URL and parse it.\"\"\"\n html = self._get_html_for_url(url)\n\n parser = FanfictionNetParser(html)\n parse_result = parser.parse()\n\n return JsonView(parse_result.is_successful(), parse_result.as_json())\n\n def _get_html_for_url(self, url):\n match = self.url_id_regex.match(url)\n story_id = match.group(1)\n short_url = \"https://www.fanfiction.net/s/\" + story_id\n\n html = self.internet.get_html(short_url)\n return html\n","sub_path":"apiphany/api/apis/ff/site/ffnetsite.py","file_name":"ffnetsite.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"447880487","text":"import PIL.Image as I\nimport numpy as np\nimport glob,os,sys\nimport random\ndef transform(max_,min_,im_ar):\n #print(im_ar)\n k=255/(max_-min_)\n b=255*min_/(min_-max_)\n ret=k*im_ar+b\n #print(ret)\n #exit()\n return ret.astype('uint8')\n\ndef norm(im_ar):\n #print(im_ar)\n mean=np.mean(im_ar)\n std=np.std(im_ar)\n ret=(im_ar-mean)/std\n ret=(ret-np.min(ret))*100\n ret=ret.astype('uint8')#transform(np.max(ret),np.min(ret),ret)\n #print(im_ar-ret)\n #exit()\n return ret\n\ndef add_noise(im_ar,pro,val):\n shape=im_ar.shape\n noise=np.zeros(shape)\n for i in range(shape[0]):\n for j in range(shape[1]):\n if random.random() 100000:\n raise ValueError(\"You should clear DirtyInstances table first\")\n if connection.vendor == 'postgresql':\n distinct = DirtyInstance.objects.distinct('object_id', 'content_type')\n DirtyInstance.objects.exclude(id__in=distinct).delete()\n else:\n pks_to_delete = []\n distinct_tuples = []\n for di in DirtyInstance.objects.all().iterator():\n if (di.object_id, di.content_type) in distinct_tuples:\n pks_to_delete.append(di.pk)\n else:\n distinct_tuples.append((di.object_id, di.content_type))\n DirtyInstance.objects.filter(id__in=pks_to_delete).delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('denorm', '0002_auto_20160525_2242'),\n ]\n\n operations = [\n migrations.RunPython(drop_duplicates, reverse_code=migrations.RunPython.noop),\n migrations.AlterUniqueTogether(\n name='dirtyinstance',\n unique_together=set([('content_type', 'object_id')]),\n ),\n ]\n","sub_path":"denorm/migrations/0003_auto_20160526_1335.py","file_name":"0003_auto_20160526_1335.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"388333560","text":"\n\nimport random\n\n\ndef eulerian_path(graph):\n path = []\n stack = []\n indegree = sum(list(graph.values()), [])\n outdegree = list(graph.keys())\n start = [x for x in outdegree if (x not in indegree) or len(graph[x]) > indegree.count(x)]\n\n if not start:\n location = random.choice(outdegree)\n elif len(start) == 1:\n location = start[0]\n else:\n location = random.choice(start)\n start = location\n\n while graph or stack:\n try:\n if len(graph[location]) == 1:\n stack.append(location)\n location = graph[location][0]\n del graph[stack[-1]]\n elif len(graph[location]) > 1:\n stack.append(location)\n location = random.choice(graph[location])\n graph[stack[-1]].remove(location)\n except Exception as e:\n path.append(location)\n location = stack[-1]\n stack.pop()\n if not stack and not graph:\n path.append(location)\n\n if path[0] != start:\n path = path[::-1]\n\n return path\n","sub_path":"genome_sequencing/assemble_genomes/eulerian_path.py","file_name":"eulerian_path.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"542981891","text":"from django.test import TestCase\n\nfrom binder import models, helpers\n\nclass HelperTests(TestCase):\n def test_ipinfo_ResolutionFail(self):\n response = helpers.ip_info(\"foobar.doesnotexist.local\")\n self.assertEqual([['Error', u'Unable to resolve foobar.doesnotexist.local: [Errno -2] Name or service not known']],\n response)\n response = helpers.ip_info(\"localhost\")\n self.assertEqual([['IPv4 (1)', u'127.0.0.1']],\n sorted(response))\n","sub_path":"binder/tests/testHelpers.py","file_name":"testHelpers.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"383915681","text":"class KNN_Classifier:\n\n def __init__(self):\n pass\n\n\n\n def inRange(self, p1, p2, range):\n # Returns whether the points are in range defined by epsilon\n x, y, z, phase2 = p2\n x_, y_, z_ = p1\n return (x_ - range < x < x_ + range) and (y_ - range < y < y_ + range) and (z_ - range < z < z_ + range)\n\n\n\n def dist(self, p1, p2):\n # Returns euclidean distance between two points.\n d = (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2\n if d == 0:\n return 0.000001\n return d\n\n\n\n def resolveTie(self, p, k_nearest, phases):\n \"\"\"\n In the case of a tie in the k nearest neighbours, base judgement on distance.\n Create a function of weights given distance. Sum(1/d)\n :param p: point trying to classify\n :param k_nearest: all k nearest points found\n :return: a phase based on the distance weights\n \"\"\"\n\n # phase_dist := list of tuples (phase, summed 1 / d of each point)\n phase_dist = [(phase, sum([1 / self.dist(p, p_) for p_ in k_nearest if p_[3] == phase])) for phase in phases]\n return sorted(phase_dist, key=lambda x:x[1])[::-1][0][0]\n\n\n\n def classify(self, x, y, z, train_data, k):\n \"\"\"\n Will classify a point based on given training observations\n :param x, y, z: The point to predict its phase\n :param train_data: a list of tuples in form: (x, y, z, PHASE)\n :param k: the number of nearest points to use in the prediction\n :return: the phase in which the KNN algorithm predicts\n \"\"\"\n\n # We are not approaching the exhaustive method of going through every point and computing distance.\n\n # Alternative faster approach:\n # 1, Iteratively define a range around given point.\n # 2, Get the number of points in range.\n # if number of points equals k, we are done.\n # 3, change range based on the difference of k\n # 4, Go to 2 (is a binary search for size of range)\n\n # First find the nearest k points\n\n # Initialize range parameter\n range = 0.2\n min_range, max_range = (0.01, 0.95)\n\n neighbours_found = 0\n converged = False\n nearest = []\n last_range = 0\n phases = list(self.getAllPhases(train_data))\n\n while not converged:\n nearest = [p for p in train_data if self.inRange((x, y, z), p, range)]\n\n neighbours_found = len(nearest)\n\n # Allow it to converge if the change in range from last iteration is negligible\n if neighbours_found == k or abs(range - last_range) < 0.008:\n converged = True\n\n last_range = range\n\n if neighbours_found < k:\n # We need to expand range\n min_range = range\n range += (max_range - range) / 2\n elif neighbours_found > k:\n # We need to shorten range\n max_range = range\n range -= (range - min_range) / 2\n\n\n # Then classify based on the phases of k points\n # List of tuples := (phase , number of k nearest neighbours in the phase (int))\n phase_list = [(phase , sum([1 for p in nearest if phase == p[3]])) for phase in phases]\n sorted_phases = sorted(phase_list, key=lambda x:x[1])[::-1]\n\n if sorted_phases[0][1] == sorted_phases[1][1]:\n return self.resolveTie((x, y, z), nearest, phases)\n return sorted_phases[0][0]\n\n\n\n def KNN(self, k, train_data, delta):\n \"\"\"\n Run the classifier on given data and generate entire ternary diagram\n\n :param k: the choice of the number of nearest neighbours to look at\n :param train_data:\n :param phases: tuple containing all phases with arbitrary data type\n :param delta: float increment of point for each dimension. Smaller delta implies denser diagram (more points)\n :param delta: [0.01, 1)\n :return: list of tuples: [(x, y, z, PHASE), ()...] for every single point within its density\n \"\"\"\n\n # The master list holding all points and their phases\n ternary = []\n ternary += train_data\n # Points in train WITHOUT phase label\n p_train = [(i[0], i[1], i[2]) for i in train_data]\n\n for x in range(0, 100, int(delta*100)):\n for y in range(0, 100 - x, int(delta*100)):\n x_ = x /100\n y_ = y /100\n z_ = (100 - x - y) / 100\n\n if (x_, y_, z_) not in p_train:\n ternary.append((x_, y_, z_, self.classify(x_, y_, z_, train_data, k)))\n\n return ternary\n\n def getAllPhases(self, train_data):\n \"\"\"\n\n :param train_data: the list of tuples as given\n :return: set of all phases within the data\n \"\"\"\n return set([x[-1] for x in train_data])\n","sub_path":"PD_P1_KNN/KNN_Classifier.py","file_name":"KNN_Classifier.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"639969406","text":"import numpy as np\nimport open3d\nimport copy\n\nfrom sklearn.neighbors import KDTree\nfrom track_point import load_p2p_matching_series, track_one_point\n\n\ndef downsample_pcd(pcd, down_sample_rate=0.003):\n # voxel_size = np.mean(pcd.compute_nearest_neighbor_distance())\n return np.asarray(pcd.points)[::int(1/down_sample_rate)]\n\n\ndef get_sample_points_track(xyz, pcd_collector, mapping_collector):\n \"\"\"\n\n :param xyz: numpy array of shape N*3, the xyz coordinates of the points\n :return: the track of the input points in the time series\n \"\"\"\n\n track_collection = []\n for xyz_ in xyz:\n track = track_one_point(xyz_, pcd_collector, mapping_collector)\n complete = True\n for t in track:\n if t.shape[0] == 0:\n complete = False\n if complete:\n track_collection.append(track)\n return track_collection\n\n\ndef predict_position_from_track(track, dt=1):\n v = track[0] - track[1]\n a = (track[0] + track[2] - 2 * track[1]) * 2\n return track[0] + dt * v\n\n\ndef extrapolate(pcd, track_collection, predict_position_collection):\n current_position = np.vstack([t[0] for t in track_collection])\n next_position = np.vstack(predict_position_collection)\n\n translation = next_position - current_position\n\n xyz = np.asarray(pcd.points)\n tree = KDTree(current_position)\n\n distance, indices = tree.query(xyz, return_distance=True, k=3)\n\n xyz_extrapolated = copy.deepcopy(xyz)\n for i, xyz_ in enumerate(xyz_extrapolated):\n weights = 1 / (0.002 + distance[i])\n weights = weights / np.sum(weights)\n d_xyz = (weights * translation[indices[i]].T).sum(axis=1)\n xyz_ += d_xyz\n pcd_extrapolate = open3d.geometry.PointCloud()\n pcd_extrapolate.points = open3d.utility.Vector3dVector(xyz_extrapolated)\n return pcd_extrapolate\n\n\nif __name__ == \"__main__\":\n dataset = \"lyon2\"\n match_path_format = \"../data/{}/registration_result/{}_to_{}/\"\n days = [\"03-21_PM\", \"03-22_AM\", \"03-22_PM\"]\n\n pcd_collector, mapping_collector = load_p2p_matching_series(days, dataset, match_path_format)\n last_pcd = pcd_collector[days[-1]]\n xyz_sampled = downsample_pcd(\n last_pcd, down_sample_rate=0.02\n )\n track_collection = get_sample_points_track(xyz_sampled, pcd_collector, mapping_collector)\n\n pos_predict = []\n for track in track_collection:\n pos_predict.append(predict_position_from_track(track))\n pcd_extrapolate = extrapolate(last_pcd, track_collection, predict_position_collection=pos_predict)\n\n last_pcd = last_pcd.translate([0, 200, 0])\n last_2_pcd = pcd_collector[days[-2]].translate([0, 400, 0])\n open3d.visualization.draw_geometries([pcd_extrapolate, last_pcd, last_2_pcd])\n # xyz_ori = xyz_sampled\n # xyz_predict = np.vstack(pos_predict)\n # pcd_predict = open3d.geometry.PointCloud()\n #\n # pcd_predict.points = open3d.utility.Vector3dVector(xyz_ori)\n # open3d.visualization.draw_geometries([pcd_predict])\n #\n # pcd_predict.points = open3d.utility.Vector3dVector(xyz_predict)\n # open3d.visualization.draw_geometries([pcd_predict])\n print(\"\")\n","sub_path":"extrapolation/extrapolation_pcd.py","file_name":"extrapolation_pcd.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"525106479","text":"#!usr/bin/env python\n# -*- encoding:utf-8 -*-\nimport os\nimport random\nfrom flask import render_template,request,current_app,make_response,url_for\nfrom flask_login import login_required\nfrom flask_login import current_user\nimport datetime\nfrom ..models import Article,ArticleType,Source,Menu\nfrom . import main\nfrom .. import db\n\n@main.route('/')\n@main.route('/index')\n# @cache.cached(timeout=60)\ndef index():\n # menus = Menu.query.all()\n # articleTypes = ArticleType.query.all()\n # articleTypeId = ArticleType.query.first().id\n return render_template('index.html',Menu=Menu,ArticleType=ArticleType,endpoint='.index')\n\n@main.route('/article-types//')\ndef articleTypes(id):\n page = request.args.get('page',1,type=int)\n menus = Menu.query.all()\n pagination = ArticleType.query.get_or_404(id).articles.order_by(Article.create_time.desc()).paginate(\n page,10,error_out=False\n )\n articles = pagination.items\n return render_template('articleLists.html',articles=articles,\n pagination=pagination,\n menus=menus,\n endpoint='.articleTypes',id=id)\n\n@main.route('/article-details/',methods=['GET','POST'])\n# @cache.cached(timeout=60)\ndef articleDetails(id):\n article = Article.query.get_or_404(id)\n # article.add_view(article,db)\n return render_template('article_details.html',article=article,id=article.id,endpoint='.articleDetails')\n return 'test'\n\n@main.route('/article-sources/')\ndef articleSources(id):\n page = request.args.get('page',1,type=int)\n pagination = Source.query.get_or_404(id).articles.order_by(\n Article.create_time.desc()).paginate(page,10,error_out=False)\n articles = pagination.items\n return render_template(\n 'articleLists.html',\n articles=articles,\n pagination=pagination,\n endpoint='.articleSources',\n id=id)\n\n\ndef gen_rnd_filename():\n filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))\n\n\n@main.route('/ckupload/', methods=['POST', 'OPTIONS'])\n@login_required\ndef ckupload():\n print(current_app.static_folder)\n \"\"\"CKEditor file upload\"\"\"\n error = ''\n url = ''\n callback = request.args.get(\"CKEditorFuncNum\")\n if request.method == 'POST' and 'upload' in request.files:\n fileobj = request.files['upload']\n fname, fext = os.path.splitext(fileobj.filename)\n rnd_name = '%s%s' % (gen_rnd_filename(), fext)\n filepath = os.path.join(current_app.static_folder, 'upload', rnd_name)\n # 检查路径是否存在,不存在则创建\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except:\n error = 'ERROR_CREATE_DIR'\n elif not os.access(dirname, os.W_OK):\n error = 'ERROR_DIR_NOT_WRITEABLE'\n if not error:\n fileobj.save(filepath)\n url = url_for('static', filename='%s/%s' % ('upload', rnd_name))\n else:\n error = 'post error'\n res = \"\"\"\"\"\" % (callback, url, error)\n response = make_response(res)\n response.headers[\"Content-Type\"] = \"text/html\"\n return response","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"127609817","text":"import os\n\ndef comprarPasaje():\n os.system('cls')\n print(\"*****************\")\n print(\"Proceso de compra\")\n print(\"*****************\")\n cantPasajes = int(input(\"\\nCuantos pasajes desea comprar: \"))\n if cantPasajes <= 0 or cantPasajes > 33:\n print(\"\\nCantidad de pasajes incorrecta, porfavor ingrese una cantidad entre 1 a 33.\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system('cls')\n else:\n os.system('cls')\n for i in range(cantPasajes):\n global rutPasajero\n rutPasajero=0\n print(f\"Ingrese rut pasajero {i+1} (ej:12345678)\")\n global listaRut\n listaRut = []\n while rutPasajero<11111110:\n rutPasajero=int(input(\"RUT: \"))\n listaRut.append(rutPasajero)\n print(\"\\nIngrese fila y asiento del pasajero.\")\n print(f\"Fila A {filaA}\")\n print(f\"Fila B {filaB}\")\n print(f\"Fila C {filaC}\")\n print(f\"\\nFila D {filaD}\")\n print(f\"Fila E {filaE}\")\n print(f\"Fila F {filaF}\")\n asignarAsiento()\n return listaRut\n\ndef listaPasajeros():\n os.system('cls')\n print(\"\\n********************\")\n print(\"Lista pasajeros (rut)\")\n print(\"********************\")\n for i in range(len(listaRut)):\n print(f\"\\n{listaRut[i]}\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system(\"cls\")\n \ndef mostrarAsientos():\n os.system(\"cls\")\n print(\"\\nLos asientos acupados se le asigno una X\")\n print(f\"\\nFila A {filaA}\")\n print(f\"Fila B {filaB}\")\n print(f\"Fila C {filaC}\")\n print(f\"\\nFila D {filaD}\")\n print(f\"Fila E {filaE}\")\n print(f\"Fila F {filaF}\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system(\"cls\")\n \n\ndef buscarPasajero():\n os.system('cls')\n print(\"********************\")\n print(\"BUSQUEDA DE PASAJERO\")\n print(\"********************\")\n buscarRut=int(input(\"\\nIngrese el RUT del pasajero que desea buscas, sin guion ni puntos: \"))\n buscarRut in rutF\n if buscarRut in rutF:\n asientoPasajero=rutF.index(busca_rut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila F\")\n else:\n if buscarRut in rutE:\n asientoPasajero=rutE.index(buscarRut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila E\")\n else:\n if buscarRut in rutD:\n asientoPasajero=rutD.index(buscarRut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila D\")\n else:\n if buscarRut in rutC:\n asientoPasajero=rutC.index(buscarRut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila C\")\n else:\n if buscarRut in rutB:\n asientoPasajero=rutB.index(buscarRut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila B\")\n else:\n if buscarRut in rutA:\n asientoPasajero=rutA.index(buscarRut)\n print(F\"El pasajero {buscarRut} está ubicado en asiento {asientoPasajero+1} / fila A\")\n else:\n print(\"\\n*****************************************************************\")\n print(f\"El pasajero {buscarRut} no se encuestra registrado en el sistema.\")\n print(\"*****************************************************************\")\n c = input(\"\\nPresione ENTER para continuar\")\n os.system(\"cls\")\n \ndef asignarAsiento():\n print(\"\\nPrecio asientos:\")\n print(\"\\nAsiento común\\t\\t\\t(C), $60.000 pesos\")\n print(\"Espacio adicional para piernas (E), $80.000 pesos\")\n print(\"No reclina\\t\\t\\t(N), $50.000 pesos\")\n filaPasajero=\"X\"\n global contadorAsientoEspacio\n global contadorAsientoComun\n global contadorAsientoNoReclina\n while filaPasajero not in (\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"):\n filaPasajero = input(\"\\nIngrese Fila [A-B-C-D-E-F]: \").upper()\n asientoPasajero = int(input(\"Ingrese Asiento: \"))\n if asientoPasajero in (1,2,3,4,5,18): \n contadorAsientoEspacio += 1\n if asientoPasajero in (6,7,8,9,11,12,13,14,15,16,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33):\n contadorAsientoComun += 1\n if asientoPasajero in (10,17):\n contadorAsientoNoReclina += 1\n if filaPasajero==\"F\":\n del filaF[asientoPasajero-1] \n del rutF[asientoPasajero-1]\n filaF.insert((asientoPasajero-1),\"X\")\n rutF.insert((asientoPasajero-1),rutPasajero)\n if filaPasajero==\"E\":\n del filaE[asientoPasajero-1]\n del rutE[asientoPasajero-1]\n filaE.insert((asientoPasajero-1),\"X\")\n rutE.insert((asientoPasajero-1),rutPasajero)\n if filaPasajero==\"D\":\n del filaD[asientoPasajero-1]\n del rutD[asientoPasajero-1]\n filaD.insert((asientoPasajero-1),\"X\")\n rutD.insert((asientoPasajero-1),rutPasajero)\n if filaPasajero==\"C\":\n del filaC[asientoPasajero-1]\n del rutC[asientoPasajero-1]\n filaC.insert((asientoPasajero-1),\"X\")\n rutC.insert((asientoPasajero-1),rutPasajero)\n if filaPasajero==\"B\":\n del filaB[asientoPasajero-1]\n del rutB[asientoPasajero-1]\n filaB.insert((asientoPasajero-1),\"X\")\n rutB.insert((asientoPasajero-1),rutPasajero)\n if filaPasajero==\"A\":\n del filaA[asientoPasajero-1]\n del rutA[asientoPasajero-1]\n filaA.insert((asientoPasajero-1),\"X\")\n rutA.insert((asientoPasajero-1),rutPasajero)\n asientoPasajero=0\n print(\"\\nOperación relizada correctamente.\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system('cls')\n \ndef reasignarAsiento():\n os.system('cls')\n rutPasajero = 0\n print(\"************************\")\n print(\"REASIGNACION DE ASIENTOS\")\n print(\"************************\")\n rutPasajero = int(input(\"Indique el RUT del pasajero que desea reasignar, sin guion ni puntos: \"))\n if rutPasajero in rutF:\n asiento=rutF.index(rutPasajero)\n rutF.remove(rutPasajero)\n del filaF[(asiento)]\n filaF.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta == \"s\":\n asignarAsiento()\n else:\n if rutPasajero in rutE:\n asiento=rutE.index(rutPasajero)\n rutE.remove(rutPasajero)\n del filaE[(asiento)]\n filaE.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta == \"s\":\n asignarAsiento()\n else:\n if rutPasajero in rutD:\n asiento=rutD.index(rutPasajero)\n rutD.remove(rutPasajero)\n del filaD[(asiento)]\n filaD.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta == \"s\":\n asignarAsiento()\n else:\n if rutPasajero in rutC:\n asiento=rutC.index(rutPasajero)\n rutC.remove(rutPasajero)\n del filaC[(asiento)]\n filaC.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta== \"s\":\n asignarAsiento()\n else:\n if rutPasajero in rutB:\n asiento=rutB.index(rutPasajero)\n rutB.remove(rutPasajero)\n del filaB[(asiento)]\n filaB.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta == \"s\":\n asignarAsiento()\n else:\n if rutPasajero in rutA:\n asiento=rutA.index(rutPasajero)\n rutA.remove(rutPasajero)\n del filaA[(asiento)]\n filaA.insert(asiento,str(asiento+1))\n pregunta = input(f\"El pasajero RUT {rutPasajero} ha sido eliminado. Desea reasignarlo? [s|n]: \")\n if pregunta == \"s\":\n asignarAsiento()\n\ndef gananciasTotales():\n os.system('cls')\n totalAsientosDinero = (contadorAsientoComun*60000)+(contadorAsientoNoReclina*50000)+(contadorAsientoEspacio*80000)\n totalAsientos = contadorAsientoComun + contadorAsientoNoReclina + contadorAsientoEspacio\n print(\"*****************\")\n print(\"Ganancias totales\")\n print(\"*****************\")\n print(\"\\nTipo de asiento\\t\\t\\tCantidad\\tTotal\")\n print(f\"Asiento común\\t $60.000\\t{contadorAsientoComun}\\t\\t{contadorAsientoComun*60000}\")\n print(f\"Espacio para piernas $80.000\\t{contadorAsientoEspacio}\\t\\t{contadorAsientoEspacio*80000}\")\n print(f\"No reclina\\t $50.000\\t{contadorAsientoNoReclina}\\t\\t{contadorAsientoNoReclina*50000}\")\n print(f\"TOTAL\\t\\t\\t\\t{totalAsientos}\\t\\t{totalAsientosDinero}\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system('cls')\n\ndef mostrarUbicacionesDisponible():\n os.system('cls')\n print(\"\\n************************\")\n print(\"Ubicaciones disponibles\")\n print(\"************************\")\n print(\"\\nAsintos disponibles asignados con una D.\")\n print(\"Asientos reservados asignador con el RUT del pasajero.\")\n print(f\"\\nFila A {rutA}\")\n print(f\"Fila B {rutB}\")\n print(f\"Fila C {rutC}\")\n print(f\"\\nFila D {rutD}\")\n print(f\"Fila E {rutE}\")\n print(f\"Fila F {rutF}\")\n c = input(\"\\nPresione ENTER para continuar.\")\n os.system('cls')\n \ndef menu():\n os.system('cls')\n salir = 7\n print(\"*****************************\")\n print(\"SISTEMA DE RESERVA DE PASAJES\")\n print(\" Linea aérea Flash\")\n print(\"*****************************\")\n while salir == 7:\n listaMenu = [\"Compra Pasajes\",\"Mostrar Ubicaciones Disponibles\", \"Ver Listado de Pasajeros\", \"Buscar Pasajero\", \"Reasignar Asiento\",\"Mostrar Ganancias Totales\",\"Salir\"]\n for i in listaMenu:\n index = listaMenu.index(i)\n print(f\"{index+1}: {i}\")\n opcion = int(input(\"Seleccione una opcion: \"))\n if opcion == 1:\n comprarPasaje()\n elif opcion == 2:\n mostrarUbicacionesDisponible()\n elif opcion == 3:\n listaPasajeros()\n elif opcion == 4:\n buscarPasajero()\n elif opcion == 5:\n reasignarAsiento()\n elif opcion == 6:\n gananciasTotales()\n elif opcion == 7:\n break\n else:\n print(\"Opcion ingresada no valida, intentelo nuevamente.\")\n \ncontadorAsientoEspacio = 0\ncontadorAsientoComun = 0\ncontadorAsientoNoReclina = 0\n \nfilaF=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\nfilaE=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\nfilaD=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\nfilaC=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\nfilaB=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\nfilaA=[\"E1\", \"E2\", \"E3\", \"E4\", \"E5\", \"C6\", \"C7\", \"C8\", \"C9\", \"N10\", \"C11\", \"C12\", \"C13\", \"C14\", \"C15\", \"C16\", \"N17\", \"E18\", \"C19\", \"C20\", \"C21\", \"C22\", \"C23\", \"C24\", \"C25\", \"C26\", \"C27\", \"C28\", \"C29\", \"C30\", \"C31\", \"C32\", \"C33\"]\n\n\nrutF=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\nrutE=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\nrutD=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\nrutC=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\nrutB=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\nrutA=[\"1D\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"11D\", \"12D\", \"13D\", \"14D\", \"15D\", \"16D\", \"17D\", \"18D\", \"19D\", \"20D\", \"21D\", \"22D\", \"23D\", \"24D\", \"25D\", \"26D\", \"27D\", \"28D\", \"29D\", \"30D\", \"31D\", \"32D\", \"33D\"]\n\nmenu()\n","sub_path":"Programa Aerolinea.py","file_name":"Programa Aerolinea.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"101338551","text":"import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import *\nimport numpy as np\n\nclass Atom():\n def __init__(self, th=None, t=None):\n self.th = th\n self.t = t\n\ndef readData(file):\n f = open(file, 'r')\n res, lines = [], [ line[:-1] for line in f ] # store lines in this list without newline\n for line in lines:\n num = line.split(':')[1]\n if 'THREADS' in line:\n atom = Atom()\n atom.th = int(num)\n elif 'TIME' in line:\n atom.t = float(num)\n elif 'SUM' in line:\n res.append(atom)\n return res\n\ndef getdata(file):\n data = readData(file)\n x, y = [None for i in range(100)], [None for j in range(100)]\n for i in range(0, 100*10, 10):\n s, th = 0, data[i].th\n for j in range(10):\n s += data[i+j].t\n x[i//10] = th\n y[i//10] = s / 10\n return x, y\n\nd1 = getdata('s_c_1_10000.out')\nd2 = getdata('s_c_256_10000.out')\nd3 = getdata('s_c_512_10000.out')\nd4 = getdata('s_c_1024_10000.out')\nd5 = getdata('s_c_1_100000.out')\nd6 = getdata('s_c_256_100000.out')\nd7 = getdata('s_c_512_100000.out')\nd8 = getdata('s_c_1024_100000.out')\nd9 = getdata('s_c_1_1000000.out')\nd10 = getdata('s_c_256_1000000.out')\nd11 = getdata('s_c_512_1000000.out')\nd12 = getdata('s_c_1024_1000000.out')\n\np1, = plt.plot(d1[0], d1[1], 'g:')\np2, = plt.plot(d2[0], d2[1], 'g-.')\np3, = plt.plot(d3[0], d3[1], 'g--')\np4, = plt.plot(d4[0], d4[1], 'g')\np5, = plt.plot(d5[0], d5[1], 'b:')\np6, = plt.plot(d6[0], d6[1], 'b-.')\np7, = plt.plot(d7[0], d7[1], 'b--')\np8, = plt.plot(d8[0], d8[1], 'b')\np9, = plt.plot(d9[0], d9[1], 'r:')\np10, = plt.plot(d10[0], d10[1], 'r-.')\np11, = plt.plot(d11[0], d11[1], 'r--')\np12, = plt.plot(d12[0], d12[1], 'r')\n\nP = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12]\nL = [\"scount_1_10000\", \"scount_256_10000\", \"scount_512_10000\", \"scount_1024_10000\",\n \"scount_1_100000\", \"scount_256_100000\", \"scount_512_100000\", \"scount_1024_100000\",\n \"scount_1_1000000\", \"scount_256_1000000\", \"scount_512_1000000\", \"scount_1024_1000000\"]\nlegend(P, L)\n\n\nplt.xlabel('Number of Threads')\nplt.ylabel('Average Execution Time of 10 runs (second)')\n\nplt.xticks(np.arange(0, 101, 5.0), fontsize=8)\nplt.yticks(np.arange(0, 5.2, 0.2), fontsize=8)\n\nplt.title('Performance of the Correct Sloppy Counter')\nplt.show()\n\n\n","sub_path":"sc/plotsc.py","file_name":"plotsc.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"27355876","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom django.test import TestCase\r\nfrom models import *\r\nfrom django.http import HttpRequest\r\nfrom views import *\r\nfrom django.test import Client\r\nimport pdb\r\n\r\nclass GameKipTestCase(TestCase):\r\n\r\n\tusers = [\r\n\t\t{ 'u' : 'test1' , 'e' : 'test1@gmail.com' , 'p' : 'test1pass' },\r\n\t\t{ 'u' : 'test2' , 'e' : 'test2@gmail.com' , 'p' : 'test2pass' },\r\n\t]\r\n\r\n\tdef setUp(self):\r\n\r\n\t\tself.group = Group.objects.create(name = 'gamekip' )\r\n\t\tself.imp_group = Group.objects.create(name = 'impostor' )\r\n\r\n\t\t# Creo usuarios de gamekip\r\n\t\tfor u in self.users:\r\n\t\t\tnew_u = User.objects.create_user( u['u'] , u['e'] , u['p'] )\r\n\t\t\tself.group.user_set.add( new_u )\r\n\r\n\t\t# Creo usuario impostor\r\n\t\tself.impostor = User.objects.create_user( 'impostor', 'imp@gmail.com' , 'impostor00' )\r\n\t\tself.imp_group.user_set.add( self.impostor )\r\n\r\n\t\t# Hago login del primer usuario\r\n\t\tself.c = Client()\r\n\t\tself.c.post('/login/', {'email': self.users[0]['e'], 'password': self.users[0]['p']})\r\n\r\n\t\tself.test_user = User.objects.all()[0]\r\n\r\n\t\t# Creando metas\r\n\t\tself.goal = Goal( title = \"Meta 1\" , created_by = self.test_user, completed = False , active_goal = True , assigned_group = self.group )\r\n\t\tself.goal.save()\r\n\t\tself.imp_goal = Goal( title = \"Meta 1 impostor\" , created_by = self.impostor, completed = False , active_goal = True , assigned_group = self.imp_group )\r\n\t\tself.imp_goal.save()\r\n\t\r\n\t# Pruebas de tareas\r\n\r\n\tdef test_create_task(self):\r\n\t\t''' Tareas se crean de forma correcta '''\r\n\r\n\t\t# Creo una tarea\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\r\n\tdef test_create_task_invalid( self ):\r\n\t\t''' Tareas no se crean si la informacion es invalida '''\r\n\r\n\t\t# Creo una tarea sin titulo\r\n\t\tresponse = self.c.post('/create_new_task', { 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\t\t# Creo una tarea sin asignarla\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\t\t# Creo una tarea con titulo pequeno\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'peque' , 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'Título muy corto' )\r\n\r\n\t\t# Creo una tarea con usuario invalido\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'titulo largo' , 'assigned_to' : 10 , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'Usuario inválido' )\r\n\r\n\t\t# Creo una tarea con usuario de otro grupo\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'titulo largo' , 'assigned_to' : self.impostor.id , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\tdef test_create_repeated_task( self ):\r\n\r\n\t\tassigned_to = self.test_user.id\r\n\r\n\t\t# Creo una tarea\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\r\n\t\t# Intento crear la misma tarea\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_to' : assigned_to , 'assigned_goal' : self.goal.id } )\r\n\t\tself.assertEqual( response.content , 'Ya %s tiene asignada esa tarea' % ( User.objects.get( id = assigned_to ).username ) )\r\n\r\n\tdef test_set_task_done( self ):\r\n\r\n\t\t# Creo tarea\r\n\t\tresponse = self.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\t\ttask = Task.objects.all()[0]\r\n\r\n\t\twas_completed = task.completed\r\n\r\n\t\t# Marco como completada\r\n\t\tresponse = self.c.post('/set_task_done', { 'task_id' : task.id } )\r\n\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\t\tself.assertEqual( Task.objects.get( id = task.id ).completed , not was_completed )\r\n\r\n\tdef test_set_invalid_task_done( self ):\r\n\r\n\t\tresponse = self.c.post('/set_task_done', { 'task_id' : 10 } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\tdef test_delete_task( self ):\r\n\r\n\t\tself.c.post('/create_new_task', { 'title' : 'Desarrollar modulo de usuarios' , 'assigned_to' : self.test_user.id , 'assigned_goal' : self.goal.id } )\r\n\r\n\t\tnum_tasks = Task.objects.all().count()\r\n\t\ttask = Task.objects.all()[0]\r\n\r\n\t\tresponse = self.c.post('/delete_task', { 'task_id' : task.id } )\r\n\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\t\tself.assertEqual( Task.objects.all().count() , num_tasks-1 )\r\n\r\n\tdef test_delete_invalid_task( self ):\r\n\r\n\t\t# Tarea no creada\r\n\t\tresponse = self.c.post('/delete_task', { 'task_id' : 10 } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\t\t# Tarea de otro grupo\r\n\t\tt = Task( assigned_to = self.impostor , created_by = self.impostor , title = \"titulo de la tarea\" , completed = False )\r\n\t\tt.save()\r\n\r\n\t\tresponse = self.c.post('/delete_task', { 'task_id' : t.id } )\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\t# Pruebas de metas\r\n\r\n\tdef test_create_goal( self ):\r\n\r\n\t\t#Creamos Meta\r\n\t\tresponse = self.c.post('/create_goal',{'title': 'proyecto fase 1','assigned_group':self.group.id})\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\r\n\tdef test_create_invalid_goal( self ):\r\n\r\n\t\t#Creamos Meta sin grupo\r\n\t\tresponse = self.c.post('/create_goal',{'title': 'proyecto fase 1'})\r\n\t\tself.assertEqual( response.content , 'error' )\r\n\r\n\t\t#Creamos Meta titulo corto\r\n\t\tresponse = self.c.post('/create_goal',{'title': 'pro1','assigned_group':self.group})\r\n\t\tself.assertEqual( response.content , 'Título muy corto' )\r\n\r\n\tdef test_edit_goal(self):\r\n\r\n\t\tresponse = self.c.post('/create_goal',{'title': 'proyecto fase 1' , 'assigned_group' : self.group.id })\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\r\n\t\tg = Goal.objects.filter( title = 'proyecto fase 1' )[0]\r\n\t\ttitle = g.title\r\n\r\n\t\tresponse = self.c.post('/edit_goal',{'title': 'proyecto fase 1 A','goal':g.id })\r\n\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\t\tself.assertEqual( Goal.objects.get( id = g.id ).title , 'proyecto fase 1 A' )\r\n\r\n\tdef test_edit_invalid_goal(self):\r\n\r\n\t\tresponse = self.c.post('/create_goal',{'title': 'proyecto fase 1' , 'assigned_group' : self.group.id } )\r\n\t\tself.assertEqual( response.content , 'ok' )\r\n\r\n\t\tg = Goal.objects.filter( title = 'proyecto fase 1' )[0]\r\n\t\ttitle = g.title\r\n\t\t \r\n\t\tresponse = self.c.post('/edit_goal',{'title': 'pro' , 'goal':g.id } )\r\n\r\n\t\tself.assertEqual( response.content , 'Título muy corto' )","sub_path":"gamekip/test_gamekip.py","file_name":"test_gamekip.py","file_ext":"py","file_size_in_byte":6683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"490292688","text":"import pygame\r\nimport ntpath\r\n\"\"\"\r\nEach button is a class.\r\nThe button will be in circular in shape.\r\nEquation of circle is then given by x^2+y^2 = r^2\r\n\"\"\"\r\nblack = (255,255,255)\r\nclass Circle:\r\n def __init__(self,screen,x,y,radius,width = 3,color = (255,255,255)): #If width = 0 circle fills\r\n self.screen = screen\r\n self.x = x\r\n self.y = y\r\n self.radius = radius\r\n self.width = width\r\n self.color = color\r\n\r\n def draw(self):\r\n pygame.draw.circle(self.screen,self.color,(self.x,self.y),self.radius,self.width)\r\n\r\n def click(self):\r\n \"\"\"\r\n In general, point x and y must satisfy (x - center_x)^2 + (y - center_y)^2 <= radius^2\r\n \"\"\"\r\n current_mouse_position = pygame.mouse.get_pos()\r\n value_of_equation_at_current_mouse_position = (current_mouse_position[0]-self.x)**2+(current_mouse_position[1]-self.y)**2\r\n if (value_of_equation_at_current_mouse_position <= self.radius**2):\r\n if pygame.mouse.get_pressed()[0]:\r\n return True\r\n else:\r\n return False\r\n\r\nclass Play(Circle):\r\n def draw(self):\r\n pygame.draw.lines(self.screen,black,True, [(self.x+10,self.y),(self.x-10,self.y-10),(self.x-10,self.y+10)],2)\r\n\r\nclass Pause(Circle):\r\n def draw(self):\r\n pygame.draw.lines(self.screen,black,True, [(self.x-10,self.y-10),(self.x-10,self.y+10)],2)\r\n pygame.draw.lines(self.screen,black,True, [(self.x+10,self.y-10),(self.x+10,self.y+10)],2)\r\n\r\nclass Next(Circle):\r\n def draw(self):\r\n pygame.draw.lines(self.screen,black,False,[(self.x,self.y),(self.x-10,self.y-10)],3)\r\n pygame.draw.lines(self.screen,black,False,[(self.x,self.y),(self.x-10,self.y+10)],3)\r\n\r\nclass Previous(Circle):\r\n def draw(self):\r\n pygame.draw.lines(self.screen,black,False,[(self.x,self.y-10),(self.x-10,self.y)],3)\r\n pygame.draw.lines(self.screen,black,False,[(self.x-10,self.y),(self.x,self.y+10)],3)\r\n \r\n\r\nclass Add(Circle):\r\n def draw(self):\r\n pygame.draw.lines(self.screen,black,False,[(self.x,self.y-10),(self.x,self.y+10)],3)\r\n pygame.draw.lines(self.screen,black,False,[(self.x-10,self.y),(self.x+10,self.y)],3)\r\n \r\n\r\nclass Bar:\r\n def __init__(self,screen,width,height):\r\n self.screen = screen\r\n self.width = width\r\n self.height = height\r\n self.white_border = (255,255,255)\r\n #self.width_of_the_playBar = self.width-150\r\n\r\n def draw(self):\r\n x = 50 #Start the bar from 50px \r\n y = self.height - 150 #Based on the other buttons in main.py.\r\n\r\n pygame.draw.rect(self.screen,self.white_border,(x,y,self.width-100,5),2)\r\n\r\nclass BarPlayed(Bar):\r\n def draw(self,dx):\r\n x = 50 #Start the bar from 50px \r\n y = self.height - 150 #Based on the other buttons in main.py.\r\n pygame.draw.rect(self.screen,(255,255,255),(x,y,dx,5),0)\r\n \r\n\r\n \r\n ","sub_path":"buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"254586854","text":"#!/usr/bin/env python3\n\nimport scapy.all as scapy\nimport argparse\n\ndef get_arguments():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-t\", \"--target\", dest=\"target\", help=\"Target IP address/range\")\n\toptions = parser.parse_args()\n\tif not options.target:\n\t\tparser.error(\"[-] Please specify target IP/range, use -h or --help for more info.\")\n\treturn options\n\ndef scan(ip):\n\tarp_request = scapy.ARP(pdst=ip)\n\tbroadcast = scapy.Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n\tarp_request_broadcast = broadcast/arp_request\n\tanswered_packets = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]\n\t\n\tclients_list = []\n\t\n\tfor element in answered_packets:\n\t\tclient_dict = {\"ip\":element[1].psrc, \"mac\":element[1].hwsrc}\n\t\tclients_list.append(client_dict)\n\treturn clients_list\n\t\ndef print_result(results_list):\n\tprint(\"IP\\t\\t\\tMAC ADDRESS\\n-------------------------------------------------------\")\n\tfor client in results_list:\n\t\tprint(client[\"ip\"]+\"\\t\\t\"+client[\"mac\"])\n\n# ----------------------- MAIN -----------------\n\nprint(\"\"\" _______ __ __ _________ \n \\ \\ _____/ |___ _ _____________| | __ / _____/ ____ _____ ____ ____ ___________ \n / | \\_/ __ \\ __\\ \\/ \\/ / _ \\_ __ \\ |/ / \\_____ \\_/ ___\\\\\\\\__ \\ / \\ / \\_/ __ \\_ __ \\\\\n/ | \\ ___/| | \\ ( <_> ) | \\/ < / \\ \\___ / __ \\| | \\ | \\ ___/| | \\/\n\\____|__ /\\___ >__| \\/\\_/ \\____/|__| |__|_ \\ /_______ /\\___ >____ /___| /___| /\\___ >__| \n \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \"\"\")\n\noptions = get_arguments()\nscan_result = scan(options.target)\nprint_result(scan_result)","sub_path":"network_scanner.py","file_name":"network_scanner.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"49309185","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\n\r\nimport time\r\nimport datetime\r\n\r\nclass datechange(object):\r\n #localtime='2017-01-12 11:33:00'\r\n def formattime(self,localtime):\r\n self.localtime= localtime\r\n try: # 有的精确到分\r\n stamp1 = datetime.datetime.strptime(self.localtime, \"%Y-%m-%d %H:%M:%S\")\r\n time_local = stamp1.timetuple()\r\n except Exception as e: # 有的精确到秒\r\n stamp1 = datetime.datetime.strptime(self.localtime, \"%Y-%m-%d %H:%M\")\r\n time_local = stamp1.timetuple()\r\n timestamp = time.mktime(time_local)#是时间戳了\r\n date1= stamp1.strftime('%y.%m.%d')\r\n #return stamp1.year,stamp1.month,date1,stamp1.hour,stamp1.weekday()\r\n return timestamp\r\n\r\n\r\n def warps(No):\r\n def deco(func):\r\n def _deco(*args,**kwargs):\r\n print(No)\r\n start = time.clock()\r\n func(*args, **kwargs)\r\n end = time.clock()\r\n print(end-start)\r\n print(str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))+'---'\\\r\n + datetime.datetime.now().strftime('%A'))\r\n #print(str(datetime.datetime.now().strftime('%c')))\r\n return _deco\r\n return deco\r\n\r\n\r\n\r\n # def warps(t):\r\n # def deco(func):\r\n # def _deco(*args,**kwargs):\r\n # print(1)\r\n # start = time.clock()\r\n # func(*args, **kwargs)\r\n # print(4)\r\n # end = time.clock()\r\n # if end - start > t:\r\n # print('bad')\r\n # else:\r\n # print ('goods')\r\n # return _deco\r\n # return deco\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# localtime='2017-04-24 11:33:00'\r\n# stamp1=datetime.datetime.strptime(localtime, \"%Y-%m-%d %H:%M:%S\")\r\n# print(stamp1.date())\r\n# print(stamp1.weekday())\r\n#\r\n#\r\n# #今天星期几\r\n# today=int(time.strftime(\"%w\"))\r\n# print (today)\r\n# #某��日期星期几\r\n# anyday=datetime.datetime(2012,4,23).strftime(\"%w\")\r\n# print (anyday)\r\n#\r\n# dt = datetime.datetime.strptime(\"2012-09-12 21:08:12\", \"%Y-%m-%d %H:%M:%S\")\r\n# print (dt.year)\r\n# print(dt.month)\r\n# print(dt.day)\r\n# print(dt.hour)\r\n# print(dt.minute)\r\n# print(dt.second)\r\n# print(dt.microsecond)\r\n# print(dt.tzinfo)\r\n# print('3333333333')\r\n# print (dt.date())\r\n# print (dt.time())\r\n# print (dt.replace(year = 2013))\r\n# print (dt.timetuple())\r\n# print('-----')\r\n# print (time.mktime(dt.timetuple()))\r\n# print (dt.utctimetuple())\r\n# print (dt.toordinal())\r\n# print (dt.weekday())\r\n# print (dt.isocalendar())\r\n# print (dt.strftime('%y-%m-%d %I:%M:%S %p'))\r\n# print (dt.strftime('(%y,%m,%d)'))\r\n#\r\n# # datetime. strftime (format)\r\n# # %a 星期的简写。如 星期三为Web\r\n# # %A 星期的全写。如 星期三为Wednesday\r\n# # %b 月份的简写。如4月份为Apr\r\n# # %B月份的全写。如4月份为April\r\n# # %c: 日期时间的字符串表示。(如: 04/07/10 10:43:39)\r\n# # %d: 日在这个月中的天数(是这个月的第几天)\r\n# # %f: 微秒(范围[0,999999])\r\n# # %H: 小时(24小时制,[0, 23])\r\n# # %I: 小时(12小时制,[0, 11])\r\n# # %j: 日在年中的天数 [001,366](是当年的第几天)\r\n# # %m: 月份([01,12])\r\n# # %M: 分钟([00,59])\r\n# # %p: AM或者PM\r\n# # %S: 秒(范围为[00,61],为什么不是[00, 59],参考python手册~_~)\r\n# # %U: 周在当年的周数当年的第几周),星期天作为周的第一天\r\n# # %w: 今天在这周的天数,范围为[0, 6],6表示星期天\r\n# # %W: 周在当年的周数(是当年的第几周),星期一作为周的第一天\r\n# # %x: 日期字符串(如:04/07/10)\r\n# # %X: 时间字符串(如:10:43:39)\r\n# # %y: 2个数字表示的年份\r\n# # %Y: 4个数字表示的年份\r\n# # %z: 与utc时间的间隔 (如果是本地时间,返回空字符串)\r\n# # %Z: 时区名称(如果是本地时间,返回空字符串)\r\n# # %%: %% => %","sub_path":"Dateformat.py","file_name":"Dateformat.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"343667206","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPhotometry\n==========\n\nDefines photometric quantities computation related objects.\n\nReferences\n----------\n- :cite:`Wikipedia2003b` : Wikipedia. (2003). Luminosity function. Retrieved\n October 20, 2014, from\n https://en.wikipedia.org/wiki/Luminosity_function#Details\n- :cite:`Wikipedia2005c` : Wikipedia. (2005). Luminous Efficacy. Retrieved\n April 3, 2016, from https://en.wikipedia.org/wiki/Luminous_efficacy\n\"\"\"\n\nimport numpy as np\n\nfrom colour.colorimetry import SDS_LEFS_PHOTOPIC\nfrom colour.constants import CONSTANT_K_M\nfrom colour.utilities import as_float\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = ['luminous_flux', 'luminous_efficiency', 'luminous_efficacy']\n\n\ndef luminous_flux(sd,\n lef=SDS_LEFS_PHOTOPIC['CIE 1924 Photopic Standard Observer'],\n K_m=CONSTANT_K_M):\n \"\"\"\n Returns the *luminous flux* for given spectral distribution using given\n luminous efficiency function.\n\n Parameters\n ----------\n sd : SpectralDistribution\n test spectral distribution\n lef : SpectralDistribution, optional\n :math:`V(\\\\lambda)` luminous efficiency function.\n K_m : numeric, optional\n :math:`lm\\\\cdot W^{-1}` maximum photopic luminous efficiency\n\n Returns\n -------\n numeric\n Luminous flux.\n\n References\n ----------\n :cite:`Wikipedia2003b`\n\n Examples\n --------\n >>> from colour import SDS_LIGHT_SOURCES\n >>> sd = SDS_LIGHT_SOURCES['Neodimium Incandescent']\n >>> luminous_flux(sd) # doctest: +ELLIPSIS\n 23807.6555273...\n \"\"\"\n\n lef = lef.copy().align(\n sd.shape,\n extrapolator_kwargs={\n 'method': 'Constant',\n 'left': 0,\n 'right': 0\n })\n sd = sd.copy() * lef\n\n flux = K_m * np.trapz(sd.values, sd.wavelengths)\n\n return as_float(flux)\n\n\ndef luminous_efficiency(\n sd, lef=SDS_LEFS_PHOTOPIC['CIE 1924 Photopic Standard Observer']):\n \"\"\"\n Returns the *luminous efficiency* of given spectral distribution using\n given luminous efficiency function.\n\n Parameters\n ----------\n sd : SpectralDistribution\n test spectral distribution\n lef : SpectralDistribution, optional\n :math:`V(\\\\lambda)` luminous efficiency function.\n\n Returns\n -------\n numeric\n Luminous efficiency.\n\n References\n ----------\n :cite:`Wikipedia2003b`\n\n Examples\n --------\n >>> from colour import SDS_LIGHT_SOURCES\n >>> sd = SDS_LIGHT_SOURCES['Neodimium Incandescent']\n >>> luminous_efficiency(sd) # doctest: +ELLIPSIS\n 0.1994393...\n \"\"\"\n\n lef = lef.copy().align(\n sd.shape,\n extrapolator_kwargs={\n 'method': 'Constant',\n 'left': 0,\n 'right': 0\n })\n sd = sd.copy()\n\n efficiency = (np.trapz(lef.values * sd.values, sd.wavelengths) / np.trapz(\n sd.values, sd.wavelengths))\n\n return efficiency\n\n\ndef luminous_efficacy(\n sd, lef=SDS_LEFS_PHOTOPIC['CIE 1924 Photopic Standard Observer']):\n \"\"\"\n Returns the *luminous efficacy* in :math:`lm\\\\cdot W^{-1}` of given\n spectral distribution using given luminous efficiency function.\n\n Parameters\n ----------\n sd : SpectralDistribution\n test spectral distribution\n lef : SpectralDistribution, optional\n :math:`V(\\\\lambda)` luminous efficiency function.\n\n Returns\n -------\n numeric\n Luminous efficacy in :math:`lm\\\\cdot W^{-1}`.\n\n References\n ----------\n :cite:`Wikipedia2005c`\n\n Examples\n --------\n >>> from colour import SDS_LIGHT_SOURCES\n >>> sd = SDS_LIGHT_SOURCES['Neodimium Incandescent']\n >>> luminous_efficacy(sd) # doctest: +ELLIPSIS\n 136.2170803...\n \"\"\"\n\n efficacy = CONSTANT_K_M * luminous_efficiency(sd, lef)\n\n return as_float(efficacy)\n","sub_path":"colour/colorimetry/photometry.py","file_name":"photometry.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236786920","text":"########################################\n## Created on 2018/07/01 ##\n## author: Chia-Ching Lin ##\n## ##\n## 專案CHUNK名字必須與155上資料夾一致 ##\n########################################\nimport os, sys, zipfile, pathlib, datetime, shutil, subprocess\nimport Metashape\nfrom tkinter.filedialog import *\nfrom bs4 import BeautifulSoup\nfrom subprocess import PIPE\nfrom ftplib import FTP\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\nfrom gdalconst import *\nfrom osgeo import gdal\nimport osr, os, affine, time\n\n\n# 前置設定參數\ntw97 = Metashape.CoordinateSystem(\"EPSG::3826\")\nws84 = Metashape.CoordinateSystem(\"EPSG::3857\")\nds84 = Metashape.CoordinateSystem(\"EPSG::4326\") \ncrs = Metashape.CoordinateSystem('LOCAL_CS[\"Local CS\",LOCAL_DATUM[\"Local Datum\",0],UNIT[\"metre\",1]]')\n\n\npath = r'\\\\140.116.228.155\\geodac_uav\\2019'\ndir = r'C:\\Users\\RSLAB\\Desktop\\dir\\\\'\n\ndir_1 = '1.測繪產品'\ndir_1_1 = '1.1.Ortho_正射影像(包含附加檔)'\ndir_1_2 = '1.2.OrigPhoto_原始照片'\ndir_1_3 = '1.3.PrecEval_精度評估報告'\ndir_1_4 = '1.4.ContCoor_控制點座標)'\ndir_1_5 = '1.5.ContPhoto_控制點照片'\ndir_1_6 = '1.6.FlyRec_飛行記錄'\ndir_1_7 = '1.7.DSM_數值地表模型'\ndir_1_8 = '1.8.3DModel_3D模型'\n\n# info = ['140.116.249.139','geodac','rsej0hk45j/vup','/TCGEO/2019']\n# ftp = FTP(info[0], info[1], info[2])\n# ftp.encoding = 'big5'\n# ftp.cwd(info[3])\n# ftp_list = ftp.nlst(info[3])\n\n\n\n## - - - 從這裡開始!! - - - \nprint(\"\\n- - - - - - - - Script started - - - - - - - - \\n\")\n\ndef workflow():\n pass\n\ndef create_dir(name):\n #pathlib.Path(path+ name).mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/2.環景照片').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/3.一般產品').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/4.影片').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/Photoscan').mkdir(parents=True, exist_ok=0)\n #open('.\\\\'+ name + '\\\\Photoscan' + '\\\\' + name + '.psx','w')\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.1.Ortho_正射影像(包含附加檔)').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.2.OrigPhoto_原始照片').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.3.PrecEval_精度評估報告').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.4.ContCoor_控制點座標)').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.5.ContPhoto_控制點照片').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.6.FlyRec_飛行記錄').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.7.DSM_數值地表模型').mkdir(parents=True, exist_ok=0)\n pathlib.Path(path+'\\\\'+ name + '/1.測繪產品' + './1.8.3DModel_3D模型').mkdir(parents=True, exist_ok=0)\n\ndef add_3D(name, date, wgs84, othro_location, cad_location, model_location, output):\n # check(dic['othro']+'index.html')\n # check(dic['cad'])\n # check(dic['model']+'tileset.json')\n root = ET.Element('tree',id=\"0\")\n one = ET.SubElement(root, \"item\", text = name[9:], id = name, nocheckbox=\"1\", im0=\"hd.gif\", im1=\"folderOpen.gif\", im2=\"folderClosed.gif\")\n ET.SubElement(one , \"item\", text = '正射影像_' + date + '(雙擊定位)' , id = wgs84 + ';;18@TileImage_ps@' + othro_location , im0='hd.gif', im1='folderOpen.gif', im2='folderClosed.gif').text = ' '\n ET.SubElement(one , \"item\", text = '工程圖說' , id = wgs84 + ';;18@Kml@' + cad_location , im0='hd.gif', im1='folderOpen.gif', im2='folderClosed.gif').text = ' '\n ET.SubElement(one , \"item\", text = '3D_模型' , id = wgs84 + ';;18@3DModel@' + model_location , im0='hd.gif', im1='folderOpen.gif', im2='folderClosed.gif').text = ' '\n xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=\" \")\n \n with open(output, 'w',encoding = 'utf8') as myXML:\n myXML.write(xmlstr) \n\ndef create_xml(i, wgs84):\n url_front = 'https://geodac.ncku.edu.tw/TCGEO/2019/'\n # create each location in ftp\n othro_location = os.path.join(url_front, i, 'othro/').replace('\\\\', '/')\n cad_location = os.path.join(url_front, i, 'cad/' ).replace('\\\\', '/')\n model_location = os.path.join(url_front, i, 'model/').replace('\\\\', '/')\n \n # output file path\n output = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + r'xml.txt' \n \n # chunkname date wgs84 othro_location cad_location model_location outputFile\n add_3D(i, i[0:8], wgs84, othro_location, cad_location, model_location, output)\n\ndef retrieve_pixel_value(geo_coord, data_source):\n \"\"\"Return floating-point value that corresponds to given point.\"\"\"\n x, y = geo_coord[0], geo_coord[1]\n forward_transform = affine.Affine.from_gdal(*data_source.GetGeoTransform())\n reverse_transform = ~forward_transform\n px, py = reverse_transform * (x, y)\n px, py = int(px + 0.5), int(py + 0.5)\n pixel_coord = px, py\n data_array = np.array(data_source.GetRasterBand(1).ReadAsArray())\n # i = data_array[0]\n # j = data_array[1]\n return(data_array[pixel_coord[1]][pixel_coord[0]])\n\ndef get_lon_lat(file_in, file_out, data): \n with open(file_in, 'r', encoding='utf8') as origin:\n with open(file_out, 'w', encoding='utf8') as out:\n num = 0\n for line in origin.readlines(): \n if num == 1 :\n out.write('\\t\\t\\t\\t\\t\\t\\t')\n for j in line.split():\n if j != '' and j != '':\n xlon = float(j.split(',')[0])\n xlat = float(j.split(',')[1])\n print(xlon, xlat)\n \n h = str(retrieve_pixel_value((xlon, xlat), data)+0.7) \n out.write(j.split(',')[0] + ',' + j.split(',')[1] + ',' + h + ' ') \n # out.write('')\n num = 0\n else: \n if line.find('0') > 0:\n pass\n else:\n out.write(line) \n \n if line.find('') > 0:\n num = 1\n print('[OK] write kml.\\n')\n\ndef add_kml(i, dir_1_8, dsm84):\n start_time = time.time()\n dsm_path = dsm84\n origin_kml_name = \"RAW_{}_{}\".format(i.split('_')[1], i.split('_')[2])\n output_kml_name = \"{}_{}_{}\".format( i.split('_')[0], i.split('_')[1], i.split('_')[2])\n origin_kml_path = os.path.join(dir_1_8, origin_kml_name)\n output_kml_path = os.path.join(dir_1_8, output_kml_name)\n data = gdal.Open(dsm_path, GA_ReadOnly)\n array = get_lon_lat(origin_kml_path, output_kml_path, data)\n \n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# 自動產生 TIFF、KMZ、TILE、MODEL(含解壓縮及中心座標檔案)\ndef export():\n \n for chunk in Metashape.app.document.chunks:\n for i in os.listdir(path):\n # print('chunk name: ' + chunk.label)\n # i為資料夾名稱 == chunk名字\n if i == chunk.label:\n \n #create_dir(i)\n \n # 1.1.Ortho_正射影像\n #------- 路徑 ---- 資料夾檔名 - 1.測繪產品 ------ 1.1 ----- 檔案名稱+副檔名 \n othro = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_1 + '\\\\' + i + '.tif'\n tile = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_1 + '\\\\' + i + '.zip'\n report = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_3 + '\\\\' + i + '.pdf'\n kmz = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_1 + '\\\\' + i + '.kmz'\n \n # 1.4.ContCoor_控制點座標)\n path_marker = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_4 + '\\\\' + i + '.txt'\n \n # 1.7.DSM_數值地表模型\n dsm97 = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_7 + '\\\\' + i + '_tw97.tif'\n dsm84 = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_7 + '\\\\' + i + '_wgs84.tif'\n \n # 1.8.3DModel_3D模型\n obj = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + 'model' + '.obj'\n kmz_3d = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + i + '.kmz'\n \n\n # 無法自動輸出控制點\n # T = chunk.transform.matrix\n # f = open(path_marker, 'wt')\n # for marker in chunk.markers:\n # if not marker.position:\n # continue\n # v_t = T.mulp(marker.position)\n # chunk.crs = Metashape.CoordinateSystem(\"EPSG::4326\")\n # v_out = chunk.crs.project(v_t)\n # f.write(marker.label + ',' + str(v_out[0]) + ',' + str(v_out[1]) + ',' + str(v_out[2]) + '\\n')\n # print(marker.label + ',' + str(v_out[0]) + ',' + str(v_out[1]) + ',' + str(v_out[2]) + '\\n')\n # f.close()\n \n \n # ## 正射影像 TIFF\n # chunk.exportOrthomosaic(othro,image_format=Metashape.ImageFormatTIFF,projection=tw97,raster_transform=Metashape.RasterTransformNone,write_kml=True,write_world=True,white_background=False)\n # print('[OK] export othro.')\n \n # ## 正射影像 KMZ\n # chunk.exportOrthomosaic(kmz ,format=Metashape.RasterFormatKMZ,raster_transform=Metashape.RasterTransformNone,write_kml=True,write_world=True)\n # print('[OK] export kmz.')\n\n # ## 報告\n # chunk.exportReport(report, title = i, description = 'Made by GEODAC')\n # print('[OK] export report.')\n\n # ## 圖專\n # chunk.exportOrthomosaic(tile,format=Metashape.RasterFormatXYZ,image_format=Metashape.ImageFormatPNG,raster_transform=Metashape.RasterTransformNone,projection=ws84,write_kml=True)\n # print('[OK] export tile.')\n \n # ## DSM\n # chunk.exportDem(path=dsm97,format=Metashape.RasterFormatTiles,image_format=Metashape.ImageFormatTIFF,projection= tw97, nodata=-32767)\n # chunk.exportDem(path=dsm84,format=Metashape.RasterFormatTiles,image_format=Metashape.ImageFormatTIFF,projection= ds84, nodata=-32767)\n # print('[OK] export dsm.') \n \n # ##三維模型 OBJ\n # chunk.exportModel(obj , binary=False, precision=6, texture_format=Metashape.ImageFormatJPEG, texture=True, normals=False, colors=False, cameras=False, udim=False, strip_extensions=False, format=Metashape.ModelFormatOBJ, projection=crs)\n # print('[OK] export obj.')\n\n # ##三維模型 KMZ\n # chunk.exportModel(kmz_3d , binary=False, precision=6, texture_format=Metashape.ImageFormatJPEG, texture=True, normals=False, colors=False, cameras=False, udim=False, strip_extensions=False, format=Metashape.ModelFormatKMZ, projection=crs)\n # print('[OK] export kmz_3d.')\n\n # ## 解壓縮KMZ_3D\n # with zipfile.ZipFile(kmz_3d, 'r') as kmz:\n # pathlib.Path(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + i).mkdir(parents=True, exist_ok=1)\n # #os.mkdir(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + i)\n # kmz.extractall(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + i + '\\\\')\n # print('[OK] unzip kmz_3d')\n \n # ## - - - 批次輸出分隔線結束 - - - \n \n ## KML新增高程\n add_kml(i, dir_1_8, dsm84) \n \n # ## 輸出至D槽,創建資料夾\n # out_case = os.path.join('D:\\Backup139\\\\', i)\n # out_tile = os.path.join(out_case, 'othro')\n # out_cad = os.path.join(out_case, 'cad')\n # out_model = os.path.join(out_case, 'model')\n \n # pathlib.Path(out_case).mkdir(parents=True, exist_ok=1)\n # pathlib.Path(out_tile).mkdir(parents=True, exist_ok=1)\n # pathlib.Path(out_cad).mkdir(parents=True, exist_ok=1)\n # # pathlib.Path(out_model).mkdir(parents=True, exist_ok=1)\n\n # # 解壓縮圖專\n # print('Start unzip tile')\n # with zipfile.ZipFile(tile, 'r') as zf:\n # # pathlib.Path(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_1 + '\\\\' + i).mkdir(parents=True, exist_ok=1)\n # # os.mkdir(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_1 + '\\\\' + i)\n # zf.extractall(out_tile)\n # print('[OK] unzip tile') \n \n \n # ## 讀取中心座標 \n # kml = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + i + '\\\\' + 'doc.kml'\n # with open(kml, 'r', encoding = 'utf8')as f:\n\n # soup = BeautifulSoup(f.read(), 'html.parser')\n # lon = soup.select('longitude')[0].text\n # lat = soup.select('latitude')[0].text\n # center = lat+ ',' + lon \n # wgs84 = lat+ ';' + lon\n # output = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + center + '.txt'\n # open(output, 'a',encoding = 'utf8')\n # print('[OK] create center file')\n \n # ## 寫入處理名單\n # with open(r'\\\\140.116.228.155\\geodac_uav\\uav.txt', 'a', encoding = 'utf8') as txt:\n # txt.write(i + ',' + center +'\\n')\n # print('[OK] add to uav.txt')\n \n # ## 自動執行Tran3D\n # path_174 = r'\\\\140.116.228.174\\geodac_data_test\\RAW\\RSImage\\UAV\\3DModel'\n # path_174 = 'T:\\\\'\n # dst_path = ''\n # folder = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\' + dir_1_8\n # nowtime = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n # tran = ''\n # # print(folder, '\\n\\n', nowtime)\n # for item in os.listdir(folder):\n # # dir_174 .b3d所在的地方\n # dir_174 = os.path.join(path_174, nowtime)\n # dst_path = dir_174 \n # pathlib.Path(dir_174).mkdir(parents=True, exist_ok=1)\n # if item[-3:] == 'txt':\n # if item != 'xml.txt':\n # # print(nowtime, item)\n # lat = item[0:13]\n # lon = item[14:28]\n # tran = \"ssh user1@140.116.228.180 -p 2202 './trans3d \" + nowtime + ' ' + lon + ' ' + lat + \"'\"\n # print(tran)\n\n # if item[-3:] == 'obj':\n # shutil.copyfile(os.path.join(folder,item),os.path.join(dir_174,item))\n # elif item[-3:] == 'mtl':\n # shutil.copyfile(os.path.join(folder, item),os.path.join(dir_174,item))\n # elif item[-3:] == 'jpg':\n # shutil.copyfile(os.path.join(folder, item),os.path.join(dir_174,item))\n \n \n # process = subprocess.Popen('powershell.exe ' + tran, stdout=PIPE, stderr=PIPE, stdin=PIPE)\n # out, err = process.communicate()\n # print('[stdout]: ', out)\n # print('[stderr]: ', err)\n # print('\\n')\n # ## 自動執行Tran3D結束\n \n # ## move tran3d from 174 to 155\n # after_tran = path_174 + '\\\\' + nowtime + '\\\\' + 'Batchedmodel'\n # dst_155 = path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + 'tran3d'\n \n # print(os.path.isdir(after_tran), after_tran)\n \n # if os.path.isdir(dst_155):\n # shutil.rmtree(dst_155)\n # shutil.copytree(after_tran, dst_155)\n # else:\n # shutil.copytree(after_tran, dst_155)\n \n # ## D槽也一份\n # if os.path.isdir(out_model):\n # shutil.rmtree(out_model) \n # shutil.copytree(after_tran, out_model)\n # else:\n # shutil.copytree(after_tran, out_model)\n \n # prjno = i.split('_')[2]\n # raw_kml_dir = r'F:\\WorkFolder\\TCGE_工程圖說'\n \n\n \n # ## 自動產生xml\n # create_xml(i, wgs84)\n # shutil.copyfile(path + '\\\\' + i + '\\\\' + dir_1 + '\\\\'+ dir_1_8 + '\\\\' + r'xml.txt', out_case + '\\\\xml.txt')\n \ndef main():\n export()\n\nmain()\n\nprint(\"\\n- - - - - - - - Script End - - - - - - - - \\n\")","sub_path":"batch_output_Metashape_2019.py","file_name":"batch_output_Metashape_2019.py","file_ext":"py","file_size_in_byte":18828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"642374490","text":"import unittest\nimport common.mainModule\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport logging\n\nmodule_logger = logging.getLogger(\"mainModule.DefaultTest\")\nclass DefaulTest(unittest.TestCase):\n # logger = logging.getLogger(\"mainModule.sub.Default\")\n # logger.info(\"creating an instance in SubModuleClass\")\n @classmethod\n def setUpClass(cls):\n\n # cls.driver = webdriver.Chrome()\n #使用本地driver\n cls.driver=webdriver.Remote(command_executor='http://47.100.188.71:4444/wd/hub',\n desired_capabilities=DesiredCapabilities.CHROME)\n #调用远程selenium grid的driver\n # opt=webdriver.Chrome.create_options().add_argument('start-maximized')\n cls.url=\"https://console.huilianyi.com/#/login\"\n cls.driver.implicitly_wait(30)\n #chrom需要注销掉\n #\n cls.driver.set_window_size(width=\"1920\", height=\"1080\")\n # cls.driver.maximize_window() 窗口最大化\n # rect = cls.driver.get_window_size()\n # print(rect)\n # logger = logging.getLogger(\"mainModule.sub.module\")\n module_logger.info('Start Testing')\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n module_logger.info('End Testing')\n\n\n\n\n\n","sub_path":"testcases/DefaultTest.py","file_name":"DefaultTest.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"290286572","text":"#!/usr/bin/python\n#-*-coding:utf-8-*-\n\nfrom flask import Flask, g, request, jsonify\nfrom transaction.bsbdj import BsAPI\n \napp = Flask(__name__)\napp.debug = True\n\n\n@app.route('/app')\ndef hello():\n msg = request.args.get('name', 'bob')\n return \"Hello, %s! - Flask\" % msg\n\n@app.route('/app/joke')\ndef joke():\n bs = BsAPI()\n return jsonify({'joke': bs.getS()})\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5001, debug=False)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90239731","text":"##\n## Imprima por cada fila, la columna 1 y la suma de los valores\n## de la columna 5\n##\n## E,22\n## A,14\n## B,14\n## ....\n## C,8\n## E,11\n## E,16\n##\nimport numpy as np\nfrom collections import Counter\nimport csv\n\nfile = open('data.csv', 'r')\n\ncol0=[]; col1=[]; col2=[]; col3=[]; col4=[]; \n\nfor line in file:\n \n data = line.strip().split(\"\\t\") \n col0.append(data[0]); \n col1.append(float(data[1])); \n col2.append(data[2]); \n col3.append(data[3]); \n col4.append(data[4]) \n \ntuples = []\n\nfor i, val1 in enumerate(col4):\n tuples1 = val1.split(\",\")\n x = np.array([])\n for j, val2 in enumerate(tuples1):\n tuples2 = val2.split(\":\")\n tuples.append(tuples2)\n x = np.append(x,[float(tuples2[1])],axis=0)\n print(str(col0[i])+\",\"+str(int(x.sum())))\n","sub_path":"q13.py","file_name":"q13.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"442951625","text":"import random\nfrom pylab import plot, show, legend\nfrom random import normalvariate\nimport numpy as np\nfrom statsmodels.tsa.arima_model import ARIMA\nimport datetime, time\n\ndef balanceGenerator():\n balances = []\n currentBalance = random.randrange(25, 200000)\n return currentBalance\n\ndef randomWalk(N, l, r, d=2):\n return np.random.uniform(l,r,(N,d))\n\n\n# for i in range(2):\n # n = 100\n # currBal = np.random.uniform(25, 100000)\n # lowBal = 25\n # print randomWalk(n, lowBal, currBal)\n\ndef outlierRejection(data, m=2):\n newData = []\n for i in range(len(data)):\n if abs(data[i] - np.mean(data)) < 3 * np.std(data):\n newData.append(data[i])\n return newData\n\ndef checkingData():\n for i in range(10):\n currBal = np.random.uniform(25, 100000)\n lowBal = 25\n ran = int(np.random.uniform(100, 200)) \n x = [normalvariate(currBal, lowBal) for i in range(ran)]\n x = outlierRejection(x)\n plot(x, 'b-')\n legend()\n\ndef creditCardData():\n for i in range(10):\n currBal = np.random.uniform(0, 5000)\n lowBal = 25\n p = 0\n d = 1\n q = 1\n ran = int(np.random.uniform(100, 200))\n x = [normalvariate(currBal, lowBal) for i in range(ran)]\n x = outlierRejection(x)\n arima = ARIMA(x, [p, d, q], exog=None, freq='M', missing='none')\n","sub_path":"dataGenerator.py","file_name":"dataGenerator.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"624685627","text":"from __future__ import print_function\nfrom dolfin import *\nimport sys\n \nN=20\nmesh = RectangleMesh(Point(0.0, 0.0), Point(1.0,1.0), 20, 20,\"crossed\")\n\nV=VectorFunctionSpace(mesh,\"P\",1) \nV_ele=FunctionSpace(mesh,\"DG\",0) \n\nFName_str=\"Fernandez_plate_model/Density_\" \nFExt_str=\".pvd\"\n\ncnt_cell_converged=[] \n\nrho0=0.8\nrho_val=[] \nfor cell_s in cells(mesh): \n rho_val.append(rho0)\n cnt_cell_converged.append(0) \n \nrho_min=0.01\nrho_max=1.740\n\nk=0.25\n\nnu=0.3 \n\nM=10000.0\n \ngamma=2.0 \n\nB=1.0 \n\nT=25.0 \ndt=0.01 \nt=dt \n\ncnt_cells=mesh.num_cells()\n\ntol=1E-14 \n\ndef bottom_fixed_boundary(x,on_boundary):\n return near(x[0],0,tol) and near(x[1],0,tol)\nFixed_left=Constant((0.,0.)) \nbc_Fixed=DirichletBC(V,Fixed_left,bottom_fixed_boundary,method='pointwise')\n \ndef bottom_right_boundary(x,on_boundary):\n return near(x[1],0.0,tol) and x[0]>0.0\nRoller_right=Constant(0)\nbc_roller=DirichletBC(V.sub(1),Roller_right,bottom_right_boundary) \n\nbcs=[bc_Fixed,bc_roller]\n\nclass Top(SubDomain):\n tol=1E-14\n def inside(self,x,on_boundary):\n return near(x[1],1.0,tol)\n\ntop=Top() \n\nboundries=MeshFunction('size_t',mesh,1) \nboundries.set_all(0) \ntop.mark(boundries,1) \nds=Measure('ds', domain=mesh,subdomain_data=boundries)\n\nF=Expression(\"m*x[0]+c\",m=-10.0,c=10.0,degree=1)\n\ndef calculate_E(updated_rho_val):\n E_updated=Function(V_ele) \n E_array=E_updated.vector().get_local()\n for i, rho in enumerate (updated_rho_val): \n E_array[i]=M*pow(rho,gamma)\n E_updated.vector().set_local(E_array)\n return E_updated\n\nE0=calculate_E(rho_val) \n\ndef calculate_Lame_coefficients(E_val):\n mu_val=(E_val)/(2*(1+nu)) \n lmbda_val=(E_val*nu)/((1+nu)*(1-2*(nu))) \n return mu_val,lmbda_val\n\nmu, lmbda=calculate_Lame_coefficients(E0) \n\n\ndef epsilon(u):\n strain_u=0.5*(nabla_grad(u)+nabla_grad(u).T)\n return strain_u\n\ndef sigma(u,mu,lmbda):\n stress_u=lmbda*div(u)*Identity(d)+2*mu*epsilon(u)\n return stress_u \n\nf=Constant((0.0,0.0)) \n\nu=TrialFunction(V) \nv=TestFunction(V)\n\nd=u.geometric_dimension()\n\na = 2*mu*inner(epsilon(u),epsilon(v))*dx + lmbda*dot(div(u),div(v))*dx\nL=dot(f,v)*dx+v[1]*F*ds(1)\n\ndef calculate_SED(epsilon_val,sigma_val): \n SED_val=0.5*inner(sigma_val,epsilon_val) \n \n SED_plot=project(SED_val, V_ele)\n SED_values=SED_plot.vector().get_local()\n \n return(SED_values,SED_plot)\n\ndef calculate_Density_change(rho_vals,SED):\n import numpy as np\n change_in_density=[]\n \n rho_plot=Function(V_ele)\n rho_array=rho_plot.vector().get_local() \n \n stimulus_plot=Function(V_ele)\n stimulus=stimulus_plot.vector().get_local() \n \n for i, cells_i in enumerate (cells(mesh)): \n \n if cnt_cell_converged[i]==0: \n stimulus[i]=SED[i]/rho_vals[i]\n \n change_in_density.append(B*(stimulus[i]-k)) \n \n rho_array[i]=rho_vals[i]+(dt*change_in_density[i])\n else: \n change_in_density.append(0)\n rho_array[i]=rho_vals[i] \n \n rho_plot.vector().set_local(rho_array) \n return rho_plot,rho_array,cnt_cell_converged,change_in_density \n\ndef check_convergence(density_values,change_in_density):\n \n tol=1E-14\n for i, density_val in enumerate (density_values):\n if density_val<=rho_min: \n cnt_cell_converged[i]=1\n density_values[i]=rho_min\n elif density_val>=rho_max: \n cnt_cell_converged[i]=1\n density_values[i]=rho_max\n elif near(change_in_density[i],0.0,tol):\n cnt_cell_converged[i]=1 \n return density_values\n\ndef create_rho_plot(updated_rho_array):\n V_ele=FunctionSpace(mesh,\"DG\",0)\n rho_ele=Function(V_ele) \n rho_ele_array=rho_ele.vector().get_local()\n \n i=0\n for cell_s in cells(mesh): \n rho_ele_array[i]=updated_rho_array[i]\n i=i+1\n rho_ele.vector().set_local(rho_ele_array)\n return rho_ele\n\nupdated_rho_val=rho_val\n\nu=Function(V) \ncnt_freq=0.0\n\nday=0 \nwhile day<=T: \n solve(a==L,u,bcs)\n cnt_freq=cnt_freq+0.01 \n \n epsilon_val=epsilon(u) \n sigma_val=sigma(u,mu,lmbda)\n \n SED,SED_plt=calculate_SED(epsilon_val,sigma_val)\n \n updated_rho, updated_rho_val,cnt_cell_converged,change=calculate_Density_change(updated_rho_val,SED) \n \n E_updated_t=calculate_E(updated_rho_val) \n E0.assign(E_updated_t)\n \n mu, lmbda=calculate_Lame_coefficients(E0) \n \n if cnt_freq>=1:\n cnt_freq=0.0 \n day = day+1\n \n rho_after_convergence=check_convergence(updated_rho_val,change)\n\n if sum(cnt_cell_converged)==cnt_cells:\n t=T+1\n day=t\n elif day==T: \n print(\"Specified days computed\")\n t=T+1\n day=t\n else:\n t=t+dt \n\nFName_str_femur=\"Density_\"\nele_rho=create_rho_plot(rho_after_convergence)\n\nfName=FName_str+str(day)+FExt_str\nFile(fName)<10:\n for i in IPdict:\n #if there has been more than 100 requests in the previous second\n if IPdict[i] > 100:\n print(\"Potential DOS attack from source IP:\", sourceIP)\n print(\"{} packets received in the past 10 seconds\".format(IPdict[i]))\n print(\"\\n\")\n #set back to 0\n IPdict[i] = 0\n\n #resetting start time\n start = time.time()\n\n","sub_path":"DOSdetection.py","file_name":"DOSdetection.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"509431521","text":"import os\nfile_num = 0\ndir_1 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/昆安(31座)/昆安每座桥记录表汇总'\ndir_2 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/楚广(40座)'\ndir_3 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/武昆(176座)'\ndir_4 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/永武(433座)'\n\ndir_5 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/安楚(306座)'\ndir_6 = '/home/jusaka/work3/2018年桥梁记录表(昆西)/楚大(132座)'\n\nfile_ass = []\ndir_file = dir_1 #切换\ndir_file_more = [dir_1, dir_2, dir_3, dir_4]\n\n# for root, dirs, files in os.walk(dir_file):\n# for file in files:\n# (filename, extension) = os.path.splitext(file) #将文件名拆分为文件名与后缀\n# if (extension == '.xlsx'): #判断该后缀是否为.c文件\n# file_ass.append(file)\n \ndef choose_content(i):\n global file_ass\n global dir_file\n file_ass.clear()\n dir_file = dir_file_more[i]\n for root, dirs, files in os.walk(dir_file):\n for file in files:\n (filename, extension) = os.path.splitext(file) #将文件名拆分为文件名与后缀\n if (extension == '.xlsx'): #判断该后缀是否为.c文件\n file_ass.append(file)\n return file_ass\n\n\n\n\n# print(file_ass)\n# for i in range(0, len(file_ass)):\n# if dir_file == dir_1:\n# open_contentfile = '2018年桥梁记录表(昆西)/昆安(31座)/昆安每座桥记录表汇总/'+file_ass[i]\n# elif dir_file == dir_2:\n# open_contentfile = '2018年桥梁记录表(昆西)/楚广(40座)/'+file_ass[i]\n# elif dir_file == dir_3:\n# open_contentfile = '2018年桥梁记录表(昆西)/武昆(176座)/'+file_ass[i]\n# elif dir_file == dir_4:\n# open_contentfile = '2018年桥梁记录表(昆西)/永武(433座)/'+file_ass[i]\n \n# print(i, open_contentfile)\n\n# def test():\n# print(\"test\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# dir_list = [dir_1, dir_2, dir_3, dir_4]\n# item = 0\n# for item in range(0, len(dir_list)):\n# for root, dirs, files in os.walk(dir_list[item]):\n# for file in files:\n# (filename, extension) = os.path.splitext(file) #将文件名拆分为文件名与后缀\n# if (extension == '.xlsx'): #判断该后缀是否为.c文件\n# file_num= file_num+1 #记录.c文件的个数为对应文件号\n# # print(file_num, os.path.join(root,filename)) #输出文件号以及对应的路径加文件名\n# file_ass.append(file)\n # print(file)\n # print(\"PLACE_RAM(\" + filename + ')')\n ","sub_path":"work2_check_2018/get_file.py","file_name":"get_file.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"169253473","text":"# coding: utf-8\nimport numpy as np\nimport scipy.misc as misc\nimport matplotlib.pyplot as plt\n\n\ndef find_a(a, prec=3):\n i=1\n step=1\n log_a = np.log(a)\n while 1 != log_a:\n print(f\"a: {a}, log_a: {log_a}, i: {i}\")\n if log_a > round(float(1), prec):\n a -= step\n i = (i+1, i-1)[log_a > 1]\n else:\n a += step\n i = (i+1, i-1)[log_a > 1]\n step = step / i\n log_a = np.log(a)\n return a\n\n\ndef taylor_sequence(a, x, max):\n factorial = lambda n: 1 if n <= 0 else n*factorial(n-1) \n value = 0\n plots = {}\n for k in range(0, max):\n value = x**k / factorial(k)\n plots[k] = value\n return value, plots\n\n\ndef main():\n a = find_a(1, 3) # working\n print(a)\n taylor = taylor_sequence(0, 1, 15) # working\n print(taylor)\n\nif __name__ == \"__main__\":\n main()","sub_path":"infinite_decimal/infinite_decimal.py","file_name":"infinite_decimal.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"246543921","text":"import os\nimport sys\nimport glob\nimport json\nimport torch\nimport numpy as np\nfrom model import models\nfrom model import metrics\nfrom data import visualize\nfrom data import data_utils\nimport matplotlib.pyplot as plt\nfrom model import dataset_loader\nfrom torchsummary import summary\nimport torch.utils.data as torchdata\nfrom torch.utils.tensorboard import SummaryWriter\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass Trainer:\n def __init__(self, cfg):\n self.cfg = cfg\n self.configure()\n self.define_loss()\n self.cal_input_channels()\n self.generate_input_mapping()\n self.create_model()\n self.create_dataloader()\n\n\n def configure(self):\n # Bounding volume parameters\n vol_type = self.cfg.vol_type\n self.vol_params = ()\n if vol_type == \"sphere\":\n center = torch.Tensor(self.cfg.vol_params[:3]).to(device)\n radius = self.cfg.vol_params[3]\n self.vol_params = (vol_type, center, radius)\n elif vol_type == \"cube\":\n min_bound = torch.Tensor(self.cfg.vol_params[:3]).to(device)\n max_bound = torch.Tensor(self.cfg.vol_params[3:]).to(device)\n self.vol_params = (vol_type, min_bound, max_bound)\n else:\n sys.exit(\"Unsupported bounding volume\")\n\n # Setup logging\n logdir = os.path.join(os.getcwd(), \"logs\")\n self.modeldir = os.path.join(os.getcwd(), \"models\")\n os.makedirs(logdir, exist_ok=True)\n os.makedirs(self.modeldir, exist_ok=True)\n self.writer = SummaryWriter(logdir)\n \n def define_loss(self):\n if self.cfg.loss == 'l1':\n self.loss_fun = metrics.l1\n elif self.cfg.loss == 'lpips':\n self.loss_fun = metrics.lpips\n elif self.cfg.loss == 'ssim':\n self.loss_fun = metrics.msssim\n elif self.cfg.loss == 'mse':\n self.loss_fun = metrics.mse\n elif self.cfg.loss == 'fft':\n self.loss_fun = metrics.loss_fft\n else:\n self.loss_fun = metrics.mse\n\n\n def cal_input_channels(self):\n dim_points = 3\n dim_viewdir = 0\n\n if self.cfg.points_type == 'spherical':\n dim_points = 2\n \n if self.cfg.use_viewdirs and self.cfg.viewdir_type == 'cartesian':\n dim_viewdir = 3\n elif self.cfg.use_viewdirs and self.cfg.viewdir_type == 'spherical':\n dim_viewdir = 2\n \n self.input_ch = dim_points + dim_viewdir\n\n if self.cfg.feature_mapping != 'none':\n self.input_ch = self.input_ch + (self.cfg.mapping_size * 2) \n # self.input_ch = (self.cfg.mapping_size * 2) \n # if self.cfg.map_points:\n # dim_points = self.cfg.mapping_size * 2\n \n # if self.cfg.use_viewdirs and self.cfg.map_viewdirs:\n # dim_viewdir = 0\n\n def generate_input_mapping(self):\n inp_size = 0\n if self.cfg.map_points:\n if self.cfg.points_type == 'spherical':\n inp_size += 2\n else:\n inp_size += 3\n \n if self.cfg.use_viewdirs and self.cfg.map_viewdirs:\n if self.cfg.viewdir_type == 'cartesian':\n inp_size += 3\n else: \n inp_size += 2\n \n self.B_dict = {}\n # Standard network - no mapping\n self.B_dict['none'] = None\n # Gaussian Fourier feature mapping\n B_gauss = torch.normal(mean=0, std=1.0, size=(self.cfg.mapping_size, inp_size))\n # Three different scales of Gaussian Fourier feature mappings\n for scale in [1., 2., 4., 8., 10., 32.]:\n self.B_dict[f'gauss_{scale}'] = B_gauss * scale\n\n self.input_map = self.B_dict[self.cfg.feature_mapping]\n \n\n def create_dataloader(self):\n datadir = self.cfg.datadir\n\n i_train = []\n i_val = []\n for f in sorted(glob.glob(datadir + \"/train/*.json\")):\n filename = f[f.rfind('_') + 1:f.rfind('.')]\n i_train.append(filename)\n \n for f in sorted(glob.glob(datadir + \"/val/*.json\")):\n filename = f[f.rfind('_') + 1:f.rfind('.')]\n i_val.append(filename)\n \n self.dataset_train = dataset_loader.DatasetLoad(data_list=i_train, data_dir=os.path.join(datadir, \"train\"),\n cfg=self.cfg, input_map=self.input_map)\n self.dataloader_train = torchdata.DataLoader(self.dataset_train, batch_size=self.cfg.batch_size, \n shuffle=True, num_workers=2, drop_last=False)\n \n self.dataset_val = dataset_loader.DatasetLoad(data_list=i_val, data_dir=os.path.join(datadir, \"val\"),\n cfg=self.cfg, input_map=self.input_map)\n self.dataloader_val = torchdata.DataLoader(self.dataset_val, batch_size=self.cfg.batch_size, \n shuffle=False, num_workers=2, drop_last=False)\n\n\n\n\n def create_model(self):\n \"\"\"\n Create a new model or load model from saved checkpoint\n \"\"\"\n self.model = models.ConvNet(num_layers=self.cfg.num_layers,\n hidden_size=self.cfg.hidden_size,\n skip_connect=self.cfg.skip_connect,\n input_ch= self.input_ch,\n output_ch=self.cfg.output_ch).to(device)\n \n self.optimizer = torch.optim.Adam(self.model.parameters(), \n lr=self.cfg.optimizer.lr,\n weight_decay=self.cfg.optimizer.weight_decay)\n self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size = self.cfg.scheduler.step_decay, gamma = self.cfg.scheduler.lr_decay)\n \n # summary(self.model, (512, 512, 512))\n\n self.start_epoch = 0\n\n # load a model from saved checkpoint if provided\n if self.cfg.checkpoint:\n print('loading model: ', self.cfg.checkpoint)\n checkpoint = torch.load(self.cfg.checkpoint, map_location=device)\n self.start_epoch = checkpoint['epoch']\n self.input_map = checkpoint['input_map'].cpu()\n self.model.load_state_dict(checkpoint['state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n \n def train(self, epoch):\n self.model.train()\n batch_loss = 0.0\n batch_clamped_output = []\n batch_diff = []\n batch_target = []\n batch_input_points = []\n batch_input_viewdirs = []\n\n for idx, sample in enumerate(self.dataloader_train):\n input = sample['input'].to(device)\n mask = sample['input_mask'].to(device)\n target = sample['target'].to(device)\n\n target = target[:,:3,...]\n mask = mask.unsqueeze(1).expand(target.shape)\n\n self.optimizer.zero_grad()\n # forward pass\n output = self.model(input)\n\n # compute losses\n loss_l1 = metrics.l1(target, output, mask)\n loss_ssim = metrics.msssim(target, output, mask)\n loss = loss_l1 + loss_ssim\n # loss = self.loss_fun(target, output, mask)\n\n # backward pass and optimize\n loss.backward()\n self.optimizer.step()\n\n # log\n batch_loss += loss.item()\n\n # visualize images on tensorboard\n if idx in [0, 1] and (epoch+1) % self.cfg.save_every == 0:\n clamped_output = torch.clamp(output.detach(), min=0.0, max=1.0) * mask\n target = target * mask\n batch_target.append(target.cpu())\n batch_diff.append(torch.abs(target-clamped_output).cpu())\n batch_clamped_output.append(clamped_output.cpu())\n\n # if idx in [0,1] and epoch == 0:\n # raw_data = sample['raw_data'].cpu()\n # if self.cfg.use_viewdirs:\n # batch_input_viewdirs.append(raw_data[:,1,...])\n # raw_data = raw_data[:,0,...]\n # batch_input_points.append(raw_data)\n\n # visualize alpha and rgb distribution for first image on tensorboard\n # if idx == 0:\n # self.writer.add_histogram(\"red\", output[0,0,...], epoch+1)\n # self.writer.add_histogram(\"green\", rgb[0,1,...], epoch+1)\n # self.writer.add_histogram(\"blue\", rgb[0,2,...], epoch+1)\n \n # log losses\n self.writer.add_scalar('rgb_loss',batch_loss/(idx+1),epoch+1)\n\n # log input and target images only once\n # if epoch == 0:\n # batch_input_points = torch.cat(batch_input_points)\n # if batch_input_points.shape[1] == 3:\n # batch_input_points = visualize.vis_cartesian_as_matplotfig(batch_input_points)\n # else:\n # batch_input_points = visualize.vis_spherical_as_matplotfig(batch_input_points)\n\n # if self.cfg.use_viewdirs:\n # batch_input_viewdirs = torch.cat(batch_input_viewdirs)\n # if batch_input_viewdirs.shape[1] == 3:\n # batch_input_viewdirs = visualize.vis_cartesian_as_matplotfig(batch_input_viewdirs)\n # else:\n # batch_input_viewdirs = visualize.vis_spherical_as_matplotfig(batch_input_viewdirs)\n \n # self.writer.add_figure('input_points', batch_input_points,epoch+1)\n # if self.cfg.use_viewdirs:\n # self.writer.add_figure('input_viewdirs', batch_input_viewdirs,epoch+1)\n \n if (epoch+1) % self.cfg.save_every == 0:\n self.writer.add_images('rgb_target', torch.cat(batch_target), epoch+1)\n self.writer.add_images('rgb_clamped', torch.cat(batch_clamped_output), epoch+1)\n self.writer.add_images('rgb_diff', torch.cat(batch_diff), epoch+1)\n \n return batch_loss/(idx+1)\n \n\n def val(self, epoch):\n self.model.eval()\n batch_l1 = 0.0\n batch_lpips = 0.0\n batch_psnr = 0.0\n batch_ssim = 0.0\n batch_mse = 0.0\n batch_fft = 0.0\n batch_clamped_output = []\n batch_diff = []\n batch_target = []\n batch_input_points = []\n batch_input_viewdirs = []\n\n with torch.no_grad():\n for idx, sample in enumerate(self.dataloader_val):\n input = sample['input'].to(device)\n mask = sample['input_mask'].to(device)\n target = sample['target'].to(device)\n\n target = target[:,:3,...]\n mask = mask.unsqueeze(1).expand(target.shape)\n\n # forward pass\n output = self.model(input)\n \n # compute losses\n # lpips = metrics.lpips(target, output, mask)\n l1 = metrics.l1(target, output, mask)\n # mse = metrics.mse(target, output, mask)\n psnr = metrics.psnr(target, output, mask)\n ssim = metrics.msssim(target, output, mask)\n # fft = metrics.loss_fft(target, output, mask)\n\n # log\n batch_l1 += l1.item()\n # batch_mse += mse.item()\n # batch_lpips += lpips.item()\n batch_psnr += psnr.item()\n batch_ssim += ssim.item()\n # batch_fft += fft.item()\n\n\n # visualize images on tensorboard\n if idx in [0,1] and (epoch+1) % self.cfg.save_every == 0:\n clamped_output = torch.clamp(output, min=0.0, max=1.0) * mask\n target = target * mask\n batch_diff.append(torch.abs(target-clamped_output).cpu())\n batch_clamped_output.append(clamped_output.cpu())\n\n if epoch == 0 and idx in [0,1]:\n batch_target.append(target.cpu())\n # raw_data = sample['raw_data'].cpu()\n # if self.cfg.use_viewdirs:\n # batch_input_viewdirs.append(raw_data[:,1,...])\n # raw_data = raw_data[:,0,...]\n # batch_input_points.append(raw_data)\n\n # log losses\n self.writer.add_scalar('rgb_val_loss',batch_l1/(idx+1),epoch+1)\n # self.writer.add_scalar('rgb_val_mse',batch_mse/(idx+1),epoch+1)\n # self.writer.add_scalar('rgb_val_lpips',batch_lpips/(idx+1),epoch+1)\n self.writer.add_scalar('rgb_val_psnr',batch_psnr/(idx+1),epoch+1)\n self.writer.add_scalar('rgb_val_ssim',batch_ssim/(idx+1),epoch+1)\n # self.writer.add_scalar('val_fft',batch_fft/(idx+1),epoch+1)\n\n # log input and target images only once\n if epoch == 0:\n # batch_input_points = torch.cat(batch_input_points)\n # if batch_input_points.shape[1] == 3:\n # batch_input_points = visualize.vis_cartesian_as_matplotfig(batch_input_points)\n # else:\n # batch_input_points = visualize.vis_spherical_as_matplotfig(batch_input_points)\n\n # if self.cfg.use_viewdirs:\n # batch_input_viewdirs = torch.cat(batch_input_viewdirs)\n # if batch_input_viewdirs.shape[1] == 3:\n # batch_input_viewdirs = visualize.vis_cartesian_as_matplotfig(batch_input_viewdirs)\n # else:\n # batch_input_viewdirs = visualize.vis_spherical_as_matplotfig(batch_input_viewdirs)\n \n # self.writer.add_figure('test_input_points', batch_input_points,epoch+1)\n # if self.cfg.use_viewdirs:\n # self.writer.add_figure('test_input_viewdirs', batch_input_viewdirs,epoch+1)\n self.writer.add_images('rgb_val_target', torch.cat(batch_target), epoch+1)\n \n if (epoch+1) % self.cfg.save_every == 0:\n self.writer.add_images('rgb_val_clamped', torch.cat(batch_clamped_output), epoch+1)\n self.writer.add_images('rgb_val_diff', torch.cat(batch_diff), epoch+1)\n \n return batch_mse/(idx+1)\n\n def start(self):\n print('Start training')\n\n self.writer.add_text('Summary', self.cfg.text_summary, 1)\n least_val_loss = 50.0\n train_loss_at_best_epoch = 0.0\n best_epoch = 0\n best_model = {}\n for epoch in range(self.start_epoch, self.cfg.max_epochs):\n train_loss = self.train(epoch)\n val_loss = self.val(epoch)\n\n # if val_loss <= least_val_loss:\n # least_val_loss = val_loss\n # train_loss_at_best_epoch = train_loss\n # best_epoch = epoch+1\n # best_model['model_state'] = self.model.state_dict()\n # best_model['optimizer_state'] = self.optimizer.state_dict()\n self.scheduler.step()\n\n if (epoch+1) % 20 == 0:\n torch.save({'epoch': epoch+1, 'input_map':self.input_map, 'state_dict': self.model.state_dict(), \n 'optimizer':self.optimizer.state_dict()},\n os.path.join(self.modeldir, '%02d.pth'%(epoch+1)))\n \n # torch.save({'epoch': best_epoch, 'input_map':self.input_map, 'state_dict': best_model['model_state'], \n # 'optimizer':best_model['optimizer_state']},\n # os.path.join(self.modeldir, 'best_model_%02d.pth'%(best_epoch)))\n\n # print('Train loss of best model: ', train_loss_at_best_epoch)\n # print('Val loss of best model: ', least_val_loss)\n # print('Best epoch: ', best_epoch)\n","sub_path":"src/model/trainer_ConvNet.py","file_name":"trainer_ConvNet.py","file_ext":"py","file_size_in_byte":15762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359757726","text":"from JumpScale import j\n\n\n\n\ndef getMachine( job):\n machine=None\n return machine\n\ndef open_port( requested_port, public_port=None):\n \"\"\"\n Open port in the firewall by creating port forward\n if public_port is None, auto select available port\n Return the public port assigned\n \"\"\"\n pf = service.hrd.getList('portforwards', [])\n pf.append(\"%s:%s\" % (spaceport, requested_port))\n service.hrd.set('portforwards', pf)\n return spaceport\n\ndef install( job):\n\n machineid=service.hrd.getSet('machineid', j.data.idgenerator.generateRandomInt(10,20))\n\n if not service.hrd.get('publicip', ''):\n service.hrd.set('publicip', \"212.3.45.%\"%j.data.idgenerator.generateRandomInt(70,120))\n service.hrd.set('sshport', executor.port)\n\n for child in service.children:\n child.hrd.set(\"ssh.addr\", service.hrd.get(\"publicip\"))\n child.hrd.set(\"ssh.port\", service.hrd.get(\"sshport\"))\n\n for port in service.hrd.getList('ports'):\n ss = port.split(':')\n if len(ss) == 2:\n service.actions.open_port(requested_port=ss[1], public_port=ss[0])\n else:\n service.actions.open_port(requested_port=port)\n\n\ndef uninstall( job):\n pass\n \n","sub_path":"fake_IT_env/actortemplates/nodes/node.ovc/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"200854274","text":"# Rosalind Exercises\n\ndef CountBases(Genome):\n '''\n Count the number of bases, ACGT, in a string as a 4-tuple\n\n Returns\n\n counts: A, C, G, T\n '''\n s = Genome.strip('\\n')\n return s.count('A'), s.count('C'), s.count('G'), s.count('T')\n\ndef reverse(text):\n tmp = []\n for i in range(len(text)-1,-1,-1):\n tmp.append(text[i])\n return ''.join(tmp)\n\ndef complement(nucleotide):\n return {\n 'A':'T',\n 'T':'A',\n 'C':'G',\n 'G':'C'\n }.get(nucleotide, 'X')\n\ndef transcribe(seq):\n nucs = {'A':'U','T':'A','C':'G','G':'C'}\n return ''.join(nucs[n] for n in seq)\n\ndef ReverseComplement(Pattern):\n revComp = []\n comp = dict(zip('ATGC','TACG'))\n for n in reverse(Pattern):\n revComp.append(comp[n])\n return ''.join(revComp)\n\n\ndef translate(seq, start=0, end=len(seq)):\n aa = []\n\n d = {'CUA': 'L', 'UGU': 'C', 'GUA': 'V', 'AUG': 'M',\n 'GCA': 'A', 'CCA': 'P', 'GAC': 'D', 'GUC': 'V',\n 'GCU': 'A', 'UGG': 'W', 'CCU': 'P', 'AGG': 'R',\n 'UUU': 'F', 'AGA': 'R', 'GCG': 'A', 'AGC': 'S',\n 'GAA': 'E', 'ACC': 'T', 'CUG': 'L', 'UCG': 'S',\n 'CGA': 'R', 'UUA': 'L', 'CUC': 'L', 'AGU': 'S',\n 'AUC': 'I', 'GGC': 'G', 'ACA': 'T', 'UGA': 'Stop',\n 'AAU': 'N', 'CAU': 'H', 'CAC': 'H', 'UAG': 'Stop',\n 'GUG': 'V', 'GCC': 'A', 'AUU': 'I', 'CUU': 'L',\n 'ACU': 'T', 'UAA': 'Stop', 'GAG': 'E', 'GGU': 'G',\n 'AAG': 'K', 'UAC': 'Y', 'GGG': 'G', 'ACG': 'T',\n 'GGA': 'G', 'UCU': 'S', 'UCA': 'S', 'GAU': 'D',\n 'CAG': 'Q', 'AAA': 'K', 'UGC': 'C', 'CCC': 'P',\n 'CGG': 'R', 'UAU': 'Y', 'CCG': 'P', 'UUC': 'F',\n 'AAC': 'N', 'UUG': 'L', 'UCC': 'S', 'AUA': 'I',\n 'CGU': 'R', 'GUU': 'V', 'CGC': 'R', 'CAA': 'Q'}\n\n for i in range(start,end,3):\n aa.append(d[seq[i:i+3]])\n\n aa = ''.join(aa).split('Stop')[0]\n\n return aa\n\ndef translateAllORFs(seq):\n orfs = []\n # Forward 3 ORFs\n for i in range(3):\n orfs.append(translate(seq=seq,start=i))\n # Reverse 3 ORFs\n return orfs\n\ndef countGC(seq):\n\n gs = seq.count('G')\n cs = seq.count('C')\n\n return (gs+cs)/len(seq)\n\ndef fibo_slow(n):\n if n < 2:\n return n\n else:\n return fibo_slow(n-2)+fibo_slow(n-1)\n\ndef fib_gen():\n '''Fibonacci generator'''\n a, b = 0,1\n yield a\n yield b\n while True:\n a,b = b, a+b\n yield b\n\ndef fib(n):\n a,b = 1,1\n for i in range(n-1):\n a,b = b, a+b\n return a\n\n# Fast Fibonacci-esque rabbit calculator. Assumes immortal rabbits\ndef immortal_rabbit_fib(n,k):\n a,b = 1,1\n for i in range(n-1):\n b,a=b+k*a,b\n return a\n\n# Fast Fibonacci-esque mortal rabbits using a dictionary\n# to stored previously computed values of the sequence in order to avoid\n# recursive calls\nfrom collections import defaultdict\n__fib_cache = {0:1,1:1,2:1}\n__fib_cache = defaultdict(lambda: 0, __fib_cache)\ndef fib_fast_mortal(n,k,m):\n #print(n,k,m)\n if n in __fib_cache:\n #print('%d is in cache. Returning %d' % (__fib_cache[n],__fib_cache[n]))\n return __fib_cache[n]\n else:\n #print('%d not in cache.' % n)\n __fib_cache[n] = n if n < 2 else k*fib_fast_mortal(n-2,k,m) + \\\n fib_fast_mortal(n-1,k,m) - __fib_cache[n-m-1]\n #print('Added %d:%d to cache' % (n,__fib_cache[n]))\n #print(__fib_cache)\n return __fib_cache[n]\n\n# rosalind.info/fibd top solution\n# Really cool solution that just keeps track of the number of\n# of rabbits in each age group\ndef rosa_fib(n,k=1):\n ages = [1] + [0]*(k-1)\n print(ages)\n for i in range(n-1):\n # of newborns # of mature rabbits\n ages = [sum(ages[1:])] + ages[:-1]\n print(ages)\n return sum(ages)\n\n\ndef calculate_dominance(k,m,n):\n from scipy.misc import comb\n tot = int(comb((k+m+n),2))\n homo = int(comb(k,2))\n homo_cross = k*(m+n)\n hetero = int(comb(m,2))\n hetero_cross = m*n\n\n # Returns the number that create a particular punnet square\n # multiplied by its punnet square derived % of dominance\n return 1/tot*(homo*(4/4)+homo_cross+hetero*.75+hetero_cross*0.5)\n\n# PERM - Enumerating Gene Orders\nimport itertools\ndef permutations(n):\n perms = list(itertools.permutations(range(1,n+1)))\n print(len(perms))\n #[print('%s %s %s' % x) for x in perms]\n\n # From Rosalind solutions\n for line in perms:\n print(' '.join(map(str,line)))\n\n\n# CONS - Consensus and Profiles\ndef consensus(filename):\n from Bio import SeqIO\n import numpy as np\n import pandas as pd\n\n # Initialize containers\n matrix = {'A':[],'C':[],'G':[],'T':[]}\n seqs = []\n\n # Read using SeqIO and add to seqs\n for record in SeqIO.parse(filename,'fasta'):\n seqs.append(record.seq)\n\n seqs = np.array(seqs)\n\n # Count # of nucs in each column\n for i in range(seqs.shape[1]):\n for nuc in list('ACGT'):\n matrix[nuc].append(list(seqs[:,i]).count(nuc))\n\n df = pd.DataFrame(matrix)\n\n # Consensus nuc at each position is the index of the maximum value\n consensus = ''.join(df.idxmax(axis=1).values)\n\n d = df.to_dict(orient='list')\n\n # Output\n return consensus\n #for nuc in list('ACGT'):\n # print('%s:' % nuc,'%r' % ' '.join(list(map(str,d[nuc]))))\n\n\ndef calculateProteinMass(poly):\n import pickle\n d = pickle.load(open('./assignments_misc/mono_table.pkl','rb'))\n mass = 0\n for aa in poly:\n mass+=d[aa]\n print('%0.3f'%mass)\n\ndef printDirectedGraph(seqs):\n '''Prints directed overlap graph given dictionary of sequence ids:seq'''\n for id,seq in seqs.items():\n suf = seq[-3:]\n #print(id,seq,suf)\n for id2,seq2 in seqs.items():\n if id2!=id:\n pre = seq2[0:3]\n if suf==pre:\n print(id,id2)\n\n\ndef countExpectedDominantChildren(s='1 0 0 1 0 1', num_offpsring=2):\n '''\n Returns the number of offpsring that can be expected from\n the population described in s, corresponding to:\n\n 1. AA-AA\n 2. AA-Aa\n 3. AA-aa\n 4. Aa-Aa\n 5. Aa-aa\n 6. aa-aa\n\n '''\n punnets = [4/4,4/4,4/4,3/4,2/4,0/4]\n offspring = [num_offpsring]*6\n nums = s.split()\n\n return sum(int(i)*j*k for i,j,k in zip(nums,punnets,offspring))\n\ndef translateDNA(seq):\n '''\n Given a DNA sequence, returns a string representing\n the resulting polypeptide with '*' for STOP codons\n '''\n from collections import defaultdict\n d = {}\n d = defaultdict(lambda x: [],d)\n with open('./assignments_misc/dna_codon_table_easy.txt','r') as f:\n for line in f.readlines():\n split = line.split()\n d[split[0]] = split[1]\n d = dict(d)\n\n aa = []\n for i in range(0,len(seq),3):\n triplet = seq[i:i+3]\n if len(triplet)==3:\n aa.append(d[triplet])\n\n return ''.join(aa).replace('Stop','*')\n","sub_path":"rosalind/rosalind.py","file_name":"rosalind.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"237615447","text":"#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python\n\n#################################################################################################\n# #\n# plot_grating_focus.py: update grating focus plots #\n# #\n# author: t. isobe (tisobe@cfa.harvard.edu) #\n# #\n# last update: Mar 12, 2021 #\n# #\n#################################################################################################\n\nimport os\nimport sys\nimport re\nimport random\nimport numpy\nimport time\nimport Chandra.Time\n\nimport matplotlib as mpl\nif __name__ == '__main__':\n mpl.use('Agg')\n\nfrom pylab import *\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as font_manager\nimport matplotlib.lines as lines\n#\n#--- reading directory list\n#\npath = '/data/mta/Script/Grating/Focus/Scripts/house_keeping/dir_list'\n\nwith open(path, 'r') as f:\n data = [line.strip() for line in f.readlines()]\n\nfor ent in data:\n atemp = re.split(':', ent)\n var = atemp[1].strip()\n line = atemp[0].strip()\n exec(\"%s = %s\" %(var, line))\n#\n#--- append pathes to private folders to a python directory\n#\nsys.path.append(bin_dir)\nsys.path.append(mta_dir)\n\nimport mta_common_functions as mcf\nimport find_moving_average as mavg #---- contains moving average routine\n\n#----------------------------------------------------------------------------------------------\n#-- update_focus_data_plot: update grating focus plots ---\n#----------------------------------------------------------------------------------------------\n\ndef update_focus_data_plot():\n \"\"\"\n update grating focus plots\n input: none, but /acis_hetg, acis_letg, hrc_letg\n output: /Plots/__focus.phg\n \"\"\"\n for d_file in ['acis_hetg', 'acis_letg', 'hrc_letg']:\n out = read_focus_data(d_file)\n time = out[0]\n try:\n a_set = [out[1], out[2], out[5], out[7]]\n except:\n continue\n\n [ctime, c_set] = remove_non_data(time, a_set)\n titles = ['AX LRF at 10% Peak', 'AX LRF at 50% Peak', 'Gaussian FWHM']\n outname = web_dir + 'Plots/' + d_file + '_ax_lrf_focus.png'\n y_label = 'Width (microns)'\n y_limits = [[50,110], [20, 60], [20,60]]\n plot_data(ctime, c_set, titles, outname, y_label, y_limits)\n\n try:\n s_set = [out[3], out[4], out[6], out[8]]\n except:\n continue\n\n [ctime, c_set] = remove_non_data(time, a_set)\n titles = ['Streak LRF at 10% Peak', 'Streak LRF at 50% Peak', 'Gaussian FWHM']\n outname = web_dir + 'Plots/' + d_file + '_streak_lrf_focus.png'\n y_label = 'Width (microns)'\n y_limits = [[50, 110], [20, 60], [20, 60]]\n plot_data(ctime, c_set, titles, outname, y_label, y_limits)\n\n#----------------------------------------------------------------------------------------------\n#-- remove_non_data: removing non (-999) data and data outside of the useable valeus --\n#----------------------------------------------------------------------------------------------\n\ndef remove_non_data(x, t_set):\n \"\"\"\n removing non (-999) data and data outside of the useable valeus\n input: x --- time\n t_set --- a list of 4 lists; first three are value list and last one error list \n output: x --- cleaned time entry\n o_set --- a list of cleaned three value lists. no error list are retured\n \"\"\"\n x = numpy.array(x)\n yarray = []\n for k in range(0, 4):\n yarray.append(numpy.array(t_set[k]))\n\n for k in range(0, 2):\n index = (yarray[k] > 0) & (yarray[k] < 100)\n x = x[index]\n for m in range(0, 4):\n yarray[m] = yarray[m][index]\n \n index = yarray[3] < 10\n x = x[index]\n for m in range(0, 4):\n yarray[m] = yarray[m][index]\n\n return [x, [list(yarray[0]), list(yarray[1]), list(yarray[2])]]\n \n#----------------------------------------------------------------------------------------------\n#-- plot_data: plot data --\n#----------------------------------------------------------------------------------------------\n\ndef plot_data(xdata, y_set, titles, outname, y_label, y_limits):\n \"\"\"\n plot data\n input: xdata --- x data\n ydata --- y data\n grating --- tile of the data\n outname --- output plot file; assume it is png\n output: hetg_all_focus.png, metg_all_focus.png, letg_all_focus.png\n \"\"\"\n# \n#--- set sizes\n#\n fsize = 18\n color = 'blue'\n color2 = 'red'\n marker = '.'\n psize = 8\n lw = 3\n alpha = 0.3\n width = 10.0\n height = 10.0\n resolution = 200\n\n xmin = 1999\n xmax = max(xdata) \n diff = xmax - int(xmax)\n if diff > 0.7:\n xmax = int(xmax) + 2\n else:\n xmax = int(xmax) + 1\n diff = xmax - xmin\n xpos = xmin + 0.02 * diff\n#\n#--- close everything opened before\n#\n plt.close('all')\n#\n#--- set font size\n#\n mpl.rcParams['font.size'] = fsize\n props = font_manager.FontProperties(size=fsize)\n plt.subplots_adjust(hspace=0.08)\n#\n#--- set plotting range\n#\n for k in range(0, 3):\n plt.subplots_adjust(hspace=0.08)\n ymin = y_limits[k][0]\n ymax = y_limits[k][1]\n diff = ymax - ymin\n ypos = ymax - 0.1 * diff\n\n panel = '31' + str(k+1)\n ax = plt.subplot(panel)\n ax.set_autoscale_on(False)\n ax.set_xbound(xmin,xmax)\n ax.set_xlim(left=xmin, right=xmax, auto=False)\n ax.set_ylim(bottom=ymin, top=ymax, auto=False)\n \n plt.plot(xdata, y_set[k], color=color, marker=marker, markersize=psize, lw=0)\n plt.tight_layout()\n\n [x, y] = remove_extreme(xdata, y_set[k])\n [xv, movavg, sigma, min_sv, max_sv, ym, yb, yt, y_sig] \\\n = mavg.find_moving_average(x, y, 1.0, 3, nodrop=0)\n#\n#--- plot envelopes\n#\n plt.plot(xv, yb, color=color2, marker=marker, markersize=0, lw=lw, alpha=alpha)\n plt.plot(xv, ym, color=color2, marker=marker, markersize=0, lw=lw, alpha=alpha)\n plt.plot(xv, yt, color=color2, marker=marker, markersize=0, lw=lw, alpha=alpha)\n#\n#--- add label\n#\n plt.text(xpos, ypos, titles[k], color=color)\n if k == 2:\n plt.xlabel('Time (year)')\n else:\n plt.setp(ax.get_xticklabels(), visible=False)\n if k == 1:\n plt.ylabel(y_label)\n\n fig = matplotlib.pyplot.gcf()\n fig.set_size_inches(width, height)\n plt.tight_layout()\n plt.savefig(outname, format='png', dpi=resolution)\n\n plt.close('all')\n\n#----------------------------------------------------------------------------------------------\n#-- remove_extreme: remove extreme data points --\n#----------------------------------------------------------------------------------------------\n\ndef remove_extreme(x, y):\n \"\"\"\n remove extreme data points\n input: x --- a list of x data\n y --- a list of y data\n output: [x, y]\n \"\"\"\n x = numpy.array(x)\n y = numpy.array(y)\n avg = numpy.mean(y)\n sig = numpy.std(y)\n bot = avg - 3.0 * sig\n top = avg + 3.0 * sig\n\n index = (y >0) & (y < 300)\n x = x[index]\n y = y[index]\n\n return [x, y]\n\n#----------------------------------------------------------------------------------------------\n#-- read_focus_data: read data file and extract data needed --\n#----------------------------------------------------------------------------------------------\n\ndef read_focus_data(infile):\n \"\"\"\n read data file and return lists of times and values\n input: infile --- data file name\n output: t_list --- a list of time data\n c1_list --- a list of data (ax slf 10%)\n c2_list --- a list of data (ax slf 50%)\n c3_list --- a list of data (streak slf 10%)\n c4_list --- a list of data (streak slf 50%)\n c5_list --- a list of data (ax slf fwhm)\n c6_list --- a list of data (streak slf fwhm)\n c7_list --- a list of data (ax slf fwhm error)\n c8_list --- a list of data (streak slf fwhm error)\n \"\"\"\n infile = data_dir + infile\n print(\"Data: \" + str(infile))\n data = mcf.read_data_file(infile)\n\n t_list = []\n c1_list = []\n c2_list = []\n c3_list = []\n c4_list = []\n c5_list = []\n c6_list = []\n c7_list = []\n c8_list = []\n for ent in data:\n atemp = re.split('\\s+', ent)\n try:\n t = mcf.chandratime_to_fraq_year(float(atemp[0]))\n v1 = float(atemp[1])\n v2 = float(atemp[2])\n v3 = float(atemp[3])\n v4 = float(atemp[4])\n v5 = float(atemp[5])\n v6 = float(atemp[6])\n v7 = float(atemp[6])\n v8 = float(atemp[6])\n except:\n continue\n\n t_list.append(t)\n c1_list.append(v1)\n c2_list.append(v2)\n c3_list.append(v3)\n c4_list.append(v4)\n c5_list.append(v5)\n c6_list.append(v6)\n c7_list.append(v7)\n c8_list.append(v8)\n\n return [t_list, c1_list, c2_list, c3_list, c4_list, c5_list, c6_list, c7_list, c8_list]\n\n#---------------------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\n update_focus_data_plot()\n","sub_path":"Grating/Focus/Scripts/plot_grating_fucus.py","file_name":"plot_grating_fucus.py","file_ext":"py","file_size_in_byte":10082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"372203912","text":"from __future__ import print_function\n\nimport os, sys, glob, time, re, gc\n\nmodule_path = os.path.abspath(os.path.join('.'))\nif module_path not in sys.path:\n sys.path.append(module_path)\nb = sys.path\nsys.path = [module_path] + b\n\nimport pathlib as p\nimport copy, warnings\nfrom collections import OrderedDict\nimport time\n\nimport numpy\n\nimport joblib as jl\n\nfrom libtbx.math_utils import ifloor, iceil\nfrom scitbx.array_family import flex\n\nfrom bamboo.common.status import status_bar, status_bar_2\n\nfrom pandda.analyse.classes import PanddaStatMapList, MapHolderList\nfrom pandda.analyse.functions import DatasetAligner, MapLoader, DensityStatistics, UncertaintyCalculator, wrapper_run\n\nfrom dask.distributed import worker_client\n\n\ndef load(model):\n # Get truncated datasets\n model.dataset.sample_loader.truncate_datasets(model.dataset.datasets)\n model.dataset.datasets = model.dataset.sample_loader.truncated_datasets\n\n # Get cur resolution for dataset\n test_datasets = model.dataset.partition_datasets(\"test\")\n train_datasets = model.dataset.partition_datasets(\"train\")\n test_datasets.update(train_datasets)\n resolutions = [d.data.summary.high_res for dtag, d in test_datasets.items()]\n max_res = max(resolutions)\n\n # Get ref map\n model.dataset.sample_loader.get_reference(max_res)\n\n # Attach grid to\n model.map_maker.attach_grid(model.grid)\n\n # Attach grid to event table maker\n model.event_table_maker.grid = model.grid\n\n return model\n\n\ndef fit(model):\n\n model.fit()\n\n return model\n\n\ndef evaluate(model):\n\n model.evaluate()\n\n return model\n\n\ndef criticise(model):\n\n event_table = model.criticise()\n\n return event_table\n\n\nclass PanDDAEventModelDistributed:\n\n def __init__(self, statistical_model, clusterer, event_finder, bdc_calculator=None, statistics=[], dataset=None,\n reference=None, grid=None, map_maker=None, event_table_maker=None, cpus=1, tree=None, name=None):\n\n self.trace = None\n self.cpus = cpus\n self.tree = tree\n self.name = name\n\n self.statistical_model = statistical_model\n self.clusterer = clusterer\n self.event_finder = event_finder\n self.bdc_calculator = bdc_calculator\n self.statistics = statistics\n self.map_maker = map_maker\n self.event_table_maker = event_table_maker\n\n self.parameters = None\n\n self.statistical_maps = None\n self.clusters = None\n self.events = None\n self.bdcs = None\n self.dataset = None\n self.grid = None\n\n self.dataset = dataset\n self.reference = reference\n self.grid = grid\n\n def instantiate(self, reference, tree):\n self.reference = reference\n self.tree = tree\n\n self.grid = self.dataset.sample_loader.get_grid(reference=self.reference)\n\n # Get truncated datasets\n self.dataset.sample_loader.truncate_datasets(self.dataset.datasets)\n self.dataset.datasets = self.dataset.sample_loader.truncated_datasets\n\n # Get cur resolution for dataset\n test_datasets = self.dataset.partition_datasets(\"test\")\n train_datasets = self.dataset.partition_datasets(\"train\")\n test_datasets.update(train_datasets)\n resolutions = [d.data.summary.high_res for dtag, d in test_datasets.items()]\n max_res = max(resolutions)\n\n # Get ref map\n self.dataset.sample_loader.get_reference(max_res)\n\n # Attach grid to\n self.map_maker.attach_grid(self.grid)\n\n # Attach grid to event table maker\n self.event_table_maker.grid = self.grid\n\n return self\n\n def clone(self, name=None, dataset=None):\n\n # Create a clone with new dataset and name\n model = PanDDAEventModelDistributed(self.statistical_model,\n self.clusterer,\n self.event_finder,\n dataset=dataset,\n reference=self.reference,\n grid=self.grid,\n bdc_calculator=self.bdc_calculator,\n statistics=self.statistics,\n map_maker=self.map_maker,\n event_table_maker=self.event_table_maker,\n cpus=self.cpus,\n tree=self.tree,\n name=name)\n\n model.tree.update({str(model.name): {\"dummy\": None}})\n\n # Attach grid to clusterer and event finder\n model.clusterer.grid = self.grid\n model.event_finder.grid = self.grid\n model.bdc_calculator.grid = self.grid\n\n return model\n\n def fit(self, samples_train, samples_test):\n\n self.parameters = self.statistical_model.fit(samples_train, samples_test)\n\n return self\n\n def evaluate_single(self, sample, dataset, ref_map):\n\n print(\"Making statistical map\")\n statistical_map = self.statistical_model.evaluate(sample)\n\n print(\"Clustering\")\n clusters = self.clusterer(dataset, statistical_map)\n\n print(\"evaluating\")\n events = self.event_finder(dataset, clusters[0], clusters[1])\n\n print(\"Finding bdcs\")\n bdcs = self.bdc_calculator(dataset, sample, ref_map, events)\n\n return statistical_map, clusters, events, bdcs\n\n def evaluate(self):\n dtags = set(self.dataset.partition_datasets(\"test\").keys()\n + self.dataset.partition_datasets(\"train\").keys()\n )\n truncated_datasets = self.dataset.sample_loader.truncated_datasets\n res = max([d.data.summary.high_res for dtag, d in self.dataset.datasets.items()])\n print(res)\n sample_loaders = {dtag: lambda d: self.dataset.sample_loader.get_sample(res, d)\n for dtag\n in dtags}\n gc.collect()\n results = jl.Parallel(n_jobs=int(self.cpus),\n verbose=10)(jl.delayed(self.evaluate_single)(sample_loaders[dtag],\n truncated_datasets[dtag],\n self.dataset.sample_loader.ref_map)\n for dtag\n in dtags)\n # with worker_client() as client:\n # results = client.map(self.evaluate_single, [(sample_loaders[dtag],\n # truncated_datasets[dtag],\n # self.dataset.sample_loader.ref_map)\n # for dtag\n # in dtags])\n\n\n # self.statistical_maps = {dtag: res[0]\n # for dtag, res\n # in zip(dtags, results)}\n self.clusters = {dtag: res[1]\n for dtag, res\n in zip(dtags, results)}\n self.events = {dtag: res[2]\n for dtag, res\n in zip(dtags, results)}\n\n self.bdcs = {dtag: res[3]\n for dtag, res\n in zip(dtags, results)}\n\n return self\n\n def criticise_single(self, sample_loader, truncated_dataset, ref_map, events, bdcs, tree):\n\n dataset_path = p.Path(tree((\"processed_datasets\", truncated_dataset.tag))[0])\n\n self.map_maker.process_single(sample_loader, truncated_dataset, ref_map, events, bdcs, dataset_path)\n\n def criticise_all(self, tree):\n # dtags = set(self.dataset.partition_datasets(\"test\").keys()\n # + self.dataset.partition_datasets(\"train\").keys()\n # )\n #\n # res = max([d.data.summary.high_res for dtag, d in self.dataset.datasets.items()])\n # sample_loaders = {dtag: lambda d: self.dataset.sample_loader.get_sample(res, d)\n # for dtag\n # in dtags}\n #\n # self.map_maker.statistical_model = self.statistical_model\n #\n # gc.collect()\n # # jl.Parallel(n_jobs=int(self.cpus),\n # # verbose=10)(jl.delayed(self.criticise_single)(sample_loaders[dtag],\n # # self.dataset.sample_loader.truncated_datasets[dtag],\n # # self.dataset.sample_loader.ref_map,\n # # self.events[dtag],\n # # self.bdcs[dtag],\n # # self.tree)\n # # for dtag\n # # in dtags)\n\n # Produce maps that are shared by iteration\n dir_path = p.Path(tree([str(self.name)])[0])\n dir_path_string = str(dir_path)\n self.map_maker.process_shell(self.dataset.sample_loader.reference,\n self.dataset.sample_loader.ref_map,\n dir_path_string)\n\n # Produce the event table\n event_table_path = dir_path / \"event_table.csv\"\n\n event_table = self.event_table_maker(self.dataset.partition_datasets(\"test\"),\n self.events,\n event_table_path)\n\n return event_table\n\n def log(self):\n log = OrderedDict()\n return log\n\n\nclass PanDDANormalModel:\n\n def __init__(self, method=\"adjusted+uncertainty\", cpus=1):\n\n self.method = method\n self.cpus = cpus\n\n self.mu = 0\n self.sigma_uncertainty = {}\n self.sigma_adjusted = 0\n\n # TODO: legacy requirement\n self.statistical_maps = PanddaStatMapList()\n\n def fit(self, samples_train, samples_test):\n\n # TODO: move into fit\n map_data_size = 0\n for dtag, sample in samples_train.items():\n map_data_size = sample.data.size()\n break\n\n characterisation_maps = [sample for dtag, sample in samples_train.items()]\n\n analysis_maps = [sample for dtag, sample in samples_test.items()]\n\n self.mu = self.fit_mu(characterisation_maps, map_data_size)\n\n self.sigma_uncertainty = self.fit_sigma_uncertainty(analysis_maps, map_data_size, cpus=self.cpus)\n\n self.sigma_adjusted = self.fit_sigma_adjusted(analysis_maps, self.sigma_uncertainty, map_data_size,\n cpus=self.cpus)\n\n def fit_mu(self, dataset_maps, map_data_size):\n \"\"\"Calculate the average map from all of the different observations\"\"\"\n print(\"\\t### Fitting mu!\")\n\n # Extract the maps to be used for averaging\n if len(dataset_maps) == 1:\n\n # Extract the map from the list\n m = dataset_maps[0]\n # Mean and median are simply the map value -- copy directly to the statistical maps\n mean_map_vals = medn_map_vals = numpy.array(m.data)\n\n else:\n\n # Chunk the points into groups - Compromise between cpu time and memory usage - ~200 dataset -> chunksize of 5000\n chunk_size = 500 * iceil(1000.0 / len(dataset_maps))\n chunk_idxs = [i for i in range(0, map_data_size, chunk_size)]\n num_chunks = len(chunk_idxs)\n\n t1 = time.time()\n\n mean_map_vals = numpy.zeros(map_data_size)\n medn_map_vals = numpy.zeros(map_data_size)\n\n for i_chunk, chunk_start in enumerate(chunk_idxs):\n status_bar_2(n=i_chunk, n_max=num_chunks)\n\n tmp_map_vals = numpy.array([m.data[chunk_start:chunk_start + chunk_size] for m in dataset_maps])\n\n # Check that the output values are the expected dimensions\n if i_chunk + 1 < num_chunks:\n assert len(tmp_map_vals) == len(dataset_maps)\n assert len(tmp_map_vals.T) == chunk_size\n\n tmp_map_means = numpy.mean(tmp_map_vals, axis=0)\n mean_map_vals[chunk_start:chunk_start + chunk_size] = tmp_map_means\n tmp_map_medns = numpy.median(tmp_map_vals, axis=0)\n medn_map_vals[chunk_start:chunk_start + chunk_size] = tmp_map_medns\n\n status_bar_2(n=num_chunks, n_max=num_chunks)\n\n t2 = time.time()\n\n mu = m.new_from_template(map_data=flex.double(mean_map_vals.flatten()),\n sparse=m.is_sparse())\n\n return mu\n\n def fit_sigma_uncertainty(self, analysis_maps, map_data_size, masked_idxs=None, mask_name=None, q_cut=1.5, cpus=1):\n \"\"\"Calculate the uncertainty in each of the different maps\"\"\"\n\n print(\"\\t### Fitting sigma_uncertainty!\")\n\n if masked_idxs is None:\n masked_idxs = flex.size_t(range(0, map_data_size))\n else:\n assert max(masked_idxs) < map_data_size, 'masked_idxs out of range of map'\n masked_idxs = flex.size_t(masked_idxs)\n\n # Extract masked map values from the average map... and sort them\n comp_vals = self.mu.data.select(masked_idxs)\n\n arg_list = []\n\n # for i_m, m in enumerate(self.dataset_maps.mask(mask_name=mask_name)):\n for i_m, m in enumerate(analysis_maps):\n\n if m.meta.map_uncertainty is not None:\n arg_list.append(None)\n continue\n\n u = UncertaintyCalculator(query_values=m.data.select(masked_idxs),\n ref_values=comp_vals)\n arg_list.append(u)\n\n t1 = time.time()\n num_to_process = len(arg_list) - arg_list.count(None)\n print('1' + ''.join(['{:<5}'.format(i) for i in range(0, num_to_process + 5, 5)])[2:])\n print(' ' * num_to_process + '|\\r', end='')\n sys.stdout.flush()\n # TODO: use joblib instead\n # map_uncertainties = easy_mp.pool_map(func=wrapper_run, args=arg_list, processes=cpus, chunksize=1)\n map_uncertainties = jl.Parallel(n_jobs=self.cpus,\n verbose=5)(jl.delayed(wrapper_run)(arg)\n for arg\n in arg_list)\n # with worker_client() as client:\n # map_uncertainties_futures = client.map(wrapper_run, arg_list)\n # map_uncertainties = client.gather(map_uncertainties_futures)\n print('|')\n\n for i_m, m in enumerate(analysis_maps):\n\n map_unc = map_uncertainties[i_m]\n\n if m.meta.map_uncertainty is not None:\n assert map_unc is None\n else:\n # TODO: remove this print\n # print(\"Adding map uncertainty for {}\".format(m.meta.tag))\n assert map_unc is not None\n m.meta.map_uncertainty = map_unc\n # TODO: Not sure why this is breaking - probably to do with futures print\n\n # return [m.meta.map_uncertainty for m in self.dataset_maps.mask(mask_name=mask_name)]\n return {m.meta.tag: m.meta.map_uncertainty for m in analysis_maps}\n\n def fit_sigma_adjusted(self, analysis_maps, uncertainties, map_data_size, cpus=1):\n\n print(\"\\t### Fitting sigma_adjusted!\")\n\n uncertainties_ordered = [uncertainties[edmap.meta.tag]\n for edmap\n in analysis_maps]\n\n self.calculate_statistical_maps(analysis_maps, uncertainties_ordered, map_data_size, cpus=self.cpus)\n\n return self.statistical_maps.sadj_map\n\n def calculate_statistical_maps(self, dataset_maps, uncertainties, map_data_size, mask_name=None, ignore_warnings=True, cpus=1):\n \"\"\"Take the sampled maps and calculate statistics for each grid point across the datasets\"\"\"\n\n # Extract the maps to be used for averaging\n\n if len(dataset_maps) == 1:\n\n self._set_statistical_maps_from_array(template_map=self.mu,\n map_array=numpy.zeros((map_data_size, 5)))\n\n return self.statistical_maps\n else:\n\n # Create statistics objects for each grid point\n if ignore_warnings:\n warnings.simplefilter('ignore', category=RuntimeWarning)\n\n # Extract the map uncertainties\n # uncertainties = [m.meta.map_uncertainty for m in dataset_maps]\n assert uncertainties.count(None) == 0, 'some maps have not got associated uncertainties'\n\n # Chunk the points into groups - Compromise between cpu time and memory usage - 1000 per cpu at 50 datasets\n chunk_size = iceil(1000.0 * cpus * 50.0 / len(dataset_maps))\n chunk_idxs = [i for i in range(0, map_data_size, chunk_size)]\n num_chunks = len(chunk_idxs)\n\n # Second level of iteration - split the first chunk level between the cpus\n chunk_size_2 = iceil(1.0 * chunk_size / cpus)\n chunk_idxs_2 = [i for i in range(0, chunk_size, chunk_size_2)]\n num_chunks_2 = len(chunk_idxs_2)\n\n t1 = time.time()\n\n # Output array of the 5 statistics for each map point\n point_statistics = numpy.zeros((map_data_size, 5))\n\n tot = 0\n for i_chunk, chunk_start in enumerate(chunk_idxs):\n status_bar_2(n=i_chunk, n_max=num_chunks)\n\n # Argument list for multiprocessing\n arg_list = []\n\n # Loop through the secondary chunks and send for multi-core processing\n for i_chunk_2, chunk_start_2 in enumerate(chunk_idxs_2):\n\n # Lower limit - always the beginning of the chunk\n l1 = chunk_start + chunk_start_2\n # Upper limit - full chunk size, limited by the larger chunk size, or by map size\n l2 = min(chunk_start + chunk_start_2 + chunk_size_2, chunk_start + chunk_size,\n map_data_size)\n\n if l1 >= l2:\n continue\n\n # Extract map values from the maps\n map_vals = [m.data[l1:l2] for m in dataset_maps]\n # Want to iterate over grid points not datasets\n map_vals = numpy.transpose(map_vals)\n assert map_vals.shape[1] == len(dataset_maps)\n\n # Create DensityStatistics object for analysis of the density variation\n arg_list.append(DensityStatistics(observations_array=map_vals, uncertainties=uncertainties))\n\n if not arg_list: continue\n\n # Calculate the statistis of the grid points\n # TODO: use joblib instead\n # tmp_point_statistics = easy_mp.pool_map(func=wrapper_run, args=arg_list, processes=cpus)\n tmp_point_statistics = jl.Parallel(n_jobs=self.cpus)(jl.delayed(wrapper_run)(arg)\n for arg\n in arg_list)\n # with worker_client() as client:\n # tmp_point_statistics_futures = client.map(wrapper_run, arg_list)\n # tmp_point_statistics = client.gather(tmp_point_statistics_futures)\n\n # Put values into the output array\n offset = 0\n for point_vals in tmp_point_statistics:\n assert point_vals.shape[1] == 5\n l1 = chunk_start + offset\n l2 = l1 + point_vals.shape[0]\n if not (point_statistics[l1:l2, :] == 0.0).all():\n print('Overwriting data?!')\n print(point_statistics[l1 - 10:l2 + 10, :])\n assert point_statistics[l1:l2, :].shape == point_vals.shape, '{} != {}'.format(\n point_statistics[l1:l2, :].shape, point_vals.shape)\n point_statistics[l1:l2, :] = point_vals\n offset += point_vals.shape[0]\n tot += offset\n\n status_bar_2(n=num_chunks, n_max=num_chunks)\n\n # Check that we've calculated the right number of things\n assert tot == map_data_size, 'tot {}, map size {}'.format(tot, map_data_size)\n\n t2 = time.time()\n\n self._set_statistical_maps_from_array(template_map=self.mu,\n map_array=point_statistics,\n map_data_size=map_data_size)\n\n def _set_statistical_maps_from_array(self, template_map, map_array, map_data_size):\n \"\"\"Set the five non-average-based statistical maps from an array\"\"\"\n\n assert map_array.shape == (map_data_size, 5)\n\n # Create the other statistical maps\n self.statistical_maps.stds_map = template_map.new_from_template(\n map_data=flex.double(map_array[:, 0].tolist()), sparse=template_map.is_sparse())\n self.statistical_maps.sadj_map = template_map.new_from_template(\n map_data=flex.double(map_array[:, 1].tolist()), sparse=template_map.is_sparse())\n self.statistical_maps.skew_map = template_map.new_from_template(\n map_data=flex.double(map_array[:, 2].tolist()), sparse=template_map.is_sparse())\n self.statistical_maps.kurt_map = template_map.new_from_template(\n map_data=flex.double(map_array[:, 3].tolist()), sparse=template_map.is_sparse())\n self.statistical_maps.bimo_map = template_map.new_from_template(\n map_data=flex.double(map_array[:, 4].tolist()), sparse=template_map.is_sparse())\n\n def evaluate(self, m):\n \"\"\"Calculate the z-map relative to the mean and std map\"\"\"\n\n assert self.method in ['none', 'adjusted', 'uncertainty', 'adjusted+uncertainty']\n uncertainty = self.sigma_uncertainty[m.meta.tag]\n\n # Check that a value has been found/supplied\n if 'uncertainty' in self.method:\n assert uncertainty is not None\n\n # Extract maps in the right sparseness\n is_sparse = m.is_sparse()\n # Extract mean values (for subtraction)\n comp_vals = self.mu.get_map_data(sparse=is_sparse)\n\n # Extract the normalisation values (for division)\n if self.method == 'none':\n norm_vals = 1.0\n # elif method == 'naive':\n # norm_vals = self.statistical_maps.stds_map.get_map_data(sparse=is_sparse)\n elif self.method == 'adjusted':\n norm_vals = self.sigma_adjusted.get_map_data(sparse=is_sparse)\n elif self.method == 'uncertainty':\n norm_vals = uncertainty\n elif self.method == 'adjusted+uncertainty':\n norm_vals = flex.sqrt(\n self.sigma_adjusted.get_map_data(sparse=is_sparse) ** 2 + uncertainty ** 2)\n else:\n raise Exception('method not found: {!s}'.format(self.method))\n\n return (m - comp_vals) * (1.0 / norm_vals)\n","sub_path":"pandda_2/pandda_analyse/event_model_distributed.py","file_name":"event_model_distributed.py","file_ext":"py","file_size_in_byte":23431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"44985950","text":"import copy\nn = int(input())\neq = list(input())\nnumbers = []\noperators = []\nfor i in range(len(eq)):\n if i%2 == 0:\n numbers.append(int(eq[i]))\n else:\n operators.append(eq[i])\n\ndef calc(numlist,oplist,idx):\n operator = oplist.pop(idx)\n if operator == '+':\n numlist[idx] += numlist.pop(idx+1)\n if operator == '-':\n numlist[idx] -= numlist.pop(idx+1)\n if operator == '*':\n numlist[idx] *= numlist.pop(idx+1)\n\n\nanswer = -float('inf')\ndef go(nums, opers, idx):\n global answer\n if idx >= len(opers):\n n, o = nums[:], opers[:] #여기도매우 중요\n while o:\n calc(n, o, 0)\n answer = max(answer, n[0])\n return\n\n go(nums, opers, idx+1)\n\n tmpn, tmpo = nums[:], opers[:] #매우중요\n calc(tmpn, tmpo, idx)\n go(tmpn, tmpo, idx+1)\n\ngo(numbers, operators, 0)\nprint(answer)\n'''\n괄호 추가하기\n괄호 안에 하나의 연산자만이 존재해야 한다. \n수식을 계산할 때는 왼 쪽 부터 순서대로 계산해야 한다. \n\n[설계]\n문제 이해가 중요하다..\n괄호를 직접 칠 필요는 없는 문제다\n순서대로 연산자를 탐색 하면서 , 해당 연산자를 수행 하면 괄호를 치는 것이고\n수행 하지 않고 다음 연산자로 넘어가면 괄호를 안치는 것이다. \n재귀함수는 \n\n재귀함수 탈출조건 : \ncount가 최초 연산자의 횟수까지 올라가면, 괄호치기가 끝났기 때문에\n남은 연산을 모두 수행한다. 그 결과를 answer와 비교한다. \n\n숫자와 연산자를 list로 따로 저장하고, \nidx를 통해 연산자에 접근한다.\n\n1) 계산을 지금 하면(괄호를 치면) calc함수에 넘겨서 해당 위치의 2개의 숫자와 연산자로 계산을 하고\n숫자 리스트와 연산자 list가 하나씩 줄어든 상태로 idx를 하나만 올려 재귀를 쏜다. idx를 올리지 않으면 다음 연산자로 자동으로 넘어가는데,\n한 괄호에 하나의 연산자만 잇어야 하기 때문에 괄호를 쳤다면 다다음 연산자로 가야하기 때문에 idx를 하나 올려줘야한다.\n\n2) 계산을 하지 않으면(괄호를 안치면) 그냥 숫자 list, 연산자 list그대로 두고 idx만 하나 올린다. 연산을 안했으니 하나 올려서 다음 선택을 하면 된다.\n\n연산 함수 : 숫자리스트, 연산자 리스트, 연산할 idx 전달받음\n연산자 list 의 해당idx를 pop하고\n숫자 리스트의 idx+1를 pop하고 idx와 곱해서 idx를 갱신한다.\n그러면 숫자 list가 해당위치만 계산되어 하나 줄어들고 연산자 list도 해당 idx만 없어진다.\n\n9\n3+8*7-9*2\n\n괄호치지 않은 나머지 연산을 할 땐 idx를 0으로 두고 계속 연산함수에 넘기면 된다.\n\n'''","sub_path":"BeakjoonOJ_Solved/16637.py","file_name":"16637.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"36764476","text":"#################################\n##### Name: Yash Kamat ##########\n##### Uniqname: ykamat ##########\n#################################\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport secrets as secrets# file that contains your API key\n\n# Global Variables\n# CACHE_PATH = '/Users/yashkamat/Development/si507/projects/project2/Project2Winter2021/cache.json'\n# API_CACHE_PATH = '/Users/yashkamat/Development/si507/projects/project2/Project2Winter2021/api_cache.json'\n\nCURR_CACHE = {}\nCURR_API_CACHE = {}\n\nHOME_URL = 'https://www.nps.gov'\n\ndef save_cache(cache_dic, path):\n\n \"\"\"\n Saves a specific dictionary to local directory as cache.\n\n Parameters\n ----------\n cache_dic: dict\n The dictionary to be cached.\n\n path: string\n The path where the dictionary should be cached.\n\n Returns\n -------\n None\n \"\"\"\n\n with open(path, 'w') as outfile:\n cache = json.dump(cache_dic, outfile)\n\ndef load_cache(path):\n\n \"\"\"\n Returns a dictionary representation of a local cache file.\n\n Parameters\n ----------\n path: string\n The path to the locally saved cache file.\n\n Returns\n -------\n cache_dic: dict\n Dictionary representation of the loaded cache.\n \"\"\"\n\n with open(path) as json_file:\n cache_dic = json.load(json_file)\n return cache_dic\n\ndef get_url(url,cache_dic):\n\n \"\"\"\n Fetches a URL if its repsonse is not in the cache.\n If the URL is in the current cache, it retrieves the response from it.\n\n Parameters\n ----------\n url: string\n The requested URL to be fetched.\n cache_dic: dict\n Dictionary representation of the current cache.\n\n Returns\n -------\n cache_dic[url]: string\n String representation of the response text for the requested url.\n \"\"\"\n\n if url in cache_dic.keys():\n print('Using cache')\n else:\n print(\"Fetching\")\n cache_dic[url] = requests.get(url).text\n return cache_dic[url]\n\ndef get_api(zipcode,cache_dic,params):\n\n \"\"\"\n Makes a call to the MapQuest API if the requested zipcode doesn't exist in the local cache.\n If zipcode exists in local cache, retrieves the API response from cache.\n\n Parameters\n ----------\n zipcode: string\n The requested zipcode to be searched.\n cache_dic: dict\n Current API cache represented as a dictionary.\n params:\n Parameters for MapQuest API request.\n\n Returns\n -------\n cache_dic[zipcode]: JSON representation of API reqest repsonse.\n \"\"\"\n\n if zipcode in cache_dic.keys():\n print('Using cache')\n else:\n print(\"Fetching\")\n cache_dic[zipcode] = requests.get('http://www.mapquestapi.com/search/v2/radius', params=params).text\n\n return cache_dic[zipcode]\n\nclass NationalSite:\n '''a national site\n\n Instance Attributes\n -------------------\n category: string\n the category of a national site (e.g. 'National Park', '')\n some sites have blank category.\n \n name: string\n the name of a national site (e.g. 'Isle Royale')\n\n address: string\n the city and state of a national site (e.g. 'Houghton, MI')\n\n zipcode: string\n the zip-code of a national site (e.g. '49931', '82190-0168')\n\n phone: string\n the phone of a national site (e.g. '(616) 319-7906', '307-344-7381')\n '''\n\n def __init__(self,category=None,name=None,address=None,zipcode=None,phone=None):\n self.category = category\n self.name = name\n self.address = address\n self.zipcode = zipcode\n self.phone = phone\n\n def info(self):\n return f'{self.name} ({self.category}): {self.address} {self.zipcode}'\n\ndef build_state_url_dict():\n ''' Make a dictionary that maps state name to state page url from \"https://www.nps.gov\"\n\n Parameters\n ----------\n None\n\n Returns\n -------\n dict\n key is a state name and value is the url\n e.g. {'michigan':'https://www.nps.gov/state/mi/index.htm', ...}\n '''\n\n response = requests.get(HOME_URL).text\n soup = BeautifulSoup(response,'html.parser')\n state_list = soup.find('ul',class_='dropdown-menu SearchBar-keywordSearch').find_all('li')\n\n links = {}\n\n for item in state_list:\n key = str(item.text).lower()\n value = item.find('a').get('href')\n links[key] = HOME_URL + value\n\n return links\n\ndef get_site_instance(site_url):\n '''Make an instances from a national site URL.\n \n Parameters\n ----------\n site_url: string\n The URL for a national site page in nps.gov\n \n Returns\n -------\n instance\n a national site instance\n '''\n\n response = get_url(site_url,CURR_CACHE)\n soup = BeautifulSoup(response, 'html.parser')\n\n # Category\n try:\n category = soup.find(\"span\", class_=\"Hero-designation\").text.strip()\n except:\n category = ''\n\n # Name\n try:\n name = soup.find(\"a\", class_=\"Hero-title\").text.strip()\n except:\n name = ''\n\n # Address\n try:\n city = soup.find(\"span\", itemprop=\"addressLocality\").text.strip()\n except:\n city = ''\n\n try:\n state = soup.find(\"span\", itemprop='addressRegion').text.strip()\n except:\n state = ''\n address = f'{city}, {state}'\n\n # Zipcode\n try:\n zipcode = soup.find(\"span\", itemprop='postalCode').text.strip()\n except:\n zipcode = ''\n\n # Phone\n try:\n phone = soup.find(\"span\", class_='tel').text.strip()\n except:\n phone = ''\n\n return NationalSite(category=category, name=name,address=address,zipcode=zipcode,phone=phone)\n\ndef get_sites_for_state(state_url):\n '''Make a list of national site instances from a state URL.\n \n Parameters\n ----------\n state_url: string\n The URL for a state page in nps.gov\n \n Returns\n -------\n list\n a list of national site instances\n '''\n sites_list = []\n home_url = 'https://www.nps.gov'\n\n response = requests.get(state_url)\n soup = BeautifulSoup(response.text,'html.parser')\n\n for ref in soup.find('ul', id='list_parks').find_all('h3'):\n site_url = home_url+ref.find('a')['href']\n sites_list.append(get_site_instance(site_url))\n\n return sites_list\n\ndef get_nearby_places(site_object):\n '''Obtain API data from MapQuest API.\n \n Parameters\n ----------\n site_object: object\n an instance of a national site\n \n Returns\n -------\n dict\n a converted API return from MapQuest API\n '''\n\n params = {'key': secrets.API_KEY,\n 'radius': '10',\n 'origin': site_object.zipcode,\n 'maxMatches': '10',\n 'ambiguities': 'ignore',\n 'outFormat': 'json'}\n\n response = get_api(zipcode=site_object.zipcode, cache_dic=CURR_API_CACHE, params=params)\n return json.loads(response)\n\ndef print_sites(site_list):\n\n \"\"\"\n Prints a formatted list of NationalSite objects.\n\n Parameters\n ----------\n site_list: list\n List of NationalSite objects.\n\n Returns\n -------\n None.\n \"\"\"\n\n for site in site_list:\n pos = site_list.index(site)\n print(f'[{pos+1}] {site.info()}')\n\ndef print_nearby(api_dict):\n\n \"\"\"\n Prints a formatted list of 'nearby locations' from an API response.\n\n Parameters\n ----------\n api_dict: dict\n Dictionary represenation of an API reponse for locations near a specific zipcode.\n\n Returns\n -------\n None.\n \"\"\"\n\n for result in api_dict['searchResults']:\n name = result['name']\n address = result['fields']['address']\n category = result['fields']['group_sic_code_name_ext']\n city = result['fields']['city']\n if (len(name) > 0) and (len(category) > 0) and (len(address) > 0):\n print(f'- {name} ({category}): {address}, {city}')\n else:\n if (len(name) == 0):\n name = \"no name\"\n if (len(category) == 0):\n category = \"no category\"\n if (len(address) == 0):\n address = \"no address\"\n if (len(city) == 0):\n city = 'no city'\n print(f'- {name} ({category}): {address}, {city}')\n\ndef user_interface():\n\n \"\"\"\n Runs the user facing loop to fetch sites or nearby locations for specific states/sites.\n Has no parameters or returns.\n\n \"\"\"\n\n try:\n CURR_CACHE = load_cache(CACHE_PATH)\n except:\n CURR_CACHE = {}\n\n try:\n CURR_API_CACHE = load_cache(API_CACHE_PATH)\n except:\n CURR_API_CACHE = {}\n\n state_urls = build_state_url_dict()\n\n while True:\n state = input('Enter a state name (e.g. Michigan, michigan) or \"exit\": ')\n\n if state == \"exit\":\n quit()\n\n elif state.lower() not in state_urls.keys():\n print('[Error] Enter proper state name')\n\n else:\n s_list = get_sites_for_state(state_urls[state.lower()])\n print('\\n-------------------------')\n print(f'List of national sites in {state}')\n print('-------------------------')\n print_sites(s_list)\n\n while True:\n choice = input('Choose the number for detail search or \"exit\" or \"back\": ')\n\n if choice == \"exit\":\n quit()\n\n elif choice == \"back\":\n break\n\n elif choice.isnumeric() == True:\n if(int(choice) <= (len(s_list)+1)):\n print('\\n-------------------------')\n print(f'Places near {s_list[(int(choice) - 1)].name}')\n print('-------------------------')\n print_nearby(get_nearby_places(s_list[(int(choice) - 1)]))\n print('')\n else:\n print('\\n[Error] Invalid input\\n-------------------------')\n else:\n print('\\n[Error] Invalid input\\n-------------------------')\n\nif __name__ == \"__main__\":\n user_interface()","sub_path":"proj2_nps.py","file_name":"proj2_nps.py","file_ext":"py","file_size_in_byte":10064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"495520392","text":"from torch import nn\nfrom torch.nn.modules.activation import GELU\nimport torch \n\nclass Generator(nn.Module):\n def __init__(self, latent_dim: int = 100):\n super(Generator, self).__init__()\n\n self.layers = nn.Sequential(\n Up(latent_dim,75),\n Up(75, 50),\n Up(50, 25),\n Up(25,20),\n Up(20, 15),\n Up(15, 10),\n Up(10, 5),\n Up(5,3)\n )\n\n def forward (self, x):\n return self.layers(x)\n\n\n\n\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, mid_channels=None):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(mid_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.double_conv(x)\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, bilinear=True):\n super().__init__()\n\n # if bilinear, use the normal convolutions to reduce the number of channels\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n else:\n self.up = nn.ConvTranspose2d(in_channels , in_channels // 2, kernel_size=2, stride=2)\n self.conv = DoubleConv(in_channels, out_channels)\n\n\n def forward(self,x):\n x = self.up(x)\n return self.conv(x)\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"424634993","text":"# 418. Integer to Roman\n# Description\n# Given an integer, convert it to a roman numeral.\n#\n# The number is guaranteed to be within the range from 1 to 3999.\n#\n# Have you met this question in a real interview?\n# Clarification\n# What is Roman Numeral?\n#\n# https://en.wikipedia.org/wiki/Roman_numerals\n# https://zh.wikipedia.org/wiki/罗马数字\n# http://baike.baidu.com/view/42061.htm\n# Example\n# 4 -> IV\n#\n# 12 -> XII\n#\n# 21 -> XXI\n#\n# 99 -> XCIX\n#\n# more examples at: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm\n#\n#\n# 418. Integer to Roman\n# Given an integer, convert it to a roman numeral.\n#\n# The number is guaranteed to be within the range from 1 to 3999.\n#\n# Example\n# 4 -> IV\n#\n# 12 -> XII\n#\n# 21 -> XXI\n#\n# 99 -> XCIX\n#\n# more examples at: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm\n\nclass Solution:\n\t\"\"\"\n\t@param n: The integer\n\t@return: Roman representation\n\t\"\"\"\n\t\n\tdef intToRoman (self, n):\n\t\t# write your code here\n\t\t\n\t\tnum = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n\t\t# for integer, we start from large to small\n\t\t\n\t\t\n\t\tnum1 = [\"I\", \"X\", \"C\", \"M\"]\n\t\tnum5 = [\"V\", \"L\", \"D\"]\n\t\t\n\t\t# from large to small\n\t\tresult = \"\"\n\t\tval = 0\n\t\tres = n\n\t\tfor i in range (len (num1) - 1, -1, -1):\n\t\t\tval = res // num [num1 [i]]\n\t\t\tres = res % num [num1 [i]]\n\t\t\t\n\t\t\t# check if val is 0, 1-4,5, or 6-8, 9\n\t\t\t# I, II, III,IV, V, VI, VII,VIII,XI X\n\t\t\tif val > 0 and val < 4:\n\t\t\t\t# 1, 2,3\n\t\t\t\tfor j in range (val):\n\t\t\t\t\tresult += num1 [i]\n\t\t\telif val == 4:\n\t\t\t\tresult += num1 [i]\n\t\t\t\tresult += num5 [i]\n\t\t\telif val == 5:\n\t\t\t\tresult += num5 [i]\n\t\t\telif val > 5 and val < 9:\n\t\t\t\t# 6, 7 , 8\n\t\t\t\tresult += num5 [i]\n\t\t\t\tfor j in range (val - 5):\n\t\t\t\t\tresult += num1 [i]\n\t\t\telif val == 9:\n\t\t\t\tresult += num1 [i]\n\t\t\t\tresult += num1 [i + 1]\n\t\t\telif val == 0:\n\t\t\t\tpass\n\t\t\n\t\treturn result\n\n# test\nassert Solution().intToRoman(99) == \"XCIX\"\n\n\n# complexity\n\n# time O(n), space O(n)","sub_path":"Algorithm/Python/HighFrequency/IntegerToRoman.py","file_name":"IntegerToRoman.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"497099085","text":"from flask import Flask, render_template, jsonify, request\nimport sqlite3\nfrom os.path import isfile\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n if isfile('database.db') == False:\n exec(open('initdb.py').read())\n return render_template('newmovie.html')\n\n@app.route('/newmovie', methods = ['POST'])\ndef newmovie():\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n \n title = request.form['title']\n year = request.form['year']\n \n try:\n cursor.execute('INSERT INTO movies (title,year) VALUES (?,?)', (title,year))\n connection.commit()\n message = 'Success!'\n except:\n connection.rollback()\n message = 'Oops!'\n finally:\n connection.close()\n return render_template('result.html', message = message)\n\n@app.route('/movies')\ndef movies():\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM movies')\n cinematography = cursor.fetchall()\n connection.close()\n return jsonify(cinematography)\n\n@app.route('/search')\ndef serach():\n partial = request.args.get('title')\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM movies WHERE title LIKE \"%{}%\" COLLATE NOCASE'.format(partial))\n foundit = cursor.fetchall()\n connection.close()\n return jsonify(foundit)\n\n@app.route('/favicon.ico')\ndef favicon():\n return app.send_static_file('favicon.ico')\n \napp.run(debug = True)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"361403349","text":"import re\n\nws_re = re.compile(r\"\\s+\") # regex for white spaces\ncomment_re = re.compile(r\"//.*\\n\") # regex for normal comments\nmultiline_comment_re = re.compile(r\"/\\**.+?\\*/\", re.DOTALL) # multiline comment\nkeyword_re = re.compile(r\"(class|constructor|function|method|field|static|var\"\n r\"|int|char|boolean|void|true|false|null|this|let|do|\"\n r\"if|else|while|return)\") # keyword regex\nsymbol_re = re.compile(r\"(\\{|\\}|\\(|\\)|\\[|\\]|\\.|,|;|\\+|-|\\*|/|&|\\||<|>|=|~)\")\nint_re = re.compile(r\"(\\d{1,5})\") # technically we allow int with 1-5 digits\nstring_re = re.compile(r\"\\\"([^\\\"]*)\\\"\")\nidentifier_re = re.compile(r\"^([a-zA-Z_][a-zA-Z_0-9]*)\")\n\ntokens = {\"keyword\": keyword_re, \"symbol\": symbol_re,\n \"stringConstant\": string_re, \"integerConstant\": int_re,\n \"identifier\": identifier_re} # map regex and types for O(1) access\nlookup_order = [\"keyword\", \"symbol\", \"stringConstant\", \"integerConstant\",\n \"identifier\"] # sets iteration order on above map\n\n'''\nTokenizes a given input file by the Jack language specification.\nThe entire file is read upon initialization, comments and spaces are removed.\nEach advance() call gets the next matching token from the beginning of the lines\nleft so far.\n'''\nclass JackTokenizer:\n # Constructor\n def __init__(self, file):\n with open(file, \"r\") as f:\n self.__lines = f.read() # read entire file\n self.__lines = comment_re.sub(\"\", self.__lines) # remove line comments\n self.__lines = ws_re.sub(\" \", self.__lines) # remove whitespaces\n self.__lines = multiline_comment_re.sub(\"\", self.__lines).strip()\n self.__EOF = False\n self.token = \"\" # current token literal\n self.tokenType = \"\" # current token type (keyword\\symbol\\const\\etc)\n\n '''\n return: True if there are more tokens to read, False otherwise.\n '''\n def has_more_tokens(self):\n return not self.__EOF\n\n '''\n Advances the token to the next one up the line, and updates the remaining\n tokens (self.__lines) to be read.\n '''\n def advance(self):\n if not self.__EOF and len(self.__lines) > 0: # still have valid input\n for token in lookup_order: # iterate by selected order\n regex = tokens[token]\n m = regex.match(self.__lines)\n if m: # found our next token\n self.token = m.group(1) # get token\n self.tokenType = token # get token type\n # save index = end of match + 1 for string tokens for the \"\n index = m.end(1) + (1 if token == \"stringConstant\" else 0)\n self.__lines = self.__lines[index:].strip() # update\n return\n self.__EOF = True # error (no regex matched)\n \n","sub_path":"Project10/JackTokenizer.py","file_name":"JackTokenizer.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"311972640","text":"# This is the instrument-specific file for the PS4000 series of instruments.\n# Code is adapted from pico-python by Andreas Amrein .\n#\n# pico-python is Copyright (c) 2013-2014 By:\n# Colin O'Flynn \n# Mark Harfouche \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#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nThis is the low level driver file for a specific Picoscope.\n\nBy this, I mean if parameters want to get passed as strings, they should be\nhandled by PSBase\nAll functions here should take things as close to integers as possible, the\nonly exception here is for array parameters. Array parameters should be passed\nin a pythonic way through numpy since the PSBase class should not be aware of\nthe specifics behind how the clib is called.\n\nThe functions should not have any default values as these should be handled\nby PSBase.\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport math\n# to load the proper dll\nimport platform\n\n# Do not import or use ill definied data types\n# such as short int or long\n# use the values specified in the h file\n# float is always defined as 32 bits\n# double is defined as 64 bits\nfrom ctypes import byref, POINTER, create_string_buffer, c_float, \\\n c_int16, c_int32, c_uint32, c_uint16, c_void_p\nfrom ctypes import c_int32 as c_enum\n\nfrom equipment.picotech.picoscope.picobase import _PicoscopeBase\n\nclass PS4000(_PicoscopeBase):\n \"\"\"The following are low-level functions for the PS4000\"\"\"\n\n LIBNAME = \"ps4000\"\n# LIBNAME = \"C:\\\\Users\\\\aamrein\\\\Code\\\\foundry_scope\\\\equipment\\\\picotech\\\\ps4000\"\n\n NUM_CHANNELS = 2\n CHANNELS = {\"A\": 0, \"B\": 1, \"MaxChannels\": 2}\n\n CHANNEL_RANGE = [\n # {\"rangeV\":20E-3, \"apivalue\":1, \"rangeStr\":\"20 mV\"},\n {\"rangeV\":50E-3, \"apivalue\":2, \"rangeStr\":\"50 mV\"},\n {\"rangeV\":100E-3, \"apivalue\":3, \"rangeStr\":\"100 mV\"},\n {\"rangeV\":200E-3, \"apivalue\":4, \"rangeStr\":\"200 mV\"},\n {\"rangeV\":500E-3, \"apivalue\":5, \"rangeStr\":\"500 mV\"},\n {\"rangeV\":1.0, \"apivalue\":6, \"rangeStr\":\"1 V\"},\n {\"rangeV\":2.0, \"apivalue\":7, \"rangeStr\":\"2 V\"},\n {\"rangeV\":5.0, \"apivalue\":8, \"rangeStr\":\"5 V\"},\n {\"rangeV\":10.0, \"apivalue\":9, \"rangeStr\":\"10 V\"},\n {\"rangeV\":20.0, \"apivalue\":10, \"rangeStr\":\"20 V\"},\n ]\n\n\n CHANNEL_COUPLINGS = {\"DC\": 1, \"AC\": 0}\n\n #has_sig_gen = True\n WAVE_TYPES = {\"Sine\": 0, \"Square\": 1, \"Triangle\": 2,\n \"RampUp\": 3, \"RampDown\": 4, \"DCVoltage\": 5}\n \n TIME_UNITS = {\"FS\":0, \"PS\":1, \"NS\":2, \"US\":3, \"MS\":4, \"S\":5}\n\n MAX_VALUE = 32764\n MIN_VALUE = -32764\n\n MAX_TIMEBASES = 19\n \n UNIT_INFO_TYPES = {\"DriverVersion\" : 0x0,\n \"USBVersion\" : 0x1,\n \"HardwareVersion\" : 0x2,\n \"VarianInfo\" : 0x3,\n \"BatchAndSerial\" : 0x4,\n \"CalDate\" : 0x5,\n \"KernelVersion\" : 0x6}\n \n channelBuffersPtr = [c_void_p(), c_void_p()]\n channelBuffersLen = [0, 0]\n \n \n SIGGEN_TRIGGER_TYPES = {\"Rising\": 0, \"Falling\": 1,\n \"GateHigh\": 2, \"GateLow\": 3}\n SIGGEN_TRIGGER_SOURCES = {\"None\": 0, \"ScopeTrig\": 1, \"AuxIn\": 2,\n \"ExtIn\": 3, \"SoftTrig\": 4, \"TriggerRaw\": 5}\n\n def __init__(self, serialNumber=None, connect=True):\n \"\"\"Load DLL etc\"\"\"\n if platform.system() == 'Linux':\n from ctypes import cdll\n self.lib = cdll.LoadLibrary(\"lib\" + self.LIBNAME + \".so\")\n else:\n from ctypes import windll\n self.lib = windll.LoadLibrary(self.LIBNAME)\n \n super(PS4000, self).__init__(serialNumber, connect)\n\n def _lowLevelOpenUnit(self, sn):\n c_handle = c_int16()\n if sn is not None:\n raise ValueError(\"PS4000 doesn't allow to be opened by serial number\")\n\n m = self.lib.ps4000OpenUnit(byref(c_handle))\n \n# print('Scope handle number: '+ str(c_handle.value))\n \n self.checkResult(m)\n self.handle = c_handle.value # handle number \n self.suggested_time_units = self.TIME_UNITS[\"NS\"]\n\n def _lowLevelCloseUnit(self):\n m = self.lib.ps4000CloseUnit(c_int16(self.handle))\n self.checkResult(m)\n print(\"PicoScope 4000 closed.\")\n \n def _lowLevelSetChannel(self, chNum, enabled, coupling, VRange, VOffset,\n BWLimited):\n # VOffset and BWLimited are unused \n m = self.lib.ps4000SetChannel(c_int16(self.handle), c_enum(chNum),\n c_int16(enabled), c_enum(coupling),\n c_enum(VRange))\n# VRangeInfo = str(self.CHANNEL_RANGE[VRange-2].get(\"rangeV\"))\n# print(\"Set voltage range to: [-\" +VRangeInfo + \"V, \" + VRangeInfo + \"V]\")\n self.checkResult(m)\n \n def _lowLevelStop(self):\n m = self.lib.ps4000Stop(c_int16(self.handle))\n self.checkResult(m)\n \n def _lowLevelGetUnitInfo(self, info):\n s = create_string_buffer(256)\n requiredSize = c_int16(0)\n\n m = self.lib.ps4000GetUnitInfo(c_int16(self.handle), byref(s),\n c_int16(len(s)), byref(requiredSize),\n c_enum(info))\n self.checkResult(m)\n if requiredSize.value > len(s):\n s = create_string_buffer(requiredSize.value + 1)\n m = self.lib.ps4000GetUnitInfo(c_int16(self.handle), byref(s),\n c_int16(len(s)),\n byref(requiredSize), c_enum(info))\n self.checkResult(m)\n\n # should this bee ascii instead?\n # I think they are equivalent...\n return s.value.decode('utf-8')\n\n def _lowLevelFlashLed(self, times):\n m = self.lib.ps2000_flash_led(c_int16(self.handle))\n self.checkResult(m)\n\n def _lowLevelSetSimpleTrigger(self, enabled, trigsrc, threshold_adc,\n direction, delay, timeout_ms): \n \n #TODO: Fix 'auto' which is where trigger occurs in block. Delay is not used\n \n m = self.lib.ps2000_set_trigger(\n c_int16(self.handle), c_enum(trigsrc), c_int16(threshold_adc),\n c_enum(direction), c_int16(0), c_int16(timeout_ms))\n self.checkResult(m)\n \n def _lowLevelRunBlock(self, numPreTrigSamples, numPostTrigSamples,\n timebase, oversample, segmentIndex):\n timeIndisposedMs = c_int32()\n m = self.lib.ps4000RunBlock(\n c_int16(self.handle), c_uint32(numPreTrigSamples),\n c_uint32(numPostTrigSamples), c_uint32(timebase),\n c_int16(oversample), byref(timeIndisposedMs),\n c_uint16(segmentIndex), c_void_p(), c_void_p())\n self.checkResult(m)\n# print(\"RunBlock info\")\n# print(\"handle\", self.handle, \"numPreTrigSamples\", numPreTrigSamples, \"numPostTrigSamples\", numPostTrigSamples)\n# print(\"timbase\", timebase, \"oversample\", oversample, \"timeIndisposedMs\", timeIndisposedMs.value, \"segmentIndex\", segmentIndex )\n return timeIndisposedMs.value\n\n def _lowLevelIsReady(self):\n ready = c_int16()\n m = self.lib.ps4000IsReady(c_int16(self.handle), byref(ready))\n self.checkResult(m)\n if ready.value:\n return True\n else:\n return False\n \n def _lowLevelGetTimebase(self, tb, noSamples, oversample, segmentIndex):\n \"\"\" Return (timeIntervalSeconds, maxSamples). \"\"\"\n maxSamples = c_int32()\n sampleRate = c_float() # [ns]\n\n m = self.lib.ps4000GetTimebase2(c_int16(self.handle), c_uint32(tb),\n c_uint32(noSamples), byref(sampleRate),\n c_int16(oversample), byref(maxSamples),\n c_uint16(segmentIndex))\n self.checkResult(m)\n\n return (sampleRate.value / 1.0E9, maxSamples.value)\n\n def getTimeBaseNum(self, sampleTimeS):\n \"\"\" Sample time in seconds to timebase as int for API calls. \"\"\"\n maxSampleTime = (((2 ** 30 - 1) - 2) / 31.25E6)\n if sampleTimeS < 64E-9:\n # Low\n timebase = math.floor(math.log(sampleTimeS * 250E6, 2))\n timebase = max(timebase, 0)\n else:\n # High (max 2^30-1)\n if sampleTimeS > maxSampleTime:\n sampleTimeS = maxSampleTime\n\n timebase = math.floor((sampleTimeS * 31.25E6) + 2)\n\n # is this cast needed?\n timebase = int(timebase)\n# print(\"timebase, sampleTimeS\", timebase, sampleTimeS)\n return timebase\n \n def getTimestepFromTimebase(self, timebase):\n \"\"\" Return sampling time as seconds. \"\"\"\n if timebase < 4:\n # Low\n dt = 2. ** timebase / 250E6\n else:\n # High\n dt = (timebase - 2.) / 31.25E6\n return dt\n \n \n def _lowLevelSetDataBuffer(self, channel, data, downSampleMode, segmentIndex):\n \"\"\"\n data should be a numpy array.\n\n Be sure to call _lowLevelClearDataBuffer\n when you are done with the data array\n or else subsequent calls to GetValue will still use the same array.\n\n segmentIndex is unused, but required by other versions of the API (eg PS5000a)\n\n \"\"\"\n dataPtr = data.ctypes.data_as(POINTER(c_int16))\n numSamples = len(data)\n\n m = self.lib.ps4000SetDataBuffer(c_int16(self.handle), c_enum(channel),\n dataPtr, c_int32(numSamples))\n self.checkResult(m)\n\n def _lowLevelClearDataBuffer(self, channel, segmentIndex):\n self.channelBuffersPtr[channel] = c_void_p()\n self.channelBuffersLen[channel] = 0\n \n def _lowLevelGetValues(self, numSamples, startIndex, downSampleRatio,\n downSampleMode, segmentIndex):\n numSamplesReturned = c_uint32()\n numSamplesReturned.value = numSamples\n overflow = c_int16()\n m = self.lib.ps4000GetValues(\n c_int16(self.handle), c_uint32(startIndex),\n byref(numSamplesReturned), c_uint32(downSampleRatio),\n c_enum(downSampleMode), c_uint16(segmentIndex),\n byref(overflow))\n self.checkResult(m)\n return (numSamplesReturned.value, overflow.value)\n\n def _lowLevelSetSigGenBuiltInSimple(self, offsetVoltage, pkToPk, waveType,\n frequency, shots, triggerType,\n triggerSource):\n m = self.lib.ps2000_set_sig_gen_built_in(\n c_int16(self.handle),\n c_int32(int(offsetVoltage * 1000000)),\n c_int32(int(pkToPk * 1000000)),\n c_int16(waveType),\n c_float(frequency), c_float(frequency),\n c_float(0), c_float(0), c_enum(0), c_uint32(0))\n self.checkResult(m)\n","sub_path":"equipment/picotech/picoscope/ps4000.py","file_name":"ps4000.py","file_ext":"py","file_size_in_byte":12552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"137966835","text":"import unittest\nimport os\nfrom Sheet_Lib import *\n\n\nclass TestSheetLib(unittest.TestCase):\n \n @classmethod\n def setUp(self):\n self.heading = \"\"\n self.date = \"\"\n self.headingList = []\n self.showSheet = []\n\n # Piping\n self.error_read, self.error_write = os.pipe()\n os.dup2(self.error_write, 2)\n\n self.stdout_read, self.stdout_write = os.pipe()\n sys.stdout = self.stdout_write\n\n self.stdin_read, self.stdin_write = os.pipe()\n os.dup2(self.stdin_write, 0)\n\n # Open file.\n self.PATH = '/resources/show sheets/'\n self.DIR = os.getcwd()\n os.chdir(self.DIR + self.PATH)\n self.file = open('lhShow.csv', 'r')\n\n # Read scene line.\n self.heading = self.file.readline()\n self.headingList = self.heading.split(\",\")\n self.date = self.headingList[0].strip()\n\n # Read blank lines\n for i in range(0, 5):\n self.file.readline()\n\n for i in self.file:\n l = i.split(',')\n self.showSheet.append(l)\n\n self.file.close()\n\n def test_get_column(self):\n\n # Check if column exits and correct.\n self.assertEqual(get_column(\"Lone Rider\", self.headingList,\n self.showSheet),\n ['', '', '', '', 'Lone Rider', '', '', '', '', '',\n '', '', '', '', '', '', '', '', '', '', '',\n 'Warm Up 1', 'Warm Up 2', '', ''])\n\n # Check for column that doesnt exist\n get_column(\"Not Real\", self.headingList,\n self.showSheet)\n\n error_string = os.read(self.error_read, 100)\n stdin_string = os.read(self.stdin_read, 100)\n #stdout_string = os.read(self.stdout_read, 100)\n self.assertEqual(error_string, 'Could not find column \"Not Real\"!')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Python Examples/sheet_lib_test.py","file_name":"sheet_lib_test.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"180179530","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup\nuser_agent='Mozilla/5.0 (compatible;MSIE 5.5;Window NT)'\nheaders={'User-Agent':user_agent}\nr=requests.get('http://seputu.com/',headers=headers)\n# print(r.text)\n#获取标题,章节\nsoup=BeautifulSoup(r.text,'html.parser',from_encoding='utf-8')\ncontent=[]\nfor mulu in soup.find_all(class_=\"mulu\"):\n h2=mulu.find('h2')\n if h2!=None:\n h2_titile=h2.string\n list=[]\n # print(h2_titile)\n for a in mulu.find(class_='box').find_all('a'):#获取所有a的标记中url和章节内容\n href=a.get('href')\n box_title=a.get('title')\n print(href,box_title)\n list.append({'href':href,'box_title':box_title})\n content.append({'title':h2_titile,'content':list})\nwith open('seputu.json','w') as fp:\n json.dump(content,fp,indent=4).encoding('utf-8')\n\n\n'''\n 出现:UserWarning: You provided Unicode markup but also provided a value for from_encoding. \n Your from_encoding will be ignored.warnings.warn\n (\"You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored.\")\n'''\n","sub_path":"ch05/5_1.py","file_name":"5_1.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"273421584","text":"import random\n\n\nrandom_number = random.randint(0, 11)\n\n\ndef number_game():\n input_number = int(input(\"guess the numeber between 0 to 10 \\n\"))\n\n if input_number == random_number:\n print(\"Correct!\")\n\n else:\n print(\"Wrong\")\n number_game()\n\n\nnumber_game()\n","sub_path":"Games (Test Fase)/TestEnv2.py","file_name":"TestEnv2.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"282015720","text":"\"\"\"\nStudent 1 : Guy Hassan\nID 1:307845032\nStudent 2 : Yahav Mizrahi\nID 2: 305759185\nStudent 3 : Yinon Hirari\nID 3 : 203409024\n\"\"\"\nimport unittest\nimport Feature_Sport_Data\nimport LocalData\nfrom mock import patch\nimport re\nfrom datetime import date\n\n\nclass TDD_Sport_Data(unittest.TestCase):\n @patch('Feature_Sport_Data.get_data_first_feature')\n def mockConnectionFirstFeature(self, mock):\n \"\"\"\n :param mock: Data of feature 1\n :return: func mock\n \"\"\"\n mock.return_value = LocalData.first_feature_data\n return mock()\n\n @patch('Feature_Sport_Data.get_data_second_feature')\n def mockConnectionSecondFeature(self, mock):\n \"\"\"\n :param mock:Data of feature 2\n :return: func mock\n \"\"\"\n mock.return_value = LocalData.second_feature_data\n return mock()\n\n # --------------------------Tests First Feature------------------------------------------\n @patch('Feature_Sport_Data.get_data_first_feature')\n def test_WinnerNameNotNone(self, mock):\n \"\"\"\n Test 1: Check if the winner name team not None.\n \"\"\"\n listofdata = self.mockConnectionFirstFeature()\n for i in range(len(listofdata)):\n self.assertIsNotNone(listofdata[i]['Winner Of League'])\n\n @patch('Feature_Sport_Data.get_data_first_feature')\n def test_StartDateSmallerThanEndDate(self, mock):\n \"\"\"\n Test 2: Check if the start date of the season befor the end date.\n \"\"\"\n listofdata = self.mockConnectionFirstFeature()\n for i in range(len(listofdata)):\n self.assertLess(listofdata[i]['Start Of Season'], listofdata[i]['End Of Season'])\n\n @patch('Feature_Sport_Data.get_data_first_feature')\n def test_AmountOfMatchIsSorted(self, mock):\n \"\"\"\n Test 3: Check Sorted amount of match.\n \"\"\"\n listofdata = self.mockConnectionFirstFeature()\n for i in range(len(listofdata)):\n for j in range(i + 1, len(listofdata)):\n self.assertLessEqual(listofdata[i]['Amount Of Match'], listofdata[j]['Amount Of Match'],\n 'The list is not sorted')\n\n @patch('Feature_Sport_Data.get_data_first_feature')\n def test_NameOfCountryIsUnique(self, mock):\n \"\"\"\n Test 4: The league name appears once.\n \"\"\"\n listofdata = self.mockConnectionFirstFeature()\n for i in range(len(listofdata)):\n for j in range(i + 1, len(listofdata)):\n self.assertNotEqual(listofdata[i]['Name Country'], listofdata[j]['Name Country'])\n\n @patch('Feature_Sport_Data.get_data_first_feature')\n def test_NumberOfWeeksGreaterOfMatches(self, mock):\n \"\"\"\n Test 5: Check if number of weeks greater number of matches.\n \"\"\"\n listofdata = self.mockConnectionFirstFeature()\n for i in range(len(listofdata)):\n start = re.findall('\\d+', (listofdata[i]['Start Of Season']))\n end = re.findall('\\d+', (listofdata[i]['End Of Season']))\n start = date(int(start[0]), int(start[1]), int(start[2]))\n end = date(int(end[0]), int(end[1]), int(end[2]))\n num_of_weeks = (end - start).days // 7\n self.assertGreater(int(num_of_weeks), int(listofdata[i]['Amount Of Match']))\n\n # --------------------------------Tests Second Feature-----------------------------------------------------------------\n @patch('Feature_Sport_Data.get_data_second_feature')\n def test_ScorersIsSorted(self, mock):\n \"\"\"\n Test 6: Check Sorted from best to good at least scores.\n \"\"\"\n listofdata = self.mockConnectionSecondFeature()\n for i in range(len(listofdata)):\n for j in range(i + 1, len(listofdata)):\n self.assertGreaterEqual(listofdata[i]['Players']['Number Of Goals'],\n listofdata[j]['Players']['Number Of Goals'], 'The list is not sorted')\n\n @patch('Feature_Sport_Data.get_data_second_feature')\n def test_NamePlayerNotNone(self, mock):\n \"\"\"\n Test 7: Check that name player not None.\n \"\"\"\n listofdata = self.mockConnectionSecondFeature()\n for i in range(len(listofdata)):\n self.assertIsNotNone(listofdata[i]['Players']['Name Player'])\n\n @patch('Feature_Sport_Data.get_data_second_feature')\n def test_NameTeamIsUnique(self, mock):\n \"\"\"\n Test 8: Check the league appears once.\n \"\"\"\n listofdata = self.mockConnectionSecondFeature()\n for i in range(len(listofdata)):\n for j in range(i + 1, len(listofdata)):\n self.assertNotEqual(listofdata[i]['Name League'], listofdata[j]['Name League'],\n 'Cannot be 2 player in same league')\n\n @patch('Feature_Sport_Data.get_data_second_feature')\n def test_AgeOfPlayerGeatherThanSixteen(self, mock):\n \"\"\"\n Test 9: Check the age of the player greater 16.\n \"\"\"\n listofdata = self.mockConnectionSecondFeature()\n for i in range(len(listofdata)):\n for j in range(i + 1, len(listofdata)):\n today = date.today()\n playerDate = re.findall('\\d+', (listofdata[i]['Players']['Date Of Birth']))\n self.assertGreater(today.year - int(playerDate[0]), 16)\n\n @patch('Feature_Sport_Data.get_data_second_feature')\n def test_NumberOfGoalGreaterThanZero(self, mock):\n \"\"\"\n Test 10: Check amount of golas greater 0.\n \"\"\"\n listofdata = self.mockConnectionSecondFeature()\n for i in range(len(listofdata)):\n self.assertGreater(int(listofdata[i]['Players']['Number Of Goals']), 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"TestDrivenDevelopment.py","file_name":"TestDrivenDevelopment.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"31470552","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import combinations_with_replacement\n\ndef polynomial_features(X, degree): #Get data and the degree in which we transform them\n n_samples, n_features = np.shape(X) #n_samples = columns\n\n def index_combinations(): #Create a combination of the features given for the specified degree\n combs = [combinations_with_replacement(range(n_features), i) for i in range(0, degree + 1)] #Create the combinations object\n flat_combs = [item for sublist in combs for item in sublist] #Append into a list\n return flat_combs\n \n combinations = index_combinations()\n n_output_features = len(combinations) #Number of possible combinations\n X_new = np.empty((n_samples, n_output_features))\n \n for i, index_combs in enumerate(combinations): \n X_new[:, i] = np.prod(X[:, index_combs], axis=1)\n\n return X_new\n\nclass PolynomialRegression(object):\n def __init__(self, degree=16, iterations=10000, alpha=0.1): #Parent constructor\n self.degree = degree #Degree of polynomial function\n self.iterations = iterations #How many times will (w) get updated\n self.alpha = alpha #How much will w get changed with each step\n \n \n def fit(self, X, y): #Fit for basic multivariate regression X = array of features, y = vector of results \n X = polynomial_features(X, degree = self.degree)\n X=np.insert(X, 0, 1, axis=1)\n \n self.training_errors = [] #With each update the new error will be added so that we can analyze the process\n \n limit= 1/math.sqrt(X.shape[1]) #A fancy way to generate a random number using the number of features of X\n self.w = np.array([np.random.uniform(-limit, limit, (X.shape[1]))]) #Create a vector (w) filled with (n) randomized weights\n print(self.w)\n for i in range(self.iterations): #Start iterating\n y_pred = X @ self.w.T #Multiply each row of feature values of X with w to get predicted result y\n mse = np.mean(0.5 * (y - y_pred)**2) #Calculate mean squared error\n mse = self.training_errors.append(mse) #append error\n self.w -= self.alpha / len(X) * np.sum((X @ self.w.T - y) * X, axis=0) #Subtract old (w) with (learning_rate/len) times the partial derivative\n \n def predict(self, X):\n X = polynomial_features(X, degree=self.degree)\n X=np.insert(X, 0, 1, axis=1)\n y_pred = X.dot(self.w.T)\n return y_pred\n \n \nmy_data = np.genfromtxt('00.2_column_data.csv', delimiter=',')\nmy_data = (my_data - my_data.mean())/(my_data.max() - my_data.min()) #feature scaling\n\nX = my_data[:, :len(my_data[0]) - 1].reshape(-1, len(my_data[0]) - 1) # -1 tells numpy to figure out the dimension by itself\ny = my_data[:, len(my_data[0])-1].reshape(-1,1) #Get y\n\npolynomialRegression = PolynomialRegression()\npolynomialRegression.fit(X, y)\n\nprint('------------------Starting Training Error------------------')\nprint(polynomialRegression.training_errors[0])\nprint('--------------------Final Training Error-------------------')\nprint(polynomialRegression.training_errors[-1])\nprint('-----------------------Final Weights-----------------------')\nprint(polynomialRegression.w)\n\n#Create the plot\nplt.scatter(my_data[:, 0].reshape(-1,1), y)\nplt.title('Plynomial Linear Regression')\nplt.xlabel('sq feet')\nplt.ylabel('price')\nplt.plot(X, polynomialRegression.predict(X))\n","sub_path":"3.polynomial_regression.py","file_name":"3.polynomial_regression.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"579861739","text":"import argparse\nimport logging\nimport time\nimport os\nimport json\nimport random\nimport cPickle\nrandom.seed(1234)\n\nimport numpy as np\nnp.random.seed(1234)\nimport tensorflow as tf\ntf.set_random_seed(1234)\n\nimport lm\nimport common_utils\nimport data_utils\nfrom exp_utils import *\n\ndef get_joint_train_op(train_lm, train_dm, opt_lm, opt_dm):\n with tf.variable_scope('joint_training_ops'):\n loss_lm = train_lm.loss * opt_lm.num_steps\n # XXX: change 0.05 into an argument or even better a decaying variable\n loss_dm = train_dm.loss * (opt_dm.num_steps * 0.05)\n joint_loss = loss_lm + loss_dm\n train_vars = tf.trainable_variables()\n grads = tf.gradients(joint_loss, train_vars)\n clipped_grads, _norm = tf.clip_by_global_norm(\n grads, opt_lm.max_grad_norm\n )\n lr = tf.Variable(opt_lm.learning_rate, trainable=False,\n name=\"learning_rate\")\n global_step = tf.get_variable(\"global_step\", [], tf.float32,\n initializer=tf.zeros_initializer,\n trainable=False)\n optimizer = tf.train.GradientDescentOptimizer(lr)\n train_op = optimizer.apply_gradients(\n zip(clipped_grads, train_vars),\n global_step=global_step)\n return train_op, lr\n\ndef run_joint_epoch(sess, train_lm, train_dm, data_iter, opt, train_op):\n start_time = time.time()\n cost_lm = 0.0\n cost_dm = 0.0\n num_words_lm = 0\n num_words_dm = 0\n state_lm = []\n state_dm = []\n for c, h in train_lm.initial_state:\n state_lm.append((c.eval(), h.eval()))\n for c, h in train_dm.initial_state:\n state_dm.append((c.eval(), h.eval()))\n for step, (x, y, w, l, seq_len) in enumerate(data_iter.iterate_epoch(\n opt.batch_size, opt.num_steps)):\n def_x, def_y, def_w, def_l, def_seq_len = data_iter.cur_features_batch(\n train_dm.opt.batch_size)\n feed_dict = {train_lm.x: x, train_lm.y: y,\n train_lm.w: w, train_lm.seq_len: seq_len,\n train_dm.x: def_x, train_dm.y: def_y, train_dm.l: def_l,\n train_dm.w: def_w, train_dm.seq_len: def_seq_len}\n fetches = [train_lm.loss, train_dm.loss, train_op]\n for c, h in train_lm.final_state:\n fetches.append(c)\n fetches.append(h)\n for i, (c, h) in enumerate(train_lm.initial_state):\n feed_dict[c], feed_dict[h] = state_lm[i]\n for c, h in train_dm.final_state:\n fetches.append(c)\n fetches.append(h)\n for i, (c, h) in enumerate(train_dm.initial_state):\n feed_dict[c], feed_dict[h] = state_dm[i]\n res = sess.run(fetches, feed_dict)\n state_flat = res[3:3+2*train_lm.opt.num_layers]\n state_lm = [state_flat[i:i+2] for i in range(0, len(state_flat), 2)]\n cost_lm += res[0]\n cost_dm += res[1]\n num_words_lm += np.sum(w)\n num_words_dm += np.sum(def_w)\n if (step + 1) % opt.progress_steps == 0:\n logger.info(\"-- @{} LM PPL: {}, DM PPL: {}, joint wps: {}\".format(\n step + 1, np.exp(cost_lm / (step + 1)),\n np.exp(cost_dm / (step + 1)),\n (num_words_lm + num_words_dm) / (time.time() - start_time)))\n return np.exp(cost_lm / (step+1)), step\n\ndef main(opt_lm, opt_dm):\n vocab_lm_path = os.path.join(opt_lm.data_dir, opt_lm.vocab_file)\n train_lm_path = os.path.join(opt_lm.data_dir, opt_lm.train_file)\n valid_lm_path = os.path.join(opt_lm.data_dir, opt_lm.valid_file)\n vocab_dm_path = os.path.join(opt_dm.data_dir, opt_dm.vocab_file)\n def_f_path = os.path.join(opt_dm.data_dir, opt_dm.def_file)\n logger.info('Loading data set...')\n logger.debug('- Loading vocab LM from {}'.format(vocab_lm_path))\n vocab_lm = data_utils.Vocabulary.from_vocab_file(vocab_lm_path)\n logger.debug('-- LM vocab size: {}'.format(vocab_lm.vocab_size))\n logger.debug('- Loading vocab DM from {}'.format(vocab_dm_path))\n vocab_dm = data_utils.Vocabulary.from_vocab_file(vocab_dm_path)\n logger.debug('-- DM vocab size: {}'.format(vocab_dm.vocab_size))\n logger.debug('- Loading def features from {}'.format(def_f_path))\n with open(def_f_path) as ifp:\n def_f_idx, def_f = cPickle.load(ifp)\n logger.debug('-- Total defs: {}'.format(len(def_f)))\n logger.debug('- Loading train LM data from {}'.format(train_lm_path))\n train_lm_iter = data_utils.TokenFeatureIterator(\n vocab_lm, train_lm_path,\n t_feature_idx=def_f_idx, t_features=def_f)\n logger.debug('- Loading valid LM data from {}'.format(valid_lm_path))\n valid_lm_iter = data_utils.DataIterator(vocab_lm, valid_lm_path)\n logger.info('Loading data completed')\n\n opt_lm.vocab_size = vocab_lm.vocab_size\n opt_dm.num_steps = def_f.shape[1]\n opt_dm.vocab_size = vocab_dm.vocab_size\n\n init_scale = opt_lm.init_scale\n sess_config =tf.ConfigProto(log_device_placement=False)\n logger.info('Starting TF Session...')\n with tf.device('/cpu:0'), tf.Session(config=sess_config) as sess:\n logger.debug(\n '- Creating initializer ({} to {})'.format(-init_scale, init_scale))\n initializer = tf.random_uniform_initializer(-init_scale, init_scale)\n logger.debug('- Creating shared embedding variables...')\n with tf.variable_scope('shared_emb'):\n shared_emb_vars = lm.sharded_variable(\n 'emb', [opt_lm.vocab_size, opt_lm.emb_size], opt_lm.num_shards)\n opt_lm.input_emb_vars = shared_emb_vars\n opt_dm.af_ex_emb_vars = shared_emb_vars\n logger.debug('- Creating training LM...')\n with tf.variable_scope('LM', reuse=None, initializer=initializer):\n train_lm = lm.LM(opt_lm, create_grads=False)\n logger.debug('- Creating validating LM (reuse params)...')\n with tf.variable_scope('LM', reuse=True, initializer=initializer):\n valid_lm = lm.LM(opt_lm, is_training=False)\n logger.debug('- Creating training DM...')\n with tf.variable_scope('DM', reuse=None, initializer=initializer):\n train_dm = lm.LMwAF(opt_dm, create_grads=False)\n logger.debug('- Creating training operation...')\n train_op, lr_var = get_joint_train_op(train_lm, train_dm,\n opt_lm, opt_dm)\n logger.debug('Trainable variables:')\n for v in tf.trainable_variables():\n logger.debug(\"- {} {} {}\".format(v.name, v.get_shape(), v.device))\n\n logger.info('Initializing vairables...')\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n state = common_utils.get_initial_training_state()\n state.learning_rate = opt_lm.learning_rate\n state, _ = resume_if_possible(opt_lm, sess, saver, state)\n logger.info('Start training loop:')\n logger.debug('\\n' + common_utils.SUN_BRO())\n # writer = tf.train.SummaryWriter(\"tf.log\", sess.graph)\n # writer.close()\n for epoch in range(state.epoch, opt_lm.max_epochs):\n epoch_time = time.time()\n logger.info(\"========= Start epoch {} =========\".format(epoch+1))\n sess.run(tf.assign(lr_var, state.learning_rate))\n logger.info(\"- Learning rate = {}\".format(state.learning_rate))\n logger.info(\"Traning...\")\n train_lm_ppl, steps = run_joint_epoch(sess, train_lm, train_dm,\n train_lm_iter,\n opt_lm, train_op)\n logger.info(\"Validating LM...\")\n valid_lm_ppl, vsteps = run_epoch(sess, valid_lm,\n valid_lm_iter, opt_lm)\n logger.info('Train ppl = {}, Valid ppl = {}'.format(\n train_lm_ppl, valid_lm_ppl))\n logger.info('----------------------------------')\n logger.info('Post epoch routine...')\n state.epoch = epoch + 1\n state.val_ppl = valid_lm_ppl\n if valid_lm_ppl < state.best_val_ppl:\n logger.info('- Best PPL: {} -> {}'.format(\n state.best_val_ppl, valid_lm_ppl))\n logger.info('- Epoch: {} -> {}'.format(\n state.best_epoch + 1, epoch + 1))\n state.best_val_ppl = valid_lm_ppl\n state.best_epoch = epoch\n ckpt_path = os.path.join(opt_lm.output_dir, \"best_model.ckpt\")\n state_path = os.path.join(opt_lm.output_dir, \"best_state.json\")\n logger.info('- Saving best model to {}'.format(ckpt_path))\n saver.save(sess, ckpt_path)\n with open(state_path, 'w') as ofp:\n json.dump(vars(state), ofp)\n else:\n logger.info('- No improvement!')\n done_training = update_lr(opt_lm, state)\n ckpt_path = os.path.join(opt_lm.output_dir, \"latest_model.ckpt\")\n state_path = os.path.join(opt_lm.output_dir, \"latest_state.json\")\n logger.info('End of epoch {}: '.format(\n epoch + 1))\n logger.info('- Saving model to {}'.format(ckpt_path))\n logger.info('- Epoch time: {}s'.format(time.time() - epoch_time))\n saver.save(sess, ckpt_path)\n with open(state_path, 'w') as ofp:\n json.dump(vars(state), ofp)\n if done_training:\n break\n logger.debug('Updated state:\\n{}'.format(state.__repr__()))\n logger.info('Done training at epoch {}'.format(state.epoch + 1))\n\nif __name__ == \"__main__\":\n global_time = time.time()\n parser = common_utils.get_common_argparse()\n parser.add_argument('--af_mode', type=str, default='gated_state',\n help='additional feature module type')\n parser.add_argument('--def_file', type=str,\n default='t_features.pickle',\n help=('token feature files '\n '(see data_utils.map_vocab_defs)'))\n parser.add_argument('--num_def_samples', type=int, default=64,\n help=('Number of definitions to sample for each batch '\n 'of text (batch size of DM)'))\n parser.add_argument('--lm_burnin', type=int, default=1,\n help=('Number of epochs to run LM before starting DM.'))\n args = parser.parse_args()\n opt_lm = common_utils.Bunch.default_model_options()\n opt_lm.update_from_ns(args)\n opt_dm = common_utils.Bunch.default_model_options()\n opt_dm.update_from_ns(args)\n opt_dm.af_function = 'ex_emb'\n opt_dm.data_dir = \"data/ptb_defs/wordnet/preprocess/\"\n opt_dm.batch_size = opt_dm.num_def_samples\n # With GPU, this will slow us down.\n # A proper weights to the loss function is enough to get correct gradients\n # opt_dm.varied_len = True\n opt_dm.reset_state = True\n logger = common_utils.get_logger(opt_lm.log_file_path)\n if opt_lm.debug:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.INFO)\n logger.info('Configurations:\\n{}'.format(opt_dm.__repr__()))\n main(opt_lm, opt_dm)\n logger.info('Total time: {}s'.format(time.time() - global_time))\n","sub_path":"train_joint_lm_dm.py","file_name":"train_joint_lm_dm.py","file_ext":"py","file_size_in_byte":11331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"350906989","text":"import sys\nimport package.Parse_Tree\n\n\ndef make_link_AFNe(G, node1, node2, token):\n if node1 not in G:\n G[node1] = {}\n (G[node1])[node2] = token\n return G\n\n\ndef make_link_AFN(G, node1, node2, token):\n if node1 not in G:\n G[node1] = {}\n if node2 in G[node1]:\n (G[node1])[node2].append(token)\n else:\n (G[node1])[node2] = [token]\n return G\n\n\ndef make_link_tree(G, node1, node2, token):\n if node1 not in G:\n G[node1] = {}\n (G[node1])[node2] = token\n return G\n\n\ndef make_state(nodesAutomata, aceptation, name):\n nodesAutomata[name] = aceptation\n return nodesAutomata\n\ndef delete_limboState(AFN, startNode, new_nodes_automata):\n color = {}\n for v in new_nodes_automata:\n color[v] = 'white'\n color[startNode] = 'gray'\n nodelist = [startNode]\n while nodelist != []:\n u = nodelist.pop()\n for neighbor in AFN[u]:\n if color[neighbor] == 'white':\n color[neighbor] = 'gray'\n if neighbor in AFN:\n nodelist.append(neighbor)\n color[u] = 'black'\n for state in color:\n if color[state] == \"white\":\n del AFN[state]\n del new_nodes_automata[state]\n return AFN\n\n\ndef make_AFD(AFN, startNode, nodesAutomata, alphabet, id_ER):\n AFD = {}\n newStates = {}\n num_state = 0\n nodes = list(nodesAutomata.keys())\n while nodes != []:\n node = nodes.pop(0)\n for symbol in alphabet:\n state = {}\n isNew = True\n if node in AFN:\n for node2 in AFN[node].keys():\n if symbol in AFN[node][node2]:\n state[node2] = 0\n else:\n for newState in newStates:\n for oldState in newStates[newState]:\n for node2 in AFN[oldState].keys():\n if symbol in AFN[oldState][node2]:\n state[node2] = 0\n if len(state) > 1:\n for newState in newStates:\n if newStates[newState] == state:\n make_link_AFN(AFD, node, newState, symbol)\n isNew = False\n break\n if isNew:\n nameState = \"q\" + str(num_state)\n while nameState in nodesAutomata.keys():\n num_state += 1\n nameState = \"q\" + str(num_state)\n num_state += 1\n newStates[nameState] = state\n make_link_AFN(AFD, node, nameState, symbol)\n nodes.append(nameState)\n else:\n make_link_AFN(AFD, node, list(state.keys())[0], symbol)\n for newState in newStates:\n for oldState in newStates[newState]:\n if nodesAutomata[oldState]:\n make_state(nodesAutomata, True, newState)\n else:\n make_state(nodesAutomata, False, newState)\n\n delete_limboState(AFD, \"q\" + str(startNode), nodesAutomata)\n return AFD\n\n\ndef add_lambda_closure(lambda_closures, initial_state, neighbor):\n if initial_state in lambda_closures:\n lambda_closures[initial_state].append(neighbor)\n else:\n lambda_closures[initial_state] = [neighbor]\n return lambda_closures\n\n\ndef find_lambda_closure(AFN, lambda_closures, AFN_e, startNode, nodesAutomata, new_nodes_automata):\n color = {}\n for v in nodesAutomata:\n color[v] = 'white'\n color[startNode] = 'gray'\n nodelist = [startNode]\n while nodelist != []:\n u = nodelist.pop()\n for neighbor in AFN_e[u]:\n if color[neighbor] == 'white':\n color[neighbor] = 'gray'\n if AFN_e[u][neighbor] == 'lambda':\n lambda_closures = add_lambda_closure(\n lambda_closures, startNode, neighbor)\n if nodesAutomata[neighbor]:\n nodesAutomata[u] = nodesAutomata[neighbor]\n if neighbor in AFN_e:\n nodelist.append(neighbor)\n else:\n if u not in AFN:\n AFN = make_link_AFN(AFN, u, neighbor, AFN_e[u][neighbor])\n elif neighbor not in AFN[u]:\n AFN = make_link_AFN(AFN, u, neighbor, AFN_e[u][neighbor])\n elif AFN_e[u][neighbor] not in AFN[u][neighbor]:\n AFN = make_link_AFN(AFN, u, neighbor, AFN_e[u][neighbor])\n new_nodes_automata[u] = nodesAutomata[u]\n new_nodes_automata[neighbor] = nodesAutomata[neighbor]\n color[u] = 'black'\n return lambda_closures, AFN, new_nodes_automata\n\n\ndef delete_lambda_transitions(lambda_closures, AFN, alphabet, nodesAutomata, new_nodes_automata):\n for state in lambda_closures:\n for state_neighbor in lambda_closures[state]:\n if state_neighbor in AFN:\n for neighbor in AFN[state_neighbor]:\n for neighbor_transition in AFN[state_neighbor][neighbor]:\n for symbol in alphabet:\n if neighbor_transition == symbol:\n if state not in AFN:\n AFN = make_link_AFN(\n AFN, state, neighbor, symbol)\n elif neighbor not in AFN[state]:\n AFN = make_link_AFN(\n AFN, state, neighbor, symbol)\n elif symbol not in AFN[state][neighbor]:\n AFN = make_link_AFN(\n AFN, state, neighbor, symbol)\n new_nodes_automata[state] = nodesAutomata[state]\n new_nodes_automata[neighbor] = nodesAutomata[neighbor]\n\n return AFN, new_nodes_automata\n\n\ndef make_AFN(AFN_e, startState, nodesAutomata, alphabet, id_ER):\n new_nodes_automata = {}\n AFN = {}\n lambda_closures = {}\n for node in AFN_e.keys():\n lambda_closures, AFN, new_nodes_automata = find_lambda_closure(AFN,\n lambda_closures, AFN_e, node, nodesAutomata, new_nodes_automata)\n AFN, new_nodes_automata = delete_lambda_transitions(\n lambda_closures, AFN, alphabet, nodesAutomata, new_nodes_automata)\n delete_limboState(AFN, \"q\" + str(startState), new_nodes_automata)\n return AFN, new_nodes_automata\n\n\ndef start_end_states(Tree, node):\n subtree = Tree[node]\n node1 = list(subtree.keys())[0]\n node2 = list(subtree.keys())[1]\n\n subAutomata1 = {}\n subAutomata2 = {}\n if node1 < node2:\n subAutomata1 = Tree[node1]\n subAutomata2 = Tree[node2]\n else:\n subAutomata1 = Tree[node2]\n subAutomata2 = Tree[node1]\n\n startNode1 = subAutomata1['start']\n endNodes1 = subAutomata1['end']\n startNode2 = subAutomata2['start']\n endNodes2 = subAutomata2['end']\n\n del Tree[node]\n del Tree[node1]\n del Tree[node2]\n\n return startNode1, endNodes1, startNode2, endNodes2\n\n\ndef transition_concatenation(AFN_e, Tree, node, nodesAutomata, state, startState):\n startNode1, endNodes1, startNode2, endNodes2 = start_end_states(\n Tree, node)\n for endNode in endNodes1:\n nodesAutomata[endNode] = False\n AFN_e = make_link_AFNe(AFN_e, endNode, startNode2, \"lambda\")\n\n if nodesAutomata[startNode1] == True:\n AFN_e = make_link_AFNe(AFN_e, startNode1, startNode2, \"lambda\")\n\n if nodesAutomata[startNode2] == True:\n endNodes2.append(startNode2)\n\n nodesAutomata[startNode1] = False\n\n Tree = make_link_tree(Tree, node, \"start\", startNode1)\n Tree = make_link_tree(Tree, node, \"end\", endNodes2)\n\n startState = startNode1.split('q')[1]\n\n return AFN_e, Tree, nodesAutomata, state, startState\n\n\ndef transition_or(AFN_e, Tree, node, nodesAutomata, state, startState):\n startNode1, endNodes1, startNode2, endNodes2 = start_end_states(\n Tree, node)\n\n startNode = \"q\" + str(state)\n\n nodesAutomata = make_state(nodesAutomata, False, startNode)\n AFN_e = make_link_AFNe(AFN_e, startNode, startNode1, \"lambda\")\n AFN_e = make_link_AFNe(AFN_e, startNode, startNode2, \"lambda\")\n\n endNodes = endNodes1 + endNodes2\n Tree = make_link_tree(Tree, node, \"start\", startNode)\n Tree = make_link_tree(Tree, node, \"end\", endNodes)\n\n startState = state\n state += 1\n return AFN_e, Tree, nodesAutomata, state, startState\n\n\ndef transition_kleen(AFN_e, Tree, node, nodesAutomata, state, startState):\n sub_node = list(Tree[node].keys())[0]\n endStates = []\n if type(sub_node) == str:\n AFN_e, Tree, nodesAutomata, state = transition(\n AFN_e, Tree, node, nodesAutomata, state)\n startState = Tree[node]['start']\n endStates = Tree[node]['end']\n else:\n startState = Tree[sub_node]['start']\n endStates = Tree[sub_node]['end']\n del Tree[sub_node]\n\n nodesAutomata[startState] = True\n for end_state in endStates:\n nodesAutomata[end_state] = True\n AFN_e = make_link_AFNe(AFN_e, end_state, startState, 'lambda')\n\n del Tree[node]\n endStates.append(startState)\n Tree = make_link_tree(Tree, node, 'start', startState)\n Tree = make_link_tree(Tree, node, 'end', endStates)\n\n startState = startState.strip('q')\n return AFN_e, Tree, nodesAutomata, state, startState\n\n\ndef transition_super(AFN_e, Tree, node, nodesAutomata, state, startState):\n sub_node = list(Tree[node].keys())[0]\n endStates = []\n if type(sub_node) == str:\n AFN_e, Tree, nodesAutomata, state = transition(\n AFN_e, Tree, node, nodesAutomata, state)\n startState = Tree[node]['start']\n endStates = Tree[node]['end']\n else:\n startState = Tree[sub_node]['start']\n endStates = Tree[sub_node]['end']\n del Tree[sub_node]\n\n nodesAutomata[startState] = False\n for end_state in endStates:\n nodesAutomata[end_state] = True\n AFN_e = make_link_AFNe(AFN_e, end_state, startState, 'lambda')\n\n del Tree[node]\n Tree = make_link_tree(Tree, node, 'start', startState)\n Tree = make_link_tree(Tree, node, 'end', endStates)\n\n startState = startState.strip('q')\n return AFN_e, Tree, nodesAutomata, state, startState\n\n\ndef transition(AFN_e, Tree, node, nodesAutomata, state):\n token = list(Tree[node].keys())[0]\n\n startState = \"q\" + str(state)\n endState = \"q\" + str(state + 1)\n AFN_e = make_link_AFNe(AFN_e, startState, endState, token)\n\n nodesAutomata = make_state(nodesAutomata, False, startState)\n nodesAutomata = make_state(nodesAutomata, True, endState)\n\n del Tree[node]\n startNode = startState\n endNodes = [endState]\n Tree = make_link_tree(Tree, node, \"start\", startNode)\n Tree = make_link_tree(Tree, node, \"end\", endNodes)\n\n state += 2\n return AFN_e, Tree, nodesAutomata, state\n\n\ndef select_transition(AFN_e, Tree, node, nodesAutomata, state, startState):\n subtree = Tree[node]\n\n if \"|\" in subtree:\n del subtree[\"|\"]\n AFN_e, Tree, nodesAutomata, state, startState = transition_or(AFN_e, Tree, node, nodesAutomata, state,\n startState)\n elif \"*\" in subtree:\n del subtree[\"*\"]\n AFN_e, Tree, nodesAutomata, state, startState = transition_kleen(AFN_e, Tree, node, nodesAutomata, state,\n startState)\n elif \"+\" in subtree:\n del subtree[\"+\"]\n AFN_e, Tree, nodesAutomata, state, startState = transition_super(AFN_e, Tree, node, nodesAutomata, state,\n startState)\n else:\n AFN_e, Tree, nodesAutomata, state, startState = transition_concatenation(AFN_e, Tree, node, nodesAutomata,\n state, startState)\n return AFN_e, Tree, nodesAutomata, state, startState\n\n\ndef makeAutomata(ERs):\n AFDS = {}\n ids_token = list(ERs.keys())\n for id_ER in ERs.keys():\n ER = ERs[id_ER]\n Tree, alphabet, compoused_automata = package.Parse_Tree.parseTree(ER, id_ER, ids_token)\n AFN_e = {}\n nodesAutomata = {}\n\n state = 0\n startState = 0\n\n len_tree = len(Tree)\n node_tree = 1\n while node_tree <= len_tree:\n subtree = Tree[node_tree]\n if len(subtree) == 1:\n AFN_e, Tree, nodesAutomata, state = transition(\n AFN_e, Tree, node_tree, nodesAutomata, state)\n else:\n AFN_e, Tree, nodesAutomata, state, startState = select_transition(AFN_e, Tree, node_tree, nodesAutomata, state,\n startState)\n node_tree += 1\n\n AFN, nodesAutomata = make_AFN(\n AFN_e, startState, nodesAutomata, alphabet, id_ER)\n\n AFDS[id_ER] = [AFN, startState, nodesAutomata, compoused_automata]\n\n return AFDS\n","sub_path":"package/Automata.py","file_name":"Automata.py","file_ext":"py","file_size_in_byte":13198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"66012504","text":"from pymongo import MongoClient\nimport sys\nimport json\nimport time\nimport os\nfrom datetime import datetime\nfrom processors import BaseProcessor\nimport resource\nfrom subprocess import PIPE, Popen, STDOUT, TimeoutExpired\n\n\nclass Processor(BaseProcessor):\n def __init__(self, name, config):\n super().__init__(name, config)\n client = MongoClient(config['mongo_host'], config['mongo_port'])\n self.db_courses = client[config['mongo_db_courses']]\n self.db_messages = client[config['mongo_db_messages']]\n self.languages_config = config[\"languages\"]\n\n def process(self, message, config=None): \n if isinstance(config, dict):\n config = {**self.config, **config}\n else:\n config = self.config\n\n try:\n need_keys = ('id', 'mqtt_key', 'user', 'language', 'course', 'problem', 'variant', 'code')\n if not all(k in message for k in need_keys):\n return None\n pr = int(message['problem'])\n var = message['variant']\n code = message['code']\n fname = message['user']\n # Определяем настройки тестов\n try:\n collection = self.db_courses[message[\"course\"]]\n problem_config = list(collection.find({'problem': pr, 'type': 'equal'}))\n # Если не нашлось ничего - выходим\n print(f\"Problem - {problem_config}\") \n if len(problem_config) == 0:\n return None\n tests = problem_config[0]['variants'][var]\n print(f\"Tests - {tests}\")\n except Exception as e:\n self.log(f'Process error: {str(e)}')\n return None\n with open(fname, 'w') as write_file:\n write_file.write(code)\n # Проверка тестов\n results = {}\n success_count = 0\n res_score = 0\n for test_key in tests:\n result = {'score': 0, 'test_out': ''}\n test = tests[test_key]\n test_in = test['in']\n test_out = test['out']\n test_score = test['score']\n p = Popen([self.languages_config[message['language']], fname], stdout=PIPE, stdin=PIPE, stderr=STDOUT) \n try:\n outs, errs = p.communicate(input=str.encode(test_in), timeout=30)\n outs = outs.decode(\"utf-8\").rstrip()\n print(f'Test input - {test_in}')\n print(f'Program output - {outs}')\n print(f'Reference output - {test_out}')\n self.log(f'Test input - {test_in}')\n self.log(f'Program output - {outs}')\n self.log(f'Reference output - {test_out}')\n result['test_out'] = outs\n if test_out == outs:\n result['score'] = test_score\n res_score += test_score\n success_count += 1\n except Exception as e:\n result['test_out'] = str(e)\n p.kill()\n outs, errs = p.communicate()\n results[test_key] = result\n \n collection_date = datetime.today().strftime('%Y-%m-%d')\n # Select problem collection\n collection = self.db_messages[f'{collection_date}']\n results['success_count'] = success_count\n results['res_score'] = res_score\n json_data = {'message': message, 'result': results}\n self.log(f'Save to MongoDB: {json_data}.')\n transaction_id = collection.insert_one(json_data).inserted_id\n self.log(f'MongoDB response: {transaction_id}.')\n del json_data['_id']\n return json_data\n except Exception as err:\n self.log(f'Process error: {str(err)}')\n return None\n","sub_path":"SGContest/ContestServer/processors/equal_processor.py","file_name":"equal_processor.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"587664214","text":"# filter warnings\nimport warnings\nwarnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\n# keras imports\nfrom keras.applications.vgg16 import VGG16, preprocess_input\nfrom keras.applications.vgg19 import VGG19, preprocess_input\nfrom keras.applications.xception import Xception, preprocess_input\nfrom keras.applications.resnet50 import ResNet50, preprocess_input\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input\nfrom keras.applications.mobilenet import MobileNet, preprocess_input\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras.models import model_from_json\nfrom keras.layers import Input\n\n# other imports\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nimport glob\n#import cv2\nimport h5py\nimport os\nimport json\nimport datetime\nimport time\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport pickle\nimport logging\nfrom skimage import color, exposure, transform\nimport pandas as pd\nfrom skimage import io\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras import backend as K\nK.set_image_data_format('channels_last')\nfrom keras import metrics\nfrom keras.optimizers import SGD\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\nfrom keras.models import load_model\n\n# load the user configs\nwith open('conf.json') as f:\n\tconfig = json.load(f)\n\n# config variables\nmodel_name \t\t= config[\"model\"]\nweights \t\t= config[\"weights\"]\ninclude_top \t= config[\"include_top\"]\ntrain_path \t\t= config[\"train_path\"]\nfeatures_path \t= config[\"features_path\"]\nlabels_path \t= config[\"labels_path\"]\ntest_size \t\t= config[\"test_size\"]\nresults \t\t= config[\"results\"]\nmodel_path \t\t= config[\"model_path\"]\nseed \t\t= config[\"seed\"]\nclassifier_path = config[\"classifier_path\"]\nlog_path\t\t= config[\"log_path\"]\n\n#Corleone\ncode_path=\"/home/drobert/tfg/traffic_sign_machine_learning/vgg19/\"\ndataset_path='/home/drobert/tfg/'\n\nfichero_log = (log_path)\n\nprint('Archivo Log en ', fichero_log)\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s : %(levelname)s : %(message)s',\n filename = fichero_log,\n filemode = 'a',)\n# start time\nprint (\"[STATUS] -------------vgg19 from scratch - start time - {}\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")))\nlogging.info(\" -------------vgg19 from scratch - start time - {}\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")))\nstart = time.time()\n\n# create the pretrained models\n# check for pretrained weight usage or not\n# check for top layers to be included or not\nNUM_CLASSES = 43\nIMG_SIZE = 299\n\n\n\nmodel = VGG19(include_top=True,classes=1000 )\n\n# Funcion para preprocesar las imagenes\ndef preprocess_img(img):\n # normalizacion del histograma en el canal 'v'\n hsv = color.rgb2hsv(img)\n hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])\n img = color.hsv2rgb(hsv)\n\n # recorte del cuadrado central\n min_side = min(img.shape[:-1])\n centre = img.shape[0] // 2, img.shape[1] // 2\n img = img[centre[0] - min_side // 2:centre[0] + min_side // 2,\n centre[1] - min_side // 2:centre[1] + min_side // 2,\n :]\n\n # reescalado de imagenes a tamaño standard\n img = transform.resize(img, (IMG_SIZE, IMG_SIZE), mode='constant')\n\n return img\n\ndef get_class(img_path):\n return int(img_path.split('/')[-2])\n\n\n\n\n\nos.chdir(dataset_path) #direccion local Jupyter Notebooks/pycharm\n#root_dir = 'GTSRB/Final_Training/Images/'\nroot_dir = train_path\n#os.chdir('/home/drobert/tfg/')#direccion en corleone\n#root_dir = 'GTSRB/Final_Training/Images/'\n\n\nimgs = []\nlabels = []\n\nruta_actual = os.getcwd()\nprint(ruta_actual)\n\nall_img_paths = glob.glob(os.path.join(root_dir, '*/*.ppm'))\n\nprint(os.path.join(root_dir, '*/*.ppm'))\nprint(len(all_img_paths))\n\nnp.random.shuffle(all_img_paths)\n\nfor img_path in all_img_paths:\n img = preprocess_img(io.imread(img_path))\n label = get_class(img_path)\n imgs.append(img)\n labels.append(label)\n\nX = np.array(imgs, dtype='float32')\nY = np.asarray(labels)\n\nprint(X.shape)\nprint(Y.shape)\n\nlogging.info(X.shape)\nlogging.info(Y.shape)\n# In[4]:\n\n# Vamos a hacer cross validation con nuestro conjunt de test.\n# En concreto vamos a hacer un Kfold con 10 splits estratificado,\n# de tal manera que cada conjunto tenga aproximadamente el mismo porcentaje\n# de muestras de cada clase que el conjunto de entrenamiento.\n\ntraining_history_list = []\nval_accuracy_list = []\n\nconfusion_matrix_list = []\nclf_list = []\nfilename_clf_list = []\n\n#Contador para saber en que fold estamos\nfold = 1\n\nskf = StratifiedKFold(n_splits=3) # numero de 'trozos' en los que dividimos el dataset de entrenamiento\nprint(skf)\nlogging.info(skf)\n\n\ndef lr_schedule(epoch):\n return lr * (0.1 ** int(epoch / 10))\n\n#Me daba un error.\n#https://stackoverflow.com/questions/46305252/valueerror-dimension-1-must-be-in-the-range-0-2-in-keras\ndef get_categorical_accuracy_keras(y_true, y_pred):\n return K.mean(K.equal(K.argmax(y_true, axis=1), K.argmax(y_pred, axis=1)))\n\nbatch_size = 32\nepochs = 20 #ponemos 5 para que sea mas rapido, normalmente 30\nlr = 0.01\n\nfor train_index, test_index in skf.split(X, Y):\n # conjuntos de train y test(validacion) para cada fold\n x_train, x_test = X[train_index], X[test_index]\n y_train_no_one_hot, y_test_no_one_hot = Y[train_index], Y[test_index]\n\n # Make one hot targets\n y_train = np.eye(NUM_CLASSES, dtype='uint8')[y_train_no_one_hot]\n y_test = np.eye(NUM_CLASSES, dtype='uint8')[y_test_no_one_hot]\n\n #one hot encodig con to_categorical\n #dummy_y = np_utils.to_categorical(y_train_no_one_hot, NUM_CLASSES)\n #dummy_y = np_utils.to_categorical(y_test_no_one_hot, NUM_CLASSES)\n\n\n\n classifier = model\n\n # vamos a entrenar nuestro modelo con SGD + momentum\n sgd = SGD(lr=lr, decay=1e-6, momentum=0.9, nesterov=True)\n classifier.compile(loss='categorical_crossentropy',\n optimizer=sgd,\n #metrics=['accuracy'])\n metrics=[metrics.categorical_accuracy])\n #metrics=[get_categorical_accuracy_keras])#unico que funciona\n\n print(\"tamaños de x_train e y_train\")\n print(x_train.shape)\n print(y_train.shape)\n\n filepath = code_path+\"vgg19-fold\"+str(fold)+\"-epochs\"+str(epochs)+\".h5\"\n\n hist = classifier.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_split=0.2,\n verbose=1,\n callbacks=[LearningRateScheduler(lr_schedule)]\n\n )\n\n\n #Guardar training / validation loss/accuracy en cada epoch\n training_history_list.append(hist.history)\n #print(\"history:\")\n #print(hist.history)\n #logging.info(\"history:\")\n #logging.info(hist.history)\n\n\n val_accuracy = classifier.evaluate(x_test, y_test, verbose=1)\n\n print(\"%s: %.2f%%\" % (classifier.metrics_names[1], val_accuracy[1] * 100))\n logging.info(\"%s: %.2f%%\" % (classifier.metrics_names[1], val_accuracy[1] * 100))\n\n val_accuracy_list.append(val_accuracy[1] * 100)\n\n\n #y_pred = classifier.predict_classes(x_test)\n #test_accuracy = np.sum(y_pred == y_test) / np.size(y_pred)\n\n\n print(\"loss y val accuracy del fold \"+str(fold)+\" :\"+str(val_accuracy))\n logging.info(\"loss y val accuracy del fold \"+str(fold)+\" :\"+str(val_accuracy))\n\n\n\n clf_list.append(classifier) # lista de cada uno de los los clasificadores\n\n #NO hacemos un pickle porque ya lo guardaos en formato h5\n fold = fold +1\n\n\n\nprint('lista de accuracys de los modelos: '+str(val_accuracy_list))\nlogging.info('lista de accuracys de los modelos: '+str(val_accuracy_list))\n\nprecision_media = (np.mean(val_accuracy_list))\ndesviacion_standar = (np.std(val_accuracy_list))\n\n\nprint(\"mean_accuarcy: %.2f%% (+/- %.2f%%)\" % (np.mean(val_accuracy_list), np.std(val_accuracy_list)))\nlogging.info(\"mean_accuarcy: %.2f%% (+/- %.2f%%)\" % (np.mean(val_accuracy_list), np.std(val_accuracy_list)))\n\n\nruta_actual = os.getcwd()\n#print(ruta_actual)\n#print(os.listdir(ruta_actual))\nos.chdir(dataset_path+'/GTSRB')#En local\n#os.chdir('/home/drobert/tfg/GTSRB')#En corleone\n\n# Cargamos el archivo csv con los datos de test y vemos que contienen los 10 primeros\ntest = pd.read_csv('GT-final_test.csv', sep=';')\n#test.head(10)\n\n# In[61]:\n\n# Cargamos el dataset de test\nos.chdir(dataset_path+'/GTSRB/Final_Test/Images/')#en local\n#os.chdir('/home/drobert/tfg/GTSRB/Final_Test/Images/')#en corleone\n\nX_test = []\ny_test = []\ni = 0\n\nfor file_name, class_id in zip(list(test['Filename']), list(test['ClassId'])):\n # img_path = os.path.join('GTSRB/Final_Test/Images/', file_name)\n img_path = os.path.join(os.getcwd(), file_name)\n X_test.append(preprocess_img(io.imread(img_path)))\n y_test.append(class_id)\n\nX_test = np.array(X_test)\ny_test = np.array(y_test)\n\n\n#Los targets tienen que estar en formato one target\ny_test_one_target = np.eye(NUM_CLASSES, dtype='uint8')[y_test]\n\n# Función para encontrar el modelo que está mas proximo a la media\ndef modelo_medio_indx(final, numeros):\n def el_menor(numeros):\n menor = numeros[0]\n retorno = 0\n for x in range(len(numeros)):\n if numeros[x] < menor:\n menor = numeros[x]\n retorno = x\n return retorno\n\n diferencia = []\n for x in range(len(numeros)):\n diferencia.append(abs(final - numeros[x]))\n # devuelve el indice del modelo más próximo a la media\n return numeros.index(numeros[el_menor(diferencia)])\n\n\n\nprint(\"precision media: \"+str(precision_media))\nlogging.info(\"precision media: \"+str(precision_media))\n\nmodel_indx = modelo_medio_indx(precision_media, val_accuracy_list)\n\nprint(\"indice del modelo medio: \"+str(model_indx))\nlogging.info(\"indice del modelo medio: \"+str(model_indx))\n\n# cargamos el modelo medio de disco\nos.chdir(code_path)\nbest_model =clf_list[model_indx]\n\ntest_accuracy = best_model.evaluate(X_test, y_test_one_target, verbose=1)\n\n#Guardar best_model en un pickle\n\n\ntoday_date = datetime.date.today().strftime(\"%d-%m-%Y\")\n\nbest_model_filename= (\"vgg19_epochs%s_test_acc_%.2f%%_%s.h5\" % (epochs,test_accuracy[1] * 100, today_date))\n\n#pickle.dump(best_model, open((code_path + str(best_model_filename)), 'wb'))\n\n#guardar con h5 no funciona por tener un metodo custom de accuracy\nbest_model.save(best_model_filename)\n\nprint(\"Accuracy en test : %s: %.2f%%\" % (best_model.metrics_names[1], test_accuracy[1] * 100))\n\nlogging.info(\"Accuracy en test : %s: %.2f%%\" % (best_model.metrics_names[1], test_accuracy[1] * 100))\n\n\n#Comprobamos que el modelo cargado tiene la misma precision\n\n#loaded_model = pickle.load(open(best_model_filename, 'rb'))\nloaded_model = load_model(best_model_filename)# No funciona con custom metrics\n\nloaded_model_test_accuracy = loaded_model.evaluate(X_test, y_test_one_target, verbose=1)\nprint(\"Loaded_model accuracy en test : %s: %.2f%%\" % (loaded_model.metrics_names[1], loaded_model_test_accuracy[1] * 100))\n#https://github.com/keras-team/keras/issues/3911\n#La solucion propuesta arriba tampoco funciona\n\n#loaded_model = load_model('best_model_filename', custom_objects={'get_categorical_accuracy_keras': get_categorical_accuracy_keras})\n#loaded_model_test_accuracy = loaded_model.evaluate(X_test, y_test_one_target, verbose=1)\n\n# Una técnica muy útil para visualizar el rendimiento de nuestro algoritmo es\n# la matriz de confusión. y la mostramos de varia formas. Solo mostramos\n# la matriz de confusion del modelo medio.\n\n#Para generar la matriz de confusión necesitamos los targets en formato lista\n#No en one hot encoding.\n\n\ny_pred = loaded_model.predict(X_test)\n#pasamos a one hot encoding para que tenga la misma estructura que y_pred\n#No funciona así, tendran que ser los 2 vectores unidimensionales\n#y_test_one_hot = to_categorical(y_test, NUM_CLASSES)\n\n#pasamos y_pred que esta en one hot encoding a un vector plano\ny_pred_no_one_hot= np.argmax(y_pred, axis=1, out=None)\n\nprint(\"shape de y_test , y_pred_no_one_hot :\")\n\nprint(y_test.shape)\nprint(y_pred_no_one_hot.shape)\n\n\n\ncm = pd.DataFrame(confusion_matrix(y_test, y_pred_no_one_hot))\n\n#logging.info(\"matriz de confusión del modelo medio: \")\n#logging.info(cm)\n\n\nprint(\"Fin de la prueba con vgg19 from scratch\")\nlogging.info(\"-----------Fin de la prueba con vgg19 from scratch-----------\")\nlogging.info(\"program ended on - \" + str(datetime.datetime.now))\n\n\n","sub_path":"vgg19/vgg19_from_scratch.py","file_name":"vgg19_from_scratch.py","file_ext":"py","file_size_in_byte":12613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"384054397","text":"#Name: Anup Thapa\n#Email: anup.thapa65@myhunter.cuny.edu\n#Date: September 16, 2020\n#This program prints the message typed by the user in upper case and lower case\n\ndef my_function(str):\n print(str)\n print(str.upper())\n print(str.lower())\n \nmy_function(\"Mihi cura futuri\")\nmy_function(\"CSci 127\")\n\nfor college in [\"Hunter college\",\"The City College of New York\",\"Baruch College\"]:\n my_function(college)\n","sub_path":"python/upandlowcase.py","file_name":"upandlowcase.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"580414580","text":"import random\nimport xlwt\nimport os\nimport json\n\ndirectory = \"/home/tab/桌面/\"\nfile_name = \"test.xls\"\n\n\n# 将预授信的一条数据作为一个类\nclass PersonalPreApproval(object):\n def __init__(self):\n self.curr_path = os.path.dirname(os.path.dirname(__file__))\n order_number = ''\n user_name = ''\n id_card_no = ''\n phone_no = ''\n ex_account_manager_no = ''\n is_credit_pre_grant = ''\n credit_pre_line = ''\n credit_end_date = ''\n is_using_strategy = ''\n is_man_white_list = ''\n man_credit_pre_line = ''\n is_local_resident = ''\n firm_position = ''\n firm_type = ''\n is_regular_EE = ''\n mean_salary = ''\n level = ''\n acm_haf_amount = ''\n acm_sif_amount = ''\n acm_m1_salary = ''\n acm_m2_salary = ''\n acm_m3_salary = ''\n acm_m4_salary = ''\n acm_m5_salary = ''\n acm_m6_salary = ''\n is_payroll_via_us = ''\n firm_population = ''\n firm_has_contract = ''\n firm_name = ''\n age = ''\n gender = ''\n\n @staticmethod\n def ran(capacity):\n return random() * capacity\n\n # 生成随机姓名:Todo(zhouwentao): 随机两个字或者三个字\n @staticmethod\n def get_name():\n family_name_list = '赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方' \\\n '俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧' \\\n '计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯咎管卢莫' \\\n '经房裘缪干解应宗宣丁贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀羊於惠甄魏加封芮羿储靳汲邴糜松井段富巫乌焦巴弓' \\\n '牧隗山谷车侯宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭厉戎祖武符刘姜詹束龙叶幸司韶郜黎蓟薄印宿白怀蒲台从鄂索咸籍赖卓蔺屠蒙' \\\n '池乔阴郁胥能苍双闻莘党翟谭贡劳逄姬申扶堵冉宰郦雍却璩桑桂濮���寿通边扈燕冀郏浦尚农温别庄晏柴瞿阎充慕连茹习宦艾鱼容' \\\n '向古易慎戈廖庚终暨居衡步都耿满弘匡国文寇广禄阙东殴殳沃利蔚越夔隆师巩厍聂晁勾敖融冷訾辛阚那简饶空曾毋沙乜养鞠须丰' \\\n '巢关蒯相查后江红游竺权逯盖益桓公万俟司马上官欧阳夏侯诸葛闻人东方赫连皇甫尉迟公羊澹台公冶宗政濮阳淳于仲孙太叔申屠' \\\n '公孙乐正轩辕令狐钟离闾丘长孙慕容鲜于宇文司徒司空亓官司寇仉督子车颛孙端木巫马公西漆雕乐正壤驷公良拓拔夹谷宰父谷粱' \\\n '晋楚阎法汝鄢涂钦段干百里东郭南门呼延归海羊舌微生岳帅缑亢况后有琴梁丘左丘东门西门商牟佘佴伯赏南宫墨哈谯笪年爱阳佟' \\\n '第五言福'\n last_name_list = '秀 娟 英 华 慧 巧 美 娜 静 淑 惠 珠 翠 雅 芝 玉 萍 红 娥 玲 芬 芳 燕 彩 春 菊 兰 凤 洁 梅 琳 素 云 莲 真 环' \\\n '雪 荣 爱 妹 霞 香 月 莺 媛 艳 瑞 凡 佳 嘉 琼 勤 珍 贞 莉 桂 娣 叶 璧 璐 娅 琦 晶 妍 茜 秋 珊 莎 锦 黛 青 倩' \\\n '婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭' \\\n '凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽'\n\n while(True):\n m_key = random.randint(0, len(last_name_list) - 1)\n l_key = random.randint(0, len(last_name_list) - 1)\n if last_name_list[l_key] == ' ' and last_name_list[m_key] == ' ':\n continue\n elif last_name_list[l_key] == ' ':\n name = family_name_list[random.randint(0, len(last_name_list)-1)] + last_name_list[m_key]\n return name\n elif last_name_list[m_key] == ' ':\n name = family_name_list[random.randint(0, len(last_name_list) - 1)] + last_name_list[l_key]\n return name\n else:\n name = family_name_list[random.randint(0, len(last_name_list) - 1)] + last_name_list[m_key] + \\\n last_name_list[l_key]\n return name\n\n @staticmethod\n def get_gender():\n gender_code = random.randint(0, 9)\n return gender_code\n\n @staticmethod\n def get_age():\n birth_year = random.randint(1958, 2007)\n birth_month = random.randint(1, 12)\n if birth_month in [1, 3, 5, 7, 8, 10, 12]:\n birth_date = random.randint(1, 31)\n elif birth_month in [4, 6, 9, 11]:\n birth_date = random.randint(1, 30)\n else:\n if (birth_year % 4 == 0) and (birth_year % 400 != 0):\n birth_date = random.randint(1, 29)\n else:\n birth_date = random.randint(1, 28)\n\n return str(birth_year) + str(\"%02d\" % birth_month) + str(\"%02d\" % birth_date)\n\n def get_identification(self):\n region_f = open(self.curr_path + '/material/region.txt', encoding='utf-8')\n region_no = random.choice(region_f.readlines())\n birth_date = self.get_age()\n self.gender = self.get_gender()\n police_station_id = random.randint(1, 99)\n\n# 取一个多位数各位的值的方法:依次执行 i % 10,i/10从个位向前取\n# birth_year_copy = birth_year\n# region_no_copy = region_no\n# region = [1, 2, 3, 4, 5, 6]\n# year = [1, 2, 3, 4]\n# for i in [0, 1, 2, 3]:\n# year[i] = birth_year_copy % 10\n# birth_year_copy = int(birth_year_copy / 10)\n# for j in [0, 1, 2, 3, 4, 5]:\n# region[j] = int(region_no_copy) % 10\n# region_no_copy = int(region_no_copy / 10)\n# ai = region[0] * 4 + region[1] * 8 + region[2] * 5 + region[3] * 10 + region[4] * 9 + region[5] * 7 + \\\n# year[0]*3 + year[1]*6 + year[2]*1 + year[3]*2 + (birth_month % 10) * 9 + \\\n# int(birth_month/10) * 7 + (birth_date % 10) * 5 + int(birth_date/10) * 10 + \\\n# (police_station_id % 10) * 4 + int(police_station_id/10) * 8 + self.gender * 2\n\n id_without_last = str(region_no).strip() + birth_date + \"%02d\" % police_station_id + str(self.gender)\n k = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]\n ai = 0\n for i in range(len(k)):\n ai += int(id_without_last[i]) * k[i]\n y = ai % 11\n c = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}\n return str(id_without_last) + c[y]\n #\n # return str(region_no) + str(birth_year) + \\\n # str(\"%02d\" % birth_month) + str(\"%02d\" % birth_date) + \"%02d\" % police_station_id + \\\n # str(self.gender) + c[y]\n\n @staticmethod\n def get_phone_no(operator_index=['dx', 'lt', 'yd']):\n dx = ['133', '149', '153', '173', '177', '180', '181', '189', '199']\n lt = ['130', '131', '132', '145', '155', '156', '166', '171', '175', '176', '185', '186']\n yd = ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159', '178',\n '182', '183', '184', '187', '188', '198']\n operator_list = []\n for i in operator_index:\n if i == 'dx':\n operator_list = operator_list + dx\n elif i == 'lt':\n operator_list = operator_list + lt\n elif i == 'yd':\n operator_list = operator_list + yd\n index = random.randint(0, len(operator_list)-1)\n operator = operator_list[index]\n return str(operator) + str(\"%08d\" % random.randint(1, 99999999))\n\n def get_bank_card(self, bank: str = None) -> str:\n def _rand_digits(length):\n return random.randint(10**(length-1), 10**length-1)\n with open(self.curr_path + '/material/bank.json', encoding='utf-8') as f:\n bank_json = json.load(f)\n sum = 0\n if bank is None:\n head = '6'\n no = head + str(random.randint(10000000000000, 99999999999999))\n else:\n head = bank_json[bank]['BIN']\n no = head + str(_rand_digits(bank_json[bank]['cardNoLength'] - len(head) - 1))\n no_list = ' '.join(no).split(' ')\n no_list.reverse()\n for i in range(0, len(no_list), 2):\n no_list[i] = str(int(no_list[i]) * 2)\n caled_no_list = ' '.join(''.join(no_list)).split(' ')\n for digit in caled_no_list:\n sum += int(digit)\n if sum % 10 == 0:\n verify = 0\n else:\n verify = 10 - (sum % 10)\n return no + str(verify)\n\n\n# 创建表头\nworkbook = xlwt.Workbook(encoding='utf-8')\nworksheet = workbook.add_sheet('预授信白名单样例')\ntitle = ['序号', '姓名', '身份证号', '手机号', '客户经理号(个贷系统)', '是否已预授信', '已预授信额度', '授信结束时间',\n '是否使用系统风控', '是否直接加入白名单', '直接预授信额度', '是否常住本地', '职业', '单位性质', '是否正式员工', '平均月收入',\n '职务级别', '公积金', '社保缴费金额', '过去第1个月实发工资', '过去第2个月实发工资', '过去第3个月实发工资',\n '过去第4个月实发工资', '过去第5个月实发工', '过去第6个月实发工资', '工资是否本行代发', '所在单位人数规模',\n '所在单位是否出具相关书面承诺', '单位名称', '年龄', '性别']\ntitle_en = ['order number', 'username', 'idcardNo', 'phoneNo', 'exAccountManagerNo', 'isCreditPreGrant',\n 'creditPreLine', 'creditEndDate(yyyy-mm-dd)', 'isUsingStrategy', 'isManWhiteList', 'manCreditPreLine',\n 'isLocalResident', 'firmPosition', 'firmType', 'isRegularEE', 'meanSalary', 'level', 'acm_haf_amount',\n 'acm_sif_amount', 'acm_m1_salary', 'acm_m2_salary', 'acm_m3_salary', 'acm_m4_salary', 'acm_m5_salary',\n 'acm_m6_salary', 'isPayrollViaUs', 'firmPopulation', 'firmHasContract', 'firmName', 'age', 'gender']\n\nfor title_column in range(0, len(title)):\n worksheet.write(0, title_column, title[title_column])\n worksheet.write(1, title_column, title_en[title_column])\n\n\nfor line in range(1, 3):\n ppa = PersonalPreApproval()\n ppa.order_number = line\n ppa.user_name = ppa.get_name()\n ppa.id_card_no = ppa.get_identification()\n ppa.phone_no = ppa.get_phone_no()\n ppa.gender = ppa.get_gender()\n ppa.age = str(2019 - int(ppa.get_age()[0: 4]))\n worksheet.write(line + 1, 0, ppa.order_number)\n worksheet.write(line + 1, 1, ppa.user_name)\n worksheet.write(line + 1, 2, ppa.id_card_no)\n worksheet.write(line + 1, 3, ppa.phone_no)\n worksheet.write(line + 1, 29, ppa.age)\n if ppa.gender % 2 == 1:\n worksheet.write(line + 1, 30, '男')\n else:\n worksheet.write(line + 1, 30, '女')\n personal_info = ['', '是', '60000', '2019-11-30', '否', '是', '60000', '是', '专业技术人员', '事业单位', '是', '10000',\n '其他', '1520', '606.86', '17620.5', '6329.51', '11720.77', '20584.69', '11479.71', '11923.81',\n '否', '小于100大于等于50', '是', '遵义市农业科学研究院']\n column = 4\n for personal_info_value in personal_info:\n worksheet.write(line + 1, column, personal_info_value)\n column += 1\n\nworkbook.save(directory + file_name)\n\n\n\n\n","sub_path":"application/preapproval.py","file_name":"preapproval.py","file_ext":"py","file_size_in_byte":11902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"513883486","text":"# Definition for a binary tree node\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass BSTIterator(object):\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.stack = []\n node = root\n while node != None:\n self.stack.append(node)\n node = node.left\n \n\n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n return len(self.stack) != 0\n \n\n def next(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if not self.stack:\n return None\n last = self.stack[-1]\n if last.right == None:\n ret = self.stack.pop()\n result = ret.val\n if not self.stack:\n return result\n while ret == self.stack[-1].right:\n ret = self.stack.pop()\n if not self.stack:\n return result\n return result\n elif last.right != None:\n result = last.val\n cur = last.right\n while cur != None:\n self.stack.append(cur)\n cur = cur.left\n return result\n \n\n# Your BSTIterator will be called like this:\nroot = TreeNode(1)\na = TreeNode(2)\nb = TreeNode(3)\nc = TreeNode(4)\nroot.left = a\na.left = c\nroot.right = b\ni, v = BSTIterator(root), []\nwhile i.hasNext(): v.append(i.next())\nprint(v)","sub_path":"Fengshuang/python/_173_Binary_Search_Tree_Iterator.py","file_name":"_173_Binary_Search_Tree_Iterator.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"50714033","text":"cities_in_f = {\"New York\": 32, \"Boston\": 75, \"Los Angeles\": 100, \"Chicago\": 50}\n\ncities_in_c = {key: round((value-32)*(5/9)) for (key,value) in cities_in_f.items()}\nprint(cities_in_c)\n\nweather = {\"New York\": \"snowing\", \"Boston\": \"sunny\", \"Los Angeles\": \"sunny\", \"Chicago\": \"cloudy\"}\nsunny_weather = {key: value for (key,value) in weather.items() if value == \"sunny\"}\nprint(sunny_weather)\n\ncities = {\"New York\": 32, \"Boston\": 75, \"Los Angeles\": 100, \"Chicago\": 50}\n\ncities_warm_cold = {key: (\"Warm\" if value >= 70 else \"Cold\") for (key,value) in cities.items()}\nprint(cities_warm_cold)\n\ndef check_temp(value):\n if value >=75:\n return \"Hot\"\n elif 75 > value >= 40:\n return \"Warm\"\n else:\n return \"Cold\"\n\ncities = {\"New York\": 32, \"Boston\": 75, \"Los Angeles\": 100, \"Chicago\": 50}\ncities_warm_cold = {key: check_temp(value) for (key,value) in cities.items()}\n\nprint(cities_warm_cold)","sub_path":"Learning/dictionarycomprehension.py","file_name":"dictionarycomprehension.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"61670303","text":"from __future__ import print_function, absolute_import\nimport logging\nimport logging.config\nimport argparse\nimport sys\nimport os\nimport os.path\nimport itertools\n\nfrom mrtarget.modules.Evidences import process_evidences_pipeline\nfrom mrtarget.common.ElasticsearchLoader import Loader\nfrom mrtarget.common.ElasticsearchQuery import ESQuery\nfrom mrtarget.common.connection import RedisManager, new_es_client, new_redis_client\nfrom mrtarget.ElasticsearchConfig import ElasticSearchConfiguration\nfrom mrtarget.modules.Association import ScoringProcess\nfrom mrtarget.modules.DataDrivenRelation import DataDrivenRelationProcess\nfrom mrtarget.modules.ECO import EcoProcess\nfrom mrtarget.modules.EFO import EfoProcess\nfrom mrtarget.modules.Ensembl import EnsemblProcess\nfrom mrtarget.modules.GeneData import GeneManager\nfrom mrtarget.modules.HPA import HPAProcess\nfrom mrtarget.modules.QC import QCMetrics\nfrom mrtarget.modules.Reactome import ReactomeProcess\nfrom mrtarget.modules.SearchObjects import SearchObjectProcess\nfrom mrtarget.modules.Uniprot import UniprotDownloader\nfrom mrtarget.modules.Metrics import Metrics\nfrom mrtarget.Settings import Config, file_or_resource\n\nimport mrtarget.cfg\n\ndef main():\n #parse config file, environment, and command line arguments\n mrtarget.cfg.setup_ops_parser()\n args = mrtarget.cfg.get_ops_args()\n\n #set up logging\n logger = None\n if args.log_config:\n if os.path.isfile(args.log_config) and os.access(args.log_config, os.R_OK):\n #read a log configuration file\n logging.config.fileConfig(args.log_config, disable_existing_loggers=False)\n logger = logging.getLogger(__name__+\".main()\")\n else:\n #unable to read the logging config file, abort\n logging.basicConfig()\n logger = logging.getLogger(__name__+\".main()\")\n logger.error(\"unable to read file {}\".format(args.log_config))\n return 1\n else:\n #no logging config specified, fall back to default\n logging.basicConfig()\n logger = logging.getLogger(__name__+\".main()\")\n\n\n if not args.release_tag:\n logger.error('A [release-tag] has to be specified.')\n print('A [release-tag] has to be specified.', file=sys.stderr)\n return 1\n else:\n Config.RELEASE_VERSION = args.release_tag\n logger.info('setting release version %s' % Config.RELEASE_VERSION)\n\n\n\n \n \n with RedisManager(args.redis_remote,args.redis_host, args.redis_port):\n\n es = new_es_client(args.elasticseach_nodes)\n redis = new_redis_client(args.redis_host, args.redis_port)\n\n #create a single query object for future use\n esquery = ESQuery(es)\n\n #read the data configuration\n data_config = mrtarget.cfg.get_data_config(args.data_config)\n\n #create something to accumulate qc metrics into over various steps\n qc_metrics = QCMetrics()\n\n with Loader(es,\n chunk_size=ElasticSearchConfiguration.bulk_load_chunk,\n dry_run = args.dry_run) as loader:\n\n if args.rea:\n process = ReactomeProcess(loader, \n data_config.reactome_pathway_data, data_config.reactome_pathway_relation)\n if not args.qc_only:\n process.process_all(args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n if args.ens:\n process = EnsemblProcess(loader)\n if not args.qc_only:\n process.process(data_config.ensembl_filename, args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n if args.unic:\n process = UniprotDownloader(loader)\n if not args.qc_only:\n process.process(data_config.uniprot_uri, args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n if args.hpa:\n process = HPAProcess(loader,redis, args.elasticseach_nodes,\n data_config.tissue_translation_map, data_config.tissue_curation_map,\n data_config.hpa_normal_tissue, data_config.hpa_rna_level, \n data_config.hpa_rna_value, data_config.hpa_rna_zscore)\n if not args.qc_only:\n process.process_all(args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery)) \n\n if args.gen:\n process = GeneManager(loader, redis,\n args.gen_plugin_places, data_config.gene_data_plugin_names,\n )\n if not args.qc_only:\n process.merge_all(data_config, dry_run=args.dry_run)\n\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery)) \n \n if args.efo:\n process = EfoProcess(loader, data_config.ontology_efo, data_config.ontology_hpo, \n data_config.ontology_mp, data_config.disease_phenotype)\n if not args.qc_only:\n process.process_all(args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n if args.eco:\n process = EcoProcess(loader, data_config.ontology_eco, data_config.ontology_so)\n if not args.qc_only:\n process.process_all(args.dry_run)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n\n if args.val:\n es_output_folder = None\n if \"elasticsearch_folder\" in vars(args) and args.elasticsearch_folder is not None:\n es_output_folder = args.elasticsearch_folder\n\n process_evidences_pipeline(filenames=data_config.input_file,\n first_n=args.val_first_n,\n es_client=es,\n redis_client=redis,\n dry_run=args.dry_run,\n output_folder=es_output_folder,\n num_workers=args.val_workers_validator,\n num_writers=args.val_workers_writer,\n max_queued_events=args.val_queue_validator_writer,\n eco_scores_uri=data_config.eco_scores,\n schema_uri = data_config.schema,\n es_hosts=args.elasticseach_nodes,\n excluded_biotypes = data_config.excluded_biotypes,\n datasources_to_datatypes = data_config.datasources_to_datatypes)\n\n #TODO qc\n\n if args.assoc:\n process = ScoringProcess(args.redis_host, args.redis_port,\n args.elasticseach_nodes)\n if not args.qc_only:\n process.process_all(data_config.scoring_weights, \n data_config.is_direct_do_not_propagate,\n data_config.datasources_to_datatypes,\n args.dry_run,\n args.as_workers_production,\n args.as_workers_score,\n args.as_queue_production_score)\n if not args.skip_qc:\n qc_metrics.update(process.qc(esquery))\n pass\n \n if args.ddr:\n process = DataDrivenRelationProcess(es)\n if not args.qc_only:\n process.process_all(args.dry_run,\n args.ddr_workers_production,\n args.ddr_workers_score,\n args.ddr_queue_production_score,\n args.ddr_queue_score_result)\n #TODO qc\n\n if args.sea:\n process = SearchObjectProcess(loader, redis)\n if not args.qc_only:\n process.process_all(\n data_config.chembl_target, \n data_config.chembl_mechanism, \n data_config.chembl_component, \n data_config.chembl_protein, \n data_config.chembl_molecule_set_uri_pattern,\n args.dry_run)\n #TODO qc\n\n if args.metric:\n process = Metrics(es, args.metric_file, \n data_config.datasources_to_datatypes).generate_metrics()\n\n if args.qc_in:\n #handle reading in previous qc from filename provided, and adding comparitive metrics\n qc_metrics.compare_with(args.qc_in)\n\n if args.qc_out:\n #handle writing out to a tsv file\n qc_metrics.write_out(args.qc_out)\n\n logger.info('`'+\" \".join(sys.argv)+'` - finished')\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"mrtarget/CommandLine.py","file_name":"CommandLine.py","file_ext":"py","file_size_in_byte":8867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"92029218","text":"import argparse\n\nfrom Bio import SeqIO, Seq\nfrom Bio.Alphabet import generic_dna\nfrom Bio.Data.CodonTable import TranslationError\n\nparser = argparse.ArgumentParser(description='Fasta line length normalizer')\n\nparser.add_argument('-n','--fasta_normalizer',\n dest='fasta_normalizer',\n action=\"store_true\"\n)\nparser.add_argument('-p','--peptide-fasta',\n dest='peptide_fasta',\n action=\"store_true\"\n)\nparser.add_argument('-c','--fasta-cleaner',\n dest='fasta_cleaner',\n action=\"store_true\"\n)\nparser.add_argument('-f','--file',\n dest='fasta_file'\n)\nparser.add_argument('-l','--length',\n dest='fasta_line_length'\n)\nparser.add_argument('-o','--overlap',\n dest='fasta_sequences_overlap'\n)\nparser.add_argument('-of','--output_file',\n dest='output_file'\n)\nparser.add_argument('-w','--wrong-bases',\n dest='wrong_bases'\n)\nparser.add_argument('-ol','--one-liner',\n dest='one_liner',\n action=\"store_true\"\n)\n\n\ndef fasta2dict(fasta_file, pyfastalib=True):\n fasta_dict = {}\n\n if pyfastalib:\n fasta_list = [line.strip() for line in open(fasta_file) if line.strip() != \"\"]\n fasta_seq_names = [fasta_list[i].replace(\">\",\"\") for i in range(0, len(fasta_list), 2)]\n fasta_sequences = [fasta_list[i] for i in range(1, len(fasta_list), 2)]\n\n for k, v in zip(fasta_seq_names, fasta_sequences):\n try:\n splited_seq_name = k.split(\"|\")\n seq_name = splited_seq_name[0]\n seq_pos = splited_seq_name[1]\n if seq_name in fasta_dict:\n fasta_dict[seq_name].append((int(seq_pos), v))\n else:\n fasta_dict[seq_name] = []\n fasta_dict[seq_name].append((int(seq_pos), v))\n except:\n print(k)\n\n for k in fasta_dict.keys():\n fasta_dict[k] = sorted(fasta_dict[k])\n\n else:\n fasta = SeqIO.to_dict(SeqIO.parse(fasta_file, format=\"fasta\"))\n fasta_dict = {k:str(v.seq) for k, v in fasta.items()}\n\n return fasta_dict\n\n\ndef dict2fasta(fasta_cleaned, output_fasta=None):\n fasta_list = []\n for k, v in fasta_cleaned.items():\n try:\n for ind, seq in v:\n fasta_list.append(\">{}|{}\\n{}\\n\".format(k, ind, seq))\n except:\n fasta_list.append(\">{}\\n{}\\n\".format(k, v))\n\n if output_fasta != None:\n with open(output_fasta, \"w+\") as f:\n f.write(\"\\n\".join(fasta_list))\n else:\n print(\"\\n\".join(fasta_list))\n\n\ndef fasta_one_liner(fasta, output_fasta=None):\n fasta = SeqIO.to_dict(SeqIO.parse(fasta, format=\"fasta\"))\n one_liner_fasta = {}\n for k, v in fasta.items():\n one_liner_fasta[k] = str(v.seq)\n dict2fasta(one_liner_fasta, output_fasta)\n\n\ndef seq_name_norm(fasta_to_clean, output_fasta=None):\n import re\n fasta = SeqIO.to_dict(SeqIO.parse(fasta_to_clean, format=\"fasta\"))\n fasta_clean = {}\n\n for k, v in fasta.items():\n k_n = re.sub(r\"([0-9])_([0-9])\", r\"\\1|\\2\", k)\n fasta_clean[k_n] = str(v.seq)\n\n dict2fasta(fasta_clean, output_fasta)\n\ndef list_normalizer(sortinglist, overlap_len, desired_len):\n sorted_list = sorted(sortinglist, key=lambda tup: tup[0])\n normalized_list = []\n if len(sorted_list) > 1:\n normalized_list = [x for x in sorted_list[:-2]]\n seq_complete = sorted_list[-2][1]\n seq_incomplete = sorted_list[-1][1]\n if len(seq_incomplete) > int(overlap_len):\n if len(seq_incomplete) < int(desired_len):\n missing_len = int(desired_len) - len(seq_incomplete)\n normalized_list.append((sorted_list[-2][0], sorted_list[-2][1]))\n seq_incomplete = seq_complete[-int(missing_len) - int(overlap_len):-int(overlap_len)] + seq_incomplete\n normalized_list.append((int(sorted_list[-1][0]), seq_incomplete))\n elif len(seq_incomplete) == int(desired_len):\n normalized_list.append((int(sorted_list[-1][0]), seq_incomplete))\n else:\n raise ValueError(\"Alguma parte do script com erro\")\n else:\n normalized_list = [x for x in sorted_list[:-1]]\n return normalized_list\n else:\n for k in sortinglist:\n if len(k[1]) == desired_len:\n normalized_list.append((int(sortinglist[-1][0]), sortinglist[-1][1]))\n return normalized_list\n\n\ndef fasta_normalizer(file, desired_len, overlap_len, output_file = None):\n fasta_dict = fasta2dict(file)\n new_fasta = {k: list_normalizer(v, overlap_len=overlap_len, desired_len=desired_len) for k, v in fasta_dict.items()}\n\n fasta_file_output = []\n estranhos = 0\n for k, v in new_fasta.items():\n for ind, seq in v:\n if len(seq) == int(desired_len):\n fasta_file_output.append(\">{}|{}\\n{}\\n\".format(k, ind, seq))\n else:\n estranhos += 1\n\n if output_file != None:\n with open(output_file, \"w+\") as f:\n f.write(\"\\n\".join(fasta_file_output))\n else:\n print(\"\\n\".join(fasta_file_output))\n\n\ndef fasta_cleaner(input_fasta, output_fasta=None, wrong_bases=\"n\"):\n fasta_dict = fasta2dict(input_fasta, pyfastalib=False)\n fasta_cleaned = {}\n\n for k, v in fasta_dict.items():\n fasta_cleaned[k] = v.replace(wrong_bases, \"\")\n\n if output_fasta == None:\n dict2fasta(fasta_cleaned)\n else:\n dict2fasta(fasta_cleaned, output_fasta)\n\n\ndef pep_fasta(input_fasta, output_fasta=None):\n fasta_dict = fasta2dict(input_fasta)\n fasta_dict_bkp = {}\n for k, v in fasta_dict.items():\n try:\n fasta_dict_bkp[k] = [(ind, Seq.Seq(x, generic_dna).translate()) for ind, x in v]\n except:\n pass\n\n dict2fasta(fasta_dict_bkp, output_fasta)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n if args.fasta_normalizer:\n fasta_normalizer(\n args.fasta_file,\n args.fasta_line_length,\n args.fasta_sequences_overlap,\n args.output_file\n )\n\n if args.fasta_cleaner:\n fasta_cleaner(args.fasta_file,\n args.output_file,\n args.wrong_bases\n )\n\n if args.peptide_fasta:\n pep_fasta(\n args.fasta_file,\n args.output_file\n )\n\n if args.one_liner:\n fasta_one_liner(\n args.fasta_file,\n args.output_file\n )\n","sub_path":"fasta_normalizer.py","file_name":"fasta_normalizer.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"197904592","text":"#!/usr/local/bin/python3\n\"\"\"\nThis package has the following function:\n\nget_main_color():\n If receives a path to an image file and returns the main color.\n It will also reduce the number of colors in the image if wanted.\n\nnamed_color():\n Returns the closest named color from the dictionary below.\n Also returns the dominant channel (r or g or b)\n\ncolor_summary():\n Summarizes the image colors into a dictionary of helpful \n values for comparing colors. See function comment.\n\n\"\"\"\nimport glob\nimport os,sys\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport pprint\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import MiniBatchKMeans\n\ncolors_dict = {\n 'red':[255,0,0],\n 'orange':[255,128,0],\n 'yellow':[255,255,0],\n 'green':[0,255,0],\n 'teal':[0,128,128],\n 'blue':[0,0,255],\n 'purple':[128,0,128],\n 'pink':[255,192,203],\n 'white':[255,255,255],\n 'gray':[128,128,128],\n 'black':[0,0,0],\n 'brown':[165,42,42]\n}\n\n\n\"\"\"\nFunction: get_main_color\n Finds the \"main\" color or dominant color.\nParams:\n path [string] : path to image \n reduce [bool] : reduce colors or not\n num_colors [int] : number of colors to reduce to\nReturns:\n summary [dict] : see below\n\"\"\"\n\ndef get_main_color(file,reduce=False,num_colors=8):\n\n if reduce:\n img = reduce_colors(file,num_colors)\n else:\n img = Image.open(file)\n\n width,height = im.size\n\n colors = img.getcolors(width*height) #put a higher value if there are many colors in your image\n \n max_occurence, most_present = 0, 0\n\n try:\n for c in colors:\n if c[0] > max_occurence:\n (max_occurence, most_present) = c\n return most_present\n except TypeError:\n raise Exception(\"Too many colors in the image\")\n\n\"\"\"\nReturns the closest named color from dict above.\nAlso returns the dominant r,g,b \n\nExamples: \n (99, 136, 95) returns ('gray', 'g')\n (216, 166, 9) returns ('orange', 'r')\n\n\"\"\"\ndef named_color(color):\n closest_rgb = 99999\n closest_name = None\n highest_rgb = None\n highest_val = 0\n \n for name,rgb in colors_dict.items():\n val = 0\n for i in range(3):\n val += abs(color[i] - rgb[i])\n if val < closest_rgb:\n closest_rgb = val\n closest_name = name\n \n if color[0] > color[1]:\n highest_rgb = 'r'\n highest_val = color[0]\n else:\n highest_rgb = 'g'\n highest_val = color[1]\n \n if color[2] > highest_val:\n highest_rgb = 'b'\n highest_val = color[2]\n\n return closest_name,highest_rgb\n\n\"\"\"\nFunction: \n color_summary\nParams:\n im [pil image]\nReturns:\n summary [dict] : see below\n'named_colors': {'counts': {'black': 11057,\n 'brown': 6907,\n 'gray': 19187,\n 'green': 117,\n 'pink': 313,\n 'teal': 12648,\n 'white': 94,\n 'yellow': 2},\n 'ratios': {'black': 0.22,\n 'brown': 0.14,\n 'gray': 0.38,\n 'green': 0.0,\n 'pink': 0.01,\n 'teal': 0.25,\n 'white': 0.0,\n 'yellow': 0.0}},\n 'rgb': {'counts': {'b': 415, 'g': 47123, 'r': 2787},\n 'ratios': {'b': 0.01, 'g': 0.94, 'r': 0.06}},\n 'total_colors': 50325}\n\"\"\"\ndef color_summary(im):\n color_count = {\n 'rgb':{\n 'counts':{},\n 'ratios':{}\n },\n 'named_colors':{\n 'counts':{},\n 'ratios':{}\n },\n 'total_colors':0\n }\n for c in list(im.getdata()):\n color_count['total_colors'] += 1\n color,rgb = named_color(c)\n if not color in color_count['named_colors']['counts']:\n color_count['named_colors']['counts'][color] = 0\n color_count['named_colors']['counts'][color] += 1\n\n if not rgb in color_count['rgb']['counts']:\n color_count['rgb']['counts'][rgb] = 0\n color_count['rgb']['counts'][rgb] += 1\n\n\n for c,count in color_count['named_colors']['counts'].items():\n color_count['named_colors']['ratios'][c] = round(count / color_count['total_colors'],2)\n\n for c,count in color_count['rgb']['counts'].items():\n color_count['rgb']['ratios'][c] = round(count / color_count['total_colors'],2)\n\n return color_count\n\n\n\"\"\"\nFunction: color_summary\n Returns a pil image with reduced colors using kmeans clustering\n by opencv\nParams:\n path [string] : path to image \n numcolors [int] : num colors to reduce to\n show [bool] : display image in gui\nReturns:\n summary [dict] : see below\n\"\"\"\ndef reduce_colors(path,numcolors,show=False):\n\n tmpfile = '/tmp/tmpimage.jpg'\n\n img = cv2.imread(path)\n Z = img.reshape((-1,3))\n\n # convert to np.float32\n Z = np.float32(Z)\n\n # define criteria, number of clusters(K) and apply kmeans()\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n K = numcolors\n ret,labels,centers=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)\n\n # Now convert back into uint8, and make original image\n centers = np.uint8(centers)\n res = centers[labels.flatten()]\n res2 = res.reshape((img.shape))\n\n # save opencv version to tmp dir\n cv2.imwrite(tmpfile,res2)\n\n if show:\n cv2.imshow('res2',res2)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return Image.open(tmpfile)\n\n\"\"\"\nabove uses python pil to some extent, this one sticks with opencv\n\"\"\"\ndef reduce_colors2(image,K=4):\n\n if isinstance(image,str):\n if os.path.isfile(image):\n image = cv2.imread(image)\n else:\n print(\"Error: image arg is string but not valid file.\")\n sys.exit()\n\n if not isinstance(image, np.ndarray):\n print(\"Error: image arg is not a string but not a valid numpy array either.\")\n sys.exit()\n\n print(K)\n \n (h, w) = image.shape[:2]\n \n # convert the image from the RGB color space to the L*a*b*\n # color space -- since we will be clustering using k-means\n # which is based on the euclidean distance, we'll use the\n # L*a*b* color space where the euclidean distance implies\n # perceptual meaning\n image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n \n # reshape the image into a feature vector so that k-means\n # can be applied\n image = image.reshape((image.shape[0] * image.shape[1], 3))\n \n # apply k-means using the specified number of clusters and\n # then create the quantized image based on the predictions\n clt = MiniBatchKMeans(n_clusters = K)\n labels = clt.fit_predict(image)\n quant = clt.cluster_centers_.astype(\"uint8\")[labels]\n \n # reshape the feature vectors to images\n quant = quant.reshape((h, w, 3))\n image = image.reshape((h, w, 3))\n \n # convert from L*a*b* to RGB\n quant = cv2.cvtColor(quant, cv2.COLOR_LAB2BGR)\n image = cv2.cvtColor(image, cv2.COLOR_LAB2BGR)\n\n return quant\n\ndef matchShapes(img1,img2):\n image2name = img2\n if isinstance(img1,str):\n if os.path.isfile(img1):\n img1 = cv2.imread(img1,0)\n else:\n print(\"Error: image arg is string but not valid file.\")\n sys.exit()\n\n if isinstance(img2,str):\n if os.path.isfile(img2):\n img2 = cv2.imread(img2,0)\n else:\n print(\"Error: image arg is string but not valid file.\")\n sys.exit()\n\n if not isinstance(img1, np.ndarray):\n print(\"Error: image arg1 is not a string but not a valid numpy array either.\")\n sys.exit()\n\n if not isinstance(img2, np.ndarray):\n print(\"Error: image arg2 is not a string but not a valid numpy array either.\")\n sys.exit()\n\n ret, thresh = cv2.threshold(img1, 127, 255,0)\n ret2, thresh2 = cv2.threshold(img2, 127, 255,0)\n contours,hierarchy = cv2.findContours(thresh,2,1)\n cnt1 = contours[0]\n contours,hierarchy = cv2.findContours(thresh2,2,1)\n if len(contours) == 0:\n return 1000000\n cnt2 = contours[0]\n\n ret = cv2.matchShapes(cnt1,cnt2,1,0.0)\n if ret == 1.7976931348623157e+308:\n return 1000000\n\n return ret\n\ndef color_distance(im1,im2,size=(128,128)):\n\n im1 = cv2.imread(im1)\n im1 = cv2.resize(im1,size)\n\n im2 = cv2.imread(im2)\n im2 = cv2.resize(im2,size)\n\n colors = ('b','g','r')\n\n comparisons = {\n 'correlation':cv2.HISTCMP_CORREL,\n 'chisquare':cv2.HISTCMP_CHISQR,\n 'intersect':cv2.HISTCMP_INTERSECT,\n 'bhattacharyya':cv2.HISTCMP_BHATTACHARYYA\n }\n\n hists = [{},{}]\n \n for i,col in enumerate(colors):\n hists[0][col] = cv2.calcHist([im1],[i],None,[256],[0,256])\n # plt.plot(hists[0][col],color = col)\n # plt.xlim([0,256])\n # plt.show()\n\n for i,col in enumerate(colors):\n hists[1][col] = cv2.calcHist([im2],[i],None,[256],[0,256])\n # plt.plot(hists[0][col],color = col)\n # plt.xlim([0,256])\n # plt.show()\n\n\n d = {}\n for key,comp in comparisons.items():\n d[key] = {}\n for c in colors:\n d[key][c] = cv2.compareHist(hists[0][c], hists[1][c],comp) \n pprint.pprint(d)\n\n\n\n\nif __name__=='__main__':\n # im = reduce_colors2(\"/Users/griffin/Dropbox/Scripts-random/image_projects/downloads/corn-blue/3. mp,550x550,matte,ffffff,t.3u5.jpg\",5)\n # cv2.imshow(\"image\", im)\n # cv2.waitKey(0)\n\n results = {}\n images = {}\n imagesList = glob.glob('/Users/griffin/Dropbox/Scripts-random/image_projects/EmojiColors/emojis_64x64'+'/*.png')\n\n img1 = '/Users/griffin/Dropbox/Scripts-random/image_projects/EmojiColors/emojis_64x64/lollipop.png'\n for img2 in imagesList:\n results[os.path.basename(img2)] = matchShapes(img1,img2)\n #images[os.path.basename(img2)] = bw\n \n results = sorted([(v, k) for (k, v) in results.items()])\n print(results[:25])\n\n bw1 = cv2.imread('/Users/griffin/Dropbox/Scripts-random/image_projects/EmojiColors/emojis_64x64/lollipop.png',0)\n ret1, thresh1 = cv2.threshold(bw1, 127, 255,0)\n cv2.imshow('res2',thresh1)\n cv2.waitKey(0)\n \n bw2 = cv2.imread('/Users/griffin/Dropbox/Scripts-random/image_projects/EmojiColors/emojis_64x64/'+results[0][1],0)\n ret2, thresh2 = cv2.threshold(bw2, 127, 255,0)\n cv2.imshow('res2',thresh2)\n cv2.waitKey(0)\n\n # i = 0\n # for name,val in results.items():\n # cv2.imshow('img',images[name])\n # i += 1\n # if i >= 5:\n # sys.exit()\n\n\n #im = Image.open(\"./downloads/forest-red/5.jpg\")\n # im = Image.open(\"/Users/griffin/Dropbox/Scripts-random/image_projects/AsciiArt/original_images/lilly_400x.jpg\")\n # width,height = im.size\n # print(width,height)\n # histogram = im.histogram()\n # print(histogram)\n\n # pprint.pprint(color_summary(im))\n\n # abe1 = '/Users/griffin/Dropbox/Scripts-random/image_projects/image_collage/downloads/forest-red/4.jpg'\n # abe2 = '/Users/griffin/Dropbox/Scripts-random/image_projects/image_collage/downloads/forest-red/5.jpg'\n # abe2 = '/Users/griffin/Dropbox/Scripts-random/image_projects/image_collage/downloads/forest1/4.jpg'\n # abe1 = '/Users/griffin/Dropbox/Scripts-random/image_projects/image_collage/downloads/forest1/4.jpg'\n\n # color_distance(abe1,abe2)\n","sub_path":"Assignments/A08/image_package/color_functions.py","file_name":"color_functions.py","file_ext":"py","file_size_in_byte":11507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"386060661","text":"import time\nimport pygal\nimport requests\nimport csv\n\nkey = \"http://coinbase.com/api/v1/prices/historical?page=\"\n\nn=69\n\nwhile (len(requests.get(key+str(n)).content) < 5):\n n+=-1\n\nprint('there are %s pages to get')%n\n\nk = n + 1\n\ndata=\"\"\n\ni=1\n\nfor i in range(1,n+1):\n r = requests.get(key+str(n))\n if r.status_code == 200:\n data += '\\n'+str(r.content)\n else:\n data += '\\n API-ERROR'\n n+=1\n \n\nwith open(\"{}_output.txt\".format(int(time.time())), \"a\") as output:\n output.write(data)\n\nprint('%r') % data\n\nchop = csv.reader(data.split())\n\ncount = 0\n\nfor row in chop:\n count+=1\n #points_for_chart = [(row1),(row2),(row3)...]\n print(row)\n\n#this generates an SVG, as long as points_for_chart exists \n#xy_chart = pygal.XY(stroke=False)\n#xy_chart.title = 'BTC'\n#xy_chart.add('BTC Price, points_for_chart)\n#xy_chart.render_to_file(\"{}_Plot.svg\".format(int(time.time())))\n","sub_path":"Tests/01InitialTests/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"189065523","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 6 15:44:05 2018\n\n@author: Labvis\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 16 13:23:32 2017\n\n@author: Labvis\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom skimage.io import imread\nfrom skimage.color import rgb2grey \nfrom skimage import filters\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom nltk.cluster.kmeans import KMeansClusterer\nfrom skimage import exposure\nfrom kmedias import kmedias\n\n\n#Leitura das imagens\ncameraman = imread('C:/Users/Labvis/Dropbox/mestrado/Processamento Digital de Imagens/Trabalho1/cameraman512.jpg')\n\n#Converte a imagem para níveis de cinza\nlena = rgb2grey(np.asarray(cameraman))*np.max(cameraman)\n\n\n\n#Vetoriza a Imagem\nimage_vector = np.reshape(lena, (1,lena.shape[0]*lena.shape[1]))\n\n#Plota o Histograma\nplt.figure(1)\nplt.xlabel('Níveis de Cinza')\nplt.ylabel('Frequência de Ocorrência')\nplt.title('Histograma')\n\nhist, bins_center = exposure.histogram(lena)\nplt.plot(bins_center, hist)\n\n\n#Calcula o kmedias\npoints,clusters,C = kmedias(image_vector.T,2,'euclidean',10)\n\n\nvector_seg2 = clusters.T\n\n#Transforma o vetor de labels na imagem segmentada\nimage_seg2 = np.reshape(vector_seg2,(lena.shape[0],lena.shape[1]))\n\n#plota a Imagem segmentada pelo kmedias\nplt.figure(2)\nplt.axis('off')\nplt.imshow(image_seg2,cmap = \"gray\")\n\n\n#Calula o limiar do Otsu\nval = filters.threshold_otsu(lena)\n\n#Plota a imagem segmentada pelo otsu\nplt.figure(3)\nplt.axis('off')\nplt.imshow(lena endtime:\n # info(\"timeout kill\")\n for p in cpopens.values():\n p.send_signal(SIGINT)\n if cclosed == N*(flows): # +1 for the sum equation\n for p in cpopens.values():\n p.send_signal(SIGINT)\n for h, line in pmonitor(spopens, timeoutms=10000):\n if h:\n info('server %s: %s' % (h.name, line))\n if 'bits/sec' in line and 'SUM' not in line:\n sclosed += 1\n if time() > endtime:\n # info(\"timeout kill\")\n for p in spopens.values():\n p.send_signal(SIGINT)\n if sclosed == N*(flows):\n info(\"shutting down\")\n for p in spopens.values():\n p.send_signal(SIGINT)\n\n # CLI(net)\n info(\"\\n\")\n info(speeds)\n info(\"\\n\")\n info(\"got %d speeds, avg %f Mbits/s\" % (len(speeds), flows*float(sum(speeds)) / len(speeds)))\n net.stop()\n\ndef main():\n topo = JellyFishTop(S, N, r)\n net = Mininet(topo=topo, host=CPULimitedHost, link = TCLink, controller=JELLYPOX)\n experiment(net)\n\nif __name__ == \"__main__\":\n setLogLevel( 'info' )\n main()\n\n","sub_path":"pox/pox/ext/build_topology.py","file_name":"build_topology.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"508342221","text":"import random\n\n'''\n Идея такая:\n 1. Раскладываем определитель на n множителей, где n - заданный порядок матрицы.\n 2. Полученное разложение это числа на главной диагонали верхнетреугольной матрицы.\n 3. Составляем верхнетругольную матрицу, на главной диагонали которой наше разложение, а \n выше неё - случайные целые числа (можно и не целые, но я хочу целые)\n 4. К полученной верхнетреугольной матрице начинаем применять рандомные элементарные преобразования \n не помню какого типа, короче того, который не меняет определитель\n 5. Вроде всё, получили то, что требовалось.\n'''\n\n\ndef is_prime(num, start): # проверяет число на простоту, сложность: O(sqrt(n)).\n div = start # пока start нужен, чтобы функция разложила число на <= n множителей, где n - порядок матрицы.\n while div ** 2 <= num and num % div != 0:\n div += 1\n\n return div ** 2 > num, div # возвращаем булевый ответ проверки на простоту, ну и заодно\n # найденый делитель числа, чтобы дважды не вставать.\n\n\ndef construct_triangle_matrix(size, diagonal): # собираем врхнетругольный вид\n matrix = []\n for i in range(size): # вот вы знали, что вот такая конструкция: matrix = [[0] * n] * n,\n matrix.append([0] * size) # создаст квадратный массив n на n, В котором при измении\n # одной строки будут меняться сразу все? Я вот не знал...\n\n random_pain = 1 # регулятор боли - генерируемых чисел в матрице\n\n for i in range(size):\n for j in range(size):\n if j == i:\n matrix[i][j] = diagonal[i]\n elif i < j:\n matrix[i][j] = random.randint(0, 10 ** random_pain - 1) # -1 чтобы число было меньше последнего десятка\n\n return matrix\n\n\ndef random_transformations(matrix): # случайные элементарные преобразования\n size = len(matrix)\n random_pain = 1 # аналогично\n '''\n На самом деле не очень случайные, мы будем брать последний столбец матрицы (потому что он \n почти полностью сгенерирован), умножать его на случайное число и прибавлять к предыдущему,\n потом то же самое сделаем с ним и тем, который до него и т.д.\n '''\n\n for i in range(size - 1, 0, -1):\n random_multyplier = random.randint(1, 10 ** random_pain - 1)\n for j in range(size):\n matrix[j][i - 1] += matrix[j][i] * random_multyplier\n\n return matrix\n\n\ndef generate_matrix(size, determinant):\n det_dividers = [1] * size\n while not is_prime(determinant, size)[0]: # будем делить определитель пока он не станет простым\n div = is_prime(determinant, size)[1]\n determinant //= div\n det_dividers.append(div)\n det_dividers.append(determinant)\n det_dividers = det_dividers[len(det_dividers) - size:] # в массиве элементов больше, чем size,\n # все лишние отрежем, останется только наши делители и несколько единиц\n\n matrix = construct_triangle_matrix(size, det_dividers)\n matrix = random_transformations(matrix) # всё, на этом этапе уже готовая матрица\n\n return matrix # в соседнем файле находится функция, которая находит определитель, можно проверить\n","sub_path":"sem_linal/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"7729377","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAlgebraic Quaternion Algorithm\n==============================\n\nRoberto Valenti's Algebraic Quaterion Algorithm (AQUA) [Valenti2015]_ estimates\na quaternion with the algebraic solution of a system from inertial/magnetic\nobservations.\n\nAQUA computes the \"tilt\" quaternion and the \"heading\" quaternion separately in\ntwo sub-parts. This avoids the impact of the magnetic disturbances on the roll\nand pitch components of the orientation.\n\nIt uses a complementary filter that fuses together gyroscope data with\naccelerometer and magnetic field readings. The correction part of the filter is\nbased on the independently estimated quaternions and works for both IMU\n(Inertial Measurement Unit) and MARG (Magnetic, Angular Rate, and Gravity)\nsensors [Valenti2016]_.\n\nReferences\n----------\n.. [Valenti2015] Valenti, R.G.; Dryanovski, I.; Xiao, J. Keeping a Good\n Attitude: A Quaternion-Based Orientation Filter for IMUs and MARGs. Sensors\n 2015, 15, 19302-19330.\n (https://res.mdpi.com/sensors/sensors-15-19302/article_deploy/sensors-15-19302.pdf)\n.. [Valenti2016] R. G. Valenti, I. Dryanovski and J. Xiao, \"A Linear Kalman\n Filter for MARG Orientation Estimation Using the Algebraic Quaternion\n Algorithm,\" in IEEE Transactions on Instrumentation and Measurement, vol.\n 65, no. 2, pp. 467-481, 2016.\n (https://ieeexplore.ieee.org/document/7345567)\n\n\"\"\"\n\nimport numpy as np\nfrom ..common.orientation import q_prod, q2R\nfrom ..common.constants import MUNICH_LATITUDE, MUNICH_HEIGHT\n\n# Reference Observations in Munich, Germany\nfrom ..utils.wgs84 import WGS\nGRAVITY = WGS().normal_gravity(MUNICH_LATITUDE, MUNICH_HEIGHT)\n\ndef slerp_I(q: np.ndarray, ratio: float, t: float) -> np.ndarray:\n \"\"\"\n Interpolation with identity quaternion\n\n Interpolate a given quaternion with the identity quaternion\n :math:`\\\\mathbf{q}_I=\\\\begin{pmatrix}1 & 0 & 0 & 0\\\\end{pmatrix}` to\n scale it to closest versor.\n\n The interpolation can be with either LERP (Linear) or SLERP (Spherical\n Linear) methods, decided by a threshold value :math:`t`, which lies\n between ``0.0`` and ``1.0``.\n\n .. math::\n \\\\mathrm{method} = \\\\left\\\\{\n \\\\begin{array}{ll}\n \\\\mathrm{LERP} & \\\\: q_w > t \\\\\\\\\n \\\\mathrm{SLERP} & \\\\: \\\\mathrm{otherwise}\n \\\\end{array}\n \\\\right.\n\n For LERP, a simple equation is implemented:\n\n .. math::\n \\\\hat{\\\\mathbf{q}} = (1-\\\\alpha)\\\\mathbf{q}_I + \\\\alpha\\\\Delta \\\\mathbf{q}\n\n where :math:`\\\\alpha\\\\in [0, 1]` is the gain characterizing the cut-off\n frequency of the filter. It basically decides how \"close\" to the given\n quaternion or to the identity quaternion the interpolation is.\n\n If the scalar part :math:`q_w` of the given quaternion is below the\n threshold :math:`t`, SLERP is used:\n\n .. math::\n \\\\hat{\\\\mathbf{q}} = \\\\frac{\\\\sin([1-\\\\alpha]\\\\Omega)}{\\\\sin\\\\Omega} \\\\mathbf{q}_I + \\\\frac{\\\\sin(\\\\alpha\\\\Omega)}{\\\\sin\\\\Omega} \\\\mathbf{q}\n\n where :math:`\\\\Omega=\\\\arccos(q_w)` is the subtended arc between the\n quaternions.\n\n Parameters\n ----------\n q : numpy.array\n Quaternion to inerpolate with.\n ratio : float\n Gain characterizing the cut-off frequency of the filter.\n t : float\n Threshold deciding interpolation method. LERP when qw>t, otherwise\n SLERP.\n\n Returns\n -------\n q : numpy.array\n Interpolated quaternion\n \"\"\"\n q_I = np.array([1.0, 0.0, 0.0, 0.0])\n if q[0]>t: # LERP\n q = (1.0-ratio)*q_I + ratio*q # (eq. 50)\n else: # SLERP\n angle = np.arccos(q[0])\n q = q_I*np.sin(abs(1.0-ratio)*angle)/np.sin(angle) + q*np.sin(ratio*angle)/np.sin(angle) # (eq. 52)\n q /= np.linalg.norm(q) # (eq. 51)\n return q\n\ndef adaptive_gain(a: float, a_norm: float, t1: float = 0.1, t2: float = 0.2, g: float = GRAVITY) -> float:\n \"\"\"\n Adaptive filter gain factor\n\n The estimated gain :math:`\\\\alpha` is dependent on the gain factor\n :math:`f` determined by the magnitude error :math:`e_m`:\n\n .. math::\n \\\\alpha = a f(e_m)\n\n where the magnitude error is defined by the measured acceleration\n :math:`\\\\mathbf{a}=\\\\begin{bmatrix}a_x & a_y & a_z\\\\end{bmatrix}^T` and the\n reference gravity :math:`g\\\\approx 9.809196 \\\\frac{m}{s^2}`:\n\n .. math::\n e_m = \\\\frac{|\\\\|\\\\mathbf{a}\\\\|-g|}{g}\n\n The gain factor is constant and equal to 1 when the magnitude of the\n nongravitational acceleration is not high enough to overcome gravity.\n\n If nongravitational acceleration rises and :math:`e_m` exceeds the\n first threshold, the gain factor :math:`f` decreases linearly with the\n increase of the magnitude until reaching zero at the second threshold\n and above it.\n\n Empirically, both thresholds have been defined at ``0.1`` and ``0.2``,\n respectively. They can be, however, changed by setting the values of\n input parameters ``t1`` and ``t2``.\n\n Parameters\n ----------\n a : float\n Constant gain yielding best results in static conditions.\n a_norm : float\n Norm of measured local acceleration vector.\n t1 : float, default: 0.1\n First threshold\n t2 : float, default: 0.2\n Second threshold\n g : float, default: 9.809196\n Reference gravitational acceleration in m/s^2. The estimated gravity in\n Munich, Germany (``9.809196``) is used as default reference value.\n\n Returns\n -------\n alpha : float\n Gain factor\n\n Examples\n --------\n >>> alpha = adaptive_gain(a, 9.71)\n \"\"\"\n em = abs(a_norm-GRAVITY)/GRAVITY # Magnitude error (eq. 60)\n f = 0.0\n if e1 np.ndarray:\n \"\"\"\n Quaternion from Earth-Field Observations\n\n Algebraic estimation of a quaternion as a function of an observation of\n the Earth's gravitational and magnetic fields.\n\n It decomposes the quaternion :math:`\\\\mathbf{q}` into two auxiliary\n quaternions :math:`\\\\mathbf{q}_{\\\\mathrm{acc}}` and\n :math:`\\\\mathbf{q}_{\\\\mathrm{mag}}`, such that:\n\n .. math::\n \\\\mathbf{q} = \\\\mathbf{q}_{\\\\mathrm{acc}}\\\\mathbf{q}_{\\\\mathrm{mag}}\n\n Parameters\n ----------\n acc : numpy.ndarray, default: None\n Sample of tri-axial Accelerometer in m/s^2\n mag : numpy.ndarray, default: None\n Sample of tri-axial Magnetometer in mT\n\n Returns\n -------\n q : numpy.ndarray\n Estimated quaternion.\n \"\"\"\n ax, ay, az = acc/np.linalg.norm(acc)\n # Quaternion from Accelerometer Readings (eq. 25)\n if az>=0:\n q_acc = np.array([np.sqrt((az+1)/2), -ay/np.sqrt(2*(1-ax)), ax/np.sqrt(2*(az+1)), 0.0])\n else:\n q_acc = np.array([-ay/np.sqrt(2*(1-az)), np.sqrt((1-az)/2.0), 0.0, ax/np.sqrt(2*(1-az))])\n q_acc /= np.linalg.norm(q_acc)\n # m_norm = np.linalg.norm(mag)\n if mag is not None and not (np.linalg.norm(mag)>0):\n lx, ly, lz = q2R(q_acc).T@(mag/np.linalg.norm(mag)) # (eq. 26)\n Gamma = lx**2 + ly**2 # (eq. 28)\n # Quaternion from Magnetometer Readings (eq. 35)\n if lx>=0:\n q_mag = np.array([np.sqrt(Gamma+lx*np.sqrt(Gamma))/np.sqrt(2*Gamma), 0.0, 0.0, ly/np.sqrt(2)*np.sqrt(Gamma+lx*np.sqrt(Gamma))])\n else:\n q_mag = np.array([ly/np.sqrt(2)*np.sqrt(Gamma-lx*np.sqrt(Gamma)), 0.0, 0.0, np.sqrt(Gamma-lx*np.sqrt(Gamma))/np.sqrt(2*Gamma)])\n # Generalized Quaternion Orientation (eq. 36)\n q = q_prod(q_acc, q_mag)\n return q/np.linalg.norm(q)\n return q_acc\n\n def updateIMU(self, q: np.ndarray, gyr: np.ndarray, acc: np.ndarray) -> np.ndarray:\n \"\"\"\n Quaternion Estimation with a IMU architecture.\n\n The estimation is made in two steps: a *prediction* is done with the\n angular rate (gyroscope) to integrate and estimate the current\n orientation; then a *correction* step uses the measured accelerometer\n to infer the expected gravity vector and use it to correct the\n predicted quaternion.\n\n If the gyroscope data is invalid, it returns the given a-priori\n quaternion. Secondly, if the accelerometer data is invalid the\n predicted quaternion (using gyroscopes) is returned.\n\n Parameters\n ----------\n q : numpy.ndarray\n A-priori quaternion.\n gyr : numpy.ndarray\n Sample of tri-axial Gyroscope in rad/s.\n acc : numpy.ndarray\n Sample of tri-axial Accelerometer in m/s^2\n\n Returns\n -------\n q : numpy.ndarray\n Estimated quaternion.\n\n \"\"\"\n if gyr is None or not np.linalg.norm(gyr)>0:\n return q\n # PREDICTION\n qDot = -0.5*q_prod([0, *gyr], q) # Quaternion derivative (eq. 38)\n qInt = q + qDot*self.Dt # Quaternion integration (eq. 42)\n qInt /= np.linalg.norm(qInt)\n # CORRECTION\n a_norm = np.linalg.norm(acc)\n if not a_norm>0:\n return qInt\n a = acc/a_norm\n gx, gy, gz = q2R(qInt).T@a # Predicted gravity (eq. 44)\n q_acc = np.array([np.sqrt((gz+1)/2.0), -gy/np.sqrt(2.0*(gz+1)), gx/np.sqrt(2.0*(gz+1)), 0.0]) # Delta Quaternion (eq. 47)\n if self.adaptive:\n self.alpha = self.adaptive_gain(self.alpha, a_norm)\n q_acc = slerp_I(q_acc, self.alpha, self.threshold)\n q_prime = q_prod(qInt, q_acc) # (eq. 53)\n return q_prime/np.linalg.norm(q_prime)\n\n def updateMARG(self, q: np.ndarray, gyr: np.ndarray, acc: np.ndarray, mag: np.ndarray) -> np.ndarray:\n \"\"\"\n Quaternion Estimation with a MARG architecture.\n\n The estimation is made in two steps: a *prediction* is done with the\n angular rate (gyroscope) to integrate and estimate the current\n orientation; then a *correction* step uses the measured accelerometer\n and magnetic field to infer the expected geodetic values. Its\n divergence is used to correct the predicted quaternion.\n\n If the gyroscope data is invalid, it returns the given a-priori\n quaternion. Secondly, if the accelerometer data is invalid the\n predicted quaternion (using gyroscopes) is returned. Finally, if the\n magnetometer measurements are invalid, returns a quaternion corrected\n by the accelerometer only.\n\n Parameters\n ----------\n q : numpy.ndarray\n A-priori quaternion.\n gyr : numpy.ndarray\n Sample of tri-axial Gyroscope in rad/s.\n acc : numpy.ndarray\n Sample of tri-axial Accelerometer in m/s^2\n mag : numpy.ndarray\n Sample of tri-axial Magnetometer in mT\n\n Returns\n -------\n q : numpy.ndarray\n Estimated quaternion.\n\n \"\"\"\n if gyr is None or not np.linalg.norm(gyr)>0:\n return q\n # PREDICTION\n qDot = -0.5*q_prod([0, *gyr], q) # Quaternion derivative (eq. 38)\n qInt = q + qDot*self.Dt # Quaternion integration (eq. 42)\n qInt /= np.linalg.norm(qInt)\n # CORRECTION\n a_norm = np.linalg.norm(acc)\n if not a_norm>0:\n return qInt\n a = acc/a_norm\n gx, gy, gz = q2R(qInt).T@a # Predicted gravity (eq. 44)\n # Accelerometer-Based Quaternion\n q_acc = np.array([np.sqrt((gz+1)/2.0), -gy/np.sqrt(2.0*(gz+1)), gx/np.sqrt(2.0*(gz+1)), 0.0]) # Delta Quaternion (eq. 47)\n if self.adaptive:\n self.alpha = self.adaptive_gain(self.alpha, a_norm)\n q_acc = slerp_I(q_acc, self.alpha, self.threshold)\n q_prime = q_prod(qInt, q_acc) # (eq. 53)\n q_prime /= np.linalg.norm(q_prime)\n # Magnetometer-Based Quaternion\n m_norm = np.linalg.norm(mag)\n if not m_norm>0:\n return q_prime\n lx, ly, lz = q2R(q_prime).T@(mag/m_norm) # World frame magnetic vector (eq. 54)\n Gamma = lx**2 + ly**2 # (eq. 28)\n q_mag = np.array([np.sqrt(Gamma+lx*np.sqrt(Gamma))/np.sqrt(2*Gamma), 0.0, 0.0, ly/np.sqrt(2*(Gamma+lx*np.sqrt(Gamma)))]) # (eq. 58)\n q_mag = slerp_I(q_mag, self.beta, self.threshold)\n # Generalized Quaternion\n q = q_prod(q_prime, q_mag) # (eq. 59)\n return q/np.linalg.norm(q)\n","sub_path":"ahrs/filters/aqua.py","file_name":"aqua.py","file_ext":"py","file_size_in_byte":16314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"142813443","text":"import sqlite3\nimport typing\n\nfrom hydrus.core import HydrusConstants as HC\nfrom hydrus.core import HydrusData\nfrom hydrus.core import HydrusExceptions\nfrom hydrus.core import HydrusTime\n\nfrom hydrus.client import ClientConstants as CC\nfrom hydrus.client import ClientLocation\nfrom hydrus.client import ClientTime\nfrom hydrus.client.db import ClientDBDefinitionsCache\nfrom hydrus.client.db import ClientDBFilesMetadataBasic\nfrom hydrus.client.db import ClientDBFilesStorage\nfrom hydrus.client.db import ClientDBMaster\nfrom hydrus.client.db import ClientDBModule\nfrom hydrus.client.db import ClientDBServices\nfrom hydrus.client.db import ClientDBURLMap\nfrom hydrus.client.importing import ClientImportFiles\nfrom hydrus.client.networking import ClientNetworkingFunctions\n\nclass ClientDBFilesMetadataRich( ClientDBModule.ClientDBModule ):\n \n def __init__(\n self,\n cursor: sqlite3.Cursor,\n modules_services: ClientDBServices,\n modules_hashes: ClientDBMaster.ClientDBMasterHashes,\n modules_files_metadata_basic: ClientDBFilesMetadataBasic.ClientDBFilesMetadataBasic,\n modules_files_storage: ClientDBFilesStorage.ClientDBFilesStorage,\n modules_hashes_local_cache: ClientDBDefinitionsCache.ClientDBCacheLocalHashes,\n modules_url_map: ClientDBURLMap.ClientDBURLMap\n ):\n \n # we could make this guy take urls, tags, ratings, notes, all that, and then make him the MediaResult cache guy\n # he could also probably do file searching too\n \n self.modules_services = modules_services\n self.modules_hashes = modules_hashes\n self.modules_files_metadata_basic = modules_files_metadata_basic\n self.modules_files_storage = modules_files_storage\n self.modules_hashes_local_cache = modules_hashes_local_cache\n self.modules_url_map = modules_url_map\n \n ClientDBModule.ClientDBModule.__init__( self, 'client files rich metadata', cursor )\n \n \n def FilterHashesByService( self, location_context: ClientLocation.LocationContext, hashes: typing.Sequence[ bytes ] ) -> typing.List[ bytes ]:\n \n # returns hashes in order, to be nice to UI\n \n if location_context.IsEmpty():\n \n return []\n \n \n if location_context.IsAllKnownFiles():\n \n return list( hashes )\n \n \n hashes_to_hash_ids = { hash : self.modules_hashes_local_cache.GetHashId( hash ) for hash in hashes if self.modules_hashes.HasHash( hash ) }\n \n valid_hash_ids = self.modules_files_storage.FilterHashIds( location_context, hashes_to_hash_ids.values() )\n \n return [ hash for hash in hashes if hash in hashes_to_hash_ids and hashes_to_hash_ids[ hash ] in valid_hash_ids ]\n \n \n def GetFileHistory( self, num_steps: int ):\n \n # get all sorts of stats and present them in ( timestamp, cumulative_num ) tuple pairs\n \n file_history = {}\n \n # first let's do current files. we increment when added, decrement when we know removed\n \n current_files_table_name = ClientDBFilesStorage.GenerateFilesTableName( self.modules_services.combined_local_media_service_id, HC.CONTENT_STATUS_CURRENT )\n \n current_timestamps = self._STL( self._Execute( 'SELECT timestamp FROM {};'.format( current_files_table_name ) ) )\n \n deleted_files_table_name = ClientDBFilesStorage.GenerateFilesTableName( self.modules_services.combined_local_media_service_id, HC.CONTENT_STATUS_DELETED )\n \n since_deleted = self._STL( self._Execute( 'SELECT original_timestamp FROM {} WHERE original_timestamp IS NOT NULL;'.format( deleted_files_table_name ) ) )\n \n all_known_import_timestamps = list( current_timestamps )\n \n all_known_import_timestamps.extend( since_deleted )\n \n all_known_import_timestamps.sort()\n \n deleted_timestamps = self._STL( self._Execute( 'SELECT timestamp FROM {} WHERE timestamp IS NOT NULL ORDER BY timestamp ASC;'.format( deleted_files_table_name ) ) )\n \n combined_timestamps_with_delta = [ ( timestamp, 1 ) for timestamp in all_known_import_timestamps ]\n combined_timestamps_with_delta.extend( ( ( timestamp, -1 ) for timestamp in deleted_timestamps ) )\n \n combined_timestamps_with_delta.sort()\n \n current_file_history = []\n \n if len( combined_timestamps_with_delta ) > 0:\n \n # set 0 on first file import time\n current_file_history.append( ( combined_timestamps_with_delta[0][0], 0 ) )\n \n if len( combined_timestamps_with_delta ) < 2:\n \n step_gap = 1\n \n else:\n \n step_gap = max( ( combined_timestamps_with_delta[-1][0] - combined_timestamps_with_delta[0][0] ) // num_steps, 1 )\n \n \n total_current_files = 0\n step_timestamp = combined_timestamps_with_delta[0][0]\n \n for ( timestamp, delta ) in combined_timestamps_with_delta:\n \n while timestamp > step_timestamp + step_gap:\n \n current_file_history.append( ( step_timestamp, total_current_files ) )\n \n step_timestamp += step_gap\n \n \n total_current_files += delta\n \n \n \n file_history[ 'current' ] = current_file_history\n \n # now deleted times. we will pre-populate total_num_files with non-timestamped records\n \n ( total_deleted_files, ) = self._Execute( 'SELECT COUNT( * ) FROM {} WHERE timestamp IS NULL;'.format( deleted_files_table_name ) ).fetchone()\n \n deleted_file_history = []\n \n if len( deleted_timestamps ) > 0:\n \n if len( deleted_timestamps ) < 2:\n \n step_gap = 1\n \n else:\n \n step_gap = max( ( deleted_timestamps[-1] - deleted_timestamps[0] ) // num_steps, 1 )\n \n \n step_timestamp = deleted_timestamps[0]\n \n for deleted_timestamp in deleted_timestamps:\n \n while deleted_timestamp > step_timestamp + step_gap:\n \n deleted_file_history.append( ( step_timestamp, total_deleted_files ) )\n \n step_timestamp += step_gap\n \n \n total_deleted_files += 1\n \n \n \n file_history[ 'deleted' ] = deleted_file_history\n \n # and inbox, which will work backwards since we have numbers for archiving. several subtle differences here\n # we know the inbox now and the recent history of archives and file changes\n # working backwards in time (which reverses increment/decrement):\n # - an archive increments\n # - a file import decrements\n # note that we archive right before we delete a file, so file deletes shouldn't change anything for inbox count. all deletes are on archived files, so the increment will already be counted\n # UPDATE: and now we add archived, which is mostly the same deal but we subtract from current files to start and don't care about file imports since they are always inbox but do care about file deletes\n \n inbox_file_history = []\n archive_file_history = []\n \n ( total_inbox_files, ) = self._Execute( 'SELECT COUNT( * ) FROM file_inbox;' ).fetchone()\n total_current_files = len( current_timestamps )\n \n # I now exclude updates and trash my searching 'all my files'\n total_update_files = 0 #self.modules_files_storage.GetCurrentFilesCount( self.modules_services.local_update_service_id, HC.CONTENT_STATUS_CURRENT )\n total_trash_files = 0 #self.modules_files_storage.GetCurrentFilesCount( self.modules_services.trash_service_id, HC.CONTENT_STATUS_CURRENT )\n \n total_archive_files = ( total_current_files - total_update_files - total_trash_files ) - total_inbox_files\n \n # note also that we do not scrub archived time on a file delete, so this upcoming fetch is for all files ever. this is useful, so don't undo it m8\n archive_timestamps = self._STL( self._Execute( 'SELECT archived_timestamp FROM archive_timestamps ORDER BY archived_timestamp ASC;' ) )\n \n if len( archive_timestamps ) > 0:\n \n first_archive_time = archive_timestamps[0]\n \n combined_timestamps_with_deltas = [ ( timestamp, 1, -1 ) for timestamp in archive_timestamps ]\n combined_timestamps_with_deltas.extend( ( ( timestamp, -1, 0 ) for timestamp in all_known_import_timestamps if timestamp >= first_archive_time ) )\n combined_timestamps_with_deltas.extend( ( ( timestamp, 0, 1 ) for timestamp in deleted_timestamps if timestamp >= first_archive_time ) )\n \n combined_timestamps_with_deltas.sort( reverse = True )\n \n if len( combined_timestamps_with_deltas ) > 0:\n \n if len( combined_timestamps_with_deltas ) < 2:\n \n step_gap = 1\n \n else:\n \n # reversed, so first minus last\n step_gap = max( ( combined_timestamps_with_deltas[0][0] - combined_timestamps_with_deltas[-1][0] ) // num_steps, 1 )\n \n \n step_timestamp = combined_timestamps_with_deltas[0][0]\n \n for ( archived_timestamp, inbox_delta, archive_delta ) in combined_timestamps_with_deltas:\n \n while archived_timestamp < step_timestamp - step_gap:\n \n inbox_file_history.append( ( archived_timestamp, total_inbox_files ) )\n archive_file_history.append( ( archived_timestamp, total_archive_files ) )\n \n step_timestamp -= step_gap\n \n \n total_inbox_files += inbox_delta\n total_archive_files += archive_delta\n \n \n inbox_file_history.reverse()\n archive_file_history.reverse()\n \n \n \n file_history[ 'inbox' ] = inbox_file_history\n file_history[ 'archive' ] = archive_file_history\n \n return file_history\n \n \n def GetHashIdStatus( self, hash_id, prefix = '' ) -> ClientImportFiles.FileImportStatus:\n \n if prefix != '':\n \n prefix += ': '\n \n \n hash = self.modules_hashes_local_cache.GetHash( hash_id )\n \n ( is_deleted, timestamp, file_deletion_reason ) = self.modules_files_storage.GetDeletionStatus( self.modules_services.combined_local_file_service_id, hash_id )\n \n if is_deleted:\n \n if timestamp is None:\n \n note = 'Deleted from the client before delete times were tracked ({}).'.format( file_deletion_reason )\n \n else:\n \n note = 'Deleted from the client {} ({}), which was {} before this check.'.format( HydrusTime.TimestampToPrettyTime( timestamp ), file_deletion_reason, HydrusTime.BaseTimestampToPrettyTimeDelta( timestamp ) )\n \n \n return ClientImportFiles.FileImportStatus( CC.STATUS_DELETED, hash, note = prefix + note )\n \n \n result = self.modules_files_storage.GetImportedTimestamp( self.modules_services.trash_service_id, hash_id )\n \n if result is not None:\n \n timestamp = result\n \n note = 'Currently in trash ({}). Sent there at {}, which was {} before this check.'.format( file_deletion_reason, HydrusTime.TimestampToPrettyTime( timestamp ), HydrusTime.BaseTimestampToPrettyTimeDelta( timestamp, just_now_threshold = 0 ) )\n \n return ClientImportFiles.FileImportStatus( CC.STATUS_DELETED, hash, note = prefix + note )\n \n \n result = self.modules_files_storage.GetImportedTimestamp( self.modules_services.combined_local_file_service_id, hash_id )\n \n if result is not None:\n \n timestamp = result\n \n mime = self.modules_files_metadata_basic.GetMime( hash_id )\n \n note = 'Imported at {}, which was {} before this check.'.format( HydrusTime.TimestampToPrettyTime( timestamp ), HydrusTime.BaseTimestampToPrettyTimeDelta( timestamp, just_now_threshold = 0 ) )\n \n return ClientImportFiles.FileImportStatus( CC.STATUS_SUCCESSFUL_BUT_REDUNDANT, hash, mime = mime, note = prefix + note )\n \n \n return ClientImportFiles.FileImportStatus( CC.STATUS_UNKNOWN, hash )\n \n \n def GetHashStatus( self, hash_type, hash, prefix = None ) -> ClientImportFiles.FileImportStatus:\n \n if prefix is None:\n \n prefix = hash_type + ' recognised'\n \n \n if hash_type == 'sha256':\n \n if not self.modules_hashes.HasHash( hash ):\n \n # this used to set the fis.hash = hash here, but that's unhelpful for the callers, who already know the hash and really want to know if there was a good match\n \n return ClientImportFiles.FileImportStatus.STATICGetUnknownStatus()\n \n else:\n \n hash_id = self.modules_hashes_local_cache.GetHashId( hash )\n \n \n else:\n \n try:\n \n hash_id = self.modules_hashes.GetHashIdFromExtraHash( hash_type, hash )\n \n except HydrusExceptions.DataMissing:\n \n return ClientImportFiles.FileImportStatus.STATICGetUnknownStatus()\n \n \n \n return self.GetHashIdStatus( hash_id, prefix = prefix )\n \n \n def GetTablesAndColumnsThatUseDefinitions( self, content_type: int ) -> typing.List[ typing.Tuple[ str, str ] ]:\n \n return []\n \n \n def GetURLStatuses( self, url ) -> typing.List[ ClientImportFiles.FileImportStatus ]:\n \n search_urls = ClientNetworkingFunctions.GetSearchURLs( url )\n \n hash_ids = set()\n \n for search_url in search_urls:\n \n results = self.modules_url_map.GetHashIds( search_url )\n \n hash_ids.update( results )\n \n \n try:\n \n results = [ self.GetHashIdStatus( hash_id, prefix = 'url recognised' ) for hash_id in hash_ids ]\n \n except:\n \n return []\n \n \n return results\n \n \n","sub_path":"hydrus/client/db/ClientDBFilesMetadataRich.py","file_name":"ClientDBFilesMetadataRich.py","file_ext":"py","file_size_in_byte":15324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"524937704","text":"from mygrations.core.parse.parser import parser\nfrom mygrations.formats.mysql.definitions.index import index\n\nclass index_key( parser, index ):\n\n _index_type = 'index'\n has_comma = False\n\n # KEY account_id (account_id,name)\n rules = [\n { 'type': 'literal', 'value': 'KEY' },\n { 'type': 'regexp', 'name': 'name', 'value': '[^\\(\\s\\)]+' },\n { 'type': 'literal', 'value': '(' },\n { 'type': 'delimited', 'name': 'columns', 'separator': ',', 'quote': '`' },\n { 'type': 'literal', 'value': ')' },\n { 'type': 'literal', 'value': ',', 'optional': True, 'name': 'ending_comma' }\n ]\n\n def __init__( self, rules = [] ):\n\n super().__init__( rules )\n\n self._errors = []\n self._warnings = []\n self._columns = []\n\n def process( self ):\n\n self._name = self._values['name'].strip().strip( '`' )\n self._columns = self._values['columns']\n self.has_comma = True if 'ending_comma' in self._values else False\n\n if len( self.name ) > 64:\n self._errors.append( 'Key name %s is too long' % ( self.name ) )\n","sub_path":"mygrations/formats/mysql/file_reader/parsers/index_key.py","file_name":"index_key.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185458987","text":"from bs4 import BeautifulSoup\nimport json\nimport pandas as pd\nimport requests\nfrom pandas.io.json import json_normalize\n\nclass SpectrumScraper:\n def __init__(self, auction_url_list = None):\n self.auction_url_list = auction_url_list if auction_url_list else self.generate_default_auction_url_list()\n self.spectrum_url_base = 'https://ssl.spectrumwine.com'\n def generate_default_auction_url_list(self):\n pass\n\n def get_auction_raw_html(self, url):\n '''\n Recursive function for hitting all the pages of an auction. Goes to a page, grabs the raw html, attempts to\n find the url for the next button. Recursively calls itself on the next page url\n '''\n print('Getting URL:', url)\n r = requests.get(url)\n next_page_url = self.find_next_page_url(r.text)\n if next_page_url is not None:\n next_page_raw_html = self.get_auction_raw_html(next_page_url)\n return [r.text] + next_page_raw_html\n else:\n return([r.text])\n\n def find_next_page_url(self, text):\n soup = BeautifulSoup(text, 'html.parser')\n next_page_tag = soup.find_all('a', title = 'Next Page')\n #While we can find a next page link\n if(next_page_tag[0].has_attr('href')):\n #next_page_tag only contains the relative link. Need to append to the domain name\n formatted_url = self.spectrum_url_base + next_page_tag[0]['href']\n return(formatted_url)\n else:\n return(None)\n\n def parse_raw_html(self, raw_html_auction_pages):\n '''\n Parse the raw html for a single auction, which contains a list of pages\n '''\n parsed_html_auct = list(map(self.parse_single_auction_page_raw_html, raw_html_auction_pages))\n # List of parsed pages, fold them together\n return parsed_html_auct\n\n def parse_single_auction_page_raw_html(self, raw_html_page):\n soup = BeautifulSoup(raw_html_page, 'html.parser')\n #Only grab the table rows we care about\n rows = soup.find_all('tr', id=lambda id: id and \"ctl00_cphContent_ucAuctionLots1_dgLots_ctl00__\" in id)\n parsed_rows = [[field.text for field in row.findAll(['a', 'span'])] for row in rows]\n\n return(parsed_rows)\n\n#test_url = ['https://ssl.spectrumwine.com/auctions/AuctionLots.aspx?AuctionID=543&SessionID=797']\ntest_url = 'https://ssl.spectrumwine.com/auctions/AuctionLots.aspx?AuctionID=543&SessionID=797&ctl00_cphContent_ucAuctionLots1_dgLotsChangePage=90_50'\n\nspectrum_scraper = SpectrumScraper([test_url])\nprint( 'p1', spectrum_scraper.auction_url_list )\nraw_html_auction_list = spectrum_scraper.get_auction_raw_html(test_url)\nprint(len(raw_html_auction_list))\nparsed_auction_list = spectrum_scraper.parse_raw_html(raw_html_auction_list)\nprint(parsed_auction_list)\n#df_auction = spectrum_scraper.convert_to_dataframe(parsed_auction_list)\n\n","sub_path":"Scrapers/spectrum_scraper.py","file_name":"spectrum_scraper.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"348449373","text":"import os\r\nimport sys\r\nimport pdb\r\np = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]\r\nsys.path.append(p)\r\nimport argparse\r\nimport logging\r\nimport torch\r\nimport numpy as np\r\nfrom pprint import pformat, pprint\r\n\r\nfrom datasets import get_dataset\r\nfrom utils.hparams import HParams\r\nfrom utils.test_utils import run_imputation\r\nfrom PIL import Image\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\nfrom transformers import Encoder\r\n#from exnode import ExnodeEncoder\r\n\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\nckpt_path_dict = dict()\r\nckpt_root_dir = './log/air_quality_min_0.8_miss/ckpt/'\r\nckpt_dir = os.path.join(ckpt_root_dir, 'best_model.pt')\r\n\r\nckpt = torch.load(ckpt_dir)\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--cfg_file', type=str)\r\nparser.add_argument('--num_missing', type=int)\r\nparser.add_argument('--save_fig', type=int)\r\nargs = parser.parse_args()\r\nparams = HParams(args.cfg_file)\r\npprint(params.dict)\r\nnp.random.seed(params.seed)\r\ntorch.manual_seed(params.seed)\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\ntorch.autograd.set_detect_anomaly(True)\r\n\r\n\r\n# creat exp dir\r\nif not os.path.exists(params.exp_dir):\r\n os.mkdir(params.exp_dir)\r\nif not os.path.exists(os.path.join(params.exp_dir, 'gen')):\r\n os.mkdir(os.path.join(params.exp_dir, 'gen'))\r\nif not os.path.exists(os.path.join(params.exp_dir, 'ckpt')):\r\n os.mkdir(os.path.join(params.exp_dir, 'ckpt'))\r\nif not os.path.exists(os.path.join(params.exp_dir, 'impute')):\r\n os.mkdir(os.path.join(params.exp_dir, 'impute'))\r\n\r\n\r\ntrain_data, val_data, test_data = get_dataset(params.data_root, params.dataset, False)\r\n\r\ntrain_mean = torch.mean(train_data, 0)\r\ntest_mean = torch.mean(test_data, 0)\r\nmodel = eval(params.model_name)(\r\n max_time_scale=params.max_time_scale,\r\n time_enc_dim=params.time_enc_dim,\r\n time_dim=params.time_dim,\r\n expand_dim=params.expand_dim,\r\n mercer=params.mercer,\r\n n_layers=params.n_layers,\r\n n_head=params.n_heads,\r\n d_k=params.att_dims,\r\n d_v=params.att_dims,\r\n d_model=params.model_dims,\r\n d_inner=params.inner_dims,\r\n d_data=train_data.shape[-1],\r\n dropout=params.dropout,\r\n use_layer_norm=params.layer_norm,\r\n use_gap_encoding=params.use_gap_encoding,\r\n adapter=params.adapter,\r\n use_mask=params.att_mask,\r\n confidence=params.confidence\r\n)\r\nmodel = nn.DataParallel(model).to(device)\r\nprint(model)\r\nprint(\"Start Imputation\")\r\nmodel.load_state_dict(ckpt)\r\nloss = run_imputation(model, params.mode, test_data.repeat(10,1,1), args.num_missing, confidence=params.confidence , max_level=params.max_level, fig_path = os.path.join(params.exp_dir, 'impute'), \r\n save_all_imgs=args.save_fig, dataset=params.dataset, train_mean=train_mean, test_mean=test_mean, gp=params.gp)\r\n\r\noutput_str = 'Testing_Loss: %4f' % (loss)\r\nprint(output_str)\r\n","sub_path":"codes_partially_observed_dimension/impute.py","file_name":"impute.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"583613576","text":"from database import Database\nfrom twitter_utils import get_request_token, get_oauth_verifier, get_access_token\nfrom user import User\n\nDatabase.initialise(\n\tuser='peter',\n\tpassword='hp271008',\n\tdatabase='learning',\n\thost='localhost'\n)\n\nuser_screen_name = raw_input(\"Enter your Twitter screen name: \")\nuser = User.load_from_db_by_screen_name(user_screen_name)\n\nif not user:\n\trequest_token = get_request_token()\n\toauth_verifier = get_oauth_verifier(request_token)\n\taccess_token = get_access_token(request_token, oauth_verifier)\n\n\tuser = User(user_screen_name, access_token['oauth_token'], access_token['oauth_token_secret'], None)\n\tuser.save_to_db()\n\n\ntweets = user.twitter_request('https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images')\n\nfor tweet in tweets['statuses']:\n print(tweet['text'])\n","sub_path":"python_postgres_twitter/twitter/project/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"40899681","text":"\n\n#Config Settings\ndll_path = r\"C:\\Users\\kalyan\\Desktop\\5775_digitizer\\Host\\5775_acq_dll\\SharedLib.dll\"\nbitfile_path = r\"C:\\Users\\kalyan\\Desktop\\5775_digitizer\\Host\\PXIe_5775_KU035.lvbitx\"\n\n\nfrom ctypes import *\nimport ctypes\nfrom sys import exit\nimport numpy as np\nnp.set_printoptions(formatter={'float': lambda x: \"{0:0.6f}\".format(x)})\n\ndef get_5775_data(bitfile_path = '',device_name ='RIO0', channel_names = 'AI0', num_samples = 320):\n try:\n \n if not bitfile_path:\n raise Exception(\" Input bitfile path is empty\")\n\n _acq_sess = cdll.LoadLibrary(dll_path)\n c_bitfile_path = c_char_p(bitfile_path.encode('utf-8'))\n c_device_name = c_char_p(device_name.encode('utf-8'))\n c_channel_names = c_char_p(channel_names.encode('utf-8'))\n c_num_samples = c_uint64(num_samples)\n c_FirstChannel = (c_double *num_samples)()\n c_SecondChannel = (c_double *num_samples)()\n c_FirstChannel_ptr = pointer(c_FirstChannel)\n c_SecondChannel_ptr = pointer(c_SecondChannel)\n c_dt = c_double(0)\n c_dt_ptr = pointer(c_dt)\n\n status = _acq_sess.GettingStarted_5775_Host_Basic_pn_SH(c_bitfile_path, c_device_name, c_channel_names, c_num_samples, c_FirstChannel_ptr, c_int32(num_samples), c_SecondChannel_ptr, c_int32(num_samples), c_dt_ptr)\n\n if status != 0:\n raise Exception(\" LabVIEW DLL Status Error reported as {}\".format(status))\n\n FirstChannel = np.array(np.fromiter(c_FirstChannel, dtype=np.double, count=num_samples))\n SecondChannel = np.array(np.fromiter(c_SecondChannel, dtype=np.double, count=num_samples))\n dt = c_dt.value\n return FirstChannel, SecondChannel, dt, status\n\n except Exception as e:\n print('Error in function get_5775_data :', e)\n return None, None, None, None\n\n\ntry:\n FirstChannel, SecondChannel, dt, status = get_5775_data(bitfile_path, 'PXI1Slot5')\n print(\"First Channel : {} \".format(FirstChannel))\n print(\"Smaple Period : \", dt)\n\nexcept Exception as e:\n print('Error :', e)\n\n","sub_path":"Host/5775_acq_dll/5775_acq.py","file_name":"5775_acq.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"421667879","text":"import unittest\n\nclass Stack(object):\n\n class StackNode(object):\n def __init__(self, item):\n self.item = item\n self.next = None\n\n\n def __init__(self):\n self.top = None\n\n def pop(self):\n if self.top is None:\n return None\n item = self.top.item\n self.top = self.top.next\n return item\n\n\n def push(self, item):\n old = self.top\n self.top = Stack.StackNode(item)\n self.top.next = old\n\n def peek(self):\n if self.top is None:\n return None\n else:\n return self.top.item\n\n def is_empty(self):\n return self.top is None\n\n\nclass StackTest(unittest.TestCase):\n\n def test_empty_stack(self):\n stack = Stack()\n self.assertIsNone(stack.pop())\n self.assertIsNone(stack.peek())\n self.assertTrue(stack.is_empty())\n stack.push(5)\n self.assertEqual(stack.pop(), 5)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/main/python/chap03StacksQueues/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"124783949","text":"import requests\nr = requests.get(\"https://movie.douban.com/chart\")\n\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(r.text, \"html.parser\")\n\nnames = soup.find_all(\"a\", \"nbg\")\n\n\nmarks = soup.find_all(\"span\", \"rating_nums\")\n\nfor name, mark in zip(names, marks):\n data = {\n '电影' : name.get(\"title\"),\n '评分' : mark.get_text()\n }\n print(data)\n","sub_path":"weekly_newmovie.py","file_name":"weekly_newmovie.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"576666386","text":"# pcinput\n# input functions that check for type\n# Pieter Spronck\n\n# These functions are rather ugly as they print error messages if something is wrong.\n# However, they are meant for a course, which means they are used by students who\n# are unaware (until the end of the course) of exceptions and things like that.\n\n# This function asks for a floating-point number. You may use it for the exercises.\n# The parameter is a prompt that is displayed when the number is asked.\n# The function uses an exception to check whether the input is actually\n# a floating-point number. We will discuss exceptions in the future, just use the\n# function as is for now.\n# To use the function, write something like:\n# myNumber = rsdpu.getFloat( \"Give me a number> \" )\n# This will then ask the user of the program for a floating-point number, and will store\n# whatever the user entered in myNumber. It will also make sure that actually\n# a floating-point number or an integer is entered; if the user enters anything else,\n# an error message is displayed and the user has to enter something else.\ndef getFloat( prompt ):\n\twhile True:\n\t\ttry:\n\t\t\tnum = float( input( prompt ) )\n\t\texcept ValueError:\n\t\t\tprint( \"That is not a number -- please try again\" )\n\t\t\tcontinue\n\t\treturn num\n\n# Similar for getting integers.\ndef getInteger( prompt ):\n\twhile True:\n\t\ttry:\n\t\t\tnum = int( input( prompt ) )\n\t\texcept ValueError:\n\t\t\tprint( \"That is not an integer -- please try again\" )\n\t\t\tcontinue\n\t\treturn num\n\n# And for strings (leading and trailing spaces are removed)\ndef getString( prompt ):\n\tline = input( prompt )\n\treturn line.strip()\n\n# And for getting one upper-case letter\ndef getLetter( prompt ):\n\twhile True:\n\t\tline = input( prompt )\n\t\tline = line.strip()\n\t\tline = line.upper()\n\t\tif len( line ) != 1:\n\t\t\tprint( \"Please enter exactly one character\" )\n\t\t\tcontinue\n\t\tif line < 'A' or line > 'Z':\n\t\t\tprint( \"Please enter a letter from the alphabet\" )\n\t\t\tcontinue\n\t\treturn line\n","sub_path":"notebooks uni/pcinput.py","file_name":"pcinput.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"359060291","text":"\"\"\"\nFile watch commercial remover\n\"\"\"\nimport os\nimport subprocess\nimport logging\nimport shutil\nimport sys\nimport time\nfrom threading import Thread\nfrom queue import Queue\n\nWORK_ROOT = \"/config/\"\n\n_LOGGER = logging.getLogger(__name__)\nlogging.basicConfig(filename=WORK_ROOT+'watcher.log', filemode='a', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n\nIN_PROCESS = set()\n\n\nclass CommercialWorker(Thread):\n \"\"\"Commercial process queue\"\"\"\n def __init__(self, queue):\n Thread.__init__(self)\n self.queue = queue\n\n def run(self):\n while True:\n # Get paths\n pid_path, file_path = self.queue.get()\n try:\n find_commercials(pid_path, file_path)\n finally:\n self.queue.task_done()\n\n\ndef find_commercials(pid_path, file_path):\n \"\"\"Call comchap to find commercials\"\"\"\n # file_path = file_path.rstrip()\n\n # print(pid_path)\n # print(file_path)\n # return\n\n # Check to make sure file exists first\n if os.path.isfile(file_path):\n _LOGGER.info(\"Processing: \" + file_path)\n\n name = os.path.splitext(os.path.basename(file_path))[0]\n path = os.path.dirname(file_path)\n\n # Make backup of original in case something goes wrong and\n # store it's size for comparison later\n backup = os.path.join(path, name + \".mkv.bak\")\n shutil.copy(file_path, backup)\n backup_size = os.path.getsize(backup)\n _LOGGER.info(\"Backup Created (%s): %s\", backup_size, backup)\n\n # Start commercial processing\n cmd = ['/opt/comchap/comchap',\n '--keep-edl',\n '--cuvid',\n '--comskip=/opt/Comskip/comskip',\n '--comskip-ini=/opt/Comskip/comskip.ini',\n file_path]\n try:\n result = subprocess.run(cmd, stdout=subprocess.DEVNULL, timeout=5400)\n _LOGGER.debug(\"Subprocess finished (code: %s) for: %s\", result.returncode, file_path)\n except subprocess.TimeoutExpired as err:\n # Timeout expired before we had a result\n _LOGGER.debug(\"1:30hr timeout expired for: %s, code: %s\", file_path, result.returncode)\n # If we end up here we need to make sure the backup is restored\n shutil.move(backup, file_path)\n # Remove working indicator\n os.remove(pid_path)\n IN_PROCESS.remove(file_path)\n\n if result.returncode == 0:\n _LOGGER.info(\"Commercial chapters inserted into: \" + file_path)\n # Explicitly set new file permissions\n shutil.chown(file_path, 99, 100)\n os.chmod(file_path, 0o644)\n\n # Make sure new file exists and is in the size ballpark\n if os.path.isfile(file_path):\n new_size = os.path.getsize(file_path)\n if new_size > (backup_size*.9):\n # New is at least 90% of backup, we can move on\n # Remove path from process set and delete file\n try:\n os.remove(pid_path)\n IN_PROCESS.remove(file_path)\n os.remove(backup)\n except OSError as err:\n _LOGGER.error(\"File removal error: \" + err)\n else:\n _LOGGER.error(\"New file size incorrect (B: %s, N: %s) Restoring Backup.\", backup_size, new_size)\n # New file size isn't what we expect, restore the backup\n shutil.move(backup, file_path)\n # Remove working indicators\n os.remove(pid_path)\n IN_PROCESS.remove(file_path) # Only removing this would allow a retry\n else:\n _LOGGER.error(\"New file doesn't exist, restoring backup.\")\n shutil.move(backup, file_path)\n # Remove working indicator from set to try again\n IN_PROCESS.remove(file_path)\n else:\n if result.stderr:\n # Something went wrong in commercial processing\n _LOGGER.error(\"Comchap error: %s\", result.stderr)\n else:\n _LOGGER.error(\"Unknown Comchap error (%s) for file: %s, Restoring backup.\", result.returncode, file_path)\n # If we end up here we need to make sure the backup is restored\n shutil.move(backup, file_path)\n # Remove working indicator\n os.remove(pid_path)\n IN_PROCESS.remove(file_path)\n else:\n # File doesn't exist, we can't do anything\n _LOGGER.info(\"%s does not exist, nothing to do...\", file_path)\n # Remove working indicator\n os.remove(pid_path)\n IN_PROCESS.remove(file_path)\n\n\ndef main():\n \"\"\"Main function.\"\"\"\n watch_path = os.fsencode(sys.argv[1])\n\n queue = Queue()\n\n for xwork in range(5):\n worker = CommercialWorker(queue)\n worker.daemon = True\n worker.start()\n\n queue.join()\n\n _LOGGER.info(\"Starting Loop...\")\n\n while True:\n # Check folder for new file tasks\n for item in os.scandir(watch_path):\n if item.is_file():\n pid = item.path.decode('utf-8')\n if pid.endswith(\".comm\"):\n # New comm task to process\n with open(pid) as fop:\n fpath = fop.readline().rstrip()\n if fpath not in IN_PROCESS:\n IN_PROCESS.add(fpath)\n queue.put((pid, fpath))\n\n # Check every 5s to limit I/O\n time.sleep(5)\n\nif __name__ == '__main__':\n main()\n","sub_path":"file_watch.py","file_name":"file_watch.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"485479042","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport os\nimport sys\nfrom io import StringIO\nimport numpy as np\nfrom pyiron_base.generic.hdfio import FileHDFio\nfrom pyiron_base._tests import PyironTestCase\nimport unittest\n\n\nclass TestFileHDFio(PyironTestCase):\n @classmethod\n def setUpClass(cls):\n cls.current_dir = os.path.dirname(os.path.abspath(__file__)).replace(\"\\\\\", \"/\")\n cls.empty_hdf5 = FileHDFio(file_name=cls.current_dir + \"/filehdfio_empty.h5\")\n cls.full_hdf5 = FileHDFio(file_name=cls.current_dir + \"/filehdfio_full.h5\")\n cls.i_o_hdf5 = FileHDFio(file_name=cls.current_dir + \"/filehdfio_io.h5\")\n cls.es_hdf5 = FileHDFio(\n file_name=cls.current_dir + \"/../static/dft/es_hdf.h5\"\n )\n with cls.full_hdf5.open(\"content\") as hdf:\n hdf[\"array\"] = np.array([1, 2, 3, 4, 5, 6])\n hdf[\"array_3d\"] = np.array([[1, 2, 3], [4, 5, 6]])\n hdf[\"traj\"] = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9]]], dtype=object)\n hdf[\"dict\"] = {\"key_1\": 1, \"key_2\": \"hallo\"}\n hdf[\"dict_numpy\"] = {\"key_1\": 1, \"key_2\": np.array([1, 2, 3, 4, 5, 6])}\n with hdf.open('group') as grp:\n grp['some_entry'] = 'present'\n with cls.i_o_hdf5.open(\"content\") as hdf:\n hdf[\"exists\"] = True\n # Open and store value in a hdf file to use test_remove_file on it, do not use otherwise\n cls.to_be_removed_hdf = FileHDFio(file_name=cls.current_dir + '/filehdfio_tbr.h5')\n with cls.to_be_removed_hdf.open('content') as hdf:\n hdf['value'] = 1\n # Remains open to be closed by test_close, do not use otherwise\n cls.opened_hdf = cls.full_hdf5.open(\"content\")\n\n @classmethod\n def tearDownClass(cls):\n cls.current_dir = os.path.dirname(os.path.abspath(__file__)).replace(\"\\\\\", \"/\")\n os.remove(cls.current_dir + \"/filehdfio_full.h5\")\n os.remove(cls.current_dir + \"/filehdfio_io.h5\")\n\n def _check_full_hdf_values(self, hdf):\n self.assertTrue(\n all(np.equal(hdf[\"content/array\"], np.array([1, 2, 3, 4, 5, 6])))\n )\n self.assertTrue(\n all(\n np.equal(\n hdf[\"content\"][\"array_3d\"],\n np.array([[1, 2, 3], [4, 5, 6]]),\n ).flatten()\n )\n )\n self.assertTrue(\n all(\n np.equal(\n hdf[\"content/traj\"][0], np.array([[1, 2, 3], [4, 5, 6]])\n ).flatten()\n )\n )\n self.assertTrue(\n all(\n np.equal(\n hdf[\"content/traj\"][1], np.array([[7, 8, 9]])\n ).flatten()\n )\n )\n self.assertEqual(hdf[\"content/dict\"][\"key_1\"], 1)\n self.assertEqual(hdf[\"content/dict\"][\"key_2\"], \"hallo\")\n self.assertEqual(hdf[\"content/dict_numpy\"][\"key_1\"], 1)\n self.assertTrue(\n all(\n np.equal(\n hdf[\"content/dict_numpy\"][\"key_2\"],\n np.array([1, 2, 3, 4, 5, 6]),\n )\n )\n )\n self.assertEqual(hdf['content/group/some_entry'], 'present')\n\n def test_get_item(self):\n self._check_full_hdf_values(self.full_hdf5)\n # Test leaving to pyiron Project at hdf file location:\n pr = self.full_hdf5['content/..']\n from pyiron_base import Project\n self.assertIsInstance(pr, Project)\n self.assertEqual(pr.path, self.full_hdf5.file_path + '/')\n # Test leaving to pyiron Project at other than hdf file location:\n pr = self.full_hdf5['..']\n self.assertIsInstance(pr, Project)\n self.assertEqual(pr.path.replace(\"\\\\\", \"/\"),\n os.path.normpath(\n os.path.join(self.full_hdf5.file_path, '..')\n ).replace(\"\\\\\", \"/\") + '/'\n )\n # Test getting a new FileHDFio object:\n group_hdf = self.full_hdf5['content/group']\n self.assertIsInstance(group_hdf, FileHDFio)\n self.assertEqual(group_hdf.h5_path, '/content/group')\n # Test getting the parent FileHDFio object:\n content_hdf = group_hdf['..']\n self.assertIsInstance(content_hdf, FileHDFio)\n self.assertEqual(content_hdf.h5_path, self.full_hdf5.h5_path + 'content')\n # Getting the '/' of the hdf would result in a path which already belongs to the project.\n # Therefore, the project is returned instead.\n pr = content_hdf['..']\n self.assertIsInstance(pr, Project)\n self.assertEqual(pr.path, self.full_hdf5.file_path + '/')\n # Test getting the same object directly:\n pr = group_hdf['../..']\n self.assertIsInstance(pr, Project)\n self.assertEqual(pr.path, self.full_hdf5.file_path + '/')\n\n def test_file_name(self):\n self.assertEqual(\n self.empty_hdf5.file_name, self.current_dir + \"/filehdfio_empty.h5\"\n )\n self.assertEqual(\n self.full_hdf5.file_name, self.current_dir + \"/filehdfio_full.h5\"\n )\n\n def test_h5_path(self):\n self.assertEqual(self.full_hdf5.h5_path, '/')\n\n def test_open(self):\n opened_hdf = self.full_hdf5.open('content')\n self.assertEqual(opened_hdf.h5_path, '/content')\n self.assertEqual(opened_hdf.history[-1], 'content')\n\n def test_close(self):\n self.opened_hdf.close()\n self.assertEqual(self.opened_hdf.h5_path, '/')\n\n def test_remove_file(self):\n path = self.to_be_removed_hdf.file_name\n self.to_be_removed_hdf.remove_file()\n self.assertFalse(os.path.isfile(path))\n\n def test_get_from_table(self):\n pass\n\n def test_get_pandas(self):\n pass\n\n def test_get(self):\n self.assertEqual(self.full_hdf5.get(\"doesnotexist\", default=42), 42,\n \"default value not returned when value doesn't exist.\")\n self.assertTrue(np.array_equal(\n self.full_hdf5.get(\"content/array\", default=42),\n np.array([1, 2, 3, 4, 5, 6])\n ), \"default value returned when value does exist.\")\n with self.assertRaises(ValueError):\n self.empty_hdf5.get('non_existing_key')\n\n def test_hd_copy(self):\n new_hdf_file = os.path.join(self.current_dir, 'copy_full.h5')\n new_hdf = FileHDFio(file_name=new_hdf_file)\n new_hdf = self.full_hdf5.hd_copy(self.full_hdf5, new_hdf)\n self._check_full_hdf_values(new_hdf)\n os.remove(new_hdf_file)\n\n def test_groups(self):\n groups = self.full_hdf5.groups()\n # _filter is actually relies on the _filter property of the Project, thus groups does not do anything.\n self.assertIsInstance(groups, FileHDFio)\n\n def test_rewrite_hdf5(self):\n pass\n\n def test_to_object(self):\n pass\n\n def test_put(self):\n self.i_o_hdf5.put('answer', 42)\n self.assertEqual(self.i_o_hdf5['answer'], 42)\n\n def test_list_all(self):\n empty_file_dict = self.empty_hdf5.list_all()\n self.assertEqual(empty_file_dict[\"groups\"], [])\n self.assertEqual(empty_file_dict[\"nodes\"], [])\n es_file_dict = self.es_hdf5.list_all()\n self.assertEqual(es_file_dict[\"groups\"], [\"es_new\", \"es_old\"])\n self.assertEqual(es_file_dict[\"nodes\"], [])\n es_group_dict = self.es_hdf5[\"es_new\"].list_all()\n self.assertEqual(es_group_dict[\"groups\"], [\"dos\"])\n self.assertEqual(\n es_group_dict[\"nodes\"],\n [\"TYPE\", \"efermi\", \"eig_matrix\", \"k_points\", \"k_weights\", \"occ_matrix\"],\n )\n\n def test_list_nodes(self):\n self.assertEqual(self.empty_hdf5.list_nodes(), [])\n self.assertEqual(\n self.es_hdf5[\"es_new\"].list_nodes(),\n [\"TYPE\", \"efermi\", \"eig_matrix\", \"k_points\", \"k_weights\", \"occ_matrix\"],\n )\n\n def test_list_groups(self):\n self.assertEqual(self.empty_hdf5.list_groups(), [])\n self.assertEqual(self.es_hdf5.list_groups(), [\"es_new\", \"es_old\"])\n\n def test_listdirs(self):\n self.assertEqual(self.empty_hdf5.listdirs(), [])\n self.assertEqual(self.es_hdf5.listdirs(), [\"es_new\", \"es_old\"])\n\n def test_show_hdf(self):\n sys_stdout = sys.stdout\n result = StringIO()\n sys.stdout = result\n self.full_hdf5.show_hdf()\n result_string = result.getvalue()\n sys.stdout = sys_stdout\n self.assertEqual(result_string,\n 'group: content\\n node array\\n node array_3d\\n node dict\\n node dict_numpy\\n' +\n ' node traj\\n group: group\\n node some_entry\\n'\n )\n\n def test_is_empty(self):\n self.assertTrue(self.empty_hdf5.is_empty)\n self.assertFalse(self.full_hdf5.is_empty)\n\n def test_is_root(self):\n self.assertTrue(self.full_hdf5.is_root)\n hdf = self.full_hdf5['content']\n self.assertFalse(hdf.is_root)\n\n def test_base_name(self):\n self.assertEqual(self.full_hdf5.base_name, 'filehdfio_full')\n self.assertEqual(self.empty_hdf5.base_name, 'filehdfio_empty')\n self.assertEqual(self.i_o_hdf5.base_name, 'filehdfio_io')\n\n def test_file_size(self):\n self.assertTrue(self.es_hdf5.file_size(self.es_hdf5) > 0)\n\n def test_get_size(self):\n self.assertTrue(self.es_hdf5.get_size(self.es_hdf5) > 0)\n\n def test_copy(self):\n copy = self.es_hdf5.copy()\n self.assertIsInstance(copy, FileHDFio)\n self.assertEqual(copy.h5_path, self.es_hdf5.h5_path)\n\n # results in an Error\n # File \"C:\\Users\\Siemer\\pyiron_git\\pyiron_base\\tests\\generic\\test_fileHDFio.py\", line 249, in test_copy_to\n # copy = self.full_hdf5.copy_to(destination)\n # File \"C:\\Users\\Siemer\\pyiron_git\\pyiron_base\\pyiron_base\\generic\\hdfio.py\", line 355, in copy_to\n # _internal_copy(source=f_source, source_path=self._h5_path, target=f_target,\n # File \"C:\\Users\\Siemer\\pyiron_git\\pyiron_base\\pyiron_base\\generic\\hdfio.py\", line 332, in _internal_copy\n # source.copy(source_path, target, name=target_path)\n # File \"C:\\Users\\Siemer\\anaconda3\\envs\\pyiron_git\\lib\\site-packages\\h5py\\_hl\\group.py\", line 494, in copy\n # h5o.copy(source.id, self._e(source_path), dest.id, self._e(dest_path),\n # File \"h5py\\_objects.pyx\", line 54, in h5py._objects.with_phil.wrapper\n # File \"h5py\\_objects.pyx\", line 55, in h5py._objects.with_phil.wrapper\n # File \"h5py\\h5o.pyx\", line 217, in h5py.h5o.copy\n # ValueError: No destination name specified (no destination name specified)\n #def test_copy_to(self):\n # file_name = self.current_dir + '/filehdfio_tmp'\n # destination = FileHDFio(file_name=file_name)\n # copy = self.full_hdf5.copy_to(destination)\n # self._check_full_hdf_values(copy)\n # os.remove(file_name)\n\n def test_remove_group(self):\n grp = 'group_to_be_removed'\n hdf = self.i_o_hdf5.create_group(grp)\n # If nothing is written to the group, the creation is not reflected by the HDF5 file\n hdf['key'] = 1\n self.assertTrue(grp in self.i_o_hdf5.list_groups())\n hdf.remove_group()\n self.assertFalse(grp in self.i_o_hdf5.list_nodes())\n # This should not raise an error, albeit the group of hdf is removed\n hdf.remove_group()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/generic/test_fileHDFio.py","file_name":"test_fileHDFio.py","file_ext":"py","file_size_in_byte":11590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"288858436","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm, gaussian_kde\nfrom scipy.special import softmax, logsumexp\n\nraw_col = '#029386'\ncluster_cols = {0: '#0343df', 1: '#e50000', 2:'#f97306', 3: '#15b01a'} \n\n\ndef simulate_data(plot = True):\n\n\tnsamples = 5000\n\n\ta_sd = 1\n\ta_mean = 3\n\ta_prop = 2\n\n\tb_mean = -2\n\tb_sd = 2\n\tb_prop = 1\n\tproportions = [a_prop, b_prop]\n\tproportions /= np.sum(proportions, axis = 0)\n\t#print(props)\n\ta = np.random.randn(int(nsamples*proportions[0]))*a_sd + a_mean\n\tb = np.random.randn(int(nsamples*proportions[1]))*b_sd + b_mean\n\n\tX = np.concatenate( (a,b) )\n\n\t\n\tif plot: \n\t\tdensity = gaussian_kde(X)\n\t\trg = np.linspace(min(X),max(X),500)\n\t\tplt.plot(rg,density(rg), raw_col, linewidth = 1) #row=0, col=0\n\t\tplt.plot(rg, norm.pdf(rg, a_mean, a_sd)*proportions[0], color = cluster_cols[0], linewidth = 1) \n\t\tplt.plot(rg, norm.pdf(rg, b_mean, b_sd)*proportions[1], color = cluster_cols[1], linewidth = 1)\n\t\tplt.show()\n\n\treturn(X)\n\ndef gmm_em(x, n_clust, plot = True, iter = 100, tol = 1e-4):\n\n\t\"\"\"fits a guassian mixture model through expectation-maximisation\"\"\"\n\n\t#initialise means and sds and props\n\tmeans = np.random.randn(n_clust)\n\tsds = np.ones(n_clust)\n\tprops = np.full(n_clust, 1/n_clust) #this has an array of size n_clust summing to one\n\tn_obs = x.shape[0]\n\tlik_hist = [] #for convergence\n\n\tfor i in range(iter):\n\n\t\tif plot:\n\t\t\tplt.cla()\n\t\t\tdensity = gaussian_kde(x)\n\t\t\trg = np.linspace(min(x),max(x),500)\n\t\t\tplt.plot(rg, density(rg), color = raw_col)\n\t\t\tfor c, (m, s, p) in enumerate(zip(means, sds, props)):\n\t\t\t\tplt.plot(rg, norm.pdf(rg, m, s)*p, color = cluster_cols[c]) \t\t\t\n\t\t\tplt.draw()\n\t\t\tplt.pause(.2)\n\n\t\t#EXPECTATION STEP\n\t\t#compute likelihood of latent labels (i.e. belonging to each cluster)\t\t\n\t\tliks = np.zeros([n_clust,n_obs])\n\t\tfor c in range(n_clust): \n\t\t\tprior = props[c] #props is cluster size\n\t\t\tloglik = norm.logpdf(x, means[c], sds[c]) + np.log(props[c])\n\t\t\tliks[c] = loglik\n\t\t\t \t\t\t\n\t\ttotal_lik = np.sum(logsumexp(liks, axis=0)) \n\t\tlik_hist.append(total_lik) \n\n\t\tresps = softmax(liks, axis=0) #responsibility vector for each sample\t\t\n\t\t\n\t\tprops = np.sum(resps, axis = 1) #to update estimates of cluster size take sum of total weights and divide by n observations\n\t\tprops /= n_obs\t\t\t\n\n\t\t#check convergence\n\t\tif i > 0: \n\t\t\tlik_change = total_lik - lik_hist[-2]\n\t\t\t# print(lik_change)\n\t\t\tassert(lik_change > 0)\n\t\t\tif lik_change < tol: \n\t\t\t\tfit = {\n\t\t\t\t\t'data':X,\n\t\t\t\t\t'means':means,\n\t\t\t\t\t'sds':sds,\n\t\t\t\t\t'props':props,\n\t\t\t\t\t'lik_hist':lik_hist,\n\t\t\t\t\t'resps':resps \n\t\t\t\t}\n\t\t\t\tprint(\"converged on step: \", i) \n\t\t\t\treturn (fit) \n\n\t\t#MAXIMISATION STEP to obtain new means and sds, given the expectations/responsibilities\n\t\tmeans = [np.average(x, weights = r) for r in resps] #weighted average \n\t\tsds = [ np.average((x-m)**2, weights = r) for m, r in zip(means, resps)] #weighted variance\n\t\tsds = np.sqrt(sds)\n\nif __name__ == '__main__':\n\tX = simulate_data(plot = True)\n\tgmm_em(X, 2, plot = True)\n\n","sub_path":"Processing/gmm_1d_example.py","file_name":"gmm_1d_example.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"61601254","text":"import re\nimport json\nimport urllib\nimport requests\nimport os\nimport time\nimport selenium.webdriver as wd\nfrom PIL import Image as im\n\n\nclass Douban(object):\n\n def __init__(self, url):\n \"\"\"\n 初始化item页信息\n :param url: 需要抓取的豆瓣电��页\n \"\"\"\n self.target_url = url\n if not os.path.exists('./'):\n os.mkdir('./src')\n self.driver = wd.Chrome()\n self.driver.maximize_window()\n self.driver.get(url)\n with open('./src/item_page.html', 'w', encoding='utf-8') as f:\n f.write(self.driver.page_source)\n # self.driver.close()\n with open('./src/item_page.html', 'r', encoding='utf-8') as f:\n self.html = f.read()\n self.data = {}\n self.basic_dir = os.path.abspath('./')\n self.header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\"}\n\n def init_data(self):\n \"\"\"\n 初始化部分电影信息\n :return:\n \"\"\"\n # 获取item名称\n _name_reg = re.compile(\n r'(.*?)', re.S)\n self.data['movie_name'] = re.findall(_name_reg, self.html)[0]\n\n # 获取item发布年份\n _released_year_reg = re.compile(\n r'\\((.*?)\\)', re.S)\n self.data['released_year'] = re.findall(\n _released_year_reg, self.html)[0]\n\n # 获取item海报url\n _posters_url_reg = re.compile(\n r'', re.S)\n self.data['posters'] = re.findall(_posters_url_reg, self.html)\n # 获取item主创姓名\n _main_team_reg = re.compile(r'(.*?)', re.S)\n for line in self.html.split('\\n'):\n if '导演' in line:\n self.data['director'] = re.findall(_main_team_reg, line)\n elif '编剧' in line:\n self.data['screenwriter'] = re.findall(_main_team_reg, line)\n elif '主演' in line:\n self.data['actor'] = re.findall(_main_team_reg, line)[:-1]\n\n # 获取item类型\n _type_reg = re.compile(r'(.*?)', re.S)\n self.data['type'] = re.findall(_type_reg, self.html)\n\n # 获取item发行地\n _state_reg = re.compile(\n r'制片国家/地区:(.*?)
', re.S)\n self.data['state'] = [item.strip()\n for item in re.findall(_state_reg, self.html)]\n\n # 获取item发行时间\n _released_time_reg = re.compile(\n r'initialReleaseDate.*?>([\\d]{4}-[\\d]{2}-[\\d]{2})\\((.*?)\\).*?>', re.S)\n self.data['released_time'] = [{item[-1]: item[0]}\n for item in re.findall(_released_time_reg, self.html)]\n\n # 获取item简介\n _summary_reg = re.compile(r'v:summary.*?>(.*?)
(.*?)', re.S)\n self.data['summary'] = '\\t' + '\\n\\t'.join([''.join(element) for element in [re.split(\n r'[\\s]', item) for item in re.findall(_summary_reg, self.html)[0]]])\n\n # 获取item主创名\n _main_team_name_reg = re.compile(\n r'
  • .*?
    (.*?)<.*?class=\"role\".*?>(.*?)<',\n re.S)\n self.data['main_team_info'] = [{'name': item[1], 'role': ' '.join(item[-1].split(' ')[1:]) if len(\n item[-1].split(' ')) != 1 else item[-1], 'avatar': item[0]} for item in\n re.findall(_main_team_name_reg, self.html)]\n\n # 获取item剧照url\n # _poster_url_reg = re.compile(\n # r'
    图片', re.S)\n # self.data['stills'] = re.findall(_poster_url_reg, self.html)\n self.data['stills'] = self.data['posters'][0][:-1] + 'S'\n\n def build_dir(self):\n \"\"\"\n 为电影创建目录结构\n .\n +-- movie_item.py\n +-- movie_name/\n | +-- main_team/\n | +-- posters/\n | +-- stills/\n | +-- movie_name_info.json\n\n :return:\n \"\"\"\n if not os.path.exists(f'./{self.data[\"movie_name\"]}'):\n os.mkdir(self.data['movie_name'])\n os.chdir(os.path.abspath(f'./{self.data[\"movie_name\"]}'))\n self.item_abs_path = os.path.abspath('./')\n for dir_name in ['./posters', './main_team', './stills']:\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\n # if not os.path.exists('./posters'):\n # os.mkdir('./posters')\n # elif not os.path.exists('./main_team'):\n # os.mkdir('./main_team')\n # elif not os.path.exists('./stills'):\n # os.mkdir('./stills')\n\n def webp_2_jpeg(self, bname, aname):\n \"\"\"\n webp 转 jpg\n :param bname: 转换前文件名,可以包含路径\n :param aname: 转换后文件名,可以包含路径\n :return:\n \"\"\"\n im.open(bname).save(aname)\n os.remove(bname)\n\n def download(self, type, name, url):\n \"\"\"\n 下载页面图片\n :param type: 图片分类\n :param name: 图片名\n :param url: 图片url\n :return:\n \"\"\"\n res = requests.get(url, headers=self.header)\n if res.status_code == 200:\n with open(f'./{type}/{name}.webp', 'wb') as w:\n w.write(res.content)\n self.webp_2_jpeg(f'./{type}/{name}.webp', f'./{type}/{name}.jpg')\n\n def get_element_page(self, url):\n \"\"\"\n 获取跳转页html\n :param url: 需要获取的跳转页url\n :return:\n \"\"\"\n self.driver.get(url)\n return self.driver.page_source\n\n def download_poster(self):\n \"\"\"\n 下载电影海报(部分)\n :return:\n \"\"\"\n _count = 0\n _poster_url = self.data['posters'][0]\n _poster_page = self.get_element_page(_poster_url)\n _poster_url_reg = re.compile(\n r'.*?class=\"prop\".*?(\\d+x\\d+).*?
    ', re.S)\n self.data['poster_urls'] = [{'url': item[0], 'pixel': item[-1]}\n for item in re.findall(_poster_url_reg, _poster_page)]\n for item in self.data['poster_urls']:\n _count += 1\n self.download(\n 'posters', f'poster-{str(_count)}-{item[\"pixel\"]}', item['url'])\n\n def download_main_team_pic(self):\n \"\"\"\n 下载电影主创人员图片\n :return:\n \"\"\"\n for item in self.data['main_team_info']:\n self.download('main_team', item['name'], item['avatar'])\n\n def download_stills(self):\n \"\"\"\n 下载电影剧照(部分)\n :return:\n \"\"\"\n _count = 0\n _stills_url = self.data['stills']\n _stills_page = self.get_element_page(_stills_url)\n _stills_url_reg = re.compile(\n r'.*?class=\"prop\".*?(\\d+x\\d+).*?
    ', re.S)\n self.data['stills_urls'] = [{'url': item[0], 'pixel': item[-1]}\n for item in re.findall(_stills_url_reg, _stills_page)]\n for item in self.data['stills_urls']:\n _count += 1\n self.download(\n 'stills', f'stills-{str(_count)}-{item[\"pixel\"]}', item['url'])\n\n def store_item_info(self):\n \"\"\"\n 保存电影信息\n :return:\n \"\"\"\n with open(f'./{self.data[\"movie_name\"]}.json', 'w', encoding='utf-8') as j:\n j.write(json.dumps(self.data))\n\n def run(self):\n \"\"\"\n 启动\n :return:\n \"\"\"\n self.init_data()\n self.build_dir()\n self.download_poster()\n self.download_main_team_pic()\n self.download_stills()\n self.store_item_info()\n self.driver.close()\n\n\nif __name__ == '__main__':\n tmp = Douban(\n r'https://movie.douban.com/subject/27060077/?tag=%E7%83%AD%E9%97%A8&from=gaia_video')\n tmp.run()\n print(json.dumps(tmp.data, indent=4))\n\n # print(os.path.abspath('./'))\n","sub_path":"tmp_1.py","file_name":"tmp_1.py","file_ext":"py","file_size_in_byte":8397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"622107999","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np \nimport scipy as sp\nimport six\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom abc import ABC, abstractmethod\nfrom utils.train_util import config_optimizer,get_vars_by_scope,plot,concat_cond_data,shuffle_data\nfrom utils.model_util import *\n\n\nclass GAN(ABC):\n \n \n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.0002,op_type='adam',clip=None,reg=None,g_penalty=False,\\\n gamma0=1.,alpha=0.01,pooling=False,strides={},*args,**kargs):\n print('x ph',x_ph,'batch size',batch_size)\n self.conv = conv\n print('conv', conv)\n self.batch_norm = batch_norm\n self.pooling = pooling\n print('pooling', pooling)\n self.ac_fn = ac_fn\n self.g_net_shape = g_net_shape\n self.d_net_shape = d_net_shape\n self.batch_size = batch_size\n self.g_penalty = g_penalty\n print('g penalty',g_penalty)\n self.strides = strides\n if g_penalty:\n print('enable discriminator regularizer')\n self.gamma0 = gamma0\n self.alpha = alpha\n if alpha > 0.:\n print('use annealing')\n self.gamma = tf.placeholder(dtype=tf.float32,shape=[], name='d_reg_gamma')\n else:\n self.gamma = gamma0\n \n self.define_model(x_ph,g_net_shape,d_net_shape,batch_size,conv,ac_fn,batch_norm,learning_rate,\\\n op_type,clip,reg,pooling,strides,*args,**kargs)\n if sess is None:\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n else:\n self.sess = sess\n\n \n def define_model(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,ac_fn,batch_norm,learning_rate,\\\n op_type,clip=None,reg=None,pooling=False,strides={},*args,**kargs):\n \n self.is_training = tf.placeholder(dtype=tf.bool,shape=[]) if batch_norm else None\n self.x_ph = x_ph # true data\n k = g_net_shape[0][0] if conv else g_net_shape[0] \n print('check e ph',batch_size,'k',k) \n self.e_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,k]) \n print('strides',strides)\n g_strides, d_strides = strides.get('generator',[]), strides.get('discriminator',[])\n self.g_W,self.g_B,self.g_H = self.define_g_net(self.e_ph,g_net_shape,reuse=False,conv=conv,ac_fn=ac_fn,\\\n batch_norm=batch_norm,training=self.is_training,\\\n reg=reg,pooling=pooling,strides=g_strides)\n self.d_W,self.d_B,self.d_H = self.define_d_net(self.x_ph,d_net_shape,reuse=False,conv=conv,ac_fn=ac_fn,\\\n batch_norm=batch_norm,training=self.is_training,\\\n reg=reg,pooling=pooling,strides=d_strides)\n _,__,self.d_fake_H = self.define_d_net(self.g_H[-1],d_net_shape,reuse=True,conv=conv,ac_fn=ac_fn,\\\n batch_norm=batch_norm,training=self.is_training,\\\n reg=reg,pooling=pooling,strides=d_strides)\n \n self.g_loss,self.d_loss = self.set_loss()\n self.g_train,self.g_var_list,self.g_opt = self.config_train(self.g_loss,scope='generator',learning_rate=learning_rate*5,clip=clip)\n self.d_train,self.d_var_list,self.d_opt = self.config_train(self.d_loss,scope='discriminator',learning_rate=learning_rate,clip=clip)\n \n return\n\n\n @staticmethod\n def define_g_net(e,net_shape,reuse,conv=False,ac_fn=tf.nn.relu,batch_norm=False,training=None,reg=None,\\\n output_ac=tf.nn.sigmoid,scope = 'generator',pooling=False,strides=[]):\n W,B,H = [],[],[]\n h = e\n dense_net_shape = net_shape[0] if conv else net_shape\n print('define generator')\n # deconv layers must after dense layers\n with tf.variable_scope(scope,reuse=reuse):\n for l in range(len(dense_net_shape)-1):\n l_batch_norm = batch_norm\n # if no conv layer and it's output layer\n if l == len(dense_net_shape) - 2 and not conv:\n ac_fn = output_ac\n l_batch_norm = False\n w, b, h = build_dense_layer(h,l,dense_net_shape[l],dense_net_shape[l+1],initialization={'w':tf.random_normal_initializer(stddev=0.02),'b':tf.constant_initializer(0.0)},\\\n ac_fn=ac_fn,batch_norm=l_batch_norm,training=training,scope=scope,reg=reg)\n W.append(w)\n B.append(b) \n #print(l,w,b)\n H.append(h) \n if conv:\n h = tf.reshape(h,[-1]+net_shape[1][0]) # net_shape[1][] is a list of input and filter shape of dconv2d\n for l in range(1,len(net_shape[1])):\n l_batch_norm = False\n # set batch norm every 2 layers, starting from first layer\n if batch_norm and l%2 == 0:\n l_batch_norm = True\n # output layer\n if l == len(net_shape[1])-1:\n ac_fn = output_ac\n l_batch_norm = False\n\n filter_shape = net_shape[1][l]\n print('input shape',h.shape)\n strd = strides[l-1] if strides else [1,2,2,1]\n print('strides',strd)\n ow, oh = int(h.shape[1].value*strd[1]), int(h.shape[2].value*strd[2]) #stride (2,2)\n output_shape = [h.shape[0].value,ow,oh,filter_shape[2]]\n print('output shape',output_shape,'filter shape',filter_shape)\n w,b,h = build_conv_bn_acfn(h,l,filter_shape,strides=strd,initialization={'w':tf.truncated_normal_initializer(stddev=0.02),'b':tf.constant_initializer(0.0)},\\\n ac_fn=ac_fn,deconv=True,output_shape=output_shape,batch_norm=l_batch_norm,training=training,scope=scope,reg=reg)\n if pooling:\n h = tf.nn.max_pool(value=h,ksize=[1,2,2,1],strides=[1,1,1,1],padding='SAME')\n \n W.append(w)\n B.append(b)\n H.append(h) \n print('generator output shape',H[-1].shape)\n return W,B,H\n\n @staticmethod\n def define_d_net(x,net_shape,reuse,conv=False,ac_fn=tf.nn.relu,batch_norm=False,training=None,reg=None,\\\n scope = 'discriminator',pooling=False,strides=[],initialization=None,*args,**kargs):\n W,B,H = [],[],[] \n h = x\n dense_net_shape = net_shape[1] if conv else net_shape\n #print('define discriminator')\n if initialization is None:\n initialization = {'w':tf.truncated_normal_initializer(stddev=0.02),'b':tf.constant_initializer(0.0)}\n if conv:\n initialization.update({'cw':tf.random_normal_initializer(stddev=0.02),'cb':tf.constant_initializer(0.0)})\n # conv layers must before dense layers\n with tf.variable_scope(scope,reuse=reuse):\n if conv:\n for l in range(len(net_shape[0])): \n filter_shape = net_shape[0][l]\n #print('filter shape',filter_shape)\n strd = strides[l] if strides else [1,2,2,1]\n #print('strides',strd)\n # set batch norm every 2 layers, starting from second layer\n l_batch_norm = False\n if batch_norm and (l+1)%2 == 0:\n l_batch_norm = True\n w,b,h = build_conv_bn_acfn(h,l,filter_shape,strides=strd,initialization=initialization,\\\n ac_fn=ac_fn,batch_norm=l_batch_norm,training=training,scope=scope,reg=reg)\n #print('output shape',h.shape)\n #if pooling:\n # h = tf.nn.max_pool(value=h,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\n W.append(w)\n B.append(b)\n H.append(h) \n h = tf.reshape(h,[h.shape[0].value,-1])\n for l in range(len(dense_net_shape)-2):\n w, b, h = build_dense_layer(h,l,dense_net_shape[l],dense_net_shape[l+1],initialization=initialization,\\\n ac_fn=ac_fn,batch_norm=batch_norm,training=training,scope=scope,reg=reg)\n W.append(w)\n B.append(b)\n H.append(h) \n #print(l,w,b)\n\n # define output layer without activation function \n w,b,h = build_dense_layer(h,l+1,dense_net_shape[-2],dense_net_shape[-1],ac_fn=None,batch_norm=False)\n W.append(w)\n B.append(b)\n H.append(h)\n #print(l+1,w,b)\n \n return W,B,H\n\n\n @staticmethod\n def restore_d_net(x,W,B,conv_L=0,ac_fn=tf.nn.relu,batch_norm=False,training=None,scope='',strides=[]):\n h = x\n H = []\n # including conv layers\n if conv_L > 0:\n conv_W, conv_B = W[:conv_L], B[:conv_L]\n for l in range(conv_L):\n l_batch_norm = False\n if batch_norm and (l+1)%2 == 0:\n l_batch_norm = True\n strd = strides[l] if strides else [1,2,2,1]\n h = restore_conv_layer(h,l,conv_W[l],conv_B[l],strides=strd,ac_fn=ac_fn,\\\n batch_norm=l_batch_norm,training=training,scope=scope)\n H.append(h)\n h = tf.reshape(h,[h.shape[0].value,-1])\n\n # restore dense layers\n for l in range(conv_L,len(W)-1):\n #print('restore layer {}: h {}, w {}, b {}'.format(l,h.shape,W[l].shape,B[l].shape))\n h = restore_dense_layer(h,l,W[l],B[l],ac_fn=ac_fn,batch_norm=batch_norm,training=training,scope=scope)\n H.append(h)\n h = restore_dense_layer(h,len(W)-1,W[-1],B[-1],ac_fn=None,batch_norm=False)\n H.append(h)\n return H\n \n\n @staticmethod\n def restore_g_net(e,W,B,conv_L=0,ac_fn=tf.nn.relu,batch_norm=False,training=None,scope='',strides=[]):\n h = e\n H = []\n print('e shape',e.shape)\n for w,b in zip(W,B):\n print('w shape',w.shape,'b shape',b.shape)\n for l,(w,b) in enumerate(zip(W[:len(W)-conv_L],B[:len(B)-conv_L])):\n \n l_batch_norm = batch_norm\n\n if l == len(W) - 2 and conv_L > 0:\n ac_fn = tf.nn.sigmoid\n l_batch_norm = False\n\n h = restore_dense_layer(h,l,w,b,ac_fn=ac_fn,batch_norm=l_batch_norm,training=training,scope=scope)\n H.append(h)\n print('h shape',h.shape)\n if conv_L > 0:\n c = W[len(W)-conv_L].shape[-1]\n k = int(np.sqrt(h.shape[1].value/c))\n print('h,c,k',h.shape,c,k)\n h = tf.reshape(h,[-1,k,k,c])\n for l,(w,b) in enumerate(zip(W[len(W)-conv_L:],B[len(B)-conv_L:])):\n l_batch_norm = False\n # set batch norm every 2 layers, starting from first layer\n if batch_norm and l%2 == 0:\n l_batch_norm = True\n # output layer\n if l == conv_L-1:\n ac_fn = tf.nn.sigmoid\n l_batch_norm = False\n strd = strides[l] if strides else [1,2,2,1]\n ow, oh = h.shape[1].value * strd[1], h.shape[2].value * strd[2]\n output_shape = [h.shape[0].value, ow, oh, w.shape[-2]] \n h = restore_conv_layer(h,l,w,b,strides=strd,ac_fn=ac_fn,deconv=True,output_shape=output_shape,\\\n batch_norm=l_batch_norm,training=training,scope=scope)\n H.append(h)\n return H\n\n \n def generator(self,e,*args,**kargs): \n if self.is_training is None:\n return self.sess.run(self.g_H[-1],feed_dict={self.e_ph:e})\n else:\n return self.sess.run(self.g_H[-1],feed_dict={self.e_ph:e,self.is_training:False})\n\n\n def discriminator(self,x,*args,**kargs):\n if self.is_training is None:\n return self.sess.run(self.d_H[-1],feed_dict={self.x_ph:x})\n else:\n return self.sess.run(self.d_H[-1],feed_dict={self.x_ph:x,self.is_training:False})\n\n @staticmethod\n def Discriminator_Regularizer(d_real_logits, d_real_x, d_fake_logits, d_fake_x,batch_size):\n d_real = tf.nn.sigmoid(d_real_logits)\n d_fake = tf.nn.sigmoid(d_fake_logits)\n grad_d_real_logits = tf.gradients(d_real_logits, d_real_x)[0]\n grad_d_fake_logits = tf.gradients(d_fake_logits, d_fake_x)[0]\n grad_dr_logits_norm = tf.norm(tf.reshape(grad_d_real_logits, [batch_size,-1]), axis=1, keep_dims=True)\n grad_df_logits_norm = tf.norm(tf.reshape(grad_d_fake_logits, [batch_size,-1]), axis=1, keep_dims=True)\n\n #set keep_dims=True/False such that grad_D_logits_norm.shape == D.shape\n assert grad_dr_logits_norm.shape == d_real.shape\n assert grad_df_logits_norm.shape == d_fake.shape\n\n reg_d_real = tf.multiply(tf.square(1.0-d_real), tf.square(grad_dr_logits_norm))\n reg_d_fake = tf.multiply(tf.square(d_fake), tf.square(grad_df_logits_norm))\n disc_regularizer = tf.reduce_mean(reg_d_real + reg_d_fake)\n return disc_regularizer\n \n def set_loss(self,*args,**kargs):\n d_real_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.d_H[-1], labels=tf.ones_like(self.d_H[-1])))\n d_fake_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.d_fake_H[-1], labels=tf.zeros_like(self.d_fake_H[-1])))\n \n d_loss = d_real_loss + d_fake_loss\n g_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.d_fake_H[-1], labels=tf.ones_like(self.d_fake_H[-1])))\n\n return g_loss, d_loss\n\n\n @staticmethod\n def config_train(loss,scope,learning_rate=0.0002,op_type='adam',beta1=0.5,decay=None,clip=None,*args,**kargs):\n \n var_list = get_vars_by_scope(scope)\n grads = tf.gradients(loss, var_list)\n if clip is not None:\n grads = [tf.clip_by_value(g, clip[0],clip[1]) for g in grads]\n grads_and_vars = list(zip(grads, var_list))\n print(scope,'learning rate',learning_rate)\n #print('var list',var_list)\n opt = config_optimizer(learning_rate,scope+'_step',grad_type=op_type,decay=decay,beta1=beta1) \n\n train = opt[0].apply_gradients(grads_and_vars, global_step=opt[1])\n\n return train,var_list,opt\n\n def print_log(self,e,feed_dict,*args,**kargs):\n d_loss = self.sess.run([self.d_loss],feed_dict=feed_dict)\n g_loss = self.sess.run([self.g_loss],feed_dict=feed_dict)\n print('epoch',e,'d loss',d_loss,'g loss',g_loss)\n return \n\n\n def update_feed_dict(self,X,Y,ii,batch_size,p=0.):\n feed_dict = {} if self.is_training is None else {self.is_training:True}\n x_batch,y_batch,ii = get_next_batch(X,batch_size,ii,labels=Y)\n e_batch = np.random.uniform(low=-1.,size=(batch_size,self.g_W[0].shape[0].value)).astype(np.float32)\n #e_batch = np.random.normal(size=(batch_size,self.g_W[0].shape[0].value)).astype(np.float32)\n\n feed_dict.update({self.x_ph:x_batch,self.e_ph:e_batch})\n if self.g_penalty and self.alpha > 0:\n feed_dict.update({self.gamma:self.gamma0*np.power(self.alpha,p)})\n return feed_dict,ii\n\n\n def training(self,X,Y,batch_size,epoch,d_obj=None,g_obj=None,disc_iter=1,vis=False,\\\n result_path='vis_results/',warm_start=False,merged=None,train_writer=None):\n \n if d_obj is None:\n d_obj = self.d_train\n if g_obj is None:\n g_obj = self.g_train\n\n if vis and not os.path.exists(result_path):\n os.makedirs(result_path)\n\n with self.sess.as_default():\n print('warm start',warm_start)\n if not warm_start:\n tf.global_variables_initializer().run()\n \n num_iters = int(np.ceil(X.shape[0]/batch_size))\n print('num iters',num_iters)\n T = epoch * num_iters\n for e in range(epoch):\n X,Y = shuffle_data(X,Y)\n ii = 0\n for i in range(num_iters):\n feed_dict,ii = self.update_feed_dict(X,Y,ii,batch_size,p=i/T)\n\n self.sess.run(d_obj,feed_dict=feed_dict)\n #d_loss = self.sess.run([self.d_loss],feed_dict=feed_dict)\n\n if (i+1) % disc_iter == 0:\n self.sess.run(g_obj,feed_dict=feed_dict)\n #g_loss = self.sess.run([self.g_loss],feed_dict=feed_dict)\n if merged is not None:\n summary = self.sess.run(merged,feed_dict=feed_dict)\n train_writer.add_summary(summary, i+e*num_iters)\n\n\n self.print_log(e,feed_dict)\n #print('epoch',e,'d loss',d_loss,'g loss',g_loss)\n if vis and (e+1)%1==0:\n e_samples = np.random.uniform(low=-1.,size=(batch_size,self.e_ph.shape[1].value)).astype(np.float32)\n #e_samples = np.random.normal(size=(batch_size,self.e_ph.shape[1].value)).astype(np.float32)\n\n x_samples = self.generator(e_samples)\n ng = int(np.sqrt(batch_size))\n fig = plot(x_samples[:ng*ng],shape=[ng,ng])\n fig.savefig(os.path.join(result_path,'e'+str(e+1)+'.pdf'))\n plt.close()\n \n\n\n\n\n\n\nclass WGAN(GAN):\n\n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.0002,op_type='adam',clip=None,reg=None,*args,**kargs):\n super(WGAN,self).__init__(x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,\\\n ac_fn,batch_norm,learning_rate,op_type,clip,reg,*args,**kargs)\n self.clip_D = [p.assign(tf.clip_by_value(p, -0.01, 0.01)) for p in self.d_var_list]\n return\n\n\n def set_loss(self,*args,**kargs):\n d_fake_loss = tf.reduce_mean(self.d_fake_H[-1])\n d_real_loss = tf.reduce_mean(self.d_H[-1])\n reg_loss = 0.0001*tf.reduce_sum(tf.losses.get_regularization_losses())\n d_loss = - d_real_loss + d_fake_loss + reg_loss\n g_loss = - d_fake_loss +reg_loss\n return g_loss,d_loss\n\n def training(self,X,Y,batch_size,epoch,disc_iter=1,vis=False,result_path='vis_results/',warm_start=False,*args,**kargs):\n d_obj = [self.d_train,self.clip_D]\n g_obj = self.g_train\n super(WGAN,self).training(X,Y,batch_size=batch_size,epoch=epoch,d_obj=d_obj,g_obj=g_obj,disc_iter=disc_iter,\\\n vis=vis,result_path=result_path,warm_start=warm_start,*args,**kargs)\n\n return\n\nclass WGAN_GP(WGAN):\n\n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.0002,op_type='adam',clip=None,reg=None,lambd=0.25,*args,**kargs):\n\n self.lambd = lambd\n super(WGAN_GP,self).__init__(x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,\\\n batch_norm,learning_rate,op_type,clip,reg,*args,**kargs)\n return\n\n\n def set_loss(self,*args,**kargs):\n g_loss,d_loss = super(WGAN_GP,self).set_loss()\n\n # This is copied from https://github.com/kodalinaveen3/DRAGAN/blob/master/DRAGAN.ipynb\n alpha = tf.random_uniform(shape=self.x_ph.get_shape(), minval=0.,maxval=1.)\n differences = self.g_H[-1] - self.x_ph # This is different from MAGAN\n interpolates = self.x_ph + (alpha * differences)\n _,__,self.d_inter_H = self.define_d_net(interpolates,self.d_net_shape,reuse=True,conv=self.conv,ac_fn=self.ac_fn,\\\n batch_norm=self.batch_norm,training=self.is_training)\n\n gradients = tf.gradients(self.d_inter_H[-1], [interpolates])[0]\n slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))\n gradient_penalty = tf.reduce_mean((slopes - 1.) ** 2)\n d_loss += self.lambd * gradient_penalty\n\n return g_loss,d_loss\n\n\n\nclass fGAN(GAN):\n\n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.0002,op_type='adam',clip=None,reg=None,divergence='KL',\\\n lamb_constr=0.,g_penalty=True,gamma0=1.,alpha=0.01,*args,**kargs):\n self.divergence = divergence\n self.lamb_constr = lamb_constr\n\n #print('lamb_constr',lamb_constr)\n\n #print('x_ph',x_ph)\n super(fGAN,self).__init__(x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,batch_norm,\\\n learning_rate,op_type,clip,reg,g_penalty,gamma0,alpha,*args,**kargs)\n \n return\n\n @staticmethod\n def get_f(divergence,tf=False):\n if tf:\n log, exp, sqrt, square = tf.log, tf.exp, tf.sqrt, tf.square\n\n else:\n log, exp, sqrt, square = np.log, np.exp, np.sqrt, np.square\n\n if divergence == 'KL':\n def f(u):\n return u*log(u)\n elif divergence == 'rv_KL':\n def f(u):\n return -log(u)\n elif divergence == 'Pearson':\n def f(u):\n return square(u-1.)\n elif divergence == 'Hellinger':\n def f(u):\n return square(sqrt(u) - 1.)\n elif divergence == 'Jensen_Shannon':\n def f(u):\n return -(u+1.)*log((1.+u)*0.5) + u*log(u)\n elif divergence == 'GAN':\n def f(u):\n return u*log(u) - (u+1.)*log(u+1.)\n else:\n raise NotImplementedError('Divergence NOT supported.') \n return f \n\n @staticmethod\n def get_act_conj_fn(divergence):\n if divergence == 'KL':\n def act_fn(v):\n return v\n\n def conj_f(t): \n return tf.exp(t-1.)\n\n elif divergence == 'rv_KL':\n def act_fn(v):\n return -tf.exp(-v)\n\n def conj_f(t):\n return -1.-tf.log(-t)\n\n elif divergence == 'Pearson':\n def act_fn(v):\n return v\n \n def conj_f(t):\n return 0.25 * tf.square(t) + t\n\n elif divergence == 'Hellinger':\n def act_fn(v):\n return 1. - tf.exp(-v)\n\n def conj_f(t):\n return t/(1.-t)\n\n elif divergence == 'Jensen_Shannon':\n def act_fn(v):\n return tf.log(2.) - tf.log(1.+tf.exp(-v))\n\n def conj_f(t):\n return -tf.log(2. - tf.exp(t))\n\n elif divergence == 'GAN':\n def act_fn(v):\n return - tf.log(1. + tf.exp(v))\n\n def conj_f(t):\n return - tf.log(1. - tf.exp(t))\n\n else:\n raise NotImplementedError('Divergence NOT supported.')\n\n return act_fn, conj_f\n \n @staticmethod\n def get_idf_gf(divergence):\n if divergence == 'KL':\n def idf_gf(x):\n return tf.exp(x - 1.)\n\n elif divergence == 'rv_KL':\n def idf_gf(x):\n return tf.exp(x) \n\n elif divergence == 'Pearson':\n def idf_gf(x):\n return 0.5 * x + 1.\n\n elif divergence == 'Hellinger':\n def idf_gf(x):\n return tf.exp(2.*x)\n\n elif divergence in ['Jensen_Shannon','GAN']:\n def idf_gf(x):\n return tf.exp(x)\n\n else:\n raise NotImplementedError('Divergence NOT supported.')\n\n return idf_gf\n\n \n def set_loss(self,d_h=None,d_fakeh=None):\n if d_h is None:\n d_h = self.d_H[-1] \n if d_fakeh is None:\n d_fakeh = self.d_fake_H[-1]\n\n act_fn,conj_f = self.get_act_conj_fn(self.divergence)\n #idf_gf = self.get_idf_gf(self.divergence)\n F = tf.reduce_mean(act_fn(d_h)) + tf.reduce_mean(-conj_f(act_fn(d_fakeh)))\n reg_loss = 0.0001 * tf.reduce_sum(tf.losses.get_regularization_losses())\n #r_constr = tf.square(tf.reduce_mean(idf_gf(tf.stop_gradient(d_fakeh[-1]))) - 1.) + tf.square(tf.reduce_mean(1./idf_gf(d_h[-1])) - 1.)\n\n g_loss = F + reg_loss #+ self.lamb_constr * r_constr\n d_loss = -F + reg_loss #+ self.lamb_constr * r_constr\n\n if self.g_penalty:\n \n d_reg = self.Discriminator_Regularizer(d_h,self.x_ph,d_fakeh,self.g_H[-1],self.batch_size)\n #d_reg = self.Discriminator_Regularizer(self.d_H[-1],self.x_ph,self.d_fake_H[-1],self.g_H[-1],self.batch_size)\n #d_reg = self.Discriminator_Regularizer(self.d_fake_H[-1],self.g_H[-1],self.batch_size,act_fn)\n\n d_loss += (self.gamma*0.5)*d_reg\n g_loss = -tf.reduce_mean(act_fn(d_fakeh)) + reg_loss\n\n return g_loss, d_loss\n\n\n\nclass CGAN(GAN):\n\n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.001,op_type='adam',clip=None,reg=None,pooling=False,\\\n c_dim=10,*args,**kargs):\n self.c_dim = c_dim\n #self.c_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,c_dim]) \n super(CGAN,self).__init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,\\\n batch_norm,learning_rate,op_type,clip,reg,pooling,*args,**kargs)\n\n return\n\n\n def define_model(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,ac_fn,batch_norm,learning_rate,\\\n op_type,clip=None,reg=None,pooling=False,*args,**kargs):\n self.conv = conv\n self.is_training = tf.placeholder(dtype=tf.bool,shape=[]) if batch_norm else None\n self.x_ph = x_ph # true data\n k = g_net_shape[0][0] if conv else g_net_shape[0] \n c_dim = self.c_dim \n #print('check e ph',batch_size,'k',k,'c_dim',c_dim) \n self.e_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,k]) \n self.c_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,c_dim]) \n #print('kargs',**kargs)\n self.g_W,self.g_B,self.g_H = self.define_g_net(self.e_ph,g_net_shape,reuse=False,conv=conv,ac_fn=ac_fn,\\\n batch_norm=batch_norm,training=self.is_training,reg=reg,\\\n pooling=pooling,**kargs)\n \n self.d_W,self.d_B,self.d_H = self.define_d_net(self.x_ph,d_net_shape,reuse=False,conv=conv,ac_fn=ac_fn,\\\n batch_norm=batch_norm,training=self.is_training,reg=reg,\\\n pooling=pooling,**kargs)\n \n self.fake_x = concat_cond_data(self.g_H[-1],self.c_ph,one_hot=False,dim=c_dim,conv=conv)\n _,__,self.d_fake_H = self.define_d_net(self.fake_x,d_net_shape,reuse=True,conv=conv,ac_fn=ac_fn,batch_norm=batch_norm,training=self.is_training,\\\n reg=reg,pooling=pooling,**kargs)\n \n self.g_loss,self.d_loss = self.set_loss()\n self.g_train,self.g_var_list,self.g_opt = self.config_train(self.g_loss,scope='generator',learning_rate=learning_rate*5,clip=clip)\n self.d_train,self.d_var_list,self.d_opt = self.config_train(self.d_loss,scope='discriminator',learning_rate=learning_rate,clip=clip)\n \n return\n\n\n @staticmethod\n def gen_feed_dict(x_ph,e_ph,c_ph,X,Y,ii,batch_size,is_training,k,c_dim,conv=False,one_hot=False):\n #print('condition gan')\n feed_dict = {} if is_training is None else {is_training:True}\n x_batch,y_batch,ii = get_next_batch(X,batch_size,ii,labels=Y)\n e_batch = np.random.uniform(low=-1.,size=(batch_size,k)).astype(np.float32)\n #e_batch = np.random.normal(size=(batch_size,k)).astype(np.float32)\n\n x_batch = concat_cond_data(x_batch,y_batch,one_hot=one_hot,dim=c_dim,conv=conv)\n e_batch = concat_cond_data(e_batch,y_batch,one_hot=one_hot,dim=c_dim,conv=False)\n \n feed_dict.update({x_ph:x_batch,e_ph:e_batch,c_ph:y_batch})\n\n return feed_dict,ii\n\n def update_feed_dict(self,X,Y,ii,batch_size,one_hot=False,p=0.):\n #print('X SHAPE',X.shape,'Y SHAPE',Y.shape)\n k = self.g_W[0].shape[0].value-self.c_dim\n feed_dict,ii = self.gen_feed_dict(self.x_ph,self.e_ph,self.c_ph,X,Y,ii,batch_size,\\\n self.is_training,k,self.c_dim,self.conv,one_hot)\n if self.g_penalty and self.alpha > 0:\n feed_dict.update({self.gamma:self.gamma0 * np.power(self.alpha,p)})\n return feed_dict, ii\n\n @staticmethod\n def Discriminator_Regularizer(d_real_logits, d_real_x, d_fake_logits, d_fake_x,batch_size,c_ph):\n d_real_logits = tf.expand_dims(tf.reduce_sum(d_real_logits * c_ph,axis=1),1)\n d_fake_logits = tf.expand_dims(tf.reduce_sum(d_fake_logits * c_ph,axis=1),1)\n d_real = tf.nn.sigmoid(d_real_logits)\n d_fake = tf.nn.sigmoid(d_fake_logits)\n grad_d_real_logits = tf.gradients(d_real_logits, d_real_x)[0]\n grad_d_fake_logits = tf.gradients(d_fake_logits, d_fake_x)[0]\n #print('logits shape',grad_d_fake_logits.shape)\n grad_dr_logits_norm = tf.norm(tf.reshape(grad_d_real_logits, [batch_size,-1]), axis=1, keep_dims=True)\n grad_df_logits_norm = tf.norm(tf.reshape(grad_d_fake_logits, [batch_size,-1]), axis=1, keep_dims=True)\n #print('logits norm shape',grad_df_logits_norm.shape)\n #print('d_real shape',d_real.shape)\n #set keep_dims=True/False such that grad_D_logits_norm.shape == D.shape\n assert grad_dr_logits_norm.shape == d_real.shape\n assert grad_df_logits_norm.shape == d_fake.shape\n\n reg_d_real = tf.multiply(tf.square(1.0-d_real), tf.square(grad_dr_logits_norm))\n reg_d_fake = tf.multiply(tf.square(d_fake), tf.square(grad_df_logits_norm))\n disc_regularizer = tf.reduce_mean(reg_d_real + reg_d_fake)\n return disc_regularizer\n\n\n def discriminator(self,x,y,*args,**kargs):\n rt = np.zeros(x.shape[0])\n iters = int(np.ceil(x.shape[0]/self.batch_size))\n ii = 0\n X = concat_cond_data(x,y,one_hot=False,dim=self.c_dim,conv=self.conv)\n for _ in range(iters):\n start = ii\n feed_dict = {} if self.is_training is None else {self.is_training:False}\n x_batch,__,ii = get_next_batch(X,self.batch_size,ii)\n feed_dict.update({self.x_ph:x_batch})\n end = ii if ii > start else x.shape[0]\n rt[start:end] = self.sess.run(self.d_H[-1],feed_dict=feed_dict).reshape(-1)[:end-start]\n return rt\n\n\n\n\nclass CWGAN(CGAN,WGAN):\n \n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.001,op_type='adam',clip=None,reg=None,c_dim=10,*args,**kargs):\n self.c_dim = c_dim\n #self.c_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,c_dim]) \n WGAN.__init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,\\\n batch_norm,learning_rate,op_type,clip,reg,*args,**kargs)\n\n return\n\n def set_loss(self):\n return WGAN.set_loss(self)\n\n\nclass CWGAN_GP(CGAN,WGAN_GP):\n \n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.001,op_type='adam',clip=None,reg=None,c_dim=10,lambd=0.25,*args,**kargs):\n self.c_dim = c_dim\n #self.c_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,c_dim]) \n WGAN_GP.__init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,\\\n batch_norm,learning_rate,op_type,clip,reg,lambd,*args,**kargs)\n\n return\n\n def set_loss(self):\n return WGAN_GP.set_loss(self)\n\n\nclass CfGAN(CGAN,fGAN):\n \n def __init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv=False,sess=None,ac_fn=tf.nn.relu,\\\n batch_norm=False,learning_rate=0.001,op_type='adam',clip=None,reg=None,divergence='KL',\\\n c_dim=10,lamb_constr=0.,g_penalty=True,gamma0=1.,alpha=0.01,*args,**kargs):\n self.c_dim = c_dim\n #print('lamb constr',lamb_constr)\n #self.c_ph = tf.placeholder(dtype=tf.float32,shape=[batch_size,c_dim]) \n fGAN.__init__(self,x_ph,g_net_shape,d_net_shape,batch_size,conv,sess,ac_fn,\\\n batch_norm,learning_rate,op_type,clip,reg,divergence,lamb_constr,g_penalty,gamma0,alpha,*args,**kargs)\n\n return\n \n def set_loss(self,d_h=None,d_fakeh=None):\n if d_h is None:\n d_h = self.d_H[-1] \n if d_fakeh is None:\n d_fakeh = self.d_fake_H[-1]\n\n act_fn,conj_f = self.get_act_conj_fn(self.divergence)\n idf_gf = self.get_idf_gf(self.divergence)\n F = tf.reduce_mean(act_fn(d_h),axis=0) + tf.reduce_mean(-conj_f(act_fn(d_fakeh)),axis=0)\n reg_loss = 0.0001 * tf.reduce_sum(tf.losses.get_regularization_losses())\n #r_constr = tf.square(tf.reduce_mean(idf_gf(tf.stop_gradient(d_fakeh[-1]))) - 1.) + tf.square(tf.reduce_mean(1./idf_gf(d_h[-1])) - 1.)\n\n g_loss = F + reg_loss #+ self.lamb_constr * r_constr\n d_loss = -F + reg_loss #+ self.lamb_constr * r_constr\n\n if self.g_penalty:\n \n d_reg = self.Discriminator_Regularizer(d_h,self.x_ph,d_fakeh,self.g_H[-1],self.batch_size,self.c_ph)\n #d_reg = self.Discriminator_Regularizer(self.d_H[-1],self.x_ph,self.d_fake_H[-1],self.g_H[-1],self.batch_size)\n #d_reg = self.Discriminator_Regularizer(self.d_fake_H[-1],self.g_H[-1],self.batch_size,act_fn)\n\n d_loss += (self.gamma*0.5)*d_reg*self.c_ph\n g_loss = -tf.reduce_mean(act_fn(d_fakeh),axis=0) + reg_loss\n \n # for multi-dims output\n c_num = tf.reduce_sum(self.c_ph,axis=0)\n c_prop = c_num /tf.reduce_sum(c_num)\n d_loss = tf.reduce_sum(d_loss * c_prop)\n g_loss = tf.reduce_sum(g_loss * c_prop)\n\n return g_loss, d_loss\n","sub_path":"base_models/gans.py","file_name":"gans.py","file_ext":"py","file_size_in_byte":34868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"633603313","text":"import os\nimport lockfile\nimport posixpath\nclass FileSystemKeyQueue(object):\n def __init__(self, dirname):\n os.path.exists(dirname) or os.mkdir(dirname)\n self.lock = lockfile.FileLock(dirname + \".lock\")\n self.dirname = dirname\n\n def _files(self):\n files = os.listdir(self.dirname)\n files = map(int, files)\n files.sort()\n return files\n\n def _old_filepath(self):\n files = self._files()\n if not files:\n return None\n return os.path.join(self.dirname, str(files[0]))\n\n def _new_filepath(self):\n files = self._files()\n if not files:\n files = [0]\n return os.path.join(self.dirname, str(files[-1]+1))\n\n def _check_key(self, key):\n key = posixpath.normpath(key)\n if not key.startswith(self.dirname): return None\n if not os.path.exists(key): return None\n return key\n\n def get(self):\n with self.lock:\n filepath = self._old_filepath()\n if not filepath: return None\n\n with open(filepath, 'rb') as f:\n data = f.read()\n newfilepath = self._new_filepath()\n os.rename(filepath, newfilepath)\n return newfilepath, data\n\n def put(self, data):\n with self.lock:\n filepath = self._new_filepath()\n with open(filepath, 'wb') as f:\n f.write(data)\n\n def remove(self, key):\n with self.lock:\n key = self._check_key(key)\n if not key: return False\n os.remove(key)\n return True\n","sub_path":"keyqueue.py","file_name":"keyqueue.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"1740065","text":"\n#Time Complexity : O(n)\n#Space Complexity : O(n)\n# Did this code successfully run on Leetcode : Yes\n#Any problem you faced while coding this : No\n\nclass Solution:\n def candy(self, ratings: List[int]) -> int:\n res = [1]*len(ratings)\n for i in range(1, len(ratings)):\n if ratings[i-1] < ratings[i]:\n res[i] = res[i-1] + 1\n sumv = 0\n print(res)\n for i in range(len(ratings)-1, 0, -1):\n if ratings[i] < ratings[i-1]:\n res[i-1] = max(res[i-1], res[i]+1)\n sumv += res[i]\n print(res)\n sumv += res[0]\n return sumv","sub_path":"candy.py","file_name":"candy.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"546933717","text":"#!/usr/bin/env python3 -u\n\nimport argparse\nimport fileinput\nimport logging\nimport os\nimport sys\n\nfrom fairseq.models.transformer import TransformerModel\n\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef main():\n src2tgt = TransformerModel.from_pretrained(\n model_name_or_path=\"wmt19.en-ru.ensemble\",\n checkpoint_file=\"model3.pt\",\n tokenizer='moses',\n bpe='fastbpe',\n ).eval()\n\n tgt2src = TransformerModel.from_pretrained(\n model_name_or_path=\"wmt19.ru-en.ensemble\",\n checkpoint_file=\"model3.pt\",\n tokenizer='moses',\n bpe='fastbpe',\n ).eval()\n\n input = [\"Because of the covid, UNC closed down\", \"How are you doing\"]\n\n top_k = 5\n\n tgt_translation = src2tgt.translate(input)\n roundtrip_translation = tgt2src.translate(tgt_translation, beam=2*top_k, top_k=5)\n print(roundtrip_translation)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"583538248","text":"# -*- coding: utf-8 -*- \nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport os\nimport numpy as np\n\ndef init(f_directory):\n mnist = input_data.read_data_sets(f_directory,dtype = tf.uint8,one_hot = True) \n print(\"训练集总数:%s\" % mnist.train.num_examples)\n print(\"验证集总数:%s\" %mnist.validation.num_examples)\n print(\"测试集总数:%s\" %mnist.test.num_examples)\n train_images = mnist.train.images\n train_labels = mnist.train.labels\n train_len = mnist.train.num_examples\n valid_images = mnist.validation.images\n valid_labels = mnist.validation.labels\n valid_len = mnist.validation.num_examples\n test_images = mnist.test.images\n test_labels = mnist.test.labels\n test_len = mnist.test.num_examples\n assert(train_images.shape[1] == valid_images.shape[1]) and (train_images.shape[1] == test_images.shape[1]) , \"图片加载部分缺失\"\n assert(train_len == train_labels.shape[0]),\"训练集缺失\"\n assert(valid_len == valid_labels.shape[0]),\"验证集缺失\"\n assert(test_len == test_labels.shape[0]),\"测试集缺失\"\n pixels = train_images.shape[1]\n return pixels,[[train_images,train_labels,train_len],[valid_images,valid_labels,valid_len],[test_images,test_labels,test_len]]\n\n#将值转化为64位整数列表\ndef _int64_feature(value):\n return tf.train.Feature(int64_list = tf.train.Int64List(value=[value]))\n#将值转化为字符串列表\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list = tf.train.BytesList(value=[value]))\n#将值转化为浮点数列表\ndef _float_feature(value):\n return tf.train.Feature(float_list = tf.train.FloatList(value=[value]))\n\ndef write_files(path,data,pixels):\n to_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),path)\n print(to_path)\n images,labels,leng = data[0],data[1],data[2]\n print(images.shape)\n writer = tf.python_io.TFRecordWriter(to_path)\n for index in range(leng):\n print(images[index].shape)\n print(np.sum(images[index]))\n image_raw = images[index].tostring()\n example = tf.train.Example(features = tf.train.Features(feature={\n 'pixels' : _int64_feature(pixels),\n 'label' : _int64_feature(np.argmax(labels[index])),\n 'image_row' : _bytes_feature(image_raw)\n }))\n writer.write(example.SerializeToString())\n\ndef main():\n print(\"ROOT_PATH:%s\" % os.path.dirname(os.path.realpath(__file__)))\n f_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)),'data')\n to_paths = [\"TF_Record_Data\\\\train_record_data\",\"TF_Record_Data\\\\validation_record_data\",\"TF_Record_Data\\\\test_record_data\"]\n pixels,data = init(f_directory)\n for i in range(len(to_paths)):\n write_files(to_paths[i],data[i],pixels)\n print(\"%s---------------Done!\" % to_paths[i].split('\\\\')[1])\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"TFRecord_Mnist/Data_to_TFRecord_Mnist_Samples.py","file_name":"Data_to_TFRecord_Mnist_Samples.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"53489231","text":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers.normalization import BatchNormalization\nimport numpy as np\n\n\nclass MyNeuralNetwork(Sequential):\n def __init__(self):\n # instantiate model\n Sequential.__init__(self)\n\n # input layer\n self.add(Dense(64, input_dim=1, kernel_initializer='uniform'))\n self.add(Dropout(rate=0.5))\n self.add(BatchNormalization())\n self.add(Activation('relu'))\n\n # # hidden layer\n self.add(Dense(64, kernel_initializer='uniform'))\n self.add(Dropout(rate=0.5))\n self.add(BatchNormalization())\n self.add(Activation('relu'))\n\n # output layer\n self.add(Dense(1, kernel_initializer='uniform', activation='linear'))\n\n self.compile(loss='mse', optimizer='adam', metrics=['mae', 'accuracy'])\n\n def init_NN_params(self):\n # If kernel_initializer='uniform', minval and maxval used by keras are -0.05 and 0.05 respectively\n minval = -0.05\n maxval = 0.05\n layers = self.layers\n for layer in layers:\n if len(layer.weights) != 0:\n if (layer.output_shape == layer.input_shape) and (len(layer.weights) == 4): # in case of BatchNormalization layer, always 4 \"weight\" parameters\n dim = layer.input_shape[1]\n gamma_init = np.ones(dim)\n beta_init = np.zeros(dim)\n moving_mean_init = np.zeros(dim)\n moving_variance_init = np.ones(dim)\n w_list = (gamma_init, beta_init, moving_mean_init, moving_variance_init) # list with total weight parameters (according to BatchNormalization doc)\n else: # otherwise (i.e, a normal layer sucha as Dense)\n in_dim = layer.input_shape[1] # input dimension\n out_dim = layer.output_shape[1] # output dimension\n link_w = np.random.uniform(minval, maxval, (in_dim, out_dim)) # weight term\n b = np.zeros(out_dim) # bias term\n w_list = (link_w, b) # list with total weight parameters (bias 'b' and weight 'w')\n layer.set_weights(w_list)\n","sub_path":"Implementaciones/BDANN-MF/PycharmProjects/DQN_DAFA/NeuralNetworkOperations.py","file_name":"NeuralNetworkOperations.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"365469224","text":"from models.Command import Command\nfrom models.Dispatcher import Dispatcher\n\nclass ExecutionContext:\n def __init__(self, command: Command, dispatcher: Dispatcher):\n self.cmd = command.cmd\n self.arg = command.arg\n self.cmd_display = str(command)\n self.dispatcher = dispatcher\n self.author = dispatcher.author\n self.send_message = dispatcher.send_message\n self.choice_callback = dispatcher.choice_callback\n self.loading_callback = dispatcher.loading_callback\n self.isadmin = dispatcher.isadmin\n self.bot = dispatcher.bot\n\n def voice_channel(self):\n return self.dispatcher.voice_channel()","sub_path":"discord_bot/models/ExecutionContext.py","file_name":"ExecutionContext.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"116716516","text":"import torch\nprint(torch.__version__)\nprint(torch.cuda.is_available())\nimport os\nimport glob\nfrom PIL import Image\nimport numpy as np\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch import optim\nfrom visdom import Visdom\n\n# 自定义数据集 :二分类\nclass myDataset(Dataset):\n def __init__(self, class1_dir, class2_dir):\n self.x, self.y = self.preprocess(class1_dir, class2_dir)\n\n def __getitem__(self, index):\n return self.x[index], self.y[index]\n\n def __len__(self):\n return self.x.shape[0]\n\n def _read_data(self, dataset_dir):\n data_dir = os.path.join('./dataset/', dataset_dir)\n data_dir = data_dir + '/*.jpg'\n eye_data = glob.glob(data_dir)\n x = []\n for img in eye_data:\n img = Image.open(img)\n img = np.asarray(img)\n x.append(img)\n x = np.array(x)\n x = torch.from_numpy(x).float() / 255.\n x = torch.unsqueeze(x, dim=3)\n return x\n\n # 预处理\n def preprocess(self, class1_dir, class2_dir):\n x1 = self._read_data(class1_dir)\n y1 = torch.ones(x1.shape[0])\n\n x2 = self._read_data(class2_dir)\n y2 = torch.zeros(x2.shape[0])\n\n x = torch.cat([x1, x2], dim=0)\n y = torch.cat([y1, y2], dim=0)\n return x, y\n\n\ntrain_dataset = myDataset('closedEyes', 'openEyes')\ntest_dataset = myDataset('close_test', 'open_test')\n# print(train_x.type(), train_y.type(), test_x.type(), test_y.type())\n\ntrain_db = DataLoader(train_dataset, batch_size=64, shuffle=True)\ntest_db = DataLoader(test_dataset, batch_size=64, shuffle=True)\n\n# x, y = iter(train_db).next()\n# print(x.shape, y.shape)\n\nclass Basenet(nn.Module):\n def __init__(self, input, output):\n super(Basenet, self).__init__()\n\n self.conv1 = nn.Conv2d(input, 64, kernel_size=[3, 3], padding=1)\n self.relu1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(64, 64, kernel_size=[3, 3], padding=1)\n self.relu2 = nn.ReLU()\n self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n\n self.conv3 = nn.Conv2d(64, 128, kernel_size=[3, 3], padding=1)\n self.relu3 = nn.ReLU()\n self.conv4 = nn.Conv2d(128, 128, kernel_size=[3, 3], padding=1)\n self.relu4 = nn.ReLU()\n self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.conv5 = nn.Conv2d(128, 256, kernel_size=[3, 3], padding=1)\n self.relu5 = nn.ReLU()\n self.conv6 = nn.Conv2d(256, 256, kernel_size=[3, 3], padding=1)\n self.relu6 = nn.ReLU()\n self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.conv7 = nn.Conv2d(256, 512, kernel_size=[3, 3], padding=1)\n self.relu7 = nn.ReLU()\n self.conv8 = nn.Conv2d(512, 512, kernel_size=[3, 3], padding=1)\n self.relu8 = nn.ReLU()\n self.maxpool4 = nn.MaxPool2d(kernel_size=4, stride=4)\n\n self.dense1 = nn.Linear(512, 256)\n self.relu9 = nn.ReLU()\n self.dense2 = nn.Linear(256, 128)\n self.relu10 = nn.ReLU()\n self.dense3 = nn.Linear(128, output)\n\n def forward(self, inputs):\n x = self.conv1(inputs)\n x = self.relu1(x)\n x = self.conv2(x)\n x = self.relu2(x)\n\n x = self.maxpool1(x)\n\n x = self.conv3(x)\n x = self.relu3(x)\n\n x = self.conv4(x)\n\n x = self.relu4(x)\n x = self.maxpool2(x)\n\n x = self.conv5(x)\n x = self.relu5(x)\n x = self.conv6(x)\n x = self.relu6(x)\n x = self.maxpool3(x)\n\n x = self.conv7(x)\n x = self.relu7(x)\n x = self.conv8(x)\n x = self.relu8(x)\n x = self.maxpool4(x)\n\n x = torch.reshape(x, [-1, 512])\n x = self.dense1(x)\n x = self.relu9(x)\n x = self.dense2(x)\n x = self.relu10(x)\n x = self.dense3(x)\n\n\n return x\n\n\ndevice = torch.device('cuda')\nbasenet = Basenet(24, 2).to(device)\n# x, _ = iter(train_db).next()\n# test = basenet(x.to(device))\n# print(basenet)\n\ncriteon = nn.CrossEntropyLoss().to(device)\noptimizer = optim.Adam(basenet.parameters(), lr=1e-4)\n\nviz = Visdom()\nviz.line([0.], [0.], win='train_loss', opts=dict(title='train_loss'))\n\nglobals_step = 0\nfor epoch in range(10):\n # train mode\n basenet.train()\n for step, (x, y) in enumerate(train_db):\n x, y = x.to(device), y.to(device)\n # forward\n logit = basenet(x)\n # loss\n # print(logit.type(), y.type())\n # logit = logit.long()\n loss = criteon(logit, y.long())\n # grads\n optimizer.zero_grad()\n loss.backward()\n # update\n optimizer.step()\n if step % 10 == 0:\n print('epoch:', epoch, 'loss:', loss.item())\n\n globals_step += 1\n viz.line([loss.item()], [globals_step], win='train_loss', update='append')\n\n # turn to eval mode\n basenet.eval()\n with torch.no_grad():\n total_num = 0\n total_correct = 0\n for x, y in test_db:\n x, y = x.to(device), y.to(device)\n logit = basenet(x)\n prob = F.softmax(logit, dim=1)\n pred = torch.argmax(prob, dim=1)\n correct = torch.eq(pred, y.long()).sum().item()\n\n total_num += x.shape[0]\n total_correct +=correct\n acc = total_correct / total_num\n print('epoch:', epoch, 'acc:', acc)\n\ntorch.save(basenet.state_dict(), 'eyes.pkl')\n\ndel basenet\n\nbasenet = Basenet(24, 2).to(device)\nbasenet.load_state_dict(torch.load('eyes.pkl'))\n\nbasenet.eval()\nwith torch.no_grad():\n total_num = 0\n total_correct = 0\n for x, y in test_db:\n x, y = x.to(device), y.to(device)\n logit = basenet(x)\n prob = F.softmax(logit, dim=1)\n pred = torch.argmax(prob, dim=1)\n correct = torch.eq(pred, y.long()).sum().item()\n\n total_num += x.shape[0]\n total_correct += correct\n acc = total_correct / total_num\n print('epoch:', epoch, 'acc:', acc)\n\nparams = basenet.state_dict()\nfor k, v in params.items():\n print(k) # 打印网络中的变量名\nprint(params['conv1.weight']) # 打印conv1的weight\nprint(params['conv1.bias']) # 打印conv1的bias\n","sub_path":"example_pytorch1.0/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"271928488","text":"\"\"\"Database Layer for the Emmission API.\n\"\"\"\n\nfrom functools import wraps\n\nfrom sqlalchemy import create_engine, Column, DateTime, Integer, Float, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nimport geoalchemy2\n\nfrom emissionsapi.config import config\nimport emissionsapi.logger\n\n# Logger\nlogger = emissionsapi.logger.getLogger('emission-api.db')\n\n# Database uri as described in\n# https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls\n# Retrieved as environment variable.\ndatabase = config('database') or 'postgresql://user:user@localhost/db'\n\n# Global session variable. Set on initialization.\n__session__ = None\n\n# Base Class of all ORM objects.\nBase = declarative_base()\n\n\nclass File(Base):\n \"\"\"ORM Object for the nc files.\n \"\"\"\n # Tablename\n __tablename__ = 'file'\n filename = Column(String, primary_key=True)\n\n\nclass Carbonmonoxide(Base):\n \"\"\"ORM Object for Carbonmonoxide Point\n \"\"\"\n # Tablename\n __tablename__ = 'carbonmonoxide'\n # Primary Key\n id = Column(Integer, primary_key=True)\n # Carbonmonoxide Value\n value = Column(Float)\n # Longitude\n longitude = Column(Float)\n # Latitude\n latitude = Column(Float)\n # timestamp\n timestamp = Column(DateTime)\n # PostGis type\n geom = Column(geoalchemy2.Geometry(geometry_type=\"POINT\"))\n\n def __init__(self, value, longitude, latitude, timestamp):\n self.value = value\n self.longitude = longitude\n self.latitude = latitude\n self.timestamp = timestamp\n self.geom = geoalchemy2.elements.WKTElement(\n f\"POINT({longitude} {latitude})\")\n\n\ndef with_session(f):\n \"\"\"Wrapper for f to make a SQLAlchemy session present within the function\n\n :param f: function to call\n :type f: function\n :raises e: Possible Exception of f\n :return: result of f\n \"\"\"\n @wraps(f)\n def decorated(*args, **kwargs):\n # Get new session\n session = get_session()\n try:\n # Call f with the session and all the other arguments\n result = f(session, *args, **kwargs)\n except Exception as e:\n # Rollback session, something bad happend.\n session.rollback()\n session.close()\n raise e\n # Close session and return the result of f\n session.close()\n return result\n return decorated\n\n\ndef get_session():\n \"\"\"Get a new session.\n\n Lazy load the database connection and create the tables.\n\n Returns:\n sqlalchemy.orm.session.Session -- SQLAlchemy Session Object\n \"\"\"\n global __session__\n # Create Database Connection, Tables and Sessionmaker if neccessary.\n if not __session__:\n Engine = create_engine(database)\n __session__ = sessionmaker(bind=Engine)\n Base.metadata.create_all(Engine)\n\n # Return new session object\n return __session__()\n\n\ndef get_points_in_polygon(session, polygon):\n \"\"\"Get all points from within the specified polygon.\n\n :param session: SQL Alchemy Session\n :type session: sqlalchemy.orm.session.Session\n :param polygon: Polygon where to search for points\n :type polygon: geoalchemy2.WKTElement\n :return: SQLAlchemy Query Object with the points from within the polygon.\n :rtype: sqlalchemy.orm.query.Query\n \"\"\"\n return session.query(Carbonmonoxide).filter(\n geoalchemy2.func.ST_WITHIN(Carbonmonoxide.geom, polygon))\n\n\ndef get_points_in_rectangle(session, upper_left, lower_right):\n \"\"\"Get all points from within a rectangle.\n\n :param session: SQL Alchemy Session\n :type session: sqlalchemy.orm.session.Session\n :param polygon: Polygon where to search for points\n :type polygon: geoalchemy2.WKTElement\n :param upper_left: Upper left point of the rectangle\n :type upper_left: tuple\n :param lower_right: Lower right point of the rectangle\n :type lower_right: tuple\n :return: SQLAlchemy Query Object with the points from within the polygon.\n :rtype: sqlalchemy.orm.query.Query\n \"\"\"\n # Defining the rectangle\n rectangle = geoalchemy2.elements.WKTElement(\n f'POLYGON(({upper_left[0]} {upper_left[1]},'\n f' {lower_right[0]} {upper_left[1]},'\n f' {lower_right[0]} {lower_right[1]},'\n f' {upper_left[0]} {lower_right[1]},'\n f' {upper_left[0]} {upper_left[1]}))')\n return get_points_in_polygon(session, rectangle)\n","sub_path":"emissionsapi/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"229195725","text":"import sys \nfrom trainer import model_cnn\n\n# from model_cnn import *\nimport argparse\nimport hypertune\n\nnum_files = range(0,15)\nGC_PATHS = []\n\nfor num_file in num_files:\n file_path = 'gs://mfccs/mfccs200_' + str(num_file) + '.tfrecords'\n GC_PATHS.append(file_path)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--alpha',\n default=0.001,\n type=float)\nparser.add_argument(\n '--job-dir',\n required=False)\n \nargs = parser.parse_args()\narguments = args.__dict__\njob_dir = arguments.pop('job_dir')\n\nprint('ALPHA',args.alpha)\nepochs = 2\n\nmodel = model_cnn.start_training(GC_PATHS[0:4], GC_PATHS[5], args.alpha, epochs)\n\nval = model_cnn.get_dataset(GC_PATHS[5])\nloss = model.evaluate(val)[0]\n\n# Calling the hypertune library and setting our metric\nhpt = hypertune.HyperTune()\nhpt.report_hyperparameter_tuning_metric(\n hyperparameter_metric_tag='loss',\n metric_value=loss,\n global_step=epochs)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"json_main.py","file_name":"json_main.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"544606272","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n## functions:part2\n## 4/2/2019\n\"\"\"\n\n## write()\n## writeline() list or tuple\n\n## create a file containing some cartoon characters\ndef main():\n outfile = open(\"Cartoon.txt\",\"w\")\n useWrite(outfile)\n add(\"Cartoon.txt\")\n print(\"Check if file is created.\") \ndef useWrite(outfile):\n outfile.write(\"Bugs Bunny\\n\")\n outfile.write(\"Daffy Duck\\n\")\n outfile.write(\"Minnie Mouse\\n\")\n outfile.close()\ndef add(fileName):\n outfile = open(fileName,\"a\") ## \"a\" --- append\n outfile.write(\"Pigs Porky\\n\")\n ## add one more line with new data \n listNew = [\"Brown Charlie\\n\",\"Bear Yogi\\n\"] \n outfile.writelines(listNew)\n outfile.close()\n\nmain()\n\ninfile = open(\"NumberFile.txt\",\"r\")\ndatalist = [eval(line) for line in infile]\ninfile.close()\n\n\n\n\n\n\n ","sub_path":"课堂笔记/3:28.py","file_name":"3:28.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"621797932","text":"__author__ = 'mmalca'\n\nimport fasttext\nimport fasttext.util\nfrom db import db_init\n\ndef get_rec():\n collection = db_init.init_collection('recipes')\n mydoc = collection.find()\n for doc in mydoc:\n id = doc[\"_id\"]\n print(doc)\n\ndef remove_rec():\n collection = db_init.init_collection('recipes')\n collection.delete_one({\"name\": \"פיתה מטוגנת\"})\n\n collection2 = db_init.init_collection('ingredients')\n collection2.delete_one({\"name\":\"פיתות\"})\n\ndef get_ing():\n collection = db_init.init_collection('ingredients')\n #myquery = { \"name\":\"תפוח אדמה\"}\n mydoc = collection.find()\n print(mydoc)\n for doc in mydoc:\n id = doc[\"_id\"]\n print(id)\nfrom db import db_operations\nfrom db import db_init\ndef add_rec():\n name = \"אפונה\"\n ingredients = [{\"name\":\"אפונה\",\"amount\" :\"2 כוסות\"}, {\"name\":\"מים\",\"amount\" :\"חצי כוס\"}, {\"name\":\"שום\",\"amount\" :\"2 שיניים\"}, {\"name\":\"כורכום\",\"amount\" :\"רבע כפית\"}, {\"name\":\"כמון\",\"amount\" :\"רבע כפית\"}, {\"name\":\"אבקת מרק\",\"amount\" :\"כפית\"}, {\"name\":\"מלח\",\"amount\" :\"כפית\"}, {\"name\":\"פלפל שחור\",\"amount\" :\"קמצוץ\"}]\n directions = [\"מחממים מחבת רחבה עם כף שמן ומוסיפים את השום והאפונה (אין צורך להפשיר לפני). מערבבים במשך כ-2 דקות.\", \"מוסיפים חצי כוס מים ומתבלים באבקת מרק, מלח, כורכום, כמון ופלפל שחור. מבשלים עם מכסה על אש בינונית במשך 8-10 דקות, עד שהרוטב מצטמצם.\" ]\n db_operations.add_recipe(name,ingredients , directions, \"jpg\")\n#\n# # ########### test - printing the recipe that we have inserted:\n# #\n\n collection = db_init.init_collection('recipes')\n myquery = { \"name\":name}\n mydoc = collection.find(myquery)\n for doc in mydoc:\n id = doc[\"_id\"]\n print(doc)\n#\n# ########### test - print new ingredirnts list\n# ingredients_list = db_operations.get_ingredients_list()\n# print(\"new ingredients list (only names and ids): ---------------\")\n# for i in ingredients_list:\n# print(i)\n\n\n#fasttext.util.download_model('he', if_exists='ignore')\n#ft_he = fasttext.load_model('cc.he.300.bin')\n\n# #### Adding new recipe ####\n#\nfrom db import db_operations\ndef myfunc():\n ingredients = [{\"name\": \"עלי בייבי\", \"amount\": \"1 חבילה\"}, {\"name\": \"עגבנית שרי\", \"amount\":\"חופן\"}, {\"name\": \"אפרסק\", \"amount\":\"1\"}, {\"name\": \"מוצרלה\", \"amount\":\"150 גרם\"} , {\"name\": \"חומץ בלסמי\", \"amount\":\"4 כפיות\"} , {\"name\": \"מלח\", \"amount\":\"1 כפית\"}]\n directions = [\"בקערה גדולה מערבבים את העלים עם העגבניות ופרוסות האפרסק.\", \"קורעים את המוצרלה לחתיכות גסות בידיים ומוסיפים לקערה.\",\"מתבלים בשמן הזית, בחומץ הבלסמי ובמלח. מערבבים, טועמים ומוסיפים מלח או חומץ לפי הטעם.\" ]\n #db_operations.add_recipe(\"סלט ירוק עם אפרסקים וגבינה ברוטב בלסמי\",ingredients , directions, \"jpg\")\n from db import db_init\n collection = db_init.init_collection('recipes')\n myquery = { \"name\":\"סלט ירוק עם אפרסקים וגבינה ברוטב בלסמי\"}\n mydoc = collection.find(myquery)\n for doc in mydoc:\n id = id = doc[\"_id\"]\n print(id)\n\n #ingredients = [{\"name\": \"פסטה\", \"amount\": \"1 כוס\"}, {\"name\": \"מים\", \"amount\":\"1/2 כוס\"}, {\"name\": \"חלב\", \"amount\":\"2 כפות\"}, {\"name\": \"חמאה\", \"amount\":\"1 כפית\"}, {\"name\": \"גבינה צהובה\", \"amount\":\"1/2 כוס\"}, {\"name\": \"מלח\", \"amount\":\"1/2 כפית\"}]\n #directions = [\"מכניסים את הפסטה לכוס או קערית גדולה.\", \"מוסיפים את המים והמלח ומערבבים\",\"מכניסים למיקרוגל ומחממים בעוצמה הגבוהה במשך 4.5 דקות.\" , \"מוציאים מהמיקרוגל ויוצקים על הפסטה את החלב.\", \"מניחים על הפסטה את החמאה ואת הגבינות המגורדות ומערבבים\", \"מכניסים שוב למיקרוגל לחצי דקה נוספת. מוציאים, מערבבים ומגישים.\"]\n\n #db_operations.add_recipe(\"מק אנד צ'יז במיקרו\",ingredients , directions, \"jpg\")\n\n# ########### test - printing the recipe that we have inserted:\n#\n #from db import db_init\n #collection = db_init.init_collection('recipes')\n #for c in collection:\n # print(c)\n #myquery = { \"name\":\"מק אנד צ'יז במיקרו\"}\n #r = collection.find_One(myquery)\n #print(r)\n\n## from http_server.server_init import init_server\n#from http_server import JsonOperations ##import *\nfrom fast_test_operations.first_impression import first_try\nfrom db import db_operations ## import *\n\n# my tries to serialize / deserialize from/to json\n# j = '{\"action\": \"print\", \"method\": \"onData\", \"data\": \"Madan Mohan\"}'\n#p = JsonToObject(j)\n\n#r = Recipe('hodaya', 123)\n#m = r.ObjectToJson()\n#print(m)\n# end of json tests\n\n##first_try()\n#Connect to the DB\n#myclient = pymongo.MongoClient(\"mongodb://193.106.55.98:5000/\")\n#GetIngredients()\n#init_server()\n\n\n\n####### Hodaya's test\n\n# import pymongo\n# mongo_server = pymongo.MongoClient(\"mongodb://193.106.55.98:5000/\")\n# from algorithm import algorithm_helper\n# id = algorithm_helper.get_ingredient_id_by_name(\"בצל\")\n#\n# collection = db_init.init_collection('recipes')\n# recipe = collection.find_one()\n# print(recipe)\n#\n# collection = db_init.init_collection('ingredients')\n# #doc = collection.find_one({ \"name\": \"בצל\" })\n# items_in_ing_col_count = collection.count_documents({})\n# bin1 = algorithm_helper.from_recipe_to_ingredients_binary(recipe, items_in_ing_col_count)\n# bin = algorithm_helper.from_ingredients_to_binary(recipe['ingredients'], items_in_ing_col_count)\n# print(bin)\n\n","sub_path":"tests_hodaya.py","file_name":"tests_hodaya.py","file_ext":"py","file_size_in_byte":6010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"191937276","text":"\n# -*- coding: utf-8 -*-\nimport multiprocessing\nimport os, sys, re, socks, time, platform, shutil, random, math\nimport string\n\nfrom telethon import TelegramClient, sync, errors\nfrom telethon.errors import SessionPasswordNeededError\nfrom telethon.tl.custom import Button\nfrom telethon.tl.functions.account import UpdateProfileRequest\nfrom telethon.tl.functions.messages import AddChatUserRequest\nfrom telethon.tl.functions.channels import InviteToChannelRequest, EditBannedRequest\nfrom telethon.tl.types import PeerUser, PeerChat, PeerChannel, ChannelBannedRights, InputMessagesFilterPhotos\n# from tasks import CeleryInviteUser\n\n# *********************************************\nimport asyncio\nimport telethon.sync\n\nloop = asyncio.get_event_loop()\n\n# *********************************************\n# VH: Aysnc method to loop message\nasync def myjob(client):\n async for message in client.iter_messages('gamesoftboy',limit=10):\n await asyncio.sleep(1)\n print(message)\n\n\ntestinfo = {\n# 申请api接口\n# https://my.telegram.org/apps\n#电话号码,电话号码,api ,key\n '91094016': ('91094016', 12345, 'd73xd14f8a78xcfr5692ec93f19'),\n}\n\n\ndef getrun(value):\n # +86这里我是填中国你可以填新加坡的\n print('+65' + str(value[0]))\n print('>>>>loading...')\n try:\n #client = TelegramClient(*value)\n api_id = 12345\n api_hash = 'd73xd14f8a78xcfr5692ec93f19'\n client = TelegramClient('TestSession', api_id, api_hash).start()\n\n print('>>>>ok...')\n if not client.is_user_authorized():\n print('>>>> client not !')\n raise\n\n # *********************************************\n print('retreiving async...') \n loop.run_until_complete(myjob(client))\n \n\n except Exception as e:\n print(e)\n finally:\n print(client)\n #client.disconnect()\n\n\n\nif __name__ == '__main__':\n for userkey, userdatavlue in testinfo.items():\n a = userkey\n b = userdatavlue\n getrun(userdatavlue)\n\n","sub_path":"GhostProtocol.py","file_name":"GhostProtocol.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"349518789","text":"from django.conf.urls import url\nfrom tasks import views\n\nurlpatterns = [\n url(r'^(?P[0-9]+)/$', views.task_detail),\n url(r'^deal/(?P[0-9]+)/(?P[0-9]+)/$', views.task_list_deal),\n url(r'^contact/(?P[0-9]+)/(?P[0-9]+)/$', views.task_list_cont),\n url(r'^finish/$', views.task_finish),\n url(r'^types/$', views.task_type_list),\n url(r'^delete/$', views.delete_tasks),\n url(r'^change_responsible/$', views.change_responsible),\n url(r'^for_birthday_script/$', views.for_birthday_script),\n url(r'^(?P\\w+)/$', views.task_list),\n]\n","sub_path":"tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"70977719","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom qa.views import popular, index, answer, test, question, ask, signup, user_login\n\nurlpatterns = [\n url(r'^$', index, name='index'),\n url(r'^popular/.*$', popular, name='popular'),\n url(r'^ask/.*$', ask, name='ask'),\n url(r'^answer/.*$', answer, name='answer'),\n url(r'^new/.*$', test),\n url(r'^question/(?P[\\d]+)/$', question, name='question'),\n url(r'^signup/.*$', signup, name='signup'),\n url(r'^login/.*$', user_login, name='login'),\n]\n","sub_path":"urls1.py","file_name":"urls1.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"558401328","text":"from django.contrib import messages\r\nfrom django.contrib.contenttypes.models import ContentType\r\nfrom django.http import HttpResponse\r\nfrom django.shortcuts import render, get_object_or_404, HttpResponseRedirect, redirect, Http404\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom urllib.parse import quote_plus\r\nfrom django.utils import timezone\r\nfrom django.db.models import Q\r\nfrom django.core.mail import send_mail\r\nfrom django.conf import settings\r\n\r\nfrom .models import Post\r\nfrom .forms import PostForm, ClientSubscribeForm\r\nfrom comments.models import Comment\r\nfrom comments.forms import CommentForm\r\n# from .utils import get_read_time\r\n\r\n\r\ndef post_list(request):\r\n today = timezone.now().date()\r\n queryset_list = Post.objects.active().order_by('-created')\r\n if request.user.is_staff or request.user.is_superuser:\r\n queryset_list = Post.objects.all().order_by('-created')\r\n queryset_list_last_items = queryset_list.order_by('-created')[:3]\r\n\r\n query = request.GET.get('q')\r\n\r\n if query:\r\n queryset_list = queryset_list.filter(\r\n Q(title__icontains=query) |\r\n Q(content__icontains=query) |\r\n Q(user__first_name__icontains=query) |\r\n Q(user__last_name__icontains=query)\r\n ).distinct()\r\n page = request.GET.get('page')\r\n paginator = Paginator(queryset_list, 5)\r\n try:\r\n queryset = paginator.page(page)\r\n except PageNotAnInteger:\r\n queryset = paginator.page(1)\r\n except EmptyPage:\r\n queryset = paginator.page(paginator.num_pages)\r\n\r\n form_contact = ClientSubscribeForm(request.POST or None)\r\n if request.method == 'POST' and form_contact.is_valid():\r\n # for key, value in form.cleaned_data.items():\r\n # print(key, value)\r\n\r\n form_full_name = form_contact.cleaned_data.get('full_name')\r\n form_email = form_contact.cleaned_data.get('email')\r\n form_skype = form_contact.cleaned_data.get('skype')\r\n form_telegram = form_contact.cleaned_data.get('telegram')\r\n\r\n subject = 'Take your bonus motherfucker!!!'\r\n contact_message = \"Hi %s: skype(%s), telegram(%s), email(%s). You fucking idiot!\" % (form_full_name, form_skype, form_telegram, form_email)\r\n from_email = settings.EMAIL_HOST_USER\r\n to_email = [form_email, from_email]\r\n send_mail(\r\n subject,\r\n contact_message,\r\n from_email,\r\n to_email,\r\n fail_silently=False,\r\n )\r\n form_contact.save()\r\n\r\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\r\n context = {\r\n 'title': 'List',\r\n 'object_list': queryset,\r\n 'object_list_3': queryset_list_last_items,\r\n 'today': today,\r\n 'form_contact': form_contact,\r\n\r\n }\r\n\r\n\r\n return render(request, 'posts/post_list.html', context)\r\n\r\n\r\ndef post_detail(request, slug=None):\r\n instance = get_object_or_404(Post, slug=slug)\r\n if instance.draft or instance.publish > timezone.now().date():\r\n if not request.user.is_staff or not request.user.is_superuser:\r\n raise Http404\r\n share_string = quote_plus(instance.content)\r\n # print(get_read_time(instance.get_markdown()))\r\n initial_data = {\r\n 'content_type': instance.get_content_type,\r\n 'object_id': instance.id\r\n }\r\n form_comment = CommentForm(request.POST or None, initial=initial_data)\r\n if form_comment.is_valid():\r\n c_type = form_comment.cleaned_data.get('content_type')\r\n content_type = ContentType.objects.get(model=c_type)\r\n obj_id = form_comment.cleaned_data.get('object_id')\r\n content_data = form_comment.cleaned_data.get('content')\r\n parent_obj = None\r\n try:\r\n parent_id = int(request.POST.get('parent_id'))\r\n except:\r\n parent_id = None\r\n\r\n if parent_id:\r\n parent_qs = Comment.objects.filter(id=parent_id)\r\n if parent_qs.exists() and parent_qs.count() == 1:\r\n parent_obj = parent_qs.first()\r\n\r\n new_comment, created = Comment.objects.get_or_create(\r\n user = request.user,\r\n content_type = content_type,\r\n object_id = obj_id,\r\n content = content_data,\r\n parent = parent_obj,\r\n )\r\n return HttpResponseRedirect(new_comment.content_object.get_absolute_url())\r\n\r\n comments = instance.comments\r\n\r\n queryset_list = Post.objects.active().order_by('-created')\r\n if request.user.is_staff or request.user.is_superuser:\r\n queryset_list = Post.objects.all().order_by('-created')\r\n queryset_list_last_items = queryset_list.order_by('-created')[:3]\r\n\r\n form_contact = ClientSubscribeForm(request.POST or None)\r\n if request.method == 'POST' and form_contact.is_valid():\r\n # for key, value in form.cleaned_data.items():\r\n # print(key, value)\r\n form_full_name = form_contact.cleaned_data.get('full_name')\r\n form_email = form_contact.cleaned_data.get('email')\r\n form_skype = form_contact.cleaned_data.get('skype')\r\n form_telegram = form_contact.cleaned_data.get('telegram')\r\n subject = 'Your Free Deposit!!!'\r\n contact_message = \"%s: %s %s via %s\" % (form_full_name, form_skype, form_telegram, form_email)\r\n from_email = settings.EMAIL_HOST_USER\r\n to_email = [form_email, from_email]\r\n send_mail(\r\n subject,\r\n contact_message,\r\n from_email,\r\n to_email,\r\n fail_silently=False,\r\n )\r\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\r\n\r\n context = {\r\n 'title': instance.title,\r\n 'instance': instance,\r\n 'share_string': share_string,\r\n 'object_list_3': queryset_list_last_items,\r\n 'form_contact': form_contact,\r\n 'comments': comments,\r\n 'form_comment': form_comment,\r\n }\r\n\r\n return render(request, 'posts/post_detail.html', context)\r\n\r\n\r\ndef post_create(request):\r\n if not request.user.is_staff or not request.user.is_superuser:\r\n raise Http404\r\n form = PostForm(request.POST or None, request.FILES or None)\r\n if form.is_valid():\r\n instance = form.save(commit=False)\r\n instance.user = request.user\r\n instance.save()\r\n messages.success(request, 'Created')\r\n return HttpResponseRedirect(instance.get_absolute_url())\r\n elif form.errors:\r\n messages.error(request, \"Not Successfully Created\")\r\n else: pass\r\n\r\n context = {\r\n 'form': form\r\n }\r\n return render(request, 'posts/post_form.html', context)\r\n\r\n\r\ndef post_update(request, slug=None):\r\n if not request.user.is_staff or not request.user.is_superuser:\r\n raise Http404\r\n instance = get_object_or_404(Post, slug=slug)\r\n form = PostForm(request.POST or None, request.FILES or None, instance=instance)\r\n if form.is_valid():\r\n instance = form.save(commit=False)\r\n instance.save()\r\n messages.success(request, 'Updated')\r\n return HttpResponseRedirect(instance.get_absolute_url())\r\n\r\n\r\n context = {\r\n 'title': instance.title,\r\n 'instance': instance,\r\n 'form': form\r\n }\r\n return render(request, 'posts/post_form.html', context)\r\n\r\n\r\ndef post_delete(request, slug=None):\r\n if not request.user.is_staff or not request.user.is_superuser:\r\n raise Http404\r\n instance = get_object_or_404(Post, slug=slug)\r\n instance.delete()\r\n messages.success(request, \"Deleted\")\r\n\r\n return redirect(\"posts:post_list\")","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"509280042","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport numpy as numpy\nfrom scipy import stats\ndef polyfit(x, y, degree):\n results = {}\n\n coeffs = numpy.polyfit(x, y, degree)\n\n # Polynomial Coefficients\n results['polynomial'] = coeffs.tolist()\n\n # r-squared\n p = numpy.poly1d(coeffs)\n # fit values, and mean\n yhat = p(x) # or [p(z) for z in x]\n ybar = numpy.sum(y)/len(y) # or sum(y)/len(y)\n ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])\n sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])\n results['determination'] = ssreg / sstot\n\n return results\n \nnetwork='OCT4'\ndir1='Contv2'\ndict={\n \"GRHL2\": 35,\n \"GRHL2wa\": 358,\n \"OVOL2\": 15,\n \"OVOLsi\": 35,\n \"NRF2\": 16,\n \"OCT4\": 356\n}\n\nboolean = open(\"{}_boolean_jsd.txt\".format(network), \"r\").read().split(\"\\n\")[1:]\nracipe = open(\"{}_racipe_jsd.txt\".format(network), \"r\").read().split(\"\\n\")[1:]\n\nbool_lis = []\nboolavg_lis=[]\nfinal_lis = []\navgbool=0\navgrac=0\nrac_lis = []\nracavg_lis = []\ncolor=[]\ncoloravg=[]\nif \"\" in boolean:\n boolean.remove(\"\")\n# if \"\" in racipe:\n# racipe.remove(\"\")\n\n# print(boolean)\n# print(racipe)\nq=0\nfor i in boolean:\n if(q%3!=0):\n q=(q+1)%3 \n continue\n q=(q+1)%3 \n temp = i.split(\" \")[1:]\n temp1 = i.split(\" \")[0:]\n temp2=int(temp1[0])\n \n for j in range(len(temp)):\n temp[j] = float(temp[j])\n bool_lis.append(temp[j])\n \n if(temp2==dict[network]):\n color.append('r')\n else:\n color.append('b')\n boolavg_lis.append(sum(temp)/len(temp)) \n if(temp2 == dict[network]):\n avgbool+=sum(temp)/len(temp) \n if(temp2==dict[network]):\n coloravg.append('r')\n else:\n coloravg.append('b')\n\n# final_lis /= final_lis[13]\nif \"\" in racipe:\n racipe.remove(\"\")\nfor i in racipe:\n temp = i.split(\" \")[1:]\n temp1 = i.split(\" \")[0:]\n temp2=int(temp1[0])\n for j in range(len(temp)):\n temp[j] = float(temp[j])\n rac_lis.append(temp[j])\n racavg_lis.append(sum(temp)/len(temp)) \n if(temp2 == dict[network]):\n avgrac+=sum(temp)/len(temp) \n \n#print(len(bool_lis))\n#color = ['b']*len(bool_lis)\n#color[12] = 'r'\n#color = []\n\n#for i in range(len(bool_lis)//7):\n # if i != dict[network]:\n # for j in range(7):\n # color.append('b')\n # else:\n # for j in range(7):\n # color.append('r')\n\n\n\nx=[0.01* i for i in range(1,40)]\nbool_lis=np.array(bool_lis)\nrac_lis=np.array(rac_lis)\ngradient, intercept, r_value, p_value, std_err = stats.linregress(bool_lis,rac_lis)\n\nplt.scatter(bool_lis,rac_lis,c=color,s=8)\n\nmn=np.min(bool_lis)\nmx=np.max(bool_lis)\nx1=np.linspace(mn,mx,500)\ny1=gradient*x1+intercept\nplt.plot(x1,y1,'-r')\n\nprint(polyfit(bool_lis,rac_lis,1),r_value**2)\n\nplt.title(r_value**2, loc='center')\n\nplt.savefig(\"{}/{}_check2.jpg\".format(dir1,network))\n\nplt.clf()\nx=[0.01* i for i in range(1,40)]\nplt.plot(x,x)\nplt.scatter(boolavg_lis,racavg_lis,c=coloravg,s=8)\nplt.savefig(\"{}/{}_checkavg2.jpg\".format(dir1,network))\nplt.clf()\n\nplt.hist(np.array(boolavg_lis)/avgbool, bins = 40)\n# plt.plot(x,x)\nplt.savefig(\"{}/{}_boolhist2.jpg\".format(dir1,network))\nplt.clf()\n\nplt.hist(np.array(racavg_lis)/avgrac, bins = 40)\n# plt.plot(x,x)\nplt.savefig(\"{}/{}_rachist.jpg\".format(dir1,network))\nplt.clf()\n\n","sub_path":"All_Boolean_Code_Unsorted/histogramedit.py","file_name":"histogramedit.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"601779999","text":"import os\nimport argparse\nimport json\nCOMMON_VIDEO_ETX = set([\n \".webm\", \".mpg\", \".mpeg\", \".mpv\", \".ogg\",\n \".mp4\", \".m4p\", \".mpv\", \".avi\", \".wmv\", \".qt\",\n \".mov\", \".flv\", \".swf\"])\n\n\ndef main(opts):\n videopath = opts.video_path\n feature_path = opts.feature_path\n csv_folder = opts.csv_folder\n if not os.path.exists(csv_folder):\n os.mkdir(csv_folder)\n if not os.path.exists(feature_path):\n os.mkdir(feature_path)\n if os.path.exists(opts.corrupted_id_file):\n corrupted_ids = set(json.load(\n open(opts.corrupted_id_file, 'r')))\n else:\n corrupted_ids = None\n\n outputFile = f\"{csv_folder}/slowfast_info.csv\"\n with open(outputFile, \"w\") as fw:\n fw.write(\"video_path,feature_path\\n\")\n fileList = []\n for dirpath, _, files in os.walk(videopath):\n for fname in files:\n input_file = os.path.join(dirpath, fname)\n if os.path.isfile(input_file):\n _, ext = os.path.splitext(fname)\n if ext.lower() in COMMON_VIDEO_ETX:\n fileList.append(input_file)\n\n for input_filename in fileList:\n filename = os.path.basename(input_filename)\n fileId, _ = os.path.splitext(filename)\n\n output_filename = os.path.join(\n feature_path, fileId+\".npz\")\n if not os.path.exists(output_filename):\n fw.write(input_filename+\",\"+output_filename+\"\\n\")\n if corrupted_ids is not None and fileId in corrupted_ids:\n fw.write(input_filename+\",\"+output_filename+\"\\n\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--video_path\", default=\"/video/\", type=str,\n help=\"The input video path.\")\n parser.add_argument(\"--feature_path\", default=\"/output/slowfast_features\",\n type=str, help=\"output feature path.\")\n parser.add_argument(\n '--csv_folder', type=str, default=\"/output/csv\",\n help='output csv folder')\n parser.add_argument(\n '--corrupted_id_file', type=str, default=\"\",\n help='corrupted id file')\n args = parser.parse_args()\n main(args)\n","sub_path":"slowfast/extract_feature/gather_video_paths.py","file_name":"gather_video_paths.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399002385","text":"\n''' Image classifier. Gets image from socket 01, sends result to socket 50 \nVersion 0.1 ? Alterações por: Roberto dia 08/08/2019, ctrl+f \"alteração 1\", \"alteração 2\", \"alteração 3\"\n2019-08-07\n'''\n\nimport numpy as np\nimport socket\nimport struct\nimport cv2\nfrom config import *\nfrom skimage import morphology\nimport datetime\nimport time\nfrom matplotlib import pyplot as plt\nimport pickle\nfrom sklearn.neural_network import MLPClassifier\nimport os.path,shutil, os\nimport sys\nfrom threading import Thread, Lock\nimport queue\n\n\nDISTANCE_BORDER_TO_ROI = 70 # Accept images when the circle is detected at this distance from the top\nIMAGES_TO_SKIP = 0 # Skip this number of images after a valid image, so that no portions of circles are detected\nHIDDEN_LAYER_SIZE = 20 # Neurons in the hidden layer of the MLP\nimg_global = None\nstatus = None\nlock = Lock()\n#q = queue.Queue(maxsize=1)\n\n''' Load image from socket. Returns OpenCV image '''\ndef get_file(sock,id,size):\n\tfileName = 'media/images/log' \n\t#len_str = sock.recv(4) # Get file size\n\t#size = struct.unpack('!i', len_str)[0]\n# print('File size received:', size)\n\tf_str = b''\n\twhile size > 0:\n\t\tif size >= 4096:\n\t\t\tdata = sock.recv(4096)\n\t\telse:\n\t\t\tdata = sock.recv(size)\n\t\t\tif not data:\n\t\t\t\tbreak \n\t\tsize -= len(data)\n\t\tf_str += data\n\t\tprint('Bytes received:', len(f_str),'missing:',size) \n\timg = cv2.imdecode(np.asarray(bytearray(f_str)),1)\n\t#print(type(img))\n\t#print(\"SAVING MOST RECENT IMAGE\")\n\n\n\t#Uncomment following lines to log images on /log/ folder\n\t\"\"\"\n\tdate_string = datetime.datetime.now().strftime(\"%H_%M_%S_%f\")[:-4]\n\tfileName = fileName + '/' + '%s' % (date_string) + '.png'\n\tcv2.imwrite(fileName, img)\n\t\"\"\"\n\n\n\t#cv2.imshow('img',img)\n\treturn img\n\n''' Get image from file '''\ndef get_greyscale(filename):\n# with open(filename, 'rb') as fp:\n# data = fp.read()\n# img = cv2.imdecode(np.asarray(bytearray(data)),1)\n\t\n\timg = cv2.imread(filename, 0)\n\t\n\treturn img\n\n\n''' Remove background, detect if image contains circle.\n\tReturn image or None '''\ndef process_image(img):\n\t\n\thsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Mudar para o HSV para detetar o verde facilmente\n\n\tlower = np.array([18, 0, 0]) # Destacar a cor verde\n\tupper = np.array([60, 255, 255])\n\n\tmask = cv2.inRange(hsv, lower, upper)\n\t# cv2.imshow('Mask', mask)\n\n\tret, mask = cv2.threshold(mask, 60, 255, cv2.THRESH_BINARY)\n\t# cv2.imshow('Threshold', mask)\n\n\tbinarized = np.where(mask > 0.1, 1, 0)\n\tprocessed = morphology.remove_small_objects(binarized.astype(bool), min_size=3000, connectivity=1).astype(int)\n\tmask_x, mask_y = np.where(processed == 0)\n\tmask[mask_x, mask_y] = 0\n\t# cv2.imshow('Final', mask)\n\n\timgDividida = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n\trows, cols = mask.shape[:3]\n\n\t# Detetar o circulo\n\tmiddle = int(cols / 2) # Linha central\n\tfor j in range(DISTANCE_BORDER_TO_ROI): # Check if the circle is close to the top of the image\n\t\tif mask[j, middle] > 0:\n\t\t\t# print('Object found')\n\t\t\treturn mask, True\n\n\treturn mask, False\n\n\n''' Sum columns or rows of a matrix. ax = 0 sums rows, =1 sums along columns '''\ndef sumColumn(matrix,ax):\n\treturn np.sum(matrix, axis=ax) # axis=1 says \"get the sum along the columns\"\n\n\n'''Normalize vector v to interval [0,1]'''\ndef normalize(v):\n\tmax_value = v.max()\n\tmin_value = v.min()\n\tif max_value>min_value :\n\t\t\tresult = (v - min_value) / (max_value - min_value)\n\treturn result\n\n\n''' Classify an image as valid or error (to reject).\n Fits the model if [y] is given and train = 1.\n Returns 0 is valid, 1 if invalid and must be rejected '''\ndef classify_image(img,train,y = [0],img_path = [None],img_original = None): #Argumento img_path adicionado por Roberto, 08/08/2019\n\trows, cols = img.shape[:2]\n\t#print('Number of rows (max):', rows)\n\t#print('Number of columns (max):', cols)\n\n\n\t#ALTERAÇÃO 1 por Roberto 08/08/2019: Garantir que dimensões da imagem satisfazem\n\t#A fazer: Adicionar condição para rows < 288 e cols > 384?\n\tif rows > 288:\n\t\twhile rows > 288:\n\t\t\timg=np.delete(img,rows-1,0)\n\t\t\trows, cols = img.shape[:2]\n\n\tif cols < 384:\n\t\tnewcol=np.zeros((rows,1))\n\t\twhile cols < 384:\n\t\t\t#print(img.shape[:2])\n\t\t\t#print(newcol.shape[:2])\n\t\t\timg=np.hstack((img,newcol))\n\t\t\trows, cols = img.shape[:2]\n\t#FIM ALTERAÇÃO 1\n\n\n\n\t#ALTERAÇÕES Roberto - julho 2019\n# newrow=np.zeros(cols)\n# img=np.vstack([img,newrow])\n# img=np.delete(img,383,1)\n# img=np.delete(img,382,1)\n# rows, cols = img.shape[:2]\n\t#print('Number of rows (max):', rows)\n\t#print('Number of columns (max):', cols)\n\t# Fim ALTERAÇÕES Roberto - julho 2019\n\n\thor = sumColumn(img,1) # Create horizontal and vertical histograms\n\tver = sumColumn(img,0)\n\th = np.concatenate([hor,ver]) # Join histograms\n\thn = normalize(h) # Normalize to [0,1]\n\n # print(hn.shape)\n\tfilename = 'neuralmodel.dat' # Read model from file if it exists\n\titeration_counter = 0\n\tprediction = [2]\n\t\n\tif os.path.isfile(filename):\n\t\tmlp = pickle.load(open(filename, 'rb'))\n\t\tif train:\n\t\t\twhile prediction[0] != y[0]:\n\t\t\t\tprint('Will update the model with the samples, performing two epochs, y=', y)\n\t\t\t\tmlp.partial_fit([hn],y)\n\t\t\t\t#mlp.partial_fit([hn],y) # Two epochs\n\t\t\t\tpickle.dump(mlp, open(filename, 'wb'))\n\t\t\t\tprint('Will predict, calling the model to predict ')\n\t\t\t\tprediction = mlp.predict(hn.reshape(1,-1))\n\t\t\t\tprint('Predicted: ',prediction)\n\t\t\t\titeration_counter = iteration_counter + 1\n\t\t\t\tif iteration_counter > 10:\n\t\t\t\t\tbreak\n\telse:\n\t\tmlp = MLPClassifier(hidden_layer_sizes=(HIDDEN_LAYER_SIZE),max_iter=10,verbose=True, tol=0.001)\n\t\tprint('New model created with ',HIDDEN_LAYER_SIZE,' neurons in the hidden layer.')\n\t\tprint('Will train model with the data available.')\n\t\tx = [hn,hn]\n\t\ty = [0, 1]\n\t\tmlp.fit(x,y)\n\t\tpickle.dump(mlp, open(filename, 'wb'))\n\tprint('Will predict, calling the model to predict ')\n\tprediction = mlp.predict(hn.reshape(1,-1))\n\tprint('Predicted: ',prediction)\n\n \n #ALTERAÇÃO 2 POR Roberto, 08/08/2019\n #RAZÃO: Não é necessário voltar a guardar novo .png e novo chart.png quando o pretendido é apenas reclassificar?\n ###### Save to file in folder accepted or rejected ##############################\n\t#fileName='accepted' \n\t#if prediction>0:\n\t#\tfileName='rejected'\n\t#date_string = datetime.datetime.now().strftime(\"%H_%M_%S\")\n\t#fileName = fileName+'/img' + '_%s' % (date_string) + '.png'\n\t#print('Will save to folder ',fileName)\n\t#cv2.imwrite(fileName, img)\n #### Save histograms too ########################################################\n\t#plt.clf()\n\t#plt.plot(hn)\n\t#plt.savefig(fileName+'chart.png')\n # plt.show()\n #FIM ALTERAÇÃO 2\n\n #ALTERAÇÃO 3 por ROBERTO 08/08/2019\n #Se o pretendido for reclassificar (já actualizou o modelo neural/neuralmodel.dat nas linhas 152 as 159?):\n\t# move ficheiros (tanto .png como chart.png) para as pastas correspondentes, sem criar novo .png nem chart.png\n\tif train:\n\t\tif y[0]==1: \n\t\t\tshutil.move(img_path,'media/images/rejected/')\n\t\t\tshutil.move(img_path+\"chart.png\",'media/images/rejected/')\n\t\t\tshutil.move(img_path+\"color.png\",'media/images/rejected/')\n\t\t\tprint('Moved from %s',img_path)\n\t\t\tprint('to .../rejected')\n\t\telif y[0]==0:\n\t\t\tshutil.move(img_path,'media/images/accepted/')\n\t\t\tshutil.move(img_path+\"chart.png\",'media/images/accepted/')\n\t\t\tshutil.move(img_path+\"color.png\",'media/images/accepted/')\n\t\t\tprint('Moved from %s',img_path)\n\t\t\tprint('to .../accepted')\n\t #Se prentendido for classificar nova imagem, executa pedaço de código comentado em ALTERAÇÃO 2\n\telse:\n###### Save to file in folder accepted or rejected ##############################\n\t\tfileName='media/images/accepted' \n\t\tif prediction>0:\n\t\t\tfileName='media/images/rejected'\n\t\tdate_string = datetime.datetime.now().strftime(\"%H_%M_%S_%f\")[:-4]\n\t\tfileName = fileName+'/img' + '_%s' % (date_string) + '.png'\n\t\tprint('Will save to folder ',fileName)\n\t\tcv2.imwrite(fileName+'color.png', img_original)\n\t\tcv2.imwrite(fileName, img)\n\t#### Save histograms too ########################################################\n\t\tplt.clf()\n\t\tplt.plot(hn)\n\t\tplt.savefig(fileName+'chart.png')\n # FIM ALTERAÇÃo 3\n\n\treturn prediction # No error detected\n \n\n\n\n''' Get images from the socket and process them '''\ndef run(socket_address):\n\n\ts = socket.socket()\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) \n\ts.bind(socket_address)\n\ts.listen(1)\n\tprint(\"Socket open at port \",socket_address,'listening to the port.')\n\n\tprint(\"Waiting for connection from clients.\")\n\t#sc, info = s.accept()\n\n\t\n\twhile True:\n\t\tsc, info = s.accept()\n\t\tip, port = str(info[0]), str(info[1])\n\t\t#q = queue.Queue()\n\t\tprint(\"Client connected:\", info) \n\t\tprint(\"CREATING THREAD\")\n\t\tThread(target=client_thread, args=(sc, ip, port)).start() \n\t\t\"\"\"mssg = sc.recv(4) # Get file size\n\t\tmessage_type = struct.unpack('!i', mssg)[0]\n\t\tprint('message is of type ' + str(message_type))\n\t\tif message_type == 2147483647:\n\t\t\ttry:\n\t\t\t\timg = get_file(sc,1) # Get image from socket\n\t\t\t\tsc.sendall(OK_COMMAND.encode())\n\t\t\tfinally:\n\t\t\t\tprint('Received, waiting more.')\n\t# sc.close()\n\t# print(\"Waiting for connection from clients.\")\n\t# sc, info = s.accept()\n\t\t\tif last_image>0: # Skip a number of images after the last valid image\n\t\t\t\tlast_image -= 1\n\t\t\t\tcontinue\n\t\t\tmask, to_process = process_image(img) # Process image\n\t\t\tif to_process: # Process this image, skip other images of the same object\n\t\t\t\tlast_image = IMAGES_TO_SKIP\n\t\t\t\tvalid = classify_image(mask,train = 0, y=[0])\n\t\telif message_type == 2147483646:\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tresponse = struct.pack('!i', 112)\n\t\t\tsc.sendall(response)\"\"\"\n \n\n# get_file(s,2) \n## s.sendall(QUIT_COMMAND.encode())\n# s.sendall(OK_COMMAND.encode())\n#\n\tprint(\"Closing socket and exit\")\n\ts.close()\n\ndef client_thread(sc,ip,port):#,q):\n\tglobal img_global, status\n\tlast_image = 0 \n\twhile True:\n\t\tmssg = sc.recv(4) # Get file size\n\t\t\"\"\"try:\n\t\t\tprint(\"received data:\", mssg.decode())\n\t\t\tmessage_type = mssg.decode()\n\t\t\t#print(\"test\")\n\t\t\t#print(\"testtest\")\n\t\t\t#prin(\"1\")\n\t\texcept:\n\t\t\tmessage_type = struct.unpack('!i', mssg)[0]\n\t\t\t#print(\"test2\")\n\t\t\tprint(message_type)\n\t\t\t#print(\"2\")\n\t\tprint('message is of type ' + str(message_type))\"\"\"\n\t\ttry:\n\t\t\tmessage = mssg.decode()\n\t\t\tsize = struct.unpack('!i', mssg)[0]\n\t\t\t#size = None\n\t\texcept:\n\t\t\t#message_type = struct.unpack('!i', mssg)[0]\n\t\t\tsize = struct.unpack('!i', mssg)[0]\n\t\t\tmessage = \"none\"\n\t\tif message == \"get_\":\n\t\t\t#f = os.listdir(fileName)\n\t\t\tprint(\"STR message\")\n\t\t\tprint(message)\n\t\t\tprint('TO IMPLEMENT') \n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\tprint('TO IMPLEMENT')\n\t\t\t#response = struct.pack('!i', 112)\n\t\t\t#sc.sendall(response)\n\t\t\t#if q.empty():\n\t\t\t#\tprint('q is empty')\n\t\t\t#n_img = q.get()\n\t\t\t#rows, cols = n_img.shape[:2]\n\t\t\tprint('\\nLOCKING\\n')\n\t\t\tlock.acquire()\n\t\t\trows, cols = img_global.shape[:2]\n\t\t\tprint('Number of rows (max):', rows)\n\t\t\tprint('Number of columns (max):', cols)\n\t\t\tencode_param = [int(cv2.IMWRITE_PNG_COMPRESSION), 9]\n\t\t\tresult, frame = cv2.imencode('.png', img_global, encode_param)\n\t\t\t#lock.release()\n\t\t\tprint('\\nRELEASED\\n')\n\t\t\tdata = pickle.dumps(frame, 0)\n\t\t\tsc.sendall(struct.pack('!i', status))\n\t\t\tsize = len(data)\n\t\t\t#len_str = struct.pack('!i', len(img_global)) # send string size \n\t\t\tsc.sendall(struct.pack('!i', size))\n\t\t\tprint('Sent filesize size to client: ',size,'(',size,')')\n\t\t\t# send bytes to socket\n\t\t\tsc.sendall(data)\n\t\t\tprint('Sent data, will wait.')\n\t\t\t#sc.sendall(struct.pack('!i', status))\n\t\t\trec_data = sc.recv(50)\n\t\t\tprint('Received from server: ',rec_data.decode())\n\t\t\tlock.release()\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"INT message\")\n\t\t\tprint(size)\n\t\t\ttry:\n\t\t\t\timg = get_file(sc,1,size) # Get image from socket\n\t\t\t\tsc.sendall(OK_COMMAND.encode())\n\t\t\tfinally:\n\t\t\t\tprint('Received, waiting more.')\n\t\t# sc.close()\n\t\t# print(\"Waiting for connection from clients.\")\n\t\t# sc, info = s.accept()\n\t\t\tif last_image>0: # Skip a number of images after the last valid image\n\t\t\t\tlast_image -= 1\n\t\t\t\tcontinue\n\t\t\tmask, to_process = process_image(img) # Process image\n\t\t\tif to_process: # Process this image, skip other images of the same object\n\t\t\t\tlast_image = IMAGES_TO_SKIP\n\t\t\t\tvalid = classify_image(mask,train = 0, y=[0],img_original = img) # 0 is accepted, 1 is rejected\n\t\t\t\tprint(\"SAVING MOST RECENT IMAGE\")\n\t\t\t\tfileName = 'media/images/recent'# + str(valid[0]) + '.png' \n\t\t\t\t#os.remove(fileName)\n\t\t\t\t#os.rmdir(fileName)\n\t\t\t\t#os.mkdir(fileName)\n\t\t\t\t#files = os.listdir(fileName)\n\t\t\t\t#print(files)\n\t\t\t\t#while len(files) > 0:\n\n\t\t\t\t\"\"\"\n\t\t\t\tfor file in os.listdir(fileName):\n\t\t\t\t\tstring = fileName + '/' + file\n\t\t\t\t\tos.remove(string)\n\t\t\t\tdate_string = datetime.datetime.now().strftime(\"%H_%M_%S_%f\")[:-4]\n\t\t\t\tfileName = fileName + '/' + '%s' % (date_string) + '_' + str(valid[0]) + '.png'\n\t\t\t\tcv2.imwrite(fileName,img)\n\t\t\t\t\"\"\"\n\n\t\t\t\t#q.put(img)\n\t\t\t\t#print(q.empty())\n\t\t\t\tprint('\\nLOCKING\\n')\n\t\t\t\tlock.acquire()\n\t\t\t\timg_global = img\n\t\t\t\tstatus = valid[0]\n\t\t\t\tlock.release()\n\t\t\t\tprint('\\nRELEASED\\n')\n\t\t\n# --- main ---\n\nprint('\\nImage classifier server. If no arguments are given, will listen to socket.')\nprint('To classify an image, type: \\\"img_classifier imagename\\\".')\nprint('To learn an image, type: \\\"img_classifier imagename class\\\", where class is 1 to reject, 0 to accept.')\n\n\n#inputfile='img/to_accept.png'\n#mask, to_process = process_image(img) # Process image \n#cv2.imshow('Threshold', img)\n# cv2.waitKey(0)\n#y = [ 0 ]\n#print('Will learn image ',inputfile,' as ',y)\n#out = classify_image(img,1,y)\n\n\nif len(sys.argv)>1: # Get file name from input, if input is given\n\tinputfile = sys.argv[1]\n\timg = get_greyscale(inputfile)\n\t\n# cv2.imshow('Threshold', img)\n# cv2.waitKey(0)\n\n\tif len(sys.argv)>2: # Get file name from input, if input is given\n\t\ty = [ int(sys.argv[2]) ]\n\t\tprint('Will learn image ',inputfile,' as ',y)\n\t\tout = classify_image(img,1,y,inputfile)\n\telse:\n\t\tprint('Will classify image ',inputfile)\n\t\tout = classify_image(img,0)\n\tprint('Prediction Output = ',out)\n# classify_image(mask,train = 0, y=[0])\nelse:\n\trun(CAMERA_ADDRESS)\n","sub_path":"imgclassifier0.1.py","file_name":"imgclassifier0.1.py","file_ext":"py","file_size_in_byte":14199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"83085029","text":"import pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import BaggingClassifier\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.utils.multiclass import unique_labels\nimport numpy as np\n\n\n# READ DATA INTO LISTS\ntraining = open(\"processed_train_raw.tsv\")\ndev = open(\"processed_dev_raw.tsv\")\nx_train = []\ny_train = []\nx_dev = []\ny_dev = []\n\nfor line in training:\n line = line.split(\"\\t\")\n x_train.append(line[2])\n y_train.append(line[1])\n\nfor line in dev:\n line = line.split(\"\\t\")\n x_train.append(line[2])\n y_train.append(line[1])\n\n# CREATE A TRAINING DATA VECTOR\nvectorizer_t = TfidfVectorizer(stop_words=\"english\")\nv_train = vectorizer_t.fit_transform(x_train)\n\n\n# TOKENIZE THE TEST DATA\nx_dev_t = []\nnltk.download('stopwords')\nnltk.download('punkt')\nstop_words = set(stopwords.words('english'))\nfor str in x_dev:\n tokens = word_tokenize(str)\n tokens = [w for w in tokens if not w in stop_words]\n x_dev_t.append(tokens)\n\n# FIND THE BEST FEATURES\nkbest_t = SelectKBest(chi2, k=400)\nkbest_t.fit(v_train, y_train)\nmask = kbest_t.get_support()\nxk_train = kbest_t.transform(v_train)\nxk_train = xk_train.toarray()\n\nbest_features = []\nfor i in range(len(mask)):\n if (mask[i]):\n best_features.append(vectorizer_t.get_feature_names()[i])\n\n\ndev_data = []\nfor line in x_dev_t:\n instance = []\n for f in best_features:\n instance.append(line.count(f))\n dev_data.append(instance)\n\ndev_data = pd.DataFrame(dev_data)\ndev_data = dev_data.values\n\n\ny_dev_i = []\nfor i in range(len(y_dev)):\n if y_dev[i] == 'Melbourne':\n y_dev_i.append(0)\n elif y_dev[i] == 'Sydney':\n y_dev_i.append(1)\n elif y_dev[i] == 'Brisbane':\n y_dev_i.append(2)\n else:\n y_dev_i.append(3)\n\nclass_names = np.array(['Melbourne', 'Sydney', 'Brisbane', 'Perth'])\n\n\nclassifier = MultinomialNB(())\ny_pred = classifier.fit(xk_train, y_train).predict(dev_data)\n\ny_pred_i = []\nfor i in range(len(y_pred)):\n if y_pred[i] == 'Melbourne':\n y_pred_i.append(0)\n elif y_pred[i] == 'Sydney':\n y_pred_i.append(1)\n elif y_pred[i] == 'Brisbane':\n y_pred_i.append(2)\n else:\n y_pred_i.append(3)\n\n\n# class definition used from:\n# https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\ndef plot_confusion_matrix(y_true, y_pred, classes,\n normalize=False,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n\n # Compute confusion matrix\n cm = confusion_matrix(y_true, y_pred)\n # Only use the labels that appear in the data\n\n classes = classes[unique_labels(y_true, y_pred)]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n title=title,\n ylabel='True label',\n xlabel='Predicted label')\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax\n\n\nnp.set_printoptions(precision=2)\n# Plot non-normalized confusion matrix\nplot_confusion_matrix(y_dev_i, y_pred_i, classes=class_names,\n title='Confusion matrix, without normalization')\n\n# Plot normalized confusion matrix\nplot_confusion_matrix(y_dev_i, y_pred_i, classes=class_names, normalize=True,\n title='MNB Normalized Confusion Matrix')\n\nplt.show()","sub_path":"confusion-matrix.py","file_name":"confusion-matrix.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"424403206","text":"\"\"\"\n\n多個線程共享數據 - 有鎖的情況\n\nVersion: 0.1\nAuthor: 駱昊\nDate: 2018-03-20\n\n\"\"\"\n\nimport time\nimport threading\n\n\nclass Account(object):\n\n\tdef __init__(self):\n\t\tself._balance = 0\n\t\tself._lock = threading.Lock()\n\n\tdef deposit(self, money):\n\t\t# 獲得鎖後代碼才能繼續執行\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tnew_balance = self._balance + money\n\t\t\ttime.sleep(0.01)\n\t\t\tself._balance = new_balance\n\t\tfinally:\n\t\t\t# 操作完成後一定要記著釋放鎖\n\t\t\tself._lock.release()\n\n\t@property\n\tdef balance(self):\n\t\treturn self._balance\n\n\nif __name__ == '__main__':\n\taccount = Account()\n\t# 創建100個存款的線程向同一個賬戶中存錢\n\tfor _ in range(100):\n\t\tthreading.Thread(target=account.deposit, args=(1,)).start()\n\t# 等所有存款的線程都執行完畢\n\ttime.sleep(2)\n\tprint('賬戶余額爲: ¥%d元' % account.balance)\n\n# 想一想結果爲什麽不是我們期望的100元\n","sub_path":"Day01-15/Day13/multithread6.py","file_name":"multithread6.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236229976","text":"from flask import session, request, redirect\n\nfrom app.server import server\n\n\n@server.route(\"/theme/light\", methods=['POST'])\ndef set_light_theme():\n session['dark_theme'] = False\n redirect_url = request.args.get('redirect') or '/'\n return redirect(redirect_url, code=303)\n\n\n@server.route(\"/theme/dark\", methods=['POST'])\ndef set_dark_theme():\n session['dark_theme'] = True\n redirect_url = request.args.get('redirect') or '/'\n return redirect(redirect_url, code=303)\n","sub_path":"app/routes/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"112579812","text":"from ast import walk, AugAssign, Add, Sub\nimport os\nimport sys\n\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), \"..\", \"..\")))\n\n\nfrom testrunner import CodersLabTestSuite, CodersLabException, p, dedent\n\n\ntc = CodersLabTestSuite(\"Inkrementacja i dekrementacja\")\n\n\n@tc.test(\"Tekst jest wypisywany na ekranie\", aborts=True)\ndef test_variables(invoke, stdout, **kwargs):\n variables = invoke()\n\n tc.assert_print_called(stdout)\n\n for expected in (\"145\", \"146\"):\n if not any(expected in line for line in stdout):\n raise CodersLabException(\n \"Nie znaleziono liczby {} w wypisywanym tekście\".format(\n p.b.get(expected)\n )\n )\n\n if \"counter\" not in variables:\n raise CodersLabException(\n \"Nie znaleziono zmiennej {}\".format(p.b.get(\"counter\"))\n )\n\n if variables[\"counter\"] != 145:\n raise CodersLabException(\n dedent(\n \"\"\"\n Po zakończeniu skryptu zmienna {} powinna mieć wartość {}.\n Jej obecna wartość to {}.\n \"\"\"\n ).format(\n p.b.get(\"counter\"),\n p.b.get(\"145\"),\n p.b.get(variables[\"counter\"]),\n )\n )\n\n\n@tc.test(\n \"Użyto operatora {op}\",\n params=(\n {\"op\": \"+=\", \"cls\": Add},\n {\"op\": \"-=\", \"cls\": Sub},\n ),\n)\ndef test_variables(ast, op, cls, **kwargs):\n for node in walk(ast):\n if isinstance(node, AugAssign) and isinstance(node.op, cls):\n return\n\n raise CodersLabException(\n dedent(\n \"\"\"\n Operator {} nie został znaleziony w kodzie.\n \"\"\"\n ).format(\n p.b.get(op),\n )\n )\n\n\ntc.run()\n","sub_path":"03_Biblioteka_standardowa_w_jezyku_Python/04_Inkrementacja_i_dekrementacja/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"228146797","text":"\"\"\"Train an ICNet Model on ADE20K Data.\"\"\"\n\nimport argparse\nimport keras\nimport logging\nimport sys\nimport setup\n\nfrom keras import backend as K\nfrom keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, TensorBoard, Callback\nimport tensorflow as tf\n\nfrom image_segmentation.icnet2 import ICNetModelFactory\nfrom image_segmentation.data_generator import ADE20KGenerator\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger('train')\n\n#from callbacks import TensorBoardImage\nfrom metrics import mean_IoU,categorical_crossentropy_logits\nfrom utils import random_crop,one_hot_it,colour_code_segmentation,prepare_data,ATRSequence,get_label_info\n\n#########################\n##Create a global session\n#########################\ns=tf.Session()\nK.set_session(s)\n\ndef train(argv):\n \"\"\"Train an ICNet model.\"\"\"\n parser = argparse.ArgumentParser(\n description='Train an ICNet model.'\n )\n # Data options\n parser.add_argument(\n '-d', '--data-directory', type=str, required=False,\n help='The top level directory containing AED2K data.'\n )\n parser.add_argument(\n '-s', '--image-size', type=int, default=384,\n help=('The pixel dimension of model input and output. Images '\n 'will be square.')\n )\n parser.add_argument(\n '-a', '--augment-images', type=bool, default=True,\n help='turn on image augmentation.'\n )\n parser.add_argument(\n '-w', '--whitelist-labels', type=str,\n help=('A pipe | separated list of object labels to whitelist. To see a'\n ' full list of allowed labels run with --list-labels.')\n )\n parser.add_argument(\n '-t', '--whitelist-threshold', type=float, default=0.7,\n help=('The fraction of whitelisted labels an image must contain to be '\n 'used for training.')\n )\n parser.add_argument(\n '--list-labels', action='store_true',\n help='If true, print a full list of object labels.'\n )\n # Training options\n parser.add_argument(\n '-b', '--batch-size', type=int, default=8,\n help='The training batch_size.'\n )\n parser.add_argument(\n '--lr', type=float, default=0.001, help='The learning rate.'\n )\n parser.add_argument(\n '-e', '--epochs', type=int, default=1000,\n help='Number of training epochs'\n )\n parser.add_argument(\n '-o', '--output', type=str, required=False,\n help='An output file to save the trained model.')\n parser.add_argument(\n '--checkpoint', type=str,\n help='A Keras model checkpoint to load and continue training.'\n )\n\n args = parser.parse_args(argv)\n\n # if args.list_labels:\n # logger.info('Labels:')\n # labels = ''\n # for label in ADE20KGenerator.load_class_labels( setup.dataset_dir):\n # labels += '%s\\n' % label\n # logger.info(labels)\n # sys.exit()\n\n whitelist_labels = None\n if args.whitelist_labels:\n whitelist_labels = args.whitelist_labels.split('|')\n\n # generator = ADE20KGenerator(\n # setup.dataset_dir,\n # batch_size=setup.batch_size,\n # image_size=(args.image_size, args.image_size)\n # )\n\n\n icnet = ICNetModelFactory.build(\n args.image_size,\n setup.classes,\n train=True\n )\n\n optimizer = keras.optimizers.Adam(lr=args.lr)\n icnet.compile(\n optimizer,\n loss=keras.losses.categorical_crossentropy,\n loss_weights=[1.0, 0.8, 0.4, 0.16],\n metrics=[mean_IoU],\n )\n icnet.summary()\n ###########\n ##callbacks\n ###########\n sess = K.get_session()\n callbacks = [ModelCheckpoint('models/ATR_ICNet.h5',\n verbose=0,\n mode='auto',\n period=1),\n TensorBoard(log_dir=setup.logdir),\n #TensorBoardImage(sess, \"Segmentation\", \"Overlay\")\n ]\n # callbacks = [\n # keras.callbacks.ModelCheckpoint(\n # args.output,\n # verbose=0,\n # mode='auto',\n # period=1\n # ),\n # ]\n\n\n\n train_input_names, train_output_names, val_input_names, val_output_names, test_input_names, test_output_names = prepare_data(setup.dataset_dir)\n\n generator = ATRSequence(\"train\", train_input_names, train_output_names, setup.batch_size, setup.csv_path)\n validation_data = ATRSequence(\"validation\", val_input_names, val_output_names, setup.batch_size, setup.csv_path)\n\n icnet.fit_generator(generator,\n len(generator),\n epochs=setup.epochs,\n verbose=1,\n shuffle=True,\n callbacks=callbacks,\n validation_data=validation_data,\n )\nif __name__ == '__main__':\n train(sys.argv[1:])\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"15064685","text":"from flask import Flask, render_template\r\nfrom data import db_session\r\nfrom data.jobs import Jobs\r\nfrom data.users import User\r\n\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'f509a688-46b1-492f-911e-a20939a0a875'\r\n\r\n\r\n@app.route('/')\r\ndef work():\r\n db_session.global_init('db/blogs.db')\r\n db_sess = db_session.create_session()\r\n all_data = []\r\n for job in db_sess.query(Jobs).all():\r\n user = job.team_leader\r\n for getting in db_sess.query(User).filter(User.id == user):\r\n user = getting.surname + ' ' + getting.name\r\n break\r\n title = job.job\r\n time = job.work_size\r\n people = job.collaborators\r\n is_finished = job.is_finished\r\n all_data.append((title, user, time, people, is_finished))\r\n return render_template(\"work.html\", all_data=all_data)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(port=8080, host='127.0.0.1')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"440094266","text":"# Copyright 2015 The Swarming Authors. All rights reserved.\n# Use of this source code is governed by the Apache v2.0 license that can be\n# found in the LICENSE file.\n\n\"\"\"Models and functions to build and query Auth DB change log.\"\"\"\n\nimport logging\nimport webapp2\n\nfrom google.appengine.api import modules\nfrom google.appengine.api import taskqueue\nfrom google.appengine.ext import ndb\n\nfrom components import decorators\n\nfrom . import config\nfrom . import model\nfrom . import utils\n\n\ndef process_change(auth_db_rev):\n \"\"\"Called asynchronously (via task queue) on AuthDB changes.\"\"\"\n logging.info('Processing AuthDB change rev %d', auth_db_rev)\n\n # We need an initial snapshot of all groups to be able to reconstruct any\n # historical snapshot later. It's important only for applications that existed\n # before change log functionality was added.\n ensure_initial_snapshot(auth_db_rev)\n\n # TODO(vadimsh): Get *History entities in historical_revision_key(auth_db_rev)\n # and diff them against previous versions to produce a set of\n # \"change log entry\" entities (displayed later in UI).\n\n\n### Code to snapshot initial state of AuthDB into *History.\n\n\nclass _AuthDBSnapshotMarker(ndb.Model):\n # AuthDB rev of the snapshot.\n auth_db_rev = ndb.IntegerProperty(indexed=False)\n\n @staticmethod\n def marker_key():\n \"\"\"Returns ndb.Key of entity that exists only if initial snapshot was done.\n\n Bump key ID to redo the snapshot.\n \"\"\"\n return ndb.Key(_AuthDBSnapshotMarker, 1, parent=model.root_key())\n\n\ndef ensure_initial_snapshot(auth_db_rev):\n \"\"\"Makes sure all current AuthDB entities are represented in the history.\n\n It's important only for applications that existed before change log\n functionality was added.\n\n It generates a new AuthDB revision by \"touching\" all existing entities. That\n way we reuse logic of generating *History entities already present in\n model.py. Note that original entities will also be updated ('auth_db_rev'\n property is modified), so it's indeed a true new AuthDB revision.\n \"\"\"\n # Already done?\n key = _AuthDBSnapshotMarker.marker_key()\n if key.get() is not None:\n return\n\n # Is it a fresh application that had change log from the very beginning?\n # No need to snapshot existing groups (they all end up in the history by usual\n # means).\n if auth_db_rev == 1:\n _AuthDBSnapshotMarker(key=key, auth_db_rev=1).put()\n return\n\n @ndb.transactional\n def touch_auth_db():\n # Recheck under transaction.\n if key.get() is not None:\n return\n to_process = []\n\n # Start slow queries in parallel.\n groups_future = model.AuthGroup.query(\n ancestor=model.root_key()).fetch_async()\n whitelists_future = model.AuthIPWhitelist.query(\n ancestor=model.root_key()).fetch_async()\n\n # Singleton entities.\n to_process.append(model.root_key().get())\n to_process.append(model.ip_whitelist_assignments_key().get())\n\n # Finish queries.\n to_process.extend(groups_future.get_result())\n to_process.extend(whitelists_future.get_result())\n\n # Update auth_db_rev properties, make *History entities. Keep modified_by\n # and modified_ts as they were.\n to_put = []\n for ent in to_process:\n if not ent:\n continue\n ent.record_revision(\n modified_by=ent.modified_by,\n modified_ts=ent.modified_ts,\n comment='Initial snapshot')\n to_put.append(ent)\n\n # Store changes, update the marker to make sure this won't run again.\n ndb.put_multi(to_put)\n auth_db_rev = model.replicate_auth_db()\n _AuthDBSnapshotMarker(key=key, auth_db_rev=auth_db_rev).put()\n\n logging.warning('Snapshotting all existing AuthDB entities for history')\n touch_auth_db()\n\n\n### Task queue plumbing.\n\n\n@model.commit_callback\ndef on_auth_db_change(auth_db_rev):\n \"\"\"Called in a transaction that updated AuthDB.\"\"\"\n # Avoid adding task queues in unit tests, since there are many-many unit tests\n # (in multiple project and repos) that indirectly make AuthDB transactions\n # and mocking out 'enqueue_process_change_task' in all of them is stupid\n # unscalable work. So be evil and detect unit tests right here.\n if not utils.is_unit_test():\n enqueue_process_change_task(auth_db_rev)\n\n\ndef enqueue_process_change_task(auth_db_rev):\n \"\"\"Transactionally adds a call to 'process_change' to the task queue.\n\n Pins the task to currently executing version of BACKEND_MODULE module\n (defined in config.py).\n\n Added as AuthDB commit callback in get_backend_routes() below.\n \"\"\"\n assert ndb.in_transaction()\n conf = config.ensure_configured()\n try:\n # Pin the task to the module and version.\n taskqueue.add(\n url='/internal/auth/taskqueue/process-change/%d' % auth_db_rev,\n queue_name=conf.PROCESS_CHANGE_TASK_QUEUE,\n headers={'Host': modules.get_hostname(module=conf.BACKEND_MODULE)},\n transactional=True)\n except Exception as e:\n logging.error(\n 'Problem adding \"process-change\" task to the task queue (%s): %s',\n e.__class__.__name__, e)\n raise\n\n\nclass InternalProcessChangeHandler(webapp2.RequestHandler):\n def post(self, auth_db_rev):\n # We don't know task queue name during module loading time, so delay\n # decorator application until the actual call.\n queue_name = config.ensure_configured().PROCESS_CHANGE_TASK_QUEUE\n @decorators.require_taskqueue(queue_name)\n def call_me(_self):\n process_change(int(auth_db_rev))\n call_me(self)\n\n\ndef get_backend_routes():\n \"\"\"Returns a list of routes with task queue handlers.\n\n Used from ui/app.py (since it's where WSGI module is defined) and directly\n from auth_service backend module.\n \"\"\"\n return [\n webapp2.Route(\n r'/internal/auth/taskqueue/process-change/',\n InternalProcessChangeHandler),\n ]\n","sub_path":"appengine/components/components/auth/change_log.py","file_name":"change_log.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"154029424","text":"import logging\nimport os\nimport pickle\n\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom telegram import ParseMode\n\nfrom typing import Set, Dict\n\n_PICKLE_FILE = 'chats_and_terms.db'\n\n\nclass Bot():\n def __init__(self,\n token: str,\n pickle_path=os.path.dirname(os.path.realpath(__file__))\n ) -> None:\n logging.info('Creating bot')\n self.token = token\n self.pickle_path = pickle_path\n self.chat_ids: Dict[str, str] = self._read_picked_data()\n\n self.updater = Updater(token, use_context=True)\n self.dispatcher = self.updater.dispatcher\n self.bot = self.updater.bot\n\n self.dispatcher.add_handler(CommandHandler('start', self._start))\n self.dispatcher.add_handler(\n MessageHandler(Filters.text, self._register))\n\n if len(self.chat_ids) > 0:\n for user in self.chat_ids.keys():\n self.bot.send_message(\n text=\n 'Hi there, just wanted to say I\\'m still on the lookout for your gear. Have a nice day :)',\n chat_id=user,\n parse_mode=ParseMode.MARKDOWN)\n\n self.updater.start_polling()\n\n def get_terms(self) -> Set[str]:\n return set(self.chat_ids.values())\n\n def _register(self, update, context) -> None:\n self.chat_ids[update.message.chat_id] = update.message.text\n update.message.reply_markdown(\n f'You will receive updates for *{update.message.text}*')\n self._update_pickled_data()\n\n def _start(self, update, context) -> None:\n self.chat_ids[update.message.chat_id] = ''\n update.message.reply_markdown(\n \"# Hi\\nI'm the friendly reverb search bot! Send me a seach query\" +\n \" and I will notify you of new listings for used electric guitars matching your query 🎸🎸🎸\"\n )\n self._update_pickled_data()\n\n def _read_picked_data(self) -> Dict[str, str]:\n try:\n with open(os.path.join(self.pickle_path, _PICKLE_FILE),\n 'rb') as handle:\n d = pickle.load(handle)\n return d if d is not None else {}\n except FileNotFoundError:\n logging.warn(\n 'No pickled data found. This is normal on the first start.')\n return {}\n\n def _update_pickled_data(self) -> None:\n with open(os.path.join(self.pickle_path, _PICKLE_FILE),\n 'wb') as handle:\n pickle.dump(self.chat_ids,\n handle,\n protocol=pickle.HIGHEST_PROTOCOL)\n\n def send_update(self, term, listing_messages) -> None:\n for user in self.chat_ids.keys():\n if term in self.chat_ids[user]:\n text = f'There are new listings for your search \\'{term}\\'! \\n'\n text += '\\n'.join(listing_messages)\n self.bot.send_message(text=text,\n chat_id=user,\n parse_mode=ParseMode.MARKDOWN)\n","sub_path":"telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"189525518","text":"from django.urls import path\nfrom . import views\n\napp_name = 'students'\nurlpatterns = [\n path('', views.StudentListView.as_view(), name='list_view'),\n path('/', views.StudentDetailView.as_view(), name='detail'),\n path('add/', views.StudentCreateView.as_view(), name='add'),\n path('edit//', views.StudentUpdateView.as_view(), name='edit'),\n path('remove//', views.StudentDeleteView.as_view(), name='remove'),]\n","sub_path":"students/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"87196044","text":"def remove_low_interaction(data, user=\"user_id\", threshold=20):\n\t'''\n\tThis function is to remove those users who have low interactions\n\t(less than the threshold)\n\t'''\n\t# 1. initialize n_users and n_samples\n\tn_users = data.select(user).distinct().count()\n\tn_samples = data.count()\n\t# 2. count the interaction and filter the users \n\t#user_id_frequent = data.groupBy(user).count().filter(\"count>\"+threshold).select(user)\n\t# print the percentage of the user_id which is removed\n\t# 2. create partition by user and count with the partition\n\twindow = Window.partitionBy(user)\n\tdata_freq = data.withColumn(\"count_interaction\",\n\t\t\t\t\t\t\t\tF.count(user) \\\n\t\t\t\t\t\t\t\t.over(window))\n\t# 3. filter the users with less count and \n\tdata_freq = data_freq.where(col(\"count_interaction\") > threshold)\n\tfrequent_user_id = data_freq.select(user).distinct()\n\tprint(\"I remove {0}% of the total users which has less than {1} iteractions.\".\\\n\t\t format(str(round((1-frequent_user_id.count()/n_users)*100, 2)), threshold))\n\t# 4. remove the count_interaction column\n\tdata_freq = data_freq.select(data.schema.names)\n\tprint(\"I remove {0}% of the total rows by deleting the users which have less than {1} iteractions.\".\\\n\t\t format(str(round((1-data_freq.count()/n_samples)*100, 2)), threshold))\n\treturn data_freq\n\ndef remove_low_interaction(data, user=\"user_id\", threshold=20):\n\t'''\n\tThis function is to remove those users who have low interactions\n\t(less than the threshold)\n\t'''\n\t# 1. initialize n_users and n_samples\n\tn_users = data.select(user).distinct().count()\n\tn_samples = data.count()\n\t# 2. count the interaction and filter the users \n\tuser_id_frequent = data.groupBy(user).count().filter(\"count>\"+threshold).select(user)\n\t# print the percentage of the user_id which is removed\n\tprint(\"I remove {0}% of the total users who have less than {1} iteractions.\".\\\n\t\t format(str(round((1-user_id_frequent.count()/n_users)*100, 2)), threshold))\n\t# 3. then delete the users with less count (by joining on the user_id which was not removed from the last step)\n\tdata_freq = data.join(user_id_frequent, user, how='inner').select(data.schema.names)\n\tprint(\"I remove {}% of the total rows by deleting the users which have less than {} iteractions.\".\\\n\t\t format(str(round((1-data_freq.count()/n_samples)*100, 2)), threshold))\n\ndef downsampling(data, user=\"user_id\", percentage=0.01):\n\t'''\n\tThis function is to keep k% of the users in the data\n\t'''\n\tuser_id_1_perc = data.select(user).distinct().sample(False, float(percentage), seed=123)\n\tdownsample_data = data.join(user_id_1_perc, user, how='inner').select(data.schema.names)\n\tprint(\"After downsampling, we only keep {0}% of the high-interation users. Now, wwe have {1} rows and {2} users.\".\\\n\t\t\tformat(float(percentage)*100, downsample_data.count(), downsample_data.select(user).distinct().count()))\n\treturn downsample_data\n\ndef downsampling(data, user=\"user_id\", percentage=0.01):\n\t'''\n\tThis function is to keep k% of the users in the data\n\t'''\n\t# get distinct user\n\tdistinct_user = list(data.select(user).distinct().toPandas()[user])\n\t# create user_id -> group id\n\ndef index_func_no_order(data, col_name):\n\t'''\n\tcol_name: data.select(col_name)\n\t'''\n\t# get distinct col\n\tdistinct_col = list(data.select(col_name).distinct().toPandas()[col_name])\n\t# create distinct column -> group id\n\tmapping = {distinct_col[i]: i+1 for i in range(len(distinct_col))}\n\t# apply mapping dictionary\n\tmapping_expr = create_map([lit(i) for i in chain(*mapping.items())])\n\tindex_data = data.withColumn(col_name+\"_index\", mapping_expr.getItem(col(col_name)))\n\treturn index_data\n\ndef index_func_order(data, col_name):\n\t'''\n\tcol_name: data.select(col_name)\n\t'''\n\tindexer = data.select(col_name).distinct()\\\n\t .orderBy(col_name) \\\n\t .withColumn(col_name+\"_index\",\n\t \t\t\t monotonically_increasing_id() \\\n\t \t\t\t .cast(IntegerType()) \\\n\t \t\t\t ) \\\n\t# indexer = (data.select(col_name).distinct() \\\n\t# \t\t\t.rdd.map(itemgetter(0)).zipWithIndex() \\\n\t# \t\t\t.toDF([col_name, col_name+\"_index\"]))\n\tdata = data.join(indexer, [col_name])\n\treturn data\n","sub_path":"code/downsampling_miscell.py","file_name":"downsampling_miscell.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"533220193","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom flask import Flask,request\n#from requests import get\nfrom sh import wget\nimport re\napp=Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n return \"\"\"\n

    Video Downloader

    \n
    \n \n \n \n
    \n\"\"\"\n\n@app.route('/down',methods=['POST','GET'])\ndef down():\n print(request.method)\n if request.method== \"POST\":\n url = request.form[\"videosrc\"]\n wget(url)\n name = re.findall(r\"\\/(\\w*?)\\.mp4\",url,re.S)[0]\n return \"\"\"\n