diff --git "a/3812.jsonl" "b/3812.jsonl"
new file mode 100644--- /dev/null
+++ "b/3812.jsonl"
@@ -0,0 +1,749 @@
+{"seq_id":"494921685","text":"import os\nimport shutil\n\n\n\nfrom files_extractor import extract_file, is_compressed_file\n\n\nclass CompressedFile:\n def __init__(self, report):\n \tself.report = report\n\n def extract_files(self, compressed_file, destination_path):\n \"\"\"\n Extract files to destination_path from compressed files that are in compressed_path \n \"\"\"\n r = False\n \n if not os.path.exists(destination_path):\n os.makedirs(destination_path)\n \n self.report.write('package file: ' + compressed_file, True, False, True)\n if os.path.isfile(compressed_file):\n if is_compressed_file(compressed_file):\n self.report.write('Extract ' + compressed_file + ' to ' + destination_path, True, False, True) \n if self.__extract__(compressed_file, destination_path):\n r = True\n if not r:\n self.report.write(compressed_file + ' is not a valid file. It must be a compressed file.', True, True, True)\n \n return r\n\n def __extract__(self, compressed_file, destination_path):\n r = False\n # create destination path\n if not os.path.exists(destination_path):\n os.makedirs(destination_path)\n # delete content of destination path\n if os.path.exists(destination_path):\n for i in os.listdir(destination_path):\n os.unlink(destination_path + '/' + i)\n # create tempdir\n temp_dir = self.create_temp_dir()\n # extract in tempdir\n if extract_file(compressed_file, temp_dir):\n # eliminate folders\n for i in os.listdir(temp_dir):\n if os.path.isfile(temp_dir + '/' + i):\n shutil.copy(temp_dir + '/' + i, destination_path)\n os.unlink(temp_dir + '/' + i)\n elif os.path.isdir(temp_dir + '/' + i):\n for f in os.listdir(temp_dir + '/' + i ):\n if os.path.isfile(temp_dir + '/' + i + '/' + f):\n shutil.copy(temp_dir + '/' + i + '/' + f, destination_path)\n os.unlink(temp_dir + '/' + i + '/' + f)\n else:\n self.report.write(f + ' is directory and its contents will be ignored.', True, True, True)\n shutil.rmtree(temp_dir + '/' + i)\n shutil.rmtree(temp_dir)\n r = True\n return r\n\n def create_temp_dir(self):\n import tempfile\n return tempfile.mkdtemp().replace('\\\\', '/')\n \n \n\n \n","sub_path":"src/xml_converter/src/reuse/files/compressed_file.py","file_name":"compressed_file.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"222011955","text":"# Standard libs\nimport argparse\nimport logging\nimport os\nimport tempfile\nfrom datetime import datetime\nfrom glob import glob\nfrom shutil import rmtree\n\n# 3rd party libs\nimport matplotlib.pyplot as plt\nimport netCDF4\nimport numpy as np\nimport pyart\nimport utm\n\nfrom nexradaws.scripts.aws import get_nexrad_data\nfrom utils import *\n\n# Sweep to take\nSWEEP = 0\n\n# Cave file\ncave_csv = 'cave_locations.csv'\n# caves = read_caves(cave_csv, 'KDFX')\n\n# Expected radar grid (azimuth and range)\nAZ_SIZE = None\nRNG_SIZE = None\nAZ = None\nRNG = None\n\n# Thresholds\nPHIDP_THRESH = 70\nREF_THRESH = 5\n\n\ndef process_files(start_date, end_date, site, data_dir, out_dir, verbose=False):\n if verbose:\n logging.basicConfig(format=\"%(asctime)s:%(levelname)s:%(message)s\", level=logging.DEBUG)\n else:\n # Set up logging\n logging.basicConfig(format=\"%(asctime)s:%(levelname)s:%(message)s\", level=logging.INFO)\n\n # Set up the directory for the radar download\n if data_dir is None:\n data_dir = tempfile.mkdtemp()\n logging.debug(\"Created temp dir: {0}\".format(data_dir))\n tmp_dir = True\n else:\n tmp_dir = False\n\n # Start by trying to download the data (should go quick if the data is already in the right directory)\n logging.debug(\"Starting to download data\")\n data_dirs = get_nexrad_data(site, start_date, end_date, data_dir)\n # Make a list of the files to process\n files = []\n for dir in data_dirs:\n dir = os.path.join(dir, '*')\n files = files + glob(dir)\n logging.debug(\"Processing {0} files\".format(len(files)))\n\n # Do some bookkeeping for later\n image_base_dir = os.path.join(out_dir, 'images')\n logging.debug(\"Images being written to {0}\".format(image_base_dir))\n nc_base_dir = os.path.join(out_dir, 'netcdf')\n logging.debug(\"NetCDFs being written to {0}\".format(nc_base_dir))\n\n # Iterate through the files\n first = True\n count = 0\n for f in files:\n logging.info(\"Processing {0}\".format(f))\n\n try:\n radar = pyart.io.read_nexrad_archive(f)\n except Exception as e:\n print(\"Can't open file \" + f)\n continue\n\n dt = pyart.graph.common.generate_radar_time_begin(radar) # Scan time\n slice = radar.get_slice(SWEEP)\n\n if radar.metadata['vcp_pattern'] not in [31, 32]:\n logging.warning(\"VCP other than clear air mode found, skipping file\")\n continue\n\n if dt > datetime.strptime(end_date, \"%Y%m%d-%H%M%S\"):\n break\n\n if first:\n radar_lat = radar.latitude['data'][0]\n radar_lon = radar.longitude['data'][0]\n\n cave_x = []\n cave_y = []\n # Convert cave lat/lon to x/y coord system\n x_radar, y_radar, _, _ = utm.from_latlon(radar_lat, radar_lon)\n\n caves = read_caves(cave_csv, site)\n\n for cave in caves:\n # Convert lat-lons to utm for\n x_bat, y_bat, _, _ = utm.from_latlon(float(cave['lat']), float(cave['lon']))\n # Calc relative x and y of roost\n x_rel_m = (x_bat - x_radar)\n y_rel_m = (y_bat - y_radar)\n cave['x'] = x_rel_m / 1e3\n cave['y'] = y_rel_m / 1e3\n\n cave_x.append(x_rel_m/1e3)\n cave_y.append(y_rel_m/1e3)\n # Get rid of misc crap\n del x_bat, y_bat, _\n\n # Convert lat-lons to utm forndvf0\n x_radar, y_radar, _, _ = utm.from_latlon(radar_lat, radar_lon)\n\n # Init arrays for averaging\n phi_dp_running = np.zeros_like(radar.fields['differential_phase']['data'][slice].data)\n phi_dp_weighted_running = np.zeros_like(phi_dp_running)\n phi_dp_linear_weighted_running = np.zeros_like(phi_dp_running)\n ref_linear_running = np.zeros_like(radar.fields['reflectivity']['data'][slice].data)\n ref_running = np.zeros_like(ref_linear_running)\n eta_linear_running = np.zeros_like(ref_linear_running)\n\n # Get azimuth, range, and elevation for conversion to x and y\n range_m, az_deg = np.meshgrid(radar.range['data'], radar.azimuth['data'][slice])\n az_rad = np.deg2rad(az_deg)\n elev = np.deg2rad(np.mean(radar.elevation['data'][slice]))\n\n x_m = range_m * np.cos(elev) * np.sin(az_rad)\n y_m = range_m * np.cos(elev) * np.cos(az_rad)\n\n # Get the correct order of the azimuths\n az_p = np.argsort(az_rad, axis=0)[:, 0]\n\n # Sort the x and y grids based on the order of the azimuths\n x_m = x_m[az_p, :]\n y_m = y_m[az_p, :]\n\n if first:\n RNG = range_m[0, :]\n RNG_SIZE = RNG.size\n AZ = az_rad[:, 0][az_p]\n AZ_SIZE = AZ.size\n first = False\n\n # # Apply filters and corrections to data\n logging.debug(\"Applying corrections\")\n gate_filter = pyart.filters.GateFilter(radar)\n gate_filter.exclude_below('differential_phase', PHIDP_THRESH)\n gate_filter.exclude_below('reflectivity', REF_THRESH)\n gate_filter = pyart.correct.despeckle_field(radar, 'differential_phase', gatefilter=gate_filter)\n\n # Extract the desired data and get it in the correct order\n phi_dp = radar.fields['differential_phase']['data'][slice][az_p, :]\n ref = radar.fields['reflectivity']['data'][slice][az_p, :]\n\n # Convert the filter to mask\n phi_dp.mask = gate_filter.gate_excluded[az_p, :]\n ref.mask = gate_filter.gate_excluded[az_p, :]\n\n # Check to make sure the data lines up with the desired size\n if phi_dp_running.shape != phi_dp.shape:\n logging.warning(\"Data size other than ({}, {}) found\".format(AZ_SIZE, RNG_SIZE))\n logging.warning(\"Data size: ({}, {})\".format(phi_dp.shape[0], phi_dp.shape[1]))\n if az_rad.size < AZ_SIZE:\n logging.debug(\"Applying pad to account for having too few azimuths\")\n diff = abs(az_rad.size - AZ_SIZE)\n phi_dp = np.pad(phi_dp, diff, mode='constant')[diff:, diff:-diff]\n ref = np.pad(ref, diff, mode='constant')[diff:, diff:-diff]\n elif az_rad.size > AZ_SIZE:\n logging.debug(\"Chopping off end of grid because too many azimuths\")\n phi_dp = phi_dp[:AZ_SIZE, :]\n ref = ref[:AZ_SIZE, :]\n else:\n logging.critical(\"SOMETHING WENT WRONG WITH THE RANGE\")\n raise Exception\n\n # Add data to the running sums\n # try:\n logging.debug(\"Added data to running sums\")\n phi_dp_running[~phi_dp.mask] += phi_dp[~phi_dp.mask]\n phi_dp_weighted_running[~phi_dp.mask] += phi_dp[~phi_dp.mask] * ref[~phi_dp.mask]\n phi_dp_linear_weighted_running[~phi_dp.mask] += phi_dp[~phi_dp.mask] * db2pow(ref[~phi_dp.mask])\n\n ref_running[~ref.mask] += ref[~ref.mask]\n ref_linear_running[~ref.mask] += db2pow(ref[~ref.mask])\n eta_linear_running[~ref.mask] += db2pow(ref[~ref.mask] + 11.6)\n\n # Make some plots\n plt.figure(figsize=(16, 8))\n plt.subplot(1, 2, 1)\n plt.xlim(-100, 100)\n plt.ylim(-100, 100)\n plt.pcolormesh(x_m * 1e-3, y_m * 1e-3, phi_dp, vmin=0, vmax=360, cmap='nipy_spectral')\n plt.colorbar()\n plt.scatter(0, 0, color='k')\n plt.scatter(cave_x, cave_y, c='y')\n\n plt.subplot(1, 2, 2)\n plt.xlim(-100, 100)\n plt.ylim(-100, 100)\n plt.pcolormesh(x_m * 1e-3, y_m * 1e-3, ref, vmin=0, vmax=50)\n plt.colorbar()\n plt.scatter(0, 0, color='k')\n\n # Create directory if needed\n image_dir = os.path.join(image_base_dir, dt.strftime('%Y/%m/'))\n if not os.path.exists(image_dir): os.makedirs(image_dir)\n image_name = os.path.join(image_dir, dt.strftime('{site}_%Y%m%d_%H%M%S.png'.format(site=site)))\n\n plt.suptitle(dt.strftime('{site} %Y%m%d-%H%M%S Elev: {elev}'.format(elev=np.rad2deg(elev), site=site)))\n logging.debug(\"Saving image: {}\".format(image_name))\n plt.savefig(image_name)\n plt.close()\n # plt.show(block=True)\n\n count += 1\n\n # If no files were processed\n if count == 0:\n return\n\n # Write out the netcdf\n logging.info(\"Preparing netCDF\")\n start_time = datetime.strptime(start_date, \"%Y%m%d-%H%M%S\")\n if not os.path.exists(nc_base_dir): os.makedirs(nc_base_dir)\n nc_name = os.path.join(nc_base_dir, start_time.strftime(\"{}_average_%Y%m%d.nc\".format(site)))\n nc = netCDF4.Dataset(nc_name, 'w')\n\n # Add the dimensions\n print(phi_dp_running.shape[1], AZ.shape)\n az = nc.createDimension('az', size=phi_dp_running.shape[0],)\n rng = nc.createDimension('rng', size=phi_dp_running.shape[1],)\n\n # Add the attributes\n attrs = {'num_scans': count,\n 'start_time': start_date,\n 'end_time': end_date,\n 'radar_lat': radar_lat,\n 'radar_lon': radar_lon,\n 'sweep_number': SWEEP,\n 'elevation': np.rad2deg(elev),\n 'site': site\n }\n nc.setncatts(attrs)\n\n # Add the variables\n var = nc.createVariable('phi_dp_sum', datatype='f8', dimensions=('az', 'rng'))\n var.setncattr('units', 'degrees')\n var[:] = phi_dp_running\n\n var = nc.createVariable('phi_dp_weighted_sum', datatype='f8', dimensions=('az', 'rng'))\n var[:] = phi_dp_weighted_running\n\n var = nc.createVariable('phi_dp_linear_weighted_sum', datatype='f8', dimensions=('az', 'rng'))\n var[:] = phi_dp_linear_weighted_running\n\n var = nc.createVariable('ref_linear_sum', datatype='f8', dimensions=('az', 'rng'))\n var.setncattr('units', 'mm^6/m^3')\n var[:] = ref_linear_running\n\n var = nc.createVariable('ref_sum', datatype='f8', dimensions=('az', 'rng'))\n var[:] = ref_running\n\n var = nc.createVariable('eta_linear_sum', datatype='f8', dimensions=('az', 'rng'))\n var[:] = eta_linear_running\n\n var = nc.createVariable('azimuth', datatype='f8', dimensions=('az',))\n var.setncattr('units', 'radians')\n var[:] = AZ\n\n var = nc.createVariable('range', datatype='f8', dimensions=('rng',))\n var.setncattr('units', 'm')\n var[:] = RNG\n\n nc.close()\n logging.info(\"NetCDF write successful\")\n\n # Delete the temporary folder if used\n if tmp_dir is True:\n logging.debug(\"Removing temp dir\")\n rmtree(data_dir)\n\nif __name__=='__main__':\n # Set up argument parser\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', dest='start_date', help=\"YYYYmmdd-HHMMSS\")\n parser.add_argument('-e', dest='end_date', help=\"YYYYmmdd-HHMMSS\")\n parser.add_argument('-r', dest='radar')\n parser.add_argument('-d', dest='data_dir',\n help='directory to download radar data (uses tmp dir otherwise)',\n default=None)\n parser.add_argument('-o', dest='out_dir',\n help='Directory to put images and netcdfs. Code will organize the dir structure')\n args = parser.parse_args()\n\n process_files(args.start_date, args.end_date, args.radar, args.data_dir, args.out_dir)\n\n\n\n","sub_path":"nightly_average.py","file_name":"nightly_average.py","file_ext":"py","file_size_in_byte":11166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"491821998","text":"from selenium import webdriver\nimport pytest\n\n# browser = webdriver.Firefox()\n# browser.get('http://localhost:8000')\n\n\nclass TestNewVisitor:\n\n @pytest.yield_fixture\n def driverPJS(self):\n driver = webdriver.PhantomJS()\n print(\"Created PhantomJS driver\")\n driver.get(\"http://localhost:8000\")\n yield driver\n driver.quit()\n print(\"\\nDestroyed PhantomJS driver\")\n\n def test_page_title(self, driverPJS):\n # She notices the page title and header mention to-do lists\n print(\"Running test\")\n assert 'Django' in driverPJS.title\n\n\n\n # # She is invited to enter a to-do item straight away\n\n\n","sub_path":"tests/functional_tests/selenium_test.py","file_name":"selenium_test.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"450022947","text":"import flask\nimport datetime\nimport random\n\napp = flask.Flask(\"my_app\")\n\n\n@app.route(\"/like\")\n@app.route(\"/home\")\ndef first_view():\n my_name = \"adam\"\n now = datetime.datetime.now()\n time = \"{}/{}/{}\".format(now.day, now.month, now.year)\n secend = datetime.time\n rendr = flask.render_template(\"te.html\", name=my_name, time=time\n , sea=secend)\n return rendr\n\n\n@app.route(\"/\")\ndef welc(num):\n number = random.randrange(1, 10)\n if num == number:\n return \"your number is\" + number\n else:\n return \"number not match\"\n\n\n@app.route(\"/me\")\ndef sec_view():\n t2 = flask.render_template(\"t2\", )\n return t2\n\n\nif __name__ == \"__main__\":\n app.run(port=5000)\n","sub_path":"python+flask_work/class_21/flask1.py","file_name":"flask1.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"509954716","text":"# maximum path sum II\nf = open('input/064input.txt').read().split('\\n')\nfor x in range(len(f)):\n\tf[x] = list(map(int,f[x].split()))\nf = f[:-1] # weird empty array in the end.\n\nrow_now = len(f) - 2 # second last\n\nwhile row_now >= 0:\n\trow_down = row_now + 1\n\tfor ind in range(len(f[row_now])): f[row_now][ind] += max(f[row_down][ind],f[row_down][ind+1])\n\trow_now -= 1\n\nprint (f[0][0]) # max sum.\n\n","sub_path":"euler/py/067.py","file_name":"067.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"125980529","text":"#!usr/bin/env python\nimport numpy as np\nfrom lxml import etree\nimport sys\n\n# some constant\nC2B = 2.\nagf_bs = 0.7\n\n# get filename\nprint(sys.argv)\nsim_type = str(sys.argv[1])\n\n# separate the string to get site name and setup\nsite_name = sim_type.split('_')[0]\nsetup = sim_type.split('_')[1]\n\nxml_fn = \"{:s}_config.xml\".format(sim_type)\n\n# first check the setup array to determine which pft to use\nif setup[0:2] == 'p0':\n # ED2 original\n pft_array=[2,3,4]\nelif setup[0:2] == 'p1':\n # ED2 TLP 6 PFT\n pft_array=[2,3,4,5,6,7]\nelif setup[0:2] == 'p2':\n # ED2 XXT 3 PFT\n pft_array=[2,3,4]\n\n\n\n# write the header for xml files\ns = '''\n'''\ntree = etree.fromstring(s)\n\n# dictionary to store parameters to change for all PFTs\npft_dict_all = {\n 'root_beta' : '0.01',\n }\n\n# create three pfts in xml\nxml_pfts=[]\nfor ipft, pft in enumerate(pft_array):\n xml_pfts.append(etree.SubElement(tree,\"pft\"))\n etree.SubElement(xml_pfts[ipft], \"num\").text = \"{:d}\".format(pft)\n for trait in pft_dict_all.keys():\n etree.SubElement(xml_pfts[ipft], trait).text = pft_dict_all[trait]\n\n# always modify fuse_dbh_max\nxml_ff = etree.SubElement(tree,\"fusefiss\")\netree.SubElement(xml_ff, \"fuse_dbh_max\").text = \"{:f}\".format(20.)\n\n\n\n# now setup hydro\nif (setup[1] == '0'):\n # ED2 default\n #do nothing\n pass\nelif (setup[1] == '2'):\n # ED2 XXT\n # do nothing\n # need to change qsw\n for ipft, pft in enumerate(pft_array):\n etree.SubElement(xml_pfts[ipft], \"qsw\").text = \"{:f}\".format(0.)\n\nelif (setup[1] == '1'):\n # ED2 TLP\n # first read in the h0_params.xml\n template_params_tree = etree.parse('./template_params.xml')\n template_root = template_params_tree.getroot()\n\n # loop over the pft setups and write into the new xml_pfts\n for ipft in np.arange(3):\n pft_to_copy = template_root[ipft]\n\n # write the intolerant pft\n pft_to_write = xml_pfts[ipft]\n\n params_dict = {\n 'wood_psi50' : -1.2 * 102.,\n 'wood_Kmax' : 3.3 / 102.,\n 'leaf_psi_tlp' : -1.67 * 102.,\n 'stoma_psi_b' : -1.67 * 102.,\n 'stoma_psi_c' : 3.,\n 'qsw' : 0.,\n }\n\n exist_vars = [element.tag for element in pft_to_write.iter()]\n # loop over pft_to_copy\n\n for element in pft_to_copy.iter():\n if element.tag == 'pft' or element.tag == 'init_laimax':\n # pass these two tags\n continue\n\n\n # over write the hydraulic properties\n if element.tag in params_dict.keys():\n etree.SubElement(pft_to_write, element.tag).text = \"{:f}\".format(\n params_dict[element.tag])\n elif element.tag in exist_vars:\n pass\n # no need to do anything\n else:\n etree.SubElement(pft_to_write, element.tag).text = element.text\n\n\n # write the tolerant pft\n params_dict = {\n 'wood_psi50' : -2.2 * 102.,\n 'wood_Kmax' : 3. / 102.,\n 'leaf_psi_tlp' : -2.83 * 102.,\n 'stoma_psi_b' : -2.83 * 102.,\n 'stoma_psi_c' : 3.5,\n 'qsw' : 0.,\n }\n\n pft_to_write = xml_pfts[ipft+3]\n\n exist_vars = [element.tag for element in pft_to_write.iter()]\n\n # loop over pft_to_copy\n for element in pft_to_copy.iter():\n if element.tag == 'pft' or element.tag == 'init_laimax':\n continue\n\n # over write the hydraulic properties\n if element.tag in params_dict.keys():\n etree.SubElement(pft_to_write, element.tag).text = \"{:f}\".format(\n params_dict[element.tag])\n elif element.tag in exist_vars:\n pass\n # no need to do anything\n else:\n etree.SubElement(pft_to_write, element.tag).text = element.text\n\n\noutput_str = etree.tostring(tree, encoding=\"UTF-8\",\n xml_declaration=True,\n pretty_print=True,\n doctype='')\n\n# write into file\nwith open(xml_fn,'wb') as f:\n f.write(output_str)\n","sub_path":"ED2-treering/run_HKK/create_xml.py","file_name":"create_xml.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"499078090","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\nimport pandas as pd\nplt.style.use('ggplot')\n# from sklearn import preprocessing\n# import seaborn as sns\n\n# def plot(v,pv_anPDF,pv_anCDF,pv_emp_exp,pv_emp_log,phase):\ndef plot(v,pv_anPDF,pv_emp_exp,pv_emp_exp_95,phase):\n print(pv_emp_exp_95)\n plt.hist(pv_emp_exp,bins=100,density=True,color='mediumseagreen',alpha=1,label='Simulated PDF')\n # sns.distplot(pv_emp_exp, hist=True, kde=False, bins=100, norm_hist=True)\n plt.plot(v,pv_anPDF,color='darkred',linestyle='dashed',label='Analytical PDF')\n # plt.plot(v,pv_anCDF,'k:',label='Analytical CDF (exponential)')\n # plt.hist(pv_emp_log,bins=100,density=1,color='green',alpha=0.7,label='Simulated PDF (log-norm)')\n plt.axvline(x=pv_emp_exp_95,color='k',label='95% = £{}'.format(pv_emp_exp_95))\n plt.xlabel('Present Value £ '+ '('+phase+')')\n plt.ylabel('Frequency')\n plt.legend(loc='best',fontsize=11)\n # fig.tight_layout()\n plt.show()\n\n\ndef pv_total(pv1,pv2,pv_95,phase):\n plt.hist(pv1,bins=100,density=1,color='blue',alpha=0.6,label='Simulated PDF (exponential)')\n plt.hist(pv2,bins=100,density=1,color='green',alpha=0.7,label='Simulated PDF (log-norm)')\n plt.axvline(x=pv_95,color='k',label='95% = £{}'.format(pv_95))\n plt.xlabel('Present Value £ '+ '('+phase+')')\n plt.ylabel('Frequency')\n plt.legend(loc='best')\n plt.show()\n\n\ndef setCoverPlot(subcontrols_list,position,positionCL,positionCH,positionEL,positionEH):\n no_constraint = [float('nan') for x in range(len(subcontrols_list))]\n costL = [float('nan') for x in range(len(subcontrols_list))]\n costH = [float('nan') for x in range(len(subcontrols_list))]\n cost_efficacyL = [float('nan') for x in range(len(subcontrols_list))]\n cost_efficacyH = [float('nan') for x in range(len(subcontrols_list))]\n for i in position:\n no_constraint[i] = 1\n for i in positionCL:\n costL[i] = 2\n for i in positionCH:\n costH[i] = 3\n for i in positionEL:\n cost_efficacyL[i] = 4\n for i in positionEH:\n cost_efficacyH[i] = 5\n\n x = np.arange(len(subcontrols_list))\n y = [0,1,2,3,4,5]\n fig, ax = plt.subplots()\n ax.scatter(x,no_constraint,s=70,color='black')\n ax.scatter(x,costL,marker='D',s=60,color='black')\n ax.scatter(x,costH,marker='X',s=60,color='black')\n ax.scatter(x,cost_efficacyL,marker='h',s=80,color='black')\n ax.scatter(x,cost_efficacyH,marker='*',s=90,color='black')\n # plt.axhline(y=1, linestyle=':',color='k',alpha=0.2)\n # plt.axhline(y=2, linestyle=':',color='k',alpha=0.2)\n # plt.axhline(y=3, linestyle=':',color='k',alpha=0.2)\n # plt.axhline(y=4, linestyle=':',color='k',alpha=0.2)\n # plt.axhline(y=5, linestyle=':',color='k',alpha=0.2)\n\n # ax.set_ylabel('Subcontrol Selection with')\n ax.set_yticks(y)\n # ax.set_yticklabels([0,'No Constraint','Cost (Level L)','Cost (Level H)', 'Cost and Efficacy\\n(Level L,eff=0.015)', 'Cost and Efficacy\\n(Level H,eff=0.015)'])\n # ax.text(s='Cost and Efficacy\\n(Level L)', x=-6, y=3.7)\n # ax.text(s='Cost and Efficacy\\n(Level H)', x=-12.2, y=4.7)\n ax.set_yticklabels([0,'A','B','C','D','E'])\n ax.text(-1, -3, \"(A) no constraint. (B) budget constraint for subcontrols level L. (C) budget constraint for subcontrols level H. (D) budget and efficacy bound for subcontrols level L. (E) budget and efficacy bound for subcontrols level H.\", color='black', wrap=True,\n bbox=dict(facecolor='none', edgecolor='black', pad=10.0))\n\n ax.set_xlabel('CIS Subcontrols')\n # ax.set_title('Set Cover Problem Control Selection')\n ax.set_xticks(x)\n ax.set_xticklabels(subcontrols_list, rotation=90)\n fig.tight_layout()\n plt.show()\n\n\ndef setCoverEfficacyBoundPlot(subcontrols_list,efficacy_bound,pos_EL,pos_EH):\n cost_efficacyL = [[float('nan') for x in range(len(subcontrols_list))] for x in range(len(pos_EL))]\n cost_efficacyH = [[float('nan') for x in range(len(subcontrols_list))] for x in range(len(pos_EH))]\n efficacy_bound.insert(0,0)\n for i in range(len(pos_EL)):\n if i == 0:\n for x in pos_EL[i]:\n cost_efficacyL[i][x] = 1\n for y in pos_EH[i]:\n cost_efficacyH[i][y] = 1\n elif i == 1:\n for x in pos_EL[i]:\n cost_efficacyL[i][x] = 2\n for y in pos_EH[i]:\n cost_efficacyH[i][y] = 2\n elif i == 2:\n for x in pos_EL[i]:\n cost_efficacyL[i][x] = 3\n for y in pos_EH[i]:\n cost_efficacyH[i][y] = 3\n elif i == 3:\n for x in pos_EL[i]:\n cost_efficacyL[i][x] = 4\n for y in pos_EH[i]:\n cost_efficacyH[i][y] = 4\n\n x = np.arange(len(subcontrols_list))\n y = np.arange(len(efficacy_bound))\n fig, ax = plt.subplots()\n for i in range(len(cost_efficacyL)):\n L = ax.scatter(x,cost_efficacyL[i],s=70,color='steelblue')\n H = ax.scatter(x,cost_efficacyH[i],marker='x',s=60,color='black')\n # plt.axhline(y=i+1, linestyle=':',color='k',alpha=0.2)\n\n ax.set_ylabel('Efficacy Bound')\n ax.set_yticks(y)\n ax.set_yticklabels(efficacy_bound)\n ax.set_xlabel('CIS Subcontrols')\n # ax.set_title('Set cover control selection with cost and efficacy bounds')\n ax.set_xticks(x)\n ax.set_xticklabels(subcontrols_list, rotation=90)\n plt.legend((L, H), ('Level L', 'Level H'), scatterpoints=1)\n fig.tight_layout()\n plt.show()\n\n\ndef knapsackOptimisationPlot(subcontrols_list,position,levels):\n kp_selection = [float('nan') for x in range(len(subcontrols_list))]\n for (i,j) in zip(position,levels):\n if j == 0:\n kp_selection[i] = 1\n else:\n kp_selection[i] = 2\n\n x = np.arange(len(subcontrols_list))\n y = [0,1,2]\n fig, ax = plt.subplots()\n ax.bar(x,kp_selection,color=\"lightseagreen\",alpha=0.8)\n ax.set_yticks(y)\n ax.set_yticklabels([0,'Level L','Level H'])\n ax.set_xlabel('CIS Subcontrols')\n ax.set_xticks(x)\n ax.set_xticklabels(subcontrols_list,rotation=90)\n\n fig.tight_layout()\n plt.show()\n\n\ndef riskPlot(risk_noconstraint,risk_CL,risk_CH,risk_EL,risk_EH,risk_KP,budget):\n\n figure, axes = plt.subplots(1, 3)\n '''ROSI'''\n rosi = []\n rosi.append((risk_noconstraint[1]-risk_noconstraint[3]-risk_noconstraint[4])/risk_noconstraint[4])\n rosi.append((risk_CL[1]-risk_CL[3]-risk_CL[4])/risk_CL[4])\n rosi.append((risk_CH[1]-risk_CH[3]-risk_CH[4])/risk_CH[4])\n rosi.append((risk_EL[1]-risk_EL[3]-risk_EL[4])/risk_EL[4])\n rosi.append((risk_EH[1]-risk_EH[3]-risk_EH[4])/risk_EH[4])\n rosi.append((risk_KP[1]-risk_KP[3]-risk_KP[4])/risk_KP[4])\n # df = pd.DataFrame({'eZn^':[risk_noconstraint[3],risk_CL[3],risk_CH[3],risk_EL[3],risk_EH[3]], 'Cost':[risk_noconstraint[4],risk_CL[4],risk_CH[4],risk_EL[4],risk_EH[4]], 'ROSI':rosi})\n df1 = pd.DataFrame({'ROSI':rosi})\n ax = df1.plot(kind=\"barh\",ax=axes[2],color={\"steelblue\"})\n ax.set_yticklabels(['A','B','C','D','E','F'])\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8])\n ax.legend(loc='upper center',bbox_to_anchor=(0.5,-0.09),fancybox=True,shadow=True,ncol=1,prop={'size': 9})\n\n '''Risk reduction vs cost'''\n risk_reduction = []\n risk_reduction.append((risk_noconstraint[1]-risk_noconstraint[3]))\n risk_reduction.append((risk_CL[1]-risk_CL[3]))\n risk_reduction.append((risk_CH[1]-risk_CH[3]))\n risk_reduction.append((risk_EL[1]-risk_EL[3]))\n risk_reduction.append((risk_EH[1]-risk_EH[3]))\n risk_reduction.append((risk_KP[1]-risk_KP[3]))\n cost = [risk_noconstraint[4],risk_CL[4],risk_CH[4],risk_EL[4],risk_EH[4],risk_KP[4]]\n\n\n # df = pd.DataFrame({'Residual Risk':risk_reduction})\n df2 = pd.DataFrame({'Residual Expected Impact':[risk_noconstraint[3],risk_CL[3],risk_CH[3],risk_EL[3],risk_EH[3],risk_KP[3]], 'Reduced Expected Impact':risk_reduction})\n ax = df2.plot(kind=\"barh\",stacked=True,ax=axes[0],color={\"indianred\",\"black\"})\n ax.set_yticklabels(['A','B','C','D','E','F'])\n ax.text(0, -3.5, \"(A) Set cover with no constraint. (B) Set cover with budget constraint for subcontrols level L. (C) Set cover with budget constraint for subcontrols level H. (D) Set cover with budget and efficacy bound for subcontrols level L. (E) Set cover with budget and efficacy bound for subcontrols level H. (F) Knapsack Optimisation with budget\", color='black', wrap=True,\n bbox=dict(facecolor='none', edgecolor='black', pad=5.0), fontsize=10)\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8])\n\n # Put a legend below current axis\n ax.legend(loc='upper center',bbox_to_anchor=(0.5,-0.09),fancybox=True,shadow=True,ncol=1,prop={'size': 9})\n\n df3 = pd.DataFrame({'Cost':cost})\n ax = df3.plot(kind=\"barh\",ax=axes[1],color={\"gray\"})\n ax.axvline(x=budget, linestyle=':',color='k',alpha=0.2,label='Budget = £'+str(budget))\n ax.set_yticklabels(['A','B','C','D','E','F'])\n # ax.set_xlabel('Budget='+str(budget),fontsize=10)\n # ax.text(budget-10,-0.8,budget)\n # ax.text(-1.4, -2.8, \"(A) Set cover with no constraint. (B) Set cover with budget constraint for subcontrols level L. (C) Set cover with budget constraint for subcontrols level H. (D) Set cover with budget and efficacy bound for subcontrols level L. (E) Set cover with budget and efficacy bound for subcontrols level H. (F) Knapsack Optimisation with budget\", color='black', wrap=True,\n # bbox=dict(facecolor='none', edgecolor='black', pad=10.0))\n # ax.get_legend()\n # plt.legend()\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8])\n ax.legend(loc='upper center',bbox_to_anchor=(0.5,-0.09),fancybox=True,shadow=True,ncol=1,prop={'size': 9})\n\n plt.show()\n\n\ndef knapsackRiskPlot(risk_KP_list,budget_list):\n eZn = []\n eZn_cap = []\n cost = []\n rosi = []\n reduced_risk = []\n for i in risk_KP_list:\n eZn.append(i[1])\n eZn_cap.append(i[3])\n cost.append(i[4])\n rosi.append((i[1]-i[3]-i[4])/i[4])\n reduced_risk.append(i[1]-i[3])\n\n print(f'eZn_cap:{eZn_cap}')\n print(f'rosi:{rosi}')\n\n # df = pd.DataFrame({'eZn_cap':eZn_cap})\n # ax = df.plot.line(color={\"indianred\"})\n # plt.plot(budget_list,eZn_cap,color='indianred',label='residual')\n plt.plot(budget_list,rosi,color='steelblue',label='rosi')\n plt.plot(budget_list,reduced_risk,color='black',label='Reduced Expected Impact')\n plt.xlabel('Budget')\n\n # fig.tight_layout()\n plt.legend(loc='best')\n plt.show()\n","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":10695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"261804201","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nРабота с проф. стандартами\n\"\"\"\nfrom sqlalchemy import Column, DateTime, ForeignKey, Integer, String, text, Text, TIMESTAMP, Float, JSON, Date, Numeric, Table\nfrom sqlalchemy.orm import relationship, exc\nfrom sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta\nimport logging\n\nBase = declarative_base()\nmetadata = Base.metadata\n\n\nclass ProfStandard(Base):\n __tablename__ = 'prof_standard'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_standard_id_seq'::regclass)\"))\n code = Column(String(16), nullable=False, unique=True)\n name = Column(String(1024), nullable=False)\n date_accepted = Column(String(1024))\n tf_cnt = Column(Integer)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n\nclass ProfStandardOkso(Base):\n __tablename__ = 'prof_standard_okso'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_standard_okso_id_seq'::regclass)\"))\n id_prof_standard = Column(ForeignKey('data.prof_standard.id'), nullable=False)\n code_okso = Column(String(16), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_standard = relationship('ProfStandard')\n\n\nclass ProfStandardOkved(Base):\n __tablename__ = 'prof_standard_okved'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_standard_okved_id_seq'::regclass)\"))\n id_prof_standard = Column(ForeignKey('data.prof_standard.id'), nullable=False)\n code_okved = Column(String(16), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_standard = relationship('ProfStandard')\n\n\nclass ProfStandardOkz(Base):\n __tablename__ = 'prof_standard_okz'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_standard_okz_id_seq'::regclass)\"))\n id_prof_standard = Column(ForeignKey('data.prof_standard.id'), nullable=False)\n code_okz = Column(String(16), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_standard = relationship('ProfStandard')\n\n\nclass ProfTf(Base):\n __tablename__ = 'prof_tf'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_id_seq'::regclass)\"))\n id_prof_standard = Column(ForeignKey('data.prof_standard.id'), nullable=False)\n level = Column(String(16), nullable=False)\n num = Column(Integer, nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_standard = relationship('ProfStandard')\n\n\nclass ProfTfAccessReq(Base):\n __tablename__ = 'prof_tf_access_reqs'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_access_reqs_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n access_req = Column(String(1024), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass ProfTfEducReq(Base):\n __tablename__ = 'prof_tf_educ_reqs'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_educ_reqs_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n educ_req = Column(String(4000), nullable=False)\n remark = Column(String(4000))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass ProfTfOkdptr(Base):\n __tablename__ = 'prof_tf_okdptr'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_okdptr_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n code_okdptr = Column(String(32), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass ProfTfOkso(Base):\n __tablename__ = 'prof_tf_okso'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_okso_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n code_okso = Column(String(32), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass ProfTfProfession(Base):\n __tablename__ = 'prof_tf_professions'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_professions_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n prof = Column(String(1024), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass ProfTfStageReq(Base):\n __tablename__ = 'prof_tf_stage_reqs'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.prof_tf_stage_reqs_id_seq'::regclass)\"))\n id_prof_tf = Column(ForeignKey('data.prof_tf.id'), nullable=False)\n stage_req = Column(String(1024), nullable=False)\n remark = Column(String(1024))\n load_date = Column(DateTime, server_default=text(\"now()\"))\n\n prof_tf = relationship('ProfTf')\n\n\nclass UtlSPOGosFgos(Base):\n __tablename__ = 'utl_spo_gos_fgos'\n __table_args__ = {'schema': 'data'}\n\n id = Column(Integer, primary_key=True, server_default=text(\"nextval('data.utl_spo_gos_fgos_id_seq'::regclass)\"))\n code_fgos = Column(String(32), nullable=False)\n name_fgos = Column(String(1024), nullable=False)\n code_gos = Column(String(32), nullable=False)\n name_gos = Column(String(1024), nullable=False)\n\n\n\ndef get_ps_standart(sess, vcode):\n \"\"\"\n возврат объекта проф. стандарта, если такого нет, то возвращается новый\n :param sess: сеанс\n :param vcode: код стандарта\n :return: объект, либо полный, либо только с code\n \"\"\"\n try:\n res = sess.query(ProfStandard).filter(ProfStandard.code == vcode).one()\n except exc.NoResultFound:\n res = ProfStandard(code=vcode)\n return res\n\n\ndef get_ps_okz(sess, ps, vcode):\n \"\"\"\n возврат ОКЗ для проф. стандарта, если такого нет, то возвращается новый\n :param sess: сеанс\n :param ps: проф. стандарт\n :param vcode: код ОКЗ\n :return: объект, либо полный, либо только с code\n \"\"\"\n try:\n res = sess.query(ProfStandardOkz).filter(ProfStandardOkz.prof_standard == ps,\n ProfStandardOkz.code_okz == str(vcode)).one()\n except exc.NoResultFound:\n res = ProfStandardOkz(prof_standard=ps, code_okz=str(vcode))\n return res\n\n\ndef get_ps_okved(sess, ps, vcode):\n \"\"\"\n возврат ОКВЭД проф. стандарта, если такого нет, то возвращается новый\n :param sess: сеанс\n :param ps: проф. стандарт\n :param vcode: код ОКВЭД\n :return: объект, либо полный, либо только с code\n \"\"\"\n try:\n res = sess.query(ProfStandardOkved).filter(ProfStandardOkved.prof_standard == ps,\n ProfStandardOkved.code_okved == str(vcode)).one()\n except exc.NoResultFound:\n res = ProfStandardOkved(prof_standard=ps, code_okved=str(vcode))\n return res\n\n\ndef get_ps_okso(sess, ps, vcode):\n \"\"\"\n возврат ОКСО проф. стандарта, если такого нет, то возвращается новый\n :param sess: сеанс\n :param ps: проф. стандарт\n :param vcode: код ОКСО\n :return: объект, либо полный, либо только с code\n \"\"\"\n try:\n res = sess.query(ProfStandardOkso).filter(ProfStandardOkso.prof_standard == ps,\n ProfStandardOkso.code_okso == str(vcode)).one()\n except exc.NoResultFound:\n res = ProfStandardOkso(prof_standard=ps, code_okso=str(vcode))\n return res\n\n\ndef get_ps_tf(sess, ps, vnum, lev):\n \"\"\"\n возврат ОКСО проф. стандарта, если такого нет, то возвращается новый\n :param sess: сеанс\n :param ps: проф. стандарт\n :param vnum: номер\n :param lev: уровень\n :return: объект, либо полный, либо только с num\n \"\"\"\n tclass = ProfTf\n try:\n res = sess.query(tclass).filter(tclass.prof_standard == ps,\n tclass.num == vnum).one()\n except exc.NoResultFound:\n res = tclass(prof_standard=ps, num=vnum)\n res.level = lev\n return res\n\n\ndef get_ps_tf_prof(sess, ps_tf, vprof):\n \"\"\"\n\n :param sess:\n :param ps_tf:\n :param vprof:\n :return:\n \"\"\"\n tclass = ProfTfProfession\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.prof == vprof).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, prof=vprof)\n return res\n\n\ndef get_ps_tf_stage(sess, ps_tf, stage):\n \"\"\"\n\n :param sess:\n :param ps_tf:\n :param stage:\n :return:\n \"\"\"\n tclass = ProfTfStageReq\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.stage_req == stage).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, stage_req=stage)\n return res\n\n\ndef get_ps_tf_okso(sess, ps_tf, okso):\n \"\"\"\n\n :param sess:\n :param ps_tf:\n :param okso:\n :return:\n \"\"\"\n tclass = ProfTfOkso\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.code_okso == str(okso)).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, code_okso=str(okso))\n return res\n\n\ndef get_ps_educ_reqs(sess, ps_tf, educ):\n \"\"\"\n\n :param sess:\n :param ps_tf:\n :param educ:\n :return:\n \"\"\"\n tclass = ProfTfEducReq\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.educ_req == educ).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, educ_req=educ)\n return res\n\n\ndef get_ps_okdptr(sess, ps_tf, okdptr):\n \"\"\"\n\n :param sess:\n :param ps_tf:\n :param okdptr:\n :return:\n \"\"\"\n tclass = ProfTfOkdptr\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.code_okdptr == str(okdptr)).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, code_okdptr=str(okdptr))\n return res\n\n\ndef get_ps_access_reqs(sess, ps_tf, access):\n \"\"\"\n :param sess:\n :param ps_tf:\n :param access:\n :return:\n \"\"\"\n tclass = ProfTfAccessReq\n try:\n res = sess.query(tclass).filter(tclass.prof_tf == ps_tf,\n tclass.access_req == str(access)).one()\n except exc.NoResultFound:\n res = tclass(prof_tf=ps_tf, access_req=str(access))\n return res\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG, format='%(lineno)d %(asctime)s %(message)s')\n","sub_path":"entity/prof_standards.py","file_name":"prof_standards.py","file_ext":"py","file_size_in_byte":12061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"381149078","text":"import os\nimport time \nimport csv\n\ncols = ['t','dmv_confirmed','dmv_deaths','dmv_recovered','us_confirmed','us_deaths','us_recovered']\n\nrootdir = 'csse_covid_19_data/csse_covid_19_daily_reports'\noutfilename = f'report_{int(time.time())}.csv'\n\nwith open(outfilename, 'a') as outfile:\n outfile.write(','.join(str(x) for x in cols) + '\\n')\n writer = csv.writer(outfile)\n for subdir, dirs, filenames in os.walk(rootdir):\n for filename in sorted(filenames):\n if filename.endswith('csv'):\n with open(f'{rootdir}/{filename}') as file:\n stats = dict(zip(cols, [0] * len(cols)))\n stats['t'] = filename.split('.')[0];\n file.readline(); # chomp first line\n source = csv.reader(file)\n for source_row in source:\n country = source_row[1];\n if country != 'US':\n continue\n state = source_row[0];\n dmv = (state == 'Virginia' or state == 'Maryland' or state == 'District of Columbia')\n confirmed = 0\n deaths = 0\n recovered = 0\n\n try:\n confirmed = int(source_row[3]);\n deaths = int(source_row[4]);\n recovered = int(source_row[5]);\n except: \n pass\n \n if dmv:\n stats['dmv_confirmed'] += confirmed\n stats['dmv_deaths'] += deaths\n stats['dmv_recovered'] += recovered\n\n stats['us_confirmed'] += confirmed\n stats['us_deaths'] += deaths\n stats['us_recovered'] += recovered\n\n writer.writerow(str(stats[col]) for col in cols);\n","sub_path":"generate_report.py","file_name":"generate_report.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"133958106","text":"from vpython import *\nfrom math import sin, cos, radians\nimport argparse\nimport numpy as np\nimport pprint as pp\nimport matplotlib.pyplot as plt\n\n\n\n\ndef set_scene(data):\n \"\"\"\n Set Vpython Scene\n param: data = dictionary with all data\n \"\"\"\n scene.title = \"Assignment 5: Projectile motion\"\n scene.width = 800\n scene.heigth = 600\n scene.caption = \"\"\"Right button drag or Ctrl-drag to rotate \"camera\" to view scene.\n To zoom, drag with middle button or Alt/Option depressed, or use scroll wheel.\n On a two-button mouse, middle is left + right.\n Touch screen: pinch/extend to zoom, swipe or two-finger rotate.\"\"\"\n scene.forward = vector(0, -.3, -1)\n scene.x = -1\n # Set background: floor, table, etc\n\n\ndef motion_no_drag(data):\n \"\"\"\n Create animation for projectile motion with no dragging force\n param: dictionary with all data\n \"\"\"\n ball_nd = sphere(pos=vector(0, data['init_height'], 0),\n radius=1, color=color.cyan, make_trail=True)\n \n # # Follow the movement of the ball\n scene.camera.follow(ball_nd)\n\n # Create lists of x and y values of motion\n index = 1 \n y_values = [data['init_height']] #list of all y positions\n y_velocities = [data['init_y_vel']] # list of y velocities\n x_values = [0] #list of all x positions\n while y_values[index-1] > 0 or index == 1:\n new_x = x_values[index - 1] + data['init_x_vel'] * data['deltat'] # find next x position\n x_values.append(new_x) #add generated x position to list\n \n new_y_vel = y_velocities[index - 1] + data['gravity'] * data['deltat'] # find new y velocity\n y_velocities.append(new_y_vel)\n new_y = y_values[index - 1] + new_y_vel * data['deltat'] #fine new y position\n y_values.append(new_y) #add new position to the list\n index += 1\n\n #create scenery elements (ground and mountains)\n ground = box(pos=vector(x_values[-1]/2,-1,-x_values[-1]/4 + 10), color=color.green, size=vector(x_values[-1] + 20, 1, x_values[-1]/2))\n mount1 = cone(pos=vector(3 * x_values[-1] / 8 - 20,-1,-3 * x_values[-1] / 8), axis=vector(0, max(y_values), 0), radius=(3 * x_values[-1] / 8), color=color.white)\n mount2 = cone(pos=vector(x_values[-1] * .825 - 20,-1,-3 * x_values[-1] / 8), axis=vector(0, max(y_values) * 2, 0), radius=(3 * x_values[-1] / 8), color=color.white)\n #Animate\n\n #loop through lists to change the position of the ball\n pos_index = 0\n while pos_index < len(y_values):\n rate(500)\n position = vector(x_values[pos_index], y_values[pos_index], 0)\n ball_nd.pos = position\n pos_index += 1\n \n #add positions to the data dictionary to be graphed\n data['x_no_drag'] = x_values\n data['y_no_drag'] = y_values\n\n\n\ndef motion_drag(data):\n \"\"\"\n Create animation for projectile motion with dragging force\n param: data = dictionary with all data\n \"\"\"\n ball_nd = sphere(pos=vector(0, data['init_height'], 0),\n radius=1, color=color.magenta, make_trail=True)\n \n # # Follow the movement of the ball\n scene.camera.follow(ball_nd)\n # Create lists of x and y values of motion\n index = 1\n x_vel = data['init_x_vel']\n y_values = [data['init_height']]\n y_vel = data['init_y_vel']\n x_values = [0]\n while y_values[index-1] > 0 or index == 1:\n # new_x = x_values[index - 1] + data['init_x_vel'] * data['deltat'] # find next x position\n x_vel = x_vel + data['x_drag_accel'] * data['deltat']\n # data['x_drag_accel'] = data['x_drag_accel'] - x_vel * data['beta'] #update acceleration based on new velocity\n new_x = x_values[index - 1] + x_vel * data['deltat']\n x_values.append(new_x) #add generated x position to list\n \n y_vel = y_vel + data['y_drag_accel'] * data['deltat'] # find new y velocity\n new_y = y_values[index - 1] + y_vel * data['deltat']\n y_values.append(new_y)\n\n index += 1\n #Animate\n pos_index = 0\n while pos_index < len(y_values):\n rate(500)\n position = vector(x_values[pos_index], y_values[pos_index], 0)\n ball_nd.pos = position\n pos_index += 1\n \n #add lists of positions to the data dictionary to be graphed\n data['x_drag'] = x_values\n data['y_drag'] = y_values\n \n \ndef plot_data(data):\n \"\"\"\n Use lists of positions with and without drag\n to create a graph\n param: data = dictionary with all data\n \"\"\"\n # Create canvas with two plots on one graph\n plt.figure()\n plt.title(\"Position with and without drag force\")\n plt.plot(data[\"x_no_drag\"], data[\"y_no_drag\"], \"g-\", label=\"Position without Drag\") #plot x vs y position without drag\n plt.ylabel(\"Y Position (m)\")\n plt.xlabel(\"X Position (m)\")\n\n plt.plot(data[\"x_drag\"], data[\"y_drag\"], \"b-\", label=\"Position with Drag\") #plot x vs y position with drag\n plt.legend()\n plt.show() # display plot\n \n\n\ndef main():\n \"\"\"\n Main method\n \"\"\"\n # 1) Parse the arguments\n parser = argparse.ArgumentParser(description=\"Projectile Motion\")\n parser.add_argument(\"--velocity\", \"-v\", action=\"store\", help=\"velocity in m/s\", dest=\"velocity\", type=float, required=\"true\")\n parser.add_argument(\"--angle\", \"-a\", action=\"store\", help=\"angle in degrees\", dest=\"angle\", type=float, required=\"true\")\n parser.add_argument(\"--height\", action=\"store\", help=\"height in meters\", dest=\"height\", type=float, default=1.2)\n\n args = parser.parse_args()\n # Set Variables\n data = {} # empty dictionary for all data and variables\n data['init_height'] = args.height # y-axis \n data['init_velocity'] = args.velocity # m/s\n data['theta'] = args.angle # degrees\n\n rad_angle = radians(args.angle) # angle in radians\n data['init_x_vel'] = cos(rad_angle) * args.velocity # velocity in the x-direction\n data['init_y_vel'] = sin(rad_angle) * args.velocity # velocity in the y-direction\n\n # Constants\n data['rho'] = 1.225 # kg/m^3, density\n data['Cd'] = 0.5 # coefficient friction\n data['deltat'] = 0.005\n data['gravity'] = -9.8 # m/s^2\n\n data['ball_mass'] = 0.145 # kg\n data['ball_radius'] = 0.075 # meters\n data['ball_area'] = pi * data['ball_radius']**2\n data['alpha'] = data['rho'] * data['Cd'] * data['ball_area'] / 2.0\n data['beta'] = data['alpha'] / data['ball_mass']\n\n #acceleration when the ball experiences drag\n data['x_drag_accel'] = - data['beta'] * data['init_x_vel']\n data['y_drag_accel'] = data['gravity'] - data['beta'] * data['init_y_vel'] \n # Set Scene\n set_scene(data)\n # 2) No Drag Animation\n motion_no_drag(data)\n # 3) Drag Animation\n motion_drag(data)\n # 4) Plot Information: extra credit\n plot_data(data)\n\n\nif __name__ == \"__main__\":\n main()\n exit(0)\n","sub_path":"lab5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":6831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"27652530","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\nimport six\n\nfrom requests_mock import adapter\nfrom requests_mock import response\nfrom requests_mock.tests import base\n\n\nclass ResponseTests(base.TestCase):\n\n def setUp(self):\n super(ResponseTests, self).setUp()\n self.method = 'GET'\n self.url = 'http://test.url/path'\n self.request = adapter._RequestObjectProxy._create(self.method,\n self.url,\n {})\n\n def create_response(self, **kwargs):\n return response.create_response(self.request, **kwargs)\n\n def test_create_response_body_args(self):\n self.assertRaises(RuntimeError,\n self.create_response,\n raw='abc',\n body='abc')\n\n self.assertRaises(RuntimeError,\n self.create_response,\n text='abc',\n json={'a': 1})\n\n def test_content_type(self):\n self.assertRaises(TypeError, self.create_response, text=55)\n self.assertRaises(TypeError, self.create_response, text={'a': 1})\n\n def test_text_type(self):\n self.assertRaises(TypeError, self.create_response, content=six.u('t'))\n self.assertRaises(TypeError, self.create_response, content={'a': 1})\n\n def test_json_body(self):\n data = {'a': 1}\n resp = self.create_response(json=data)\n\n self.assertEqual('{\"a\": 1}', resp.text)\n self.assertIsInstance(resp.text, six.string_types)\n self.assertIsInstance(resp.content, six.binary_type)\n self.assertEqual(data, resp.json())\n\n def test_body_body(self):\n value = 'data'\n body = six.BytesIO(six.b(value))\n resp = self.create_response(body=body)\n\n self.assertEqual(value, resp.text)\n self.assertIsInstance(resp.text, six.string_types)\n self.assertIsInstance(resp.content, six.binary_type)\n","sub_path":"requests_mock/tests/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"486520232","text":"def CalcMes():\r\n soma = \"0\"\r\n contas = []\r\n nomec = []\r\n cont = 0\r\n while (soma != \"1\"):\r\n nomec.append(input(\"Crie um rótulo para a conta: \"))\r\n contas.append(float(input(\"Insira o valor: \")))\r\n cont = cont + 1\r\n soma = input(\"Para parar, digite 1!\")\r\n\r\n for i in range(cont):\r\n print(nomec[i],\":\",contas[i])\r\n result = sum(contas)\r\n print(\"O somatório das contas é igual a:\",result)\r\n \r\nCalcMes()\r\n\r\n","sub_path":"CalcMes.py","file_name":"CalcMes.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"475306494","text":"# This file is python code\n\nimport os\n\nDecider('timestamp-match')\n\ncommon_files = Glob(\"src/*.cpp\") + Glob(\"src/graphics/*.cpp\") + Glob(\"src/graphics/frustum/*.cpp\") + Glob(\"src/net/*.cpp\");\nserver_files = Glob(\"src/dedicated/*.cpp\")\nclient_files = Glob(\"src/main/*.cpp\")\neditor_files = Glob(\"src/editor/*.cpp\")\nloader3ds_files = Glob(\"src/loader_3ds/*.cpp\")\n\ninclude_dirs = ['src', 'src/graphics'] + os.environ['C_INCLUDE_PATH'].split(':')\n#libs = ['boost_system-gcc41-mt-1_39']\nlibs = ['SDL', 'SDL_mixer', 'GL', 'GLU', 'png', 'GLEW']\nlib_dirs = [os.environ['LD_LIBRARY_PATH'].split(':'), './lib/']\nenv = Environment(CPPPATH = include_dirs, LIBS = libs, LIBPATH = lib_dirs)\nenv.ParseConfig('pkg-config --cflags --libs sdl')\n\ncommon_flags = '-Wall -Wextra -Werror -std=c++0x -pedantic'\n\n\n\nopt = env.Clone(CCFLAGS = common_flags + ' -O3', LINKFLAGS = '-O3')\noptcommon = opt.Object(common_files)\noptclient = opt.Program('bin/client', optcommon + opt.Object(client_files))\noptserver = opt.Program('bin/server', optcommon + opt.Object(server_files))\nopteditor = opt.Program('bin/editor', optcommon + opt.Object(editor_files))\noptloader_3ds = opt.Program('bin/loader_3ds', opt.Object(loader3ds_files))\nopt.Alias('client', 'bin/client')\nopt.Alias('server', 'bin/server')\nopt.Alias('editor', 'bin/editor')\nopt.Alias('loader3ds', 'bin/loader_3ds')\n\ndbg = env.Clone(CCFLAGS = common_flags + ' -g -O0', LINKFLAGS = '-g')\ndbgcommon = dbg.Object(common_files, OBJPREFIX = 'debug-')\ndebugclient = dbg.Program('bin/debug-client', dbgcommon + dbg.Object(client_files, OBJPREFIX = 'debug-'))\ndebugserver = dbg.Program('bin/debug-server', dbgcommon + dbg.Object(server_files, OBJPREFIX = 'debug-'))\ndebugeditor = dbg.Program('bin/debug-editor', dbgcommon + dbg.Object(editor_files, OBJPREFIX = 'debug-'))\ndbg.Alias('debug', 'bin/debug-client')\ndbg.Alias('debug', 'bin/debug-server')\ndbg.Alias('debug', 'bin/debug-editor')\n\nprof = env.Clone(CCFLAGS = common_flags + ' -pg -O3 -D NDEBUG', LINKFLAGS = '-pg -O3')\nprofcommon = prof.Object(common_files, OBJPREFIX = 'profile-')\nprofileclient = prof.Program('bin/profile-client', profcommon + prof.Object(client_files, OBJPREFIX = 'profile-'))\nprofileserver = prof.Program('bin/profile-server', profcommon + prof.Object(server_files, OBJPREFIX = 'profile-'))\nprofileeditor = prof.Program('bin/profile-editor', profcommon + prof.Object(editor_files, OBJPREFIX = 'profile-'))\nprof.Alias('profile', 'bin/profile-client')\nprof.Alias('profile', 'bin/profile-server')\nprof.Alias('profile', 'bin/profile-editor')\n\n\nDefault(optclient, optserver, opteditor)\n\n\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"330247770","text":"from urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup\nfrom discord.ext import commands\nimport json\nimport time\nimport discord\nfrom discord.ext.commands import Bot\nimport logging\n\n\nclass senate:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def senatecount(self):\n req = Request('http://oppressive.games/power/bill.php?bill=', headers={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) '\n 'Version/7.0.3 Safari/7046A194A'})\n html = str(urlopen(req).read())\n s = BeautifulSoup(html, \"lxml\")\n second_req = Request('http://oppressive.games/power/senate.php', headers={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) '\n 'Version/7.0.3 Safari/7046A194A'})\n senator_html = str(urlopen(second_req).read())\n s2 = BeautifulSoup(senator_html, \"lxml\").find_all('table')[1]\n senator_data = [[cell.text for cell in row(\"td\")]\n for row in s2(\"tr\")]\n senator_data = [cell for cell in senator_data if 'Democratic Party' in ''.count(cell)]\n # senator_data = [cell for cell in senator_data if 'Democratic Party' in cell]\n print(senator_data)\n await self.bot.say(str(senator_data))\n \n \ndef setup(bot):\n bot.add_cog(senate(bot))\n","sub_path":"senate.py","file_name":"senate.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"96343238","text":"from .captchaRecognizeMain import CAPTCHA_SET, captchaRecognize\nfrom ..utils import Post\nimport os\nimport random\nimport requests\n\n\n__all__ = [\"createTestSet\", \"cropImage\", \"CAPTCHA_SET_PATH\",\n \"CURRENT_DIR\", \"getRequsetCaptcha\"]\n\n\nCURRENT_DIR = os.path.dirname(__file__)\nCAPTCHA_SET_PATH = CURRENT_DIR + \"/captcha_set\"\n\n\ndef getRequsetCaptcha(headers, telephone_number, dir_path=None, captcha_name=\"captcha\"):\n ''' 获取验证码 '''\n captcha_params = {\n \"captcha_str\": telephone_number,\n }\n\n captcha_url = \"https://h5.ele.me/restapi/eus/v3/captchas\"\n\n captcha_json = Post(captcha_url, headers=headers, jsons=captcha_params).json\n captcha_hash = captcha_json[\"captcha_hash\"]\n b64data = captcha_json['captcha_image']\n filepath, extension = Post.base64decode(b64data, captcha_name, dir_path)\n return filepath, extension, captcha_hash\n\n\ndef cropImage(binary_object, letters, extension, dir_path=\".\", captcha_name=\"captcha\"):\n \"\"\" 分割图片,使用md5哈希命名 \"\"\"\n image_objects = []\n count = 0\n for letter in letters:\n # 四元组,左、上、右、下\n temp_object = binary_object.crop(\n (letter[0], 0, letter[1], binary_object.size[1]))\n image_path = \"%s/%s.%s\" % (dir_path,\n captcha_name + f\"___{count+1}\", extension)\n temp_object.convert(\"RGB\").save(image_path)\n image_objects.append(temp_object)\n count += 1\n\n return image_objects\n\n\ndef splitCaptcha(captcha_name=\"captcha\"):\n ''' 请求并分割验证码, 将结果放入captcha_set目录,需要人工筛选放入对应的子目录 '''\n headers = {\n \"referer\": \"https://h5.ele.me/login/\"\n }\n telephone_numbers = [x for x in range(10)]\n telephone_heads = [\"1581\", \"1861\", \"1355\", \"1760\"]\n\n # 构造电话号码\n telephone_number = random.choice(telephone_heads)\n for i in range(7):\n telephone_number += str(random.choice(telephone_numbers))\n\n # 请求验证码\n filepath, extension, captcha_hash = getRequsetCaptcha(headers, telephone_number,\n dir_path=CAPTCHA_SET_PATH, captcha_name=captcha_name)\n\n # 扫描验证码\n binary_object, letters, extension = captchaRecognize(\n filepath, extension, captcha_name=captcha_name)\n\n # 分割验证码字符\n cropImage(binary_object, letters, extension,\n CAPTCHA_SET_PATH, captcha_name=captcha_name)\n if len(letters) < 4:\n raise\n\n return captcha_hash\n\n\ndef createTestSet(captcha_set_path=None, captcha_set=None, captcha_numbers=1):\n ''' 创建训练数据集,目录为captcha_set_path, captcha_set为验证码可能包含的文字或者字母等的list '''\n global CAPTCHA_SET_PATH\n global CAPTCHA_SET\n\n if captcha_set_path:\n captcha_set_path = captcha_set_path\n else:\n captcha_set_path = CAPTCHA_SET_PATH\n\n if captcha_set:\n captcha_set = captcha_set\n else:\n captcha_set = CAPTCHA_SET\n\n print(captcha_set_path)\n # 创建captcha_set目录及其子目录\n if os.system(f\"mkdir '{captcha_set_path}'\"):\n for capt in captcha_set:\n dir_path = captcha_set_path + '/' + capt\n os.system(f\"mkdir '{dir_path}'\")\n\n # 请求验证码并分割,将结果放入captcha_set目录,人为放入其子目录\n # 请求100次\n for i in range(captcha_numbers):\n # 请求1次\n splitCaptcha(f\"captcha__{str(i+1)}\")\n","sub_path":"crawlerUtils/captcha/captchaTestSetCreate.py","file_name":"captchaTestSetCreate.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"14574768","text":"from phidl import LayerSet\nimport numpy as np\n\n#%%\ndef vt_layers():\n vt_lyrs = LayerSet()\n \n color_mat = gds_colors()\n \n #gds layer name, layer number, data type, description, color from color list, dither\n layer_data = [['m1',40,0,'wiring for stf and r1',32,'I3'],\n ['m1e',40,1,'wiring for stf and r1 endpoint',32,'I2'],\n ['m1f',40,2,'wiring for stf and r1 fill',32,'I1'],\n ['m1l',40,3,'wiring for stf and r1 label',32,'I1'],\n ['m1p',40,4,'wiring for stf and r1 pad',32,'I4'],\n ['stf',10,0,'superconducting thin film for spds and inductors',3,'I5'],\n ['stfe',10,1,'superconducting thin film endpoint',3,'I1'],\n ['stff',10,2,'superconducting thin film fill',3,'I1'],\n ['stfp',10,3,'superconducting thin film pad',3,'I3'],\n ['r1',30,0,'spd and loop resistor',18,'I5'],\n ['r1f',30,2,'spd and loop resistor fill',18,'I1'],\n ['r1p',30,3,'spd and loop resistor pad',18,'I3'],\n ['v1',50,0,'via from m1 to m2',11,'I5'],\n ['v1e',50,1,'v1 endpoint',11,'I1'], \n ['m2',41,0,'ground plane',32,'I1'],\n ['m2e',41,1,'m2 endpoint',32,'I1'],\n ['m2l',41,3,'m2 label',32,'I0'],\n ['m2i',41,4,'m2 invert',32,'I1'],\n ['m2o',41,5,'m2 offset',32,'I2'],#postprocessing will trace around this layer to allow vias\n ['m2m',41,6,'m2 moats',32,'I2'], \n ['v2',51,0,'via from m2 to jj1, jj2, or m1',11,'I6'],\n ['v2e',51,1,'v2 endpoint',11,'I1'],\n ['jj1',21,0,'jj bottom contact / m3',14,'I4'],\n ['jj1e',21,1,'jj bottom contact endpoint',14,'I2'],\n ['jj1f',21,2,'jj bottom contact fill',14,'I1'], \n ['jj2',22,0,'jj top contact',13,'I5'],\n ['jj2e',22,1,'jj top contact endpoint',13,'I2'],\n ['jj2f',22,2,'jj top contact fill',13,'I1'],\n ['v3',52,0,'via to jj top and bottom contacts',11,'I8'],\n ['v3e',52,1,'v3 endpoint',11,'I5'],\n ['m3',42,0,'jj contact metal',34,'I9'],\n ['m3e',42,1,'jj contact metal endpoint',34,'I1'],\n ['m3f',42,2,'jj contact metal fill',34,'I1'],\n ['m3l',42,3,'jj contact metal label',34,'I1'],\n ['m3p',42,4,'jj contact metal pad',34,'I4'],\n ['m3cs',43,6,'m3 label',34,'I0'],\n ['r2',31,0,'jj shunt resistor',8,'I9'],\n ['r2f',31,2,'jj shunt resistor fill',8,'I1'],\n ['r2p',31,3,'jj shunt resistor pad',8,'I3'],\n ['v4',54,0,'via to r2 / pad opening',16,'I1'],\n ['v4e',54,1,'v4 endpoint',16,'I2'], \n ['pkg',60,0,'SU8 packaging layer',1,'I1'], \n ['pkfc',60,1,'fiber core dummy layer',21,'I1'],\n ['ipm1',19,0,'inductor port m1',11,'I1'],\n ['ipj1',19,0,'inductor port jj1',11,'I1'],\n ['ipm3',19,0,'inductor port m3',11,'I1'],\n ['ipl',19,0,'inductor port labels',11,'I1'],\n ['pl',95,0,'pad locations',47,'I1'],\n ['ce',96,0,'chip edge',48,'I1'],\n ['dp',99,10,'data prep dummy',8,'I1'],\n ]\n \n# ['v4',53,0,'via from m4 to m3',11,'I9'],\n# ['v4e',53,1,'via from m4 to m3 endpoint',11,'I1'], \n# ['m4',43,0,'upper metal wiring',34,'I9'],\n# ['m4e',43,1,'m4 endpoint',34,'I2'],\n# ['m4f',43,2,'m4 fill',34,'I1'],\n# ['m4l',43,3,'m4 label',34,'I0'],\n# ['m4cs',43,6,'m4 label',34,'I0'],\n# ['r3',32,0,'resistor / pad cap',19,'I9'],\n# ['r3f',32,1,'resistor / pad cap fill',16,'I1'],\n# ['v5',54,0,'via to r3 / pad opening',16,'I1'],\n# ['v5e',54,1,'v4 endpoint',11,'I2'],\n \n \n num_layers = len(layer_data) \n for ii in range(num_layers): \n color_number = layer_data[ii][4]\n color_hex = '#{0:02x}{1:02x}{2:02x}'.format(clamp(color_mat[:,color_number-1][0]*256), clamp(color_mat[:,color_number-1][1]*256), clamp(color_mat[:,color_number-1][2]*256))\n vt_lyrs.add_layer(name = layer_data[ii][0], gds_layer = layer_data[ii][1], gds_datatype = layer_data[ii][2],description = layer_data[ii][3], color = color_hex, inverted = False,alpha = 0.6, dither = layer_data[ii][5])\n \n return vt_lyrs, layer_data\n\n#%%\ndef vt_layers_post():\n vt_lyrs = LayerSet()\n \n color_mat = gds_colors()\n \n #gds layer name, layer number, data type, description, color from color list, dither\n layer_data = [['m1',40,0,'wiring for stf and r1',32,'I9'],\n ['stf',10,0,'superconducting thin film for spds and inductors',3,'I5'],\n ['r1',30,0,'spd and loop resistor',18,'I5'],\n ['v1',50,0,'via from m1 to m2',11,'I5'], \n ['m2',41,0,'ground plane',32,'I1'], \n ['v2',51,0,'via from m2 to jj1, jj2, or m1',11,'I6'],\n ['jj1',21,0,'jj bottom contact / m3',14,'I4'], \n ['jj2',22,0,'jj top contact',13,'I5'],\n ['v3',52,0,'via to jj top and bottom contacts',11,'I8'],\n ['m3',42,0,'jj contact metal',34,'I9'],\n ['r2',31,0,'jj shunt resistor',8,'I9'],\n ['v4',54,0,'via to r2 / pad opening',16,'I1'], \n ['pkg',60,0,'SU8 packaging layer',1,'I1'], \n ['ce',96,0,'chip edge',48,'I1'],\n ] \n \n num_layers = len(layer_data) \n for ii in range(num_layers): \n color_number = layer_data[ii][4]\n color_hex = '#{0:02x}{1:02x}{2:02x}'.format(clamp(color_mat[:,color_number-1][0]*256), clamp(color_mat[:,color_number-1][1]*256), clamp(color_mat[:,color_number-1][2]*256))\n vt_lyrs.add_layer(name = layer_data[ii][0], gds_layer = layer_data[ii][1], gds_datatype = layer_data[ii][2],description = layer_data[ii][3], color = color_hex, inverted = False,alpha = 0.6, dither = layer_data[ii][5])\n \n return vt_lyrs, layer_data\n\n#%%\ndef write_lyp(lyrs,layer_data,lyp_file_name):\n\n num_layers = len(lyrs._layers)\n color_mat = gds_colors()\n \n# gds_layers = np.zeros([num_layers,1])\n# for ii in range(num_layers):\n# gds_layers[ii] = layer_data[ii][1]\n# \n# index_array,gds_layers_sorted = np.argsort(gds_layers)\n \n A = '\\n'\n \n for kk in range(num_layers):\n \n ii = kk#index_array[kk]\n color_number = layer_data[ii][4]\n color_hex = '#{0:02x}{1:02x}{2:02x}'.format(clamp(color_mat[:,color_number-1][0]*256), clamp(color_mat[:,color_number-1][1]*256), clamp(color_mat[:,color_number-1][2]*256))\n A = A + '\\n'+color_hex+'\\n'\n A = A + ''+color_hex+'\\n'\n A = A + '0\\n'\n A = A + '0\\n'\n A = A + ''+layer_data[ii][5]+'\\n'\n A = A + 'true\\n'\n A = A + 'false\\n'\n A = A + '1\\n'\n A = A + 'false\\n'\n A = A + '0\\n'\n A = A + ''+str(layer_data[ii][1])+'/'+str(layer_data[ii][2])+': '+str(layer_data[ii][0])+'; '+str(layer_data[ii][3])+'\\n'\n A = A + ''+str(layer_data[ii][1])+'/'+str(layer_data[ii][2])+'@1'+'\\n'\n A = A + '\\n'\n \n A = A + '' \n \n print(A,file=open(lyp_file_name+'.lyp','w'))\n# with open('vt.lyp','w') as text_file:\n# text_file.write(A)\n \n return\n\n#%%\ndef gds_colors():\n \n ## define colors\n #blues lightest to darkest\n blueVec1 = np.array([145,184,219]); blue1 = blueVec1/256;\n blueVec2 = np.array([96,161,219]); blue2 = blueVec2/256;\n blueVec3 = np.array([24,90,149]); blue3 = blueVec3/256;\n blueVec4 = np.array([44,73,100]); blue4 = blueVec4/256;\n blueVec5 = np.array([4,44,80]); blue5 = blueVec5/256;\n #reds lightest to darkest\n redVec1 = np.array([246,177,156]); red1=redVec1/256;\n redVec2 = np.array([246,131,98]); red2 = redVec2/256;\n redVec3 = np.array([230,69,23]); red3 = redVec3/256;\n redVec4 = np.array([154,82,61]); red4 = redVec4/256;\n redVec5 = np.array([123,31,4]); red5 = redVec5/256;\n #greens lightest to darkest\n greenVec1 = np.array([142,223,180]); green1 = greenVec1/256;\n greenVec2 = np.array([89,223,151]); green2 = greenVec2/256;\n greenVec3 = np.array([16,162,84]); green3 = greenVec3/256;\n greenVec4 = np.array([43,109,74]); green4 = greenVec4/256;\n greenVec5 = np.array([3,87,42]); green5 = greenVec5/256;\n #yellows lightest to darkest\n yellowVec1 = np.array([246,204,156]); yellow1 = yellowVec1/256;\n yellowVec2 = np.array([246,185,98]); yellow2 = yellowVec2/256;\n yellowVec3 = np.array([230,144,23]); yellow3 = yellowVec3/256;\n yellowVec4 = np.array([154,115,61]); yellow4 = yellowVec4/256;\n yellowVec5 = np.array([123,74,4]); yellow5 = yellowVec5/256;\n \n #blue grays\n gBlueVec1 = np.array([197,199,202]); gBlue1 = gBlueVec1/256;\n gBlueVec2 = np.array([195,198,202]); gBlue2 = gBlueVec2/256;\n gBlueVec3 = np.array([142,145,149]); gBlue3 = gBlueVec3/256;\n gBlueVec4 = np.array([108,110,111]); gBlue4 = gBlueVec4/256;\n gBlueVec5 = np.array([46,73,97]); gBlue5 = gBlueVec5/256;\n #red grays\n gRedVec1 = np.array([242,237,236]); gRed1 = gRedVec1/256;\n gRedVec2 = np.array([242,235,233]); gRed2 = gRedVec2/256;\n gRedVec3 = np.array([230,231,218]); gRed3 = gRedVec3/256;\n gRedVec4 = np.array([172,167,166]); gRed4 = gRedVec4/256;\n gRedVec5 = np.array([149,88,71]); gRed5 = gRedVec5/256;\n #green grays\n gGreenVec1 = np.array([203,209,206]); gGreen1 = gGreenVec1/256;\n gGreenVec2 = np.array([201,209,204]); gGreen2 = gGreenVec2/256;\n gGreenVec3 = np.array([154,162,158]); gGreen3 = gGreenVec3/256;\n gGreenVec4 = np.array([117,122,119]); gGreen4 = gGreenVec4/256;\n gGreenVec5 = np.array([50,105,76]); gGreen5 = gGreenVec5/256;\n #yellow grays\n gYellowVec1 = np.array([242,240,236]); gYellow1 = gYellowVec1/256;\n gYellowVec2 = np.array([242,239,233]); gYellow2 = gYellowVec2/256;\n gYellowVec3 = np.array([230,225,218]); gYellow3 = gYellowVec3/256;\n gYellowVec4 = np.array([172,169,166]); gYellow4 = gYellowVec4/256;\n gYellowVec5 =np.array( [149,117,71]); gYellow5 = gYellowVec5/256;\n \n #pure grays (white to black)\n gVec1 = np.array([256,256,256]); g1 = gVec1/256;\n gVec2 = np.array([242,242,242]); g2 = gVec2/256;\n gVec3 = np.array([230,230,230]); g3 = gVec3/256;\n gVec4 = np.array([204,204,204]); g4 = gVec4/256;\n gVec5 = np.array([179,179,179]); g5 = gVec5/256;\n gVec6 = np.array([153,153,153]); g6 = gVec6/256;\n gVec7 = np.array([128,128,128]); g7 = gVec7/256;\n gVec8 = np.array([102,102,102]); g8 = gVec8/256;\n gVec9 = np.array([77,77,77]); g9 = gVec9/256;\n gVec10 = np.array([51,51,51]); g10 = gVec10/256;\n gVec11 = np.array([26,26,26]); g11 = gVec11/256;\n gVec12 = np.array([0,0,0]); g12 = gVec12/256;\n \n color_mat = np.column_stack((blue1,blue2,blue3,blue4,blue5,red1,red2,red3,red4,red5,green1,green2,green3,green4,green5,yellow1,yellow2,yellow3,yellow4,yellow5,\n gBlue1,gBlue2,gBlue3,gBlue4,gBlue5,gRed1,gRed2,gRed3,gRed4,gRed5,gGreen1,gGreen2,gGreen3,gGreen4,gGreen5,gYellow1,gYellow2,gYellow3,gYellow4,gYellow5,\n g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12))\n \n return color_mat\n\n#%%\ndef clamp(x): return int(max(0, min(x, 255)))","sub_path":"gds_backups/spd_res__gds_made_20200201/vt_util.py","file_name":"vt_util.py","file_ext":"py","file_size_in_byte":12143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"480993042","text":"import os\nimport os.path as osp\nimport numpy as np\n# `pip install easydict` if you don't have it\nfrom easydict import EasyDict as edict\n\n__C = edict()\n# Consumers can get config by:\n# from wsl.config import cfg_wsl\ncfg_wsl = __C\n\n#\n# Training options\n#\n\n__C.TRAIN = edict()\n\n# Scales to use during training (can list multiple scales)\n# Each scale is the pixel size of an image's shortest side\n__C.TRAIN.SCALES = (600, )\n\n# Max pixel size of the longest side of a scaled input image\n__C.TRAIN.MAX_SIZE = 1000\n\n# Images to use per minibatch\n# If image per Batch lagerer than 64, blob will exceed INT_MAX.\n__C.TRAIN.IMS_PER_BATCH = 2\n\n# TODO(YH): BATCH_SIZE is determined by IM_PER_BATCH and iter_size\n# Minibatch size (number of regions of interest [ROIs])\n# __C.TRAIN.BATCH_SIZE = 128\n\n__C.TRAIN.ROIS_PER_IM = 10000\n\n# Use horizontally-flipped images during training?\n__C.TRAIN.USE_FLIPPED = True\n\n__C.TRAIN.USE_DISTORTION = True\n__C.TRAIN.SATURATION = 1.5\n__C.TRAIN.EXPOSURE = 1.5\n\n__C.TRAIN.USE_CROP = False\n__C.TRAIN.CROP = 0.9\n\n__C.TRAIN.ROI_AU = False\n__C.TRAIN.ROI_AU_STEP = 1\n\n__C.TRAIN.CPG_CACHE = False\n__C.TRAIN.CPG_CACHE_PATH = 'data/cpg_cache/'\n\n# Overlap required between a ROI and ground-truth box in order for that ROI to\n# be used as a bounding-box regression training example\n__C.TRAIN.BBOX_THRESH = 0.5\n\n# Iterations between snapshots\n__C.TRAIN.SNAPSHOT_ITERS = 10000\n\n# solver.prototxt specifies the snapshot path prefix, this adds an optional\n# infix to yield the path: [_]_iters_XYZ.caffemodel\n__C.TRAIN.SNAPSHOT_INFIX = ''\n\n# Use a prefetch thread in roi_data_layer.layer\n# So far I haven't found this useful; likely more engineering work is required\n__C.TRAIN.USE_PREFETCH = False\n\n# Train using these proposals\n__C.TRAIN.PROPOSAL_METHOD = 'selective_search'\n\n# Make minibatches from images that have similar aspect ratios (i.e. both\n# tall and thin or both short and wide) in order to avoid wasting computation\n# on zero-padding.\n__C.TRAIN.ASPECT_GROUPING = True\n\n__C.TRAIN.PASS_IM = 0\n\n__C.TRAIN.SHUFFLE = True\n\n__C.TRAIN.GAN_STEP = 0.0\n__C.TRAIN.GAN_imdb_name = ''\n\n\n#\n# Testing options\n#\n\n__C.TEST = edict()\n\n# Scales to use during testing (can list multiple scales)\n# Each scale is the pixel size of an image's shortest side\n__C.TEST.SCALES = (600, )\n\n# Max pixel size of the longest side of a scaled input image\n__C.TEST.MAX_SIZE = 1000\n\n# Overlap threshold used for non-maximum suppression (suppress boxes with\n# IoU >= this threshold)\n__C.TEST.NMS = 0.3\n\n# Experimental: treat the (K+1) units in the cls_score layer as linear\n# predictors (trained, eg, with one-vs-rest SVMs).\n__C.TEST.SVM = False\n\n# Test using these proposals\n__C.TEST.PROPOSAL_METHOD = 'selective_search'\n\n__C.TEST.ROIS_PER_IM = 10000\n__C.TEST.USE_FLIPPED = True\n__C.TEST.BBOX = False\n\n# for grid search NMS max_per_image thresh and so on\n__C.TEST.CACHE = False\n__C.TEST.MAP = 0.0\n\n#\n# MISC\n#\n\n# The mapping from image coordinates to feature map coordinates might cause\n# some boxes that are distinct in image space to become identical in feature\n# coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor\n# for identifying duplicate boxes.\n# 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16\n__C.DEDUP_BOXES = 1. / 16.\n\n# Pixel mean values (BGR order) as a (1, 1, 3) array\n# We use the same pixel mean for all networks even though it's not exactly what\n# they were trained with\n# fast rcnn\n# __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])\n# VGG 16\n__C.PIXEL_MEANS = np.array([[[103.939, 116.779, 123.68]]])\n# CaffeNet\n# __C.PIXEL_MEANS = np.array([[[104.00, 117.00, 123.00]]])\n\n# For reproducibility\n__C.RNG_SEED = 3\n\n# A small number that's used many times\n__C.EPS = 1e-14\n\n# Root directory of project\n__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))\n\n# Data directory\n__C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data'))\n\n# Model directory\n__C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc'))\n\n# Name (or path to) the matlab executable\n__C.MATLAB = 'matlab'\n\n# Place outputs under an experiments directory\n__C.EXP_DIR = 'default'\n\n# Use GPU implementation of non-maximum suppression\n__C.USE_GPU_NMS = True\n\n# Default GPU device id\n__C.GPU_ID = 0\n\n__C.CSC_DEBUG = False\n\n__C.CONTEXT = False\n__C.CONTEXT_RATIO = 1.8\n\n__C.USE_ROI_SCORE = False\n\n__C.USE_BG = False\n\n__C.SPATIAL_SCALE = 1. / 16.\n\n__C.RESIZE_MODE = 'FIT_SMALLEST'\n\n__C.USE_FEEDBACK = False\n__C.FEEDBACK_DIR = ''\n__C.FEEDBACK_NUM = 0\n\n\ndef get_vis_dir(imdb, net=None):\n \"\"\"Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'vis', __C.EXP_DIR, imdb.name))\n if net is not None:\n outdir = osp.join(outdir, net.name)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n file_path = 'tmp'\n if os.path.islink(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n import shutil\n shutil.rmtree(file_path)\n else:\n # It is a file\n os.remove(file_path)\n\n os.symlink(outdir, file_path)\n return outdir\n\n\ndef get_output_dir(imdb, net=None):\n \"\"\"Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n outdir = osp.abspath(\n osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))\n if net is not None:\n outdir = osp.join(outdir, net.name)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n return outdir\n","sub_path":"lib/wsl/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"639186911","text":"from my_celery.main import app\nimport time\n\n@app.task(bind=True)\ndef t2(self,a,b):\n # print(args)\n print(\"++++++++++\",a + b)\n time.sleep(5)\n print(\"t2 end\")\n print(self.request.id)\n return a+b","sub_path":"celery2/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"183940689","text":"from telegram import ReplyKeyboardMarkup\n\n\nTOKEN = \"TOKEN\"\n\nmusic_tracks = ['Bot Queue Music/{}'.format(i) for i in ('Elevator Music A.mp3',\n 'Elevator Music B.mp3',\n # 'It Hates Me So Much Extended.mp3',\n # 'Seduce Me.mp3',\n 'TF2 Upgrade Station.mp3')]\nadmins = []\npeople = {}\nsubjects = {}\nqueue = []\npath_to_people = 'config/people.cfg'\npath_to_admins = 'config/admins.cfg'\npath_to_subjects = 'config/subjects.cfg'\npath_to_subjects_folder = 'subjects/'\nwith open(path_to_people, encoding='utf-8') as file:\n for line in file.readlines():\n line = line.split()\n people[int(line[0])] = line[1]\nwith open(path_to_admins, encoding='utf-8') as file:\n for line in file.readlines():\n admins.append(int(line))\nwith open(path_to_subjects, encoding='utf-8') as file:\n for line in file.readlines():\n line = line.split()\n namelen = int(line[0])\n subjects[' '.join(line[1:namelen+1])] = line[namelen+1:]\n\n\nmarkups = {'idle': ReplyKeyboardMarkup([['Собрать отчёт в PDF',\n 'Отправить отчёт вышестоящим инстанциям'],\n ['Встать в очередь',\n 'Выйти из очереди',\n 'Послушать музыку'],\n ['Панель админ. доступа']],\n one_time_keyboard=True,\n resize_keyboard=True),\n 'admin': ReplyKeyboardMarkup([['Получить архив с отчётами',\n 'Разослать \"письма счастья\"'],\n ['Следующий']],\n one_time_keyboard=True,\n resize_keyboard=True),\n 'gathering': ReplyKeyboardMarkup([['Конец']],\n resize_keyboard=True,\n one_time_keyboard=False),\n 'subjects': ReplyKeyboardMarkup([[subject] for subject in subjects],\n resize_keyboard=True,\n one_time_keyboard=False),\n 'letter_type_choice': ReplyKeyboardMarkup([['Шаблонные', 'Написать своё']],\n resize_keyboard=True,\n one_time_keyboard=False)\n }\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"344974691","text":"from logging import getLogger\nfrom random import choice, random\nfrom .components import *\nimport tcod\nfrom engine.ecs import Entity\n\nfrom core.ai import Wander, FollowEntity, FollowAndAttack\n\n\nclass Player(Entity):\n tile = '@'\n\n def __init__(self, x, y):\n Entity.__init__(self,\n Position(x, y),\n Moveable(),\n Renderable(x,y, self.tile),\n Controllable(),\n Inventory(),\n BlocksMovement(),\n Combat(20, 5),\n )\n\nclass Wall(Entity):\n tile = '#'\n color = tcod.white\n\n def __init__(self, x, y):\n Entity.__init__(self,\n Position(x, y),\n BlocksMovement(),\n Renderable(x, y, self.tile)\n )\n\n\nclass Floor(Entity):\n tile = '.'\n\n def __init__(self, x, y):\n Entity.__init__(self,\n Position(x, y),\n Renderable(x, y, Floor.tile)\n )\n\nclass CreditStick(Entity):\n tile = '$'\n\n def __init__(self, x, y, value=0):\n Entity.__init__(self,\n Position(x, y),\n Renderable(x, y, self.tile),\n Pickup(),\n )\n self.value = value\n\n def pickup(self, other_ent, _map):\n if Inventory in other_ent:\n inventory = other_ent.components[Inventory]\n pos = self.components[Position]\n map_ents = _map.grid[pos.y][pos.x]\n\n inventory.credits += self.value\n map_ents.remove(self)\n\n def __str__(self):\n return self.__class__.__name__\n\n CREDIT_RANGE = range(1, 30)\n\n @classmethod\n def create(cls, x, y):\n value = choice(CreditStick.CREDIT_RANGE)\n return cls(x, y, value)\n\n\nclass ItemPickup:\n\n def pickup(self, other_ent, _map):\n if Inventory in other_ent:\n inventory = other_ent.components[Inventory]\n pos = self.components[Position]\n map_ents = _map.grid[pos.y][pos.x]\n\n inventory.items.append(self)\n map_ents.remove(self)\n\n def __str__(self):\n return self.__class__.__name__\n\n\nclass Rock(Entity, ItemPickup):\n tile = '*'\n\n def __init__(self, x, y):\n Entity.__init__(self,\n Position(x, y),\n Renderable(x, y, self.tile),\n Pickup(),\n )\n\n @classmethod\n def create(cls, x, y):\n return cls(x, y)\n\nclass PlayerSpawner(Entity):\n\n def __init__(self, x, y):\n Entity.__init__(self,\n Position(x, y),\n PlayerSpawn()\n )\n\n\nclass Citizen(Entity):\n tile = 'O'\n\n def __init__(self, x, y, ai_class, ai_args=None):\n ai_function = ai_class(self, *ai_args if ai_args else ())\n super().__init__(\n Position(x, y),\n Moveable(),\n AIComponent(ai_function=ai_function),\n Renderable(x, y, self.tile),\n BlocksMovement(),\n Combat(10, 2),\n )\n\n PROB_FOLLOWER = 0.5\n\n @classmethod\n def create(cls, x, y, player=None):\n #TODO: Should randomized values be strictly in map generation, or\n # does it make sense for entities to define how they're generated?\n if random() < cls.PROB_FOLLOWER:\n return cls(x, y, Wander)\n else:\n return cls(x, y, FollowEntity, (player,))\n\n\nclass KillerRobot(Entity):\n tile = 'r'\n\n def __init__(self, x, y, player=None):\n super().__init__(\n Position(x, y),\n Moveable(),\n AIComponent(ai_function=FollowAndAttack(self, player)),\n Renderable(x, y, self.tile),\n BlocksMovement(),\n Combat(10, 2),\n )\n\n @classmethod\n def create(cls, x, y):\n return cls(x, y)\n\nclass Terminal(Entity):\n tile = '?'\n log = getLogger('Terminal')\n\n def __init__(self, x, y):\n super().__init__(\n Position(x, y),\n Renderable(x, y, self.tile),\n BlocksMovement(),\n Interactable(self.open_terminal),\n )\n\n def open_terminal(self, bcast):\n bcast.publish('open-terminal')\n","sub_path":"core/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"508273425","text":"\"\"\"\nbooruhelper.py - Required for the booru modules to work correctly\nCopyright 2014 Max Gurela\n\nLicensed under the Eiffel Forum License 2 (It's GPL compatible!).\n\"\"\"\nimport json\nimport urllib\nimport urllib2\nimport urlparse\nimport re\n\nfrom urllib import quote\n\nua_firefox = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0' \\\n ' Firefox/17.0'\n\ndef get(*args, **kwargs):\n return open(*args, **kwargs).read()\n\ndef open(url, query_params=None, user_agent=None, post_data=None,\n referer=None, get_method=None, **kwargs):\n\n if query_params is None:\n query_params = {}\n\n if user_agent is None:\n user_agent = ua_firefox\n\n query_params.update(kwargs)\n\n url = prepare_url(url, query_params)\n\n request = urllib2.Request(url, post_data)\n\n if get_method is not None:\n request.get_method = lambda: get_method\n\n request.add_header('User-Agent', user_agent)\n\n if referer is not None:\n request.add_header('Referer', referer)\n\n return urllib2.build_opener().open(request)\n\n\ndef prepare_url(url, queries):\n if queries:\n scheme, netloc, path, query, fragment = urlparse.urlsplit(url)\n\n query = dict(urlparse.parse_qsl(query))\n query.update(queries)\n query = urllib.urlencode(dict((to_utf8(key), to_utf8(value))\n for key, value in query.iteritems()))\n\n url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))\n\n return url\n\ndef to_utf8(s):\n if isinstance(s, unicode):\n return s.encode('utf8', 'ignore')\n else:\n return str(s)","sub_path":"booruhelper.py","file_name":"booruhelper.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"490558632","text":"\n\nimport os\nimport sys\nimport time\n\n\nos.environ['SPARK_HOME']=\"/spark/spark-1.6.0-bin-hadoop2.6/\"\n\nsys.path.append(\"/spark/spark-1.6.0-bin-hadoop2.6/python\")\n\ntry:\n from pyspark import SparkContext\n from pyspark import SparkConf\n import pyspark.mllib.linalg.distributed.CoordinateMatrix\n import pyspark.mllib.linalg.distributed.MatrixEntry\n from pyspark.mllib.linalg import Vectors\n import numpy as np\n\n print (\"Successfully imported Spark Modules\")\n\n\n if __name__ == \"__main__\":\n start_time = time.time()\n master = \"local\"\n sc = SparkContext(master, \"WordCount\")\n\n path = \"/ydata-ymusic-user-song-ratings-meta-v1_03/\"\n data = sc.textFile(path + \"train_0_sub_100k.txt\")\n\n data = data.repartition(8)\n data.count()\n\n # distribution of the ratings\n drt = data.map(lambda x: (x.split(\"\\t\")[2], 1))\n drt1 = drt.reduceByKey(lambda x,y: x+y).collectAsMap()\n\n # distribution of songs by genre\n # \"song idalbumidartist idgenre id\"\n gendata = sc.textFile(path+\"song-attributes.txt\")\n gdata = gendata.map(lambda x: (x.split(\"\\t\")[0], x.split(\"\\t\")[3]))\n\n\n gendata1 = (gendata.map(lambda x: (x.split(\"\\t\")[3], 1))\n .reduceByKey(lambda x,y: x+y)\n .takeOrdered(10, key = lambda x: -x[1])\n )\n\n ###Top 5 genre\n data = sc.textFile(path + \"train_0.txt\")\n data = data.repartition(8)\n songs_ratings = data.map(lambda x: (x.split(\"\\t\")[1], 1))\n song_attributes = (sc.textFile(path+\"song-attributes.txt\")\n .map(lambda x: (x.split(\"\\t\")[0], x.split(\"\\t\")[3])))\n\n top5genre = (song_attributes.join(songs_ratings)\n .map(lambda x: (x[1][0], x[1][1]))\n .reduceByKey(lambda x,y: x+y)\n .takeOrdered(5, key= lambda x:-x[1]))\n\n ###Top 5 songs\n top5songs = (songs_ratings.reduceByKey(lambda x,y: x+y)\n .takeOrdered(5, key = lambda x: -x[1]))\nexcept ImportError as e:\n print (\"Can not import Spark Modules\", e)\n sys.exit(1)\n\n\n","sub_path":"scripts-Swetha/edacode.py","file_name":"edacode.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"23385415","text":"from Jumpscale import j\n\n\nclass BuilderRocksDB(j.baseclasses.builder):\n def build(self, reset=True, install=True):\n self.install(reset=reset)\n\n def install(self, reset=False):\n # install required packages to run.\n if self._done_check(\"install\", reset):\n return\n j.builders.system.python_pip.install(\n \"http://home.maxux.net/wheelhouse/python_rocksdb-0.6.9-cp35-cp35m-manylinux1_x86_64.whl\"\n )\n\n self._done_set(\"install\")\n","sub_path":"JumpscaleBuildersExtra/db/BuilderRocksDB.py","file_name":"BuilderRocksDB.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"316193059","text":"import random \nwinning_number = random.randint(1,100)\nguess = 1\nnum = int(input(\" Enter any number : \"))\ngame_over = False\n\nwhile not game_over:\n if num == winning_number:\n print(f\"You Win, and You Guessed this number in {guess} times\")\n game_over = True\n else: \n if num < winning_number:\n print(\"Too Low\")\n \n else:\n print(\"Too High\")\n guess += 1 \n num = int(input(\"Guess Again : \"))\n \n # Dry - don't repeat yourself","sub_path":"number_guessing_game2.py","file_name":"number_guessing_game2.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"401886570","text":"from setuptools import setup\nimport os\n\n# Grab line that contains version number from a file,\n# then execute it into the name space.\nversion_line = None\nwith open(os.path.join('til', 'til.py')) as f:\n for line in f.readlines():\n if '__version__' in line:\n version_line = line\n break\n\n__version__ = None\nif version_line:\n exec(version_line)\nelse:\n raise ValueError(\"Version number not found.\")\n\nsetup(\n name=\"cmdline-til\",\n packages=[\"til\"],\n entry_points={\n \"console_scripts\": ['til = til.til:main']\n },\n version=__version__,\n description=\"Python command line to record TILs (Today I Learned) quickly.\",\n long_description=\"\"\"A python command line tool to quickly take down notes and store it in a directory in /home.\"\"\",\n author=\"Patrick Lee\",\n author_email=\"me@patricklee.nyc\",\n url=\"https://github.com/patleeman/til\",\n download_url=\"https://github.com/patleeman/til/tarball/{}\".format(__version__)\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"201621007","text":"import pytest\n\nfrom dvc.exceptions import InvalidArgumentError\n\n\ndef test_file(tmp_dir, dvc):\n msg = (\n \"`--file` is currently incompatible with `-n|--name` \"\n \"and requires `--single-stage`\"\n )\n with pytest.raises(InvalidArgumentError, match=msg):\n dvc.run(fname=\"path/dvc.yaml\", name=\"my\", cmd=\"mycmd\")\n","sub_path":"tests/unit/repo/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"276429298","text":"# -*- coding: utf-8 -*-\n\"\"\"\n flask_security.decorators\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Flask-Security decorators module\n\n :copyright: (c) 2012 by Matt Wright.\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom functools import wraps\n\nfrom flask import Response, abort, current_app, redirect, request, url_for\nfrom flask_login import current_user # pragma: no flakes\nfrom flask_principal import Permission, RoleNeed\nfrom werkzeug.local import LocalProxy\nfrom werkzeug.routing import BuildError\n\nfrom . import utils\n\n# Convenient references\n_security = LocalProxy(lambda: current_app.extensions['security'])\n\n\n_default_unauthorized_html = \"\"\"\n
Unauthorized
\n
The server could not verify that you are authorized to access the URL\n requested. You either supplied the wrong credentials (e.g. a bad password),\n or your browser doesn't understand how to supply the credentials required.\n
\n \"\"\"\n\n\ndef _get_unauthorized_response(text=None, headers=None):\n text = text or _default_unauthorized_html\n headers = headers or {}\n return Response(text, 401, headers)\n\n\ndef _get_unauthorized_view():\n view = utils.get_url(utils.config_value('UNAUTHORIZED_VIEW'))\n if view:\n if callable(view):\n view = view()\n else:\n try:\n view = url_for(view)\n except BuildError:\n view = None\n utils.do_flash(*utils.get_message('UNAUTHORIZED'))\n redirect_to = '/'\n if (request.referrer and\n not request.referrer.split('?')[0].endswith(request.path)):\n redirect_to = request.referrer\n\n return redirect(view or redirect_to)\n abort(403)\n\n\ndef auth_required(*auth_methods):\n \"\"\"\n Decorator that protects enpoints through multiple mechanisms\n Example::\n\n @app.route('/dashboard')\n @auth_required('session')\n def dashboard():\n return 'Dashboard'\n\n :param auth_methods: Specified mechanisms.\n \"\"\"\n login_mechanisms = {\n 'session': lambda: current_user.is_authenticated\n }\n\n def wrapper(fn):\n @wraps(fn)\n def decorated_view(*args, **kwargs):\n h = {}\n mechanisms = [(method, login_mechanisms.get(method))\n for method in auth_methods]\n for method, mechanism in mechanisms:\n if mechanism and mechanism():\n return fn(*args, **kwargs)\n if _security._unauthorized_callback:\n return _security._unauthorized_callback()\n else:\n return _get_unauthorized_response(headers=h)\n return decorated_view\n return wrapper\n\n\ndef roles_required(*roles):\n \"\"\"Decorator which specifies that a user must have all the specified roles.\n Example::\n\n @app.route('/dashboard')\n @roles_required('admin', 'editor')\n def dashboard():\n return 'Dashboard'\n\n The current user must have both the `admin` role and `editor` role in order\n to view the page.\n\n :param args: The required roles.\n \"\"\"\n def wrapper(fn):\n @wraps(fn)\n def decorated_view(*args, **kwargs):\n perms = [Permission(RoleNeed(role)) for role in roles]\n for perm in perms:\n if not perm.can():\n if _security._unauthorized_callback:\n return _security._unauthorized_callback()\n else:\n return _get_unauthorized_view()\n return fn(*args, **kwargs)\n return decorated_view\n return wrapper\n\n\ndef roles_accepted(*roles):\n \"\"\"Decorator which specifies that a user must have at least one of the\n specified roles. Example::\n\n @app.route('/create_post')\n @roles_accepted('editor', 'author')\n def create_post():\n return 'Create Post'\n\n The current user must have either the `editor` role or `author` role in\n order to view the page.\n\n :param args: The possible roles.\n \"\"\"\n def wrapper(fn):\n @wraps(fn)\n def decorated_view(*args, **kwargs):\n perm = Permission(*[RoleNeed(role) for role in roles])\n if perm.can():\n return fn(*args, **kwargs)\n if _security._unauthorized_callback:\n return _security._unauthorized_callback()\n else:\n return _get_unauthorized_view()\n return decorated_view\n return wrapper\n\n\ndef anonymous_user_required(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n if current_user.is_authenticated:\n return redirect(utils.get_url(_security.post_login_view))\n return f(*args, **kwargs)\n return wrapper\n","sub_path":"flask_security/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"116022576","text":"import asyncio\n\nfrom collections import namedtuple\n\nfrom aiocache import cached, RedisCache\nfrom aiocache.serializers import PickleSerializer\n\nResult = namedtuple('Result', \"content, status\")\n\nRedisCache.set_defaults(\n namespace=\"main\",\n db=1,\n pool_min_size=3,\n serializer=PickleSerializer())\n\n\n@cached(cache=RedisCache, ttl=10, key=\"key\")\nasync def decorator():\n return Result(\"content\", 200)\n\n\nasync def global_cache():\n cache = RedisCache()\n obj = await cache.get(\"key\")\n\n assert obj.content == \"content\"\n assert obj.status == 200\n assert cache.db == 1\n assert cache.pool_min_size == 3\n\n\ndef test_default_cache():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(decorator())\n loop.run_until_complete(global_cache())\n\n loop.run_until_complete(RedisCache(namespace=\"main\").delete(\"key\"))\n\n\nif __name__ == \"__main__\":\n test_default_cache()\n","sub_path":"examples/config_default_cache.py","file_name":"config_default_cache.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"21888225","text":"import math\ndef isPrime(x):\n temp = int(math.sqrt(x))\n for y in range(2,temp+1):\n if(x % y == 0):\n return False\n return True\n\ndef primeFactors(x):\n answer = []\n for tmp in range(2,x):\n if(isPrime(tmp)):\n if(x % tmp == 0):\n while(x % tmp == 0):\n x = x/tmp\n answer.append(tmp)\n print(answer)\nprimeFactors(270)\nprimeFactors(45)\nprint(isPrime(2))\nprint(isPrime(45))\n","sub_path":"q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"527837731","text":"load(\"@bazel_skylib//lib:collections.bzl\", \"collections\")\nload(\"@fbcode_macros//build_defs/lib:python_common.bzl\", \"python_common\")\nload(\"@fbcode_macros//build_defs/lib:visibility.bzl\", \"get_visibility\")\nload(\"@fbsource//tools/build_defs:fb_native_wrapper.bzl\", \"fb_native\")\n\ndef python_unittest(\n name,\n py_version = None,\n py_flavor = \"\",\n base_module = None,\n main_module = None,\n strip_libpar = True,\n srcs = (),\n versioned_srcs = (),\n tags = (),\n gen_srcs = (),\n deps = (),\n tests = (),\n par_style = None,\n emails = None,\n external_deps = (),\n needed_coverage = None,\n argcomplete = None,\n strict_tabs = None,\n compile = None,\n args = None,\n env = None,\n python = None,\n allocator = None,\n check_types = False,\n preload_deps = (),\n visibility = None,\n resources = (),\n jemalloc_conf = None,\n typing = False,\n typing_options = \"\",\n check_types_options = \"\",\n runtime_deps = (),\n cpp_deps = (), # ctypes targets\n helper_deps = False,\n analyze_imports = False,\n additional_coverage_targets = (),\n version_subdirs = None):\n visibility = get_visibility(visibility, name)\n\n all_attributes = python_common.convert_binary(\n is_test = True,\n fbconfig_rule_type = \"python_unittest\",\n buck_rule_type = \"python_test\",\n base_path = native.package_name(),\n name = name,\n py_version = py_version,\n py_flavor = py_flavor,\n base_module = base_module,\n main_module = main_module,\n strip_libpar = strip_libpar,\n srcs = srcs,\n versioned_srcs = versioned_srcs,\n tags = tags,\n gen_srcs = gen_srcs,\n deps = deps,\n tests = tests,\n par_style = par_style,\n emails = emails,\n external_deps = external_deps,\n needed_coverage = needed_coverage,\n argcomplete = argcomplete,\n strict_tabs = strict_tabs,\n compile = compile,\n args = args,\n env = env,\n python = python,\n allocator = allocator,\n check_types = check_types,\n preload_deps = preload_deps,\n visibility = visibility,\n resources = resources,\n jemalloc_conf = jemalloc_conf,\n typing = typing,\n typing_options = typing_options,\n check_types_options = check_types_options,\n runtime_deps = runtime_deps,\n cpp_deps = cpp_deps,\n helper_deps = helper_deps,\n analyze_imports = analyze_imports,\n additional_coverage_targets = additional_coverage_targets,\n version_subdirs = version_subdirs,\n )\n\n py_tests = []\n for attributes in all_attributes:\n fb_native.python_test(**attributes)\n py_tests.append(\n (\":\" + attributes[\"name\"], attributes.get(\"tests\")),\n )\n\n # TODO: This should probably just be test_suite? This rule really doesn't\n # make sense....\n # Create a genrule to wrap all the tests for easy running if a test was created\n # for multiple python versions (they'll have different names)\n if len(py_tests) > 1:\n # We are propogating tests from sub targets to this target\n gen_tests = []\n for test_target, tests_attribute in py_tests:\n gen_tests.append(test_target)\n if tests_attribute:\n gen_tests.extend(tests_attribute)\n gen_tests = collections.uniq(gen_tests)\n\n cmd = \" && \".join([\n \"echo $(location {})\".format(test_target)\n for test_target in gen_tests\n ] + [\"touch $OUT\"])\n\n fb_native.genrule(\n name = name,\n visibility = visibility,\n out = \"unused\",\n tests = gen_tests,\n cmd = cmd,\n )\n","sub_path":"infra_macros/fbcode_macros/build_defs/python_unittest.bzl","file_name":"python_unittest.bzl","file_ext":"bzl","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"11054463","text":"from itertools import groupby\nfrom typing import Any, List\n\nimport sqlalchemy as sa\nfrom repka.api import BaseRepository, T\nfrom sqlalchemy import Table, UniqueConstraint\n\nfrom polytical_views.models import (\n Person,\n Tweet,\n Sentiment,\n FullSentiment,\n Feature,\n PersonScore,\n TwitterTask,\n)\n\nmetadata = sa.MetaData()\n\npeople_table = sa.Table(\n \"people\",\n metadata,\n sa.Column(\"id\", sa.Integer, primary_key=True, autoincrement=True),\n sa.Column(\"url\", sa.String),\n sa.Column(\"pic\", sa.String),\n sa.Column(\"name\", sa.String),\n)\n\ntweets_table = sa.Table(\n \"tweets\",\n metadata,\n sa.Column(\"id\", sa.Integer, primary_key=True, autoincrement=True),\n sa.Column(\n \"person_id\", sa.Integer, sa.ForeignKey(people_table.c.id), nullable=False\n ),\n sa.Column(\"url\", sa.String),\n sa.Column(\"text\", sa.String),\n sa.Column(\"created_at\", sa.DateTime),\n)\n\nfeatures_table = sa.Table(\n \"features\",\n metadata,\n sa.Column(\"id\", sa.Integer, primary_key=True, autoincrement=True),\n sa.Column(\"title\", sa.String, unique=True),\n sa.Column(\"keywords\", sa.ARRAY(sa.String)),\n sa.Column(\"vocab_to_int\", sa.JSON),\n sa.Column(\"net\", sa.JSON)\n)\n\ntweets_sentiment_table = sa.Table(\n \"tweets_sentiment\",\n metadata,\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"tweet_id\", sa.Integer, sa.ForeignKey(tweets_table.c.id)),\n sa.Column(\"feature_id\", sa.Integer, sa.ForeignKey(features_table.c.id)),\n sa.Column(\"sentiment\", sa.Integer),\n UniqueConstraint(\"tweet_id\", \"feature_id\"),\n)\n\ntwitter_tasks_table = sa.Table(\n \"twitter_task\",\n metadata,\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"result_id\", sa.Integer, sa.ForeignKey(people_table.c.id)),\n sa.Column(\"status\", sa.Integer),\n)\n\n\nclass PersonRepository(BaseRepository[Person]):\n @property\n def table(self) -> Table:\n return people_table\n\n def deserialize(self, **kwargs: Any) -> T:\n return Person(**kwargs)\n\n\nclass TweetRepository(BaseRepository[Tweet]):\n @property\n def table(self) -> Table:\n return tweets_table\n\n def deserialize(self, **kwargs: Any) -> T:\n return Tweet(**kwargs)\n\n\nclass FeatureRepository(BaseRepository[Feature]):\n @property\n def table(self) -> Table:\n return features_table\n\n def deserialize(self, **kwargs: Any) -> T:\n return Feature(**kwargs)\n\n\nclass SentimentRepository(BaseRepository[Sentiment]):\n @property\n def table(self) -> Table:\n return tweets_sentiment_table\n\n @property\n def features_table(self) -> Table:\n return features_table\n\n @property\n def tweets_table(self) -> Table:\n return tweets_table\n\n def deserialize(self, **kwargs: Any) -> T:\n return Sentiment(**kwargs)\n\n async def get_full_sentiments(self, tweet_id: int) -> List[FullSentiment]:\n join = sa.join(\n self.table,\n self.features_table,\n self.table.c.feature_id == self.features_table.c.id,\n )\n query = (\n sa.select(\n [*self.table.c, self.features_table.c.title.label(\"feature_name\")]\n )\n .select_from(join)\n .where(self.table.c.tweet_id == tweet_id)\n )\n return [FullSentiment(**row) async for row in self.connection.execute(query)]\n\n async def get_person_scores(self, person_id: int) -> List[PersonScore]:\n scores = await self.get_all_people_scores()\n return [score for score in scores if score.person_id == person_id]\n\n async def get_all_people_scores(self) -> List[PersonScore]:\n join = sa.join(\n sa.join(\n self.table,\n self.tweets_table,\n self.table.c.tweet_id == self.tweets_table.c.id,\n ),\n self.features_table,\n self.table.c.feature_id == self.features_table.c.id,\n )\n\n query = (\n sa.select(\n [\n self.tweets_table.c.person_id,\n self.features_table.c.id.label(\"feature_id\"),\n self.features_table.c.title.label(\"feature_name\"),\n self.table.c.sentiment,\n self.tweets_table.c.id.label(\"tweet_id\"),\n ]\n )\n .select_from(join)\n .order_by(\"person_id\", \"feature_id\")\n )\n\n rows = await self.connection.execute(query)\n rows_list = [row async for row in rows]\n\n grouped = groupby(rows_list, lambda row: (row.person_id, row.feature_id))\n\n res = []\n for (person_id, feature_id), group in grouped:\n group_list = list(group)\n\n score = PersonScore(\n person_id=person_id,\n feature_id=feature_id,\n feature_name=group_list[0].feature_name,\n score=sum(row.sentiment for row in group_list) / len(group_list),\n reasons=[row.tweet_id for row in group_list],\n )\n res.append(score)\n\n return res\n\n\nclass TwitterTaskRepository(BaseRepository[TwitterTask]):\n @property\n def table(self) -> Table:\n return twitter_tasks_table\n\n def deserialize(self, **kwargs: Any) -> T:\n return TwitterTask(**kwargs)\n\n async def get_by_result_id(self, result_id: int):\n return (await self.get_all([self.table.c.result_id == result_id]))[0]\n","sub_path":"polytical_views/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"253954183","text":"from module import *\nfrom DCview import *\n\nclass DCplayer(Hand):\n def __init__(self):\n super(DCplayer, self).__init__()\n self.check_correct=[]\n\n def __str__(self):\n show=super(DCplayer, self).__str__()\n show+=\" \"\n for check in self.check_correct:\n show+=check.rjust(8)+\" \"\n return show\n\n def set_Joker(self):\n left=[]\n right=[]\n while self.joker!=0:\n print(\"You have to insert your Joker! \",end='')\n loc=Reader.select_loc(self, self)\n if self.cards[len(self.cards)-1].color==\"White\":\n self.white_joker=loc\n else:\n self.black_joker=loc\n left=self.cards[:loc-1]\n right=self.cards[loc-1:]\n left.append(self.cards[len(self.cards)-self.joker])\n right.remove(self.cards[len(self.cards)-self.joker])\n self.cards=left+right\n self.joker=self.joker-1\n\n def match(self, card, you):\n num=0\n import random\n while True:\n num=random.randrange(len(self.cards))\n if self.check_correct[num]==\"Covered\":\n break\n if self.cards[num-1]==card:\n print(\"\\n\\n\\n\\n\\nCPU is right\")\n self.cards[self.cards.index(card)].check=1\n else:\n print(\"\\n\\n\\n\\n\\nCPU is wrong\")\n you.wrong()\n\n def status(self):\n for i in range(len(self.cards)):\n if self.cards[i].check==0:\n self.check_correct[i]=\"Covered\"\n else:\n self.check_correct[i]=\"Opened\"\n\n def sorting(self, card):\n super(DCplayer, self).sorting(card)\n for i in range(len(self.cards)):\n self.check_correct[i]=\" \"\n self.status()\n\n\n def check_win(self, you):\n count=0\n for card in you.cards:\n if card.face_up:\n count+=1\n if count==len(you.cards):\n self.win()\n return True\n\n def check_lose(self):\n count=0\n for card in self.cards:\n if card.check==1:\n count+=1\n if count==len(self.cards):\n self.lose()\n return True\n\n def wrong(self):\n print(\"You wrong! You have to open your card.\")\n loc=Reader.select_loc(self, self)\n while True:\n if self.check_correct[loc-1]==\"Covered\":\n self.cards[loc-1].check=1\n self.sorting(None)\n break\n else:\n loc=Reader.select_loc(self, self)\n\nclass DCcpu(Hand):\n def __init__(self, cards):\n super(DCcpu, self).__init__()\n self.ans=cards\n self.check_correct=[]\n\n def choose_loc(self):#조커 위치\n loc=0\n for i in range(len(self.cards)-1):\n if int(self.cards[i+1].number)-int(self.cards[i].number)>3:\n return i\n elif int(self.cards[i+1].number)-int(self.cards[i].number)==0:\n import random\n return i+1\n else:\n import random\n loc=random.randrange(2)\n if loc==0:\n return 2\n else:\n return len(self.cards)-1\n\n def set_Joker(self):\n left=[]\n right=[]\n while self.joker!=0:\n loc=self.choose_loc()\n if self.cards[len(self.cards)-1].color==\"White\":\n self.white_joker=loc\n else:\n self.black_joker=loc\n left=self.cards[:loc-1]\n right=self.cards[loc-1:]\n left.append(self.cards[len(self.cards)-self.joker])\n right.remove(self.cards[len(self.cards)-self.joker])\n self.cards=left+right\n self.joker=self.joker-1\n \n def correct_ans(self):\n for i in range(len(self.cards)):\n for j in range(len(self.ans)):\n if self.cards[i].color==self.ans[j].color\\\n and self.cards[i].number==self.ans[j].number:\n self.ans.remove(self.ans[j])\n break\n import random\n return self.ans[random.randrange(len(self.ans))]\n\n def wrong(self):\n while True:\n import random\n loc=random.randrange(len(self.cards))\n if not self.cards[loc].face_up:\n self.cards[loc].flip()\n break\n","sub_path":"DaVinci.py","file_name":"DaVinci.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"547056823","text":"#! /usr/bin/python3\n#-*- coding:utf-8 -*-\n\nfrom influxdb import InfluxDBClient\nfrom datetime import datetime\n\nprotocol = 'line'\ndef write2db(datatype,data,client):\n tmp = [{\"measurement\":None,\"tags\":{},\"fields\":{},\"time\":datetime.now().isoformat()}]\n tmp[0][\"measurement\"] = datatype[\"measurement\"]\n for x in datatype['tags']:\n tmp[0][\"tags\"][x] = getattr(data,x)\n for y in datatype['fields']:\n tmp[0][\"fields\"][y] = getattr(data,y)\n for z in datatype['time']:\n tmp[0]['time'][z] = getattr(data,z)\n client.write_points(tmp)","sub_path":"plugins/db_modules.py","file_name":"db_modules.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"305545161","text":"import asyncio\nimport configparser\nimport json\nfrom sqlite3 import OperationalError\n\nfrom telethon import TelegramClient\n\nclient = None\nclass TelegramConnection:\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read(\"config.ini\")\n\n self.api_id = config['Telegram']['api_id']\n self.api_hash = str(config['Telegram']['api_hash'])\n\n self.phone = config['Telegram']['phone']\n self.username = config['Telegram']['username']\n\n def set_credtional(self, api_id, api_hash, phone, username):\n self.api_id = api_id\n self.api_hash = api_hash\n self.phone = phone\n self.username = username\n\n async def get_client(self):\n global client\n try:\n if client is not None:\n return client\n client = TelegramClient(self.username, api_id=self.api_id, api_hash=self.api_hash)\n await client.start()\n return client\n except Exception as e:\n print(e)\n return None\n","sub_path":"global_utils/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"67873777","text":"# Copyright 2021 The Google Earth Engine Community Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# [START earthengine__apidocs__ee_data_getdownloadid]\n\"\"\"Demonstrates the ee.data.getDownloadId method.\"\"\"\n\nimport io\nimport requests\nimport ee\n\n\nee.Authenticate()\nee.Initialize()\n\n# A Sentinel-2 surface reflectance image.\nimg = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG')\n\n# A small region within the image.\nregion = ee.Geometry.BBox(-122.0859, 37.0436, -122.0626, 37.0586)\n\n# Image chunk as a NumPy structured array.\nimport numpy\ndownload_id = ee.data.getDownloadId({\n 'image': img,\n 'bands': ['B3', 'B8', 'B11'],\n 'region': region,\n 'scale': 20,\n 'format': 'NPY'\n})\nresponse = requests.get(ee.data.makeDownloadUrl(download_id))\ndata = numpy.load(io.BytesIO(response.content))\nprint(data)\nprint(data.dtype)\n\n# Single-band GeoTIFF files wrapped in a zip file.\ndownload_id = ee.data.getDownloadId({\n 'image': img,\n 'name': 'single_band',\n 'bands': ['B3', 'B8', 'B11'],\n 'region': region\n})\nresponse = requests.get(ee.data.makeDownloadUrl(download_id))\nwith open('single_band.zip', 'wb') as fd:\n fd.write(response.content)\n\n# Multi-band GeoTIFF file wrapped in a zip file.\ndownload_id = ee.data.getDownloadId({\n 'image': img,\n 'name': 'multi_band',\n 'bands': ['B3', 'B8', 'B11'],\n 'region': region,\n 'scale': 20,\n 'filePerBand': False\n})\nresponse = requests.get(ee.data.makeDownloadUrl(download_id))\nwith open('multi_band.zip', 'wb') as fd:\n fd.write(response.content)\n\n# Band-specific transformations.\ndownload_id = ee.data.getDownloadId({\n 'image': img,\n 'name': 'custom_single_band',\n 'bands': [\n {'id': 'B3', 'scale': 10},\n {'id': 'B8', 'scale': 10},\n {'id': 'B11', 'scale': 20}\n ],\n 'region': region\n})\nresponse = requests.get(ee.data.makeDownloadUrl(download_id))\nwith open('custom_single_band.zip', 'wb') as fd:\n fd.write(response.content)\n\n# Multi-band GeoTIFF file.\ndownload_id = ee.data.getDownloadId({\n 'image': img,\n 'bands': ['B3', 'B8', 'B11'],\n 'region': region,\n 'scale': 20,\n 'format': 'GEO_TIFF'\n})\nresponse = requests.get(ee.data.makeDownloadUrl(download_id))\nwith open('multi_band.tif', 'wb') as fd:\n fd.write(response.content)\n# [END earthengine__apidocs__ee_data_getdownloadid]\n","sub_path":"samples/python/apidocs/ee_data_getdownloadid.py","file_name":"ee_data_getdownloadid.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"464777027","text":"# Copyright (c) 2016. Zuercher Hochschule fuer Angewandte Wissenschaften\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom django.core.urlresolvers import reverse\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ungettext_lazy\n\nfrom horizon import tables\n\nfrom mistraldashboard import api\nfrom mistraldashboard.default.utils import humantime\n\n\nclass CreateDelayTolerantWorkload(tables.LinkAction):\n name = \"create\"\n verbose_name = _(\"Create Delay Tolerant Workload\")\n url = \"horizon:mistral:delayt_workloads:create\"\n classes = (\"ajax-modal\",)\n icon = \"plus\"\n\n\nclass DeleteDelayTolerantWorkload(tables.DeleteAction):\n @staticmethod\n def action_present(count):\n return ungettext_lazy(\n u\"Delete Delay Tolerant Workload\",\n u\"Delete Delay Tolerant Workloads\",\n count\n )\n\n @staticmethod\n def action_past(count):\n return ungettext_lazy(\n u\"Deleted Delay Tolerant Workload\",\n u\"Deleted Delay Tolerant Workloads\",\n count\n )\n\n def delete(self, request, delay_tolerant_workload_name):\n api.delay_tolerant_workload_delete(request,\n delay_tolerant_workload_name)\n\n\nclass WorkflowColumn(tables.Column):\n def get_link_url(self, datum):\n workflow_url = \"horizon:mistral:workflows:detail\"\n obj_id = datum.workflow_name\n return reverse(workflow_url, args=[obj_id])\n\n\nclass DelayTolerantWorkloadsTable(tables.DataTable):\n id = tables.Column(\n \"id\",\n verbose_name=_(\"ID\"),\n link=\"horizon:mistral:delayt_workloads:detail\"\n )\n name = tables.Column(\n \"name\",\n verbose_name=_(\"Name\")\n )\n workflow_name = WorkflowColumn(\n \"workflow_name\",\n verbose_name=_(\"Workflow\"),\n link=True\n )\n deadline = tables.Column(\n \"deadline\",\n verbose_name=_(\"Deadline\"),\n )\n job_duration = tables.Column(\n \"job_duration\",\n verbose_name=_(\"Job Duration\"),\n )\n created_at = tables.Column(\n \"created_at\",\n verbose_name=_(\"Created at\"),\n filters=[humantime]\n )\n updated_at = tables.Column(\n \"updated_at\",\n verbose_name=_(\"Updated at\"),\n filters=[humantime]\n )\n\n def get_object_id(self, datum):\n return datum.name\n\n class Meta(object):\n name = \"delay tolerant workload\"\n verbose_name = _(\"Delay Tolerant Workload\")\n table_actions = (\n tables.FilterAction,\n CreateDelayTolerantWorkload,\n DeleteDelayTolerantWorkload\n )\n row_actions = (DeleteDelayTolerantWorkload,)\n","sub_path":"mistraldashboard/delayt_workloads/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"198232258","text":"import csv\nimport datetime\nimport re\nimport yaml\n\nclass Population( object ):\n \n def __init__( self ):\n\n self.entry_rx_short = re.compile( '^\\s*#(?P\\w+)\\s+(?P\\d+|\\d+\\.\\d+|\\.\\d+)\\s*(h|hr|hrs)\\s*$' )\n self.entry_rx_long = re.compile( '^\\s*(?P.*?)\\s+#(?P\\w+)\\s+(?P\\d+|\\d+\\.\\d+|\\.\\d+)\\s*(h|hr|hrs)\\s*$' )\n\n self.entries = []\n self.entries_rejected = []\n self.entries_earliest = False\n self.entries_latest = False\n\n self.tag_counts = {}\n\n def _sum_tags( self ):\n \n for e in self.entries:\n if e['tag'] not in self.tag_counts:\n self.tag_counts[e['tag']] = 0\n self.tag_counts[e['tag']] += e['effort']\n \n def _set_earliest_and_latest( self ):\n \n self.entries_earliest = min( [ e['date'] for e in self.entries ] )\n self.entries_latest = max( [e['date'] for e in self.entries ] )\n\nclass CSVPopulation( Population ):\n\n def __init__( self, path_to_export_file, path_to_filter_file ):\n super().__init__()\n \n self.path_to_export_file = path_to_export_file\n self.path_to_filter_file = path_to_filter_file\n \n with open( self.path_to_filter_file ) as f:\n self.filters = yaml.safe_load( f )\n \n with open( self.path_to_export_file, newline='' ) as f:\n rdr = csv.reader( f )\n rdr.__next__()\n for r in rdr:\n\n # 0 user_email_address\n # 1 status\n # 2 body\n # 3 occurred_on\n # 4 completed_on\n # 5 created_at\n # 6 archived_at\n \n if r[0] in self.filters['skip']:\n continue\n \n m = self.entry_rx_short.match( r[2] )\n if m:\n \n if m.group( 'tag' ) in self.filters['tags'].keys():\n filtered_tag = self.filters['tags'][m.group( 'tag' )]\n else:\n filtered_tag = m.group( 'tag' )\n \n self.entries.append( {\n 'email': r[0],\n 'date': datetime.datetime.strptime( r[4], '%Y-%m-%d' ),\n 'description': '(none)',\n 'tag': filtered_tag,\n 'effort': float( m.group( 'effort' ) )\n } )\n continue\n \n m = self.entry_rx_long.match( r[2] )\n if m:\n\n if m.group( 'tag' ) in self.filters['tags'].keys():\n filtered_tag = self.filters['tags'][m.group( 'tag' )]\n else:\n filtered_tag = m.group( 'tag' )\n \n self.entries.append( {\n 'email': r[0],\n 'date': datetime.datetime.strptime( r[4], '%Y-%m-%d' ),\n 'description': m.group( 'description' ),\n 'tag': filtered_tag,\n 'effort': float( m.group( 'effort' ) )\n } )\n continue\n \n self.entries_rejected.append( {\n 'email': r[0],\n 'date': r[4],\n 'body': r[2]\n } )\n \n self._sum_tags()\n self._set_earliest_and_latest()\n \n @property\n def source( self ):\n return 'csv | %s | %s' % ( self.path_to_export_file, self.path_to_filter_file )\n","sub_path":"src/ireportedthis/population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"532277873","text":"import numpy as np \nimport os\nimport skimage.io as io\nimport skimage.transform as trans\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\n\nsmooth = 1.\n\n# def iou(y_true, y_pred):\n# y_pred = tf.cast(y_pred[:,:,:,0],'float32')\n# y_true = tf.cast(y_true[:,:,:,0],'float32') \n \n# # pred = tf.cast(y_pred,'float32')\n# # true = tf.cast(y_true,'float32') \n \n# y_pred = keras.batch_flatten(y_pred)\n# y_true = keras.batch_flatten(y_true)\n \n# tp = y_true * y_pred\n# fp = y_true * (1 - y_pred)\n# fn = (1-y_true) * y_pred\n \n# tp = keras.sum(tp,axis=-1)\n# fp = keras.sum(fp,axis=-1)\n# fn = keras.sum(fn,axis=-1)\n \n# intersection = tp + smooth \n# union= (tp+fp+fn) + smooth\n \n# iou = intersection/union\n# return iou\n\ndef iou(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f) \n return (intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) - intersection + smooth)\n\ndef dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\ndef dice_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef unet(pretrained_weights = None, batchnorm = True, input_size = (256,256,1)):\n \n inputs = Input(input_size)\n \n #Downsample Block 1\n conv1 = Conv2D(64, (3, 3), padding='same')(inputs)\n if batchnorm == True:\n conv1 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv1)\n conv1 = Activation('relu')(conv1) \n \n conv1 = Conv2D(64, (3, 3), padding='same')(conv1)\n if batchnorm == True:\n conv1 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv1)\n else:\n conv1 = conv1\n conv1 = Activation('relu')(conv1) \n \n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n #Downsample Block 2\n conv2 = Conv2D(128, (3, 3), padding='same')(pool1)\n if batchnorm == True:\n conv2 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv2)\n conv2 = Activation('relu')(conv2)\n \n conv2 = Conv2D(128, (3, 3), padding='same')(conv2)\n if batchnorm == True:\n conv2 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv2)\n else:\n conv2 = conv2\n conv2 = Activation('relu')(conv2)\n \n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n \n #Downsample Block 3\n conv3 = Conv2D(256, (3, 3), padding='same')(pool2)\n if batchnorm == True:\n conv3 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv3)\n conv3 = Activation('relu')(conv3)\n \n conv3 = Conv2D(256, (3, 3), padding='same')(conv3)\n if batchnorm == True:\n conv3 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv3)\n else:\n conv3 = conv3\n conv3 = Activation('relu')(conv3)\n \n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n #Downsample Block 4\n conv4 = Conv2D(512, (3, 3), padding='same')(pool3)\n if batchnorm == True:\n conv4 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv4)\n conv4 = Activation('relu')(conv4)\n \n conv4 = Conv2D(512, (3, 3), padding='same')(conv4)\n if batchnorm == True:\n conv4 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv4)\n else:\n conv4 = conv4 \n conv4 = Activation('relu')(conv4)\n \n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n \n #Middle block \n conv5 = Conv2D(1024, (3, 3), padding='same')(pool4)\n if batchnorm == True:\n conv5 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv5)\n conv5 = Activation('relu')(conv5)\n \n conv5 = Conv2D(1024, (3, 3), padding='same')(conv5)\n if batchnorm == True:\n conv5 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv5)\n else:\n conv5 = conv5\n conv5 = Activation('relu')(conv5)\n \n #Upsample Block 1 \n up6 = Conv2DTranspose(512, (2, 2), strides=(2, 2), padding='same')(conv5) \n if batchnorm == True:\n up6 = BatchNormalization(axis=3, epsilon=1.001e-5)(up6)\n up6 = Activation('relu')(up6) \n \n up6 = concatenate([up6, conv4], axis=3)\n \n conv6 = Conv2D(512, (3, 3), padding='same')(up6)\n if batchnorm == True:\n conv6 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv6)\n conv6 = Activation('relu')(conv6)\n \n conv6 = Conv2D(512, (3, 3), padding='same')(conv6)\n if batchnorm == True:\n conv6 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv6)\n conv6 = Activation('relu')(conv6)\n \n #Upsample Block 2\n up7 = Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv6) \n if batchnorm == True:\n up7 = BatchNormalization(axis=3, epsilon=1.001e-5)(up7)\n up7 = Activation('relu')(up7) \n \n up7 = concatenate([up7, conv3], axis=3)\n \n conv7 = Conv2D(256, (3, 3), padding='same')(up7)\n if batchnorm == True:\n conv7 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv7)\n conv7 = Activation('relu')(conv7)\n \n conv7 = Conv2D(256, (3, 3), padding='same')(conv7)\n if batchnorm == True:\n conv7 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv7)\n conv7 = Activation('relu')(conv7)\n \n #Upsample Block 3\n up8 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv7) \n if batchnorm == True:\n up8 = BatchNormalization(axis=3, epsilon=1.001e-5)(up8)\n up8 = Activation('relu')(up8)\n \n up8 = concatenate([up8, conv2], axis=3)\n \n conv8 = Conv2D(128, (3, 3), padding='same')(up8)\n if batchnorm == True:\n conv8 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv8)\n conv8 = Activation('relu')(conv8)\n \n conv8 = Conv2D(128, (3, 3), padding='same')(conv8)\n if batchnorm == True:\n conv8 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv8)\n conv8 = Activation('relu')(conv8)\n \n #Upsample Block 4\n up9 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv8) \n if batchnorm == True:\n up9 = BatchNormalization(axis=3, epsilon=1.001e-5)(up9)\n up9 = Activation('relu')(up9)\n \n up9 = concatenate([up9, conv1], axis=3) \n \n conv9 = Conv2D(64, (3, 3), padding='same')(up9)\n if batchnorm == True:\n conv9 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv9)\n conv9 = Activation('relu')(conv9)\n \n conv9 = Conv2D(64, (3, 3), padding='same')(conv9)\n if batchnorm == True:\n conv9 = BatchNormalization(axis=3, epsilon=1.001e-5)(conv9)\n conv9 = Activation('relu')(conv9)\n \n #Output\n conv10 = Conv2D(1, (1, 1), activation='sigmoid')(conv9)\n\n model = Model(inputs=[inputs], outputs=[conv10])\n\n model.compile(optimizer = Adam(lr = 1e-4), loss = dice_loss, metrics = ['accuracy', iou])\n \n #model.summary()\n\n if(pretrained_weights):\n model.load_weights(pretrained_weights)\n\n return model\n\n\n","sub_path":"unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":7056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"40753028","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPyramid views for IAM Policies (permissions)\n\n\"\"\"\nimport simplejson as json\n\nfrom boto.exception import BotoServerError\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.i18n import TranslationString as _\nfrom pyramid.view import view_config\n\nfrom ..constants import policies, permissions\nfrom ..forms import ChoicesManager\nfrom ..forms.policies import IAMPolicyWizardForm\nfrom ..models import Notification\nfrom ..views import BaseView, JSONResponse, TaggedItemView\n\n\nclass IAMPolicyWizardView(BaseView):\n \"\"\"Create IAM Policy wizard\"\"\"\n TEMPLATE = '../templates/policies/iam_policy_wizard.pt'\n\n def __init__(self, request):\n super(IAMPolicyWizardView, self).__init__(request)\n self.request = request\n self.ec2_conn = self.get_connection()\n self.iam_conn = self.get_connection(conn_type='iam')\n self.policy_json_endpoint = self.request.route_url('iam_policy_json')\n self.create_form = IAMPolicyWizardForm(request=self.request, formdata=self.request.params or None)\n self.target_type = self.request.params.get('type', 'user') # 'user' or 'group'\n self.target_name = self.request.params.get('id', '') # user or group name\n self.choices_manager = ChoicesManager(conn=self.ec2_conn)\n self.render_dict = dict(\n page_title=self.get_page_title(),\n create_form=self.create_form,\n policy_json_endpoint=self.policy_json_endpoint,\n policy_actions=permissions.POLICY_ACTIONS,\n controller_options=json.dumps(self.get_controller_options()),\n resource_choices=dict(\n instances=self.get_instance_choices(),\n images=self.get_image_choices(),\n volumes=self.get_volume_choices(),\n snapshots=self.get_snapshot_choices(),\n security_groups=self.get_security_group_choices(),\n key_pairs=self.get_key_pair_choices(),\n vm_types=self.get_vm_type_choices(),\n availability_zones=self.get_availability_zone_choices(),\n ),\n )\n\n @view_config(route_name='iam_policy_new', renderer=TEMPLATE, request_method='GET')\n def iam_policy_new(self):\n \"\"\"Displays the Create IAM Policy wizard\"\"\"\n return self.render_dict\n\n @view_config(route_name='iam_policy_create', renderer=TEMPLATE, request_method='POST')\n def iam_policy_create(self):\n \"\"\"Handles the POST from the Create IAM Policy wizard\"\"\"\n target_route = '{0}_view'.format(self.target_type) # 'user_view' or 'group_view'\n location = self.request.route_url(target_route, name=self.target_name) # redirect to detail page after submit\n if self.create_form.validate():\n policy_name = self.request.params.get('name')\n policy_json = self.request.params.get('policy', '{}')\n try:\n if self.target_type == 'user':\n caller = self.iam_conn.put_user_policy\n else:\n caller = self.iam_conn.put_group_policy\n caller(self.target_name, policy_name, policy_json)\n prefix = _(u'Successfully created IAM policy')\n msg = '{0} {1}'.format(prefix, policy_name)\n queue = Notification.SUCCESS\n except BotoServerError as err:\n msg = err.message\n queue = Notification.ERROR\n self.request.session.flash(msg, queue=queue)\n return HTTPFound(location=location)\n else:\n self.request.error_messages = self.create_form.get_errors_list()\n return self.render_dict\n\n def get_page_title(self):\n prefix = _(u'Add access policy for')\n return '{0} {1} {2}'.format(prefix, self.target_type.capitalize(), self.target_name)\n\n def get_controller_options(self):\n return {\n 'policyJsonEndpoint': self.policy_json_endpoint,\n 'cloudType': self.cloud_type,\n 'actionsList': self.get_all_actions(),\n }\n\n def get_instance_choices(self):\n resource_name = 'instance'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All instances...'))]\n for instance in self.ec2_conn.get_only_instances():\n value = '{0}{1}'.format(arn_prefix, instance.id)\n label = TaggedItemView.get_display_name(instance)\n choices.append((value, label))\n return choices\n\n def get_vm_type_choices(self):\n resource_name = 'vmtype'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All instance types...'))]\n vm_type_choices = self.choices_manager.instance_types(\n cloud_type=self.cloud_type, add_blank=False, add_description=False)\n for vm_type_choice in vm_type_choices:\n label = vm_type_choice[1]\n value = '{0}{1}'.format(arn_prefix, vm_type_choice[0])\n choices.append((value, label))\n return choices\n\n def get_image_choices(self):\n resource_name = 'image'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All images...'))]\n # Set owner alias to 'self' for AWS\n owner_alias = 'self' if self.cloud_type == 'aws' else None\n owners = [owner_alias] if owner_alias else []\n images = self.ec2_conn.get_all_images(owners=owners, filters={'image-type': 'machine'})\n for image in images:\n value = '{0}{1}'.format(arn_prefix, image.id)\n label = TaggedItemView.get_display_name(image)\n choices.append((value, label))\n return choices\n\n def get_volume_choices(self):\n resource_name = 'volume'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All volumes...'))]\n for volume in self.ec2_conn.get_all_volumes():\n value = '{0}{1}'.format(arn_prefix, volume.id)\n label = TaggedItemView.get_display_name(volume)\n choices.append((value, label))\n return choices\n\n def get_snapshot_choices(self):\n resource_name = 'snapshot'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All snapshots...'))]\n for snapshot in self.ec2_conn.get_all_snapshots():\n value = '{0}{1}'.format(arn_prefix, snapshot.id)\n label = TaggedItemView.get_display_name(snapshot)\n choices.append((value, label))\n return choices\n\n def get_security_group_choices(self):\n resource_name = 'securitygroup'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All security groups...'))]\n for security_group in self.ec2_conn.get_all_security_groups():\n value = '{0}{1}'.format(arn_prefix, security_group.name)\n label = '{0} ({1})'.format(security_group.name, security_group.id)\n choices.append((value, label))\n return choices\n\n def get_availability_zone_choices(self):\n resource_name = 'availabilityzone'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All zones...'))]\n for avail_zone_choice in self.choices_manager.availability_zones(add_blank=False):\n value = '{0}{1}'.format(arn_prefix, avail_zone_choice[0])\n label = avail_zone_choice[0]\n choices.append((value, label))\n return choices\n\n def get_key_pair_choices(self):\n resource_name = 'keypair'\n arn_prefix = self.get_arn_prefix(resource_name)\n choices = [(self.get_all_choice(resource_name), _(u'All key pairs...'))]\n for key_pair in self.ec2_conn.get_all_key_pairs():\n value = '{0}{1}'.format(arn_prefix, key_pair.name)\n label = key_pair.name\n choices.append((value, label))\n return choices\n\n def get_arn_prefix(self, resource, add_all=False):\n region = ''\n if self.cloud_type == 'aws':\n region = self.region\n return 'arn:aws:ec2:{region}::{resource}/{all}'.format(\n region=region, resource=resource, all='*' if add_all else '')\n\n def get_all_choice(self, resource):\n return self.get_arn_prefix(resource, add_all=True)\n\n @staticmethod\n def get_all_actions():\n actions = []\n for namespace in permissions.POLICY_ACTIONS:\n actions.extend(namespace.get('actions'))\n return actions\n\n\nclass IAMPolicyWizardJsonView(BaseView):\n \"\"\"View for returning JSON of canned policies\"\"\"\n\n @view_config(route_name='iam_policy_json', renderer='json', request_method='GET')\n def iam_policy_json(self):\n policy_type = self.request.params.get('type')\n policy_dict = policies.TYPE_POLICY_MAPPING.get(policy_type)\n if policy_dict:\n return dict(policy=policy_dict)\n return JSONResponse(status=404, message=_(u'Unable to locate policy'))\n\n\n","sub_path":"koala/views/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":9158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"170029527","text":"#!/usr/bin/env python3\nimport random\nimport sys\ntry:\n lines = sys.argv[1]\n try:\n number = int(lines)\n except ValueError as err:\n print(err)\n lines = 5\n if 1<= number <=10:\n lines = number\n else:\n lines = 5\nexcept IndexError:\n lines = 5\nguanci = ('the', 'a')\nzhuti = ('cat', 'dog', 'man', 'woman')\ndongci = ('sang', 'ran', 'jumped')\nzhuangyu = ('loudly', 'quietly', 'well', 'badly')\ni = 0\nwhile i < lines:\n rnd = random.randint(10, 19)\n if 10 <= rnd <= 14:\n print(random.choice(guanci), random.choice(zhuti), random.choice(dongci), random.choice(zhuangyu))\n else:\n print(random.choice(guanci), random.choice(zhuti), random.choice(dongci))\n i += 1 \n","sub_path":"chaper 1/4/aweful_poetry_2.py","file_name":"aweful_poetry_2.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"145201952","text":"# -*- coding: utf-8 -*-\nimport os\nimport multiprocessing\nimport time\nimport pandas as pd\nimport re\nimport php_fn\n\n\n# 特征集\n[text_feature_set, other_feature_set] = [multiprocessing.Manager().list(), multiprocessing.Manager().list()] \n\n\n# 获取php函数名\nfn_files_path = php_fn.project_path + \"/res/php_fn/\" # txt文件所在文件夹的绝对路径\nfn_files = os.listdir(fn_files_path) # txt文件名\nfn = pd.Series([[], [], [], []], index=[fn_file[:-4] for fn_file in fn_files])\nfor fn_file in fn_files:\n # 打开某个txt文件\n with open(fn_files_path + fn_file, \"r\", encoding=\"UTF-8\", errors=\"ignore\") as f:\n source = f.read().split()\n fn[str(fn_file[:-4])] = source\n\n\ndef text_feature(sample_file):\n \"\"\"\n @author: hanchenchen\n @date: 9/18/2018\n @fn:\n @version: 2.1\n \"\"\"\n tf = pd.Series([0, 0, 0, 0, 0, 0], index=[\"cmt_chars_num\", \"words_num\", \"diff_words_num\", \"longest_word_len\", \"chars_num\", \"special_chars_num\"])\n with open(sample_file, \"r\", encoding=\"UTF-8\", errors=\"ignore\") as f:\n source = f.read()\n tf[\"cmt_chars_num\"] = len(source) # 注释字符数\n # 字符串中的注释暂时当作注释,因为正常的代码中字符串极少包含注释\n source = re.compile(\"\\/\\*[\\s\\S]*\\*\\/\").sub('', source) # 去/*...*/注释\n source = re.compile(\"\\/\\/.*?\").sub('', source) # 去//注释\n tf[\"cmt_chars_num\"] -= len(source)\n words = re.findall(\"[a-zA-Z]+\", source)\n tf[\"words_num\"] = len(words) # 单词数量\n tf[\"diff_words_num\"] = len(set(words)) # 不同单词数量\n tf[\"longest_word_len\"] = max([len(word) for word in words]) # 最大单词长度\n tf[\"chars_num\"] = len(re.findall(\"\\S\", source)) # 字符数量\n tf[\"special_chars_num\"] = tf[\"chars_num\"] - len(re.findall(\"[a-zA-Z0-9]\", source)) # 特殊字符数量\n return tf\n\n\ndef other_feature(sample_file):\n \"\"\"\n @author: hanchenchen\n @date: 9/24/2018\n @function:\n @version: 2.0\n \"\"\"\n of = pd.Series([0, 0, 0, 0], index=[fn_file[:-4] for fn_file in fn_files])\n with open(sample_file, \"r\", encoding=\"UTF-8\", errors=\"ignore\") as f:\n source = f.read()\n for i in range(0, len(fn)):\n for item in fn[i]:\n of[str(fn.index[i])] += len(re.findall(item, source))\n return of\n\n\ndef analyze_feature(file_name):\n \"\"\"\n @author: hanchenchen\n @date: 9/23/2018\n @function:\n @version: 2.0\n \"\"\"\n text_feature_set.append(text_feature(file_name))\n other_feature_set.append(other_feature(file_name))\n\n\ndef main():\n \"\"\"\n @author: hanchenchen\n @date: 9/26/2018\n @function: 多线程分析样本特征\n @version: 1.0\n \"\"\" \n \n \"\"\"\n # singleprocess\n start_time = time.time() \n sample_files_path = php_fn.project_path + \"/res/samples/\"\n files = os.listdir(sample_files_path)\n for file in files:\n analyze_feature(sample_files_path + file)\n end_time = time.time()\n print(\"singleprocess needs \" + str(end_time - start_time) + \"s\")\n \"\"\"\n \n # multiprocess\n start_time = time.time() \n sample_files_path = php_fn.project_path + \"/res/samples/\"\n files = os.listdir(sample_files_path)\n pool = multiprocessing.Pool()\n for file in files:\n pool.apply_async(analyze_feature, [sample_files_path+file])\n pool.close()\n pool.join()\n end_time = time.time()\n print(\"分析样本特征成功!耗时:%.3f s\" % (end_time - start_time))\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"webshell/src/analyze_feature.py","file_name":"analyze_feature.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"177152055","text":"\"\"\"\nЗадание:\n1) В файле, содержащем фамилии студентов и их оценки, изменить на прописные буквы фамилии тех студентов, которые имеют\nсредний балл за национальной шкалой более «4».\n\"\"\"\npath_1 = \"Task_1/file.txt\"\n\n\ndef average_score(filename):\n students = []\n grades = []\n sum_grades = []\n student = []\n with open(filename, \"r\", encoding=\"utf8\") as open_file:\n for line in open_file:\n for i in line:\n if i.isdigit():\n sum_grades.append(int(i))\n grades.append(i)\n elif i.isalpha():\n student.append(i)\n if (sum(sum_grades)/len(sum_grades)) < 4:\n students.append({\"student\": \"\".join(student), \"grades\": grades})\n else:\n students.append({\"student\": (\"\".join(student)).lower(), \"grades\": grades})\n sum_grades = []\n grades = []\n student = []\n print(students)\n\n with open(filename, \"w\", encoding=\"utf8\") as write_file:\n for i in range(len(students)):\n write_file.write(f\"{students[i]['student']} - {', '.join(students[i]['grades'])}\\n\")\n\n\naverage_score(path_1)\n\n\"\"\"\n2) Из текстового файла удалить все слова, содержащие от трех до пяти символов, но при этом из каждой строки должно быть\nудалено только четное количество таких слов.\n\"\"\"\npath_2 = \"Task_2/file.txt\"\n\n\ndef delete_small_words(filename):\n lines = []\n with open(filename, \"r\", encoding=\"utf8\") as open_file:\n for line in open_file:\n current_line = line.split()\n count = 0\n for word in current_line:\n if 3 <= len(word) <= 5:\n count += 1\n\n if count % 2 == 0:\n for idx, word in enumerate(current_line):\n if 3 <= len(word) <= 5:\n current_line.pop(idx)\n lines.append(current_line)\n\n if count % 2 != 0:\n for idx, word in enumerate(current_line):\n if 3 <= len(word) <= 5 and count != 1:\n current_line.pop(idx)\n count -= 1\n lines.append(current_line)\n\n with open(filename, \"w\", encoding=\"utf8\") as write_file:\n for i in range(len(lines)):\n write_file.write(f\"{' '.join(x for x in lines[i])}\\n\")\n\n\ndelete_small_words(path_2)\n\n\"\"\"\n3) Из текста программы выбрать все числа (целые и вещественные) и записать их в файл g в виде: число 1 – номер строки,\nчисло 2 – номер строки и так далее.\nВ качестве выполненного ДЗ отправить ссылку на проект GitHub в котором будет находится код.\n\"\"\"\npath_3 = \"Task_3/file.txt\"\n\n\ndef numbers(filename):\n digits = []\n current_line = 0\n with open(f\"{filename}\", \"r\", encoding=\"utf-8\") as open_file:\n for line in open_file:\n numbers_list = line.split()\n current_line += 1\n\n for i in numbers_list:\n digit = ''.join([char for char in i if char.isdigit() or char == '.'])\n if digit:\n digits.append({\"number\": digit, \"line\": current_line})\n\n open_file.close()\n\n with open(\"Task_3/g.txt\", \"w\", encoding=\"utf8\") as write_file:\n for i in range(len(digits)):\n write_file.write(f\"Число {digits[i]['number']} - строка {digits[i]['line']}\\n\")\n\n\nnumbers(path_3)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"545142506","text":"import sys\nimport copy\nimport itertools\nsys.path.append('../intcode')\n\nimport intcode\n\nwith open(\"day17.input\") as file:\n program = [int(val) for val in file.read().split(',')]\n\nsystem = intcode.IntCode()\nsystem.load_program(program)\n\nin_queue = system.get_input_queue()\nout_queue = system.get_output_queue()\n\nship_map = {}\n\nsystem.run_program()\n\ndef read_map(out_queue, ship_map, do_print):\n pos = (0,0)\n robot_pos = None\n robot_dir = None\n was_newline = False\n map_done = False\n while not out_queue.empty():\n obj = chr(out_queue.get())\n if do_print:\n print(obj, end='')\n if obj == '\\n':\n if was_newline:\n map_done = True\n else:\n was_newline = True\n pos = (0, pos[1]+1)\n elif not map_done:\n was_newline = False\n if obj == '#':\n ship_map[pos] = {'visits': 0, 'allowed_visits': 1}\n elif obj == '^':\n robot_pos = pos\n robot_dir = (0,-1)\n ship_map[pos] = {'visits': 0, 'allowed_visits': 1}\n pos = (pos[0]+1, pos[1])\n return robot_pos, robot_dir\n\ndef read_map2(ship_map):\n with open(\"day17.part2.input.example\") as file:\n robot_pos = None\n robot_dir = None\n pos = (0,0)\n for line in file:\n for obj in line.rstrip():\n if obj == '#':\n ship_map[pos] = {'visits': 0, 'allowed_visits': 1}\n elif obj == '^':\n robot_pos = pos\n robot_dir = (0,-1)\n ship_map[pos] = {'visits': 0, 'allowed_visits': 1}\n pos = (pos[0]+1, pos[1])\n pos = (0, pos[1]+1)\n return robot_pos, robot_dir\n\ndef is_corner(ship_map, pos):\n total_num_paths = 0\n for step in [(1,0),(0,1)]:\n next_pos1 = (pos[0] + step[0], pos[1] + step[1])\n next_pos2 = (pos[0] - step[0], pos[1] - step[1])\n num_paths = 0\n if ((next_pos1 in ship_map and next_pos2 in ship_map) or\n (next_pos1 not in ship_map and next_pos2 not in ship_map)):\n return False\n return True\n\ndef is_end(ship_map, pos):\n num_paths = 0\n for step in [(1,0),(-1,0),(0,1),(0,-1)]:\n num_paths += 1 if (pos[0] + step[0], pos[1] + step[1]) in ship_map else 0\n return num_paths == 1\n\ndef get_nodes(ship_map, robot_pos):\n checksum = 0\n nodes = {robot_pos:{}}\n for pos in ship_map:\n if (((pos[0] + 1, pos[1]) in ship_map) and\n ((pos[0] - 1, pos[1]) in ship_map) and\n ((pos[0], pos[1] + 1) in ship_map) and\n ((pos[0], pos[1] - 1) in ship_map)):\n checksum += pos[0]*pos[1]\n elif is_end(ship_map, pos) or is_corner(ship_map, pos):\n nodes[pos] = None\n return nodes,checksum\n\ndef find_next_node(ship_map, nodes, node_pos, prev = None):\n search_dirs = [(1,0),(-1,0),(0,1),(0,-1)]\n for direction in search_dirs:\n for length in itertools.count(1):\n next_pos = (node_pos[0] + direction[0] * length, node_pos[1] + direction[1] * length)\n if not next_pos in ship_map:\n if length > 1:\n next_pos = (node_pos[0] + direction[0] * (length - 1), node_pos[1] + direction[1] * (length - 1))\n if next_pos != prev:\n return next_pos,direction,(length-1)\n break\n return None,None,None\n\ndef get_turn(current_direction, next_direction):\n directions = [(0,-1), (1,0), (0,1), (-1,0)]\n if ((directions.index(current_direction) + 1) % len(directions)) == directions.index(next_direction):\n return \"R\"\n else:\n return \"L\"\n\ndef get_path(ship_map, nodes, robot_pos, robot_dir):\n prev_node = None\n cur_node = robot_pos\n cur_dir = robot_dir\n path = []\n while True:\n next_node,next_dir,length = find_next_node(ship_map, nodes, cur_node, prev_node)\n if not next_node:\n return path\n\n path.append(get_turn(cur_dir, next_dir))\n path.append(str(length))\n\n nodes[cur_node] = next_node\n prev_node = cur_node\n cur_node = next_node\n cur_dir = next_dir\n\ndef input_string(string, in_queue):\n for ch in string:\n in_queue.put(ord(ch))\n in_queue.put(ord('\\n'))\n\nprogram[0] = 2\nsystem.load_program(program)\nsystem.run_program()\n\nrobot_pos, robot_dir = read_map(out_queue, ship_map, True)\n#robot_pos, robot_dir = read_map2(ship_map)\nnodes, checksum = get_nodes(ship_map, robot_pos)\nprint(\"Alignemnt calibration=%u\" % (checksum))\npath = get_path(ship_map, nodes, robot_pos, robot_dir)\nprint(''.join(path))\n\nA=\"R,8,L,4,R,4,R,10,R,8\"\nB=\"L,12,L,12,R,8,R,8\"\nC=\"R,10,R,4,R,4\"\nseq=\"A,A,B,C,B,C,B,C,C,A\"\n\ninput_string(seq, in_queue)\ninput_string(A, in_queue)\ninput_string(B, in_queue)\ninput_string(C, in_queue)\ninput_string(\"n\", in_queue)\nsystem.run_program()\nwhile not out_queue.empty():\n data = out_queue.get()\n if data > 400:\n print(data)\n else:\n print(chr(data), end='')\n","sub_path":"17/day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"464506944","text":"from PyQt5.QtWidgets import QLabel\nfrom PyQt5.QtCore import Qt, QPoint, QThread, QMutex\nfrom PyQt5.QtGui import QPixmap, QPainter, QPen, QColor\nimport cv2\nfrom Board.ImgProcess import ImgProcess\nimport threading\n\n'''暂未完成的功能(1)\nclass ColorizeThread(QThread):\n def __init__(self, colSignal, showSignal, img_sket, img_style):\n super().__init__()\n self.mutex = QMutex()\n self.colSignal = colSignal\n self.showSignal = showSignal\n self.img_sket = img_sket\n self.img_style = img_style\n\n def run(self):\n self.mutex.lock()\n self.colSignal.emit(self.img_sket, self.img_style)\n self.showSignal.emit()\n self.mutex.unlock()\n'''\n\nclass DrawingBoard(QLabel, ImgProcess):\n pen = 0\n eraser = 1\n def __init__(self, parent=None):\n super().__init__(parent)\n\n # 鼠标移动事件的起点与终点\n self.startPos = QPoint(0, 0)\n self.endPos = QPoint(0, 0)\n self.leftMousePress = False\n\n self.imgLayer = None # 线稿图层,用于显示原线稿(QPixmap对象)\n self.paintLayer = QPixmap(200, 200) # 画板图层,用于交互涂色\n self.paintLayer.fill(Qt.transparent)\n\n self.imgLoc = (0, 0) # 图层的左上角坐标\n\n # 画笔参数\n self.penCol = \"#87CEFA\"\n self.penDiameter = 15\n\n self.using = self.pen\n\n # 信号传递器\n self.paintComplete = None\n\n def mousePressEvent(self, QMouseEvent):\n if QMouseEvent.button() == Qt.LeftButton:\n self.leftMousePress = True\n self.startPos = QMouseEvent.pos()\n self.endPos = self.startPos\n\n def mouseReleaseEvent(self, QMouseEvent):\n if QMouseEvent.button() == Qt.LeftButton:\n self.leftMousePress = False\n # 获取涂色后的线稿\n if self.imgLayer != None:\n self.downloadImg()\n\n def mouseMoveEvent(self, QMouseEvent):\n if self.leftMousePress:\n self.endPos = QMouseEvent.pos()\n self.update()\n\n def downloadImg(self):\n \"\"\"获取用户涂色后的图片并传递给上色AI\"\"\"\n\n ''' 暂未完成的功能(2)\n def colorizeThread(img_bottom, img_style):\n self.paintComplete.colorizeSignal.emit(img_bottom, img_style)\n self.paintComplete.showSignal.emit()\n '''\n\n img_bottom = self.Qimg2opencv(self.imgLayer) # 将QPixmap对象转化为opencv对象\n img_top = self.Qimg2opencv(self.paintLayer)\n img_style = self.coverImg(img_bottom.copy(), img_top.copy()) # 画板覆盖在原线稿上\n\n ''' 暂未完成的功能(1)——AI上色时左侧画板可继续涂写(QThread)\n self.colThread = ColorizeThread(\n self.paintComplete.colorizeSignal,\n self.paintComplete.showSignal,\n img_bottom, img_style)\n self.colThread.start()\n '''\n\n ''' 暂未完成的功能(2)——AI上色时左侧画板可继续涂写(threading)\n threading.Thread(target=colorizeThread, args=(img_bottom, img_style), daemon=True).start()\n '''\n\n self.paintComplete.waitSignal.emit()\n self.paintComplete.colorizeSignal.emit(img_bottom, img_style)\n self.paintComplete.showSignal.emit()\n\n def revealImg(self):\n def checkPos(pos):\n '''检查画笔坐标是否越界'''\n if pos.x() < self.imgLoc[0]:\n return False\n if pos.x() > self.imgLoc[0] + self.paintLayer.width():\n return False\n if pos.y() < self.imgLoc[1]:\n return False\n if pos.y() > self.imgLoc[1] + self.paintLayer.height():\n return False\n return True\n\n # 图片适应画板大小\n scale_x = (self.width() - 80) / self.imgLayer.width()\n scale_y = (self.height() - 80) / self.imgLayer.height()\n scale = min(scale_x, scale_y)\n\n size = self.imgLayer.size()\n self.imgLayer = self.imgLayer.scaled(scale * size)\n self.paintLayer = self.paintLayer.scaled(scale * size)\n\n # 图片居中,记录左上角坐标\n x = int((self.width() - self.imgLayer.width()) / 2)\n y = int((self.height() - self.imgLayer.height()) / 2)\n self.imgLoc = (x, y)\n\n '''在画板图层涂色'''\n qp = QPainter(self.paintLayer)\n qp.begin(self.paintLayer)\n\n # 设置画笔\n if self.using == self.pen:\n col = QColor(self.penCol)\n elif self.using == self.eraser:\n col = QColor(Qt.white)\n pen = QPen(col, self.penDiameter, Qt.SolidLine)\n qp.setPen(pen)\n\n # 沿轨迹涂色\n if self.startPos != self.endPos and checkPos(self.startPos) and checkPos(self.endPos):\n diff = QPoint(self.imgLoc[0], self.imgLoc[1])\n qp.drawLine(self.startPos - diff, self.endPos - diff)\n\n qp.end()\n\n self.startPos = self.endPos\n\n '''重新显示线稿图层与画板图层'''\n painter = QPainter(self)\n painter.begin(self)\n\n x, y = self.imgLoc[:]\n painter.drawPixmap(x, y, self.imgLayer)\n painter.drawPixmap(x, y, self.paintLayer)\n\n painter.end()\n\n def paintEvent(self, QPaintEvent):\n super().paintEvent(QPaintEvent)\n\n if self.imgLayer != None:\n self.revealImg()\n\n def loadImg(self, fpath):\n img = cv2.imread(fpath, 1)\n pixmap = self.opencv2Qimg(img)\n\n self.imgLayer = pixmap\n\n self.paintLayer.fill(Qt.transparent)\n self.paintLayer = self.paintLayer.scaled(\n self.imgLayer.width(), self.imgLayer.height())\n\n self.update()","sub_path":"Board/DrawingBoard.py","file_name":"DrawingBoard.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"56010744","text":"# -*- coding: utf-8 -*-\n\"\"\"Application configuration.\n\nMost configuration is set via environment variables.\n\nFor local development, use a .env file to set\nenvironment variables.\n\"\"\"\nimport os\n\nfrom environs import Env\n\nENV = Env()\nENV.read_env()\n\nPROJECT_ROOT: str = os.path.join(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir), os.pardir\n)\nTEST_PATH: str = os.path.join(PROJECT_ROOT, \"tests\")\nFLASK_ENV: str = ENV.str(\"FLASK_ENV\", default=\"production\")\nDEBUG: bool = FLASK_ENV == \"development\" # if flask environment is development set debug to True\nSQLALCHEMY_DATABASE_URI = ENV.str(\"DATABASE_URL\")\nSECRET_KEY = ENV.str(\"SECRET_KEY\")\nBCRYPT_LOG_ROUNDS = ENV.int(\"BCRYPT_LOG_ROUNDS\", default=13)\nDEBUG_TB_ENABLED = DEBUG\nDEBUG_TB_INTERCEPT_REDIRECTS: bool = False\nCACHE_TYPE: str = \"simple\" # Can be \"memcached\", \"redis\", etc.\nSQLALCHEMY_TRACK_MODIFICATIONS: bool = False\nWEBPACK_MANIFEST_PATH: str = \"webpack/manifest.json\"\nJWT_SECRET_KEY: str = ENV.str(\n \"JWT_SECRET_KEY\", default=SECRET_KEY\n) # If this is not set, we use the flask SECRET_KEY value instead.\nREFRESH_EXP_LENGTH: int = ENV.int(\"REFRESH_EXP_LENGTH\", default=30)\nACCESS_EXP_LENGTH: int = ENV.int(\"ACCESS_EXP_LENGTH\", default=10)\n","sub_path":"src/config/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"480352052","text":"import sys\n\nfrom typing import Optional, List, Generator\n\nif sys.version_info >= (3, 8):\n from typing import TypedDict # pylint: disable=no-name-in-module\nelse:\n from typing_extensions import TypedDict\n\nfrom .base import Detector\nfrom ..filth.known import KnownFilth\n\nKnownFilthItem = TypedDict(\n 'KnownFilthItem',\n {'match': str, 'match_end': Optional[str], 'limit': Optional[int], 'filth_type': Optional[str]},\n total=False,\n)\n\n\nclass KnownFilthDetector(Detector):\n \"\"\"Use some predefined phrases to label the text.\n\n This is useful if you have found that some particular\n type of PII occurs regularly or you want to compare\n scrubadub with already selected PII.\n \"\"\"\n\n filth_cls = KnownFilth\n name = 'known'\n\n def __init__(self, known_filth_items: Optional[List[KnownFilthItem]] = None, **kwargs):\n super().__init__(**kwargs)\n if known_filth_items is None:\n known_filth_items = []\n self._known_filth_items = known_filth_items\n\n def _find_all(\n self,\n text: str,\n substr: str,\n comparison_type: Optional[str] = None,\n document_name: Optional[str] = None\n ) -> Generator[KnownFilth, None, None]:\n \"\"\"Yield filth for each match to substr in text.\"\"\"\n substr_len = len(substr)\n start_location = text.find(substr)\n\n while start_location >= 0:\n yield KnownFilth(\n start_location,\n start_location + substr_len,\n text[start_location:start_location + substr_len],\n comparison_type=comparison_type,\n detector_name=self.name,\n document_name=document_name,\n )\n start_location = text.find(\n substr,\n start_location + substr_len\n )\n\n def _find_all_between(\n self,\n text: str,\n substr_start: str,\n substr_end: str,\n limit: int = 150,\n comparison_type: Optional[str] = None,\n document_name: Optional[str] = None\n ) -> Generator[KnownFilth, None, None]:\n \"\"\"Yield filth for text between (and including)\n substr_start and substr_end, but only if the text\n between the two is less than limit characters.\n \"\"\"\n substr_start_len = len(substr_start)\n substr_end_len = len(substr_end)\n start_location = text.find(substr_start)\n\n while start_location >= 0:\n end_location = text.find(\n substr_end,\n start_location + substr_start_len,\n start_location + substr_start_len + limit + substr_end_len\n )\n if end_location >= 0:\n yield KnownFilth(\n start_location,\n end_location + substr_end_len,\n text[start_location:end_location + substr_end_len],\n comparison_type=comparison_type,\n detector_name=self.name,\n document_name=document_name,\n )\n next_search_start = end_location + substr_end_len\n else:\n next_search_start = start_location + substr_start_len\n\n start_location = text.find(substr_start, next_search_start)\n\n def iter_filth(\n self,\n text: str,\n document_name: Optional[str] = None\n ) -> Generator[KnownFilth, None, None]:\n \"\"\"Iterate over the predefined PII list and yield\n filth instances.\"\"\"\n for pii_item in self._known_filth_items:\n # could also implement other types in here too\n if 'match' in pii_item and 'match_end' in pii_item and pii_item['match_end'] is not None:\n for found_item in self._find_all_between(\n text,\n pii_item['match'],\n pii_item['match_end'],\n limit=int(pii_item.get('limit', 150) or 150),\n comparison_type=pii_item.get('filth_type', None),\n document_name=document_name,\n ):\n yield found_item\n elif 'match' in pii_item:\n for found_item in self._find_all(\n text,\n pii_item['match'],\n comparison_type=pii_item.get('filth_type', None),\n document_name=document_name,\n ):\n yield found_item\n else:\n raise ValueError(\n \"Unknown keys in predefined PII item: \"\n \"{}\".format(pii_item.keys())\n )\n","sub_path":"scrubadub/detectors/known.py","file_name":"known.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"444569582","text":"from qlib.web import CMESP500Scraper\nfrom datetime import datetime\n\n\nif __name__ == '__main__':\n run_date = datetime.today().strftime('%Y%m%d')\n\n scraper = CMESP500Scraper()\n scraper.load_all()\n\n data_dir = r'/home/yue/study/OptionStrategies/data/CMESP500'\n\n print(\"Loaded {} futures contracts\".format(scraper.futures_data.shape[0]))\n scraper.futures_data.to_csv('{}/CMESP500Futures_{}.csv'.format(data_dir, run_date), index=False)\n\n print(\"Loaded {} options contracts\".format(scraper.options_data.shape[0]))\n scraper.options_data.to_csv('{}/CMESP500Options_{}.csv'.format(data_dir, run_date), index=False)\n","sub_path":"python-package/scripts/download_cme_sp500.py","file_name":"download_cme_sp500.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"351422048","text":"'''Codificação run-lenght. Escreva uma função recursiva que implemente a técnica de\ncompressão run-lenght descrita no exercício anterior. Sua função deve receber uma lista ou\numa string como seu único parâmetro. Ela deve retornar a lista compactada em run-lenght\ncomo seu único resultado. Inclua um programa principal que leia uma string do usuário, a\ncompacte e exiba o resultado codificado em run-lenght.'''\n\ndef mapear(x):\n if x.isdigit() == False:\n return x \n\ndef is_null(str):\n if str.isdigit() == False:\n return True\n else:\n return False\n\ndef cod_run_lenght(string):\n if type(string) == str:\n resultado = map(mapear,filter(is_null,string))\n resultado = list(resultado)\n return cod_run_lenght([resultado,[]])\n\n elif len(string[0]) != 0:\n x = string[0]\n index = string[1]\n letra = x[0]\n if index == []:\n index.append(letra)\n index.append(0)\n if index[-2] == letra:\n index[-1] = index[-1]+1\n if index[-2] != letra:\n index.append(letra)\n index.append(1)\n x.pop(0)\n return cod_run_lenght([x,index])\n else:\n return string[1]\n\nprint(f'Decodificada = {cod_run_lenght(\"AAAAAABBAAACCAABVBB\")}')","sub_path":"Lista 8/EBSS-AER-Alg-08-Ex-11.py","file_name":"EBSS-AER-Alg-08-Ex-11.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"165797670","text":"from pandas2pygal import pandas_to_pygal_Bar, colour_dict\nimport pandas2pygal\nimport pandas\nfrom pygal.style import Style\n\ndata_path = \"./data/Sample - Superstore Sales (Excel).xlsx\"\ndata = pandas.read_excel(data_path, sheet_name = \"Orders\")\nprint(data.columns)\n\npyg = pandas_to_pygal_Bar(\n data = data,\n groupby1 = 'Region',\n aggregate = 'Sales',\n colourstyle= colour_dict[\"RedBlueStyle\"],\n decimal_places=0,\n print_values = False,\n rounded_bars = 0,\n title = \"Test Bar Chart\",\n value_suffix = \"\",\n x_label_rotation = 0,\n legend_at_bottom=True,\n legend_at_bottom_columns = 3,\n horizontal = False,\n agg_type = \"sum\")\n\npyg.render_in_browser()","sub_path":"test_pandas2pygal.py","file_name":"test_pandas2pygal.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"242448332","text":"\"\"\"\nThis class models the form on contact page\nThe form consists of some input fields.\n\"\"\"\n\nfrom .Base_Page import Base_Page\nimport conf.locators_conf as locators\nfrom utils.Wrapit import Wrapit\n\nclass Contact_Form_Object:\n \"Page object for the contact Form\"\n\n #locators\n #contact_name_field = locators.contact_name_field\n FORM_EMAIL_ID = locators.FORM_EMAIL_ID\n FORM_ACCOUNT_NUMBER = locators.FORM_ACCOUNT_NUMBER\n FORM_EXPIRY_DATE = locators.FORM_EXPIRY_DATE\n FORM_CVV = locators.FORM_CVV\n FORM_ZIP_CODE = locators.FORM_ZIP_CODE\n FORM_REMEMBER_ME = locators.FORM_REMEMBER_ME\n FORM_MOBILE = locators.FORM_MOBILE\n FORM_SUBMIT = locators.FORM_SUBMIT\n\n @Wrapit._exceptionHandler\n def set_name(self,name):\n \"Set the name on the Kick start form\"\n result_flag = self.set_text(self.contact_name_field,name)\n self.conditional_write(result_flag,\n positive='Set the name to: %s'%name,\n negative='Failed to set the name in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_email(self,email):\n \"Set the email on the form\"\n result_flag = self.set_text(self.FORM_EMAIL_ID,email)\n self.conditional_write(result_flag,\n positive='Set the email to: %s'%email,\n negative='Failed to set the email in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_account_number(self,account_number):\n \"Set the account number on the form\"\n result_flag = self.set_text(self.FORM_ACCOUNT_NUMBER,account_number)\n self.conditional_write(result_flag,\n positive='Set the account number to: %s'%account_number,\n negative='Failed to set the account number in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_expiry_date(self,expiry_date):\n \"Set the expiry date on the form\"\n result_flag = self.set_text(self.FORM_EXPIRY_DATE,expiry_date)\n self.conditional_write(result_flag,\n positive='Set the expiry date to: %s'%expiry_date,\n negative='Failed to set the expiry date in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_cvv(self,cvv):\n \"Set the cvv on the form\"\n result_flag = self.set_text(self.FORM_CVV,cvv)\n self.conditional_write(result_flag,\n positive='Set the cvv to: %s'%cvv,\n negative='Failed to set the cvv in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_zip_code(self,zip_code):\n \"Set the zip code on the form\"\n result_flag = self.set_text(self.FORM_ZIP_CODE,zip_code)\n self.conditional_write(result_flag,\n positive='Set the zip code to: %s'%zip_code,\n negative='Failed to set the zip code in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._exceptionHandler\n def set_mobile(self,mobile):\n \"Set the mobile number on the form\"\n result_flag = self.set_text(self.FORM_MOBILE,mobile)\n self.conditional_write(result_flag,\n positive='Set the mobile number to: %s'%mobile,\n negative='Failed to set the mobile number in the form',\n level='debug')\n\n return result_flag\n\n @Wrapit._screenshot\n def click_pay_button(self):\n \"Click the pay button\"\n result_flag = self.click_element(self.FORM_SUBMIT)\n self.conditional_write(result_flag,\n positive=\"Clicked on the pay button\",\n negative=\"Could not click on the pay button\")\n\n return result_flag","sub_path":"page_objects/contact_form_object.py","file_name":"contact_form_object.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"291895124","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import xrange\n\nfrom util import log\nfrom pprint import pprint\n\nfrom model import Model\nfrom input_ops import create_input_ops\n\nimport os\nimport time\nimport h5py\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport numpy as np\n\n\nclass Trainer(object):\n\n def __init__(self,\n config,\n dataset_train,\n dataset_test):\n self.config = config\n hyper_parameter_str = config.dataset+'_lr_'+str(config.learning_rate)\n self.train_dir = './train_dir/%s-%s-%s' % (\n config.prefix,\n hyper_parameter_str,\n time.strftime(\"%Y%m%d-%H%M%S\")\n )\n\n if not os.path.exists(self.train_dir):\n os.makedirs(self.train_dir)\n log.infov(\"Train Dir: %s\", self.train_dir)\n\n # --- input ops ---\n self.batch_size = config.batch_size\n\n _, self.batch_train = create_input_ops(dataset_train, self.batch_size,\n is_training=True)\n _, self.batch_test = create_input_ops(dataset_test, self.batch_size,\n is_training=False)\n\n # --- create model ---\n self.model = Model(config)\n\n # --- optimizer ---\n self.global_step = tf.contrib.framework.get_or_create_global_step(graph=None)\n self.learning_rate = config.learning_rate\n if config.lr_weight_decay:\n self.learning_rate = tf.train.exponential_decay(\n config.learning_rate,\n global_step=self.global_step,\n decay_steps=10000,\n decay_rate=0.5,\n staircase=True,\n name='decaying_learning_rate'\n )\n\n self.check_op = tf.no_op()\n\n # --- checkpoint and monitoring ---\n log.warn(\"********* var ********** \")\n slim.model_analyzer.analyze_vars(tf.trainable_variables(), print_info=True)\n\n self.g_optimizer = tf.contrib.layers.optimize_loss(\n loss=self.model.loss,\n global_step=self.global_step,\n learning_rate=self.learning_rate,\n optimizer=tf.train.AdamOptimizer,\n clip_gradients=20.0,\n name='g_optimizer_loss',\n )\n\n self.summary_op = tf.summary.merge_all()\n\n self.saver = tf.train.Saver(max_to_keep=1000)\n self.summary_writer = tf.summary.FileWriter(self.train_dir)\n\n self.checkpoint_secs = 600 # 10 min\n\n self.supervisor = tf.train.Supervisor(\n logdir=self.train_dir,\n is_chief=True,\n saver=None,\n summary_op=None,\n summary_writer=self.summary_writer,\n save_summaries_secs=300,\n save_model_secs=self.checkpoint_secs,\n global_step=self.global_step,\n )\n\n session_config = tf.ConfigProto(\n allow_soft_placement=True,\n gpu_options=tf.GPUOptions(allow_growth=True),\n device_count={'GPU': 1},\n )\n self.session = self.supervisor.prepare_or_wait_for_session(config=session_config)\n\n self.ckpt_path = config.checkpoint\n if self.ckpt_path is not None:\n log.info(\"Checkpoint path: %s\", self.ckpt_path)\n self.saver.restore(self.session, self.ckpt_path)\n log.info(\"Loaded the pretrain parameters from the provided checkpoint path\")\n\n def train(self, dataset):\n log.infov(\"Training Starts!\")\n pprint(self.batch_train)\n\n max_steps = 100000\n\n output_save_step = 1000\n\n for s in xrange(max_steps):\n step, summary, x, loss, loss_g_update, loss_z_update, step_time = \\\n self.run_single_step(self.batch_train, dataset, step=s, is_train=True)\n\n if s % 10 == 0:\n self.log_step_message(step, loss, loss_g_update, loss_z_update, step_time)\n\n self.summary_writer.add_summary(summary, global_step=step)\n\n if s % output_save_step == 0:\n log.infov(\"Saved checkpoint at %d\", s)\n save_path = self.saver.save(self.session,\n os.path.join(self.train_dir, 'model'),\n global_step=step)\n if self.config.dump_result:\n f = h5py.File(os.path.join(self.train_dir, 'dump_result_'+str(s)+'.hdf5'), 'w')\n f['image'] = x\n f.close()\n\n def run_single_step(self, batch, dataset, step=None, is_train=True):\n _start_time = time.time()\n\n batch_chunk = self.session.run(batch)\n\n # Optmize the generator {{{\n # ========\n fetch = [self.global_step, self.summary_op, self.model.loss,\n self.model.x_recon, self.check_op, self.g_optimizer]\n\n fetch_values = self.session.run(\n fetch, feed_dict=self.model.get_feed_dict(batch_chunk, step=step)\n )\n [step, summary, loss, x] = fetch_values[:4]\n # }}}\n\n # Optimize the latent vectors {{{\n fetch = [self.model.z, self.model.z_grad, self.model.loss]\n\n fetch_values = self.session.run(\n fetch, feed_dict=self.model.get_feed_dict(batch_chunk, step=step)\n )\n\n [z, z_grad, loss_g_update] = fetch_values\n\n z_update = z - self.config.alpha * z_grad[0]\n norm = np.sqrt(np.sum(z_update ** 2, axis=1))\n z_update_norm = z_update / norm[:, np.newaxis]\n\n loss_z_update = self.session.run(\n self.model.loss, feed_dict={self.model.x: batch_chunk['image'], self.model.z: z_update_norm}\n )\n for i in range(len(batch_chunk['id'])):\n dataset.set_data(batch_chunk['id'][i], z_update_norm[i, :])\n # }}}\n\n _end_time = time.time()\n\n return step, summary, x, loss, loss_g_update, loss_z_update, (_end_time - _start_time)\n\n def run_test(self, batch, is_train=False, repeat_times=8):\n\n batch_chunk = self.session.run(batch)\n\n loss = self.session.run(\n self.model.loss, feed_dict=self.model.get_feed_dict(batch_chunk, is_training=False)\n )\n\n return loss\n\n def log_step_message(self, step, loss, loss_g_update,\n loss_z_update, step_time, is_train=True):\n if step_time == 0:\n step_time = 0.001\n log_fn = (is_train and log.info or log.infov)\n log_fn((\" [{split_mode:5s} step {step:4d}] \" +\n \"Loss: {loss:.5f} \" +\n \"G update: {loss_g_update:.5f} \" +\n \"Z update: {loss_z_update:.5f} \" +\n \"({sec_per_batch:.3f} sec/batch, {instance_per_sec:.3f} instances/sec) \"\n ).format(split_mode=(is_train and 'train' or 'val'),\n step=step,\n loss=loss,\n loss_z_update=loss_z_update,\n loss_g_update=loss_g_update,\n sec_per_batch=step_time,\n instance_per_sec=self.batch_size / step_time\n )\n )\n\n\ndef check_data_path(path):\n if os.path.isfile(os.path.join(path, 'data.hy')) \\\n and os.path.isfile(os.path.join(path, 'id.txt')):\n return True\n else:\n return False\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type=int, default=16)\n parser.add_argument('--prefix', type=str, default='default')\n parser.add_argument('--checkpoint', type=str, default=None)\n parser.add_argument('--dataset', type=str, default='MNIST', choices=['MNIST', 'SVHN', 'CIFAR10'])\n parser.add_argument('--learning_rate', type=float, default=1e-4)\n parser.add_argument('--alpha', type=float, default=1.0)\n parser.add_argument('--lr_weight_decay', action='store_true', default=False)\n parser.add_argument('--dump_result', action='store_true', default=False)\n config = parser.parse_args()\n\n if config.dataset == 'MNIST':\n import datasets.mnist as dataset\n elif config.dataset == 'SVHN':\n import datasets.svhn as dataset\n elif config.dataset == 'CIFAR10':\n import datasets.cifar10 as dataset\n else:\n raise ValueError(config.dataset)\n\n config.conv_info = dataset.get_conv_info()\n config.deconv_info = dataset.get_deconv_info()\n dataset_train, dataset_test = dataset.create_default_splits()\n\n m, l = dataset_train.get_data(dataset_train.ids[0])\n config.data_info = np.concatenate([np.asarray(m.shape), np.asarray(l.shape)])\n\n trainer = Trainer(config,\n dataset_train, dataset_test)\n\n log.warning(\"dataset: %s, learning_rate: %f\",\n config.dataset, config.learning_rate)\n trainer.train(dataset_train)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Generative-Latent-Optimization-Tensorflow-master/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":8930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"438414206","text":"import json\nfrom unittest import TestCase, main\nfrom unittest.mock import patch, MagicMock\n\nfrom opengraph.opengraph import OpenGraph\n\nHTML = \"\"\"\n\n \n The Rock (1996)\n \n \n \n \n \n \n \n
hello world
\n \n\n\"\"\"\n\n\nHTML_WITH_MISSING_REQUIRED_ATTRS = \"\"\"\n\n \n The Rock (1996)\n \n \n \n \n \n
hello world
\n \n\n\"\"\"\n\n\nclass OpenGraphTests(TestCase):\n def test_parser(self):\n og = OpenGraph()\n og.parser(HTML)\n\n self.assertTrue(og.is_valid())\n self.assertDictEqual(\n og,\n {\n \"_url\": None,\n \"description\": \"movie description\",\n \"image\": \"http://ia.media-imdb.com/images/rock.jpg\",\n \"scrape\": False,\n \"title\": \"The Rock\",\n \"type\": \"movie\",\n \"url\": \"http://www.imdb.com/title/tt0117500/\"\n }\n )\n\n def test_parser_with_missing_required_attrs(self):\n og = OpenGraph()\n og.parser(HTML_WITH_MISSING_REQUIRED_ATTRS)\n\n self.assertFalse(og.is_valid())\n self.assertDictEqual(\n og,\n {\n \"_url\": None,\n \"scrape\": False,\n \"title\": \"The Rock\",\n \"type\": \"movie\",\n \"url\": \"http://www.imdb.com/title/tt0117500/\"\n }\n )\n\n def test_convert_to_json(self):\n og = OpenGraph()\n og.parser(HTML)\n\n json_encoded = og.to_json()\n\n self.assertIsInstance(json_encoded, str)\n\n decoded = json.loads(json_encoded)\n\n self.assertDictEqual(\n decoded,\n {\n \"_url\": None,\n \"description\": \"movie description\",\n \"image\": \"http://ia.media-imdb.com/images/rock.jpg\",\n \"scrape\": False,\n \"title\": \"The Rock\",\n \"type\": \"movie\",\n \"url\": \"http://www.imdb.com/title/tt0117500/\"\n }\n )\n\n def test_is_valid(self):\n og = OpenGraph()\n og.parser(HTML)\n\n self.assertTrue(og.is_valid())\n\n def test_is_valid_with_missing_required_attrs(self):\n og = OpenGraph()\n og.parser(HTML_WITH_MISSING_REQUIRED_ATTRS)\n\n self.assertFalse(og.is_valid())\n\n @patch(\"opengraph.opengraph.urlopen\")\n def test_open_url(self, urlopen_mock):\n read_mock = MagicMock()\n read_mock.read.return_value = HTML\n urlopen_mock.side_effect = lambda url: read_mock\n\n og = OpenGraph(url=\"http://www.example.com\")\n\n self.assertTrue(og.is_valid())\n self.assertDictEqual(\n og,\n {\n \"_url\": \"http://www.example.com\",\n \"description\": \"movie description\",\n \"image\": \"http://ia.media-imdb.com/images/rock.jpg\",\n \"scrape\": False,\n \"title\": \"The Rock\",\n \"type\": \"movie\",\n \"url\": \"http://www.imdb.com/title/tt0117500/\"\n }\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_opengraph.py","file_name":"test_opengraph.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"451702165","text":"import csv\nimport numpy\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nnum_iter = 500\nnum_reps = 75\nmax_allowed_qual = 5000\n\nfile = 'probabilistic_selection_test_500_iterations.csv'\n\nall_repetitions_data = []\n\nnum_lowtier_rules = 8\nnum_hightier_rules = 5\n\nchunk_size = 100\n\nrule_applications_a = []\nrule_acceptance_a = []\nrule_effectiveness_a = []\nrule_selection_chance_a = []\nrule_proportions_a = []\n\nfor i in range(0, int(num_iter/chunk_size)):\n rule_applications_a.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n rule_acceptance_a.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n rule_effectiveness_a.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n\nwith open(file, 'r') as sim_data_file:\n csv_reader = csv.DictReader(sim_data_file)\n\n valid_reps = []\n for row in csv_reader:\n if int(row['iteration']) == num_iter and float(row['current solution quality']) < max_allowed_qual and len(valid_reps) < num_reps:\n valid_reps.append(row['repetition'])\n\n print('')\n print(valid_reps)\n print('')\n print(len(valid_reps))\n print('')\n\n sim_data_file.seek(0)\n\n next(csv_reader)\n\n data_list = list(csv_reader)\n current_data_list_index = 0\n\n for repetition_index in range(0, len(valid_reps)):\n current_rep_num = valid_reps[repetition_index]\n current_rep_data = []\n\n for i in range(0, num_iter):\n current_rep_data.append([])\n\n for data_index in range(current_data_list_index, len(data_list)):\n row = data_list[data_index]\n current_data_list_index += 1\n if row['repetition'] == current_rep_num:\n rep = int(current_rep_num)\n iter = int(row['iteration'])\n tier = row['rule tier']\n rule = int(row['rule number'])\n acceptance = int(row['rule acceptance'])\n\n quality_before = float(row['quality before rule'])\n quality_after = float(row['quality after rule'])\n quality_change = quality_after - quality_before\n\n current_rep_data[int(row['iteration'])-1].append({'rep': rep,\n 'iter': iter,\n 'tier': tier,\n 'rule': rule,\n 'acceptance': acceptance,\n 'quality_change': quality_change})\n\n elif row['repetition'] in valid_reps:\n current_data_list_index -= 1\n break\n\n all_repetitions_data.append(current_rep_data)\n\nfor i in range(0, len(all_repetitions_data)):\n for j in range(0, len(all_repetitions_data[i])):\n iteration = all_repetitions_data[i][j][0]\n chunk = int((iteration['iter'] - 1) / chunk_size)\n\n if iteration['tier'] == 'low':\n rule_index = iteration['rule'] - 1\n elif iteration['tier'] == 'high':\n rule_index = iteration['rule'] - 2 + num_lowtier_rules\n\n rule_applications_a[chunk][rule_index] += 1\n\n if iteration['acceptance'] == 1:\n rule_acceptance_a[chunk][rule_index] += 1\n\nrule_effectiveness_a = numpy.divide(rule_acceptance_a, rule_applications_a)\nrule_selection_chance_a = numpy.divide(rule_applications_a, len(all_repetitions_data)*chunk_size)\n\nfor i in range(0, len(rule_acceptance_a)):\n total_accepted = sum(rule_acceptance_a[i])\n rule_proportions_a.append(numpy.divide(rule_acceptance_a[i], total_accepted))\n\nerror_a = []\n\nfor chunk in rule_proportions_a:\n error_a.append(stats.sem(chunk))\n\n# print(rule_applications_a)\n# print(rule_acceptance_a)\n# print(rule_effectiveness_a)\n# print(rule_selection_chance_a)\n# print(rule_proportions_a)\n# print('')\n\nfile = 'probabilistic_selection_test_500_iterations.csv'\n\nall_repetitions_data = []\n\nrule_applications_b = []\nrule_acceptance_b = []\nrule_effectiveness_b = []\nrule_selection_chance_b = []\nrule_proportions_b = []\n\nfor i in range(0, int(num_iter/chunk_size)):\n rule_applications_b.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n rule_acceptance_b.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n rule_effectiveness_b.append(numpy.zeros(num_lowtier_rules+num_hightier_rules))\n\nwith open(file, 'r') as sim_data_file:\n csv_reader = csv.DictReader(sim_data_file)\n\n valid_reps = []\n for row in csv_reader:\n if int(row['iteration']) == num_iter and float(row['current solution quality']) < max_allowed_qual and len(valid_reps) < num_reps:\n valid_reps.append(row['repetition'])\n\n print('')\n print(valid_reps)\n print('')\n print(len(valid_reps))\n print('')\n\n sim_data_file.seek(0)\n\n next(csv_reader)\n\n data_list = list(csv_reader)\n current_data_list_index = 0\n\n for repetition_index in range(0, len(valid_reps)):\n current_rep_num = valid_reps[repetition_index]\n current_rep_data = []\n\n for i in range(0, num_iter):\n current_rep_data.append([])\n\n for data_index in range(current_data_list_index, len(data_list)):\n row = data_list[data_index]\n current_data_list_index += 1\n if row['repetition'] == current_rep_num:\n rep = int(current_rep_num)\n iter = int(row['iteration'])\n tier = row['rule tier']\n rule = int(row['rule number'])\n acceptance = int(row['rule acceptance'])\n\n quality_before = float(row['quality before rule'])\n quality_after = float(row['quality after rule'])\n quality_change = quality_after - quality_before\n\n current_rep_data[int(row['iteration'])-1].append({'rep': rep,\n 'iter': iter,\n 'tier': tier,\n 'rule': rule,\n 'acceptance': acceptance,\n 'quality_change': quality_change})\n\n elif row['repetition'] in valid_reps:\n current_data_list_index -= 1\n break\n\n all_repetitions_data.append(current_rep_data)\n\nfor i in range(0, len(all_repetitions_data)):\n for j in range(0, len(all_repetitions_data[i])):\n iteration = all_repetitions_data[i][j][0]\n chunk = int((iteration['iter'] - 1) / chunk_size)\n\n if iteration['tier'] == 'low':\n rule_index = iteration['rule'] - 1\n elif iteration['tier'] == 'high':\n rule_index = iteration['rule'] - 2 + num_lowtier_rules\n\n rule_applications_b[chunk][rule_index] += 1\n\n if iteration['acceptance'] == 1:\n rule_acceptance_b[chunk][rule_index] += 1\n\nrule_effectiveness_b = numpy.divide(rule_acceptance_b, rule_applications_b)\nrule_selection_chance_b = numpy.divide(rule_applications_b, len(all_repetitions_data)*chunk_size)\n\nfor i in range(0, len(rule_acceptance_b)):\n total_accepted = sum(rule_acceptance_b[i])\n rule_proportions_b.append(numpy.divide(rule_acceptance_b[i], total_accepted))\n\nerror_b = []\n\nfor chunk in rule_proportions_b:\n error_b.append(stats.sem(chunk))\n\n# print(rule_applications_b)\n# print(rule_acceptance_b)\n# print(rule_effectiveness_b)\n\n#######################################################################################################################\n#######################################################################################################################\n\nchunk_labels = ('1', '2', '3', '4', '5')\ny_pos = numpy.arange(len(chunk_labels))\nbar_width = 0.35\n\n# for rule in range(0, num_lowtier_rules + num_hightier_rules):\n# effectiveness_a = []\n# effectiveness_b = []\n# for chunk in rule_proportions_a:\n# effectiveness_a.append(chunk[rule])\n# for chunk in rule_proportions_b:\n# effectiveness_b.append(chunk[rule])\n# plt.bar(y_pos, effectiveness_a, bar_width, color='g', align='center', alpha=0.5, label='Random Selection')\n# # plt.bar(y_pos+bar_width, effectiveness_b, bar_width, color='c', align='center', alpha=0.5, label='Probabilistic Selection')\n# # plt.errorbar(y_pos, effectiveness_a, yerr=error_a, color='g', alpha=0.5, fmt='o')\n# # plt.errorbar(y_pos + bar_width, effectiveness_b, yerr=error_b, color='c', alpha=0.5, fmt='o')\n# plt.xticks(y_pos, chunk_labels)\n# plt.ylim(0, 0.75)\n# plt.grid()\n# plt.xlabel('Iteration Chunk (Every 100 Iter.)')\n# plt.ylabel('Acceptance Rate of Applied Rule')\n# plt.legend(loc=1)\n#\n # if rule < 8:\n # plt.title('Lower-Tier Rule: ' + str(rule+1))\n # else:\n # plt.title('Higher-Tier Rule: ' + str(rule-7))\n# print(effectiveness_a)\n# print(effectiveness_b)\n# plt.show()\n\nall_rule_proportions = []\n\nfor rule in range(0, num_lowtier_rules + num_hightier_rules):\n proportion = []\n for chunk in rule_proportions_a:\n proportion.append(chunk[rule])\n all_rule_proportions.append(proportion)\n\nprint(all_rule_proportions)\n\ncolors = [(0.8, 0, 0), (0, 0.8, 0), (0, 0, 0.8), (0.8, 0.8, 0), (0.8, 0, 0.8), (0, 0.8, 0.8), (0.8, 0.4, 0.4), (0.4, 0.8, 0.4),\n (0.4, 0.4, 0.8), (0.8, 0.2, 0.4), (0.2, 0.2, 0), (0.8, 1.0, 0.4), (0.9, 0.6, 0.2)]\nlast_bottom = numpy.zeros(len(rule_proportions_a))\n\nfor rule_index in range(0, len(all_rule_proportions)):\n rule = all_rule_proportions[rule_index]\n if rule_index < 8:\n rule_name = \"LT Rule: \"+ str(rule_index+1)\n else:\n rule_name = \"HT Rule: \"+str(rule_index-7)\n plt.bar(y_pos, rule, bar_width, color=colors[rule_index], bottom=last_bottom, align='center', alpha=0.5, label=rule_name)\n plt.xticks(y_pos, chunk_labels)\n plt.ylim(0, 1.0)\n plt.xlabel('Iteration Chunk (Every 100 Iter.)')\n plt.ylabel('Proportion')\n plt.title('Proportion of Each Rule Within All Accepted Rules per Chunk (Random Rule Selection)')\n plt.legend(loc=1)\n\n last_bottom += rule\n\nplt.grid()\nplt.show()\n\n#######################################################################################################################\n#######################################################################################################################\n\nlumped_proportions = numpy.zeros(5)\nbest_rules = [4, 6, 7, 10, 12]\n\nfor rule_index in range(0, len(all_rule_proportions)):\n if rule_index not in best_rules:\n for chunk_index in range(len(rule_proportions_a)):\n lumped_proportions[chunk_index] += all_rule_proportions[rule_index][chunk_index]\n print(lumped_proportions)\n\nlumped_and_best_proportions = []\nlumped_and_best_proportions.append(lumped_proportions)\n\nfor index in best_rules:\n lumped_and_best_proportions.append(all_rule_proportions[index])\n\ncolors = [(0.5, 0.4, 0.2), (0, 0.6, 0), (0, 0.2, 0.5), (0.7, 0.2, 0.1), (0.4, 0.8, 0.2), (0.8, 0.5, 0)]\nlast_bottom = numpy.zeros(len(rule_proportions_a))\n\nfor rule_index in range(0, len(lumped_and_best_proportions)):\n rule = lumped_and_best_proportions[rule_index]\n if rule_index == 0:\n rule_name = \"OTHER\"\n elif rule_index == 1:\n rule_name = 'LT Rule 5'\n elif rule_index == 2:\n rule_name = 'LT Rule 7'\n elif rule_index == 3:\n rule_name = 'LT Rule 8'\n elif rule_index == 4:\n rule_name = 'HT Rule 3'\n elif rule_index == 5:\n rule_name = 'HT Rule 5'\n plt.bar(y_pos, rule, bar_width, color=colors[rule_index], bottom=last_bottom, align='center', alpha=0.5,\n label=rule_name)\n plt.xticks(y_pos, chunk_labels)\n plt.ylim(0, 1.0)\n plt.xlabel('Iteration Chunk (Every 100 Iter.)')\n plt.ylabel('Proportion')\n plt.title('Proportion of Each Rule Within All Accepted Rules per Chunk (Probabilistic Rule Selection)')\n plt.legend(loc=1)\n\n last_bottom += rule\n\nplt.grid()\nplt.show()\n\n#######################################################################################################################\n#######################################################################################################################\n\nlower_tier_proportions = numpy.zeros(5)\nhigher_tier_proportions = numpy.zeros(5)\n\nfor rule_index in range(len(all_rule_proportions)):\n if rule_index < 8:\n for chunk_index in range(len(all_rule_proportions[rule_index])):\n lower_tier_proportions[chunk_index] += all_rule_proportions[rule_index][chunk_index]\n print(lower_tier_proportions)\n elif rule_index >= 8:\n for chunk_index in range(len(all_rule_proportions[rule_index])):\n higher_tier_proportions[chunk_index] += all_rule_proportions[rule_index][chunk_index]\n print(higher_tier_proportions)\n\ncombined_tiers_proportions = []\ncombined_tiers_proportions.append(lower_tier_proportions)\ncombined_tiers_proportions.append(higher_tier_proportions)\n\ncolors = [(0.8, 0.8, 0), (0, 0.2, 0.8)]\n\nlast_bottom = numpy.zeros(len(rule_proportions_a))\n\nfor tier_index in range(len(combined_tiers_proportions)):\n tier = combined_tiers_proportions[tier_index]\n if tier_index == 0:\n tier_name = \"Lower-Tier\"\n elif tier_index == 1:\n tier_name = \"Higher-Tier\"\n plt.bar(y_pos, tier, bar_width, color=colors[tier_index], bottom=last_bottom, align='center', alpha=0.5, label=tier_name)\n plt.xticks(y_pos, chunk_labels)\n plt.ylim(0, 1.0)\n plt.xlabel('Iteration Chunk (Every 100 Iter.)')\n plt.ylabel('Proportion')\n plt.title('Proportion of Each Rule Tier Within All Accepted Rules per Chunk (Probabilistic Rule Selection)')\n plt.legend(loc=1)\n\n last_bottom += tier\n\nplt.grid()\nplt.show()\n","sub_path":"tests/Revised Simulations/rule_effectiveness_test.py","file_name":"rule_effectiveness_test.py","file_ext":"py","file_size_in_byte":13875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"528014061","text":"import Color\nimport Dimension\nimport Position\nimport Block\nimport Board\n\n\ndef let_all_full_rows_explode(board):\n \"\"\"\n Let all the blocks in all the full rows on the given board explode.\n - The function starts with examining the given board collecting all the\n blocks in all rows that are completely filled. Hereafter, it will let\n each of these blocks explode exactly once in ascending order of their\n position.\n - If part of a full row has already exploded because of explosions of\n (electrified) blocks in lower rows, other blocks in that row will still\n explode (even if the row is no longer completely filled).\n - If a fragile block in a full row has already exploded because of explosions\n of (electrified) blocks in lower rows, the replacing blocks will not explode\n on their own. They may, however, explode as a result of other electrified\n blocks exploding.\n - The function returns the score resulting from all explosions.\n ASSUMPTIONS\n - The given board is a proper board.\n NOTE\n - This function is already provided (you do not have to work out this function yourself).\n \"\"\"\n assert Board.is_proper_board(board)\n blocks_to_explode = []\n full_rows_sorted = list(Board.get_all_full_rows(board))\n list.sort(full_rows_sorted)\n for row in full_rows_sorted:\n list.extend(blocks_to_explode, Board.get_all_blocks_in_row(board, row))\n total_score = 0\n for block in blocks_to_explode:\n if Board.contains_block(board, block):\n total_score += Board.let_explode(board, block)\n return total_score\n\n\ndef adjust_score(score, level, score_from_explosions, nb_full_rows, nb_columns):\n \"\"\"\n Return the new score and the new level in view of the given score, the given\n level, the score resulting from explosions that have taken place, the total\n number of full rows in which these explosions took place and the number of\n columns on the board.\n NOTE\n - This function is already provided (you do not have to work out this function yourself). Its details are irrelevant.\n \"\"\"\n\n def treshold_for_level(level):\n if level == 1:\n return 11 * nb_columns\n else:\n return treshold_for_level(level - 1) + (10 + level) * nb_columns * level\n\n extra_score = score_from_explosions * nb_full_rows * level\n score += extra_score\n if score > treshold_for_level(level):\n level += 1\n return (score, level)\n\n\ndef stabilize_board(level, score, board):\n \"\"\"\n Stabilize the given board and return the updated level and score in view of\n the given level and given score.\n - The function continuously lets all blocks on the given board fall down,\n followed by explosions of all full rows, until the board is stable.\n - The function returns a tuple (l,s) in which l is the new level and s is\n the new score in view of the given level and given score.\n ASSUMPTIONS\n - The given level is a positive integer number.\n - The given score is a non-negative integer number.\n - The given board is a proper board.\n NOTE\n - This function is already provided (you do not have to work out this function yourself).\n \"\"\"\n assert isinstance(level, int) and (level >= 1)\n assert isinstance(score, int) and (score >= 0)\n assert Board.is_proper_board(board)\n Board.let_all_blocks_fall(board)\n nb_full_rows = len(Board.get_all_full_rows(board))\n while (nb_full_rows > 0):\n if nb_full_rows > 0:\n score_from_explosions = let_all_full_rows_explode(board)\n score, level = \\\n adjust_score(score, level, score_from_explosions, nb_full_rows,\n Dimension.get_nb_of_columns(Board.get_dimension(board)))\n Board.let_all_blocks_fall(board)\n nb_full_rows = len(Board.get_all_full_rows(board))\n return (level, score)\n\n\ndef get_all_possible_moves(board):\n all_possible_moves = []\n for block in Board.get_all_blocks(board):\n i = 1\n check1 = False\n check2 = False\n while 1:\n if Board.can_move_over(board, block, i) and not check1:\n all_possible_moves.append((block, i))\n else:\n check1 = True\n if Board.can_move_over(board, block, -i) and not check2:\n all_possible_moves.append((block, -i))\n else:\n check2 = True\n if check1 and check2:\n break\n i += 1\n return all_possible_moves\n\n\ndef play_greedy(blocks, dimension=(8, 10)):\n \"\"\"\n Play the game in a greedy way on a board with the given dimension,\n using the given blocks to fill the bottom row in each step of the game.\n The function repeatedly shifts all blocks up one row, adds new blocks to the\n bottom row and stabilizes the board, computes the move that yields the highest\n score, and makes that move.\n - The given blocks are collected in a list of which each element is a list of\n blocks to fill the bottom row once.\n - The function computes and executes in each step the move yielding the\n highest score.\n - The function returns a tuple consisting of the total score after all\n the given blocks have been used or as soon as the game has come to an end,\n followed by a list of all the moves that have been made. Each move in the\n latter list is a tuple containing the block to move, followed by the\n distance over which that block has been moved.\n ASSUMPTIONS\n - The given dimension is a proper dimension.\n - Each element in the list of blocks ((blocks[I]) is a sequence that can be\n used to fill the bottom row once in a valid way (i.e., no overlapping\n positions, no remaining gap larger than half the number of columns after\n a complete fill, ...)\n - The elements in the list of blocks (blocks[I]) are used in the order from left\n to right.\n - Each basic element in the list of blocks ((blocks[I][J]) is a tuple\n involving a (leftmost) position in the bottom row of the board followed by\n a proper block for a board with the given dimension.\n \"\"\"\n if not blocks:\n return 0, []\n\n board = Board.make_board(dimension)\n level = 1\n score = 0\n total_moves = []\n while blocks:\n Board.insert_bottom_row(board, blocks.pop(0))\n level, score = stabilize_board(level, score, board)\n all_possible_moves = get_all_possible_moves(board)\n max_score = 0\n best_moves = []\n for move in all_possible_moves:\n board_copy = Board.copy_board(board)\n Board.move_block_horizontally(board_copy, move[0], move[1])\n temp_level, temp_score = stabilize_board(level, score, board_copy)\n if temp_score > max_score:\n max_score = temp_score\n best_moves = [move]\n elif temp_score == max_score:\n best_moves.append(move)\n if len(best_moves) > 1:\n lowest_block_moves = []\n lowest_row = Dimension.get_nb_of_rows(dimension)\n lowest_column = Dimension.get_nb_of_columns(dimension)\n for move in best_moves:\n pos = Board.get_leftmost_position_of(board, move[0])\n row_nb = Position.nb_of_row(dimension, Position.get_row(pos))\n col = Position.get_column(pos)\n if row_nb <= lowest_row:\n lowest_row = row_nb\n if col < lowest_column:\n lowest_column = col\n lowest_block_moves = [move]\n elif col == lowest_column:\n lowest_block_moves.append(move)\n if len(lowest_block_moves) > 1:\n lowest_move = Dimension.get_nb_of_columns(dimension)\n for move in lowest_block_moves:\n if move[1] < lowest_move:\n lowest_move = move[1]\n best_moves = [move]\n else:\n best_moves = lowest_block_moves\n total_moves.append(best_moves[0])\n Board.move_block_horizontally(board, best_moves[0][0], best_moves[0][1])\n level, score = stabilize_board(level, score, board)\n return score, total_moves\n\n\ndef get_top_moves(board, blocks, min_score=100, max_nb_moves=10, level=1, score=0):\n \"\"\"\n Compute the best possible moves to play the game on the given board starting from\n the given level and the given score using the given blocks to fill the bottom row\n in each step of the game to reach a score at least as high as the given minimal\n score in no more than the given maximum number of moves.\n Play starts with moving all blocks up one row, adding new blocks to the bottom\n row and stabilizing the board.\n - The given blocks are collected in a list of which each element is a list of\n blocks to fill the bottom row once.\n - The function returns None if the given minimal score cannot be reached.\n Otherwise, the function returns a list of all the moves to reach at least\n the minimal score. Each move in the latter list is a tuple containing\n the lefmost position of the block to move, followed by the block itself,\n followed by the distance over which that block has to be moved.\n The position of the block is taken at the time of the move, which may obviously\n differ from the initial position taken by that block on the board.\n - If several solutions exist to reach at least the minimal score, the function\n returns the shortest of them in terms of number of moves. If several\n shortest solutions exist, the function returns the solution that is less\n than all other solutions of the same length using Python's operator to compare\n lists.\n - Upon exit, the given board and the given list of blocks must be in the same\n state they were in upon entry.\n ASSUMPTIONS\n - The given board is a proper and stable board.\n - Each element in the list of blocks ((blocks[I]) is a sequence that can be\n used to fill the bottom row once in a valid way (i.e., no overlapping\n positions, no remaining gap larger than half the number of columns after\n a complete fill, ...)\n - The elements in the list of blocks (blocks[I]) are used in the order from left\n to right.\n - Each basic element in the list of blocks ((blocks[I][J]) is a tuple\n involving a (leftmost) position in the bottom row of the board followed by\n a proper block for a board with the given dimension.\n - The given minimal score is a non-negative integer number.\n - The given maximum number of moves is an integer number. If it is negative,\n the function must return None.\n - The given level is a positive integer number.\n - The given score is a non-negative integer number.\n NOTE:\n - This function must use the given functions let_all_full_rows_explode\n and stabilize_board each time all rows of the board must explode,\n respectively the board must be stabilized.\n \"\"\"\n if max_nb_moves < 0:\n return None\n if max_nb_moves == 0 or not blocks:\n if min_score > 0:\n return None\n else:\n return []\n\n blocks = blocks.copy()\n cboard = Board.copy_board(board)\n if blocks:\n Board.insert_bottom_row(cboard, blocks.pop(0))\n else:\n return []\n level, score = stabilize_board(level, score, cboard)\n best_moves = []\n max_score = 0\n\n for move in get_all_possible_moves(cboard):\n temp_moves = []\n copy = Board.copy_board(cboard)\n pos = Board.get_leftmost_position_of(copy, move[0])\n Board.move_block_horizontally(copy, move[0], move[1])\n if not Board.is_empty_row(copy, 'X'):\n continue\n temp_level, temp_score = stabilize_board(level, score, copy)\n\n if max_nb_moves > 1 and temp_score < min_score:\n temp_moves = get_top_moves(copy, blocks.copy(), min_score, max_nb_moves-1, level, temp_score)\n if temp_moves:\n moves_test = temp_moves.copy()\n blocks_copy = blocks.copy()\n while moves_test:\n Board.insert_bottom_row(copy, blocks_copy.pop(0))\n temp_level, temp_score = stabilize_board(temp_level, temp_score, copy)\n cache_move = moves_test.pop(0)\n Board.move_block_horizontally(copy, Board.get_block_at(copy, cache_move[0]), cache_move[2])\n temp_level, temp_score = stabilize_board(temp_level, temp_score, copy)\n\n if temp_score >= min_score:\n if temp_moves:\n best_moves = [[(pos,) + move] + temp_moves]\n else:\n best_moves = [[(pos,) + move]]\n max_score = temp_score\n\n if max_score < min_score:\n return None\n\n if len(best_moves) == 0:\n return None\n\n if len(best_moves) > 1:\n min = max_nb_moves\n for i in best_moves:\n if len(i) < min:\n min = len(i)\n best_moves = [i]\n elif len(i) == min and i not in best_moves:\n best_moves.append(i)\n\n if len(best_moves) > 1:\n min = None\n for i in best_moves:\n if not min or i < min:\n min = i\n\n return best_moves[0]\n\n\n\n\n\ndef let_player_move_block(board):\n \"\"\"\n Let the player move one of the blocks on the given board.\n ASSUMPTIONS\n - The given board is a proper board.\n - The bottom row of the given board is not empty.\n \"\"\"\n assert Board.is_proper_board(board)\n assert not Board.is_empty_row(board, \"a\")\n block_to_move = None\n distance_to_move_over = None\n while (block_to_move is None) or (distance_to_move_over is None):\n players_position = \\\n input(\"Some position of block to move: \").split(',')\n if (len(players_position) > 1) and str.isdigit(players_position[1]):\n players_position[1] = eval(players_position[1])\n players_position = tuple(players_position)\n if not Position.is_proper_position(players_position):\n print(\" ---> A proper position consists of a letter, a comma and some digits!\")\n elif not Position.is_within_boundaries(Board.get_dimension(board), players_position):\n print(\" ---> The position is outside the boundaries of the board!\")\n elif Board.is_free_at(board, players_position):\n print(\" ---> No block at the given position\")\n else:\n the_block = Board.get_block_at(board, players_position)\n players_distance = int(input(\"Enter distance to move block over : \"))\n if (not isinstance(players_distance, int)) or (players_distance == 0):\n print(\" ---> The distance must be a non-zero integer number.!\")\n elif not Board.can_move_over(board, the_block, players_distance):\n print(\" ---> The given block cannot move over the given distance\")\n else:\n block_to_move = the_block\n distance_to_move_over = players_distance\n Board.move_block_horizontally(board, block_to_move, distance_to_move_over)\n\n\ndef play_keyboard(blocks = [], nb_rows=10, nb_columns=8):\n \"\"\"\n Function to play the game on a board with the given number of rows and the\n given number of columns via the keyboard, using the given blocks to fill\n the bottom row.\n - The given blocks are collected in a list of which each element is a list of\n blocks to fill the bottom row once. The function will first use elements from\n that list until the list is exhausted. From that point on, the function will\n generate blocks to fill the bottom row in a random way.\n ASSUMPTIONS\n - The given number of rows and the given number of columns are integer numbers\n greater than 1.\n \"\"\"\n assert (nb_rows > 1) and (nb_columns > 1)\n score = 0\n level = 1\n the_board = Board.make_board((nb_rows, nb_columns))\n while Board.is_empty_row(the_board, \"X\"):\n if len(blocks) > 0:\n Board.insert_bottom_row(the_board,blocks.pop(0))\n else:\n Board.push_all_blocks_up(the_board)\n max_block_length = max(2, \\\n round(nb_columns / 4) if level <= 3 else \\\n round(nb_columns / 3) if level <= 6 else\n round(nb_columns / 2))\n Board.fill_bottom_row(the_board, max_block_length)\n level, score = stabilize_board(level, score, the_board)\n Board.print_board(the_board)\n let_player_move_block(the_board)\n level, score = stabilize_board(level, score, the_board)\n print(\"Score: \", score, \"[level: \", level, \"]\")\n print(\"Einde spel!\")\n\n\nif __name__ == '__main__':\n # You are free to change the content of blocks_to_fill\n block1_1 = Block.make_block(1, color=Color.RED)\n block1_2 = Block.make_block(3, color=Color.RED)\n block1_3 = Block.make_block(4, color=Color.RED)\n block2_1 = Block.make_block(1, color=Color.BLUE)\n block2_2 = Block.make_block(2, color=Color.BLUE)\n block2_3 = Block.make_block(4, color=Color.BLUE)\n block3_1 = Block.make_block(3, color=Color.MAGENTA)\n block3_2 = Block.make_block(1, color=Color.MAGENTA)\n block3_3 = Block.make_block(2, color=Color.MAGENTA)\n block3_4 = Block.make_block(1, color=Color.MAGENTA)\n block4_1 = Block.make_block(3, color=Color.GREEN)\n block4_2 = Block.make_block(3, color=Color.GREEN)\n block4_3 = Block.make_block(1, color=Color.GREEN)\n blocks_to_fill = \\\n [[((\"a\", 1), block1_1), ((\"a\", 2), block1_2)], #((\"a\", 5), block1_3)],\n [((\"a\", 1), block2_1), ((\"a\", 3), block2_2), ((\"a\", 5), block2_3)],\n [((\"a\", 1), block3_1), ((\"a\", 5), block3_2), ((\"a\", 6), block3_3), ((\"a\", 8), block3_4)],\n [((\"a\", 1), block4_1), ((\"a\", 5), block4_2), ((\"a\", 8), block4_3)]\n ]\n play_keyboard(blocks_to_fill,nb_columns=9)\n","sub_path":"Game-backup.py","file_name":"Game-backup.py","file_ext":"py","file_size_in_byte":18449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"428535844","text":"\"\"\"Gateway for accessing the Discourse API (for forums)\"\"\"\n\nimport json\nimport re\nfrom urllib import urlencode\n\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import ndb\n\n\nclass Error(Exception):\n pass\n\n\nclass DiscourseAPIClient(object):\n \"\"\"An API client for interacting with Discourse\"\"\"\n\n def __init__(self, discourse_url, api_key, api_username='system'):\n self._discourse_url = discourse_url\n self._api_key = api_key\n self._api_username = api_username\n\n @ndb.tasklet\n def _getRequest(self, req_string, params=None, payload=None):\n response = yield self._sendDiscourseRequest(req_string, params,\n payload, 'GET')\n raise ndb.Return(response)\n\n @ndb.tasklet\n def _putRequest(self, req_string, params=None, payload=None):\n response = yield self._sendDiscourseRequest(req_string, params,\n payload, 'PUT')\n raise ndb.Return(response)\n\n @ndb.tasklet\n def _postRequest(self, req_string, params=None, payload=None):\n response = yield self._sendDiscourseRequest(req_string, params,\n payload, 'POST')\n raise ndb.Return(response)\n\n @ndb.tasklet\n def _deleteRequest(self, req_string, params=None, payload=None):\n response = yield self._sendDiscourseRequest(req_string, params,\n payload, 'DELETE')\n raise ndb.Return(response)\n\n @ndb.tasklet\n def _sendDiscourseRequest(self, req_string, params, payload, method):\n if payload is None:\n payload = {}\n if params is None:\n params = {}\n\n if method == 'GET' or method == 'DELETE':\n params.update({'api_key': self._api_key,\n 'api_username': self._api_username})\n else:\n payload.update({'api_key': self._api_key,\n 'api_username': self._api_username})\n\n if params:\n url = '%s%s?%s' % (self._discourse_url, req_string,\n urlencode(params))\n else:\n url = '%s%s' % (self._discourse_url, req_string)\n\n response = yield ndb.get_context().urlfetch(\n url=url, payload=urlencode(payload), method=method,\n headers={'Content-Type': 'application/x-www-form-urlencoded'}\n )\n\n if response.status_code != 200:\n raise Error(\"%s request to %s returned a code of %d\" %\n (method, req_string, response.status_code))\n\n raise ndb.Return(json.loads(response.content))\n\n # USER ACTIONS\n\n @ndb.tasklet\n def getUserByEmail(self, user_email):\n \"\"\"Finds a user with the given email\n\n This method takes a user email and returns a future which resolves to\n the Discourse user with that email address, if they exist. If no user\n is found, None is returned.\n \"\"\"\n users = yield self._getRequest('admin/users/list/active.json',\n params={'filter': user_email,\n 'show_emails': 'true'})\n\n for user in users:\n if user['email'].lower() == user_email.lower():\n raise ndb.Return(user)\n\n raise ndb.Return(None)\n\n @ndb.tasklet\n def createUser(self, name, email, password, username, external_id=None):\n \"\"\"Create a Discourse account\n\n This method takes a user object and returns the Discourse API response\n containing the user information for that user.\n \"\"\"\n\n # user = yield self.getUserByEmail(email)\n # if user:\n # raise ndb.Return(user)\n\n payload = {\n 'username': username,\n 'email': email,\n 'name': name,\n 'password': password,\n }\n\n if external_id:\n payload['external_id'] = external_id\n\n response = yield self._postRequest('users/', payload=payload)\n raise ndb.Return(response)\n\n @ndb.tasklet\n def deleteUser(self, email):\n user = yield self.getUserByEmail(email)\n if user is None:\n raise ndb.Return(None)\n\n response = yield self._deleteRequest('admin/users/%s.json' % user['id'])\n raise ndb.Return(response)\n\n # CATEGORY ACTIONS\n\n @ndb.tasklet\n def getCategoryByName(self, category_name):\n categories = yield self._getRequest('categories.json')\n\n for category in categories['category_list']['categories']:\n if category['name'] == category_name:\n raise ndb.Return(category)\n\n raise ndb.Return(None)\n\n @ndb.tasklet\n def createCategory(self, category_name, parent_category_name=None,\n **kwargs):\n \"\"\"Create a category\"\"\"\n category = yield self.getCategoryByName(category_name)\n if category:\n raise ndb.Return(None)\n\n defaults = {\n 'color': 'FFFFFF',\n 'text_color': '000000'\n }\n\n payload = {\n 'name': category_name,\n 'allow_badges': True\n }\n\n payload.update(defaults)\n\n for k, v in kwargs.iteritems():\n payload[k] = v\n\n if parent_category_name:\n parent_category = yield \\\n self.getCategoryByName(parent_category_name)\n payload['parent_category_id'] = parent_category['id']\n\n response = yield self._postRequest('categories', payload=payload)\n raise ndb.Return(response)\n\n @ndb.tasklet\n def deleteCategory(self, category_name):\n category = yield self.getCategoryByName(category_name)\n if not category:\n raise ndb.Return(None)\n\n response = yield self._deleteRequest('categories/%s' % category['slug'])\n raise ndb.Return(response)\n\n # GROUP ACTIONS\n\n @ndb.tasklet\n def addUserToGroup(self, user_email, group_name):\n \"\"\"Adds the given account to the Discourse group with the given name\"\"\"\n\n user = yield self.getUserByEmail(user_email)\n if not user:\n raise Error(\"Unable to find user with email %s\" % user_email)\n\n groups = yield self._getRequest('admin/groups.json')\n\n group_id = None\n for group in groups:\n if group['name'] == group_name:\n group_id = group['id']\n break\n else:\n raise Error(\"Group named %s not found\" % group_name)\n\n payload = {\n 'usernames': user['username']\n }\n\n result = yield self._putRequest('admin/groups/%s/members.json' %\n group_id, payload=payload)\n raise ndb.Return(result)\n\n @ndb.tasklet\n def removeUserFromGroup(self, user_email, group_name):\n \"\"\"Removes an account from a group\"\"\"\n\n user = yield self.getUserByEmail(user_email)\n if not user:\n raise Error(\"Unable to find user with email %s\" % user_email)\n\n group = yield self.getGroupByName(group_name)\n if not group:\n raise Error(\"Group named %s not found\" % group_name)\n\n result = yield self._deleteRequest('admin/groups/%s/members.json' % group['id'],\n params={'user_id': user['id']})\n raise ndb.Return(result)\n\n @ndb.tasklet\n def createGroup(self, group_name, **kwargs):\n \"\"\"Creates a group with the given name on Discourse\"\"\"\n\n groups = yield self._getRequest('admin/groups.json')\n\n for group in groups:\n if group['name'] == group_name:\n raise ndb.Return(None)\n # raise Error(\"Group named %s already exists!\" % group_name)\n\n payload = {\n 'name': group_name\n }\n\n for k, v in kwargs.iteritems():\n payload[k] = v\n\n response = yield self._postRequest('admin/groups', payload=payload)\n raise ndb.Return(response)\n\n @ndb.tasklet\n def deleteGroup(self, group_name):\n group = yield self.getGroupByName(group_name)\n if not group:\n raise ndb.Return(None)\n\n response = yield self._deleteRequest('admin/groups/%s' % group['id'])\n raise ndb.Return(response)\n\n @ndb.tasklet\n def getGroupByName(self, group_name):\n groups = yield self._getRequest('admin/groups.json')\n\n for group in groups:\n if group['name'] == group_name:\n raise ndb.Return(group)\n\n raise ndb.Return(None)\n\n # CONTENT ACTIONS\n\n @ndb.tasklet\n def createPost(self, text, title, category_name, **kwargs):\n \"\"\"Creates a post\"\"\"\n\n category = yield self.getCategoryByName(category_name)\n\n payload = {\n 'raw': text,\n 'title': title,\n 'category': category['id']\n }\n\n for k, v in kwargs.iteritems():\n payload[k] = v\n\n response = yield self._postRequest('posts', payload=payload)\n","sub_path":"src/discourse.py","file_name":"discourse.py","file_ext":"py","file_size_in_byte":9000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"470679868","text":"import autograd.numpy as np\nimport so3\nimport parse\n\n\ndef GetIMU():\n TS, GYRO, TEMP, MAG, ACCEL = [], [], [], [], []\n for entry in parse.ParseLog(open(\"../rustlerlog-BMPauR\")):\n if entry[0] == 'img':\n continue\n elif entry[0] != 'imu':\n continue\n _, ts, gyro, mag, accel = entry\n TS.append(ts)\n # gyro (rads/sec)\n GYRO.append(np.array(gyro[:3], np.float32) * np.pi / (180 * 14.375))\n TEMP.append(gyro[3])\n # magnetometer (in some random uT/LSB count units)\n MAG.append(mag.astype(np.float32))\n # accel (m/s^2)\n ACCEL.append(accel.astype(np.float32) * 9.81 / 256.0)\n return (np.array(TS), np.array(GYRO), np.array(TEMP),\n np.array(MAG), np.array(ACCEL))\n\n\nTS, GYRO, TEMP, MAG, ACCEL = GetIMU()\n\n\ndef magcal_residual(MAG, a, mb):\n \"\"\" residual from all observations given magnetometer eccentricity, bias,\n gyro bias, and gyro scale\"\"\"\n\n A = np.array([\n [a[0], a[1], a[2]],\n [0, a[3], a[4]],\n [0, 0, a[5]]\n ])\n\n mag = np.dot(MAG - mb, A)\n return np.mean(np.abs(1 - np.einsum('ji,ji->j', mag, mag)))\n\n\ndef magcal_residual2(a, mb, gb, gs):\n \"\"\" residual from all observations given magnetometer eccentricity, bias,\n gyro bias, and gyro scale\"\"\"\n\n A = np.array([\n [a[0], a[1], a[2]],\n [0, a[3], a[4]],\n [0, 0, a[5]]\n ])\n\n mag = np.dot(MAG - mb, A)\n dt = TS[1:] - TS[:-1]\n w = gs * (GYRO[1:] - gb)\n C = so3.tensorexp(w.T * dt)\n rot_mag = np.einsum('ijl,lj->li', C, mag[:-1])\n return np.mean(np.abs(1 - np.einsum('ji,ji->j', mag[1:], rot_mag)))\n\n# (x-u)^T A (x-u) - 1\n# x^T A (x-u) - u^T A (x-u) - 1\n# x^T A x - x^T A u - u^T A x + u^T A u - 1\n# x^T A x - (2 u^T A) x + (u^T A u - 1) = 0\n\n# i wonder if a more numerically stable parameterization would be to use 1/diag\n# ...nope\n","sub_path":"py/calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"306573186","text":"import numpy as np\r\ndef forward(A,B,pi,T,N,o):\r\n alpha=np.zeros((T,N))\r\n for i in range(N):\r\n alpha[0][i]=pi[i]*B[i][o[0]]\r\n for t in range(T-1):\r\n for i in range(N):\r\n sum_temp = 0\r\n for j in range(N):\r\n sum_temp=sum_temp+alpha[t][j]*A[j][i]\r\n alpha[t+1][i]=sum_temp*B[i][o[t+1]]\r\n p_o_lamda=alpha[T-1].sum(axis=0)\r\n return p_o_lamda,alpha\r\ndef backward(A,B,pi,T,N,o):\r\n beta=np.ones((T,N))\r\n for t in range(T-1,0,-1):\r\n for i in range(N):\r\n beta[t-1][i]=0\r\n for j in range(N):\r\n beta[t-1][i]=beta[t-1][i]+A[i][j]*B[j][o[t]]*beta[t][j]\r\n p_o_lamda=0\r\n for i in range(N):\r\n p_o_lamda=p_o_lamda+pi[i]*B[i][o[0]]*beta[0][i]\r\n return p_o_lamda,beta\r\nif __name__ == '__main__':\r\n A=[[0.5,0.1,0.4],[0.3,0.5,0.2],[0.2,0.2,0.6]]\r\n B=[[0.5,0.5],[0.4,0.6],[0.7,0.3]]\r\n pi=[0.2,0.3,0.5]\r\n T=8\r\n N=3\r\n # 红色0,白色1\r\n o=[0,1,0,0,1,0,1,1]\r\n forward_p,alpha=forward(A,B,pi,T,N,o)\r\n backward_p,beta=backward(A,B,pi,T,N,o)\r\n # 求P(i4=q3|O,λ)\r\n i=3-1\r\n t=4-1\r\n densum=0\r\n for j in range(N):\r\n densum=densum+alpha[t][j]*beta[t][j]\r\n gamma43=alpha[t][i]*beta[t][i]/densum\r\n print('P(i_4=q_3|0,λ) =',gamma43)","sub_path":"forward_and_backward.py","file_name":"forward_and_backward.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"448741308","text":"from logic import TruthTable\r\n\r\nproposition1 = input(\"Enter Proposition 1:\\n\")\r\nproposition2 = input(\"Enter Proposition 2:\\n\")\r\n\r\nmyTable1 = TruthTable(['p', 'q'], [proposition1])\r\nmyTable2 = TruthTable(['p', 'q'], [proposition2])\r\n\r\nprint(myTable1.table)\r\nprint(myTable2.table)\r\n\r\nif myTable1.table == myTable2.table:\r\n print(\"The Propositions are equivalent.\")\r\nelse:\r\n print(\"The Propositions are not equivalent.\")\r\n","sub_path":"Lab9/CSE015/Lab2Problem2.py","file_name":"Lab2Problem2.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"14226365","text":"import argparse\nimport codecs\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef main(args, loglevel):\n # set up logging\n logging.basicConfig(format=\"%(levelname)s: %(message)s\", level=loglevel)\n\n file = codecs.open(args.file, 'r', 'utf-8')\n total = 0\n\n if args.output.endswith('/'):\n outfile_prefix = args.output + args.prefix\n else:\n outfile_prefix = args.output + '/' + args.prefix\n\n outfiles = [codecs.open('%s%s' % (outfile_prefix, i), 'w', 'utf-8') for i in xrange(args.number)]\n\n article = ''\n for line in file:\n article += line\n if line == '\\n':\n outf = outfiles[total % args.number]\n outf.write(article)\n total += 1\n article = ''\n\n file.close()\n [f.close() for f in outfiles]\n logger.info('Finished partititoning %d articles into %d partitions' % (total, args.number))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"Partitions a file generated by WikiExtractor\",\n fromfile_prefix_chars='@')\n\n parser.add_argument(\n \"-f\",\n \"--file\",\n help=\"Path to the file with plaintext articles generated by WikiExtractor\",\n required=True,\n type=str\n )\n\n parser.add_argument(\n \"-n\",\n \"--number\",\n help=\"number of partitions\",\n required=True,\n type=int\n )\n\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"increase output verbosity\",\n action=\"store_true\")\n\n parser.add_argument(\n \"-o\",\n \"--output\",\n help=\"Path to the output directory\",\n required=True,\n type=str\n )\n\n parser.add_argument(\n \"-p\",\n \"--prefix\",\n help=\"Prefix for output files (default: partition-)\",\n default=\"partition-\",\n type=str\n )\n\n args = parser.parse_args()\n\n loglevel = logging.INFO\n if args.verbose:\n loglevel = logging.DEBUG\n\n main(args, loglevel)\n","sub_path":"scripts/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"168991974","text":"\"\"\"\nAdvent of Code 2020\nDay: 14\nPuzzle: 1\nLanguage: Python\n\"\"\"\n\n# incorrect guesses: 142232120440\n\nimport re\n\n\ndef add_mask(num, mask):\n res = list()\n for idx, mask_digit in enumerate(mask):\n if mask_digit == \"X\":\n res.append(num[idx])\n elif mask_digit == \"0\":\n res.append(\"0\")\n else:\n res.append(\"1\")\n\n return int(\"\".join(res), 2)\n\n\ndef main():\n infile_path = \"../../../data/2020_day_14.txt\"\n with open(infile_path, \"r\") as infile:\n data = infile.readlines()\n\n mask = None\n mem = dict()\n\n for line in data:\n if line.startswith(\"mask\"):\n mask = line.split(\"=\")[1].strip()\n else:\n # mem\n num = bin(int(line.split(\"=\")[1].strip()))[2:].zfill(36)\n target = int(re.search(r\"\\[(\\d+)\\]\", line).group(1))\n res = add_mask(num, mask)\n mem[target] = res\n\n print(sum(mem.values()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/advent_of_python/2020_puzzles/day14puzzle1.py","file_name":"day14puzzle1.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"324237491","text":"import numpy as np\nimport pandas as pd\n\ndef keepindications_removeexclusionstt(metr,dat,lkupTab,include_or_exclude, lookbac, tempsort_dayx, b, uflagx):\n print('initiating keepIremoveE')\n print(len(dat))\n print('number unique MRNs')\n print(dat.MRN.nunique()) #\n \n if (include_or_exclude=='exclude'):\n ex_dat=dat[(dat.dys_difftime_test_code<=lookbac) & (dat.dys_difftime_test_code>=0)]\n if metr in ['dexa','narc']:\n ex_dat.loc[ex_dat.dys_difffrom_rCODE>tempsort_dayx, 'rCODE']='ERASEDplaceholder' # ERASEDplaceholder will not (likely) wind up in reference table cell, whereas None actually can\n elif metr == 'vitd':\n ex_dat.loc[ex_dat.dys_difffrom_rCODE>365, 'rCODE']='ERASEDplaceholder'\n elif len(lkupTab[lkupTab['class']=='CPT'])>0:\n raise ValueError('the comparison btwn main service code, and prior service codes is invalid. That is to say, prior service codes are not being considered as they should be, given that ref table has a CPT code in it')\n else:\n pass\n print('starting vect_mrn')\n deb1=ex_dat\n vect_mrn_pd=vect_mrn(metr, ex_dat, lkupTab, b, 'exclude', uflagx)\n debA = vect_mrn_pd[0]\n debB = vect_mrn_pd[1]\n deb2=vect_mrn_pd[-1]\n \n ### return only those from the dat.pd which are NOT in the vect_mrn result \n #(those in time window w/o valid indications, \n #or any with valid indications that date from beyond lookback period/or result after service performed)\n dat=dat[~dat['MRN'].isin(vect_mrn_pd[-1])]\n \n return (deb1, debA, debB, deb2, dat)\n elif (include_or_exclude=='include'):\n if metr in ['dexa','narc']:\n# in_dat = dat[dat.dys_difffrom_rCODE<=tempsort_dayx]\n in_dat = dat\n in_dat.loc[in_dat.dys_difffrom_rCODE>tempsort_dayx, 'rCODE']='ERASEDplaceholder'\n elif metr == 'vitd':\n in_dat = dat\n in_dat.loc[in_dat.dys_difffrom_rCODE>365, 'rCODE']='ERASEDplaceholder'\n elif len(lkupTab[lkupTab['class']=='CPT'])>0:\n raise ValueError('the comparison btwn main service code, and prior service codes is invalid.')\n else:\n in_dat = dat\n vect_mrn_pd=vect_mrn(metr, in_dat, lkupTab, b, 'include', uflagx)\n dat=dat[dat['MRN'].isin(vect_mrn_pd)] \n return dat\n else:\n raise ValueError(\"Set 3rd ARG to 'include' or 'exclude'\")\n\n\ndef vect_mrn(met, loc_pd, lkupTa, b, i_or_e, uflagxx): \n lkupTa_0= lkupTa[lkupTa.startWith==0]\n lkupTa_1= lkupTa[lkupTa.startWith==1]\n if len(lkupTa_1[lkupTa_1['class']!='ICD'])>0:\n raise ValueError('reference table has a startWith stem that has class other than ICD')\n else:\n pass \n \n if uflagxx == False: \n vect_mr=np.unique(pd.concat([loc_pd['MRN'][loc_pd.ccslev.astype(str).isin(lkupTa_0['subcode'][lkupTa_0['class']=='CCS'])],\n ## following line changed from TEST_CODE to rCODE, for the column of procedures/services merged on queried service\n loc_pd['MRN'][loc_pd.rCODE.isin(lkupTa_0['subcode'][lkupTa_0['class']=='CPT'])],\n loc_pd['MRN'][loc_pd.hcclev.astype(str).isin(lkupTa_0['subcode'][lkupTa_0['class']=='HCC'])],\n loc_pd['MRN'][loc_pd['ICD{}_subcode'.format(b)].isin(lkupTa_0['subcode'][lkupTa_0['class']=='ICD'])]]))\n elif uflagxx == True:\n vect_mr=np.unique(pd.concat([loc_pd['MRN'][loc_pd.rCODE.isin(lkupTa_0['subcode'][lkupTa_0['class']=='CPT'])],\n loc_pd['MRN'][loc_pd['ICD{}_subcode'.format(b)].isin(lkupTa_0['subcode'][lkupTa_0['class']=='ICD'])]]))\n deba=[loc_pd[loc_pd.rCODE.isin(lkupTa_0['subcode'][lkupTa_0['class']=='CPT'])],\n loc_pd[loc_pd['ICD{}_subcode'.format(b)].isin(lkupTa_0['subcode'][lkupTa_0['class']=='ICD'])]]\n else:\n raise KeyError('uflagxx in keepinclusionsremoveexclusions()/vect_mr() is incompatible with algorithm design')\n \n print('starting the startWith chunk')\n# if (np.sum(lkupTa_1['startWith'][lkupTa_1['key']==met])>0): ## This is the original rule for entering startWith chunk\n if len(lkupTa_1)>0:\n print('entered startWith chunk')\n lkupTa_1.loc[:,'length']=lkupTa_1['subcode'].apply(lambda x: len(x))\n print('the stems that are length zero: {}'.format(len(lkupTa_1[lkupTa_1.length==0])))\n print(lkupTa_1[lkupTa_1['length']==0])\n lkupTa_1=lkupTa_1[lkupTa_1.length>0]\n lengthsx=lkupTa_1.groupby('length').count()\n lengthsx.reset_index(inplace=True)\n lengthsx=lengthsx['length']\n testerbean=0\n debb=deba\n for n in lengthsx:\n print('stem length is: {}'.format(n))\n t_stCodes=list(lkupTa_1.loc[lkupTa_1.length==n, 'subcode'])\n # create temp dataframe that is light\n t_loc_pd=loc_pd[['MRN','ICD{}_subcode'.format(b)]]\n # create third column\n t_loc_pd.loc[:,'trunc']=t_loc_pd.loc[:,'ICD{}_subcode'.format(b)].str[:n]\n # add those MRNs to the main vect_mr\n vect_mr=np.append(vect_mr,np.unique(t_loc_pd['MRN'][t_loc_pd['trunc'].isin(t_stCodes)]))\n if testerbean ==0:\n debb = t_loc_pd[t_loc_pd['trunc'].isin(t_stCodes)]\n testerbean+=1\n else:\n debb = pd.concat([debb, t_loc_pd[t_loc_pd['trunc'].isin(t_stCodes)]])\n print('keepin/ex stemming cycle completed x1')\n# else:\n # raise KeyError('startWith Chunk is using incorrect uflagxx')\n #######################################\n ########################################\n print('done with startWith chunk, now parsing for uniques')\n \n # new line, just for cleanness - restrict to unique MRN\n vect_mr = np.unique(vect_mr)\n print('done with vect_mrn')\n return (deba, debb, vect_mr)\n","sub_path":"Scripts/keepind_ex_testingreportable_20170710.py","file_name":"keepind_ex_testingreportable_20170710.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"444936546","text":"from django.shortcuts import render, render_to_response\nimport json\nimport urllib2\n\n# Create your views here.\n\n\ndef home(request):\n return render(request, \"index.html\")\n\n\ndef about(request):\n codeschool = urllib2.urlopen('https://www.codeschool.com/users/dmmoody.json')\n codeschool_data = json.load(codeschool)\n\n treehouse = urllib2.urlopen('http://teamtreehouse.com/duanemoody.json')\n treehouse_data = json.load(treehouse)\n badge_count = 0\n points = treehouse_data['points']['total']\n course_dict = {}\n activity_date = []\n for i in treehouse_data['badges']:\n badge_count += 1\n activity_date.append(i['earned_date'])\n if i['courses']:\n if i['courses'][0]['title'] in course_dict:\n course_dict[i['courses'][0]['title']].append([i['courses'][1]['title'], i['icon_url']])\n else:\n course_dict[i['courses'][0]['title']] = [[i['courses'][1]['title'], i['icon_url']]]\n activity_date = json.dumps(activity_date)\n return render_to_response('about.html', {'treehouse_data': treehouse_data,\n 'course_dict': course_dict,\n 'points': points,\n 'badge_count': badge_count,\n 'activity_date': activity_date,\n 'codeschool_data': codeschool_data})\n\ndef projects(request):\n github = urllib2.urlopen('https://api.github.com/users/dmmoody/repos')\n github_data = json.load(github)\n return render_to_response('projects.html', {'github_data': github_data})","sub_path":"dmmoody/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"173199171","text":"# ftp.retrbinary(\"RETR \" + file ,open(\"pub/sistemas/tup/downloads/\" + file, 'wb').write)\nimport pandas as pd\nimport urllib.request\nimport io\nfrom zipfile import ZipFile\nfrom ftplib import FTP\n\n\n# AQUI TALVEZ POSSA SER RETIRADO PRA NÃO PRECISAR ABRIR DUAS VEZES O FTP\ndef getfullfilename(year: int, month: int):\n TabelaUnificada = 'TabelaUnificada_{}{}'.format(year,month)\n ftp = FTP(\"ftp2.datasus.gov.br\")\n ftp.login()\n ftp.cwd(\"pub/sistemas/tup/downloads/\")\n filenames = ftp.nlst()\n result = list(filter(lambda x: x.startswith(TabelaUnificada), filenames))\n ftp.close()\n return result[0]\n\ndef download(file: str, year: int, month: int, cache: bool=True) -> object:\n TabelaUnificadaName = getfullfilename(year, month)\n mysock = urllib.request.urlopen('ftp://ftp2.datasus.gov.br/pub/sistemas/tup/downloads/' + TabelaUnificadaName)\n memfile = io.BytesIO(mysock.read())\n with ZipFile(memfile, 'r') as myzip:\n f = myzip.open(file + '.txt')\n col = myzip.open(file + '_layout.txt')\n colunas, content = col.read(), f.read()\n colunas, content = colunas.decode(\"unicode_escape\"), content.decode(\"unicode_escape\")\n dfcol = (pd.DataFrame([x.split(',') for x in colunas.split('\\r\\n')]))\n dfcol = dfcol.rename(columns=dfcol.iloc[0]).drop([0]).dropna()\n\n df = (pd.DataFrame([x.split('\\r\\n') for x in content.split('\\r\\n')]))\n FinalDF = pd.DataFrame(columns=dfcol['Coluna'].tolist())\n \n # AQUI TEM QUE ACHAR UMA MANEIRA MAIS EFETIVA QUE O FOR\n for i in dfcol.index:\n inicio = int(dfcol.loc[i]['Inicio'])\n fim = int(dfcol.loc[i]['Fim'])\n row = []\n for s in range(len(df)):\n row.append(df.loc[s][0][inicio-1:fim])\n FinalDF[dfcol.loc[i]['Coluna']] = row\n return FinalDF\n","sub_path":"pysus/online_data/SIGTAP.py","file_name":"SIGTAP.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"156312038","text":"import gi\nimport dbus\nimport dbus.service\nimport dbus.mainloop.glib\nimport time\n\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom dbus.exceptions import DBusException\nfrom dbus.types import ByteArray\n\nfrom g13gui.applet.loopbackdisplaydevice import LoopbackDisplayDevice\nfrom g13gui.bitwidgets.display import Display\nfrom g13gui.bitwidgets.screen import Screen\n\ngi.require_version('GLib', '2.0')\nfrom gi.repository import GLib\n\n\nBUTTONS = [\n 'L1', 'L2', 'L3', 'L4'\n]\n\n\nclass Applet(dbus.service.Object):\n BUS_INTERFACE = 'com.theonelab.g13.Applet'\n BUS_PATH = '/com/theonelab/g13/Applet'\n\n def __init__(self, name):\n dbus.service.Object.__init__(self, dbus.SessionBus(),\n Applet.BUS_PATH)\n\n self._name = name\n self._dd = LoopbackDisplayDevice()\n self._d = Display(self._dd)\n self._s = Screen(self._d)\n self._s.hide()\n\n self._registered = False\n self._manager = None\n\n def register(self):\n try:\n self._manager = self._bus.get_object(\n 'com.theonelab.g13.AppletManager',\n '/com/theonelab/g13/AppletManager')\n except DBusException:\n self._manager = None\n return True\n\n self._manager.Register(self._name)\n self._registered = True\n\n GLib.idle_add(self.onRegistered)\n GLib.timeout_add_seconds(1, self._ping)\n\n return False\n\n def _ping(self):\n if self._manager:\n result = False\n\n try:\n result = self._manager.Ping()\n except DBusException as err:\n print('Lost connection with AppletManager: %s' % err)\n self._registered = False\n GLib.idle_add(self.onUnregistered)\n GLib.timeout_add_seconds(1, self.register)\n return False\n\n if not result:\n print('Lost registration with AppletManager')\n self._registered = False\n GLib.idle_add(self.onUnregistered)\n GLib.timeout_add_seconds(1, self.register)\n return False\n\n return True\n\n def run(self):\n self._bus = dbus.SessionBus()\n\n GLib.timeout_add_seconds(1, self.register)\n\n loop = GLib.MainLoop()\n loop.run()\n\n @property\n def name(self):\n return self._name\n\n @property\n def displayDevice(self):\n return self._dd\n\n @property\n def display(self):\n return self._d\n\n @property\n def screen(self):\n return self._s\n\n @property\n def manager(self):\n return self._manager\n\n def onKeyPressed(self, timestamp, key):\n pass\n\n def onKeyReleased(self, timestamp, key):\n pass\n\n def onShown(self, timestamp):\n pass\n\n def onHidden(self):\n pass\n\n def onRegistered(self):\n pass\n\n def onUnregistered(self):\n pass\n\n def maybePresentScreen(self):\n if self.screen.visible and self._manager:\n self.screen.nextFrame()\n frame = self.displayDevice.frame\n frame = ByteArray(frame)\n self._manager.Present(frame, byte_arrays=True)\n\n @dbus.service.method(BUS_INTERFACE,\n in_signature='d', out_signature='ay',\n byte_arrays=True)\n def Present(self, timestamp):\n self.screen.show()\n self.onShown(timestamp)\n self.screen.nextFrame()\n return ByteArray(self.displayDevice.frame)\n\n @dbus.service.method(BUS_INTERFACE)\n def Unpresent(self):\n self.screen.hide()\n self.onHidden()\n\n def _setButtonPressed(self, state, button):\n if button in BUTTONS:\n buttonIdx = BUTTONS.index(button)\n button = self._s.buttonBar.button(buttonIdx)\n if button:\n button.pressed = state\n\n @dbus.service.method(BUS_INTERFACE,\n in_signature='di', out_signature='ay',\n byte_arrays=True)\n def KeyPressed(self, timestamp, key):\n self.onKeyPressed(timestamp, key)\n self._setButtonPressed(True, key)\n self.screen.nextFrame()\n return ByteArray(self.displayDevice.frame)\n\n @dbus.service.method(BUS_INTERFACE,\n in_signature='di', out_signature='ay',\n byte_arrays=True)\n def KeyReleased(self, timestamp, key):\n self.onKeyReleased(timestamp, key)\n self._setButtonPressed(False, key)\n self.screen.nextFrame()\n return ByteArray(self.displayDevice.frame)\n\n\ndef RunApplet(cls, *args, **kwargs):\n DBusGMainLoop(set_as_default=True)\n applet = cls(*args, **kwargs)\n applet.run()\n","sub_path":"g13gui/applet/applet.py","file_name":"applet.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"266664849","text":"from itertools import combinations\nn=int(input())\npairs=[]\nfor i in range(n-1):\n x=input().split(\" \")\n pairs.append([int(x[1]),int(x[0])])\ntrees=[]\nfor i in range(n):\n x=input().split(\" \")\n trees.append([int(x[0]),int(x[1])])\nprint(trees)\n\ntrees.sort()\n\nlocation=[]\nfor i in range(n):\n location.append(\"\")\nlocation[0]=tree.index(trees[0])\ntrees.pop(0)\nfor i in range(len(pairs)):\n x=pairs[i]\n start=x[0]\n end=x[1]\n location[x[1]]=tree.index(trees[0])\n trees.pop(0)\nprint(location)\nprint(pairs)\nprint(\"0 1\")\nprint(\"1 3\")\nprint(\"1 2\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Code/CodeRecords/2175/60636/269464.py","file_name":"269464.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"653432879","text":"\"\"\"Basic SpearCube Calculations\n\"\"\"\n\nimport coloredlogs\nimport logging\nimport numpy as np\n\nfrom common import logger\nfrom orbits import constants as orbit_k, orbiter, manoeuvres\nfrom propulsion import rocket\n\n\nlogger.configure_logging()\n__log = logging.getLogger(__name__)\n\n\ndef print_comms(\n orbit,\n mother_coverage, coverage_time, contact_time,\n uhf_max_data, s_band_max_data\n):\n \"\"\"Helper\n This function prints in the console the results of the analysis.\n \"\"\"\n mother_coverage_h = mother_coverage / 3600\n coverage_time_h = coverage_time / 3600\n contact_time_h = contact_time / 3600\n\n u_max_data_B = np.divide(u_max_data, 8)\n u_max_data_kB = np.divide(u_max_data_B, 1024)\n s_max_data_B = np.divide(s_max_data, 8)\n s_max_data_kB = np.divide(s_max_data_B, 1024)\n\n __log.info(\n '>>> mother_coverage (s) = %.0f, (h) = %.3f',\n mother_coverage, mother_coverage_h\n )\n __log.info(\n '>>> coverage_time (s) = %.0f, (h) = %.3f',\n coverage_time, coverage_time_h\n )\n __log.info(\n '>>> contact_time (s) = %.0f, (h) = %.3f',\n contact_time, contact_time_h\n )\n __log.info(\n '>>> U max data (b) = %.0f, (kB) = %.0f',\n u_max_data, u_max_data_kB\n )\n __log.info(\n '>>> S max data (b) = %.0f, (kB) = %.0f',\n s_max_data, s_max_data_kB\n )\n\n comms_orbits = np.divide(mother_coverage, orbit.T)\n\n u_orbit_kB = np.divide(u_max_data_kB, comms_orbits)\n s_orbit_kB = np.divide(s_max_data_kB, comms_orbits)\n u_orbit_MB = np.divide(u_orbit_kB, 1024)\n s_orbit_MB = np.divide(s_orbit_kB, 1024)\n\n __log.info('>>> Comms Orbits = %.0f', comms_orbits)\n __log.info('>>> U per orbit (kB) = %.0f', u_orbit_kB)\n __log.info('>>> S per orbit (kB) = %.0f', s_orbit_kB)\n __log.info('>>> U per orbit (MB) = %.0f', u_orbit_MB)\n __log.info('>>> S per orbit (MB) = %.0f', s_orbit_MB)\n\n\ndef print_analysis(orbit, impulse, fuel_mass, exhaust_rate):\n \"\"\"Helper\n This function prints in the console the results of the analysis.\n \"\"\"\n T_s = orbit.T\n T_h = np.divide(T_s, 3600)\n\n __log.info('>>> orbital period (s) = %.0f, (h) = %.3f', T_s, T_h)\n __log.info('>>> (T_i, T_e) (s) = (%.0f, %.0f)', orbit.T_i, orbit.T_e)\n __log.info('>>> delta_v (m/s) = %.3f,', orbit.v)\n __log.info('>>> impulse (s) = %s', impulse)\n __log.info('>>> fuel (kg) = %s', fuel_mass)\n __log.info('>>> exhaust rate (g/s) = %s', np.multiply(exhaust_rate, 1000))\n\n\nh = 500000 # altitude in meters\ni = [50, 90] # inclination of the orbital plane\n\nMOTHER_COVERAGE = 10 * 3600 # hours, mothership / mission specs\nTDMA_SLOTS = 10 # mothership / mission specs\nU_BITRATE = 512E3 # 512 kbps, mothership / mission specs\nS_BITRATE = 3E6 # 3 Mbps, mothership / mission specs\n\ncubesat_mass = 24 # 12U CubeSat mass (specs)\nprotocol_overhead = 0.1 # comms protocol efficiency (ASSUMPTION)\n\n# ### Calculations\n\nllo = orbiter.Orbiter(h, i, central_body=orbit_k.Moon)\nleo = orbiter.Orbiter(h, i, central_body=orbit_k.Earth)\n\nllo_descent = manoeuvres.calculate_descent(\n llo, cubesat_mass,\n descent_delta_v=orbit_k.Moon['llo2surface-delta-v']['value']\n)\nleo_descent = manoeuvres.calculate_descent(\n leo, cubesat_mass,\n descent_delta_v=orbit_k.Earth['leo2surface-delta-v']['value']\n)\n\ncomms_orbits = np.divide(MOTHER_COVERAGE, llo.T)\ncoverage_time = np.multiply(comms_orbits, llo.T_i)\ncontact_time = np.divide(coverage_time, TDMA_SLOTS)\n\nu_max_data = np.multiply(\n np.multiply(contact_time, U_BITRATE), protocol_overhead\n)\ns_max_data = np.multiply(\n np.multiply(contact_time, S_BITRATE), protocol_overhead\n)\n\n# ### printing results\n__log.info('Results using the Moon as a central body')\nprint_analysis(llo, *llo_descent)\nprint_comms(\n llo,\n MOTHER_COVERAGE, coverage_time, contact_time, s_max_data, u_max_data\n)\n# __log.info('Results for the Earth as a central body')\n# print_analysis(leo, *leo_descent)\n","sub_path":"src/spearcube.py","file_name":"spearcube.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"520497726","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\ndef getCryptocurrencyInfo(symbol):\n\n url = \"https://www.bithumb.com/\"\n\n _START_TIME = time.time()\n\n if getNameFromCryptoSymbol(symbol) == 404: # 항목 없음 에러 코드\n return 404 # 함수 종료\n\n try:\n response = requests.get(url, timeout=0.9)\n print(\"getting information about : \" + symbol)\n #time.sleep(1)\n except:\n # timeout 내에 제대로 bithumb.com에서 응답이 돌아오지 않는 경우\n # 404란 error returning code를 대신 반환하고,\n # 이것을 run.py\n return 404, 404, 404, 404, 404, 404, 404\n\n if response.status_code == 200:\n #print(\"access ok\")\n html = response.text\n soup = BeautifulSoup(html, 'html.parser')\n\n # selector name 가져오기\n SELECTOR_NAME_PRICE = \"#assetReal\" + symbol + \"_KRW\"\n SELECTOR_NAME_CHANGE_KRW = \"#assetRealPrice\" + symbol + \"_KRW\"\n SELECTOR_NAME_CHANGE_PERCENT = \"#assetRealRate\" + symbol + \"_KRW\"\n SELECTOR_NAME_TRANSACTION = \"#assetReal\" + symbol + \"_KRW2KRW\"\n\n cryptocurrency_KRname = getNameFromCryptoSymbol(symbol)\n cryptocurrency_to_KRW = soup.select_one(SELECTOR_NAME_PRICE).get_text() # 가격 추출\n cryptocurrency_change_KRW = soup.select_one(SELECTOR_NAME_CHANGE_KRW).get_text() # 변동량 추출\n cryptocurrency_change_PERCENT = soup.select_one(SELECTOR_NAME_CHANGE_PERCENT).get_text() # 변동률 추출\n cryptocurrency_transaction_KRW = soup.select_one(SELECTOR_NAME_TRANSACTION).get_text().replace('₩','').split('.', 1)[0] + \" [bithumb 거래소 기준]\" # 거래량(24hr) 추출\n\n # 추가 정보\n # 암호화폐 거래량을 KRW 단위가 아닌 요청한 암호화폐 단위로 보여준다.\n realTransactionKRW = int(soup.select_one(SELECTOR_NAME_TRANSACTION).get_text().replace('≈','').replace(',','').replace('원','').replace(' ',''))\n realTransactionCRYPTO = int(soup.select_one(SELECTOR_NAME_PRICE).get_text().replace(',','').replace('원','').replace(' ',''))\n #print(realTransactionKRW) \n #print(realTransactionCRYPTO)\n cryptocurrency_transaction_CRYPTO = round((realTransactionKRW / realTransactionCRYPTO), 2)\n cryptocurrency_transaction_CRYPTO = \"≈ \" + (\"{:,}\".format(cryptocurrency_transaction_CRYPTO))\n\n # print(cryptocurrency_KRname)\n # print(cryptocurrency_to_KRW)\n # print(cryptocurrency_change_KRW)\n # print(cryptocurrency_change_PERCENT)\n # print(cryptocurrency_transaction_KRW)\n # print(cryptocurrency_transaction_CRYPTO)\n\n # 문자열로 모두 변환시켜주자(원활한 출력을 위해서)\n\n _END_TIME = time.time()\n running_time = round((_END_TIME - _START_TIME), 4)\n print(\"running time : \", str(running_time) + \" SEC.\")\n\n return str(cryptocurrency_KRname), str(cryptocurrency_to_KRW), str(cryptocurrency_change_KRW), str(cryptocurrency_change_PERCENT), str(cryptocurrency_transaction_KRW), str(cryptocurrency_transaction_CRYPTO), str(running_time)\n\n\ndef getNameFromCryptoSymbol(symbol):\n\n file = open('./resource/cryptocurrencySymbolList.txt','rt', encoding='UTF8')\n \n try:\n while True:\n line = file.readline()\n if symbol == line.split()[0]: # 정확한 암호화폐명을 입력해야만 결과를 반환\n name = line.split('\\t')[1].strip()\n break\n if not line:\n return 404\n\n except: # 제대로 입력하지 않아 예외가 생기면 모두 404 에러처리\n return 404\n \n file.close()\n\n return name\n\n# print(getNameFromCryptoSymbol(\"ARW\"))\n\n# print(getCryptocurrencyInfo(\"BTC\"))\n# print(getCryptocurrencyInfo(\"ETH\"))\n# print(getCryptocurrencyInfo(\"XRP\"))\n# print(getCryptocurrencyInfo(\"DOT\"))\n# print(getCryptocurrencyInfo(\"XLM\"))\n# print(getCryptocurrencyInfo(\"EOS\"))\n# print(getCryptocurrencyInfo(\"TRX\"))\n# print(getCryptocurrencyInfo(\"ARW\"))\n# print(getCryptocurrencyInfo(\"LTC\"))\n# print(getCryptocurrencyInfo(\"CRO\"))\n# print(getCryptocurrencyInfo(\"XTZ\"))\n# print(getCryptocurrencyInfo(\"ETC\"))\n# print(getCryptocurrencyInfo(\"UNI\"))\n# print(getCryptocurrencyInfo(\"VET\"))\n# print(getCryptocurrencyInfo(\"XEM\"))\n# print(getCryptocurrencyInfo(\"ENJ\"))\n# print(getCryptocurrencyInfo(\"GRT\"))","sub_path":"Outdated/getCryptocurrencyInfo_OLD.py","file_name":"getCryptocurrencyInfo_OLD.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"477147399","text":"# __author__ = 橙子老师\r\n# __date__ = 2020-08-24\r\n\r\n# 导入MySQLdb模块\r\nimport MySQLdb\r\nimport config\r\n\r\n\"\"\"\r\n所有回调函数都遵循相同的接口规范,读者在实际开发中,可以将回调函数作为业务层的代码\r\n分离到其它文件\r\n\"\"\"\r\n\r\ndef query_all_employee(table_name, cursor, **kwargs):\r\n \"\"\"\r\n :param table_name: 有效的mysql数据表名\r\n 数据表名的关系模型(id, name)\r\n :param ursor: 数据库的游标对象\r\n :return:\r\n \"\"\"\r\n\r\n sql = \"select id, name from {}\".format(table_name)\r\n cursor.execute(sql)\r\n for index, row in enumerate(cursor.fetchall()):\r\n print(\"{}. 员工编号:{} 员工姓名:{}\".format(index+1, row[0], row[1]))\r\n\r\n\r\ndef add_employee(table_name , cursor, **kwargs):\r\n \"\"\"\r\n :param table_name: 有效的mysql数据表名\r\n 数据表名的关系模��(id, name)\r\n :param cursor: 数据库的游标对象\r\n :param kwargs: 可变参数,支持传递的参数有db_handler,表示MySQL数据库对象,\r\n redis_handler表示redis连接对象\r\n :return:\r\n \"\"\"\r\n\r\n employee_name = input(\"请输入员工的姓名:___\\b\\b\\b\")\r\n age = input(\"请输入员工的年龄:___\\b\\b\\b\")\r\n salary = input(\"请输入员工的工资:___\\b\\b\\b\")\r\n sex = input(\"请输入员工的性别:___\\b\\b\\b\")\r\n\r\n\r\n sql = \"insert into {}(name,age,slalary,sex) values(%s,%s,%s,%s)\".format(table_name)\r\n\r\n affected_rows = cursor.execute(sql, (employee_name,age,salary,sex ))\r\n if affected_rows < 1:\r\n print(\"数据库操作发生异常\")\r\n else:\r\n _ = kwargs[\"db_handler\"].commit() if \"db_handler\" in kwargs else None\r\n print(\"员工{}已被添加至数据库\".format(employee_name))\r\n\r\n\r\ndef delete_employee(table_name, cursor, **kwargs):\r\n \"\"\"\r\n :param table_name: 有效的mysql数据表名\r\n 数据表名的关系模型(id, name)\r\n :param cursor: 数据库的游标对象\r\n :param kwargs: 可变参数,支持传递的参数有db_handler,表示MySQL数据库对象,\r\n redis_handler表示redis连接对象\r\n :return:\r\n \"\"\"\r\n\r\n try:\r\n employee_id = int(input(\"请输入员工的编号:__\\b\\b\"))\r\n except ValueError:\r\n employee_id = -1\r\n print(\"你输入了无效的员工编号\")\r\n\r\n if employee_id > 0:\r\n sql = \"delete from {} where id=%s\".format(table_name)\r\n affected_rows = cursor.execute(sql, (employee_id, ))\r\n if affected_rows < 1:\r\n print(\"员工编号{}不存在\".format(employee_id))\r\n else:\r\n _ = kwargs[\"db_handler\"].commit() if \"db_handler\" in kwargs else None\r\n print(\"编号为{}的员工已从数据库删除\".format(employee_id))\r\n\r\n\r\nclass SimpleEmployeeMs:\r\n\r\n def __init__(self, table_name, cursor, db_handler=None, redis_handler=None):\r\n self.__db_handler = db_handler\r\n self.__table_name = table_name\r\n self.__cursor = cursor\r\n self.__redis_handler = redis_handler\r\n\r\n \"\"\"\r\n 定义命令字典结构,格式举例:{\r\n 1: callback_function\r\n }\r\n 这样用户在输入指定的命令时,直接调用对应的回调函数\r\n 回调函数由用户进行定义\r\n \"\"\"\r\n self.__commands = {}\r\n self.__begin_prompt = \"输入<>中的指令来执行对应的操作:\\n\"\r\n self.__quit_prompt = \" 退出员工管理系统\\n\"\r\n self.__prompts = []\r\n self.__command_index = 1\r\n\r\n def __obtain_user_command(self, prompt):\r\n\r\n command = \"quit\"\r\n valid = True\r\n try:\r\n command = input(prompt)\r\n _ = self.__commands[int(command)]\r\n\r\n except (ValueError, KeyError):\r\n if command != \"quit\":\r\n command = None\r\n valid = False\r\n return command, valid\r\n\r\n def add_command(self, prompt, cb):\r\n '''\r\n\r\n :param prompt:表示命令行的提示消息,eg:\"查询所有员工\"\r\n :param cb: 回调函数,用来定义特定的业务逻辑\r\n :return:\r\n '''\r\n self.__commands[self.__command_index] = cb\r\n \"\"\"\r\n (1)__commands是一个字典对象,键名为命令编号,\r\n 键值为具体的命令执行,通过回调函数来执行相应的处理\r\n {\r\n 0:command,\r\n 1:command\r\n \"\"\"\r\n self.__command_index +=1\r\n self.__prompts.append(prompt)\r\n\r\n def __generate_prompt(self):\r\n prompt = self.__begin_prompt\r\n for index, value in enumerate(self.__prompts):\r\n prompt += \"<{}> {}\\n\".format(index+1, value)\r\n prompt += self.__quit_prompt\r\n return prompt\r\n\r\n\r\n def serve_forever(self):\r\n prompt = self.__generate_prompt()\r\n while True:\r\n command, valid = self.__obtain_user_command(prompt)\r\n if not valid:\r\n print(\"你输入了非法的指令!\")\r\n continue\r\n\r\n if command == \"quit\":\r\n break\r\n\r\n self.__commands[int(command)](self.__table_name, self.__cursor,\r\n db_handler = self.__db_handler)\r\n print(\"--------------------------------------------\\n\")\r\n\r\n self.__cursor.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n \"\"\"\r\n (1)数据库的配置信息\r\n (2)读者在实际开发中,可以将配置信息单独写到配置文件中,\r\n 将配置信息与具体的业务代码进行分离,有助于提升代码的可维护性\r\n \"\"\"\r\n\r\n\r\n\r\n \"\"\"\r\n 在连接数据库时,需指定��据库的字符编码,否则会出现乱码\r\n mysql创建数据表时的默认编码为utf8\r\n \"\"\"\r\n try:\r\n db = MySQLdb.connect(config.DB_CONFIG[\"mysql\"][\"host\"], config.DB_CONFIG[\"mysql\"][\"username\"],\r\n config.DB_CONFIG[\"mysql\"][\"password\"], config.DB_CONFIG[\"mysql\"][\"database\"],\r\n charset=\"utf8\")\r\n mysql_cursor = db.cursor()\r\n table_name = 'employee'\r\n # 如果cursor对象无效或表名table_name不存在,则会产生异常\r\n mysql_cursor.execute(\"select 0 from {}\".format(table_name))\r\n simple_employee_ms = SimpleEmployeeMs(table_name, mysql_cursor, db)\r\n\r\n # 员工管理系统的命令行选项,以及处理逻辑都由用户来进行定义\r\n simple_employee_ms.add_command(\"查询所有员工\", query_all_employee)\r\n simple_employee_ms.add_command(\"添加新员工\", add_employee)\r\n simple_employee_ms.add_command(\"删除老员工\", delete_employee)\r\n simple_employee_ms.serve_forever()\r\n\r\n except Exception as e:\r\n print(\"数据库连接或获取游标对象时产生异常!{}\".format(e))","sub_path":"chenzhan/simple_employee_ms.py","file_name":"simple_employee_ms.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"517478108","text":"import os\nimport logging\nimport json\n\nimport requests\n\n\nDATETIME_FORMAT = '%Y-%m-%dT%H:%M:00Z'\nLOG = logging.getLogger(__name__)\n\n\nclass Uploader(object):\n API_URL = None\n API_TOKEN = None\n\n def __init__(self):\n # Load the credentials from the env\n self.API_URL = os.environ['SEALEVEL_API_URL']\n self.API_URL_NEW = os.environ['SEALEVEL_API_URL_NEW']\n self.API_TOKEN = os.environ['SEALEVEL_API_TOKEN']\n\n @classmethod\n def encode_datetime(cls, row):\n row['timestamp'] = row['timestamp'].strftime(DATETIME_FORMAT)\n return row\n\n @classmethod\n def prepare(cls, observation):\n data = dict(observation._asdict())\n data = cls.encode_datetime(data)\n data['wind_degrees'] = data['wind_direction']\n data['wind_direction'] = ''\n\n data['wind_gust'] = cls.knots_to_si(data['wind_speed_highest'])\n del data['wind_speed_highest']\n\n data['wind_speed'] = cls.knots_to_si(data['wind_speed_average'])\n del data['wind_speed_average']\n\n data['temperature'] = data['air_temperature']\n del data['air_temperature']\n\n data['precipitation'] = data['rainfall']\n del data['rainfall']\n\n data['datetime'] = data['timestamp']\n del data['timestamp']\n\n del data['dew_point']\n del data['humidity']\n\n data['supplier'] = 'seatruck'\n data['minute'] = data['datetime']\n return data\n\n @classmethod\n def knots_to_si(cls, knots):\n return knots * (1852.0 / 3600.0)\n\n def upload(self, slug, observation):\n headers = {\n 'Authorization': 'Token {}'.format(self.API_TOKEN),\n 'Content-Type': 'application/json'\n }\n\n url = self.API_URL.format(location_slug=slug)\n url_new = self.API_URL_NEW.format(location_slug=slug)\n data = self.prepare(observation)\n payload = json.dumps([data])\n print(payload)\n LOG.info('HTTP POST {}'.format(url))\n response = requests.post(url, payload, headers=headers, timeout=90)\n response.raise_for_status()\n\n response = requests.post(url_new, payload, headers=headers, timeout=90)\n response.raise_for_status()\n","sub_path":"collector/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"541890814","text":"import math\nimport random\nimport uuid\n\nimport numpy as np\nfrom rtree import index\n\n\ndef obstacle_generator(obstacles):\n \"\"\"\n Add obstacles to r-tree\n \"\"\"\n for obstacle in obstacles:\n yield (uuid.uuid4(), obstacle, obstacle)\n\n\ndef dist_between_points(a, b):\n \"\"\"\n #return: Euclidean distance between a and b\n \"\"\"\n distance = sum(map(lambda a_b: (a_b[0] - a_b[1]) ** 2, zip(a, b)))\n\n return math.sqrt(distance)\n\n\nclass ConfigureSpace(object):\n def __init__(self, dimension_lengths, O=None):\n \"\"\"\n Initialize Search Space\n \"\"\"\n # sanity check\n if len(dimension_lengths) < 2:\n raise Exception(\"Must have at least 2 dimensions\")\n self.dimensions = len(dimension_lengths) # number of dimensions\n # sanity checks\n if any(len(i) != 2 for i in dimension_lengths):\n raise Exception(\"Dimensions can only have a start and end\")\n if any(i[0] >= i[1] for i in dimension_lengths):\n raise Exception(\"Dimension start must be less than dimension end\")\n self.dimension_lengths = dimension_lengths # length of each dimension\n p = index.Property()\n p.dimension = self.dimensions\n if O is None:\n self.obs = index.Index(interleaved=True, properties=p)\n else:\n # r-tree representation of obstacles\n # sanity check\n if any(len(o) / 2 != len(dimension_lengths) for o in O):\n raise Exception(\"Obstacle has incorrect dimension definition\")\n if any(o[i] >= o[int(i + len(o) / 2)] for o in O for i in range(int(len(o) / 2))):\n raise Exception(\"Obstacle start must be less than obstacle end\")\n self.obs = index.Index(obstacle_generator(O), interleaved=True, properties=p)\n\n def obstacle_free(self, x):\n \"\"\"\n Check if a location resides inside of an obstacle\n\n \"\"\"\n return self.obs.count(x) == 0\n\n def sample_free(self,x_new):\n \"\"\"\n Sample a location within X_free\n \"\"\"\n\n while True: # sample until not inside of an obstacle\n x = self.sample()\n if self.obstacle_free(x):\n return x\n\n def collision_free(self, start, end, r):\n \"\"\"\n Check if a line segment intersects an obstacle\n \"\"\"\n dist = dist_between_points(start, end)\n # divide line between points into equidistant points at given resolution\n dim_linspaces = [np.linspace(s_i, e_i, int(math.ceil(dist / r))) for s_i, e_i in zip(start, end)]\n\n coll_free = all(map(self.obstacle_free, zip(*dim_linspaces)))\n\n return coll_free\n\n def sample(self):\n \"\"\"\n Return a random location within X\n \"\"\"\n x = np.empty(len(self.dimension_lengths), np.float)\n for dimension in range(len(self.dimension_lengths)):\n\n x[dimension] = random.uniform(self.dimension_lengths[dimension][0], self.dimension_lengths[dimension][1])\n\n return tuple(x)\n","sub_path":"Phase2/configure_space.py","file_name":"configure_space.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"145460040","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom hellodjango.views import hello, current_datetime, hours_ahead\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'hellodjango.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n # my urls\n url(r'^hello/$', hello),\n url(r'^time/$', current_datetime),\n url(r'^time/plus/(\\d{1,2})/$', hours_ahead),\n url(r'^books/$', 'books.views.publishers', name='publishers'),\n url(r'^meta/$', 'hellodjango.views.display_meta', name='display_meta'),\n url(r'^search/$', 'books.views.search', name='search'),\n url(r'^contact/$', 'hellodjango.views.contact', name='contact'),\n url(r'^contact/thanks/$', 'hellodjango.views.thanks', name='thanks'),\n\n # admin urls\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"hellodjango/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"17201275","text":"import json\nimport logging\nimport os\nimport time\n\nimport numpy as np\nimport scipy\nimport torch\nfrom torch.utils.data import DataLoader, Dataset, RandomSampler\nimport tqdm\nimport transformers\n\nimport textattack\n\nfrom .train_args_helpers import dataset_from_args, model_from_args, write_readme\n\ndevice = textattack.shared.utils.device\nlogger = textattack.shared.logger\n\n\ndef make_directories(output_dir):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n\ndef batch_encode(tokenizer, text_list):\n if hasattr(tokenizer, \"batch_encode\"):\n return tokenizer.batch_encode(text_list)\n else:\n return [tokenizer.encode(text_input) for text_input in text_list]\n\n\ndef train_model(args):\n logger.warn(\n \"WARNING: TextAttack's model training feature is in beta. Please report any issues on our Github page, https://github.com/QData/TextAttack/issues.\"\n )\n start_time = time.time()\n make_directories(args.output_dir)\n\n num_gpus = torch.cuda.device_count()\n\n # Save logger writes to file\n log_txt_path = os.path.join(args.output_dir, \"log.txt\")\n fh = logging.FileHandler(log_txt_path)\n fh.setLevel(logging.DEBUG)\n logger.addHandler(fh)\n logger.info(f\"Writing logs to {log_txt_path}.\")\n\n # Use Weights & Biases, if enabled.\n if args.enable_wandb:\n global wandb\n import wandb\n\n wandb.init(sync_tensorboard=True)\n\n # Get list of text and list of label (integers) from disk.\n train_text, train_labels, eval_text, eval_labels = dataset_from_args(args)\n\n # Filter labels\n if args.allowed_labels:\n logger.info(f\"Filtering samples with labels outside of {args.allowed_labels}.\")\n final_train_text, final_train_labels = [], []\n for text, label in zip(train_text, train_labels):\n if label in args.allowed_labels:\n final_train_text.append(text)\n final_train_labels.append(label)\n logger.info(\n f\"Filtered {len(train_text)} train samples to {len(final_train_text)} points.\"\n )\n train_text, train_labels = final_train_text, final_train_labels\n final_eval_text, final_eval_labels = [], []\n for text, label in zip(eval_text, eval_labels):\n if label in args.allowed_labels:\n final_eval_text.append(text)\n final_eval_labels.append(label)\n logger.info(\n f\"Filtered {len(eval_text)} dev samples to {len(final_eval_text)} points.\"\n )\n eval_text, eval_labels = final_eval_text, final_eval_labels\n\n label_id_len = len(train_labels)\n label_set = set(train_labels)\n args.num_labels = len(label_set)\n logger.info(\n f\"Loaded dataset. Found: {args.num_labels} labels: ({sorted(label_set)})\"\n )\n\n if isinstance(train_labels[0], float):\n # TODO come up with a more sophisticated scheme for when to do regression\n logger.warn(f\"Detected float labels. Doing regression.\")\n args.num_labels = 1\n args.do_regression = True\n else:\n args.do_regression = False\n\n train_examples_len = len(train_text)\n\n if len(train_labels) != train_examples_len:\n raise ValueError(\n f\"Number of train examples ({train_examples_len}) does not match number of labels ({len(train_labels)})\"\n )\n if len(eval_labels) != len(eval_text):\n raise ValueError(\n f\"Number of teste xamples ({len(eval_text)}) does not match number of labels ({len(eval_labels)})\"\n )\n\n model = model_from_args(args, args.num_labels)\n tokenizer = model.tokenizer\n\n logger.info(f\"Tokenizing training data. (len: {train_examples_len})\")\n train_text_ids = batch_encode(tokenizer, train_text)\n logger.info(f\"Tokenizing eval data (len: {len(eval_labels)})\")\n eval_text_ids = batch_encode(tokenizer, eval_text)\n load_time = time.time()\n logger.info(f\"Loaded data and tokenized in {load_time-start_time}s\")\n\n # multi-gpu training\n if num_gpus > 1:\n model = torch.nn.DataParallel(model)\n logger.info(f\"Training model across {num_gpus} GPUs\")\n\n num_train_optimization_steps = (\n int(train_examples_len / args.batch_size / args.grad_accum_steps)\n * args.num_train_epochs\n )\n\n param_optimizer = list(model.named_parameters())\n no_decay = [\"bias\", \"LayerNorm.bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [\n p for n, p in param_optimizer if not any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.01,\n },\n {\n \"params\": [\n p for n, p in param_optimizer if any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.0,\n },\n ]\n\n optimizer = transformers.optimization.AdamW(\n optimizer_grouped_parameters, lr=args.learning_rate\n )\n\n scheduler = transformers.optimization.get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps=args.warmup_proportion,\n num_training_steps=num_train_optimization_steps,\n )\n\n global_step = 0\n\n # Start Tensorboard and log hyperparams.\n from tensorboardX import SummaryWriter\n\n tb_writer = SummaryWriter(args.output_dir)\n\n def is_writable_type(obj):\n for ok_type in [bool, int, str, float]:\n if isinstance(obj, ok_type):\n return True\n return False\n\n args_dict = {k: v for k, v in vars(args).items() if is_writable_type(v)}\n\n tb_writer.add_hparams(args_dict, {})\n\n # Start training\n logger.info(\"***** Running training *****\")\n logger.info(f\"\\tNum examples = {train_examples_len}\")\n logger.info(f\"\\tBatch size = {args.batch_size}\")\n logger.info(f\"\\tMax sequence length = {args.max_length}\")\n logger.info(f\"\\tNum steps = {num_train_optimization_steps}\")\n logger.info(f\"\\tNum epochs = {args.num_train_epochs}\")\n logger.info(f\"\\tLearning rate = {args.learning_rate}\")\n\n train_input_ids = np.array(train_text_ids)\n train_labels = np.array(train_labels)\n train_data = list((ids, label) for ids, label in zip(train_input_ids, train_labels))\n train_sampler = RandomSampler(train_data)\n train_dataloader = DataLoader(\n train_data, sampler=train_sampler, batch_size=args.batch_size\n )\n\n eval_input_ids = np.array(eval_text_ids)\n eval_labels = np.array(eval_labels)\n eval_data = list((ids, label) for ids, label in zip(eval_input_ids, eval_labels))\n eval_sampler = RandomSampler(eval_data)\n eval_dataloader = DataLoader(\n eval_data, sampler=eval_sampler, batch_size=args.batch_size\n )\n\n def get_eval_score():\n model.eval()\n correct = 0\n total = 0\n logits = []\n labels = []\n for input_ids, batch_labels in eval_dataloader:\n if isinstance(input_ids, dict):\n ## HACK: dataloader collates dict backwards. This is a temporary\n # workaround to get ids in the right shape\n input_ids = {\n k: torch.stack(v).T.to(device) for k, v in input_ids.items()\n }\n batch_labels = batch_labels.to(device)\n\n with torch.no_grad():\n batch_logits = textattack.shared.utils.model_predict(model, input_ids)\n\n logits.extend(batch_logits.cpu().squeeze().tolist())\n labels.extend(batch_labels)\n\n model.train()\n logits = torch.tensor(logits)\n labels = torch.tensor(labels)\n\n if args.do_regression:\n pearson_correlation, pearson_p_value = scipy.stats.pearsonr(logits, labels)\n return pearson_correlation\n else:\n preds = logits.argmax(dim=1)\n correct = (preds == labels).sum()\n return float(correct) / len(labels)\n\n def save_model():\n model_to_save = (\n model.module if hasattr(model, \"module\") else model\n ) # Only save the model itself\n\n # If we save using the predefined names, we can load using `from_pretrained`\n output_model_file = os.path.join(args.output_dir, args.weights_name)\n output_config_file = os.path.join(args.output_dir, args.config_name)\n\n torch.save(model_to_save.state_dict(), output_model_file)\n try:\n model_to_save.config.to_json_file(output_config_file)\n except AttributeError:\n # no config\n pass\n\n global_step = 0\n\n def save_model_checkpoint():\n # Save model checkpoint\n output_dir = os.path.join(args.output_dir, \"checkpoint-{}\".format(global_step))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n # Take care of distributed/parallel training\n model_to_save = model.module if hasattr(model, \"module\") else model\n model_to_save.save_pretrained(output_dir)\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\n logger.info(f\"Checkpoint saved to {output_dir}.\")\n\n model.train()\n args.best_eval_score = 0\n args.best_eval_score_epoch = 0\n args.epochs_since_best_eval_score = 0\n\n def loss_backward(loss):\n if num_gpus > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n if args.grad_accum_steps > 1:\n loss = loss / args.grad_accum_steps\n loss.backward()\n return loss\n\n for epoch in tqdm.trange(\n int(args.num_train_epochs), desc=\"Epoch\", position=0, leave=False\n ):\n prog_bar = tqdm.tqdm(\n train_dataloader, desc=\"Iteration\", position=1, leave=False\n )\n for step, batch in enumerate(prog_bar):\n input_ids, labels = batch\n labels = labels.to(device)\n if isinstance(input_ids, dict):\n ## HACK: dataloader collates dict backwards. This is a temporary\n # workaround to get ids in the right shape\n input_ids = {\n k: torch.stack(v).T.to(device) for k, v in input_ids.items()\n }\n logits = textattack.shared.utils.model_predict(model, input_ids)\n\n if args.do_regression:\n # TODO integrate with textattack `metrics` package\n loss_fct = torch.nn.MSELoss()\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss_fct = torch.nn.CrossEntropyLoss()\n loss = loss_fct(logits, labels)\n loss = loss_backward(loss)\n\n if global_step % args.tb_writer_step == 0:\n tb_writer.add_scalar(\"loss\", loss.item(), global_step)\n tb_writer.add_scalar(\"lr\", scheduler.get_last_lr()[0], global_step)\n prog_bar.set_description(f\"Loss {loss.item()}\")\n if (step + 1) % args.grad_accum_steps == 0:\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n # Save model checkpoint to file.\n if (\n global_step > 0\n and (args.checkpoint_steps > 0)\n and (global_step % args.checkpoint_steps) == 0\n ):\n save_model_checkpoint()\n\n model.zero_grad()\n\n # Inc step counter.\n global_step += 1\n\n # Check accuracy after each epoch.\n eval_score = get_eval_score()\n tb_writer.add_scalar(\"epoch_eval_score\", eval_score, global_step)\n\n if args.checkpoint_every_epoch:\n save_model_checkpoint()\n\n logger.info(\n f\"Eval {'pearson correlation' if args.do_regression else 'accuracy'}: {eval_score*100}%\"\n )\n if eval_score > args.best_eval_score:\n args.best_eval_score = eval_score\n args.best_eval_score_epoch = epoch\n args.epochs_since_best_eval_score = 0\n save_model()\n logger.info(f\"Best acc found. Saved model to {args.output_dir}.\")\n else:\n args.epochs_since_best_eval_score += 1\n if (args.early_stopping_epochs > 0) and (\n args.epochs_since_best_eval_score > args.early_stopping_epochs\n ):\n logger.info(\n f\"Stopping early since it's been {args.early_stopping_epochs} steps since validation acc increased\"\n )\n break\n\n # end of training, save tokenizer\n try:\n tokenizer.save_pretrained(args.output_dir)\n logger.info(f\"Saved tokenizer {tokenizer} to {args.output_dir}.\")\n except AttributeError:\n logger.warn(\n f\"Error: could not save tokenizer {tokenizer} to {args.output_dir}.\"\n )\n\n # Save a little readme with model info\n write_readme(args, args.best_eval_score, args.best_eval_score_epoch)\n\n # Save args to file\n args_save_path = os.path.join(args.output_dir, \"train_args.json\")\n final_args_dict = {k: v for k, v in vars(args).items() if is_writable_type(v)}\n with open(args_save_path, \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(final_args_dict, indent=2) + \"\\n\")\n logger.info(f\"Wrote training args to {args_save_path}.\")\n","sub_path":"textattack/commands/train_model/run_training.py","file_name":"run_training.py","file_ext":"py","file_size_in_byte":13112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"74049057","text":"import itertools\nimport re\n\nfrom . import document\n\n\nSPACEPTN = r' \\t\\n\\r'\nWORDPTN = r'a-zA-Z0-9'\nCTRLPTN = re.escape(''.join(map(chr, itertools.chain(range(0,8), [11,12], range(14,32), range(127,160)))))\n\n\ndef mktype(chars):\n return re.compile(r'(^|(? \"\n else: data = data + str(i) + \" => \"\n data = data + '\"' + \"\".join(binary) + '\"' + \",\\n\"\n i += 1\n\n if (len(instructionList) < 64):\n data = data + \"others => (others => '0'));\"\n\n if(DestinationFilename == None):\n print(\"\\n\" + data)\n else:\n file = open(DestinationFilename, \"w\")\n textFull = file.write(data)\n file.close()\n print(\"\\nAll OK\")\n\ndef getBinary(value, nBits):\n isneg = value < 0\n binary = list(\"0\" * nBits)\n if (isneg): value *= -1\n\n for i in range(nBits):\n pot = 2**(nBits-1 - i)\n\n if (value >= pot):\n binary[i] = '1'\n value -= pot\n\n if isneg:\n for i in range(nBits):\n if (binary[i] == '1'): binary[i] = '0'\n else: binary[i] = '1'\n\n if (binary[nBits-1] == '0'): binary[nBits-1] = '1'\n else:\n binary[nBits-1] = '0'\n\n i = nBits-2\n while (i > 0 and binary[i] == '1'):\n binary[i] = '0'\n i -= 1\n\n if (i != nBits): binary[i] = '1'\n\n return binary\n\ndef getInstruction(name):\n aux = {\"type\": -1}\n for i in translator:\n if i.get(\"name\") == name:\n aux = i\n return aux\n\ndef convertInstruction(instruction):\n code = list(\"0\" * 32)\n components = instruction.split(' ')\n\n print(\"-\"*50)\n print(\"Original instruction: \" + str(instruction))\n\n instruction = getInstruction(components[0])\n\n print(\"Instruction detected: \" + str(instruction))\n print(\"Components detected: \" + str(components))\n\n if (instruction.get(\"type\") == 0):\n rd = getBinary(int(components[1]), 5)\n rs = getBinary(int(components[2]), 5)\n if (instruction.get(\"subtype\") == 0):\n rt = getBinary(int(components[3]), 5)\n else:\n rt = getBinary(0, 5)\n\n for i in range(4): code[i] = instruction.get(\"opcode\")[i]\n for i in range(2): code[i + 4] = instruction.get(\"flags\")[i]\n for i in range(5): code[i + 6] = rd[i]\n for i in range(5): code[i + 11] = rs[i]\n for i in range(5): code[i + 16] = rt[i]\n for i in range(11): code[i + 21] = instruction.get(\"flags2\")[i]\n\n elif (instruction.get(\"type\") == 1):\n rd = []\n rs = []\n imm = []\n if (instruction.get(\"subtype\") == 0):\n rd = getBinary(int(components[2]), 5)\n rs = getBinary(int(components[1]), 5)\n imm = getBinary(int(components[3]), 16)\n elif (instruction.get(\"subtype\") == 1):\n rd = getBinary(int(components[2]), 5)\n rs = getBinary(int(components[1]), 5)\n imm = getBinary(0, 16)\n elif (instruction.get(\"subtype\") == 2):\n rd = getBinary(int(components[1]), 5)\n rs = getBinary(int(components[2]), 5)\n imm = getBinary(int(components[3]), 16)\n else:\n rd = getBinary(int(components[1]), 5)\n rs = getBinary(0, 5)\n imm = getBinary(int(components[2]), 16)\n\n for i in range(4): code[i] = instruction.get(\"opcode\")[i]\n for i in range(2): code[i + 4] = instruction.get(\"flags\")[i]\n for i in range(5): code[i + 6] = rd[i]\n for i in range(5): code[i + 11] = rs[i]\n for i in range(16): code[i + 16] = imm[i]\n\n elif (instruction.get(\"type\") == 2):\n imm = []\n if (len(components) > 1): imm = getBinary(int(components[1]), 26)\n else: imm = getBinary(0, 26)\n\n for i in range(4): code[i] = instruction.get(\"opcode\")[i]\n for i in range(2): code[i + 4] = instruction.get(\"flags\")[i]\n for i in range(26): code[i + 6] = imm[i]\n\n return code\n\n###################################### 02200000 0000 00 10001 00000 0000000000000000\n\nbinaries = []\n\nif (len(sys.argv) < 2):\n\tprint(\"Number of arguments given wrong!\\nUse python assembler_v2.py to obtain the result on the given path\\nUse python assembler_v2.py to obtain the result on screen.\")\nelse:\n #Instructions loaded from the given path\n instructionList = loadData( sys.argv[1] )\n\n #Each instruction is converted to the binary format for the final result\n for instruction in instructionList:\n converted = convertInstruction(instruction)\n print(\"\".join(converted))\n\n binaries.append(converted[24:32])\n binaries.append(converted[16:24])\n binaries.append(converted[8:16])\n binaries.append(converted[0:8])\n\n if(len(sys.argv) == 3):\n showResult(binaries, sys.argv[2])\n else:\n showResult(binaries, None)\n","sub_path":"CPU_Semi-Out-Of-Order/assembler_v2.py","file_name":"assembler_v2.py","file_ext":"py","file_size_in_byte":11380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"425488690","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 23:46:19 2019\n\n@author: Padamban\n\"\"\"\n\nimport os\nimport matplotlib.pyplot as plt\nimport simpleaudio as sa\nimport numpy as np\nimport scipy\nfrom scipy import signal\nfrom mpl_toolkits import mplot3d\nimport scipy.io.wavfile as wav\nimport random\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport pickle\nimport scipy.signal as sg\n\n\nclass AudioManager:\n \n def readAudio(self, file):\n fs, raw_audio = wav.read(file) \n raw = np.array([raw_audio]).astype(float)[0]\n return raw \n \n def playOriginalAudio(self,file):\n wave_obj = sa.WaveObject.from_wave_file(file)\n play_obj = wave_obj.play()\n play_obj.wait_done()\n \n def playSyntesizedAudio(self, syntesized):\n Sn = syntesized\n ply = Sn * 32767 / max(abs(Sn))\n ply = ply.astype(np.int16)\n play_obj = sa.play_buffer(ply, 1, 2, 8000)\n play_obj.wait_done()\n \n\nclass Printer:\n \n def __init__(self, enable):\n self.enable = enable\n \n def prnt(self, tab, text, enable=0):\n indent = \"|\"+ \" \"*int(tab) \n if self.enable or enable:\n print(indent+text)\n \n def plot(self, data, sep=False):\n fig, ax1 = plt.subplots()\n for i, d in enumerate(data):\n ax = ax1.twinx() if sep and i else ax1 \n span = range(d[3],d[3]+len(d[0])) if len(d) == 4 else d[4]\n ax.plot(span, d[0], d[2], label=d[1]) \n plt.legend()\n plt.show() \n \n \n \nclass Pickle:\n def __init__(self, folder, sTag='', lTag=''):\n self.folder = folder\n self.saveTag = sTag\n self.loadTag = lTag\n\n def path(self, name, tag=''):\n return self.folder + '/' + tag + str(name) +'.pkl'\n \n def save(self, name, data, oTag=None):\n tag = self.saveTag if oTag==None else oTag\n pickle_out = open( self.path(name, tag) ,\"wb\")\n pickle.dump(data, pickle_out)\n pickle_out.close()\n\n def load(self, name, oTag=None):\n tag = self.loadTag if oTag==None else oTag\n pickle_in = open(self.path(name, tag), 'rb')\n data = pickle.load(pickle_in)\n pickle_in.close()\n return data \n \n def SaveData(self, data, oTag=None):\n self.save('raw', data.raw, oTag)\n self.save('gain', data.gain, oTag)\n self.save('pitch', data.pitch, oTag)\n self.save('power', data.power, oTag)\n self.save('lpc', data.lpc, oTag)\n\n\n def LoadData(self, oTag=None):\n data = SpeachData(); \n data.raw = self.load('raw', oTag)\n data.gain = self.load('gain', oTag)\n data.power = self.load('power', oTag)\n data.pitch = self.load('pitch', oTag) \n data.lpc = self.load('lpc', oTag) \n return data\n\n \n def SaveEncoded(self, data, oTag=None):\n self.save('binaries', data.binaries, oTag)\n self.save('maxgain', data.maxGain, oTag)\n\n\n def LoadEncoded(self, oTag=None):\n data = EncodedData(); \n data.binaries = self.load('binaries', oTag)\n data.maxGain = self.load('maxgain', oTag) \n return data\n \n def SaveDecoded(self, data, oTag=None):\n self.save('qlpc', data.lpc, oTag)\n self.save('qpitch', data.pitch, oTag)\n self.save('qgain', data.gain, oTag)\n\n\n def LoadDecoded(self, oTag=None):\n data = DecodedData(); \n data.lpc = self.load('qlpc', oTag)\n data.gain = self.load('qgain', oTag) \n data.pitch = self.load('qpitch', oTag) \n return data\n\n def getFileSize(self, file):\n return os.path.getsize(file)\n\n\n\nclass Math:\n \n def autocorrelation(self, x) : \n xp = x-np.mean(x)\n f = np.fft.fft(xp)\n p = np.array([np.real(v)**2+np.imag(v)**2 for v in f]) \n pi = np.fft.ifft(p)\n c = np.real(pi)[:int(x.size/2)]/np.sum(xp**2)\n return c\n \n def normalize(self, d):\n return 2*(d - np.min(d))/np.ptp(d)-1\n \n \nclass SpeachData:\n raw=[]\n pitch=[]\n power=[]\n lpc=[]\n gain=[] \n \n\n \nclass EncodedData:\n binaries = ''\n maxGain = 0\n\nclass DecodedData:\n lpc = []\n gain = []\n pitch = []\n\n\n\n ","sub_path":"P1/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"14848109","text":"fname = input(\"Enter file name: \")\nfh = open(fname)\nlst = list()\nfor line in fh:\n line=line.rstrip()\n words=line.split()\n for each in words:\n if each not in lst:\n lst.append(each)\nlst.sort()\nprint(lst)\n","sub_path":"words.py","file_name":"words.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"57185148","text":"#!/usr/bin/env python3\n\"\"\"\nDefines a function that builds an identity block\nusing Keras\n\"\"\"\nimport tensorflow.keras as K\n\n\ndef identity_block(A_prev, filters):\n \"\"\"\n Builds an identity block using Keras\n \"\"\"\n F11, F3, F12 = filters\n init = K.initializers.he_normal()\n activation = K.activations.relu\n C11 = K.layers.Conv2D(filters=F11,\n kernel_size=(1, 1),\n padding='same',\n kernel_initializer=init)(A_prev)\n Batch_Norm11 = K.layers.BatchNormalization(axis=3)(C11)\n ReLU11 = K.layers.Activation(activation)(Batch_Norm11)\n C3 = K.layers.Conv2D(filters=F3,\n kernel_size=(3, 3),\n padding='same',\n kernel_initializer=init)(ReLU11)\n Batch_Norm3 = K.layers.BatchNormalization(axis=3)(C3)\n ReLU3 = K.layers.Activation(activation)(Batch_Norm3)\n C12 = K.layers.Conv2D(filters=F12,\n kernel_size=(1, 1),\n padding='same',\n kernel_initializer=init)(ReLU3)\n Batch_Norm12 = K.layers.BatchNormalization(axis=3)(C12)\n Addition = K.layers.Add()([Batch_Norm12, A_prev])\n output = K.layers.Activation(activation)(Addition)\n return output\n","sub_path":"supervised_learning/0x08-deep_cnns/2-identity_block.py","file_name":"2-identity_block.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"491875204","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 15 15:47:20 2019\nPlots all the concentration files inside the folders\n@author: sr802\n\"\"\"\n\nimport sys\nimport os\nimport numpy as np\nimport warnings\nimport glob\nwarnings.filterwarnings(\"ignore\")\nimport matplotlib.pyplot as plt\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../../')) #This falls into Utilities path\nimport Lammps.core_functions as cf\n\n\n# Hydrodynamic radius using kirkwood expression using poly_analysis.py on the \n# Equilibration system(See for instance the radius.dat inside \n# 6.High_concentration/6.F_sequential/E_8.0_S_1.0/Conc_dist)\n\nRh=[2.758531,2.755166] #LJ,GLJ \ncf.set_plot_appearance()\n\n\ndirectories=glob.glob('*/')\n\nname={\"u\":\"Solute\",\"v\":\"Solvent\",\"t\":\"Solution\"}\ncolors={\"u\":\"red\",\"v\":\"blue\",\"t\":\"black\"}\nltype={\"u\":\"-\",\"v\":\"-\",\"t\":\"--\"}\n\nplt.close('all')\n\nfor counter,directory in enumerate(directories):\n files=glob.glob('%s/prof_*.dat'%directory)\n fig,ax=plt.subplots()\n files=sorted(files)[::-1]\n \n for f in files:\n key=f.split(\"/\")[-1].split('_')[1][0]\n print (key)\n data=cf.read_data_file(f).values\n plt.plot(data[:,1],data[:,3],color=colors[key],label=name[key],linestyle=ltype[key])\n \n plt.legend(loc='bottom right')\n ax.set_ylabel(r'$c[\\sigma^{-3}]$')\n ax.set_xlabel(r'$r[\\sigma]$')\n ax.set_xlim(0,9)\n ax.set_ylim(0,ax.get_ylim()[1])\n# ax.axvline(x=Rh[counter], ymin=0, ymax=1,ls='-.',c='black')\n fig.tight_layout()\n fig.savefig('%s.pdf'%directory.split('/')[0])\n\nplt.show()","sub_path":"Lammps/PDP/Plots/concentration_distributions.py","file_name":"concentration_distributions.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"251299585","text":"class Sort:\n\n\tdef __init__(self,arr,flag):\n\t\tself.list_ = arr\n\t\tself.length = len(arr)\n\t\tif flag==\"merge\":\n\t\t\tself.mergeSort_(self.list_)\n\t\telif flag==\"insert\":\n\t\t\tself.insertionSort()\n\n\tdef insertionSort(self):\n\t\tfor i in range(1, self.length): \n\t\t\tkey = self.list_[i] \n\t\t\tj = i-1\n\t\t\twhile j >=0 and key < self.list_[j] : \n\t\t\t\tself.list_[j+1] = self.list_[j] \n\t\t\t\tj -= 1\n\t\t\tself.list_[j+1] = key\t\t\n\n\tdef mergeSort_(self,arr):\n\t\tif len(arr) >1: \n\t\t\tmid = len(arr)//2\n\t\t\tleft = arr[:mid]\n\t\t\tright = arr[mid:]\n\n\t\t\tself.mergeSort_(left)\n\t\t\tself.mergeSort_(right)\n\t \n\t\t\ti = j = k = 0\n\n\t\t\twhile i < len(left) and j < len(right): \n\t\t\t\tif left[i] < right[j]: \n\t\t\t\t\tarr[k] = left[i] \n\t\t\t\t\ti+=1\n\t\t\t\telse: \n\t\t\t\t\tarr[k] = right[j] \n\t\t\t\t\tj+=1\n\t\t\t\tk+=1\n\t \n\t\t\twhile i < len(left): \n\t\t\t\tarr[k] = left[i] \n\t\t\t\ti+=1\n\t\t\t\tk+=1\n\n\t\t\twhile j < len(right): \n\t\t\t\tarr[k] = right[j] \n\t\t\t\tj+=1\n\t\t\t\tk+=1\n\n\tdef printlist(self):\n\t\tprint(*self.list_)\n\n_sort = Sort([13,17,8,19,2,5],\"insert\")\n_sort.printlist()\n\n_sort = Sort([12,7,3,5,17,15],\"merge\")\n_sort.printlist() ","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"73092506","text":"from blastaligner import *\r\nfrom csvtogw import *\r\nfrom gdv import *\r\nfrom seq_source_file import *\r\nimport sys\r\nimport os\r\n\r\nspecies1=str(input(\"Enter the filename of edgelist for Species 1 (do not include .csv): \"))\r\nspecies2=str(input(\"Enter the filename of edgelist for Species 2 (do not include .csv): \"))\r\n\r\npathname=os.path.dirname(sys.argv[0])\r\nnewdir1=os.path.join(pathname,species1)\r\nif not os.path.exists(newdir1):\r\n os.makedirs(newdir1)\r\n\r\nnewdir2=os.path.join(pathname,species2)\r\nif not os.path.exists(newdir2):\r\n os.makedirs(newdir2)\r\n\r\nListA=cleanlist(species1)\r\nListB=cleanlist(species2)\r\n\r\n\r\nwhile True:\r\n try:\r\n print(\"1\\tConvert .csv file to .gml and .gw files\\n2\\tConvert .csv file to .fasta files\\n3\\tObtain similarity score via orthologs and blast (requires .fasta files)\\n4\\tCreate orca input and output files (obtain graphlet count matrix in .out file)\\n5\\tGraphlet degree similarity signature (requires orca output files)\\n0\\tExit\")\r\n option=(int(input(\"Enter an option: \")))\r\n\r\n if option==0:\r\n sys.exit()\r\n elif option==1:\r\n csvtogw(species1, newdir1)\r\n csvtogw(species2, newdir2)\r\n elif option==2:\r\n print(\"Generating fasta files for\" + species1 + \"...\")\r\n fasta(species1,ListA,newdir1)\r\n print(\"Generating fasta files for\" + species2 + \"...\")\r\n fasta(species2,ListB,newdir2)\r\n elif option==3:\r\n databasename=str(input(\"Enter the name of the database from https://omabrowser.org/oma/genomePW/ (species must be in correct order!) (do not include .txt): \"))\r\n print(\"Calculating similarity score...\")\r\n seq_score(species1,species2,ListA,ListB,databasename,newdir1,newdir2)\r\n elif option==4:\r\n orca_input(species1,ListA, newdir1)\r\n orca_input(species2,ListB,newdir2)\r\n elif option==5:\r\n protein1=str(input(\"Please enter 1 protein from Species1: \"))\r\n protein2=str(input(\"Please enter 1 protein from Species2: \"))\r\n similarity=signature_score(protein1,protein2, ListA,ListB,newdir1,newdir2,species1,species2)\r\n print('Signature similarity= ',similarity)\r\n\r\n except ValueError:\r\n print(\"Please enter a valid option!\")\r\n","sub_path":"Benchmarking alignments/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"236309434","text":"import numpy as np\nfrom back.backend import FilterSpace, FilterType, ApproxType, plot_template\nimport matplotlib.pyplot as plt\n\nFS = FilterSpace()\n#FS.addFilter(FilterType.LP, ApproxType.BW, 1000 * (2 * np.pi), 5000 * (2 * np.pi), 0.5, 30, 100, 1, n=9, rp=1, GD=1, nmin=1, nmax=20, Qmax=150)\n#FS.addFilter(FilterType.LP, ApproxType.C, 1000 * (2 * np.pi), 3000 * (2 * np.pi), 3, 30, 0, rp=1, GD=1, nmin=1, nmax=20, Qmax=150)\n#FS.addFilter(FilterType.LP, ApproxType.CH1, 1000 * (2 * np.pi), 3000 * (2 * np.pi), 3, 30, 0, rp=1, GD=1, nmin=1, nmax=15, Qmax=150)\n#FS.addFilter(FilterType.HP, ApproxType.BW, 4000 * (2 * np.pi), 1000 * (2 * np.pi), 3, 30, 0, 1, rp=1, GD=1, nmin=1, nmax=20, Qmax=150)\n#FS.addFilter(FilterType.BP, ApproxType.BW, [2E3 * (2 * np.pi), 3E3 * (2 * np.pi)], [1E3 * (2 * np.pi), 4E3 * (2 * np.pi)], 3, 30, 100, 1, nmin=1, nmax=15, Qmax=150)\n#FS.addFilter(FilterType.BP, ApproxType.LG, [2 * (2 * np.pi), 4 * (2 * np.pi)], [1 * (2 * np.pi), 5 * (2 * np.pi)], 3, 20, 0, nmin=1, nmax=15, Qmax=150)\n#FS.addFilter(FilterType.BR, ApproxType.CH2, [1 * (2 * np.pi), 5 * (2 * np.pi)], [2 * (2 * np.pi), 4 * (2 * np.pi)], 0.5, 20, 0, 10, rp=1, nmin=1, nmax=15, Qmax=150)\n#FS.addFilter(FilterType.BR, ApproxType.C, [1, 5], [2, 4], 3, 20, 100, rp=1, nmin=1, nmax=15, Qmax=150)\nFS.addFilter(FilterType.GD, ApproxType.B, 10 * (2 * np.pi), 15 * (2 * np.pi), 3, 30, 0, tol=10, GD=1E-2, nmin=1, nmax=15, Qmax=150)\n#FS.addFilter(FilterType.GD, ApproxType.G, 10 * (2 * np.pi), 15 * (2 * np.pi), 3, 30, 0, tol=10, GD=1E-2, nmin=1, nmax=15, Qmax=150)\nfil = FS.filters[0]\n#fil.print_self()\n\nprint(\"Pole pairs: \", FS.filters[0].get_pole_pairs())\nprint(\"Zero pairs: \", FS.filters[0].get_zero_pairs())\n#FS.filters[0].add_stage(FS.filters[0].zeros, FS.filters[0].poles)\nFS.filters[0].get_stages()\n\nfor i in range(len(FS.filters[0].stages)):\n ns = \"\"\n num = FS.filters[0].stages[i][0]\n if len(num) == 3:\n ns = str(num[0]) + \"s^2 + \" + str(num[1]) + \"s + \" + str(num[2])\n elif len(num) == 2:\n ns = str(num[0]) + \"s + \" + str(num[1])\n elif len(num) == 1:\n ns = str(num[0])\n print(\" \\t \\t \" + ns)\n print(FS.filters[0].stage_names[i] + \": \" + \"--------------------------------\" + \" Order: \" + str(FS.filters[0].get_stage_n(i)) + \" Q: \" + str(FS.filters[0].get_stage_Q(i)))\n ds = \"\"\n den = FS.filters[0].stages[i][1]\n if len(den) == 3:\n ds = str(den[0]) + \"s^2 + \" + str(den[1]) + \"s + \" + str(den[2])\n elif len(num) == 2:\n ds = str(den[0]) + \"s + \" + str(den[1])\n elif len(num) == 1:\n ds = str(den[0])\n print(\" \\t \\t \" + ds)\n print(\"\\n\")\n\n# # BODE\n# fig, ax = plt.subplots(2, 1)\n# axmod, axph = ax\n# plot_template(axmod, fil.type, fil.data, False)\n# FS.plot_mod(axmod, A=False)\n# FS.plot_ph(axph)\n'''b, a = fil.num, fil.den\nwmin, wmax = fil.get_wminmax()\n#wmin = min(fil.data.wp, fil.data.wa)/10 if fil.type <= FilterType.HP elif fil.type <= FilterType.GD else min(fil.data.wp[0], fil.data.wa[0])/10\n#wmax = max(fil.data.wp, fil.data.wa)*10 if fil.type <= FilterType.HP else max(fil.data.wp[1], fil.data.wa[1])*10\nw = np.linspace(wmin, wmax, int(wmax/wmin * 10))\n#H = ss.TransferFunction(b, a)\nfil.plot_mod(axmod, w)\nfil.plot_ph(axph, w)\nfig.suptitle(\"Filter frequency response\")\naxmod.set_xlabel('Frequency [radians / second]')\naxmod.set_ylabel('Amplitude [dB]')\naxmod.grid()\naxph.set_xlabel('Frequency [radians / second]')\naxph.set_ylabel('Phase [°]')\naxph.grid()\n#plt.ylim(-60, 10)\n#plt.grid(which='both', axis='both')\n#plt.show()'''\n\n# BO2\nfig3, ax3 = plt.subplots(1, 1)\nFS.filters[0].plot_selected_stages(ax3, [1])\n\n\n# # POLOS Y CEROS\n# fig2, ax2 = plt.subplots(1, 1)\n# FS.plot_zp(ax2)\n'''fig2.suptitle(\"Poles and Zeros\")\nax2.scatter(fil.zeros.real, fil.zeros.imag, marker='o', edgecolors=\"red\", facecolors=\"None\")\nax2.scatter(fil.poles.real, fil.poles.imag, marker='x', color=\"blue\")\nax2.set_xlabel('Real')\nax2.set_ylabel('Imaginary')\nax2.grid()'''\n\n# # RETARDO DE GRUPO\n# figGD, axGD = plt.subplots(1, 1)\n# FS.plot_gd(axGD)\n'''wmin, wmax = fil.get_wminmax()\n#wmin = min(fil.data.wp, fil.data.wa)/10 if fil.type <= FilterType.HP elif fil.type <= FilterType.GD else min(fil.data.wp[0], fil.data.wa[0])/10\n#wmax = max(fil.data.wp, fil.data.wa)*10 if fil.type <= FilterType.HP else max(fil.data.wp[1], fil.data.wa[1])*10\nw = np.linspace(0, wmax*2/3, int(wmax/wmin * 10))\nfil.plot_gd(axGD, w)\n#axGD.set_ylim([0, 1])\nfigGD.suptitle(\"Filter group delay\")\naxGD.set_xlabel('Frequency [radians / second]')\naxGD.set_ylabel('Group Delay')\naxGD.grid()'''\n\nplt.show()\n\n\n\n\n","sub_path":"back/test_backend.py","file_name":"test_backend.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"66058607","text":"import pandas as pd\nimport numpy as np\nimport argparse\nimport dataio\nimport json\nimport glob\nimport os\n\n\nparser = argparse.ArgumentParser(description='Combine runs')\nparser.add_argument('--datasets', type=str, nargs='+')\noptions = parser.parse_args()\n\nfor DATASET_NAME in options.datasets:\n CSV_FOLDER, CSV_TRAIN, CSV_TEST, CSV_VAL, CONFIG_FILE, Q_NPZ = dataio.build_paths(DATASET_NAME)\n\n tracked_metrics = ['accuracy', 'll_mcmc_all']\n experiments = next(os.walk(CSV_FOLDER))[1] # List all folders\n for experiment in experiments:\n results = {}\n df = {}\n for run_id in range(5):\n rlog = os.path.join(CSV_FOLDER, experiment, str(run_id), 'rlog.csv')\n results_file = os.path.join(CSV_FOLDER, experiment, str(run_id), 'results.json')\n if os.path.isfile(rlog):\n df[run_id] = pd.read_csv(rlog)\n if os.path.isfile(results_file):\n with open(results_file) as f:\n results[run_id] = json.load(f)\n if df:\n mean_df = pd.DataFrame()\n for column in tracked_metrics:\n mean_df[column] = np.column_stack([df[i][column] for i in df]).mean(axis=1)\n mean_df.to_csv(os.path.join(CSV_FOLDER, experiment, 'rlog.csv'))\n\n if results:\n with open(os.path.join(CSV_FOLDER, experiment, 'results.json'), 'w') as f:\n f.write(json.dumps({\n 'args': results[0]['args'],\n 'legends': {\n 'short': results[0]['legends']['short'],\n 'full': results[0]['legends']['full'],\n 'latex': results[0]['legends']['latex']\n },\n 'metrics': {\n metric: np.mean([results[i]['metrics'][metric] for i in results])\n for metric in {'ACC', 'AUC', 'NLL'}\n }\n }, indent=4))\n","sub_path":"combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"321366225","text":"import cv2\r\nfrom time import sleep\r\nimport numpy\r\n\r\ncamera = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n\tstatus, image = camera.read()\r\n\tif(status):\r\n\t\tcv2.imwrite(\"video1.jpg\", image)\r\n\t\t\r\n\t\tgrayscaled = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\t\tretval, threshold = cv2.threshold(grayscaled, 60, 255, cv2.THRESH_BINARY)\r\n\t\t\r\n\t\ta = cv2.resize(image, (600, 500))\r\n\t\tcv2.imshow('original',a)\r\n\t\t\r\n\t\tif cv2.waitKey(5) == ord('o'):\r\n\t\t\tbreak\r\n\t\t\r\n\t\tb = cv2.resize(threshold, (600, 500))\r\n\t\tcv2.imshow('threshold', b)\r\n\t\t\r\n\t\tif cv2.waitKey(5) == ord('t'):\r\n\t\t\tbreak\r\n\tsleep(0.03)\r\n\r\n\r\n\r\n","sub_path":"My_programs/open_cv/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"586821381","text":"import music21\n\nimport sys\nimport copy\n\n#music21.environment.set('musicxmlPath', '/usr/bin/musescore')\nmusic21.environment.set('autoDownload', 'allow')\n\ndef convert(fin, lower=0, higher=0):\n s = music21.converter.parse(fin)\n noteOne = None\n for note in s.flat.notes:\n if isinstance(note, music21.chord.Chord):\n for pitch in note:\n if noteOne == None:\n noteOne = music21.note.Note()\n noteOne.pitch = pitch\n interval = music21.interval.Interval(noteStart = noteOne, noteEnd = pitch)\n rinterval = interval.reverse()\n #we have to do it twice, once would make everything noteOne\n pitch.transpose(rinterval, inPlace = True)\n pitch.transpose(rinterval, inPlace = True)\n for l in range(lower):\n pitch.transpose(music21.interval.GenericInterval('Octave').reverse(), inPlace = True)\n for h in range(higher):\n pitch.transpose(music21.interval.GenericInterval('Octave'), inPlace = True)\n else:\n if noteOne == None:\n noteOne = copy.deepcopy(note)\n interval = music21.interval.Interval(noteStart = noteOne, noteEnd = note)\n rinterval = interval.reverse()\n #we have to do it twice, once would make everything noteOne\n note.transpose(rinterval, inPlace = True)\n note.transpose(rinterval, inPlace = True)\n for l in range(lower):\n note.transpose(music21.interval.GenericInterval('Octave').reverse(), inPlace = True)\n for h in range(higher):\n note.transpose(music21.interval.GenericInterval('Octave'), inPlace = True)\n midiOut = 'inverse.mid'\n s.write('midi', fp = midiOut)\n return midiOut\n\ndef main():\n if len(sys.argv) < 2:\n print('You must provide the midi file to read')\n print('\\t{} '.format(sys.argv[0]))\n sys.exit(1)\n f = sys.argv[1]\n fout = convert(f)\n\nif __name__ == '__main__':\n main()\n","sub_path":"invert.py","file_name":"invert.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"582335154","text":"'''\nAuthor: alexc89@mit.edu\nSendMessageAchMatlab\nUsed to multicast Hubo's status on LCM. It will take the information received on ACH and convert it to LCM. This is needed for live visualization.\n\n'''\n\nimport lcm\nimport time\nimport ach\nimport hubo_ach as ha\nimport time\nfrom ctypes import *\n\n#Import LCM Messages\nfrom lcmtypes import hubo_hubo2state\n\n\n\n\n\n#Message Conversion\ndef convertLCM_Matlab(x):\n NUM_JOINT = 40\n msg = hubo_hubo2state()\n msg.timestamp = time.time()\n msg.state = [0,0,0,0,0,0] #Basic Link Position\n msg.state += [x.joint[i].pos for i in range(NUM_JOINT)] #Moter joints positions\n msg.state += [0,0,0,0,0,0] #Basic Link Velocities\n msg.state += [x.joint[i].vel for i in range(NUM_JOINT)] #Motor joint velocity\n #Retroactively adding passive finger joints and their velocity\n FINGER_JOINTPOS = [17,38] #Left and Right hand.\n FINGER_JOINTPOS = [[FINGER_JOINTPOS[hand] +2*finger for finger in range(5) ] for hand in range(2)]#Populate 5 fingers\n FINGER_JOINTPOS = FINGER_JOINTPOS[0] + FINGER_JOINTPOS[1]\n FINGER_JOINTPOS += [FINGER_JOINTPOS[finger] +1 for finger in range(len(FINGER_JOINTPOS))]#Populate 2 knuckles for each finger\n FINGER_JOINTPOS += [2*knuckles for knuckles in FINGER_JOINTPOS] #add velocity\n FINGER_JOINTPOS.sort()\n [msg.state.insert(knuckle, 0) for knuckle in FINGER_JOINTPOS] #Insert zero for the passive knuckles position + Velocity\n return msg\n\n\nif __name__ == \"__main__\":\n #Setup ACH LCM channels\n lc = lcm.LCM(\"udpm://239.255.76.67:7667?ttl=2\")\n #Setup ACH\n c = ach.Channel(ha.HUBO_CHAN_STATE_NAME)#HuboState\n c. flush()\n\n while True: #constant Transmission \n #Grab a frame form ACH\n state = ha.HUBO_STATE()\n [status, framesize] = c.get(state, wait=True, last=False)\n if status == ach.ACH_OK or status == ach.ACH_MISSED_FRAME:\n x =1#print \"ACH grab successful\" #Testing Probe 1\n else:\n raise ach.AchException( c.result_string(status))\n \n \n #ACH to LCM conversion\n msg = convertLCM_Matlab(state)\n# msg.imu = [convert_imu(x) for x in state.imu]\n# msg.ft = [convert_ft(x) for x in state.ft]\n# msg.joint = [convert_joint_state(x) for x in state.joint]\n# msg.status = [convert_joint_status(x) for x in state.status]\n# msg.driver = [convert_jmc_state(x) for x in state.driver]\n# msg.power = convert_power(state.power)\n# msg.time = state.time\n# msg.refWait = state.refWait\n \n #Pushout an LCM message\n lc.publish(\"HuboState\", msg.encode())\n #Loop Delay\n time.sleep(0.01)\n #ACH LCM terminate\n c.close()\n","sub_path":"ach-lcm-util-simplified/sendMessageAchMatlab.py","file_name":"sendMessageAchMatlab.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"39208081","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\ndef find(node, parent, target):\n if node is None:\n return None, -1\n if node.val == target:\n return parent, 0\n elif node.left is None and node.right is None:\n return None, -1\n\n lp, ld = find(node.left, node, target)\n rp, rd = find(node.right, node, target)\n if lp is None and rp is None:\n return None, -1\n elif lp is not None:\n return lp, ld + 1\n else:\n return rp, rd + 1\n\n\nclass Solution:\n def isCousins(self, root, x, y):\n xp, xd = find(root, None, x)\n yp, yd = find(root, None, y)\n return xd == yd and xp != yp\n","sub_path":"src/leetcode/P3322.py","file_name":"P3322.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"38990100","text":"import csv\nimport openpyxl as xl\nimport webbrowser\n\nweb_address = input('Please enter the web address:')\nworking_dir = '~/Documents/HUD/Projects/Scripts/{}'\n\n\n# noinspection PyUnboundLocalVariable\ndef main():\n \"\"\"\n function to control the script, taking in the name of the file that will be used and\n deciding whether to use a .csv function or .xlsx function\n \"\"\"\n while True:\n # noinspection PyBroadException\n try:\n\n filename = input('Please enter the file you wish to use: ')\n file = working_dir.format(filename)\n print('Reading {}'.format(file))\n if file.endswith('.csv'):\n process_csv(import_csv(file))\n elif file.endswith('.xlsx'):\n process_xlsx(import_xlsx(file))\n else:\n print('{} is not a valid file.'.format(filename))\n except Exception:\n print('{} does not exist.'.format(filename))\n pass\n\n\ndef import_csv(file):\n \"\"\"\n function to import the .csv file and convert it to a list\n :param file: the file name that is opened\n :return: returns data as a list of lists\n \"\"\"\n try:\n with open(file) as working_file:\n reader = csv.reader(working_file)\n csv_data = list(reader)\n return csv_data\n except Exception:\n raise\n\n\n\ndef import_xlsx(file):\n \"\"\"\n function to import the .xlsx file and convert it to a worksheet object\n :param file: the file name that is opened\n :return: returns the worksheet object\n \"\"\"\n try:\n wb = xl.load_workbook(file)\n except Exception:\n raise\n print('Choose a sheet from the workbook: ')\n print(wb.sheetnames)\n sheet = wb[input()]\n print('Reading {}{}'.format(sheet.title, '.'))\n return sheet\n\n\ndef process_csv(csv_list):\n \"\"\"\n function that iterates through the list and opens browser tabs when it\n finds seven digit number values\n :param csv_list: a list generated from a .csv file\n \"\"\"\n print('Opening browser tabs...')\n for elements in csv_list:\n for element in elements:\n if element.isdigit() and len(element) == 7:\n webbrowser.open(web_address + element)\n\n\ndef process_xlsx(sheet):\n \"\"\"\n function that iterates through the worksheet object and opens browser tabs when it\n finds seven digit number values\n :param sheet: a worksheet from an .xlsx file\n \"\"\"\n print('Opening browser tabs...')\n for row in sheet.iter_rows():\n for cell in row:\n if str(cell.value).isdigit() and len(str(cell.value)) == 7:\n webbrowser.open(web_address + str(cell.value))\n\n\nmain()\n","sub_path":"tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"606062055","text":"import sys\nimport numpy as np\n\n# Run:\n# python scripts/timeints-divide-and-partition.py \\\n#
\".format(error)\n\n\t\treturn app.make_response(error)","sub_path":"3D_Scanner/uni3dface/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"296880070","text":"# -*- coding: utf-8 -*-\n\"\"\"\n完整的TensorFlow训练神经网络,实现以下功能:\n1. 使用激活函数实现神经网络模型的去线性化\n2. 使用一个或多个隐藏层使神经网络的结构更深\n3. 使用带指数衰减的学习率设置\n4. 使用正则化来避免过度拟合\n5. 使用滑动平均模型来使得最终模型更加健壮\n\n出自《Tensorflow 实战Google深度学习框架》 \n侵权望告知,删除相关代码\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# MNIST数据集相关的常数\nINPUT_NODE = 784 # 输入层的节点数,在图像识别方面,节点数等于图片的像素\nOUPUT_NODE = 10 # 输出层的节点数。这个等于类别的数目。因为在MNIST数据集中\n# 需要区分的是0~9这10个数字,所以这里输出层的节点数为10\n\n# 配置神经网络的参数\nLAYER1_NODE = 500 # 隐藏层节点数。这里使用1层500节点的隐藏层\nBATCH_SIZE = 100 # 一个训练batch中的训练数据个数。数字越小时,训练过程越\n# 接近随机梯度下降;数字越大,训练越接近梯度下降。\n\nLEARNING_RATE_BASE = 0.8 # 基础的学习率\nLEARNING_RATE_DECAY = 0.99 # 学习率的衰减率\nREGULARIZATION_RATE = 0.0001 # 正则化项系数\nTRAINING_STEPS = 30000 # 训练轮数\nMOVING_AVERAGE_DECAY = 0.99 # 滑动平均衰减率\n\n# 定义一个辅助函数\n\"\"\"\n给定神经网络的输入和所有参数,计算神经网络的前向传播结果。在这里定义了一个使用ReLU激活函\n数的三层全链接神经网络。通过加入隐藏层实现了多层网络结构,通过ReLU激活函数实现了去线性化。\n在这个函数中也支持传入用于计算参数平均值的类。这样方便在测试中使用滑动平均模型。\n\"\"\"\n\n\ndef inference(input_tensor, avg_class, weights1, biases1, weights2, biases2):\n # 当没有提供滑动平均类时,直接使用参数当前的取值\n if avg_class is None:\n # 计算隐藏层的前向传播结果,这里使用里ReLU激活函数\n layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)\n \"\"\"\n\t\t计算输出层的前向传播结果,因为在计算损失函数时会一并计算softmax函数,所以这里不需\n\t\t要加入激活函数。而且不加入softmax函数不会影响测试结果。因为预测时使用的是不同类别\n\t\t对应节点输出值得相对大小,有没有softmax层对最后分类的结果的计算没有影响。于是在计\n\t\t算整个神经网络的前向传播时可以不加入最后的softmax层。\n\t\t\"\"\"\n return tf.matmul(layer1, weights2) + biases2\n\n else:\n \"\"\"\n\t\t首先使用avg_class.average函数来计算得出变量的滑动平均值,然后再计算相应的神经网络\n\t\t前向传播结果\n\t\t\"\"\"\n layer1 = tf.nn.relu(\n tf.matmul(input_tensor, avg_class.average(weights1)) +\n avg_class.average(biases1))\n return tf.matmul(layer1, avg_class.average(weights2)) + avg_class.average(biases2)\n\n\n# 训练模型的过程\ndef train(mnist):\n x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')\n y_ = tf.placeholder(tf.float32, [None, OUPUT_NODE], name='y-input')\n\n # 生成隐藏层的参数\n weights1 = tf.Varialbe(\n tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))\n biases1 = tf.Varialbe(tf.constant(0.1, shape=[LAYER1_NODE]))\n # 生成输出层的参数\n weights2 = tf.Varialbe(\n tf.truncated_normal([LAYER1_NODE, OUPUT_NODE], stddev=0.1))\n biases2 = tf.Varialbe(tf.constant(0.1, shape=[OUPUT_NODE]))\n\n # 计算在当前参数下神经网络前向传播的结果。这里给出的用于计算滑动平均模型的类为None\n # 所以函数不会使用参数的滑动平均值\n y = inference(x, None, weights1, biases1, weights2, biases2)\n\n \"\"\"\n\t定义存储训练轮数的变量。这个变量不需要计算滑动平均值,所以这里指定这个变量为不可训练的\n\t变量(trainable = False)。在使用TensorFlow训练神经网络时,一般会将代表训练轮数的变量指\n\t定位不可训练的参数。\n\t\"\"\"\n global_step = tf.Varialbe(0, trainable=False)\n\n # 给定滑动平均衰减率和训练轮数的变量。初始化滑动平均类。\n varialbe_averages = tf.train.ExponentialMovingAverage(\n MOVING_AVERAGE_DECAY, global_step)\n\n \"\"\"\n\t在所有代表神经网络参数的变量上使用滑动平均。其他辅助变量(比如gloabal_step)就不需要了。\n\ttf.trainable_variables返回的就是涂上集合GraphKeys.TRAINABLE_VARIABLES中的元素。这个集合\n\t的元素就是所有没有指定trainable = False的参数\n\t\"\"\"\n varialbe_averages_op = varialbe_averages.apply(\n tf.trainable_variables())\n\n \"\"\"\n\t计算使用了滑动平均之后的前向传播结果。滑动平均不会改变变量本身的取值,而是会维护一个影子\n\t变量来记录其滑动平均值。所以当需要使用这个滑动平均值时,需要明确调用average函数\n\t\"\"\"\n\n average_y = inference(\n x, varialbe_averages, weights1, biases1, weights2, biases2)\n\n \"\"\"\n\t计算交叉熵作为刻画预测值和真实值之间差距的损失函数。这里使用了TensorFlow中提供的sparse_softmax\n\t_cross_entropy_with_logits函数来计算交叉熵。当分类问题只有一个正确答案时,可以使用这个函数来加\n\t速交叉熵的计算。MNIST问题的图片中只包含了0~9中的一个数字,所以可以使用这个函数来计算交叉熵损失。\n\t这个函数的第一个参数是神经网络不包括softmax层的前向传播结果,第二个是训练数据的正确答案。因为\n\t标准答案是一个长度为10的一维数组,而该函数需要提供的是一个正确答案的数字,所以需要使用tf.argmax\n\t函数来得到正确答案的类别编号。\n\t\"\"\"\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n y, tf.argmax(y_, 1))\n # 计算在当前batch中所有样例的交叉熵平均值。\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n\n # 计算L2正则化损失函数。\n regularizer = tf.contrib.layer.l2_regularizer(REGULARIZATION_RATE)\n # 计算正则化损失。一般只计算神经网络边上权重的正则化损失,而不使用偏执项。\n regularization = regularizer(weights1) + regularizer(weights2)\n # 总损失等于交叉式损失和正则化损失的和\n loss = cross_entropy_mean + regularization\n # 设置指数衰减的学习率\n learning_rate = tf.train.exponential_decay(\n LEARNING_RATE_BASE, # 基础的学习率,随着迭代的进行,更新变量时使用的学习率在\n # 这个基础上递减\n global_step, # 当前迭代的轮数\n mnist.train.num_examples / BATCH_SIZE, # 过完所有的训练数据需要的迭代次数\n LEARNING_RATE_DECAY) # 学习率衰减速度\n\n \"\"\"\n\t使用tf.train.GrandientDescentOptimizer优化算法来优化损失函数。注意这里损失函数包含了交叉熵损失和\n\tL2正则化损失\n\t\"\"\"\n train_step = tf.train.GrandientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\n\n \"\"\"\n\t在训练神经网络数据时,每过一遍数据既需要通过反向传播来更新神经网络中的参数,又需要更新每一个参数的\n\t滑动平均值。为了一次完成多个操作,TensorFlow提供了tf.control_dependencies和tf.group两种机制,下面\n\t两汉程序和train_op = tf.grouo(train_step,varialbe_averages_op)是等价的\n\t\"\"\"\n with tf.control_dependencies([train_step], varialbe_averages_op):\n train_op = tf.no_op(name='train')\n\n \"\"\"\n\t检验使用了滑动平均模型的神经网络前向传播结果是否正确。tf.argmax(average_y,1)计算每一个样例的预测答案。\n\t其中average_y是一个batch_size * 10 的二维数组。\n\t\"\"\"\n","sub_path":"MNIST/Completed_NN_MNIST_Tensorflow.py","file_name":"Completed_NN_MNIST_Tensorflow.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"497251303","text":"#수치미분은 너무 느려서 안 돌아감\n\nimport os,sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nsys.path.append(os.pardir)\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n\n(x_train,t_train),(x_test,t_test)=load_mnist(normalize=True,one_hot_label=True)\n\ntrain_loss_list=[]\n\niters_num=10000\ntrain_size=x_train.shape[0]\nbatch_size=100\nlearning_rate=0.1\n\nnetwork=TwoLayerNet(784,50,10)\n\nfor i in range(iters_num):\n\tbatch_mask=np.random.choice(train_size,batch_size)\n\tx_batch=x_train[batch_mask]\n\tt_batch=t_train[batch_mask]\n\n\tgrad = network.numerical_gradient(x_batch, t_batch)\n \n\tfor key in ('W1','b1','W2','b2'):\n\t\tnetwork.params[key]-=grad[key]*learning_rate\n\n\tloss = network.loss(x_batch,t_batch)\n\ttrain_loss_list.append(loss)\n\tif i%1000==0:\n\t\tprint(loss)\n\nplt.plot(range(len(train_loss_list)),train_loss_list)\nplt.ylim(0,10)\nplt.show()","sub_path":"exercise/ch04/train_neuralnet.py","file_name":"train_neuralnet.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"334680165","text":"from g_factors3 import gen_f\nfrom scipy.stats import norm\nfrom scipy.optimize import minimize\nfrom scipy.stats import burr\nimport pandas as pd\nimport numpy as np\ndef gen_v():\n data = pd.read_csv(\"data.csv\")\n data[data==' ']=np.nan\n data=data.dropna()\n data.head(5)\n data_E=data.iloc[0:56,:]\n data_T=data.iloc[56::,:]\n stress=np.int8(data_E.iloc[:,31])\n tired=np.int8(data_E.iloc[:,32])\n st=np.int8(data_E.iloc[:,31:33])\n choice3=np.int8(data_E.iloc[:,37])\n choice4=np.int8(data_E.iloc[:,38])\n tend=np.int8(choice3)+np.int8(choice4)\n risk=np.int8(data_E.iloc[:,34])\n delay=np.int8(data_E.iloc[:,39])\n fst=np.zeros((3,3))\n for i in range (0,3):\n for j in range (0,3):\n fst[i,j]=np.array([i for i in np.where(st[:,0]==i)[0] if i in np.where(st[:,1]==j)[0]]).size\n fst/=fst.sum()\n frd=np.zeros((2,2))\n for i in range (0,2):\n for j in range (0,2):\n frd[i,j]=np.array([i for i in np.where(risk==i+1)[0] if i in np.where(delay==j+1)[0]]).size\n frd/=frd.sum()\n frd\n time=np.float32(data_E.iloc[:,1:11])\n mu=np.zeros(10)\n std=np.zeros(10)\n for i in range (0,10):\n mu[i],std[i]=norm.fit(time[:,i])\n farmiliar=np.float32(data_E.iloc[:,21:31])\n mu_f=np.zeros(10)\n std_f=np.zeros(10)\n for i in range (0,10):\n mu_f[i],std_f[i]=norm.fit(farmiliar[:,i])\n m1=np.load('m1.npy')\n m2=np.load('m2.npy')\n m3=np.load('m3.npy')\n m4=np.load('m4.npy')\n f=data_E.iloc[:,21:31]\n f_e=np.zeros((data_E.shape[0],10))\n rv1=burr(m1[0], m1[1], m1[2], m1[3])\n rv2=burr(m2[0], m2[1], m2[2], m2[3])\n rv3=burr(m3[0], m3[1], m3[2], m3[3])\n rv4=burr(m4[0], m4[1], m4[2], m4[3])\n x=np.arange(0,4000)\n f_e[np.where(f=='0')] = 0\n f_e[np.where(f=='1')] = x.dot(rv1.pdf(x))\n f_e[np.where(f=='2')] = x.dot(rv2.pdf(x))\n f_e[np.where(f=='3')] = x.dot(rv3.pdf(x))\n f_e[np.where(f=='4')] = x.dot(rv4.pdf(x))\n mu_fe=np.zeros(10)\n std_fe=np.zeros(10)\n for i in range (0,10):\n mu_fe[i],std_fe[i]=norm.fit(f_e[:,i])\n v=[fst,frd,mu,std,mu_fe,std_fe,mu_f,std_f]\n return v,tend,stress,tired,risk,delay,time,farmiliar,f_e\n\ndef fun(v,i,stress,tired,risk,delay,time,farmiliar,f_e):\n fst,frd,mu,std,mu_fe,std_fe,mu_f,std_f=v\n #print(frd)\n tend_p=fst[stress[i],tired[i]]*frd[risk[i]-1,delay[i]-1]\n for i1 in range (0,10):\n tend_p*=norm.pdf(time[i,i1],mu[i1],std[i1])\n for i1 in range (0,10):\n tend_p*=norm.pdf(farmiliar[i,i1],mu_f[i1],std_f[i1])\n for i1 in range (0,10):\n tend_p*=norm.pdf(f_e[i,i1],mu_fe[i1],std_fe[i1])\n return tend_p\n\ndef err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e):\n error=0\n p=np.zeros(56)\n for i in range(0,56):\n p[i]=fun(v,i,stress,tired,risk,delay,time,farmiliar,f_e)\n p=p/p.sum()\n #mu_tend,std_tend=norm.fit(tend)\n for i in range(0,56):\n if tend[i]>20:\n error+=np.abs(1-p[i])\n else:\n error+=np.abs(0-p[i])\n return error\n\ndef update(m,load):\n v,tend,stress,tired,risk,delay,time,farmiliar,f_e=gen_v()\n if load==1:\n v=np.load('v.npy')\n fst,frd,mu,std,mu_fe,std_fe,mu_f,std_f=v\n function1 = lambda fst: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function2 = lambda frd: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function3 = lambda mu: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function4 = lambda std: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function5 = lambda mu_fe: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function6 = lambda std_fe: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function7 = lambda mu_f: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n function8 = lambda std_f: err(v,tend,stress,tired,risk,delay,time,farmiliar,f_e)\n f=[function1,function2,function3,function4,function5,function6,function7,function8]\n for i in range (0,m):\n k=np.random.randint(0,7)\n t=32\n if i%100==0:\n t/=2\n v[k]=minimize(f[k],v[k],method='Nelder-Mead', tol=t)['x'].reshape(v[k].shape)\n if i%10==0:\n np.save('v.npy',v)","sub_path":"mini.py","file_name":"mini.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"185309056","text":"##################################################################################\n# This file contains the main methods for doing simulation, evolution, \n# implementing our two evolutioanry strategies.\n##################################################################################\n\n\nimport numpy as np\nfrom individual import Individual\n\n\ndef initialize_generation(environment, population_size, num_genes):\n\t\"\"\"\n\tRandomly initializes a generation by returning list of objects of class Individual.\n\t:param population_size: number of individuals in population\n\t:param num_genes: total number of weights in neural network controller\n\t\"\"\"\n\t# initialize all individuals in the population \n\tall_genotypes = np.random.uniform(-1, 1, (population_size, num_genes))\n\tall_sigmas = np.random.uniform(0.001, 0.1, (population_size, num_genes))\n\tgeneration = [Individual(all_genotypes[i], all_sigmas[i]) for i in range(population_size)]\n\n\t# compute fitness of all individuals\n\tfor individual in generation:\n\t\tindividual.fitness = individual.compute_fitness(environment)\n\n\treturn generation\n\n\ndef generate_next_generation(environment, population, adaptive_mutation):\n\t\"\"\"\n\tGenerates next generation from current population.\n\t:param environment: (simulation) environment object\n\t:param population: list of objects of class Individual\n\t\"\"\"\n\t# generate pairs of parents that can be used for recombination\n\tparent_pairs = parent_selection_ranking(population, num_pairs=len(population)*4)\n\n\t# generate offspring\n\toffspring = []\n\tfor i in range(len(parent_pairs)):\n\t\tchildren = create_offspring(environment, parent_pairs[i][0], parent_pairs[i][1], adaptive_mutation, num_offspring=1)\n\t\toffspring += children # concatenate children to offspring list\t\n\n\tnew_population = survival_selection_top(offspring, len(population))\n\treturn new_population\n\ndef parent_selection_ranking(population, num_pairs, s=1.5):\n\t\"\"\"\n\tRank-based parent selection using linear ranking (with s = 1.5)\n\t:param: population: list of objects of class Individual\n\t:param num_pairs: number of parent pairs that we want to generate \n\t\"\"\"\n\t# compute linearly adjusted ranks\n\tpop_size = len(population)\n\tsorted_population = sorted(population, key = lambda individual: individual.fitness)\n\n\t# compute linearly adjusted ranks\n\tselection_probs = []\n\tfor i in range(len(sorted_population)):\n\t\tselection_probs.append(((2-s)/pop_size) + 2*i*(s-1)/(pop_size*(pop_size-1)))\n\n\t# sample random parent pairs\n\tparent_pairs = []\n\twhile len(parent_pairs) != num_pairs:\n\t\tselection = np.random.choice(sorted_population, 2, replace=False, p=selection_probs)\n\t\tparent_pairs.append((selection[0], selection[1]))\n\n\treturn parent_pairs\n\n\ndef create_offspring(environment, parent_1, parent_2, adaptive_mutation, num_offspring):\n\t\"\"\"\n\tGenerate num_offspring from parent_1 and parent_2 using recombination and mutation\n\t:param environment: (simulation) environment object\n\t:param parent_1: first parent object of class Individual\n\t:param parent_2: first parent object of class Individual\n\t:param num_offspring: number of offspring to generate from the parent pair\n\t\"\"\"\n\t# create num_offspring children from the parent pair\n\tchildren = []\n\tfor i in range(num_offspring):\n\t\t# apply whole arithmetic recombination to create children\n\t\tchild = recombine(parent_1, parent_2, adaptive_mutation)\n\n\t\t# apply mutation and add child to children list\t\t\n\t\tif adaptive_mutation:\n\t\t\tchild.mutate_self_adaptive()\n\t\telse:\n\t\t\tchild.mutate()\n\t\n\t\t# compute child's fitness after mutation\n\t\tchild.fitness = child.compute_fitness(environment)\n\t\tchildren.append(child)\n\n\treturn children\n\n\ndef recombine(parent_1, parent_2, adaptive_mutation):\n\t\"\"\"\n\tPerforms recombination between two parents, creating a child.\n\tUse blend_crossover for ES1 and whole_arith_recombination for ES2.\n\t:param parent_1: first parent object of class Individual\n\t:param parent_2: first parent object of class Individual\n\t\"\"\"\n\tchild_genotype = blend_crossover(parent_1, parent_2)\n\tif adaptive_mutation:\n\t\tchild_sigma = child_sigma_v4(parent_1, parent_2)\n\telse:\n\t\t# child sigma will be ignored in this case\n\t\tchild_sigma = parent_1.sigma\n\n\t# return new child object\n\treturn Individual(child_genotype, child_sigma)\n\n\ndef blend_crossover(parent_1, parent_2):\n\t\"\"\"\n\tref. A Crossover Operator Using Independent Component Analysis for Real-Coded Genetic Algorithms (Takahashi & Kita, 2001)\n\t\"\"\"\n\talpha = 0.5 # ref Eshelmann & Schafer\n\n\tchild_genotype = np.zeros((parent_1.num_genes,))\n\tfor i in range(parent_1.num_genes):\n\t\tdifference = abs(parent_1.genotype[i] - parent_2.genotype[i])\n\t\tbound_1 = min(parent_1.genotype[i], parent_2.genotype[i]) - alpha * difference\n\t\tbound_2 = max(parent_1.genotype[i], parent_2.genotype[i]) + alpha * difference\n\t\tchild_genotype[i] = np.random.uniform(bound_1, bound_2)\n\n\treturn child_genotype\n\n\ndef child_sigma_v4(parent_1, parent_2):\n\t\"\"\"\n\tSigma calculation for the self-adapting mutation with n step sizes. Uses\n\tuniform crossover.\n\t\"\"\"\n\tchild_sigma = np.zeros((parent_1.num_genes,))\n\tfor i in range(parent_1.num_genes):\n\t\tif np.random.uniform(0,1) <= 0.5:\n\t\t\tchild_sigma[i] = parent_1.sigma[i]\n\t\telse:\n\t\t\tchild_sigma[i] = parent_2.sigma[i]\n\treturn child_sigma\n\ndef child_sigma_v5(parent_1, parent_2):\n\t\"\"\"\n\tSigma calculation for the self-adapting mutation with n step sizes. Uses\n\twhole arithmetic recombination.\n\t\"\"\"\n\talpha = np.random.uniform(0, 1.0)\n\tchild_sigma = alpha * parent_1.sigma + (1-alpha) * parent_2.sigma\n\treturn child_sigma\n\n\ndef survival_selection_top(offspring, population_size):\n\tsorted_offspring = sorted(offspring, key = lambda individual: individual.fitness)\n\tbest_offspring = sorted_offspring[-population_size:]\n\treturn best_offspring","sub_path":"evolution.py","file_name":"evolution.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"180856126","text":"from flask import Flask\r\nfrom flask import render_template\r\nfrom flask import request\r\n\r\nimport requests\r\nimport json\r\nimport urllib\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return render_template('mypage.html')\r\n\r\n@app.route('/apitest',methods=['GET','POST'])\r\ndef apitest():\r\n if request.method == 'POST':\r\n appkey = \"0026fe208ea18ff0e4c0546f227e3f47\"\r\n request1(appkey, \"GET\")\r\n num = request.form['num']\r\n print(\"num--->\" + num)\r\n return render_template('apitest.html',result = num)\r\n else:\r\n return render_template('apitest.html',result = 'NOTHING')\r\n\r\n\r\ndef request1(appkey, m=\"GET\"):\r\n url = \"http://apis.juhe.cn/idcard/index\"\r\n params = {\r\n \"cardno\": \"\", # 身份证号码\r\n \"dtype\": \"\", # 返回数据格式:json或xml,默认json\r\n \"key\": appkey, # 你申请的key\r\n\r\n }\r\n params = urllib.parse.urlencode(params)\r\n if m == \"GET\":\r\n f = urllib.request.urlopen(\"%s?%s\" % (url, params))\r\n else:\r\n f = urllib.request.urlopen(url, params)\r\n\r\n content = f.read()\r\n res = json.loads(content)\r\n if res:\r\n error_code = res[\"error_code\"]\r\n if error_code == 0:\r\n # 成功请求\r\n print\r\n res[\"result\"]\r\n else:\r\n print\r\n \"%s:%s\" % (res[\"error_code\"], res[\"reason\"])\r\n else:\r\n print\r\n \"request api error\"\r\nif __name__ == '__main__':\r\n app.run('10.141.36.112','8080')\r\n","sub_path":"untitled10/untitled10.py","file_name":"untitled10.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"321630533","text":"from src.constantes import NOME, TELEFONE, EMAIL\nfrom src.Contato import Contato\n\ndef valida_caracteres_validos(valor: str, caracteres: str) -> bool:\n caracteres = caracteres.lower()\n for letra in valor.lower():\n if letra not in caracteres:\n return False\n return True\n\ndef is_nome(valor: str) -> bool:\n '''\n Dado uma string qualquer, identifica se é um nome válido\n '''\n if (valor.strip() == ''):\n return False\n caracteres_validos = \"abcdefghijklmnopqrstuvwxyzç'-áéíóúâêîôûàèìòùäëïöüãõ \"\n return valida_caracteres_validos(valor, caracteres_validos)\n\ndef identifica_coluna(valor: str) -> int:\n if Contato.verificar_telefone(valor):\n return TELEFONE\n if Contato.verificar_email(valor):\n return EMAIL\n if is_nome(valor):\n return NOME\n return -1","sub_path":"src/verificacoes.py","file_name":"verificacoes.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"134115201","text":"import datetime\nimport os\nimport warnings\nfrom pathlib import Path\nfrom typing import NoReturn\n\n_project_root_folder_name: str = 'chewing_sensor_study'\n_global_experiment_name: str = 'untitled_experiment_'\n_untitled_experiment_name: str = 'untitled_experiment_'\n\n\ndef _get_experiment_name() -> str:\n global _global_experiment_name\n\n if _global_experiment_name is _untitled_experiment_name:\n _global_experiment_name = _global_experiment_name + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n warnings.warn(\n 'Module has no experiment name configured.\\nAssigning the following name: ' + _global_experiment_name)\n\n return _global_experiment_name\n\n\ndef set_experiment_name(experiment_name: str, is_file_name: bool = False) -> NoReturn:\n assert isinstance(experiment_name, str)\n assert isinstance(is_file_name, bool)\n\n global _global_experiment_name\n if is_file_name:\n file_name = Path(experiment_name)\n _global_experiment_name = file_name.name[0:-len(file_name.suffix)]\n else:\n _global_experiment_name = experiment_name\n\n\ndef get_root_path() -> Path:\n cwd: Path = Path(os.getcwd())\n\n while cwd.name is not _project_root_folder_name:\n cwd = cwd.parent\n\n return cwd\n\n\ndef get_generated_path() -> Path:\n return get_root_path() / 'generated'\n\n\ndef get_results_path() -> Path:\n x = get_root_path() / 'results' / _get_experiment_name()\n x.mkdir(parents=True, exist_ok=True)\n\n return x\n\n\ndef get_models_path() -> Path:\n x = get_results_path() / 'models'\n x.mkdir(parents=True, exist_ok=True)\n\n return x\n\n\ndef get_best_model_path(lopo_idx: int = -1) -> Path:\n models_path: Path = get_models_path()\n if lopo_idx == -1:\n model_name = \"best.h5\"\n else:\n model_name = \"best_\" + str(lopo_idx) + \".h5\"\n\n return models_path / model_name\n\n\ndef get_tensorboard_logdir(lopo_idx: int = -1) -> Path:\n assert isinstance(lopo_idx, int)\n\n x: Path = get_results_path() / \"tensorboard\"\n if lopo_idx != -1:\n x = x / (\"LOPO_\" + str(lopo_idx))\n x.mkdir(parents=True, exist_ok=True)\n\n return x\n\n\ndef set_tensorflow_log_level(n: int = 3) -> NoReturn:\n assert isinstance(n, int)\n\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(n)\n\n\ndef enable_tensorflow_eager_execution(enabled: bool = True) -> NoReturn:\n assert isinstance(enabled, bool)\n\n from tensorflow.python.framework.ops import enable_eager_execution, disable_eager_execution\n if enabled:\n enable_eager_execution()\n else:\n disable_eager_execution()\n\n\ndef get_res_main() -> Path:\n return get_root_path() / 'res' / 'main'\n\n\ndef get_res_test() -> Path:\n return get_root_path() / 'res' / 'test'\n\n\ndef get_src_main() -> Path:\n return get_root_path() / 'src' / 'main'\n\n\ndef get_src_test() -> Path:\n return get_root_path() / 'src' / 'test'\n\n\ndef get_wu2_path(machine_name: str = \"\") -> Path:\n assert isinstance(machine_name, str)\n\n if machine_name == \"mahakam\":\n return Path(\"~/workspace/Datasets/chewing_sensor_study/wu2/Collected signals.min/\")\n else:\n return Path(\"~/workspace/Datasets/chewing_sensor_study/wu2/Collected signals.min/\")\n\n\ndef print_summary() -> NoReturn:\n print('root : ' + str(get_root_path()))\n print('results : ' + str(get_results_path()))\n print('models : ' + str(get_models_path()))\n print('tensorboard: ' + str(get_tensorboard_logdir()))\n print('res/main : ' + str(get_res_main()))\n print('res/test : ' + str(get_res_test()))\n print('src/main : ' + str(get_src_main()))\n print('src/test : ' + str(get_src_test()))\n\n\nif __name__ == '__main__':\n enable_tensorflow_eager_execution(True)\n print(\"globalconfig: enabled TensorFlow eager execution mode\")\n\n print_summary()\n","sub_path":"src/globalconfig.py","file_name":"globalconfig.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"581281263","text":"# _*_ coding: utf-8 _*_\n__author__ = 'LelandYan'\n__date__ = '2018/9/23 12:54'\n\nfrom urllib import request\nfrom urllib.parse import *\nimport random\nimport time\nfrom datetime import datetime\nimport socket\n\nDEFAULT_AGENT = 'wswp'\nDEFAULT_DELAY = 5\nDEFAULT_RETRIES = 1\nDEFAULT_TIMEOUT = 60\n\n\nclass Download:\n def __init__(self, delay=DEFAULT_DELAY, user_agent='DEFAULT_AGENT', proxies=None, num_retries=DEFAULT_RETRIES,\n timeout=DEFAULT_TIMEOUT, opener=None, cache=None):\n socket.setdefaulttimeout(timeout)\n self.throttle = Throttle(delay)\n self.user_agent = user_agent\n self.proxies = proxies\n self.num_retries = num_retries\n self.opener = opener\n self.cache = cache\n\n def __call__(self, url):\n result = None\n if self.cache:\n try:\n result = self.cache[url]\n except KeyError:\n pass\n else:\n try:\n if self.num_retries > 0 and 500 <= result['code'] < 600:\n result = None\n except Exception as e:\n result = None\n else:\n pass\n if result is None:\n self.throttle.wait(url)\n proxy = random.choice(self.proxies) if self.proxies else None\n headers = {'User-agent': self.user_agent}\n result = self.download(url, headers, proxy=proxy, num_retries=self.num_retries)\n if self.cache:\n self.cache[url] = result\n return result['html']\n\n def download(self, url, headers, proxy, num_retries, data=None):\n print('Downloading: ', url)\n req = request.Request(url, data, headers or {})\n opener = self.opener or request.build_opener()\n if proxy:\n proxy_params = {urlparse(url).scheme: proxy}\n opener.add_handler(request.ProxyHandler(proxy_params))\n try:\n response = opener.open(req)\n html = response.read().decode('utf-8')\n code = response.code\n except Exception as e:\n print('Download error', str(e))\n html = \"\"\n if hasattr(e, 'code'):\n code = e.code\n if num_retries > 0 and 500 <= code < 600:\n return self.download(url, headers, proxy, num_retries - 1, data)\n else:\n code = None\n return {\"html\": html, 'code': code}\n\n\nclass Throttle:\n def __init__(self, delay):\n self.delay = delay\n self.domains = {}\n\n def wait(self, url):\n domain = urlsplit(url).netloc\n last_accessed = self.domains.get(domain)\n if self.delay > 0 and last_accessed is not None:\n sleep_delay = self.delay - (datetime.now() - last_accessed).seconds\n if sleep_delay > 0:\n time.sleep(sleep_delay)\n self.domains[domain] = datetime.now()\n","sub_path":"practice/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"536952831","text":"\"\"\"\nWSGI config for secretgraph project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\n\"\"\"\n\n# WARNING: prefer asgi over wsgi as wsgi lacks lots of features like websockets\n\nfrom pathlib import Path\nimport os\nimport sys\n\nBASE_DIR = Path(__file__).resolve(strict=True).parent.parent\nif str(BASE_DIR) not in sys.path:\n sys.path.append(str(BASE_DIR))\n\nfrom django.core.wsgi import get_wsgi_application # noqa: E402\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"secretgraph.settings.debug\")\nif not os.environ.get(\n \"SECRETGRAPH_SILENCE\",\n \"django.core.management\" in sys.modules, # is loaded by manage.py\n):\n print(\"USE SETTINGS:\", os.environ[\"DJANGO_SETTINGS_MODULE\"])\n\napplication = get_wsgi_application()\n","sub_path":"secretgraph/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"149874404","text":"from uuid import uuid4\nfrom django.contrib.auth.models import AbstractUser\nfrom django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\nfrom django_intenum import IntEnumField\nfrom hsreplaynet.games.models import Visibility\n\n\nHEARTHSTONE_LOCALES = (\n\t(\"enUS\", \"English\"),\n\t# (\"enGB\", \"English (GB)\"),\n\t(\"zhTW\", \"Chinese (TW)\"),\n\t(\"zhCN\", \"Chinese (CN)\"),\n\t(\"frFR\", \"French\"),\n\t(\"deDE\", \"German\"),\n\t(\"itIT\", \"Italian\"),\n\t(\"jaJP\", \"Japanese\"),\n\t(\"koKR\", \"Korean\"),\n\t(\"plPL\", \"Polish\"),\n\t(\"ptBR\", \"Portuguese (BR)\"),\n\t# (\"ptPT\", \"Portuguese (PT)\"),\n\t(\"ruRU\", \"Russian\"),\n\t(\"esES\", \"Spanish (ES)\"),\n\t(\"esMX\", \"Spanish (MX)\"),\n\t(\"thTH\", \"Thai\"),\n)\n\n\nclass AccountClaim(models.Model):\n\tid = models.UUIDField(primary_key=True, editable=False, default=uuid4)\n\ttoken = models.OneToOneField(\"api.AuthToken\")\n\tapi_key = models.ForeignKey(\"api.APIKey\", on_delete=models.CASCADE, null=True)\n\tcreated = models.DateTimeField(\"Created\", auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn str(self.id)\n\n\tdef get_absolute_url(self):\n\t\treturn reverse(\"account_claim\", kwargs={\"id\": self.id})\n\n\tdef get_full_url(self):\n\t\treturn \"https://hsreplay.net\" + self.get_absolute_url()\n\n\nclass User(AbstractUser):\n\tid = models.BigAutoField(primary_key=True)\n\tusername = models.CharField(max_length=150, unique=True)\n\tbattletag = models.CharField(\n\t\tmax_length=24, blank=True,\n\t\thelp_text=\"The user's primary Battle.net username.\"\n\t)\n\tis_fake = models.BooleanField(default=False)\n\n\t# Profile fields\n\tlocale = models.CharField(\n\t\tmax_length=8, default=\"enUS\",\n\t\tchoices=HEARTHSTONE_LOCALES,\n\t\thelp_text=\"The user's preferred Hearthstone locale for display\"\n\t)\n\tdefault_replay_visibility = IntEnumField(\n\t\t\"Default replay visibility\",\n\t\tenum=Visibility, default=Visibility.Public\n\t)\n\texclude_from_statistics = models.BooleanField(default=False)\n\tjoust_autoplay = models.BooleanField(default=True)\n\tsettings = JSONField(default={})\n\n\t@cached_property\n\tdef stripe_customer(self):\n\t\tfrom djstripe.models import Customer\n\t\tcustomer, created = Customer.get_or_create(self)\n\t\treturn customer\n\n\t@cached_property\n\tdef is_premium(self):\n\t\tfrom django.conf import settings\n\n\t\t# The PREMIUM_OVERRIDE setting allows forcing a True or False for all users\n\t\t# This is especially useful if no Stripe API key is available\n\t\tpremium_override = getattr(settings, \"PREMIUM_OVERRIDE\", None)\n\t\tif premium_override is not None:\n\t\t\treturn premium_override\n\n\t\tif not getattr(settings, \"STRIPE_SECRET_KEY\", \"\"):\n\t\t\t# Override to false if we don't have a Stripe secret key to avoid unnecessary errors.\n\t\t\treturn False\n\n\t\tnow = timezone.now()\n\t\tcustomer = self.stripe_customer\n\t\tsubscriptions = customer.subscriptions.filter(status=\"active\", current_period_end__gt=now)\n\t\treturn subscriptions.count() > 0\n\n\tdef delete_replays(self):\n\t\tself.replays.update(is_deleted=True)\n\n\tdef guess_player_name(self):\n\t\tnames = []\n\t\tfor replay in self.replays.filter(spectator_mode=False):\n\t\t\tname = replay.friendly_player.name\n\t\t\tif name:\n\t\t\t\tnames.append(name)\n\t\tif names:\n\t\t\treturn max(set(names), key=names.count)\n\n\tdef trigger_webhooks(self, replay):\n\t\tif self.is_fake:\n\t\t\t# Fake users should never have webhooks\n\t\t\treturn\n\n\t\twebhooks = self.webhooks.filter(is_active=True, is_deleted=False)\n\t\tif webhooks.count():\n\t\t\tdata = replay.serialize()\n\t\t\tfor webhook in webhooks:\n\t\t\t\twebhook.trigger(data)\n\n\nclass AccountDeleteRequest(models.Model):\n\tuser = models.OneToOneField(User)\n\treason = models.TextField(blank=True)\n\tdelete_replay_data = models.BooleanField(default=False)\n\tcreated = models.DateTimeField(auto_now_add=True)\n\tupdated = models.DateTimeField(auto_now=True)\n\n\tdef __str__(self):\n\t\treturn \"Delete request for %s\" % (self.user)\n\n\tdef process(self):\n\t\tif self.user.last_login > self.updated:\n\t\t\t# User logged back in since the request was filed. Request no longer valid.\n\t\t\treturn\n\t\tif self.delete_replay_data:\n\t\t\tself.user.delete_replays()\n\t\tself.user.delete()\n","sub_path":"hsreplaynet/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"436841851","text":"import re\n\nfrom seqbio.calculation.SeqCal import gcContent, atContent, countBase, countBasesDict\nfrom seqbio.pattern.SeqPattern import enzTargetsScan, cpgSearch\nfrom seqbio.seqMan.dnaconvert import dna2rna, reverseComplementSeq, dna2protein, reverseSeq, complementSeq, loadCodons\n\n# Input\n# seq = 'ATGGGccGTAGAATTCTTGCaaGCCCGT'\n# seq = seq.upper()\n\n# print(\"Transcription: \", dna2rna(seq))\n# print(\"Transcription-revcomp: \", dna2rna(reverseComplementSeq(seq)))\n# print(\"Translation: \", dna2protein(seq))\n# print(\"Translation-revcomp: \", dna2protein(reverseComplementSeq(seq)))\n# print(\"GC Content:\", gcContent(seq))\n# print(\"Count Bases: \", countBasesDict(seq))\n# print(\"Count Bases-revcomp: \", countBasesDict(reverseComplementSeq(seq)))\n# print(\"Search EcoRI: \", enzTargetsScan(seq, 'EcoRI'))\n# print(\"Search EcoRI-revcomp: \", enzTargetsScan(reverseComplementSeq(seq), 'EcoRI'))\n\ndef test():\n seq = 'ATGGGccGTAGAATTCTTGCaaGCCCGT'\n seq = seq.upper()\n\n print(\"Transcription: \", dna2rna(seq))\n print(\"Transcription-revcomp: \", dna2rna(reverseComplementSeq(seq)))\n print(\"Translation: \", dna2protein(seq))\n print(\"Translation-revcomp: \", dna2protein(reverseComplementSeq(seq)))\n print(\"GC Content:\", gcContent(seq))\n print(\"Count Bases: \", countBasesDict(seq))\n print(\"Count Bases-revcomp: \", countBasesDict(reverseComplementSeq(seq)))\n print(\"Search EcoRI: \", enzTargetsScan(seq, 'EcoRI'))\n print(\"Search EcoRI-revcomp: \", enzTargetsScan(reverseComplementSeq(seq), 'EcoRI'))\n\ndef argparserLocal():\n from argparse import ArgumentParser\n '''Argument parser for the commands'''\n parser = ArgumentParser(prog='myseq', description='Work with sequence')\n\n subparsers = parser.add_subparsers(\n title='commands', description='Please choose command below:' ,\n dest='command'\n )\n \n subparsers.required = True\n\n #first command is gcContent\n cgc_command = subparsers.add_parser('gcContent', help='Calculate GC content')\n cgc_command.add_argument(\"-s\", \"--seq\", type=str, default=None,\n help=\"Provide sequence\")\n\n #second command is countBases\n cbase_command = subparsers.add_parser('countBases', help='Count number of each base')\n cbase_command.add_argument(\"-s\", \"--seq\", type=str, default=None, \n help=\"Provide Sequence\")\n cbase_command.add_argument(\"-r\", \"--revcomp\", action ='store_true', default=False, \n help=\"Convet DNA to reverse-complementary\")\n\n #third command is transcription\n transc_command = subparsers.add_parser('transcription', help='Convert DNA->RNA')\n transc_command.add_argument(\"-s\", \"--seq\", type=str, default=None, \n help=\"Provide Sequence\")\n transc_command.add_argument(\"-r\", \"--revcomp\", action ='store_true', default=False, \n help=\"Convet DNA to reverse-complementary\")\n\n #fouth command is translation\n transl_command = subparsers.add_parser('translation', help='Convert DNA->Protein')\n transl_command.add_argument(\"-s\", \"--seq\", type=str, default=None, \n help=\"Provide Sequence\")\n transl_command.add_argument(\"-r\", \"--revcomp\", action ='store_true', default=False, \n help=\"Convet DNA to reverse-complementary\")\n\n #fifth command is enzTargetsScan\n renz_command = subparsers.add_parser('enzTargetsScan', help='Find restriction enzyme')\n renz_command.add_argument(\"-s\", \"--seq\", type=str, default=None, \n help=\"Provide Sequence\")\n renz_command.add_argument(\"-e\", \"--enz\", type=str, default=None, \n help=\"Provide Enzyme name\")\n renz_command.add_argument(\"-r\", \"--revcomp\", action ='store_true', default=False, \n help=\"Convet DNA to reverse-complementary\")\n\n\n # parser.print_help()\n\n return parser\n\ndef main():\n parser = argparserLocal()\n args = parser.parse_args()\n # print(args)\n \n if args.command == 'gcContent':\n if args.seq == None:\n print(\"------------------------------------------------------\\nError: Invalid input (You do not provide -s or --seq)\\n------------------------------------------------------\\n\")\n exit(parser.parse_args(['gcContent','-h']))\n # print(\"line 96\", args.seq.upper())\n # print(\"line 97\", countBase(args.seq, 'G'))\n # print(\"line 98\", countBase(args.seq, 'c'))\n # print(\"line 99\", len(args.seq))\n # print(\"line 100\", float(gcContent(args.seq)))\n print(\"Input \", args.seq, \"GC Content = \", gcContent(args.seq.upper()))\n\n elif args.command == 'countBases':\n if args.seq == None:\n print(\"------------------------------------------------------\\nError: Invalid input (You do not provide -s or --seq)\\n------------------------------------------------------\\n\")\n exit(parser.parse_args(['countBases','-h']))\n elif args.revcomp:\n print(\"Input \", args.seq, \"countBases = \", countBasesDict(reverseComplementSeq(args.seq.upper())))\n else:\n print(\"Input \", args.seq, \"countBases = \", countBasesDict(args.seq.upper()))\n \n elif args.command == 'transcription':\n if args.seq == None:\n print(\"------------------------------------------------------\\nError: Invalid input (You do not provide -s or --seq)\\n------------------------------------------------------\\n\")\n exit(parser.parse_args(['transcription','-h']))\n elif args.revcomp:\n print(\"Input \", args.seq, \"Transcription = \", dna2rna(reverseComplementSeq(args.seq.upper())))\n else:\n print(\"Input \", args.seq, \"Transcription = \", dna2rna(args.seq.upper()))\n\n elif args.command == 'translation':\n if args.seq == None:\n print(\"------------------------------------------------------\\nError: Invalid input (You do not provide -s or --seq)\\n------------------------------------------------------\\n\")\n exit(parser.parse_args(['translation','-h']))\n elif args.revcomp:\n print(\"Input \", args.seq, \"Translation = \", dna2protein(reverseComplementSeq(args.seq.upper())))\n else:\n print(\"Input \", args.seq, \"Translation = \", dna2protein(args.seq.upper()))\n\n elif args.command == 'enzTargetsScan':\n if args.seq == None or args.enz == None:\n print(\"--------------------------------------------------------\\nError: Invalid input (You do not provide --seq or --enz)\\n--------------------------------------------------------\\n\")\n exit(parser.parse_args(['enzTargetsScan','-h']))\n elif args.revcomp:\n print(\"Input \", args.seq, args.enz, \"sites = \", enzTargetsScan(reverseComplementSeq(args.seq.upper()), args.enz))\n else:\n print(\"Input \", args.seq, args.enz, \"sites = \", enzTargetsScan(args.seq.upper(), args.enz))\n\n # print(args.seq, gcContent(args.seq))\n # print(args.seq, enzTargetsScan(args.seq, args.enz))\n\n\nif __name__ == \"__main__\":\n # test()\n main()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"185724192","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /var/makina/pasteStage/pasteFunBot/Paste-1.7.2-py2.6.egg/paste/util/threadinglocal.py\n# Compiled at: 2009-07-20 09:44:04\n\"\"\"\nImplementation of thread-local storage, for Python versions that don't\nhave thread local storage natively.\n\"\"\"\ntry:\n import threading\nexcept ImportError:\n\n class local(object):\n pass\n\n\nelse:\n try:\n local = threading.local\n except AttributeError:\n import thread\n\n class local(object):\n\n def __init__(self):\n self.__dict__['__objs'] = {}\n\n def __getattr__(self, attr, g=thread.get_ident):\n try:\n return self.__dict__['__objs'][g()][attr]\n except KeyError:\n raise AttributeError('No variable %s defined for the thread %s' % (\n attr, g()))\n\n def __setattr__(self, attr, value, g=thread.get_ident):\n self.__dict__['__objs'].setdefault(g(), {})[attr] = value\n\n def __delattr__(self, attr, g=thread.get_ident):\n try:\n del self.__dict__['__objs'][g()][attr]\n except KeyError:\n raise AttributeError('No variable %s defined for thread %s' % (\n attr, g()))","sub_path":"pycfiles/pasteFunBot-0.1.tar/threadinglocal.py","file_name":"threadinglocal.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"175508243","text":"\"\"\" This file is experimental and may disappear without warning \"\"\"\nfrom __future__ import print_function, division, absolute_import\n\nimport os\n\nfrom .executor import default_executor\nfrom .utils import ignoring\n\nwith ignoring(ImportError):\n import snakebite.protobuf.ClientNamenodeProtocol_pb2 as client_proto\n from snakebite.client import Client\n\n\ndef get_locations(filename, name_host, name_port, data_root='/data/dfs/dn'):\n client = Client(name_host, name_port, use_trash=False)\n files = list(client.ls([filename]))\n return [pair for file in files for pair in find(file, client, data_root)]\n\n\ndef find(f, client, data_root='/data/dfs/dn'):\n request = client_proto.GetBlockLocationsRequestProto()\n request.src = f['path']\n request.length = long(f['length'])\n request.offset = long(0)\n\n response = client.service.getBlockLocations(request)\n\n return [{'block': block,\n 'path': get_local_path(block, data_root),\n 'hosts': [location.id.ipAddr for location in block.locs]}\n for block in response.locations.blocks]\n\n\ndef get_local_path(block, data_root='/data/dfs/dn'):\n pool = block.b.poolId\n Id = block.b.blockId\n loc = idtoBlockdir(Id)\n return \"{}/current/{}/current/finalized/{}/blk_{}\".format(\n data_root, pool, loc, Id)\n\n\nBLOCK_SUBDIR_PREFIX = 'subdir'\ndef idtoBlockdir(blockId):\n d1 = str(((blockId >> 16) & 0xff))\n d2 = str(((blockId >> 8) & 0xff))\n pathd1 = BLOCK_SUBDIR_PREFIX+d1\n pathd2 = BLOCK_SUBDIR_PREFIX+d2\n path = os.path.join(pathd1, pathd2)\n return path\n\n\ndef get_data_root():\n confd = os.environ.get('HADOOP_CONF_DIR', os.environ.get('HADOOP_INSTALL',\n '') + '/hadoop/conf')\n conf = os.sep.join([confd, 'hdfs-site.xml'])\n import xml\n x = xml.etree.ElementTree.fromstring(open(conf).read())\n for e in x:\n if e.find('name').text == 'dfs.datanode.data.dir':\n return e.find('value').text\n\n\ndef map_blocks(func, location, namenode_host, namenode_port,\n data_root='/data/dfs/dn', executor=None, **kwargs):\n \"\"\" Map a function over blocks of a location in HDFS\n\n >>> L = map_blocks(pd.read_csv, '/data/nyctaxi/',\n ... '192.168.1.100', 9000) # doctest: +SKIP\n >>> type(L)[0] # doctest: +SKIP\n Future\n \"\"\"\n executor = default_executor(executor)\n blocks = get_locations(location, namenode_host, namenode_port, data_root)\n paths = [blk['path'] for blk in blocks]\n hosts = [blk['hosts'] for blk in blocks]\n return executor.map(func, paths, workers=hosts, **kwargs)\n\n\ndef dask_graph(func, location, namenode_host, namenode_port, executor=None,\n **kwargs):\n \"\"\" Produce dask graph mapping function over blocks in HDFS\n\n Inserts HDFS host restrictions into the executor.\n\n Returns a graph and keys corresponding to function applied to blocks.\n Does not trigger execution.\n\n >>> dsk, keys = dask_graph(pd.read_csv, '/data/nyctaxi/',\n ... '192.168.1.100', 9000) # doctest: +SKIP\n \"\"\"\n executor = default_executor(executor)\n blocks = get_locations(location, namenode_host, namenode_port, **kwargs)\n paths = [blk['path'] for blk in blocks]\n hosts = [blk['hosts'] for blk in blocks]\n names = [(funcname(func), path) for path in paths]\n restrictions = dict(zip(names, hosts))\n\n dsk = {name: (func, path) for name, path in zip(names, paths)}\n\n executor.send_to_scheduler({'op': 'update-graph',\n 'dsk': {},\n 'keys': [],\n 'restrictions': restrictions})\n return dsk, names\n\n\ndef read_csv(location, namenode_host, namenode_port, executor=None, **kwargs):\n import pandas as pd\n import dask.dataframe as dd\n from dask.compatibility import apply\n executor = default_executor(executor)\n\n blocks = get_locations(location, namenode_host, namenode_port, **kwargs)\n paths = [blk['path'] for blk in blocks]\n hosts = [blk['hosts'] for blk in blocks]\n name = 'hdfs-read-csv-' + location\n names = [(name, i) for i, _ in enumerate(paths)]\n\n restrictions = dict(zip(names, hosts))\n executor.send_to_scheduler({'op': 'update-graph',\n 'dsk': {},\n 'keys': [],\n 'restrictions': restrictions})\n\n future = executor.submit(fill_kwargs, blocks[0]['path'], **kwargs)\n columns, kwargs = future.result()\n rest_kwargs = assoc(kwargs, 'header', None)\n\n dsk = {(name, i): (apply, pd.read_csv, (path,), rest_kwargs)\n for i, path in enumerate(paths)}\n dsk[(name, 0)] = (apply, pd.read_csv, (paths[0],), kwargs)\n divisions = [None] * (len(paths) + 1)\n\n return dd.DataFrame(dsk, name, columns, divisions)\n","sub_path":"distributed/hdfs.py","file_name":"hdfs.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"167262587","text":"#!/Users/student/usr/local/bin/python3.6\n\nimport sys\nimport requests\nimport os\n\nkey = \"VDUIHNUQXDE1S0LZIN3JA6HMS3NE7DZ4\" # put your token here\n\ntry:\n if not os.path.isfile(sys.argv[1]):\n print('That file does not exist')\n sys.exit()\nexcept IndexError:\n print(\"Please provide a file to upload\")\n sys.exit()\nfilename = sys.argv[1]\nfile = open(filename, \"rb\")\nr = requests.post(f'https://www.momsagainstdiscord.com/upload?key={key}', files={filename: file})\n\nif not r.ok:\n if r.status_code == 413:\n print('File too large')\n sys.exit()\n else:\n print(r.text)\n sys.exit()\nif not r.json()['success']:\n print(r.json()['error'])\nelse:\n print(r.json()['files']['url'])\n if os.uname().sysname == \"Linux\":\n os.system(f\"echo \\'http://plz-notice.me{r.json()['files']['url']}\\' | xclip -selection clipboard\")\n elif os.uname().sysname == \"Darwin\":\n os.system(f\"echo \\'http://plz-notice.me{r.json()['files']['url']}\\' | pbcopy\")\n","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"641236584","text":"import random\nWORDS=(\"asia\",\"europe\",\"us\")\n#word=WORDS[random.randrange(len(WORDS))]\nword=random.choice(WORDS)\nanswer=word\njumble=\"\"\n#print(word)\nwhile word:\n position=random.randrange(len(word))\n jumble+=word[position]\n word=word[:position]+word[(position+1):]\n\n#main\nprint(\"\"\"\nwelcome to word jumble\nunscramble the letters to make the right word\n(enter quit to exit game)\n\"\"\")\nprint(\"the jumble word is:\", jumble)\n\nguess=input(\"\\nEnter your guess: \")\nwhile guess!=answer and guess !=\"quit\":\n print(\"Sorry, Guess again:\")\n guess=input(\"Enter your guess: \")\n\nif guess==answer:\n print(\"Thats right!! you got it! \")\n\nprint(\"Thanks for playing\")","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"150505055","text":"'''Handprint: HANDwritten Page RecognitIoN Test for Caltech Archives.\n\nThis project uses alternative optical character recognition (OCR) and\nhandwritten text recognition (HTR) methods on documents from the Caltech\nArchives (http://archives.caltech.edu). Tests include the use of Google's\nOCR capabilities in their Google Cloud Vision API\n(https://cloud.google.com/vision/docs/ocr), Microsoft's Azure, and others.\n\nAuthors\n-------\n\nMichael Hucka -- Caltech Library\n\nCopyright\n---------\n\nCopyright (c) 2018 by the California Institute of Technology. This code is\nopen-source software released under a 3-clause BSD license. Please see the\nfile \"LICENSE\" for more information.\n'''\n\nfrom halo import Halo\nimport json\nimport os\nfrom os import path\nimport plac\nimport requests\nimport sys\nfrom sys import exit as exit\ntry:\n from termcolor import colored\nexcept:\n pass\nimport time\nimport traceback\nfrom urllib import request\n\nimport handprint\nfrom handprint.constants import ON_WINDOWS, ACCEPTED_FORMATS, KNOWN_METHODS\nfrom handprint.constants import FORMATS_MUST_CONVERT\nfrom handprint.messages import msg, color, MessageHandlerCLI\nfrom handprint.progress import ProgressIndicator\nfrom handprint.network import network_available, download_url\nfrom handprint.files import files_in_directory, replace_extension, handprint_path\nfrom handprint.files import readable, writable, filename_extension, convert_image\nfrom handprint.htr import GoogleHTR\nfrom handprint.htr import MicrosoftHTR\nfrom handprint.exceptions import *\nfrom handprint.debug import set_debug, log\n\n# Main program.\n# ......................................................................\n\n@plac.annotations(\n creds_dir = ('look for credentials files in directory \"D\"', 'option', 'c'),\n from_file = ('read file names or URLs from file \"F\"', 'option', 'f'),\n list = ('print list of known methods', 'flag', 'l'),\n method = ('use method \"M\" (default: \"all\")', 'option', 'm'),\n output = ('write output to directory \"O\"', 'option', 'o'),\n root_name = ('name downloaded images using root file name \"R\"', 'option', 'r'),\n given_urls = ('assume have URLs, not files (default: files)', 'flag', 'u'),\n quiet = ('do not print info messages while working', 'flag', 'q'),\n no_color = ('do not color-code terminal output', 'flag', 'C'),\n debug = ('turn on debugging (console only)', 'flag', 'D'),\n version = ('print version info and exit', 'flag', 'V'),\n images = 'if given -u, URLs, else directories and/or files',\n)\n\ndef main(creds_dir = 'D', from_file = 'F', list = False, method = 'M',\n output = 'O', given_urls = False, root_name = 'R', quiet = False,\n no_color = False, debug = False, version = False, *images):\n '''Handprint (a loose acronym of \"HANDwritten Page RecognitIoN Test\") can\nrun alternative optical character recognition (OCR) and handwritten text\nrecognition (HTR) methods on images of document pages.\n\nIf given the command-line flag -l (or /l on Windows), Handprint will print a\nlist of the known methods and then exit. The option -m (/m on Windows) can\nbe used to select a specific method. (The default method is to run them all.)\n\nWhen invoked, the command-line arguments should contain one of the following:\n\n a) one or more directory paths or one or more image file paths, which will\n be interpreted as images (either individually or in directories) to be\n processed;\n\n b) if given the -u option (/u on Windows), one or more URLs, which will be\n interpreted as network locations of image files to be processed;\n\n c) if given the -f option (/f on Windows), a file containing either image\n paths or (if combined with the -u option), image URLs\n\nIf given URLs (via the -u option), Handprint will first download the images\nfound at the URLs to a local directory indicated by the option -o (/o on\nWindows). Handprint will send each image file to OCR/HTR services from\nGoogle, Microsoft and others. It will write the results to new files placed\neither in the same directories as the original files, or (if given the -o\noption) to the directory indicated by the -o option value (/o on Windows).\nThe results will be written in files named after the original files with the\naddition of a string that indicates the service used. For example, a file\nnamed \"somefile.jpg\" will produce\n\n somefile.jpg\n somefile.google.txt\n somefile.google.json\n somefile.microsoft.txt\n somefile.microsoft.json\n somefile.amazon.txt\n somefile.amazon.json\n ...\n\nand so on for each image and each service used. The .txt files will contain\nthe text extracted (if any). The .json files will contain the complete\nresponse from the service, converted to JSON by Handprint. In some cases,\nsuch as Google's API, the service may offer multiple operations and will\nreturn individual results for different API calls or options; in those cases,\nHandprint combines the results of multiple API calls into a single JSON\nobject.\n\nNote that if -u (/u on Windows) is given, then an output directory MUST also\nbe specified using the option -o (/o on Windows) because it is not possible\nto write the results in the network locations represented by the URLs. Also,\nwhen -u is used, the images and text results will be stored in files whose\nroot names have the form \"document-N\", where \"N\" is an integer. The root\nname can be changed using the -r option (/r on Windows). The image will be\nconverted to ordinary JPEG format for maximum compatibility with the\ndifferent OCR services and written to \"document-N.jpg\", and the URL\ncorresponding to each document will be written in a file named\n\"document-N.url\" so that it is possible to connect each \"document-N.jpg\" to\nthe URL it came from.\n\nCredentials for different services need to be provided to Handprint in the\nform of JSON files. Each service needs a separate JSON file named after the\nservice (e.g., \"microsoft_credentials.json\") and placed in a directory that\nHandprint searches. By default, Handprint searches for the files in a\nsubdirectory named \"creds\" where Handprint is installed, but an alternative\ndirectory can be indicated at run-time using the -c command-line option (/c\non Windows). The specific format of each credentials file is different for\neach service; please consult the Handprint documentation for more details.\n\nIf given the -q option (/q on Windows), Handprint will not print its usual\ninformational messages while it is working. It will only print messages\nfor warnings or errors.\n\nIf given the -V option (/V on Windows), this program will print version\ninformation and exit without doing anything else.\n\n '''\n\n # Prepare notification methods and hints.\n say = MessageHandlerCLI(not no_color, quiet)\n prefix = '/' if ON_WINDOWS else '-'\n hint = '(Hint: use {}h for help.)'.format(prefix)\n\n # Process arguments.\n if debug:\n set_debug(True)\n if version:\n print_version()\n exit()\n if list:\n say.info('Known methods:')\n for key in KNOWN_METHODS.keys():\n say.info(' {}'.format(key))\n exit()\n if not network_available():\n exit(say.fatal_text('No network.'))\n\n if from_file == 'F':\n from_file = None\n else:\n if not path.isabs(from_file):\n from_file = path.realpath(path.join(os.getcwd(), from_file))\n if not path.exists(from_file):\n exit(say.error_text('File not found: {}'.format(from_file)))\n if not readable(from_file):\n exit(say.error_text('File not readable: {}'.format(from_file)))\n\n if creds_dir == 'D':\n creds_dir = path.join(handprint_path(), 'creds')\n if not readable(creds_dir):\n exit(say.error_text('Directory not readable: {}'.format(creds_dir)))\n else:\n if __debug__: log('Assuming credentials found in \"{}\".', creds_dir)\n\n if method == 'M':\n method = 'all'\n method = method.lower()\n if method != 'all' and method not in KNOWN_METHODS:\n exit(say.error_text('\"{}\" is not a known method. {}'.format(method, hint)))\n\n if not images and not from_file:\n exit(say.error_text('Need provide images or URLs. {}'.format(hint)))\n if any(item.startswith('-') for item in images):\n exit(say.error_text('Unrecognized option in arguments. {}'.format(hint)))\n\n if output == 'O':\n output = None\n else:\n if not path.isabs(output):\n output = path.realpath(path.join(os.getcwd(), output))\n if path.isdir(output):\n if not writable(output):\n exit(say.error_text('Directory not writable: {}'.format(output)))\n else:\n os.mkdir(output)\n if __debug__: log('Created output directory \"{}\"', output)\n if given_urls and not output:\n exit(say.error_text('Must provide an output directory if using URLs.'))\n if root_name != 'R' and not given_urls:\n exit(say.error_text('Option {}r can only be used with URLs.'.format(prefix)))\n if root_name == 'R':\n root_name = 'document'\n\n # Create a list of files to be processed.\n targets = targets_from_arguments(images, from_file, given_urls, say)\n if not targets:\n exit(say.warn_text('No images to process; quitting.'))\n\n # Let's do this thing.\n try:\n if method == 'all':\n say.info('Applying all methods in succession.')\n for m in KNOWN_METHODS.values():\n if not say.be_quiet():\n say.msg('='*70, 'dark')\n run(m, targets, given_urls, output, root_name, creds_dir, say)\n if not say.be_quiet():\n say.msg('='*70, 'dark')\n else:\n m = KNOWN_METHODS[method]\n run(m, targets, given_urls, output, root_name, creds_dir, say)\n except (KeyboardInterrupt, UserCancelled) as err:\n exit(say.info_text('Quitting.'))\n except ServiceFailure as err:\n exit(say.error_text(str(err)))\n except Exception as err:\n if debug:\n import pdb; pdb.set_trace()\n exit(say.error_text('{}\\n{}'.format(str(err), traceback.format_exc())))\n say.info('Done.')\n\n\n# If this is windows, we want the command-line args to use slash intead\n# of hyphen.\n\nif ON_WINDOWS:\n main.prefix_chars = '/'\n\n\f\n# Helper functions.\n# ......................................................................\n\ndef run(method_class, targets, given_urls, output_dir, root_name, creds_dir, say):\n spinner = ProgressIndicator(say.use_color(), say.be_quiet())\n try:\n tool = method_class()\n tool_name = tool.name()\n say.info('Using method \"{}\".'.format(tool_name))\n tool.init_credentials(creds_dir)\n for index, item in enumerate(targets, 1):\n if not given_urls and (item.startswith('http') or item.startswith('ftp')):\n say.warn('Skipping URL \"{}\"'.format(item))\n continue\n if say.use_color() and not say.be_quiet():\n action = 'Downloading' if given_urls else 'Reading'\n spinner.start('{} {}'.format(action, item))\n fmt = None\n if given_urls:\n # Make sure the URLs point to images.\n response = request.urlopen(item)\n if response.headers.get_content_maintype() != 'image':\n spinner.fail('Did not find an image at \"{}\"'.format(item))\n continue\n fmt = response.headers.get_content_subtype()\n if fmt not in ACCEPTED_FORMATS:\n spinner.fail('Cannot use image format {} in \"{}\"'.format(fmt, item))\n continue\n # If we're given URLs, we have to invent file names to store\n # the images and the OCR results.\n base = '{}-{}'.format(root_name, index)\n url_file = path.realpath(path.join(output_dir, base + '.url'))\n if __debug__: log('Writing URL to {}', url_file)\n with open(url_file, 'w') as f:\n f.write(url_file_content(item))\n file = path.realpath(path.join(output_dir, base + '.' + fmt))\n if __debug__: log('Starting wget on {}', item)\n (success, error) = download_url(item, file)\n if not success:\n spinner.fail('Failed to download {}: {}'.format(item, error))\n continue\n else:\n file = path.realpath(path.join(os.getcwd(), item))\n fmt = filename_extension(file)\n if output_dir:\n dest_dir = output_dir\n else:\n dest_dir = path.dirname(file)\n if not writable(dest_dir):\n say.fatal('Cannot write output in \"{}\".'.format(dest_dir))\n return\n if fmt in FORMATS_MUST_CONVERT:\n spinner.update('Converting file format to JPEG: \"{}\"'.format(file))\n (success, converted_file, msg) = convert_image(file, fmt, 'jpeg')\n if not success:\n spinner.fail('Failed to convert \"{}\": {}'.format(file, msg))\n # Note: 'file' now points to the converted file, not the original\n file = converted_file\n file_name = path.basename(file)\n base_path = path.join(dest_dir, file_name)\n txt_file = replace_extension(base_path, '.' + tool_name + '.txt')\n json_file = replace_extension(base_path, '.' + tool_name + '.json')\n spinner.update('Sending to {} for text extraction'.format(tool_name))\n save_output(tool.document_text(file), txt_file)\n spinner.update('Text from {} saved in {}'.format(tool_name, txt_file))\n spinner.update('All data from {} saved in {}'.format(tool_name, json_file))\n save_output(json.dumps(tool.all_results(file)), json_file)\n if say.use_color() and not say.be_quiet():\n short_path = path.relpath(txt_file, os.getcwd())\n spinner.stop('{} -> {}'.format(item, short_path))\n except (KeyboardInterrupt, UserCancelled) as err:\n if spinner:\n spinner.stop()\n raise\n except Exception as err:\n if spinner:\n spinner.fail(say.error_text('Stopping due to a problem'))\n raise\n\n\ndef targets_from_arguments(images, from_file, given_urls, say):\n targets = []\n if from_file:\n with open(from_file) as f:\n targets = f.readlines()\n targets = [line.rstrip('\\n') for line in targets]\n if __debug__: log('Read {} lines from \"{}\".', len(targets), from_file)\n if not given_urls:\n targets = filter_urls(targets, say)\n elif given_urls:\n # We assume that the arguments are URLs and take them as-is.\n targets = images\n else:\n # We were given files and/or directories. Look for image files.\n for item in filter_urls(images, say):\n if path.isfile(item) and filename_extension(item) in ACCEPTED_FORMATS:\n targets.append(item)\n elif path.isdir(item):\n targets += files_in_directory(item, extensions = ACCEPTED_FORMATS)\n else:\n say.warn('\"{}\" not a file or directory'.format(item))\n return targets\n\n\ndef filter_urls(item_list, say):\n results = []\n for item in item_list:\n if item.startswith('http') or item.startswith('ftp'):\n say.warn('Unexpected URL: \"{}\"'.format(item))\n continue\n else:\n results.append(item)\n return results\n\n\ndef url_file_content(url):\n return '[InternetShortcut]\\nURL={}\\n'.format(url)\n\n\ndef print_version():\n print('{} version {}'.format(handprint.__title__, handprint.__version__))\n print('Author: {}'.format(handprint.__author__))\n print('URL: {}'.format(handprint.__url__))\n print('License: {}'.format(handprint.__license__))\n\n\ndef save_output(text, file):\n with open(file, 'w') as f:\n f.write(text)\n\n# init_halo_hack() is mostly a guess at a way to keep the first part of the\n# spinner printed by Halo from overwriting part of the first message we\n# print. It seems to work, but the problem that this tries to solve occurred\n# sporadically anyway, so maybe the issue still remains and I just haven't\n# seen it happen again.\n\ndef init_halo_hack():\n\n '''Write a blank to prevent occasional garbled first line printed by\n Halo.'''\n sys.stdout.write('')\n sys.stdout.flush()\n time.sleep(0.1)\n\n\f\n# Main entry point.\n# ......................................................................\n# The following allows users to invoke this using \"python3 -m handprint\".\n\nif __name__ == '__main__':\n plac.call(main)\n\n\f\n# For Emacs users\n# ......................................................................\n# Local Variables:\n# mode: python\n# python-indent-offset: 4\n# End:\n","sub_path":"handprint/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":17059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"209631836","text":"from random import random #import the random function\n\n\ndef shuffle(L):\n \"\"\"\n This function uses Durstenfeld algorithm to shuffle the list L\n \"\"\"\n n = len(L)\n for i in L:\n d = L.index(i)\n \n for i in range(d):\n n = n - 1\n x = int(random() * d) - n\n L[d], L[x] = L[x], L[d] #exchange\n #print(L)\n return L\n#print(shuffle([\"alpha\",\"beta\",\"gamma\",\"delta\",\"epsilon\",\"zeta\",\"eta\",\"theta\",\"iota\",\"kappa\",\"lambda\",\"mu\"])) #test shuffle function\n \ndef check_shuffle(L, shuffled_L):\n \"\"\"\n This function checks if the shuffled list meets the requirement. \n The first argument is the original list while the second is the shuffled list.\n \"\"\"\n assert len(shuffled_L) == len(L), \"Length of shuffled list and original list are not the same\"\n for i in L:\n assert i in shuffled_L, \"Elements in original list not in Shuffled list\"\n\ndef quality(shuffled_L):\n \"\"\"\n This function checks the quality of the shuffling of the list.\n \"\"\"\n greater_than_previous = []\n v = 0\n \n for i in range(len(shuffled_L) - 1):\n v = i + 1\n if shuffled_L[v] > shuffled_L[i]:\n greater_than_previous.append(shuffled_L[v])\n \n quality_no = len(greater_than_previous)/len(shuffled_L)\n return quality_no\n \ndef average_quality(L, trials):\n \"\"\"\n This function checks the average quality over a given number of trials of a given list \n \"\"\"\n av_quality = []\n qua = 0\n \n \n for i in range(trials): #this loop will do our shuffle and quality function for a given number of trials\n s = L.copy() #make a copy of the original list\n shuffle(s)\n q = quality(s)\n av_quality.append(q)\n \n for x in range(len(av_quality)): #this for loop calculates the average quality\n qua = av_quality[x] + qua\n average_q = qua/len(av_quality)\n print('this is the average quality: ', average_q)\naverage_quality(list(range(100)), 1000)\n \n \n \n \n\n ","sub_path":"shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"400375311","text":"# -*- coding: utf-8 -*-\nimport os\nimport mimetypes\nfrom tempfile import mktemp\nfrom werkzeug.utils import secure_filename\nfrom flask import Flask, request, render_template, redirect, url_for\n \napp = Flask(__name__)\n \nUPLOAD_FOLDER = 'static/Uploads'\nALLOWED_MIMETYPES = {'image/jpeg', 'image/png', 'image/gif'}\n \n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'GET':\n return render_template('upload.html', img='')\n elif request.method == 'POST':\n f = request.files['file']\n fname = mktemp(suffix='_', prefix='u', dir=UPLOAD_FOLDER) + secure_filename(f.filename)\n f.save(fname)\n if mimetypes.guess_type(fname)[0] in ALLOWED_MIMETYPES:\n return render_template('upload.html', img=fname)\n else:\n os.remove(fname)\n return redirect(url_for('upload'), 302)\n \n@app.route('/')\ndef index():\n return redirect(url_for('upload'), 302)\n \nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"mvp/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"496496108","text":"# -*- coding: utf-8 -*-\n# File: pyScript27_SortingIntro.py\n\n\"\"\"\n# CS 5010\n# Learning Python (Python version: 3)\n# Topics:\n# - Brief introduction to soring in Python (using built in functions)\n\"\"\"\n\n\"\"\"\nSorting a Simple List\n\"\"\"\nsimpleList = [3,7,22,8,14,55,1,23,45,9]\n# Sorting in ascending order\n# Can use built in function sorted that doesn't modify the original list,\n# and returns a new sorted list\nnewLst = sorted(simpleList)\nprint(newLst) # [1, 3, 7, 8, 9, 14, 22, 23, 45, 55]\nprint(simpleList) # [3, 7, 22, 8, 14, 55, 1, 23, 45, 9]\n# For in-place sorting call \"sort\"\nsimpleList.sort()\nprint(simpleList) # [1, 3, 7, 8, 9, 14, 22, 23, 45, 55]\nprint(\">>>.....................<<<\\n\")\n\n#%%\n\n# Descending order? Sure!\nsimpleList = [3,7,22,8,14,55,1,23,45,9]\nprint(sorted(simpleList, reverse=True)) # [55, 45, 23, 22, 14, 9, 8, 7, 3, 1]\nsimpleList.sort(reverse=True)\nprint(simpleList) # [55, 45, 23, 22, 14, 9, 8, 7, 3, 1]\nprint(\">>>.....................<<<\\n\")\n# What is going on? Well, behind the scenes Python is calling a \n# version of *mergesort* on the list. \n\n#%%\n\n\"\"\"\nSorting a Simple Tuple\n\"\"\"\n# Important note:\n# Tuples must always use the \"sorted\" function to return a sorted * list *\n# You cannot modify tuples, so there isn't an in-place sort function.\nsimpleTup = (2,6,9,22,1,45,16,34)\nsortedTup = sorted(simpleTup)\nprint(sortedTup) # [1, 2, 6, 9, 16, 22, 34, 45]\nprint(\">>>.....................<<<\\n\")\n\n#%%\n\"\"\"\nSorting a List of Tuples or Lists of Lists\n\"\"\"\n# The sorted function takes in a keyword argument called \"key\"\n# Key provides a way to specify a function and returns what you would like\n# your items sorted by.\n\n# Sorting List of Tuples \nq = \"Are you suggesting coconuts migrate\" # Fun quote from Monty Python\nprint(q)\nwordslist = q.split(' ') # split by the ' ' delimiter. Result: a list!\nwlen = [(word, len(word)) for word in wordslist]\n# \"wlen\" is a list of tuples (word, word length) at index positions 0 and 1\nwlen_sorted = sorted(wlen, key=lambda wlen: wlen[1]) # sort by length\n# using the method \"sorted\" on wlen, sorting elements by length\nprint(wlen_sorted)\n# *** The above could also be achieved in the following way (w/out using lambda) ***\n# def getKey(item):\n# return item[1]\n# sorted(wlen, key=getKey)\nprint(\">>>.....................<<<\\n\")\n\n#%%\n\n# Sorting List of Lists\ndef getKey(item):\n return item[0]\n\n\nlst = [[2, 3], [6, 7], [7, 14], [25, 15], [35, 8], [1, 44]]\nsortedLst = sorted(lst, key=getKey) # sort by the FIRST item in the sub-list\nprint(sortedLst) # [[1, 44], [2, 3], [6, 7], [7, 14], [25, 15], [35, 8]]\n\n#%%\n\n# Sorting by the SECOND item in each sub-list is a simple matter of\n# changing what the function returns, as follows:\ndef getKey2(item):\n\treturn item[1]\nlst = [[2, 3], [6, 7], [7, 14], [25, 15], [35, 8], [1, 44]]\nsortedLst2 = sorted(lst, key=getKey2) # sort by the SECOND item in the sub-list\nprint(sortedLst2) \nprint(\">>>.....................<<<\\n\")\n#%%\n\n\"\"\"\nSorting a List (or Tuple) of Custom Python Objects\n\"\"\"\n# Let's create a class:\nclass Pet():\n def __init__(self, name, age): # Constructor\n self.name = name\n self.age = age\n \n # Tells Python how we want the object to be represented\n # In this case, we tell Python to represent an object of type Pet\n # by it's class name, name, and age\n def __repr__(self): \n return '{}: {} {}'.format(self.__class__.__name__,self.name, self.age)\n # Tells the interpreter how to display the object when it is printed\n \n# Create some 'Pet' objects:\ng = Pet('Ginger', 5)\nf = Pet('Fido', 12)\nt = Pet('Tiger', 9)\ns = Pet('Sparky', 8)\n\n# Example of __repr__ being called:\nprint(t)\n\n# Make a list of these Pet objects, so that we can sort them:\npetLst = [g,f,t,s]\n\n# Print out the Pet list\nprint(petLst) # [Pet: Ginger 5, Pet: Fido 12, Pet: Tiger 9, Pet: Sparky 8]\n\n# Sort by age:\ndef getPetKey(aPet):\n return aPet.age\n\nsortedPetLst = sorted(petLst, key=getPetKey)\nprint(\"Sorted pet list (by age): \\n\" + str(sortedPetLst))\n# [Pet: Ginger 5, Pet: Sparky 8, Pet: Tiger 9, Pet: Fido 12]\n","sub_path":"Module04/pyScript27_SortingIntro.py","file_name":"pyScript27_SortingIntro.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"378101708","text":"import os\n\nimport pandas as pd\n\n\ndef get_form_counts(df, form):\n return df[df['form'] == form].shape[0]\n\n\nif __name__ == '__main__':\n base_dir = os.path.expanduser('~/acronyms/expansion_etl/data/derived/')\n df = pd.read_csv(os.path.join(base_dir, 'all_prototype_contexts.csv'))\n acronyms = pd.read_csv(os.path.join(base_dir, 'prototype_acronym_expansions.csv'))\n\n sf_counts = []\n lf_counts = []\n sf_counts_map = {}\n for idx, row in acronyms.iterrows():\n row = row.to_dict()\n sf = row['sf']\n lf = row['lf']\n if sf not in sf_counts_map:\n sf_counts_map[sf] = get_form_counts(df, sf)\n sf_counts.append(sf_counts_map[sf])\n lf_counts.append(get_form_counts(df, lf))\n acronyms['sf_count'] = sf_counts\n acronyms['lf_count'] = lf_counts\n acronyms.to_csv(os.path.join(base_dir, 'prototype_acronym_expansions_w_counts.csv'), index=False)\n","sub_path":"expansion_etl/context_extraction/add_counts_to_prototype.py","file_name":"add_counts_to_prototype.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"164344500","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport sqlite3 as lite\ntry:\n from HTMLParser import HTMLParser\nexcept:\n from html.parser import HTMLParser\nimport functools\nimport logging\n\n\ncon = None # this is the db connection object. \n\nclass ContentmanagementPipeline(object):\n \"\"\" Store catalog info into three tables within Contentmanagement.db\n\n Three tables are Industry, Category, Classify,respectively\n Industry stands for 35 separate industries-(level 1)\n Category stands for around 1400 separate categories-(level 2)\n Classify stands for around 6000 separate classifications-(level 3) \n\n \"\"\"\n\n def __init__(self):\n self.setupDBcon()\n self.createTable()\n\n def check_spider_pipeline(process_item_method):\n \"\"\"decorator to check the pipeline attribute of spider, for\n whether or not it should be executed\n \"\"\"\n @functools.wraps(process_item_method)\n def wrapper(self, item, spider):\n\n # message template for debugging\n msg = '%%s %s pipeline step' % (self.__class__.__name__,)\n\n # if class is in the spider's pipeline, then use the\n # process_item method normally.\n if self.__class__ in spider._pipelines:\n logging.info(msg % 'executing')\n return process_item_method(self, item, spider)\n\n # otherwise, just return the untouched item (skip this step in\n # the pipeline)\n else:\n logging.info(msg % 'skipping')\n return item\n\n return wrapper\n\n @check_spider_pipeline\n def process_item(self, item, spider):\n self.storeInDB(item)\n return item\n\n def storeInDB(self,item):\n # We store industryInfo into corresponding table, then fetch the sequence column\n # standed by 'industryranking' as industryID( because when in multithread cases,\n # the item is not fetched by normal sequence)\n # item['categoryMemeber'] is a list as folllowing structure\n # [category1, category2, categoy3, ...]\n # catesel['classifyMember'] that also is category['classifyMember'] is a list as folllowing\n # [classify1, classify2, classify3, ...]\n\n self.storeIndustryInfoInDb(item)\n industryID = item['industryranking'] # lastrowid doesn't work here\n for catesel in item['categoryMember']: \n self.storeCategoryInfoInDb(catesel,industryID)\n categoryID = catesel['categoryranking']\n for classifysel in catesel['classifyMember']:\n self.storeClassifyInfoInDb(classifysel,industryID,categoryID)\n\n def setupDBcon(self):\n self.con_catalog = lite.connect('Contentmanagement.db')\n self.cur = self.con_catalog.cursor()\n\n def createTable(self):\n \"\"\"create three level tables\"\"\"\n self.createIndustryTable()\n self.createCategoryTable()\n self.createClassifyTable()\n\n def createIndustryTable(self):\n self.cur.execute('''DROP TABLE IF EXISTS Industry''')\n self.cur.execute('''CREATE TABLE IF NOT EXISTS Industry( id INTEGER PRIMARY KEY NOT NULL,\\\n industryName TEXT,\\\n industryurl TEXT,\\\n industryranking INTEGER,\\\n industrytotal INTEGER\\\n )''')\n \n def createCategoryTable(self):\n self.cur.execute('''DROP TABLE IF EXISTS Category''')\n self.cur.execute('''CREATE TABLE IF NOT EXISTS Category( id INTEGER PRIMARY KEY NOT NULL,\\\n industryID INTEGER NOT NULL,\\\n categoryName TEXT,\\\n categoryurl TEXT,\\\n categoryranking INTEGER,\\\n categorytotal INTEGER\\\n )''')\n\n def createClassifyTable(self):\n self.cur.execute('''DROP TABLE IF EXISTS Classify''')\n self.cur.execute('''CREATE TABLE IF NOT EXISTS Classify( id INTEGER PRIMARY KEY NOT NULL,\\\n industryID INTEGER NOT NULL,\\\n categoryID INTEGER NOT NULL,\\\n classifyName TEXT,\\\n classifyurl TEXT,\\\n classifyranking INTEGER,\\\n classifytotal INTEGER\\\n )''')\n\n def storeIndustryInfoInDb(self, item):\n \"\"\"Store 35 industry information to Industry table( first level) \"\"\"\n self.cur.execute(\"INSERT INTO Industry(\\\n industryName, \\\n industryurl, \\\n industryranking,\\\n industrytotal\\\n ) \\\n VALUES( ?, ?, ?,?)\", \\\n ( \\\n item.get('industryName', ''), \n item.get('industryurl', ''), \n item.get('industryranking'),\n item.get('industrytotal') \n ))\n self.con_catalog.commit() \n\n def storeCategoryInfoInDb(self,item,industryID):\n \"\"\"Store thousand of Category info to Category table( second level)\"\"\"\n self.cur.execute(\"INSERT INTO Category(\\\n industryID,\\\n categoryName, \\\n categoryurl, \\\n categoryranking,\\\n categorytotal\\\n ) \\\n VALUES( ?, ?, ?,?,?)\", \\\n (\\\n industryID,\n item.get('categoryName', ''), \n item.get('categoryurl', ''), \n item.get('categoryranking'),\n item.get('categorytotal') \n ))\n self.con_catalog.commit() \n\n def storeClassifyInfoInDb(self, item,industryID,categoryID):\n \"\"\"Store thousand of Classify info to Classify table( third level)\"\"\"\n self.cur.execute(\"INSERT INTO Classify(\\\n industryID,\\\n categoryID,\\\n classifyName, \\\n classifyurl, \\\n classifyranking,\\\n classifytotal\\\n ) \\\n VALUES( ?, ?, ?,?,?,?)\", \\\n ( \\\n industryID,\n categoryID,\n item.get('classifyName', ''),\n item.get('classifyurl', ''), \n item.get('classifyranking'),\n item.get('classifytotal')\n ))\n self.con_catalog.commit() \n\n def __del__(self):\n self.closeDB()\n\n def closeDB(self):\n self.con_catalog.close()\n\n\n\nclass YellowpagePipeline(object):\n\n def __init__(self):\n self.setupDBcon()\n self.createTable()\n\n def process_item(self, item, spider):\n self.storeCompanyInDb(item)\n return item\n\n def setupDBcon(self): \n \"\"\"connect bjYellowpages database and setup cursor \"\"\"\n self.con = lite.connect('bjYellowpages.db')\n self.cur = self.con.cursor()\n\n def createTable(self): \n \"\"\"create Company table\"\"\"\n self.cur.execute('''DROP TABLE IF EXISTS Company''')\n self.cur.execute('''CREATE TABLE IF NOT EXISTS Company(id INTEGER PRIMARY KEY NOT NULL,\n industryID INTEGER,\n categoryID INTEGER,\n classfiyID INTEGER,\n name TEXT,\n url TEXT,\n legalRepresentative TEXT,\n registedCapital TEXT,\n businessModel TEXT,\n employNum TEXT,\n majorMarket TEXT,\n customerType TEXT,\n industry TEXT,\n productionInfo TEXT,\n industryInfo TEXT,\n districtInfo TEXT,\n relatedLink TEXT,\n companyTag TEXT,\n updateTime TEXT,\n viewNum TEXT,\n description TEXT,\n contactPerson TEXT,\n webSite TEXT,\n postNum TEXT,\n location TEXT,\n phone TEXT,\n fax TEXT \n )''')\n \n def storeCompanyInDb(self,item): \n \"\"\" store information to Company table \"\"\"\n self.cur.execute('''INSERT INTO Company(\n industryID ,\n categoryID ,\n classfiyID ,\n name ,\n url ,\n legalRepresentative ,\n registedCapital ,\n businessModel ,\n employNum ,\n majorMarket ,\n customerType ,\n industry ,\n productionInfo ,\n industryInfo ,\n districtInfo ,\n relatedLink ,\n companyTag ,\n updateTime ,\n viewNum ,\n description ,\n contactPerson ,\n webSite ,\n postNum ,\n location ,\n phone ,\n fax \n )\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', \n (\n item.get('industryID'),\n item.get('categoryID'),\n item.get('classifyID'),\n item.get('name',''),\n item.get('url',''),\n self.strip_tag(item.get('legalRepresentative')),\n self.strip_tag(item.get('registedCapital')),\n self.strip_tag(item.get('businessModel')),\n self.strip_tag(item.get('employNum')),\n self.strip_tag(item.get('majorMarket')),\n self.strip_tag(item.get('customerType')),\n self.strip_tag(item.get('industry')),\n self.strip_tag(item.get('productionInfo')),\n self.strip_tag(item.get('industryInfo')),\n self.strip_tag(item.get('districtInfo')),\n self.strip_tag(item.get('relatedLink')),\n self.strip_tag(item.get('companyTag')),\n self.strip_tag(item.get('updateTime')),\n self.strip_tag(item.get('viewNum')),\n self.strip_tag(item.get('description')),\n self.strip_tag(item.get('contactPerson')),\n self.strip_tag(item.get('webSite')),\n self.strip_tag(item.get('postNum')),\n self.strip_tag(item.get('location')),\n self.strip_tag(item.get('phone')),\n self.strip_tag(item.get('fax'))\n ))\n self.con.commit()\n\n def strip_tag(self,html):\n \"\"\"strip off the useless html tag such as ...\"\"\"\n s = MLStripper()\n s.feed(html)\n return s.get_data() \n\n def __del__(self):\n self.closeDB()\n\n def closeDB(self):\n self.con.close()\n\n\nclass MLStripper(HTMLParser): \n \"\"\"strip off the useless html tag such as ...\"\"\"\n def __init__(self):\n super().__init__()\n self.reset()\n self.fed = []\n def handle_data(self,d):\n self.fed.append(d)\n def get_data(self):\n return ''.join(self.fed)\n\n","sub_path":"yellowpage/yellowpageSpider-for-github/yellowpage/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":10450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"405650498","text":"import json\r\nimport asyncio\r\n\r\nfrom prettytable import PrettyTable\r\nfrom ..utils.CustomLogger import CustomLogger\r\nfrom bfxapi import Client\r\nfrom .DataServerWebsocket import DataServerWebsocket\r\nfrom ..Strategy.OrderManager import OrderManager\r\nimport websockets\r\n\r\nlogger = CustomLogger('HFExecutor', logLevel='INFO')\r\n\r\ndef _format_candle(mts, open, close, high, low, volume, symbol, tf):\r\n return {\r\n 'mts': mts,\r\n 'open': open,\r\n 'close': close,\r\n 'high': high,\r\n 'low': low,\r\n 'volume':volume,\r\n 'symbol': symbol,\r\n 'tf': tf,\r\n }\r\n\r\ndef _logTrades(positions):\r\n x = PrettyTable()\r\n x.field_names = [\"Date\", \"Symbol\", \"Direction\", \"Amount\", \"Price\", \"Fee\", \"P&L\", \"Label\"]\r\n\r\n for pos in positions:\r\n for i, t in enumerate(pos.trades):\r\n lastItem = i+1 == len(pos.trades)\r\n pl = round(pos.netProfitLoss, 2)\r\n x.add_row([t.date, pos.symbol, t.direction, abs(t.amount), round(t.price, 2),\r\n round(t.fee, 2), pl if lastItem else 0, t.tag])\r\n print(x)\r\n\r\ndef _finish(strategy):\r\n print (\"\\nBacktesting complete: \\n\")\r\n\r\n profitLoss = 0\r\n totalFees = 0\r\n totalTrades = 0\r\n totalVolume = 0\r\n positions = strategy.closedPositions\r\n minProfitLoss = 0\r\n maxProfitLoss = 0\r\n totalLossesCount = 0\r\n totalLosses = 0\r\n totalGainersCount = 0\r\n totalGainers = 0\r\n\r\n for pos in positions:\r\n profitLoss += pos.profitLoss\r\n totalFees += pos.totalFees\r\n totalTrades += len(pos.trades)\r\n totalVolume += pos.volume\r\n if pos.netProfitLoss < 0:\r\n totalLossesCount += 1\r\n totalLosses += pos.netProfitLoss\r\n else:\r\n totalGainersCount += 1\r\n totalGainers += pos.netProfitLoss\r\n netP = pos.netProfitLoss\r\n minProfitLoss = netP if netP < minProfitLoss else minProfitLoss\r\n maxProfitLoss = netP if netP > maxProfitLoss else maxProfitLoss\r\n \r\n _logTrades(positions)\r\n print('')\r\n\r\n totalNetProfitLoss = profitLoss - totalFees\r\n logger.info(\"Net P/L {} | Gross P/L {} | Vol {} | Fees {}\".format(\r\n round(totalNetProfitLoss, 2), round(profitLoss, 2),\r\n round(totalVolume, 2), round(totalFees, 2)))\r\n logger.info(\"Min P/L {} | Max P/L {} | Avg P/L {}\".format(\r\n round(minProfitLoss, 2), round(maxProfitLoss, 2), \r\n round(totalNetProfitLoss / totalTrades, 2)))\r\n logger.info(\"Losses {} (total {}) | Gains {} (total {})\".format(\r\n totalLossesCount, round(totalLosses, 2), totalGainersCount,\r\n round(totalGainers, 2)))\r\n logger.info(\"{} Positions | {} Trades\".format(len(positions), totalTrades))\r\n\r\n####################################################\r\n# Public Functions #\r\n####################################################\r\n\r\ndef backtestWithDataServer(strategy, fromDate, toDate, trades=True, candles=True,\r\n tf='1m', candleFields=\"*\", tradeFields=\"*\", sync=True):\r\n def end():\r\n _finish(strategy)\r\n try:\r\n ws = DataServerWebsocket(symbol=strategy.symbol)\r\n strategy.ws = ws\r\n ws.on('done', end)\r\n ws.on('new_candle', strategy._process_new_candle)\r\n ws.on('new_trade', strategy._process_new_trade)\r\n strategy.OrderManager = OrderManager(ws, backtesting=True, logLevel='INFO')\r\n strategy.ws.run(fromDate, toDate, trades, candles, tf, candleFields, tradeFields, sync)\r\n except websockets.ConnectionClosed:\r\n pass \r\n\r\nasync def _process_candle_batch(strategy, candles):\r\n for c in candles:\r\n await strategy._process_new_candle(c)\r\n async def call_finish():\r\n await strategy.close_open_positions()\r\n _finish(strategy)\r\n # call via event emitter so it scheduled correctly\r\n strategy.on(\"done\", call_finish)\r\n await strategy._emit(\"done\")\r\n\r\ndef backtestOffline(strategy, file=None, candles=None, tf='1hr'):\r\n strategy.OrderManager = OrderManager(None, backtesting=True, logLevel='INFO')\r\n if candles:\r\n return strategy._executeWithCandles(candles)\r\n elif file:\r\n with open(file, 'r') as f:\r\n candleData = json.load(f)\r\n candleData.reverse()\r\n candles = map(lambda candleArray: _format_candle(\r\n candleArray[0], candleArray[1], candleArray[2], candleArray[3],\r\n candleArray[4], candleArray[5], strategy.symbol, tf\r\n ), candleData)\r\n # run async event loop\r\n loop = asyncio.get_event_loop()\r\n task = asyncio.ensure_future(_process_candle_batch(strategy, candles))\r\n loop.run_until_complete(task)\r\n else:\r\n raise KeyError(\"Expected either 'candles' or 'file' in parameters.\")\r\n\r\ndef _start_bfx_ws(strategy, API_KEY=None, API_SECRET=None):\r\n bfx = Client(\r\n API_KEY,\r\n API_SECRET,\r\n manageOrderBooks=True\r\n )\r\n async def subscribe():\r\n await bfx.ws.subscribe('candles', strategy.symbol, timeframe='1m')\r\n await bfx.ws.subscribe('trades', strategy.symbol)\r\n await bfx.ws.subscribe('book', strategy.symbol)\r\n bfx.ws.on('connected', subscribe)\r\n bfx.ws.on('new_candle', strategy._process_new_candle)\r\n bfx.ws.on('new_trade', strategy._process_new_trade)\r\n bfx.ws.run()\r\n\r\nasync def _seed_candles(strategy, bfxapi):\r\n seed_candles = await bfxapi.rest.get_seed_candles(strategy.symbol)\r\n candles = map(lambda candleArray: _format_candle(\r\n candleArray[0], candleArray[1], candleArray[2], candleArray[3],\r\n candleArray[4], candleArray[5], strategy.symbol, '1m'\r\n ), seed_candles)\r\n for candle in candles:\r\n strategy._process_new_seed_candle(candle)\r\n\r\ndef backtestLive(strategy):\r\n backtesting=True\r\n bfx = Client()\r\n strategy.OrderManager = OrderManager(bfx.ws, backtesting=backtesting, logLevel='INFO')\r\n t = asyncio.ensure_future(_seed_candles(strategy, bfx))\r\n asyncio.get_event_loop().run_until_complete(t)\r\n _start_bfx_ws(strategy)\r\n\r\ndef executeLive(strategy, API_KEY, API_SECRET):\r\n backtesting=False \r\n bfx = Client(\r\n API_KEY=API_KEY,\r\n API_SECRET=API_SECRET\r\n )\r\n strategy.OrderManager = OrderManager(bfx.ws, backtesting=backtesting, logLevel='INFO')\r\n t = asyncio.ensure_future(_seed_candles(strategy, bfx))\r\n asyncio.get_event_loop().run_until_complete(t)\r\n bfx.ws.run()\r\n bfx.ws.on('new_candle', strategy._process_new_candle)\r\n bfx.ws.on('new_trade', strategy._process_new_trade)\r\n","sub_path":"HFStrategy/utils/Executor.py","file_name":"Executor.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"214086569","text":"# -*- coding: utf-8 -*-\n# file: i3pystatus\n# author: moparx - http://moparx.com/configs\n# last mod: 08/16/2014 - 10:55 EDT\n# vim: set ai et fenc=utf-8 ft=python nu si sts=0 sw=4 ts=8 tw=0 :\n# ----------------------------------------------------------------------\n\nimport subprocess\n\nfrom i3pystatus import Status\nfrom i3pystatus.mail import maildir\n\nstatus = Status(standalone=True)\n\n#Clock\nstatus.register(\"clock\",\n format = \" %a, %b %_d %Y %I:%M%P \", )\n\n# Audio\nstatus.register(\"pulseaudio\",\n format = \" {volume} \",\n format_muted = \" muted {%volume} \", )\n\n# CPU temperature\nstatus.register(\"temp\",\n format = \" {temp:.0f}°C \", )\n\n# Average load\nstatus.register(\"load\",\n format = \" {avg1} {avg5} \",\n critical_limit = 4, )\n\n# MPD status\n# status.register(\"mpd\",\n# format = \"[ {status} {artist} - {title} ]\",\n# status = {\n# \"pause\": \"\",\n# \"play\": \"\",\n# \"stop\": \"\",\n# }, )\n#\n# Email\n# status.register(\"mail\",\n# format = \" {unread} new email \",\n# format_plural = \" {unread} new emails \",\n# color_unread = \"#00FF00\",\n# email_client = \"urxvtc -e mutt\",\n# backends = [\n# maildir.MaildirMail(\n# directory = \"/home/moparx/.mail/inbox\"\n# )\n# ])\n#\n\nstatus.run()\n","sub_path":"i3/i3status.config.py","file_name":"i3status.config.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"554356014","text":"import csv\nimport ntpath\nfrom zipfile import ZipFile\n\nimport requests\nfrom mechanize import Browser\nfrom tqdm import tqdm\n\nurl = \"https://www.bseindia.com/markets/MarketInfo/BhavCopy.aspx\"\nbr = Browser()\nbr.set_handle_robots(False)\nbr.open(url)\n\nmain_url = None\n\nfor link in br.links():\n # print link.url\n\n if (link.url.startswith('http://www.bseindia.com/download/BhavCopy/Equity/') or link.url.startswith(\n 'https://www.bseindia.com/download/BhavCopy/Equity/')) and (\n link.url.endswith('_CSV.ZIP') or link.url.endswith('csv.zip')):\n main_url = link.url\n\nfilename = ntpath.basename(main_url)\nresponse = requests.get(main_url, stream=True)\n\nwith open(filename, \"wb\") as handle:\n for data in tqdm(response.iter_content()):\n handle.write(data)\n\ncsv_filename = None\n\nwith ZipFile(filename, 'r') as zip:\n # printing all the contents of the zip file\n zip.printdir()\n\n csv_filename = zip.NameToInfo.keys()[0]\n\n # extracting all the files\n print('Extracting all the files now...')\n zip.extractall()\n print('Done!')\n\nindex_of_SC_CODE = 0\nindex_of_SC_NAME = 1\nindex_of_OPEN = 4\nindex_of_HIGH = 5\nindex_of_LOW = 6\nindex_of_CLOSE = 7\n\nout_file = open('parsed_data.csv', 'a')\nout_file.truncate(0)\nheader = 'SC_CODE,SC_NAME,OPEN,HIGH,LOW,CLOSE\\n'\nout_file.write(header)\n\nwith open(csv_filename, 'r') as csvFile:\n reader = csv.reader(csvFile)\n\n reader = iter(reader)\n next(reader)\n\n for row in reader:\n out_file.write('%s,%s,%s,%s,%s,%s\\n' % (\n row[index_of_SC_CODE], row[index_of_SC_NAME], row[index_of_OPEN], row[index_of_HIGH],\n row[index_of_LOW], row[index_of_CLOSE]))\n\ncsvFile.close()\nout_file.close()\n","sub_path":"hackerrank_hiring_challenge/webscraper_v3.py","file_name":"webscraper_v3.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"36600406","text":"import torch\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\n\n# 读取csv文件,并只使用第二列数据\n# data_csv=pd.read_csv('../CSV/data.csv',usecols=[1])# shape (145, 1)\ndata_csv = pd.read_csv('../CSV/test01.csv', usecols=[1])\n# data2_csv=data2_csv.dropna()\n# data2_csv=data2_csv.values\n# plt.plot(data2_csv)\n# plt.show()\n\n\n# 去除数据集中的na\ndata_csv = data_csv.dropna()\ndataset = data_csv.values # shape (144, 1)\n# 转换为float32\ndataset = dataset.astype('float32')\n# 归一 新数据=(原数据-最小值)/(最大值-最小值)\n# max_value = np.max(dataset)\nmax_value = np.max(dataset)-np.min(dataset)\ndataset = list(map(lambda x: x-np.min(dataset) / max_value, dataset)) # list len:144\n\n\ndef create_dataset(dataset, look_back):\n dataX, dataY = [], []\n for i in range(len(dataset) - look_back):\n dataX.append(dataset[i:i + look_back])\n dataY.append(dataset[i + look_back])\n return np.array(dataX), np.array(dataY)\n\n\ndataX, dataY = create_dataset(dataset, 2)\n# dataX.shape (142, 2, 1)\n# dataY.shape (142, 1)\n\ntrain_size = int(len(dataX) * 0.7)\ntrain_x = dataX[:train_size]\ntrain_y = dataY[:train_size]\n\ndataSet = Data.TensorDataset(data_tensor=torch.from_numpy(train_x), target_tensor=torch.from_numpy(train_y))\ndataloader = Data.DataLoader(dataset=dataSet, batch_size=64, shuffle=True)\ntest_x = dataX[train_size:]\ntest_y = dataY[train_size:]\n\n\nclass Lstm(nn.Module):\n def __init__(self):\n super(Lstm, self).__init__()\n self.layer1 = nn.LSTM(input_size=2, hidden_size=6, num_layers=2,dropout=0.2)\n self.layer2 = nn.Linear(6, 1)\n\n def forward(self, x):\n x, _ = self.layer1(x)\n s, b, h = x.size()\n x = x.view(-1, h)\n x = self.layer2(x)\n x.view(s, b, -1)\n return x\n\n\nlstm = Lstm().cuda()\noptimizer = torch.optim.Adam(lstm.parameters(), 0.001)\nloss_func = nn.MSELoss().cuda()\nloss_list = []\nfor epoch in range(100):\n print(epoch)\n a = 0\n for step, (b_x, b_y) in enumerate(dataloader):\n # print('b_x:',b_x)\n torch_x = b_x.view(-1, 1, 2)\n torch_y = b_y.view(-1, 1, 1)\n # print('torch_x',torch_x)\n datax = Variable(torch_x).cuda()\n datay = Variable(torch_y).cuda()\n pre = lstm(datax)\n loss = loss_func(pre, datay)\n optimizer.zero_grad()\n loss.backward()\n loss_list.append(loss.data[0])\n optimizer.step()\n if (step % 10 == 0):\n print(step)\n print('loss:', loss)\n\nplt.figure()\nplt.plot(loss_list)\nplt.xlabel(\"step\")\nplt.ylabel(\"loss\")\nplt.figure()\nlstm.eval()\ntorch_testx = torch.from_numpy(test_x.reshape(-1, 1, 2))\nvar_testx = Variable(torch_testx).cuda()\nprediction = lstm(var_testx)\n\nplt.plot(test_y.reshape(-1, 1), color='red', label='real')\nplt.plot(prediction.cpu().data, color='blue', label='pre')\n\nplt.legend(loc='best')\nplt.show()\n","sub_path":"pytorch_step02/RNN_test2.py","file_name":"RNN_test2.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"45873743","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS, cross_origin\nfrom urllib import parse\nimport sys\nimport os\n\n\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D\nfrom tensorflow.keras.layers import Dropout, Flatten\nfrom tensorflow.keras.models import Sequential, model_from_json\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport numpy as np\n\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\n\nbaseDir = os.path.dirname(os.path.abspath(__file__))\njsonPath = os.path.join(baseDir, 'model.json')\nh5Path = os.path.join(baseDir, 'model.h5')\n\ndef saveModel(model):\n global jsonPath\n global h5Path\n \n # 모델 저장\n model_json = model.to_json()\n with open(jsonPath, \"w\") as json_file : \n json_file.write(model_json)\n # 웨이트 저장\n model.save_weights(h5Path)\n \n print(\"Saved model to disk\")\n return True\n\ndef loadModel():\n global h5Path\n global jsonPath\n \n try:\n with open(jsonPath, \"r\") as jsonFile:\n jsonData = jsonFile.read()\n loadedModel = model_from_json(jsonData)\n loadedModel.load_weights(h5Path)\n \n print(\"Loaded model from disk\")\n loadedModel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n print(\"Loaded model compiled\")\n\n return loadedModel\n except Exception as e:\n print(e)\n return None\n\nmodel = loadModel()\nif not model:\n np.random.seed(7)\n\n img_rows = 28\n img_cols = 28\n\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\n input_shape = (img_rows, img_cols, 1)\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n\n x_train = x_train.astype('float32') / 255.\n x_test = x_test.astype('float32') / 255.\n\n print('x_train shape:', x_train.shape)\n print(x_train.shape[0], 'train samples')\n print(x_test.shape[0], 'test samples')\n\n batch_size = 128\n num_classes = 10\n epochs = 12\n\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPool2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(num_classes, activation='softmax'))\n model.summary()\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n hist = model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1, \n validation_data=(x_test, y_test))\n saveModel(model)\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n@app.route('/api/predict', methods=['get'])\n@cross_origin()\ndef hello_world():\n global model\n px = request.args.get('px')\n if not px:\n return jsonify({'status':False})\n l = parse.unquote(px).split(' ')\n l = list(map(lambda x: int(x, 16)/15, l))\n \n img_rows = 28\n img_cols = 28\n l = np.array(l)\n d = l.reshape(1, img_rows, img_cols, 1)\n\n lab = model.predict_classes(d)\n print(lab)\n # lab = model._make_predict_function(d)\n return jsonify({'status':True, 'label':int(lab[0])})\n\nif __name__ == '__main__':\n app.run(port=3002, host='0.0.0.0')\n","sub_path":"portfolio/handwritin/flask/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"103673705","text":"import xml.etree.cElementTree as ct\nxmlele=ct.parse(\"F:/country_data.xml\")\ncountry=ct.Element('country')\ncountry.set('name','China')\nrank=ct.Element('rank')\nrank.text='1'\ncountry.append(rank)\nxmlele.getroot().append(country)\nprint(ct.tostring(xmlele.getroot()).decode())\nxmlele.write('sample.xml')\n","sub_path":"modifyXml.py","file_name":"modifyXml.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"469065490","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport sqlite3\n\nclass Player_Match:\n\n sqlite_var = 0\n theCursor = 0\n\n def clear_entries(self):\n self.Goal_entry.delete(0, \"end\")\n self.Assist_entry.delete(0, \"end\")\n self.Yellow_Card_entry.delete(0, \"end\")\n self.Red_Card_entry.delete(0, \"end\")\n\n def refresh(self):\n self.update_tree()\n self.clear_entries()\n self.search_value.set(\"\")\n\n def search_record(self):\n try:\n self.tree.delete(*self.tree.get_children())\n\n query = \"\"\"SELECT m.Adversary, m.Place, m.Result, m.Date, p.Name, pm.Goal, pm.Assist, pm.Yellow_Card, pm.Red_Card \n FROM Player_Match pm, Players p, Team t, Matches m\n WHERE pm.ID_matches = m.ID_matches and pm.ID_player = p.ID_player and (m.Adversary like ? or m.Place like ? or m.Date like ? or m.Tournament like ? or p.Name like ?)\n ORDER BY pm.ID_matches ASC\"\"\"\n self.theCursor.execute(query, ('%' + self.search_value.get() + '%', '%' + self.search_value.get() + '%', '%' + self.search_value.get() + '%', '%' + self.search_value.get() + '%', '%' + self.search_value.get() + '%'))\n self.result = self.theCursor.fetchall()\n\n length = str(len(self.result))\n if(length == 0):\n messagebox.showinfo('Jogos', 'Não foi possível encontrar um resultado!')\n if(length != '0'):\n i = 0\n\n for row in self.result: \n if(i % 2 == 0):\n self.tree.insert(\"\", tk.END, values=row, tag='1')\n else:\n self.tree.insert(\"\", tk.END, values=row, tag='2')\n i = i + 1\n except:\n print(\"Não foi possível encontrar dados!\")\n\n def update_record(self):\n try:\n query1 = \"SELECT ID_matches, ID_player FROM Matches, Players WHERE Date = ? and Name = ?\"\n self.theCursor.execute(query1, (self.Date_value.get(), self.Name_value.get()))\n res = self.theCursor.fetchall()\n query2 = \"\"\"UPDATE Player_Match \n SET Goal = ?, Assist = ?, Yellow_Card = ?, Red_Card = ? \n WHERE ID_matches = ? and ID_player = ?;\"\"\"\n self.theCursor.execute(query2, (self.Goal_value.get(), self.Assist_value.get(), self.Yellow_Card_value.get(), self.Red_Card_value.get(), res[0][0], res[0][1]))\n print('Dados atualizados!')\n except sqlite3.IntegrityError:\n messagebox.showerror('Jogos', 'Este jogo já se encontra no banco de dados!')\n except:\n print('Não foi possível atualizar os dados!')\n finally:\n if self.search_value.get() == \"\":\n self.update_tree()\n else:\n self.search_record()\n self.sqlite_var.commit()\n \n\n def selectItem(self, event):\n self.curItem = self.tree.item(self.tree.focus())\n print(self.curItem)\n\n self.Goal_value.set(self.curItem['values'][5])\n self.Assist_value.set(self.curItem['values'][6])\n self.Yellow_Card_value.set(self.curItem['values'][7])\n self.Red_Card_value.set(self.curItem['values'][8])\n self.Date_value.set(self.curItem['values'][3])\n self.Name_value.set(self.curItem['values'][4])\n\n def update_tree(self):\n try:\n self.tree.delete(*self.tree.get_children())\n\n self.theCursor.execute(\"\"\"SELECT m.Adversary, m.Place, m.Result, m.Date, p.Name, pm.Goal, pm.Assist, pm.Yellow_Card, pm.Red_Card \n FROM Player_Match pm, Players p, Team t, Matches m\n WHERE pm.ID_matches = m.ID_matches and pm.ID_player = p.ID_player\n ORDER BY pm.ID_matches ASC\"\"\")\n self.rows = self.theCursor.fetchall()\n i = 0\n\n for row in self.rows:\n if(i % 2 == 0):\n self.tree.insert(\"\", tk.END, values=row, tag='1')\n else:\n self.tree.insert(\"\", tk.END, values=row, tag='2')\n i = i + 1\n except:\n print('Não foi possível atualizar a árvore!')\n\n def populate_Database(self):\n \n self.theCursor.execute(\"SELECT ID_matches FROM Matches\")\n result_1 = self.theCursor.fetchall()\n self.theCursor.execute(\"SELECT ID_player FROM Players\")\n result_2 = self.theCursor.fetchall()\n\n for i in result_1:\n for j in result_2:\n self.theCursor.execute(\"SELECT * FROM Player_Match WHERE ID_matches = ? and ID_player = ?\", (i[0], j[0]))\n res = self.theCursor.fetchall()\n if not res:\n self.theCursor.execute(\"INSERT INTO Player_Match (ID_matches, ID_player, Goal, Assist, Yellow_Card, Red_Card) VALUES (?,?,?,?,?,?)\", (i[0], j[0], 0, 0, 0, 0))\n self.sqlite_var.commit()\n\n def setup_db(self):\n try:\n self.sqlite_var = sqlite3.connect('Soccer Team.db')\n self.theCursor = self.sqlite_var.cursor()\n except:\n print('Não foi possível conectar ao banco de dados!')\n \n try:\n self.theCursor.execute(\"CREATE TABLE if not exists Player_Match(ID_player INTEGER NOT NULL, ID_matches INTEGER NOT NULL, Goal INTEGER DEFAULT 0, Assist INTEGER DEFAULT 0, Yellow_Card INTEGER DEFAULT 0, Red_Card INTEGER DEFAULT 0, PRIMARY KEY(ID_player, ID_matches), FOREIGN KEY (ID_player) REFERENCES Players (ID_player), FOREIGN KEY (ID_matches) REFERENCES Matches (ID_matches));\")\n self.populate_Database()\n except:\n print('Não foi possível criar a tabela!')\n finally:\n self.sqlite_var.commit()\n self.update_tree()\n \n def back(self):\n self.pm.destroy()\n\n def __init__(self):\n\n self.pm = tk.Tk()\n self.pm.title('Jogos')\n self.pm.resizable(False, False)\n self.pm.iconbitmap(\"futebol.ico\")\n self.pm.geometry('+350+30')\n self.pm['bg'] = '#4db8ff'\n\n self.Date_value = tk.StringVar()\n self.Name_value = tk.StringVar()\n\n self.Goal = tk.Label(self.pm, text='Gol:', font='Ariel', fg='white', bg='#4db8ff')\n self.Goal.grid(row=0, column=0, columnspan=3, sticky=tk.W, padx=10, pady=10)\n\n self.Goal_value = tk.StringVar(self.pm, value=\"\")\n self.Goal_entry = ttk.Entry(self.pm, font='Ariel, 10', textvariable=self.Goal_value)\n self.Goal_entry.grid(row=0, column=1, sticky=tk.W + tk.E, columnspan=2, padx=10, pady=10)\n\n self.Assist = tk.Label(self.pm, text='Assistência:', font='Ariel', fg='white', bg='#4db8ff')\n self.Assist.grid(row=1, column=0, columnspan=3, sticky=tk.W, padx=10, pady=10)\n\n self.Assist_value = tk.StringVar(self.pm, value=\"\")\n self.Assist_entry = ttk.Entry(self.pm, font='Ariel, 10', textvariable=self.Assist_value)\n self.Assist_entry.grid(row=1, column=1, sticky=tk.W + tk.E, columnspan=2, padx=10, pady=10)\n\n self.Yellow_Card = tk.Label(self.pm, text='Cartão Amarelo:', font='Ariel', fg='white', bg='#4db8ff')\n self.Yellow_Card.grid(row=2, column=0, columnspan=3, sticky=tk.W, padx=10, pady=10)\n\n self.Yellow_Card_value = tk.StringVar(self.pm, value=\"\")\n self.Yellow_Card_entry = ttk.Entry(self.pm, font='Ariel, 10', textvariable=self.Yellow_Card_value)\n self.Yellow_Card_entry.grid(row=2, column=1, sticky=tk.W + tk.E, columnspan=2, padx=10, pady=10)\n\n self.Red_Card = tk.Label(self.pm, text='Cartão Vermelho:', font='Ariel', fg='white', bg='#4db8ff')\n self.Red_Card.grid(row=3, column=0, columnspan=3, sticky=tk.W, padx=10, pady=10) \n\n self.Red_Card_value = tk.StringVar(self.pm, value=\"\")\n self.Red_Card_entry = ttk.Entry(self.pm, font='Ariel, 10', textvariable=self.Red_Card_value)\n self.Red_Card_entry.grid(row=3, column=1, sticky=tk.W + tk.E, columnspan=2, padx=10, pady=10)\n\n self.update_button = ttk.Button(self.pm, text='Atualizar', cursor=\"hand2\", command=self.update_record)\n self.update_button.grid(row=0, column=3, padx=9, sticky=tk.W+tk.E)\n\n self.tree = ttk.Treeview(self.pm, selectmode=\"browse\", column=(\"column1\", \"column2\", \"column3\", \"column4\", \"column5\", \"column6\", \"column7\", \"column8\", \"column9\"), show='headings')\n self.tree.column(\"column1\", width=150, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#1\", text=\"Adversário\")\n self.tree.column(\"column2\", width=150, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#2\", text=\"Local\")\n self.tree.column(\"column3\", width=50, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#3\", text=\"Resultado\")\n self.tree.column(\"column4\", width=80, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#4\", text=\"Data\")\n self.tree.column(\"column5\", width=180, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#5\", text=\"Jogador\")\n self.tree.column(\"column6\", width=50, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#6\", text=\"Gol\")\n self.tree.column(\"column7\", width=50, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#7\", text=\"Ass\")\n self.tree.column(\"column8\", width=50, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#8\", text=\"CA\")\n self.tree.column(\"column9\", width=50, minwidth=100, stretch=tk.NO)\n self.tree.heading(\"#9\", text=\"CV\")\n self.tree.bind(\"\", self.selectItem)\n self.tree.bind(\"\", self.selectItem)\n self.tree.tag_configure('1', background='ivory2')\n self.tree.tag_configure('2', background='ivory2')\n self.tree.grid(row=4, column=0, padx=9, pady=9, sticky=tk.W+tk.E, columnspan=4)\n\n tk.Label(self.pm, text='Pesquisar:', font='Ariel', fg='white', bg='#4db8ff').grid(row=5, column=0, columnspan=2, sticky=tk.E, padx=9, pady=9)\n self.search_value = tk.StringVar(self.pm, value=\"\")\n tk.Entry(self.pm, textvariable= self.search_value).grid(row=5, column=2, sticky=tk.W + tk.E, padx=9, pady=9)\n\n self.search_button = ttk.Button(self.pm, text='Pesquisar', cursor=\"hand2\", command=self.search_record)\n self.search_button.grid(row=5, column=3, padx=9, sticky=tk.W+tk.E) \n\n self.refresh_button = ttk.Button(self.pm, text='Atualizar', cursor=\"hand2\", command=self.refresh) \n self.refresh_button.grid(row=6, column=2, padx=9, pady=9, sticky=tk.W+tk.E)\n\n self.back_button = ttk.Button(self.pm, text='Voltar', cursor=\"hand2\", command=self.back)\n self.back_button.grid(row=6, column=3, padx=9, sticky=tk.W+tk.E)\n\n self.setup_db()\n self.populate_Database()\n self.pm.mainloop()\n\n ","sub_path":"classes/player_match.py","file_name":"player_match.py","file_ext":"py","file_size_in_byte":10867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"268641569","text":"import random\nfrom Square import Square\nclass BigSquare:\n \n def __init__(self, _position):\n self.position = _position\n self.corner = [None, None]\n self.smallSquares = list()\n self.numbers = list()\n self.numbers = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9] #list to ensure no repeats\n\n def returnPosition(self):\n return self.position\n\n def returnCorner(self):\n return self.corner\n\n def returnSmallSquares (self):\n return self.smallSquares\n\n \n\n \n def estCornersBig(self, startCoordinates, boxsize):\n '''\n Determines the coordinate of the first corner based on designated \n number (position) and the length of an individual Sudoku box\n \n startCoordinates = the top-left corner of board\n boxSize = width of a small square\n\n |0|1|2|\n |3|4|5|\n |6|7|8|\n '''\n _corner = [0,0]\n\n # is the 1st bigSquare on board\n if self.position == 0:\n _corner = startCoordinates\n\n # special case if bigSquare on first row \n elif self.position < 3:\n _corner[0] = startCoordinates[0] + (int (self.position % 3) * 3 * boxsize)\n _corner[1] = startCoordinates[1]\n\n # if bigSquare begins on new row\n elif self.position % 3 == 0:\n _corner [0] = startCoordinates[0]\n _corner [1] = startCoordinates[1] + (int (self.position / 3) * 3 * boxsize)\n\n # general formula for the other cases\n else:\n _corner[0] = startCoordinates[0] + ((self.position % 3) * 3 * boxsize) \n _corner[1] = startCoordinates[1] + (int(self.position / 3) * 3 * boxsize)\n\n x,y = _corner #x and y sed as placeholders for elements of determined corner (array)\n _corner_ = (x,y) #elements of array are used to create a tuple\n self.corner = _corner_ #tuple is loaded into corner variable of square\n\n \n\n\n def divide9 (self, boxsize):\n '''\n Creates and adds Square objects to BigSquare's list of squares\n \n boxsize = width of one square on grid\n '''\n for i in range(9):\n self.smallSquares.append( Square (i) )\n x = self.corner[0]\n y = self.corner[1]\n tuple = (x, y)\n self.smallSquares[i].estCorners ( tuple, boxsize )\n\n \n\n def printInfo (self):\n ''' \n Testing method\n\n Prints Squares that compose respective BigSquare\n '''\n for i in self.smallSquares:\n print ( str( i.returnPosition() ) + \": \" + str(i.returnCorner()) )\n\n\n\n def randomizeSquares(self, amount):\n '''\n Randomly selects smaller squares, designates them as programmed,\n and assigns them a random value\n \n amount = a random integer representing amount of Squares\n to change\n '''\n for i in range (amount):\n square= self.smallSquares[random.randint(0,8)] # random square\n\n # ensures that numbers are not repeated\n _max = (len (self.numbers) - 1) \n num = self.numbers.pop ( random.randint (0, _max))\n \n square.setValue (num)\n square.preset()\n \n \n \n\n# Testing\n'''\nbigSquares = list()\nSTARTCOORDINATES = (100, 50)\nBOXSIZE = 30\nfor num in range (9):\n bigSquares.append ( BigSquare (num) )\n bigSquares[num].estCornersBig ( STARTCOORDINATES, BOXSIZE)\n print (\"\\n This is box \" + str(bigSquares[num].retPosition()) + \", whose coordinates equal \" + str(bigSquares[num].retCorner()) )\n bigSquares[num].divide9 (BOXSIZE)\n bigSquares[num].printInfo()\n print()\n'''\n\n\n\n","sub_path":"BigSquare.py","file_name":"BigSquare.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"116057400","text":"import sqlite3\nimport pandas as pd\n\nclass Quering():\n '''\n Quering through rpg_dp.sqlite3\n '''\n\n def __init__(self):\n self.self = self\n\n\n def character_cnt(self):\n '''\n #1 How many total Characters are there?\n '''\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n char_cnt = curs.execute(\"\"\"SELECT COUNT(DISTINCT(character_id))\n FROM charactercreator_character;\"\"\")\n \n char_cnt_result = curs.fetchone()\n print(f'There are total characters', char_cnt_result)\n\n conn.close()\n\n\n def characters_in_subclass(self):\n '''\n #2 How many of each specific subclass?\n '''\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n subclass_char = curs.execute(\n \"\"\"SELECT 'mages', COUNT(*) \n FROM charactercreator_mage \n \n UNION\n \n SELECT 'clerics', COUNT(*) \n FROM charactercreator_cleric\n\n UNION\n\n SELECT 'fighter', COUNT(*) \n FROM charactercreator_fighter\n\n UNION\n\n SELECT 'thieves', COUNT(*) \n FROM charactercreator_thief\n \n UNION\n \n SELECT 'necromancer', COUNT(*)\n FROM charactercreator_necromancer;\"\"\")\n\n subclass_cnt = curs.fetchall()\n print(f'Number of characters in each subclass:\\n', subclass_cnt)\n\n conn.close()\n\n def total_items(self):\n '''\n \"#3 How many total Items?\"\n '''\n\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n items = curs.execute(\"\"\"SELECT COUNT(item_id)\n FROM armory_item\"\"\")\n\n items_total = curs.fetchall()\n\n print(f'Total {items_total[0]}')\n\n conn.close()\n\n def weapons_not_weapons(self):\n '''\n \"#4 How many of the Items are weapons? How many are not?\"\n '''\n conn = sqlite3.connect('rpg_dg.sqlite3')\n curs = conn.cursor()\n weapon_cnt = \"\"\"SELECT COUNT(item_ptr_id)\n FROM armory_weapon\"\"\"\n weapons = curs.fetchone()\n\n not_weapon_cnt = curs.execute(\n \"\"\"SELECT COUNT(item_id)\n FROM armory_item\n WHERE NOT EXISTS \n (SELECT item_ptr_id\n FROM armory_weapon \n WHERE armory_weapon.item_ptr_id = armory_item.item_id;\"\"\")\n not_weapons = curs.fetchone()\n\n print(\"{weapons[0]} weapons and {not_weapons[0]} not weapons.\" )\n\n conn.close()\n\n def items_per_character(self):\n \"\"\"\n #5 How many Items does each character have? \n (Return first 20 rows)\n \"\"\"\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n items_per_char = curs.execute(\"\"\"SELECT character_id, COUNT(item_id)\n FROM charactercreator_character_inventory\n GROUP BY character_id\n LIMIT 20;\"\"\")\n items_char = curs.fetchall()\n print(\"Items per charachter (first 20):\\n\", items_char)\n \n conn.close()\n \n def weapons_per_character(self):\n \"\"\"\n #6 How many Weapons does each character have? \n (Return first 20 rows)\n \"\"\"\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n weapons_each = curs.execute(\"\"\"SELECT COUNT(item_id)\n FROM charactercreator_character_inventory inventory\n JOIN armory_weapon as weapon\n ON weapon.item_ptr_id = inventory.item_id\n GROUP BY character_id;\"\"\")\n \n weapons_per_char = curs.fetchall()\n\n print('Number of weapons per character:\\n', weapons_per_char)\n\n conn.close()\n\n \n def avg_items(self):\n \"\"\"\n #7 On average, how many Items does each Character have?\n \"\"\"\n\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n average_items = curs.execute(\"\"\"SELECT AVG(num_items)\n FROM(SELECT character_id, COUNT(item_id) as num_items\n FROM charactercreator_character_inventory\n GROUP BY character_id) AS grouped;\"\"\")\n\n avg_items_char = curs.fetchall()\n\n print(f'The average number of items per character is {avg_items_char}')\n\n conn.close()\n\n\n def avg_weapons(self):\n \"\"\"\n #8 On average, how many Weapons does each character have\n \"\"\"\n conn = sqlite3.connect('rpg_db.sqlite3')\n curs = conn.cursor()\n\n average_weapons = curs.execute(\"\"\"SELECT AVG(weapon_items)\n FROM(SELECT character_id, COUNT(item_id) as weapon_items\n FROM charactercreator_character_inventory\n WHERE EXISTS \n (SELECT item_ptr_id\n FROM armory_weapon \n WHERE armory_weapon.item_ptr_id = charactercreator_character_inventory.item_id)\n GROUP BY character_id);\"\"\")\n\n avg_weap = curs.fetchall()\n\n print(f'The average number of weapons per character is {avg_weap}')\n\n conn.close()","sub_path":"module1-introduction-to-sql/rpg_queries2.py","file_name":"rpg_queries2.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"98438562","text":"import matplotlib.pyplot as plt\r\nimport numpy as mp\r\nimport copy\r\n\r\n#Функция: проверить одну последовательность является ли симетрической.\r\n#Если она не симмерична, то return [] пустой лист\r\n#Если она симметрична, то return лист построенный всевозможными индексами Центра симметрии\r\n#Внимание: Для правильного 8-угольного, построенного последовательностью 11110000,\r\n# его ось симметрия через ни одной точки не проходит.\r\n# Т.е. при p == 1, программа выходит информацию [] именно <не симметричная посл-ть>\r\n# Тогда в случае size % 2 == 0 && колво единицы % 2 == 0, если при p == 1 выходит информацию <не симметричная посл-ть>\r\n# Не можем сказать \"не симметричая посл-ть\", еще понадобится проверить при p == 0.\r\ndef check_symmetry (arr: list, p: int, size: int):\r\n flag: list = []\r\n i: int = 0\r\n j: int\r\n k: int\r\n l: int\r\n for i in range(0, size, 1):\r\n k = (i + 1) % size\r\n j = (i - p) % size\r\n l = 1\r\n while(l <= (size - 1) / 2):\r\n if(arr[k] != arr[j]):\r\n break\r\n k = (k + 1) % size\r\n j = (j - 1) % size\r\n l = l + 1\r\n if(l > (size - 1) / 2):\r\n flag = flag + [i]\r\n return flag\r\n\r\n#Функция : изобразить график\r\n#строка 55 - 80: изобразить ось симметрии\r\ndef Paint(arr: list, size: int):\r\n i: int\r\n x: list = [0] * (size + 1)\r\n y: list = [0] * (size + 1)\r\n h: float = 2*mp.pi / size\r\n flag: list = check_symmetry(arr,1,size)\r\n\r\n for i in range (0,size + 1,1):\r\n x[i] = mp.cos(i * h + mp.pi / 2)\r\n y[i] = mp.sin(i * h + mp.pi / 2)\r\n plt.plot(x,y,color = \"k\",linestyle = \"--\",linewidth = 0.8)\r\n for i in range (0,size,1):\r\n if(arr[i] == 1):\r\n plt.scatter(x[i],y[i],s = 20,color = 'blue')\r\n else:\r\n plt.scatter(x[i],y[i],s = 20,color = 'red')\r\n x.pop()\r\n y.pop()\r\n\r\n if(flag != []):\r\n if(size % 2 == 1):\r\n for i in range (0,len(flag),1):\r\n plt.plot([x[flag[i]], (x[(flag[i] + size // 2) % size] + x[(flag[i] - size // 2) % size]) / 2],\r\n [y[flag[i]], (y[(flag[i] + size // 2) % size] + y[(flag[i] - size // 2) % size]) / 2], color=\"y\",\r\n linewidth=0.5)\r\n else:\r\n for i in range(0, len(flag), 1):\r\n plt.plot([x[flag[i]], x[(flag[i] + size // 2) % size]], [y[flag[i]], y[(flag[i] + size // 2) % size]],\r\n color=\"y\",linewidth=0.5)\r\n if(arr.count(1) % 2 == 0):\r\n flag = check_symmetry(arr, 0, size)\r\n if (flag != []):\r\n for i in range(0, len(flag), 1):\r\n plt.plot(\r\n [(x[flag[i]] + x[(flag[i] + 1) % size]) / 2, -(x[flag[i]] + x[(flag[i] + 1) % size]) / 2],\r\n [(y[flag[i]] + y[(flag[i] + 1) % size]) / 2, -(y[flag[i]] + y[(flag[i] + 1) % size]) / 2],\r\n color=\"y\", linewidth=0.5)\r\n else:\r\n if(size % 2 == 0 and arr.count(1) % 2 == 0):\r\n flag = check_symmetry(arr, 0, size)\r\n if (flag != []):\r\n for i in range(0, len(flag), 1):\r\n plt.plot([(x[flag[i]] + x[(flag[i] + 1) % size]) / 2, -(x[flag[i]] + x[(flag[i] + 1) % size]) / 2],\r\n [(y[flag[i]] + y[(flag[i] + 1) % size]) / 2, -(y[flag[i]] + y[(flag[i] + 1) % size]) / 2],\r\n color=\"y\",linewidth=0.5)\r\n plt.show()\r\n\r\n# total: массив массивов: напр:[[1,1,0,0],[1,0,1,0]], содержащий всевозможные неповторяющие после-ти.\r\n# Если в total нет текущего массива, то выходим flag = 1 (not in)\r\n# Иначе flag = 0 (in)\r\ndef check (total: list, arr: list, size: int):\r\n flag: int = 1\r\n i: int\r\n j: int\r\n temp : list = [0] * size\r\n for i in range (0,size,1):\r\n for j in range(0,size,1):\r\n temp[j] = arr[(i + j) % size]\r\n if(temp in total):\r\n flag = 0\r\n break\r\n return flag\r\n\r\n\r\n# Алгоритм с возвратом, по-англ: Depth-first search\r\n# void DFS(Vertex v)\r\n# {\r\n# visited[v] = True\r\n# for (каждая соседняя точка w) if(visited[w] == 0) {DFS(W)}\r\n# }\r\n# Перебор всевозможных комбинаций при заданной длине массива и количестве \"1\"\r\ndef Traverse(total: list, arr: list, visited: list, quantity1: int, m: int, size: int):\r\n i: int\r\n for i in range(1,size,1):\r\n if(visited[i] == 0):\r\n visited[i] = 1\r\n arr[i] = 1\r\n if(m == quantity1):\r\n if(check(total,arr,size) == 1):\r\n total.append(copy.deepcopy(arr))\r\n visited[i] = 0\r\n arr[i] = 0\r\n continue\r\n Traverse(total,arr,visited,quantity1,m + 1,size)\r\n arr[i] = 0\r\n visited[i] = 0\r\n\r\ndef mmaaiinn():\r\n f = open('C:/Users/shaoj/PycharmProjects/lab_2/result_lab2.txt', 'w')\r\n n: int = int(input())\r\n k: int = int(input())\r\n if(n <= 2 or 2*k > n or n >= 16):\r\n f.write(\"ERROR: incorrect parameter\")\r\n f.close()\r\n return\r\n f.write(\"n == %d k == %d\\n\" % (n,k))\r\n i: int\r\n j: int\r\n l: int\r\n total: list = []\r\n arr: list = [0]*n\r\n visited: list = [0]*n\r\n arr[0] = 1\r\n visited[0] = 1\r\n temp: list\r\n if(k == 1):\r\n total = [arr]\r\n else:\r\n Traverse(total, arr, visited, k, 2, n)\r\n print(len(total))\r\n for i in range(0, len(total), 1):\r\n temp = check_symmetry(total[i],1,n)\r\n if(temp != []):\r\n if (n % 2 == 1):\r\n f.write(\"%s %d\\n\" % (total[i], len(temp)))\r\n for j in range(0, len(temp), 1):\r\n f.write(\"%d|\" % total[i][(temp[j]) % n])\r\n for l in range(0, (len(total[i]) - 1) // 2, 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\"|\")\r\n for l in range((len(total[i]) - 1) // 2, len(total[i]) - 1, 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\"\\n\")\r\n else:\r\n if(total[i].count(1) % 2 == 0):\r\n f.write(\"%s %d\\n\" % (total[i], len(temp + check_symmetry(total[i], 0, n))))\r\n else:\r\n f.write(\"%s %d\\n\" % (total[i], len(temp)))\r\n\r\n for j in range(0, len(temp), 1):\r\n f.write(\"%d|\" % total[i][(temp[j]) % n])\r\n for l in range(0, len(total[i]) // 2 - 1, 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\"|\")\r\n f.write(\"%d|\" % total[i][(temp[j] + n // 2) % n])\r\n for l in range(len(total[i]) // 2 + 1, len(total[i]), 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l) % n])\r\n f.write(\"\\n\")\r\n\r\n if(total[i].count(1) % 2 == 0):\r\n temp = check_symmetry(total[i], 0, n)\r\n if (temp != []):\r\n for j in range(0, len(temp), 1):\r\n for l in range(0, len(total[i]) // 2, 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\" | \")\r\n for l in range(len(total[i]) // 2, len(total[i]), 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\"\\n\")\r\n else:\r\n if((n % 2 == 0 and total[i].count(1) % 2 == 0) == False):\r\n f.write(\"%s %d\\n\" % (total[i], len(temp)))\r\n else:\r\n temp = check_symmetry(total[i], 0, n)\r\n f.write(\"%s %d\\n\" % (total[i], len(temp)))\r\n if(temp != []):\r\n for j in range(0, len(temp), 1):\r\n for l in range(0, len(total[i]) // 2, 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\" | \")\r\n for l in range(len(total[i]) // 2, len(total[i]), 1):\r\n f.write(\"%d\" % total[i][(temp[j] + l + 1) % n])\r\n f.write(\"\\n\")\r\n f.close()\r\n\r\n\r\nmmaaiinn()\r\n","sub_path":"ShaoTsziatsi/symmetry.py","file_name":"symmetry.py","file_ext":"py","file_size_in_byte":9039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"149708155","text":"class Node:\n # Constructor to create a new node\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\nroot = Node(100)\nroot.left = Node(120)\nroot.right = Node(50)\nroot.right.right = Node(70)\nroot.right.left = Node(160)\nroot.left.left = Node(140)\nroot.left.right = Node(150)\npath = []\nresult = []\nimport copy\ndef findPath(root,key,sum_,path):\n if root == None:\n return\n path.append(root.data)\n if key == sum_+root.data:\n print (\"key found\",path)\n result.append(copy.deepcopy(path))\n path.pop()\n return\n findPath(root.left,key,sum_ + root.data,path)\n findPath(root.right,key,sum_ + root.data,path)\n path.pop()\nfindPath(root,220,0,path)\n","sub_path":"my_question/binary-tree-all-path-to-given-sum.py","file_name":"binary-tree-all-path-to-given-sum.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"180624226","text":"\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^discussions/$', views.homepage, name=\"home\"),\n url(r'^discuss/(?P\\d+)/$', views.DiscussionView.as_view(), name=\"discussion\"),\n url(r'^start-discussion/$', views.StartDiscussionView.as_view(), name=\"start-discussion\"),\n \n \n \n\n url(r'^comments/(?P\\d+)/reply$', views.ReplyToComment.as_view(), name=\"reply_to_comment\"),\n url(r'^comments/(?P\\d+)/edit$', views.EditComment.as_view(), name=\"edit_comment\"),\n\n url(r'^api/posts/(?P\\d+)/upvote$', views.upvote_post, name=\"upvote_post\"),\n url(r'^api/posts/(?P\\d+)/downvote$', views.downvote_post, name=\"downvote_post\"),\n url(r'^api/posts/(?P\\d+)/undovote$', views.undo_vote_on_post, name=\"undo_vote_on_post\"),\n\n url(r'^api/comments/(?P\\d+)/upvote$', views.upvote_comment, name=\"upvote_comment\"),\n url(r'^api/comments/(?P\\d+)/downvote$', views.downvote_comment, name=\"downvote_comment\"),\n url(r'^api/comments/(?P\\d+)/undovote$', views.undo_vote_on_comment, name=\"undo_vote_on_comment\"),\n \n]","sub_path":"discussions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"147172188","text":"#\n# Spec2Vec\n#\n# Copyright 2019 Netherlands eScience Center\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport logging\nfrom pprint import pprint \nimport gensim \nfrom gensim import corpora\nfrom gensim import models\nfrom gensim.test.utils import get_tmpfile\nfrom gensim.models.callbacks import CallbackAny2Vec\n\n#from scipy import spatial\nfrom sklearn.decomposition import PCA\n\n# Imports from Spec2Vec functions\nimport helper_functions as functions\n\n \nclass EpochLogger(CallbackAny2Vec):\n '''Callback to log information about training progress.\n Used to keep track of gensim model training (word2vec, lda...)'''\n def __init__(self, num_of_epochs):\n self.epoch = 0\n self.num_of_epochs = num_of_epochs\n def on_epoch_end(self, model):\n print('\\r', 'Epoch ', (self.epoch+1), ' of ', self.num_of_epochs, '.' , end=\"\")\n self.epoch += 1\n\n\nclass SimilarityMeasures():\n \"\"\" Class to run different similarity measure on sentence-like data.\n Words can be representing all kind of things (Pfam domains for proteins, peaks for spectra etc.).\n Documents lists of words.\n \n Similarity measuring methods:\n 1) Low-dimensional document vector similarity (e.g. cosine similarity)\n a) Word2Vec based centroid vector (tfidf weighted or not weighted)\n b) PCA\n 2) Topic modeling:\n a) LDA\n b) LSI\n \"\"\"\n \n def __init__(self, initial_documents):\n self.initial_documents = initial_documents\n self.corpus = []\n self.dictionary = []\n self.bow_corpus = []\n self.stopwords = []\n self.X_data = None\n \n # Trained models\n self.model_word2vec = None\n self.model_lda = None\n self.model_lsi = None\n self.index_lda = None\n self.index_lsi = None\n self.tfidf = None\n self.vectors_centroid = []\n self.vectors_pca = []\n \n # Listed similarities\n self.list_similars_ctr = None\n self.list_similars_ctr_idx = None\n self.list_similars_pca = None\n self.list_similars_pca_idx = None\n self.list_similars_lda = None\n self.list_similars_lda_idx = None\n self.list_similars_lsi = None\n self.list_similars_lsi_idx = None\n\n\n def preprocess_documents(self, max_fraction, min_frequency, \n remove_stopwords = None, create_stopwords = False):\n \"\"\" Preprocess 'documents'\n \n Obvious steps: \n --> in 'helper_functions.preprocess_document'\n - Take all words that occur at least (min_frequency =) 2 times.\n - Lower case\n \n Calculate word frequency\n --> Words that occur more than max_fraction will become stopwords (words with no or little discriminative power)\n \n Args:\n --------\n max_fraction: float\n Gives maximum fraction of documents that may contain a certain word.\n min_frequency: int\n Words that occur less frequently will be ignored.\n remove_stopwords: list, None\n Give list of stopwords if they should be removed. Default is None.\n create_stopwords: bool\n if True: Words that are more common then max_fraction will be added to stopwords.\n \"\"\"\n \n if max_fraction <= 0 or max_fraction > 1:\n print(\"max_fraction should be value > 0 and <= 1.\")\n \n # Preprocess documents (all lower letters, every word exists at least 2 times)\n print(\"Preprocess documents...\")\n if remove_stopwords is None:\n self.corpus, frequency = functions.preprocess_document(self.initial_documents, \n stopwords = [], min_frequency = min_frequency)\n else:\n self.corpus, frequency = functions.preprocess_document(self.initial_documents, \n stopwords = remove_stopwords, min_frequency = min_frequency) \n \n # Create dictionary (or \"vocabulary\") containting all unique words from documents\n self.dictionary = corpora.Dictionary(self.corpus)\n \n if create_stopwords:\n # Calculate word frequency to determine stopwords\n print(\"Calculate inverse document frequency for entire dictionary.\")\n documents_size = len(self.corpus)\n self.idf_scores = functions.ifd_scores(self.dictionary, self.corpus)\n \n # Words that appear too frequently (fraction>max_fration) become stopwords\n self.stopwords = self.idf_scores[\"word\"][self.idf_scores[\"word count\"] > documents_size*max_fraction]\n \n print(len(self.stopwords), \" stopwords were selected from a total of \", \n len(self.dictionary), \" words in the entire corpus.\")\n \n # Create corpus, dictionary, and BOW corpus\n self.corpus, frequency = functions.preprocess_document(self.corpus, self.stopwords, min_frequency = min_frequency)\n \n self.bow_corpus = [self.dictionary.doc2bow(text) for text in self.corpus]\n\n\n## ------------------------------------------------------------------------------\n## ---------------------- Model building & training ----------------------------\n## ------------------------------------------------------------------------------\n \n def build_model_word2vec(self, file_model_word2vec, size=100, \n window=50, min_count=1, workers=4, \n iter=100, use_stored_model=True):\n \"\"\" Build Word2Vec model (using gensim)\n \n Args:\n --------\n file_model_word2vec: str,\n Filename to save model (or load model if it exists under this name).\n size: int,\n Dimensions of word vectors (default = 100) \n window: int,\n Window size for context words (small for local context, \n larger for global context, default = 50)\n min_count: int,\n Only consider words that occur at least min_count times in the corpus (default =1).\n workers: int,\n Number of threads to run the training on (should not be more than number of cores/threads, default = 4).\n iter: int,\n Number of training iterations (default=100). \n use_stored_model: bool,\n Load stored model if True, else train new model.\n \"\"\"\n \n epoch_logger = EpochLogger(iter)\n\n # Check if model already exists and should be loaded\n if os.path.isfile(file_model_word2vec) and use_stored_model: \n print(\"Load stored word2vec model ...\")\n self.model_word2vec = gensim.models.Word2Vec.load(file_model_word2vec)\n else:\n if use_stored_model:\n print(\"Stored word2vec model not found!\")\n \n print(\"Calculating new word2vec model...\")\n \n # Set up GENSIM logging\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.WARNING)\n # Train word2vec model\n self.model_word2vec = gensim.models.Word2Vec(self.corpus, size=size,\n window=window, min_count=min_count, \n workers=workers, iter=iter,\n seed=42, callbacks=[epoch_logger])\n \n # Save model\n self.model_word2vec.save(file_model_word2vec) \n \n \n def build_model_lda(self, file_model_lda, num_of_topics=100, num_pass=4, \n num_iter=100, use_stored_model=True):\n \"\"\" Build LDA model (using gensim).\n \n Args:\n --------\n file_model_lda: str,\n Filename to save model (or load model if it exists under this name).\n num_of_topics: int,\n Number of topics to sort feature into (default = 100).\n num_pass: int,\n Number of passes through the corpus during training.\n num_iter: int,\n Number of training iterations (default=100). \n use_stored_model: bool,\n Load stored model if True, else train new model.\n \"\"\"\n \n # Check if model already exists and should be loaded\n if os.path.isfile(file_model_lda) and use_stored_model: \n print(\"Load stored LDA model ...\")\n self.model_lda = gensim.models.LdaModel.load(file_model_lda)\n else:\n if use_stored_model:\n print(\"Stored LDA model not found!\")\n print(\"Calculating new LDA model...\")\n self.model_lda = gensim.models.LdaModel(self.bow_corpus, id2word=self.dictionary, \n num_topics=num_of_topics, passes=num_pass, iterations=num_iter) \n \n # Save model\n self.model_lda.save(file_model_lda)\n \n # Output the Keyword in the 10 topics\n pprint(\"Keyword in the 10 topics\")\n pprint(self.model_lda.print_topics())\n \n \n def build_model_lsi(self, file_model_lsi, num_of_topics=100, \n num_iter=10, use_stored_model=True):\n \"\"\" Build LSI model (using gensim).\n \n Args:\n --------\n file_model_lsi: str,\n Filename to save model (or load model if it exists under this name).\n num_of_topics: int,\n Number of topics to sort feature into (default = 100).\n num_iter: int,\n Number of training iterations (default=100). \n use_stored_model: bool,\n Load stored model if True, else train new model.\n \"\"\"\n \n # Check if model already exists and should be loaded\n if os.path.isfile(file_model_lsi) and use_stored_model: \n print(\"Load stored LSI model ...\")\n self.model_lsi = gensim.models.LsiModel.load(file_model_lsi)\n else:\n if use_stored_model:\n print(\"Stored LSI model not found!\")\n print(\"Calculating new LSI model...\")\n self.model_lsi = gensim.models.LsiModel(self.bow_corpus, \n id2word=self.dictionary, \n power_iters=num_iter,\n num_topics=num_of_topics) \n \n # Save model\n self.model_lsi.save(file_model_lsi)\n\n \n## ------------------------------------------------------------------------------\n## -------------------- Calculate document vectors ------------------------------\n## ------------------------------------------------------------------------------\n \n def get_vectors_centroid(self, method = 'update', \n extra_weights = None, \n tfidf_weighted=True, \n weight_method = 'sqrt', \n tfidf_model = None,\n extra_epochs = 10):\n \"\"\" Calculate centroid vectors for all documents\n \n Individual word vectors are weighted using tfidf (unless weighted=False).\n \n Args:\n --------\n method: str\n Which method to use if not all words are present in trained model.\n 'update': word2vec model will be updated by additional training of the model.\n 'ignore': will ignore all 'words' not present in the pre-trained model.\n TODO 'substitute\": will look to replace missing words with closest matches?\n extra_weights: list\n List of extra weights for add documents (and every word). Set to \"False\" if not used.\n tfidf_weighted: bool\n True, False\n weight_method: str\n Select method for how to weigh the extra_weights...\n 'sqrt' - weight word vectors by sqrt or extra_weights\n None\n tfidf_model: str\n Give filename if pre-defined tfidf model should be used. Otherwise set to None.\n extra_epochs: int\n Number of extra epochs to train IF method is 'update' and missing words are detected.\n \"\"\"\n # TODO maybe move the update section to the build_model function?\n \n # Check if everything is there:\n # 1) Check if model and bow-corpus are present\n if self.model_word2vec is None:\n print(\"Word2vec model first needs to be load or made (self.build_model_word2vec).\")\n if len(self.bow_corpus) == 0:\n print(\"BOW corpus has not been calculated yet (bow_corpus).\")\n \n # 2) Check if all words are included in trained word2vec model\n dictionary = [self.dictionary[x] for x in self.dictionary]\n test_vocab = []\n for i, word in enumerate(dictionary): \n if word not in self.model_word2vec.wv.vocab:\n test_vocab.append((i, word))\n \n if len(test_vocab) > 0:\n print(\"Not all 'words' of the given documents are present in the trained word2vec model!\")\n print(len(test_vocab), \" out of \", len(self.dictionary), \" 'words' were not found in the word2vec model.\")\n if method == 'update':\n print(\"The word2vec model will hence be updated by additional training.\")\n self.model_word2vec.build_vocab(self.corpus, update=True)\n self.model_word2vec.train(self.corpus, total_examples=len(self.corpus), epochs = extra_epochs)\n self.model_word2vec.save('newmodel')\n \n elif method == 'ignore':\n print(\"'Words'missing in the pretrained word2vec model will be ignored.\")\n \n _, missing_vocab = zip(*test_vocab)\n print(\"Removing missing 'words' from corpus...\")\n # Update corpus and BOW-corpus\n self.corpus = [[word for word in document if word not in missing_vocab] for document in self.corpus]\n self.bow_corpus = [self.dictionary.doc2bow(text) for text in self.corpus]\n # TODO: add check with word intensities \n else:\n print(\"Given method how do deal with missing words could not be found.\")\n else:\n print(\"All 'words' of the given documents were found in the trained word2vec model.\")\n \n if tfidf_weighted is True:\n if tfidf_model is not None:\n self.tfidf = models.TfidfModel.load(tfidf_model)\n print(\"Tfidf model found and loaded.\")\n else:\n if self.tfidf is None:\n self.tfidf = models.TfidfModel(self.bow_corpus)\n print(\"No tfidf model found.\")\n else:\n print(\"Using present tfidf model.\")\n \n \n vector_size = self.model_word2vec.wv.vector_size\n vectors_centroid = []\n \n for i in range(len(self.bow_corpus)):\n if (i+1) % 10 == 0 or i == len(self.bow_corpus)-1: # show progress\n print('\\r', ' Calculated centroid vectors for ', i+1, ' of ', len(self.bow_corpus), ' documents.', end=\"\")\n \n document = [self.dictionary[x[0]] for x in self.bow_corpus[i]]\n if extra_weights is not None:\n document_weight = [extra_weights[i][self.initial_documents[i].index(self.dictionary[x[0]])] for x in self.bow_corpus[i]]\n document_weight = np.array(document_weight)/np.max(document_weight) # normalize\n if len(document_weight) == 0:\n print(\"Something might have gone wrong with: \", i)\n np.ones((len(document)))\n elif weight_method == 'sqrt':\n document_weight = np.sqrt(document_weight) # idea: take sqrt to make huge intensity differences less severe\n elif weight_method is None:\n pass\n else:\n print(\"Unkown weight adding method.\")\n else:\n document_weight = np.ones((len(document)))\n if len(document) > 0:\n term1 = self.model_word2vec.wv[document]\n if tfidf_weighted:\n term2 = np.array(list(zip(*self.tfidf[self.bow_corpus[i]]))[1])\n else:\n term2 = np.ones((len(document)))\n \n term1 = term1 * np.tile(document_weight, (vector_size,1)).T\n weighted_docvector = np.sum((term1.T * term2).T, axis=0)\n else:\n weighted_docvector = np.zeros((self.model_word2vec.vector_size))\n vectors_centroid.append(weighted_docvector)\n \n self.vectors_centroid = np.array(vectors_centroid) \n# # TODO add save and load options\n\n \n def get_vectors_pca(self, dimension=100):\n \"\"\" Calculate PCA vectors for all documents.\n \n Args:\n -------\n dimension: int\n Dimension of reduced PCA vectors. Default is 100. \n \"\"\"\n pca = PCA(n_components=dimension)\n \n input_dim = len(self.dictionary)\n corpus_dim = len(self.corpus)\n \n # See if there is one-hot encoded vectors (X_data)\n if self.X_data is None:\n # Transform data to be used as input for Keras model\n self.X_data = np.zeros((corpus_dim, input_dim))\n \n for i, bow_doc in enumerate(self.bow_corpus[:corpus_dim]):\n word_vector_bow = np.array([x[0] for x in bow_doc]).astype(int)\n word_vector_count = np.array([x[1] for x in bow_doc]).astype(int)\n self.X_data[i,:] = functions.full_wv(input_dim, word_vector_bow, word_vector_count)\n\n self.vectors_pca = pca.fit_transform(self.X_data)\n\n\n## ------------------------------------------------------------------------------\n## -------------------- Calculate similarities ----------------------------------\n## ------------------------------------------------------------------------------\n \n def get_centroid_similarity(self, num_hits=25, method='cosine'):\n \"\"\" Calculate centroid similarities(all-versus-all --> matrix)\n \n Args:\n -------\n num_centroid_hits: int\n Function will store the num_centroid_hits closest matches. Default is 25. \n method: str\n See scipy spatial.distance.cdist for options. Default is 'cosine'.\n \n \"\"\"\n list_similars_idx, list_similars, mean_similarity = functions.calculate_similarities(self.vectors_centroid, \n num_hits, method = method)\n print(\"Calculated distances between \", list_similars.shape[0], \" documents.\")\n self.list_similars_ctr_idx = list_similars_idx\n self.list_similars_ctr = list_similars\n\n\n def get_pca_similarity(self, num_hits=25, method='cosine'):\n \"\"\" Calculate PCA similarities(all-versus-all --> matrix)\n \n Args:\n -------\n num_centroid_hits: int\n Function will store the num_centroid_hits closest matches. Default is 25. \n method: str\n See scipy spatial.distance.cdist for options. Default is 'cosine'.\n \n \"\"\"\n list_similars_idx, list_similars, mean_similarity = functions.calculate_similarities(self.vectors_pca, \n num_hits, method = method)\n \n self.list_similars_pca_idx = list_similars_idx\n self.list_similars_pca = list_similars\n \n \n def get_lda_similarity(self, num_hits=25):\n \"\"\" Calculate LDA topic based similarities (all-versus-all)\n \n Args:\n -------\n num_centroid_hits: int\n Function will store the num_centroid_hits closest matches. Default is 25. \n \n \"\"\"\n\n # Now using faster gensim way (also not requiering to load everything into memory at once)\n index_tmpfile = get_tmpfile(\"index\")\n index = gensim.similarities.Similarity(index_tmpfile, self.model_lda[self.bow_corpus], \n num_features=len(self.dictionary)) # build the index\n Cdist = np.zeros((len(self.corpus), len(self.corpus)))\n for i, similarities in enumerate(index): # yield similarities of all indexed documents\n Cdist[:,i] = similarities\n \n# Cdist = 1 - Cdist # switch from similarity to distance\n\n # Create numpy arrays to store similarities\n list_similars_idx = np.zeros((Cdist.shape[0],num_hits), dtype=int)\n list_similars = np.zeros((Cdist.shape[0],num_hits))\n \n for i in range(Cdist.shape[0]):\n list_similars_idx[i,:] = Cdist[i,:].argsort()[-num_hits:][::-1]\n list_similars[i,:] = Cdist[i, list_similars_idx[i,:]]\n\n self.list_similars_lda_idx = list_similars_idx\n self.list_similars_lda = list_similars\n \n \n def get_lsi_similarity(self, num_hits=25):\n \"\"\" Calculate LSI based similarities (all-versus-all)\n \n Args:\n -------\n num_centroid_hits: int\n Function will store the num_centroid_hits closest matches. Default is 25. \n \n \"\"\"\n\n # Now using faster gensim way (also not requiering to load everything into memory at once)\n index_tmpfile = get_tmpfile(\"index\")\n index = gensim.similarities.Similarity(index_tmpfile, self.model_lsi[self.bow_corpus], \n num_features=len(self.dictionary)) # build the index\n Cdist = np.zeros((len(self.corpus), len(self.corpus)))\n for i, similarities in enumerate(index): # yield similarities of all indexed documents\n Cdist[:,i] = similarities\n \n# Cdist = 1 - Cdist # switch from similarity to distance\n\n # Create numpy arrays to store distances\n list_similars_idx = np.zeros((Cdist.shape[0],num_hits), dtype=int)\n list_similars = np.zeros((Cdist.shape[0],num_hits))\n \n for i in range(Cdist.shape[0]):\n list_similars_idx[i,:] = Cdist[i,:].argsort()[-num_hits:][::-1]\n list_similars[i,:] = Cdist[i, list_similars_idx[i,:]]\n\n self.list_similars_lsi_idx = list_similars_idx\n self.list_similars_lsi = list_similars","sub_path":"code/similarity_measure.py","file_name":"similarity_measure.py","file_ext":"py","file_size_in_byte":23251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"129443981","text":"# Define a daysBetweenDates procedure that would produce the\n# correct output if there was a correct nextDay procedure.\n#\n# Note that this will NOT produce correct outputs yet, since\n# our nextDay procedure assumes all months have 30 days\n# (hence a year is 360 days, instead of 365).\n#\n\ndef nextDay(year, month, day):\n \"\"\"Simple version: assume every month has 30 days\"\"\"\n _next_day = (year, month, day+1)\n if day == 30:\n _next_day = (year, month+1, 1) if month < 12 else (year+1, 1, 1)\n return _next_day\n\ndef dateIsBefore(year1, month1, day1, year2, month2, day2):\n if year1 < year2:\n return True\n elif year1 == year2:\n if month1 < month2:\n return True\n elif month1 == month2 and day1 < day2:\n return True\n else:\n return False\n return False\n\n\ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\n \"\"\"Returns the number of days between year1/month1/day1\n and year2/month2/day2. Assumes inputs are valid dates\n in Gregorian calendar, and the first date is not after\n the second.\"\"\"\n\n days = 0\n while dateIsBefore(year1, month1, day1, year2, month2, day2):\n year1, month1, day1 = nextDay(year1, month1, day1)\n days += 1\n return days\n\ndef test():\n\n test_cases = [((2012,9,30,2012,10,30),30),\n ((2012,1,1,2013,1,1),360),\n ((2012,9,1,2012,9,4),3)]\n\n for (args, answer) in test_cases:\n result = daysBetweenDates(*args)\n if result != answer:\n print(\"Test with data:\", args, \"failed\")\n else:\n print(\"Test case passed!\")\n\nprint(\"Holas 4\")\nprint(daysBetweenDates(2012,9,30,2012,10,30))","sub_path":"2-how-to-solve-problems.py","file_name":"2-how-to-solve-problems.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"315249349","text":"\"\"\"Return prefixes dictionary from reading prefixes file.\"\"\"\n\nimport os\nfrom pathlib import Path\nimport pytest\nfrom csv2shex.constants import PREFIXFILE_NAME\nfrom csv2shex.prefixes import get_prefixes\n\n\nPREFIXFILE_CONTENT = (\n \"prefixes:\\n\"\n \" dc: http://purl.org/dc/elements/1.1/\\n\"\n \" dcterms: http://purl.org/dc/terms/\\n\"\n)\n\nPREFIXES_PYOBJ = {\n \"prefixes\": {\n \"dc\": \"http://purl.org/dc/elements/1.1/\",\n \"dcterms\": \"http://purl.org/dc/terms/\",\n }\n}\n\n\ndef test_get_prefixes(tmp_path):\n \"\"\"Return dictionary of configuration settings from YAML file.\"\"\"\n os.chdir(tmp_path)\n Path(PREFIXFILE_NAME).write_text(PREFIXFILE_CONTENT)\n assert get_prefixes() == PREFIXES_PYOBJ\n\n\ndef test_get_prefixes_from_prefixfile_with_lines_commented_out(tmp_path):\n \"\"\"Return configuration dictionary even if some lines are commented out.\"\"\"\n os.chdir(tmp_path)\n prefixfile_content = (\n \"prefixes:\\n\"\n \"# dc: http://purl.org/dc/elements/1.1/\\n\"\n \" dcterms: http://purl.org/dc/terms/\\n\"\n )\n Path(PREFIXFILE_NAME).write_text(prefixfile_content)\n expected = {\"prefixes\": {\"dcterms\": \"http://purl.org/dc/terms/\"}}\n assert get_prefixes() == expected\n\n\ndef test_exit_if_prefixfile_has_bad_yaml(tmp_path):\n \"\"\"Raise exception if config file has bad YAML.\"\"\"\n os.chdir(tmp_path)\n prefixfile_content = \"DELIBE\\nRATELY BAD: -: ^^YAML CONTENT^^\\n\"\n Path(PREFIXFILE_NAME).write_text(prefixfile_content)\n with pytest.raises(SystemExit):\n get_prefixes()\n","sub_path":"tests/test_prefixes_get_prefixes.py","file_name":"test_prefixes_get_prefixes.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"606309020","text":"\nimport json\nimport pandas as pd\nimport os\nimport cv2\n\nfilename=[]\nwidth=[]\t\nheight=[]\t\nClass=[]\t\nxmin=[]\t\nymin=[]\nxmax=[]\nymax=[]\na=[]\nfile_number=0\n#classes=['bus','light','traffic_sign','person','bike','truck','motor','car','train','Rider']\nclasses=['bus','light','traffic light','person','bike','truck','motor','car','train','Rider',\"traffic sign\"]\nbblabel=[]\nloop=0\njason_path=\"/home/mayank-s/PycharmProjects/Datasets/Berkely_DeepDrive/labels/100k/train\"\nimage_path=\"/home/mayank-s/PycharmProjects/Datasets/Berkely_DeepDrive/bdd100k/images/100k/train\"\n\nfor i in os.listdir(image_path):\n # if loop > 5:\n # break\n image_name=i\n dat=image_name.split(\".\")[0]\n filename=os.path.join(jason_path, dat+\".json\")\n Image_com_path = os.path.join(image_path, image_name)\n try:\n # filename=jason_path+\n # if image_name.split('.')==k.split('.'):\n my_image = cv2.imread(Image_com_path, 1)\n\n data=open(filename,'r')\n data1 = data.read()\n data.close()\n Json = json.loads(data1)\n # filename.append(Json['name'])\n # for obj in root.iter('object'):\n for ki in Json['frames'][0]['objects']:\n loop+=1\n # print(\"count run\", loop)\n object_name=ki['category']\n if object_name in classes:\n # print(ki.box2d.category)\n xmin=int(ki['box2d']['x1'])\n xmax=int(ki['box2d']['x2'])\n ymin=int(ki['box2d']['y1'])\n ymax=int(ki['box2d']['y2'])\n width=my_image.shape[0]\n height=my_image.shape[1]\n # coordinate = [xmin, ymin, xmax, ymax, class_num]\n data_label = [dat, width, height, object_name, xmin, ymin, xmax, ymax]\n bblabel.append(data_label)\n except IOError:\n print(\"error at loop:{lp} and image:{dt}\".format(lp=loop,dt=dat))\n print('error1')\n except:\n print(\"error at loop:{lp} and image:{dt}\".format(lp=loop, dt=dat))\n print('error2')\n # print('ERROR...object detecion failed for Filename: {fn} , Check file type '.format(fn=filename), '\\n')\n else:\n print(\"successfull for \", dat)\n\n\n ''' print(len(Json['frames'][0]['objects']))\n length_Variable=len(Json['frames'][0]['objects'])\n for z in range(length_Variable):\n for j in classes:\n if j==Json['frames'][0]['objects'][z]['category']:\n Class.append(Json['frames'][0]['objects'][z]['category'])\n xmin.append(Json['frames'][0]['objects'][z]['box2d']['x1'])\n xmax.append(Json['frames'][0]['objects'][z]['box2d']['x2'])\n ymin.append(Json['frames'][0]['objects'][z]['box2d']['y1'])\n ymax.append(Json['frames'][0]['objects'][z]['box2d']['y2'])\n for s in range(len(Class)):\n b=[filename[file_number]+'.jpg',Class[s],xmin[s],xmax[s],ymin[s],ymax[s]]\n a.append(b)\n else:\n pass\n file_number=file_number+1'''\ncolumns=['filename','Class','xmin','xmax','ymin','ymax']\n\n# pd1=pd.DataFrame(a,columns=columns)\n# df=pd.DataFrame(bblabel)\n# df.to_csv('out.csv')\n# pd1.to_csv('output_bb.csv')\n\n\ndf=pd.DataFrame(bblabel,columns=columns)\ndf.to_csv('output_Train.csv')\n","sub_path":"Deep learning/Load Datasets/json_to_csv.py","file_name":"json_to_csv.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"59369694","text":"from utilities import make_request\nfrom datetime import datetime\nimport pyrebase\nconfig = {\n \"apiKey\": \"AIzaSyDi0s4cV7eeultcnZTEkyQp7FchO5L6TGo\",\n \"authDomain\": \"payment-gateway-f5a88.firebaseapp.com\",\n \"databaseURL\": \"https://payment-gateway-f5a88-default-rtdb.asia-southeast1.firebasedatabase.app\",\n \"projectId\": \"payment-gateway-f5a88\",\n \"storageBucket\": \"payment-gateway-f5a88.appspot.com\",\n \"messagingSenderId\": \"413267159482\",\n \"appId\": \"1:413267159482:web:69047cd2cd5bddae4ad583\"\n}\nfirebase=pyrebase.initialize_app(config)\ndb=firebase.database()\ndef walletDeposit(amount,country,currency,customer_id):\n checkout_page={\n \"amount\": amount,\n \"complete_payment_url\": \"http://mediapipe-com.stackstaging.com/\",\n 'complete_checkout_url': \"http://mediapipe-com.stackstaging.com/\",\n \"country\": country,\n \"currency\": currency,\n \"customer\": customer_id,\n \"error_payment_url\": \"http://www.rapyd.net\",\n \"merchant_reference_id\": \"950ae8c6-79\",\n \"language\": \"en\",\n \"metadata\": {\n \"merchant_defined\": True\n },\n \"payment_method_type_categories\": [\n \"bank_redirect\",\n \"cash\",\n \"card\",\n \"ewallet\",\n \"bank_transfer\"\n ]\n }\n result = make_request(method='post', path='/v1/checkout', body=checkout_page)\n payment_time = datetime.fromtimestamp(result['data']['timestamp']).ctime().split()\n token = result['data']['id']\n current_wallet_balance=db.child(\"customers/\"+customer_id+\"/wallet/balance\").get().val()\n current_wallet_balance=int(current_wallet_balance)\n amount=int(amount)\n wallet_balance=current_wallet_balance+amount\n db.child(\"customers/\"+customer_id+\"/wallet\").update({\"balance\":wallet_balance})\n data={\n \"amount\":str(amount)+currency,\n \"action\":\"Deposited to Wallet\",\n \"id\":token,\n \"status\":\"Completed\",\n \"date_day\":payment_time[2],\n \"date_month\":payment_time[1],\n \"date_year\":payment_time[0]\n }\n db.child(\"customers\").child(customer_id).child('transactions').child(token).update(data)\n return result[\"data\"][\"redirect_url\"]","sub_path":"wallet_deposit.py","file_name":"wallet_deposit.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"255234925","text":"import random\nimport arcade\nimport math\n\n# --- Constants ---\nSPRITE_SCALING_PLAYER = 0.5\nSPRITE_SCALING_COIN = 0.2\nSPRITE_SCALING_GEM = 0.2\nCOIN_COUNT = 50\nGEM_COUNT = 20\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nMOVEMENT_SPEED = 5\n\n\nclass SilverCoin(arcade.Sprite):\n \"\"\" Creating our coin \"\"\"\n\n def __init__(self, filename, sprite_scaling):\n super().__init__(filename, sprite_scaling)\n\n self.change_x = 0\n self.change_y = 0\n\n def update(self):\n\n \"\"\" Move the coin \"\"\"\n self.center_x += self.change_x\n self.center_y += self.change_y\n\n if self.left < 0:\n self.change_x *= -1\n\n if self.right > SCREEN_WIDTH:\n self.change_x *= -1\n\n if self.bottom < 0:\n self.change_y *= -1\n\n if self.top > SCREEN_HEIGHT:\n self.change_y *= -1\n\n\nclass RedGem(arcade.Sprite):\n \"\"\"Creating the Evil Gem\"\"\"\n\n def __init__(self, filename, sprite_scaling):\n super().__init__(filename, sprite_scaling)\n\n self.circle_angle = 1\n\n self.circle_radius = random.randrange(1, 200)\n\n self.circle_speed = .05\n\n self.circle_center_x = random.randrange(0, SCREEN_WIDTH)\n self.circle_center_y = random.randrange(0, SCREEN_HEIGHT)\n\n def update(self):\n self.center_x = self.circle_radius * math.sin(self.circle_angle) + self.circle_center_x\n self.center_y = self.circle_radius * math.cos(self.circle_angle) + self.circle_center_y\n\n self.circle_angle += self.circle_speed\n\n\nclass MyGame(arcade.Window):\n \"\"\" Our custom Window Class\"\"\"\n\n def __init__(self):\n \"\"\" Initializer \"\"\"\n # Call the parent class initializer\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, \"Sprite Fright\")\n\n # Variables that will hold sprite lists\n self.player_list = None\n self.coin_list = None\n self.gem_list = None\n\n # Set up the player info\n self.player_sprite = None\n self.score = 0\n\n # Don't show the mouse cursor\n self.set_mouse_visible(False)\n\n # Is the game over?\n self.game_over = False\n self.length_of_play = 0\n\n arcade.set_background_color(arcade.color.AMAZON)\n\n # Loading up our sounds\n self.bad_sound = arcade.load_sound(\"error3.wav\")\n self.good_sound = arcade.load_sound(\"coin2.wav\")\n\n def setup(self):\n \"\"\" Set up the game and initialize the variables. \"\"\"\n\n # Sprite lists\n self.player_list = arcade.SpriteList()\n self.coin_list = arcade.SpriteList()\n self.gem_list = arcade.SpriteList()\n\n # Score\n self.score = 0\n\n # Set up the player\n # Character image from kenney.nl\n self.player_sprite = arcade.Sprite(\"player_stand.png\", SPRITE_SCALING_PLAYER)\n self.player_sprite.center_x = 50\n self.player_sprite.center_y = 50\n self.player_list.append(self.player_sprite)\n\n # Create the coins\n for i in range(COIN_COUNT):\n # Create the coin instance\n # Coin image from kenney.nl\n coin = SilverCoin(\"coinSilver.png\", SPRITE_SCALING_COIN)\n\n # Position the coin\n coin.center_x = random.randrange(SCREEN_WIDTH)\n coin.center_y = random.randrange(SCREEN_HEIGHT)\n\n coin.change_x = random.randrange(-4, 5)\n coin.change_y = random.randrange(-4, 5)\n\n # Add the coin to the lists\n self.coin_list.append(coin)\n\n # Create the Gems\n for i in range(GEM_COUNT):\n # Gem image from Kenny.nl\n gem = RedGem(\"gemRed.png\", SPRITE_SCALING_GEM)\n\n # Position the Gems\n gem.center_x = random.randrange(SCREEN_WIDTH)\n gem.center_y = random.randrange(SCREEN_HEIGHT)\n\n gem.change_x = random.randrange(-5, 6)\n gem.change_y = random.randrange(-5, 6)\n\n # Add the coin to the lists\n self.gem_list.append(gem)\n\n def on_draw(self):\n \"\"\" Draw everything \"\"\"\n arcade.start_render()\n self.coin_list.draw()\n self.gem_list.draw()\n self.player_list.draw()\n\n # Put the text on the screen.\n output = f\"Score: {self.score}\"\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 24)\n\n if self.game_over is True:\n arcade.draw_text(\"Game Over\\n Thanks for playing!\", SCREEN_WIDTH / 3, SCREEN_HEIGHT / 2,\n arcade.color.WHITE, 36)\n\n def on_key_press(self, key, modifiers):\n \"\"\" Called when user presses key \"\"\"\n if key == arcade.key.LEFT:\n self.player_sprite.change_x = -MOVEMENT_SPEED\n if key == arcade.key.RIGHT:\n self.player_sprite.change_x = MOVEMENT_SPEED\n if key == arcade.key.UP:\n self.player_sprite.change_y = MOVEMENT_SPEED\n if key == arcade.key.DOWN:\n self.player_sprite.change_y = -MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\" Called whenever a user releases a key \"\"\"\n if key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player_sprite.change_x = 0\n elif key == arcade.key.UP or key == arcade.key.DOWN:\n self.player_sprite.change_y = 0\n\n def update(self, delta_time):\n\n \"\"\" Movement and game logic \"\"\"\n # Call update on all sprites (The sprites don't do much in this\n # example though\n self.length_of_play += 1\n\n if self.game_over is False:\n self.player_sprite.update()\n\n self.coin_list.update()\n\n self.gem_list.update()\n\n # Generate a list of all sprites that collided with the player.\n\n coins_hit_list = arcade.check_for_collision_with_list(self.player_sprite,\n\n self.coin_list)\n\n gem_hit_list = arcade.check_for_collision_with_list(self.player_sprite,\n\n self.gem_list)\n\n # Loop through each colliding sprite, remove it, and add to the score.\n\n for coin in coins_hit_list:\n coin.remove_from_sprite_lists()\n\n arcade.play_sound(self.good_sound)\n\n self.score += 1\n\n for gem in gem_hit_list:\n gem.remove_from_sprite_lists()\n\n arcade.play_sound(self.bad_sound)\n\n self.score -= 2\n\n if self.player_sprite.left < 0:\n self.player_sprite.left = 0\n\n if self.player_sprite.right > SCREEN_WIDTH:\n self.player_sprite.right = SCREEN_WIDTH\n\n if self.player_sprite.top > SCREEN_HEIGHT:\n self.player_sprite.top = SCREEN_HEIGHT\n\n if self.player_sprite.bottom < 0:\n self.player_sprite.bottom = 0\n\n if self.score >= 20 or self.score <= -10 or self.length_of_play > 3600:\n self.game_over = True\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame()\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Lab 08 - Sprites/lab_08.py","file_name":"lab_08.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"75781156","text":"import csv\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport matplotlib.pyplot as plt\nfrom matplotlib.axis import Axis\nfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange\n\ndb = pd.read_csv('Sykt_t_data_day_mean_2020WithRp5.csv', encoding='cp1251')\ndb = db.set_index(pd.DatetimeIndex(db['date']))\nprint(db.head(0))\n\n\nb_date = '01.01.2020'\ne_date = '31.12.2020'\n\ninter_year = 2020\ntemperature = 10\n\n\nbegin_date = pd.to_datetime(b_date, format='%d.%m.%Y')\nend_date = pd.to_datetime(e_date, format='%d.%m.%Y')\n\ndb_select = db[['Intraday_mean', 'Precipitation']].loc[(db.index >= begin_date) & (db.index <= end_date)]\n\ndb1_select = db_select.loc[(db_select['Intraday_mean'] >= temperature)]# & (db_select['Precipitation'] > 0)]\n\nprint(db1_select.index.min())\nbegin_date1 = db1_select.index.min()\n\nend_date1 = db1_select.index.max()\n\nprint(db1_select.index.max())\n\n\nstep = dt.timedelta(days=1)\n\ndate = pd.date_range(begin_date1, end_date1, freq='1D')\n\nprint(date)\n\nyearData = pd.DataFrame(date, index=date, columns=['date'])\n\n\nyearData['GTK'] = yearData.apply(lambda row: db['Precipitation'].loc[(db.index >= row['date']) & (db.index < row['date'] + step) & (db['Intraday_mean'] >= temperature)].sum()*10/db['Intraday_mean'].loc[(db.index >= row['date']) & (db.index < row['date'] + step) & (db['Intraday_mean'] >= temperature)].sum(), axis=1)\nyearData['GTK'] = yearData['GTK'].fillna(0)\nprint(yearData)\nvar1 = yearData['GTK']\n\n\n\n\n\n\n#\n# step = dt.timedelta(days=7)\n#\n# date = pd.date_range(begin_date1, end_date1, freq='7D')\n#\n# print(date)\n# barData = pd.DataFrame(date, index=date, columns=['date'])\n# bars = barData['date'].apply(lambda x: x.strftime('%d.%m'))\n#\n# bars = bars.append(pd.Series([(barData['date'].max()+step).strftime('%d.%m')], index=[barData['date'].max()+step]))\n\n# title = \"Диаграмма изменчивости суточного гидротермического коэффициента Селянинова\\n\" + r\"%s год\" % (begin_date1.strftime(\"%Y\")) + \"\\n\" + r\"вегетационный период с %s по %s\" % (begin_date1.strftime(\"%d.%m\"), end_date1.strftime(\"%d.%m\"))\n# plt.title(title, fontsize=12)\n\n# y_pos = np.arange(0, var1.size)\n\n#\n# # plt.Axes.bar(y_pos, var1)#, edgecolor=\"black\", linewidth=0.5)\n#\n# date = pd.date_range(begin_date1, end_date1, freq='7D')-dt.timedelta(days=7)\n# Date = pd.DataFrame(date, index=date, columns=['date'])\n# bars = Date['date'].apply(lambda x: x.strftime('%d.%m'))\n# bars = bars.append(pd.Series([(yearData['date'].max()+dt.timedelta(days=7)).strftime('%d.%m')], index=[yearData['date'].max()+dt.timedelta(days=7)]))\n# print(bars)\n# xtick_pos = np.arange(0, bars+1)\n# # print(bars)\n# fig, ax = plt.subplots()\n\n# print(var1.size)\ndelta = dt.timedelta(days=1)\ndates = pd.date_range(begin_date1, end_date1, freq='1D')\nprint(dates)\n\nfig, ax = plt.subplots()\nax.bar(dates, var1)\n\nax.set_xlim(dates[0], dates[-1]+delta)\n\nax.xaxis.set_major_locator(DayLocator(interval=7))\nAxis.set_minor_locator(ax.xaxis, DayLocator())\nax.xaxis.set_major_formatter(DateFormatter('%d.%m'))\n\nax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')\nfig.autofmt_xdate()\n\nfig.suptitle(\"Диаграмма изменчивости суточного гидрот��рмического коэффициента Селянинова\\n\" + r\"%s год\" % (begin_date1.strftime(\"%Y\")) + \"\\n\" + r\"вегетационный период с %s по %s\" % (begin_date1.strftime(\"%d.%m\"), end_date1.strftime(\"%d.%m\")), fontsize=12, fontweight='bold')\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n# ax.xaxis.set_major_locator(xtick_pos)\n# ax.xaxis.set_minor_locator(MultipleLocator(1))\n# plt.xticks(MultipleLocator(7), bars, fontsize=12, rotation='vertical')\n# ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\n# xtick_pos = np.arange(0, var1.size+1)\n# # xtick_pos = pd.Series([0,4,8,12,16,20,24])\n# print(xtick_pos)\n# # bars = pd.Series(['30.04', '28.05', '25.06', '23.07', '20.08', '17.09', '15.10'])\n# bars=[]\n# plt.xticks(xtick_pos, bars, fontsize=12, rotation='vertical')\n# # plt.tick_params(axis='x', width=2.5, color='black')\n# # plt.ylim(0, 8)\n# plt.xlim(-0.5, var1.size+0.5)\n# # plt.axvline(linewidth=0.75, x=0, color='b')\n# plt.axvline(linewidth=0.75, x=14+6/10, color='b')\n# plt.show()\n\n","sub_path":"Selyaninov_stolbiki.py","file_name":"Selyaninov_stolbiki.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"344908516","text":"import googlemaps\nfrom datetime import datetime\nimport json\n\n\ndef flask_googlemapsearch(user_address, user_radius):\n # Note: user_radius will have to be capped at MAYBE <25000? due to weird, inconsistent results\n API_key = \"\"\n gmaps = googlemaps.Client(key=API_key)\n\n # Location and user generality, but for now rely on user address\n user_lat = gmaps.geocode(user_address)[0]['geometry']['location']['lat']\n user_long = gmaps.geocode(user_address)[0]['geometry']['location']['lng']\n user_latlong = (user_lat, user_long)\n\n gmaps_nearby = gmaps.places_nearby(\n user_latlong, user_radius, type='grocery_or_supermarket' or 'store' or 'establishment' or 'food')['results']\n\n if not len(gmaps_nearby):\n print(\"No results nearby! Try expanding your search radius.\")\n # else:\n # print(gmaps_nearby)\n #gmaps_json = json.dumps(gmaps_nearby)\n # print(gmaps_json)\n\n store_dict = {}\n store_list = ['metro', 'longo\\'s', 'zehrs', 'no frills']\n\n for store in gmaps_nearby:\n if \"metros\" in store['name'].lower() or \"longo's\" in store['name'].lower() or \"no frills\" in store['name'].lower() or \"zehrs\" in store['name'].lower():\n store_dict[store['name']] = store['vicinity']\n #store_location = store['name'] + \" at \" + store['vicinity']\n # store_list.append(store_location)\n\n return store_dict\n","sub_path":"flask_googlemapsearch.py","file_name":"flask_googlemapsearch.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"342366196","text":"import tensorflow as tf\nimport numpy as np\nimport keras\nfrom util import loader\n\n\ndef get_non_trainable_variable(input_variable):\n return tf.Variable(input_variable, trainable=False)\n\n\ndef compute_accuracy(session, prediction, v_xs, v_ys):\n correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(v_ys, 1))\n accuracy_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n result = session.run(accuracy_op, feed_dict={target_train_x: v_xs, target_train_label: v_ys})\n return result\n\n\ndef get_weight(shape):\n var = tf.Variable(tf.random_normal(shape), dtype=tf.float32, trainable=True)\n return var\n\n\ndef get_model(w1, w2, x):\n flatten_num = image_width ** 2\n layer = tf.reshape(x, [-1, flatten_num])\n layer = tf.matmul(layer, w1)\n layer = tf.nn.relu(layer)\n layer = tf.matmul(layer, w2)\n return layer\n\n\nsess = tf.Session()\n# sess = tf_debug.LocalCLIDebugWrapperSession(sess)\nimage_width = 28\nclass_num = 10\n\nfashion_mnist = keras.datasets.fashion_mnist\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n(train_images, train_labels), (test_images, test_labels) = loader.load_data()\ntrain_images = (train_images / 255.0 - 0.5) * 2\ntest_images = (test_images / 255.0 - 0.5) * 2\ntrain_labels = sess.run(tf.one_hot(train_labels, class_num))\ntest_labels = sess.run(tf.one_hot(test_labels, class_num))\n\ntarget_train_x = tf.placeholder(tf.float32, shape=(None, image_width, image_width))\ntarget_train_label = tf.placeholder(tf.float32, shape=(None, class_num))\n\n# flatten_num = image_width ** 2\n#\nw1_t = tf.Variable(tf.random_normal([784, 128], stddev=1, seed=1))\nw2_t = tf.Variable(tf.random_normal([128, 10], stddev=1, seed=1))\n#\n# target_output = tf.reshape(target_train_x, [-1, flatten_num])\n# target_output = tf.matmul(target_output, w1_t)\n# target_output = tf.nn.relu(target_output)\n# target_output = tf.matmul(target_output, w2_t)\ntarget_output = get_model(w1_t, w2_t, target_train_x)\n\n# sparse不接受one-hot,不加sparse接受\n# 这里还没有求均值��但是有负号\n# target_output = tf.nn.softmax(target_output)\n# cross_entropy = -tf.reduce_mean(target_train_label * tf.log(tf.clip_by_value(target_output, 1e-10, 1.0)))\n\ncross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits_v2(labels=target_train_label, logits=target_output))\ntrain_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)\n\ndataset_size = len(train_images)\n\nbatch_size = 8\ncheck_interval = 1000\nsteps = dataset_size // batch_size\nsteps = steps if dataset_size % batch_size == 0 else steps + 1\n\ninit_op = tf.global_variables_initializer()\nsess.run(init_op)\nepochs = 5\n\nfor epoch in range(epochs):\n print(\"Epoch %d / %d\" % (epoch + 1, epochs))\n for i in range(steps):\n start = (i * batch_size) % dataset_size\n end = min(start + batch_size, dataset_size)\n\n sess.run(train_step,\n feed_dict={target_train_x: train_images[start:end], target_train_label: train_labels[start:end]})\n\n if i % check_interval == 0 and i != 0:\n total_cross_entropy = sess.run(cross_entropy,\n feed_dict={target_train_x: train_images, target_train_label: train_labels})\n accuracy = compute_accuracy(sess, target_output, train_images, train_labels)\n print(\"After %d training step(s), loss: %g, accuracy: %g\" % (i, total_cross_entropy, accuracy))\n total_cross_entropy = sess.run(cross_entropy,\n feed_dict={target_train_x: train_images, target_train_label: train_labels})\n accuracy = compute_accuracy(sess, target_output, train_images, train_labels)\n print(\"======================================================\")\n print(\"At the end of epoch %d, loss: %g, accuracy: %g\" % (epoch + 1, total_cross_entropy, accuracy))\n print(\"======================================================\")\n\nw1_n = sess.run(w1_t)\nnp.save('../model/nw1.npy', w1_n)\nw2_n = sess.run(w2_t)\nnp.save('../model/nw2.npy', w2_n)\nsess.close()\ntf.reset_default_graph()\n\nsess = tf.Session()\n","sub_path":"attack/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"340928285","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nturner-GAN\r\n\"\"\"\r\n\r\n#Si no funciona el entorno, mirar aquí: https://medium.com/@pushkarmandot/installing-tensorflow-theano-and-keras-in-spyder-84de7eb0f0df\r\n#slim = tf.contrib.slim \r\n#https://medium.freecodecamp.org/how-ai-can-learn-to-generate-pictures-of-cats-ba692cb6eae4 \r\n\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport random\r\nimport scipy.misc\r\nfrom utils2 import *\r\n\r\n\r\n\r\nHEIGHT, WIDTH, CHANNEL = 128, 128, 3\r\nBATCH_SIZE = 64\r\nEPOCH = 5000\r\nversion = 'newUkiyoe'\r\nnewPoke_path = './' + version\r\n\r\ndef lrelu(x, n, leak=0.2): \r\n return tf.maximum(x, leak * x, name=n) \r\n \r\ndef process_data(): \r\n \r\n current_dir = os.getcwd()\r\n # parent = os.path.dirname(current_dir)\r\n pokemon_dir = os.path.join(current_dir, 'Ukiyo_e')\r\n images = []\r\n for each in os.listdir(pokemon_dir):\r\n images.append(os.path.join(pokemon_dir,each))\r\n # print images \r\n all_images = tf.convert_to_tensor(images, dtype = tf.string) #se convierten el vector de imágenes en un tensor\r\n \r\n images_queue = tf.train.slice_input_producer(\r\n [all_images]) #divide el tensor en particiones\r\n \r\n content = tf.read_file(images_queue[0])\r\n image = tf.image.decode_jpeg(content, channels = CHANNEL)\r\n # sess1 = tf.Session()\r\n # print sess1.run(image)\r\n image = tf.image.random_flip_left_right(image)\r\n image = tf.image.random_brightness(image, max_delta = 0.1) #ajusta el brillo a un valor concreto aleatorio\r\n image = tf.image.random_contrast(image, lower = 0.9, upper = 1.1)\r\n # noise = tf.Variable(tf.truncated_normal(shape = [HEIGHT,WIDTH,CHANNEL], dtype = tf.float32, stddev = 1e-3, name = 'noise')) \r\n # print image.get_shape()\r\n size = [HEIGHT, WIDTH]\r\n image = tf.image.resize_images(image, size)\r\n image.set_shape([HEIGHT,WIDTH,CHANNEL])\r\n # image = image + noise\r\n # image = tf.transpose(image, perm=[2, 0, 1])\r\n # print image.get_shape()\r\n \r\n image = tf.cast(image, tf.float32)\r\n image = image / 255.0\r\n \r\n iamges_batch = tf.train.shuffle_batch(\r\n [image], batch_size = BATCH_SIZE,\r\n num_threads = 4, capacity = 200 + 3* BATCH_SIZE,\r\n min_after_dequeue = 200)\r\n num_images = len(images)\r\n\t\t\t\t\t\t\t\t\t#está mezclando los tensores de imágenes [images] de cada epoch y dará como resultado image_batch, que es el lote de imagenes a tratar en esa epoch. \r\n\t\t\t\t\t\t\t\t\t#capacity: maximo numero de elementos en la cola(pila). min_after_dequeue:minimo numero de elementos en la pila despues del dequeue(retirar elementos de la pila).\r\n\t\r\n\r\n return iamges_batch, num_images\r\n\r\ndef generator(input, random_dim, is_train, reuse=False):\r\n c4, c8, c16, c32, c64 = 512, 256, 128, 64, 32 # channel num\r\n s4 = 4\r\n output_dim = CHANNEL # RGB image\r\n with tf.variable_scope('gen') as scope:\r\n if reuse:\r\n scope.reuse_variables()\r\n w1 = tf.get_variable('w1', shape=[random_dim, s4 * s4 * c4], dtype=tf.float32,\r\n initializer=tf.truncated_normal_initializer(stddev=0.02))\r\n b1 = tf.get_variable('b1', shape=[c4 * s4 * s4], dtype=tf.float32,\r\n initializer=tf.constant_initializer(0.0))\r\n flat_conv1 = tf.add(tf.matmul(input, w1), b1, name='flat_conv1') \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #matmul = matrix multiplication. flat_conv1=inputxw1 + b1 ----> dimensiones:(1x100)matmul(100x8096) + (1x8096) = (1x8096)\r\n #Convolution, bias, activation, repeat! \r\n conv1 = tf.reshape(flat_conv1, shape=[-1, s4, s4, c4], name='conv1') \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #el -1 es porque desconocemos la dimension (aunque es 1x8096) y queremos que numpy la averigue. Esta transformando un tensor de 1x8096 en otro tensor de 4x4x512\r\n bn1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn1') # adds a batch normalization layer. input:conv1/// is_training: Whether or not the layer is in training mode. In training mode it would accumulate the statistics of the moments/// epsilon: small float added to the variance to avoid dividing by zero/// decay=disminucion de la media\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #Normalize the activations of the previous layer at each batch, i.e. applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1.\r\n\t\t #se aplica ReLu\r\n # 8*8*256\r\n #Convolution, bias, activation, repeat! \r\n act1 = tf.nn.relu(bn1, name='act1')\r\n conv2 = tf.layers.conv2d_transpose(act1, c8, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\", \t\t\t\t\t\t\t\t #input=act1; filters=c8=256 -> es la dimension del espacio de salida; kernel_size = dimensiones de los filtros/// strides=salto por el que se multiplica\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02), \t\t\t\t\t\t\t\t #inicializador del kernel\t\t\r\n name='conv2')\r\n bn2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn2')\r\n act2 = tf.nn.relu(bn2, name='act2')\r\n # 16*16*128\r\n conv3 = tf.layers.conv2d_transpose(act2, c16, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv3')\r\n bn3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn3')\r\n act3 = tf.nn.relu(bn3, name='act3')\r\n # 32*32*64\r\n conv4 = tf.layers.conv2d_transpose(act3, c32, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv4')\r\n bn4 = tf.contrib.layers.batch_norm(conv4, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn4')\r\n act4 = tf.nn.relu(bn4, name='act4')\r\n # 64*64*32\r\n conv5 = tf.layers.conv2d_transpose(act4, c64, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv5')\r\n bn5 = tf.contrib.layers.batch_norm(conv5, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn5')\r\n act5 = tf.nn.relu(bn5, name='act5')\r\n \r\n #128*128*3\r\n conv6 = tf.layers.conv2d_transpose(act5, output_dim, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv6')\r\n # bn6 = tf.contrib.layers.batch_norm(conv6, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn6')\r\n act6 = tf.nn.tanh(conv6, name='act6')\r\n return act6\r\n\r\n\r\ndef discriminator(input, is_train, reuse=False):\r\n c2, c4, c8, c16 = 64, 128, 256, 512 # channel num: 64, 128, 256, 512\r\n with tf.variable_scope('dis') as scope:\r\n if reuse:\r\n scope.reuse_variables()\r\n\r\n #Convolution, activation, bias, repeat! \r\n conv1 = tf.layers.conv2d(input, c2, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv1')\r\n bn1 = tf.contrib.layers.batch_norm(conv1, is_training = is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope = 'bn1')\r\n act1 = lrelu(conv1, n='act1') #se aplica Leaky Relu en lugar de Relu\r\n #Convolution, activation, bias, repeat! \r\n conv2 = tf.layers.conv2d(act1, c4, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv2')\r\n bn2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn2')\r\n act2 = lrelu(bn2, n='act2')\r\n #Convolution, activation, bias, repeat! \r\n conv3 = tf.layers.conv2d(act2, c8, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv3')\r\n bn3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn3')\r\n act3 = lrelu(bn3, n='act3')\r\n #Convolution, activation, bias, repeat! \r\n conv4 = tf.layers.conv2d(act3, c16, kernel_size=[5, 5], strides=[2, 2], padding=\"SAME\",\r\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\r\n name='conv4')\r\n bn4 = tf.contrib.layers.batch_norm(conv4, is_training=is_train, epsilon=1e-5, decay = 0.9, updates_collections=None, scope='bn4')\r\n act4 = lrelu(bn4, n='act4')\r\n \r\n # start from act4\r\n dim = int(np.prod(act4.get_shape()[1:]))\r\n fc1 = tf.reshape(act4, shape=[-1, dim], name='fc1')\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #el -1 es porque desconocemos la dimension y queremos que numpy la averigue\r\n \r\n \r\n w2 = tf.get_variable('w2', shape=[fc1.shape[-1], 1], dtype=tf.float32,\r\n initializer=tf.truncated_normal_initializer(stddev=0.02))\r\n b2 = tf.get_variable('b2', shape=[1], dtype=tf.float32,\r\n initializer=tf.constant_initializer(0.0))\r\n\r\n # wgan just get rid of the sigmoid\r\n logits = tf.add(tf.matmul(fc1, w2), b2, name='logits')\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #logits es el vector de predicciones que genera el discriminador antes de ser normalizado con sigmoid function (entre 1 y 0).\r\n # dcgan\r\n acted_out = tf.nn.sigmoid(logits)\r\n return logits # acted_out\r\n\r\n\r\ndef train():\r\n random_dim = 100\r\n \r\n with tf.variable_scope('input'):\r\n #real and fake image placeholders\r\n real_image = tf.placeholder(tf.float32, shape = [None, HEIGHT, WIDTH, CHANNEL], name='real_image') \t#un placeholder(marcador de posicion) consiste en reservar espacio en memoria para una variable, pero no asignar el valor a esa variable aun. Se asigna en la sesión, de manera que la variable tendrá esos valores durante esa sesión. El placeholder es el método para introducir datos en los gráficos computacionales (tensores) de Tensorflow.\r\n random_input = tf.placeholder(tf.float32, shape=[None, random_dim], name='rand_input') \t\t\t\t#este placeholder será de tipo float con dimensiones (cualquiera(None) x random_dim) y con ese nombre\r\n is_train = tf.placeholder(tf.bool, name='is_train') \t\t\t\t\t\t\t\t\t\t\t\t#placeholder de tipo booleano: 1 o 0\r\n \r\n # wgan\r\n fake_image = generator(random_input, random_dim, is_train)\r\n \r\n real_result = discriminator(real_image, is_train)\r\n fake_result = discriminator(fake_image, is_train, reuse=True)\r\n \r\n d_loss = tf.reduce_mean(fake_result) - tf.reduce_mean(real_result) \t\t\t\t\t\t\t\t\t# This optimizes the discriminator. tf.reduce_mean-->hace la media de todos los valores. d_loss es la funcion de error del discriminador y se basa en la distancia entre el resultado verdadero y el falso.\r\n g_loss = -tf.reduce_mean(fake_result) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# This optimizes the generator. la funcion de error del generador, que se basa en la media del resultado falso generado\r\n \r\n\r\n t_vars = tf.trainable_variables() \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Devuelve todas las variables creadas con trainable=True\r\n d_vars = [var for var in t_vars if 'dis' in var.name]\r\n g_vars = [var for var in t_vars if 'gen' in var.name]\r\n trainer_d = tf.train.RMSPropOptimizer(learning_rate=2e-4).minimize(d_loss, var_list=d_vars) \t\t\t#Root Mean Squared Propagation: es una version adaptada del stochastic gradient descent. Va minimizando d_loss. Es un método de optimización adaptativa del learning rate.\r\n trainer_g = tf.train.RMSPropOptimizer(learning_rate=2e-4).minimize(g_loss, var_list=g_vars) \t\t\t#va minimizando g_loss \r\n # clip discriminator weights\r\n d_clip = [v.assign(tf.clip_by_value(v, -0.01, 0.01)) for v in d_vars] \t\t\t\t\t\t\t\t\t#las d_vars(variables del discriminador) inferiores a -0.01 serán 0.01 y las superiores a 0.01 serán 0.01\r\n\r\n \r\n batch_size = BATCH_SIZE\r\n image_batch, samples_num = process_data() \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#se obtienen las imágenes estandarizadas. samples_num es el numero de imagenes que se tratan, el numero de muestras. image_batch\r\n \r\n batch_num = int(samples_num / batch_size)\r\n total_batch = 0\r\n sess = tf.Session()\r\n saver = tf.train.Saver() \r\n sess.run(tf.global_variables_initializer()) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#antes de usar variables estas deben de ser inicializadas\r\n sess.run(tf.local_variables_initializer())\r\n # continue training\r\n save_path = saver.save(sess, \"/tmp/model.ckpt\") \t\t\t\t\t\t\t\t\t\t\t\t\t\t#guarda las variables \r\n ckpt = tf.train.latest_checkpoint('./model/' + version) \t\t\t\t\t\t\t\t\t\t\t\t#encuentra el nombre de del archivo del ultimo checkpoint guardado. './model/' es el directorio donde se encuentra el checkpoint\r\n saver.restore(sess, save_path) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#restaura las variables que se han guardado previamente\r\n coord = tf.train.Coordinator()\r\n\t \r\n threads = tf.train.start_queue_runners(sess=sess, coord=coord) \t\t\t\t\t\t\t\t\t\t#threading implica multiples tareas ejecutandose asincronicamente. El metodo de threading es el queuing y ayuda para introducir los datos en el training set. Cuando Tensorflow está leyendo la entrada de datos necesita mantener muchas queues operando simultaneamente, por lo que el Coordinator ayuda a gestionarlo. Multithreaded queues are a powerful and widely used mechanism supporting asynchronous computation. https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.10/tensorflow/g3doc/how_tos/threading_and_queues/index.md \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# https://www.tensorflow.org/guide/graphs explica como funciona tensorflow y sus graficos y sesiones\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Like everything in TensorFlow, a queue is a node in a TensorFlow graph. It's a stateful node, like a variable: other nodes can modify its content. In particular, nodes can enqueue new items in to the queue, or dequeue existing items from the queue\r\n\t\r\n\t \r\n print('batch size: %d, batch num per epoch: %d, epoch num: %d' % (batch_size, batch_num, EPOCH))\r\n print('total training sample num:%d' % samples_num)\r\n print('start training...')\r\n for i in range(EPOCH):\r\n print(\"Running epoch {}/{}...\".format(i, EPOCH))\r\n for j in range(batch_num):\r\n print(j)\r\n d_iters = 5\r\n g_iters = 1\r\n\r\n train_noise = np.random.uniform(-1.0, 1.0, size=[batch_size, random_dim]).astype(np.float32) \t\t\t\t#el vector de ruido aleatorio normalizado de tamaño 64 x 100\r\n for k in range(d_iters):\r\n print(k)\r\n train_image = sess.run(image_batch)\r\n #wgan clip weights\r\n sess.run(d_clip) \r\n \r\n # Update the discriminator\r\n _, dLoss = sess.run([trainer_d, d_loss],\r\n feed_dict={random_input: train_noise, real_image: train_image, is_train: True})\r\n\r\n # Update the generator\r\n for k in range(g_iters):\r\n \r\n _, gLoss = sess.run([trainer_g, g_loss],\r\n feed_dict={random_input: train_noise, is_train: True})\r\n\r\n # print 'train:[%d/%d],d_loss:%f,g_loss:%f' % (i, j, dLoss, gLoss)\r\n \r\n # save check point every 500 epoch\r\n if i%100 == 0:\r\n if not os.path.exists('./model/' + version):\r\n os.makedirs('./model/' + version)\r\n saver.save(sess, './model/' +version + '/' + str(i)) \r\n if i%50 == 0:\r\n # save images\r\n if not os.path.exists(newPoke_path):\r\n os.makedirs(newPoke_path)\r\n sample_noise = np.random.uniform(-1.0, 1.0, size=[batch_size, random_dim]).astype(np.float32) \t\t\t\t#vector de ruido de 64 x 100\r\n imgtest = sess.run(fake_image, feed_dict={random_input: sample_noise, is_train: False})\r\n # imgtest = imgtest * 255.0\r\n # imgtest.astype(np.uint8)\r\n save_images(imgtest, [8,8] ,newPoke_path + '/epoch' + str(i) + '.jpg')\r\n \r\n print('train:[%d],d_loss:%f,g_loss:%f' % (i, dLoss, gLoss))\r\n\t\t\t\r\n coord.request_stop() \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#requests that threads should stop\r\n coord.join(threads) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#waits until the specified threads have stopped.\r\n\r\n\r\n# def test():\r\n # random_dim = 100\r\n # with tf.variable_scope('input'):\r\n # real_image = tf.placeholder(tf.float32, shape = [None, HEIGHT, WIDTH, CHANNEL], name='real_image')\r\n # random_input = tf.placeholder(tf.float32, shape=[None, random_dim], name='rand_input')\r\n # is_train = tf.placeholder(tf.bool, name='is_train')\r\n \r\n # # wgan\r\n # fake_image = generator(random_input, random_dim, is_train)\r\n # real_result = discriminator(real_image, is_train)\r\n # fake_result = discriminator(fake_image, is_train, reuse=True)\r\n # sess = tf.InteractiveSession()\r\n # sess.run(tf.global_variables_initializer())\r\n # variables_to_restore = slim.get_variables_to_restore(include=['gen'])\r\n # print(variables_to_restore)\r\n # saver = tf.train.Saver(variables_to_restore) \r\n # ckpt = tf.train.latest_checkpoint('./model/' + version)\r\n # saver.restore(sess, ckpt)\r\n\r\n #tf.reset_default_graph()\r\nif __name__ == \"__main__\":\r\n train()\r\n # test()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\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":"Ukiyoe.py","file_name":"Ukiyoe.py","file_ext":"py","file_size_in_byte":18410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"420992018","text":"import math\nimport warnings\nfrom typing import TYPE_CHECKING\nfrom typing import List\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\nfrom etna.loggers import tslogger\n\nif TYPE_CHECKING:\n from etna.transforms.base import Transform\n\nTTimestamp = Union[str, pd.Timestamp]\n\n\nclass TSDataset:\n \"\"\"TSDataset is the main class to handle your time series data.\n It prepares the series for exploration analyzing, implements feature generation with Transforms\n and generation of future points.\n\n Notes\n -----\n TSDataset supports custom indexing and slicing method.\n It maybe done through these interface: TSDataset[timestamp, segment, column]\n If at the start of the period dataset contains NaN those timestamps will be removed.\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(periods=30, start_time=\"2021-06-01\", n_segments=2, scale=1)\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> ts = TSDataset(df_ts_format, \"D\")\n >>> ts[\"2021-06-01\":\"2021-06-07\", \"segment_0\", \"target\"]\n timestamp\n 2021-06-01 1.0\n 2021-06-02 1.0\n 2021-06-03 1.0\n 2021-06-04 1.0\n 2021-06-05 1.0\n 2021-06-06 1.0\n 2021-06-07 1.0\n Freq: D, Name: (segment_0, target), dtype: float64\n\n >>> from etna.datasets import generate_ar_df\n >>> pd.options.display.float_format = '{:,.2f}'.format\n >>> df_to_forecast = generate_ar_df(100, start_time=\"2021-01-01\", n_segments=1)\n >>> df_regressors = generate_ar_df(120, start_time=\"2021-01-01\", n_segments=5)\n >>> df_regressors = df_regressors.pivot(index=\"timestamp\", columns=\"segment\").reset_index()\n >>> df_regressors.columns = [\"timestamp\"] + [f\"regressor_{i}\" for i in range(5)]\n >>> df_regressors[\"segment\"] = \"segment_0\"\n >>> df_to_forecast = TSDataset.to_dataset(df_to_forecast)\n >>> df_regressors = TSDataset.to_dataset(df_regressors)\n >>> tsdataset = TSDataset(df=df_to_forecast, freq=\"D\", df_exog=df_regressors)\n >>> tsdataset.df.head(5)\n segment segment_0\n feature regressor_0 regressor_1 regressor_2 regressor_3 regressor_4 target\n timestamp\n 2021-01-01 1.62 -0.02 -0.50 -0.56 0.52 1.62\n 2021-01-02 1.01 -0.80 -0.81 0.38 -0.60 1.01\n 2021-01-03 0.48 0.47 -0.81 -1.56 -1.37 0.48\n 2021-01-04 -0.59 2.44 -2.21 -1.21 -0.69 -0.59\n 2021-01-05 0.28 0.58 -3.07 -1.45 0.77 0.28\n \"\"\"\n\n idx = pd.IndexSlice\n\n def __init__(self, df: pd.DataFrame, freq: str, df_exog: Optional[pd.DataFrame] = None):\n \"\"\"Init TSDataset.\n\n Parameters\n ----------\n df:\n dataframe with timeseries\n freq:\n frequency of timestamp in df\n df_exog:\n dataframe with exogenous data;\n if the series is known in the future features' names should start with prefix 'regressor_`.\n \"\"\"\n self.raw_df = df.copy(deep=True)\n self.raw_df.index = pd.to_datetime(self.raw_df.index)\n self.freq = freq\n self.df_exog = None\n\n self.raw_df.index = pd.to_datetime(self.raw_df.index)\n\n try:\n infered_freq = pd.infer_freq(self.raw_df.index)\n except ValueError:\n warnings.warn(\"TSDataset freq can't be inferred\")\n infered_freq = None\n\n if infered_freq != self.freq:\n warnings.warn(\n f\"You probably set wrong freq. Discovered freq in you data is {infered_freq}, you set {self.freq}\"\n )\n\n self.raw_df = self.raw_df.asfreq(self.freq)\n\n self.df = self.raw_df.copy(deep=True)\n\n if df_exog is not None:\n self.df_exog = df_exog.copy(deep=True)\n self.df_exog.index = pd.to_datetime(self.df_exog.index)\n self.df = self._merge_exog(self.df)\n\n self.transforms: Optional[Sequence[\"Transform\"]] = None\n self._update_regressors()\n\n def transform(self, transforms: Sequence[\"Transform\"]):\n \"\"\"Apply given transform to the data.\"\"\"\n self._check_endings()\n self.transforms = transforms\n for transform in self.transforms:\n tslogger.log(f\"Transform {transform.__class__.__name__} is applied to dataset\")\n self.df = transform.transform(self.df)\n self._update_regressors()\n\n def fit_transform(self, transforms: Sequence[\"Transform\"]):\n \"\"\"Fit and apply given transforms to the data.\"\"\"\n self._check_endings()\n self.transforms = transforms\n for transform in self.transforms:\n tslogger.log(f\"Transform {transform.__class__.__name__} is applied to dataset\")\n self.df = transform.fit_transform(self.df)\n self._update_regressors()\n\n def __repr__(self):\n return self.df.__repr__()\n\n def _repr_html_(self):\n return self.df._repr_html_()\n\n def __getitem__(self, item):\n if isinstance(item, slice) or isinstance(item, str):\n df = self.df.loc[self.idx[item]]\n elif len(item) == 2 and item[0] is Ellipsis:\n df = self.df.loc[self.idx[:], self.idx[:, item[1]]]\n elif len(item) == 2 and item[1] is Ellipsis:\n df = self.df.loc[self.idx[item[0]]]\n else:\n df = self.df.loc[self.idx[item[0]], self.idx[item[1], item[2]]]\n first_valid_idx = df.first_valid_index()\n df = df.loc[first_valid_idx:]\n return df\n\n def make_future(self, future_steps: int) -> \"TSDataset\":\n \"\"\"Return new TSDataset with future steps.\n\n Parameters\n ----------\n future_steps:\n number of timestamp in the future to build features for.\n\n Returns\n -------\n dataset with features in the future.\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df_regressors = pd.DataFrame({\n ... \"timestamp\": list(pd.date_range(\"2021-06-01\", periods=40))*2,\n ... \"regressor_1\": np.arange(80), \"regressor_2\": np.arange(80) + 5,\n ... \"segment\": [\"segment_0\"]*40 + [\"segment_1\"]*40\n ... })\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> df_regressors_ts_format = TSDataset.to_dataset(df_regressors)\n >>> ts = TSDataset(df_ts_format, \"D\", df_exog=df_regressors_ts_format)\n >>> ts.make_future(4)\n segment segment_0 segment_1\n feature regressor_1 regressor_2 target regressor_1 regressor_2 target\n timestamp\n 2021-07-01 30 35 nan 70 75 nan\n 2021-07-02 31 36 nan 71 76 nan\n 2021-07-03 32 37 nan 72 77 nan\n 2021-07-04 33 38 nan 73 78 nan\n \"\"\"\n max_date_in_dataset = self.df.index.max()\n future_dates = pd.date_range(\n start=max_date_in_dataset, periods=future_steps + 1, freq=self.freq, closed=\"right\"\n )\n\n new_index = self.raw_df.index.append(future_dates)\n df = self.raw_df.reindex(new_index)\n df.index.name = \"timestamp\"\n\n if self.df_exog is not None:\n df = self._merge_exog(df)\n\n # check if we have enough values in regressors\n if self.regressors:\n for segment in self.segments:\n regressors_index = self.df_exog.loc[:, pd.IndexSlice[segment, self.regressors]].index\n if not np.all(future_dates.isin(regressors_index)):\n warnings.warn(\n f\"Some regressors don't have enough values in segment {segment}, \"\n f\"NaN-s will be used for missing values\"\n )\n\n if self.transforms is not None:\n for transform in self.transforms:\n df = transform.transform(df)\n\n futute_dataset = df.tail(future_steps).copy(deep=True)\n futute_dataset = futute_dataset.sort_index(axis=1, level=(0, 1))\n future_ts = TSDataset(futute_dataset, freq=self.freq)\n future_ts.transforms = self.transforms\n future_ts.df_exog = self.df_exog\n return future_ts\n\n @staticmethod\n def _check_regressors(df: pd.DataFrame, df_exog: pd.DataFrame):\n \"\"\"Check that regressors in df_exog begin not later than in df and end later than in df.\"\"\"\n df_segments = df.columns.get_level_values(\"segment\")\n for segment in df_segments:\n target = df[segment][\"target\"].dropna()\n exog_regressor_columns = [x for x in set(df_exog[segment].columns) if x.startswith(\"regressor\")]\n for series in exog_regressor_columns:\n exog_series = df_exog[segment][series].dropna()\n if target.index.min() < exog_series.index.min():\n raise ValueError(\n f\"All the regressor series should start not later than corresponding 'target'.\"\n f\"Series {series} of segment {segment} have not enough history: \"\n f\"{target.index.min()} < {exog_series.index.min()}.\"\n )\n if target.index.max() >= exog_series.index.max():\n raise ValueError(\n f\"All the regressor series should finish later than corresponding 'target'.\"\n f\"Series {series} of segment {segment} have not enough history: \"\n f\"{target.index.max()} >= {exog_series.index.max()}.\"\n )\n\n def _merge_exog(self, df: pd.DataFrame) -> pd.DataFrame:\n self._check_regressors(df=df, df_exog=self.df_exog)\n df = pd.merge(df, self.df_exog, left_index=True, right_index=True, how=\"left\").sort_index(axis=1, level=(0, 1))\n return df\n\n def _check_endings(self):\n \"\"\"Check that all targets ends at the same timestamp.\"\"\"\n max_index = self.df.index.max()\n for segment in self.df.columns.get_level_values(\"segment\"):\n if np.isnan(self.df.loc[max_index, pd.IndexSlice[segment, \"target\"]]):\n raise ValueError(f\"All segments should end at the same timestamp\")\n\n def inverse_transform(self):\n \"\"\"Apply inverse transform method of transforms to the data.\n Applied in reversed order.\n \"\"\"\n if self.transforms is not None:\n for transform in reversed(self.transforms):\n self.df = transform.inverse_transform(self.df)\n\n @property\n def segments(self) -> List[str]:\n \"\"\"Get list of all segments in dataset.\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> ts = TSDataset(df_ts_format, \"D\")\n >>> ts.segments\n ['segment_0', 'segment_1']\n \"\"\"\n return self.df.columns.get_level_values(\"segment\").unique().tolist()\n\n def _update_regressors(self):\n result = set()\n for column in self.columns.get_level_values(\"feature\"):\n if column.startswith(\"regressor\"):\n result.add(column)\n self._regressors = list(result)\n\n @property\n def regressors(self) -> List[str]:\n \"\"\"Get list of all regressors across all segments in dataset.\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> regressors_timestamp = pd.date_range(start=\"2021-06-01\", periods=50)\n >>> df_regressors_1 = pd.DataFrame(\n ... {\"timestamp\": regressors_timestamp, \"regressor_1\": 1, \"segment\": \"segment_0\"}\n ... )\n >>> df_regressors_2 = pd.DataFrame(\n ... {\"timestamp\": regressors_timestamp, \"regressor_1\": 2, \"segment\": \"segment_1\"}\n ... )\n >>> df_exog = pd.concat([df_regressors_1, df_regressors_2], ignore_index=True)\n >>> df_exog_ts_format = TSDataset.to_dataset(df_exog)\n >>> ts = TSDataset(df_ts_format, df_exog=df_exog_ts_format, freq=\"D\")\n >>> ts.regressors\n ['regressor_1']\n \"\"\"\n return self._regressors\n\n def plot(\n self, n_segments: int = 10, column: str = \"target\", segments: Optional[Sequence[str]] = None, seed: int = 1\n ):\n \"\"\"Plot of random or chosen segments.\n\n Parameters\n ----------\n n_segments:\n number of random segments to plot\n column:\n feature to plot\n segments:\n segments to plot\n seed:\n seed for local random state\n \"\"\"\n if not segments:\n segments = self.segments\n k = min(n_segments, len(segments))\n columns_num = min(2, k)\n rows_num = math.ceil(k / columns_num)\n _, ax = plt.subplots(rows_num, columns_num, figsize=(20, 5 * rows_num), squeeze=False)\n ax = ax.ravel()\n rnd_state = np.random.RandomState(seed)\n for i, segment in enumerate(sorted(rnd_state.choice(segments, size=k, replace=False))):\n df_slice = self[:, segment, column]\n ax[i].plot(df_slice.index, df_slice.values)\n ax[i].set_title(segment)\n\n plt.show()\n\n @staticmethod\n def to_flatten(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Return pandas DataFrame with flatten index.\n\n Parameters\n ----------\n df:\n DataFrame in ETNA format.\n\n Returns\n -------\n pd.DataFrame\n with TSDataset data\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df.head(5)\n timestamp segment target\n 0 2021-06-01 segment_0 1.00\n 1 2021-06-02 segment_0 1.00\n 2 2021-06-03 segment_0 1.00\n 3 2021-06-04 segment_0 1.00\n 4 2021-06-05 segment_0 1.00\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> TSDataset.to_flatten(df_ts_format).head(5)\n timestamp target segment\n 0 2021-06-01 1.0 segment_0\n 1 2021-06-02 1.0 segment_0\n 2 2021-06-03 1.0 segment_0\n 3 2021-06-04 1.0 segment_0\n 4 2021-06-05 1.0 segment_0\n \"\"\"\n aggregator_list = []\n category = []\n segments = df.columns.get_level_values(\"segment\").unique().tolist()\n for segment in segments:\n if df[segment].select_dtypes(include=[\"category\"]).columns.to_list():\n category.extend(df[segment].select_dtypes(include=[\"category\"]).columns.to_list())\n aggregator_list.append(df[segment].copy())\n aggregator_list[-1][\"segment\"] = segment\n df = pd.concat(aggregator_list)\n df = df.reset_index()\n category = list(set(category))\n df[category] = df[category].astype(\"category\")\n df.columns.name = None\n return df\n\n def to_pandas(self, flatten: bool = False) -> pd.DataFrame:\n \"\"\"Return pandas DataFrame.\n\n Parameters\n ----------\n flatten:\n If False return pd.DataFrame with multiindex\n if True with flatten index\n\n Returns\n -------\n pd.DataFrame\n with TSDataset data\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df.head(5)\n timestamp segment target\n 0 2021-06-01 segment_0 1.00\n 1 2021-06-02 segment_0 1.00\n 2 2021-06-03 segment_0 1.00\n 3 2021-06-04 segment_0 1.00\n 4 2021-06-05 segment_0 1.00\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> ts = TSDataset(df_ts_format, \"D\")\n >>> ts.to_pandas(True).head(5)\n timestamp target segment\n 0 2021-06-01 1.0 segment_0\n 1 2021-06-02 1.0 segment_0\n 2 2021-06-03 1.0 segment_0\n 3 2021-06-04 1.0 segment_0\n 4 2021-06-05 1.0 segment_0\n >>> ts.to_pandas(False).head(5)\n segment segment_0 segment_1\n feature target target\n timestamp\n 2021-06-01 1.00 1.00\n 2021-06-02 1.00 1.00\n 2021-06-03 1.00 1.00\n 2021-06-04 1.00 1.00\n 2021-06-05 1.00 1.00\n \"\"\"\n if not flatten:\n return self.df.copy()\n return self.to_flatten(self.df)\n\n @staticmethod\n def to_dataset(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Convert pandas dataframe to ETNA Dataset format.\n\n Parameters\n ----------\n df:\n DataFrame with columns [\"timestamp\", \"segment\"]. Other columns considered features.\n\n Examples\n --------\n >>> from etna.datasets import generate_const_df\n >>> df = generate_const_df(\n ... periods=30, start_time=\"2021-06-01\",\n ... n_segments=2, scale=1\n ... )\n >>> df.head(5)\n timestamp segment target\n 0 2021-06-01 segment_0 1.00\n 1 2021-06-02 segment_0 1.00\n 2 2021-06-03 segment_0 1.00\n 3 2021-06-04 segment_0 1.00\n 4 2021-06-05 segment_0 1.00\n >>> df_ts_format = TSDataset.to_dataset(df)\n >>> df_ts_format.head(5)\n segment segment_0 segment_1\n feature target target\n timestamp\n 2021-06-01 1.00 1.00\n 2021-06-02 1.00 1.00\n 2021-06-03 1.00 1.00\n 2021-06-04 1.00 1.00\n 2021-06-05 1.00 1.00\n\n >>> df_regressors = pd.DataFrame({\n ... \"timestamp\": pd.date_range(\"2021-01-01\", periods=10),\n ... \"regressor_1\": np.arange(10), \"regressor_2\": np.arange(10) + 5,\n ... \"segment\": [\"segment_0\"]*10\n ... })\n >>> TSDataset.to_dataset(df_regressors).head(5)\n segment segment_0\n feature regressor_1 regressor_2\n timestamp\n 2021-01-01 0 5\n 2021-01-02 1 6\n 2021-01-03 2 7\n 2021-01-04 3 8\n 2021-01-05 4 9\n \"\"\"\n df[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"])\n feature_columns = df.columns.tolist()\n feature_columns.remove(\"timestamp\")\n feature_columns.remove(\"segment\")\n df = df.pivot(index=\"timestamp\", columns=\"segment\")\n df = df.reorder_levels([1, 0], axis=1)\n df.columns.names = [\"segment\", \"feature\"]\n df = df.sort_index(axis=1, level=(0, 1))\n return df\n\n def _find_all_borders(\n self,\n train_start: Optional[TTimestamp],\n train_end: Optional[TTimestamp],\n test_start: Optional[TTimestamp],\n test_end: Optional[TTimestamp],\n test_size: Optional[int],\n ) -> Tuple[TTimestamp, TTimestamp, TTimestamp, TTimestamp]:\n \"\"\"Find borders for train_test_split if some values wasn't specified.\"\"\"\n if test_end is not None and test_start is not None and test_size is not None:\n warnings.warn(\n \"test_size, test_start and test_end cannot be applied at the same time. test_size will be ignored\"\n )\n\n if test_end is None:\n if test_start is not None and test_size is not None:\n test_start_idx = self.df.index.get_loc(test_start)\n if test_start_idx + test_size > len(self.df.index):\n raise ValueError(\n f\"test_size is {test_size}, but only {len(self.df.index) - test_start_idx} available with your test_start\"\n )\n test_end_defined = self.df.index[test_start_idx + test_size]\n elif test_size is not None and train_end is not None:\n test_start_idx = self.df.index.get_loc(train_end)\n test_start = self.df.index[test_start_idx + 1]\n test_end_defined = self.df.index[test_start_idx + test_size]\n else:\n test_end_defined = self.df.index.max()\n else:\n test_end_defined = test_end\n\n if train_start is None:\n train_start_defined = self.df.index.min()\n else:\n train_start_defined = train_start\n\n if train_end is None and test_start is None and test_size is None:\n raise ValueError(\"At least one of train_end, test_start or test_size should be defined\")\n\n if test_size is None:\n if train_end is None:\n test_start_idx = self.df.index.get_loc(test_start)\n train_end_defined = self.df.index[test_start_idx - 1]\n else:\n train_end_defined = train_end\n\n if test_start is None:\n train_end_idx = self.df.index.get_loc(train_end)\n test_start_defined = self.df.index[train_end_idx + 1]\n else:\n test_start_defined = test_start\n else:\n if test_start is None:\n test_start_idx = self.df.index.get_loc(test_end_defined)\n test_start_defined = self.df.index[test_start_idx - test_size + 1]\n else:\n test_start_defined = test_start\n\n if train_end is None:\n test_start_idx = self.df.index.get_loc(test_start_defined)\n train_end_defined = self.df.index[test_start_idx - 1]\n else:\n train_end_defined = train_end\n\n if np.datetime64(test_start_defined) < np.datetime64(train_end_defined):\n raise ValueError(\"The beginning of the test goes before the end of the train\")\n\n return train_start_defined, train_end_defined, test_start_defined, test_end_defined\n\n def train_test_split(\n self,\n train_start: Optional[TTimestamp] = None,\n train_end: Optional[TTimestamp] = None,\n test_start: Optional[TTimestamp] = None,\n test_end: Optional[TTimestamp] = None,\n test_size: Optional[int] = None,\n ) -> Tuple[\"TSDataset\", \"TSDataset\"]:\n \"\"\"Split given df with train-test timestamp indices or size of test set.\n In case of inconsistencies between test_size and (test_start, test_end), test_size is ignored\n\n Parameters\n ----------\n train_start:\n start timestamp of new train dataset, if None first timestamp is used\n train_end:\n end timestamp of new train dataset, if None previous to test_start timestamp is used\n test_start:\n start timestamp of new test dataset, if None next to train_end timestamp is used\n test_end:\n end timestamp of new test dataset, if None last timestamp is used\n test_size:\n number of timestamps to use in test set\n\n Returns\n -------\n train, test:\n generated datasets\n\n Examples\n --------\n >>> from etna.datasets import generate_ar_df\n >>> pd.options.display.float_format = '{:,.2f}'.format\n >>> df = generate_ar_df(100, start_time=\"2021-01-01\", n_segments=3)\n >>> df = TSDataset.to_dataset(df)\n >>> ts = TSDataset(df, \"D\")\n >>> train_ts, test_ts = ts.train_test_split(\n ... train_start=\"2021-01-01\", train_end=\"2021-02-01\",\n ... test_start=\"2021-02-02\", test_end=\"2021-02-07\"\n ... )\n >>> train_ts.df.tail(5)\n segment segment_0 segment_1 segment_2\n feature target target target\n timestamp\n 2021-01-28 -2.06 2.03 1.51\n 2021-01-29 -2.33 0.83 0.81\n 2021-01-30 -1.80 1.69 0.61\n 2021-01-31 -2.49 1.51 0.85\n 2021-02-01 -2.89 0.91 1.06\n >>> test_ts.df.head(5)\n segment segment_0 segment_1 segment_2\n feature target target target\n timestamp\n 2021-02-02 -3.57 -0.32 1.72\n 2021-02-03 -4.42 0.23 3.51\n 2021-02-04 -5.09 1.02 3.39\n 2021-02-05 -5.10 0.40 2.15\n 2021-02-06 -6.22 0.92 0.97\n \"\"\"\n train_start_defined, train_end_defined, test_start_defined, test_end_defined = self._find_all_borders(\n train_start, train_end, test_start, test_end, test_size\n )\n\n if pd.Timestamp(test_end_defined) > self.df.index.max():\n warnings.warn(f\"Max timestamp in df is {self.df.index.max()}.\")\n if pd.Timestamp(train_start_defined) < self.df.index.min():\n warnings.warn(f\"Min timestamp in df is {self.df.index.min()}.\")\n\n train_df = self.df[train_start_defined:train_end_defined][self.raw_df.columns] # type: ignore\n train_raw_df = self.raw_df[train_start_defined:train_end_defined] # type: ignore\n train = TSDataset(df=train_df, df_exog=self.df_exog, freq=self.freq)\n train.raw_df = train_raw_df\n\n test_df = self.df[test_start_defined:test_end_defined][self.raw_df.columns] # type: ignore\n test_raw_df = self.raw_df[train_start_defined:test_end_defined] # type: ignore\n test = TSDataset(df=test_df, df_exog=self.df_exog, freq=self.freq)\n test.raw_df = test_raw_df\n\n return train, test\n\n @property\n def index(self) -> pd.core.indexes.datetimes.DatetimeIndex:\n \"\"\"Return TSDataset timestamp index.\n\n Returns\n -------\n pd.core.indexes.datetimes.DatetimeIndex\n timestamp index of TSDataset\n \"\"\"\n return self.df.index\n\n @property\n def columns(self) -> pd.core.indexes.multi.MultiIndex:\n \"\"\"Return columns of self.df.\n\n Returns\n -------\n pd.core.indexes.multi.MultiIndex\n multindex of dataframe with target and features.\n \"\"\"\n return self.df.columns\n\n @property\n def loc(self) -> pd.core.indexing._LocIndexer:\n \"\"\"Return self.df.loc method.\n\n Returns\n -------\n pd.core.indexing._LocIndexer\n dataframe with self.df.loc[...]\n \"\"\"\n return self.df.loc\n\n def isnull(self) -> pd.DataFrame:\n \"\"\"Return dataframe with flag that means if the correspondent object in self.df is null.\n\n Returns\n -------\n pd.Dataframe\n is_null dataframe\n \"\"\"\n return self.df.isnull()\n\n def head(self, n_rows: int = 5) -> pd.DataFrame:\n \"\"\"Return the first `n` rows.\n\n Mimics pandas method.\n\n This function returns the first `n` rows for the object based\n on position. It is useful for quickly testing if your object\n has the right type of data in it.\n For negative values of `n`, this function returns all rows except\n the last `n` rows, equivalent to ``df[:-n]``.\n\n Parameters\n ----------\n n_rows:\n number of rows to select.\n\n Returns\n -------\n pd.DataFrame\n the first `n` rows or 5 by default.\n \"\"\"\n return self.df.head(n_rows)\n\n def tail(self, n_rows: int = 5) -> pd.DataFrame:\n \"\"\"Return the last `n` rows.\n\n Mimics pandas method.\n\n This function returns last `n` rows from the object based on\n position. It is useful for quickly verifying data, for example,\n after sorting or appending rows.\n For negative values of `n`, this function returns all rows except\n the first `n` rows, equivalent to ``df[n:]``.\n\n Parameters\n ----------\n n_rows:\n number of rows to select.\n\n Returns\n -------\n pd.DataFrame\n the last `n` rows or 5 by default.\n\n \"\"\"\n return self.df.tail(n_rows)\n\n def describe(\n self,\n percentiles: Optional[List[float]] = None,\n include: Optional[Union[str, List[np.dtype]]] = None,\n exclude: Optional[Union[str, List[np.dtype]]] = None,\n datetime_is_numeric: bool = False,\n ) -> pd.DataFrame:\n \"\"\"Generate descriptive statistics.\n\n Mimics pandas method.\n\n Descriptive statistics include those that summarize the central\n tendency, dispersion and shape of a\n dataset's distribution, excluding ``NaN`` values.\n\n Parameters\n ----------\n percentiles : list-like of numbers, optional\n The percentiles to include in the output. All should\n fall between 0 and 1. The default is\n ``[.25, .5, .75]``, which returns the 25th, 50th, and\n 75th percentiles.\n include : 'all', list-like of dtypes or None (default), optional\n A white list of data types to include in the result. Ignored\n for ``Series``. Here are the options:\n - 'all' : All columns of the input will be included in the output.\n - A list-like of dtypes : Limits the results to the\n provided data types.\n To limit the result to numeric types submit\n ``numpy.number``. To limit it instead to object columns submit\n the ``numpy.object`` data type. Strings\n can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n select pandas categorical columns, use ``'category'``\n - None (default) : The result will include all numeric columns.\n exclude : list-like of dtypes or None (default), optional,\n A black list of data types to omit from the result. Ignored\n for ``Series``. Here are the options:\n - A list-like of dtypes : Excludes the provided data types\n from the result. To exclude numeric types submit\n ``numpy.number``. To exclude object columns submit the data\n type ``numpy.object``. Strings can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n exclude pandas categorical columns, use ``'category'``\n - None (default) : The result will exclude nothing.\n datetime_is_numeric : bool, default False\n Whether to treat datetime dtypes as numeric. This affects statistics\n calculated for the column. For DataFrame input, this also\n controls whether datetime columns are included by default.\n\n Returns\n -------\n pd.DataFrame\n Summary statistics of the TSDataset provided.\n\n \"\"\"\n return self.df.describe(percentiles, include, exclude, datetime_is_numeric)\n","sub_path":"etna/datasets/tsdataset.py","file_name":"tsdataset.py","file_ext":"py","file_size_in_byte":31500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"184289527","text":"from Node import Node\n\nclass DecisionTree:\n def __init__(self,population,attributes):\n self.root = Node('',attributes,population)\n self.root.parent = None\n self.buildTree(self.root)\n \n def buildTree(self,node,child = 'root'):\n if len(node.attributes) == 0 or node.entropy() == 0.0:#If either cannot branch anymore or there is no uncertainty\n return\n\n #Find best attribute to branch from\n attr = ''\n m = -1\n highest_information_gain = -1\n for a in node.attributes:\n node.attr = a\n node.extrema()\n \n highest_accuracy = -1\n h_g = -1\n best_margin = -1\n \n for margin in range(int(node.min),int(node.max)):\n node.branch(float(margin))\n if node.information_gain() > h_g:\n h_g = node.information_gain()\n best_margin = margin\n \n #Once you have the best margin, you can branch\n node.branch(float(best_margin))\n if node.information_gain() > highest_information_gain: #If branching using this attribute gives the most information/least entropy, save it\n highest_information_gain = node.information_gain()\n attr = node.attr\n m = best_margin\n \n node.attr = attr\n ##node.attr = node.attributes[0]\n ##node.extrema()\n ##m = (node.max +node.min)/2\n node.branch(m)\n #Remove the attribute from children nodes\n for a in range(len(node.attributes)):\n if node.attributes[a] is not node.attr:\n node.children[0].attributes.append(node.attributes[a])\n node.children[1].attributes.append(node.attributes[a])\n #print 'Parent: {}'.format(node.attributes)\n #print 'Children: {}'.format(node.children[0].attributes)\n \n self.buildTree(node.children[0],child = 'left')\n self.buildTree(node.children[1],child = 'right')\n \n def decide_gender(self,person):\n n = self.root\n while n is not None:\n attr = n.attr\n #print attr\n if not n.is_leaf() and hasattr(person,attr):\n #print n.margin\n margin = n.margin\n val = getattr(person,attr)\n if val n.females:\n return 1.0\n else: return 0.0","sub_path":"lib/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"472942527","text":"import sys \nimport numpy as np\nimport xarray as xr\n\nfrom os import listdir\nfrom os.path import isfile, join\n\narg_names = ['command', 'cmap', 'fname']\nargs = dict(zip(arg_names, sys.argv))\n\nprint(args)\nprint(\"hello from tony and the create_png_cmd app\")\n\nfrom playLib.pl_objects import Play\n\npl=Play()\n\nmypath='/mnt/ga-et-data/Cloud_Veg_ET/Data/ETO'\nfname = args['fname']\n\nfull_filename = mypath +'/' + fname\n\nary = np.load(full_filename)\n\nary = np.flip(ary, axis=0)\n\nary[(ary<0)]=0\n\namin = ary.min()\namax = ary.max()\n\nprint(amin, amax)\ndef normal(x):\n global amin\n global amax\n x = (x+amin)/(amax-amin)\n return x\n\nary = normal(ary)\n\nprint(ary.min(), ary.max())\n\ncmap=args['cmap']\noutput_file_name = './data/' + fname\npl.pl_create_png(output_file_name, ary, cmap=cmap)\n","sub_path":"01-notebooks/15-pickled-numpy-work/create_png_cmd.py","file_name":"create_png_cmd.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"571096528","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\nimport datetime\nimport time\nimport csv\nfrom torchvision import models\nimport glob\nimport os, sys\nimport random\nimport shutil\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport KPN\n\n\ndef WriteMapping(txt_root, csv_root):\n with open(csv_root, 'w', encoding='utf-8') as csv_f:\n with open(txt_root, encoding=\"UTF-8\") as txt_f:\n for line in txt_f.readlines():\n line = line.strip('\\n') # 去掉列表中每一个元素的换行符\n if(line != \"\"):\n list = line.split(' ', 4)\n id = list[0]\n code = list[1]\n csv_writer = csv.writer(csv_f)\n csv_writer.writerow([id,code])\n txt_f.close()\n csv_f.close()\n\ndef ReadMapping(csv_root):\n with open(csv_root,\"r\",encoding='utf-8') as csv_f:\n\n csv_f.close()\n\ndef CopyImage(root, target):\n dirs = os.listdir(root) # 列出所有图像的名称\n num = 5000\n sample = random.sample(dirs, num)\n print(sample)\n for name in sample:\n if os.path.exists(root + name):\n shutil.copy(root + name, target + name)\n else:\n continue\n\ndef Resize(root):\n path_to_images = root\n all_images = glob.glob(path_to_images + '*')\n for i, image_file in enumerate(all_images):\n im = Image.open(image_file)\n im = im.resize((224, 224), resample=Image.LANCZOS)\n im.save(image_file)\n if i % 500 == 0:\n print(i)\n\ndef Save_Image(dir,image):\n image = image.permute(1, 2, 0).cpu().detach().numpy()\n image = image * [0.5, 0.5, 0.5] + [0.5, 0.5, 0.5]\n image = image * 255.0\n image = np.clip(image, 0, 255)\n image = image.astype(np.uint8)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n cv2.imwrite(dir, image)\n\ndef Save_NoiseAndDenoise_Image(root_dir, noise_dir, denoise_dir, load_model_dir):\n net = KPN.KPN().cuda()\n net.load_state_dict(torch.load(load_model_dir))\n net.eval()\n data_transforms = transforms.Compose([\n # transforms.Resize(256),\n # transforms.RandomResizedCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n\n images = os.listdir(root_dir)\n for i in range(len(images)):\n img_path = os.path.join(root_dir, images[i])\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = data_transforms(img)\n\n noise_img = np.random.normal(0, 30, img.shape).astype(np.float32)\n noise_img = noise_img / 255.0\n noisy_img = img + noise_img\n save_noise_path = os.path.join(noise_dir, images[i])\n Save_Image(save_noise_path, noisy_img)\n\n true_input = noisy_img.unsqueeze(0).cuda()\n output = net(true_input, true_input)\n denoise_img = output.squeeze(0)\n save_denoise_path = os.path.join(denoise_dir, images[i])\n Save_Image(save_denoise_path, denoise_img)\n\ndef Valiation(net, class_map_dir):\n class_map = {}\n with open(class_map_dir, 'r') as csv_f:\n reader = csv.reader(csv_f, delimiter=',')\n last_label = ''\n for i, row in enumerate(reader):\n id = row[0]\n code = row[1]\n class_map[code] = id\n\n\n\nif __name__ == '__main__':\n # WriteMapping(\"C:/Users/lab-301/Desktop/1.txt\", \"C:/Users/lab-301/Desktop/classMap.csv\")\n\n # rootDir = \"D:/mini_ImageNet/images/\"\n # tarDir = \"D:/PycharmProjects/proc_images/samples/\"\n # CopyImage(rootDir,tarDir)\n # Resize(tarDir)\n\n image_gt_dir = \"./image_gt\"\n image_noisy_dir = \"./image_noisy\"\n image_pred_dir = \"./image_pred\"\n # load_model_dir = \"./KPNmodels/KPN_epoch20.pth\"\n # Save_NoiseAndDenoise_Image(image_gt_dir, image_noisy_dir, image_pred_dir, load_model_dir)\n\n net = models.resnet50(pretrained=True)\n class_map_dir = \"./classMap.csv\"\n Valiation(net, class_map_dir)\n\n","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"238275975","text":"# -*- coding:utf-8 -*-\n\nimport StockIO\nimport StockConfig\nimport StockIndicator\nimport numpy as np\nimport StockFilterWrapper\nimport StockAlgrithm\nimport StockFilter2\n\n@StockFilterWrapper.filtrate_stop_trade\ndef select(stock_list, x_position=-1, min_item=10):\n \"\"\"\n 均线选股法\n :param stock_list:\n :param kline_type:\n :param avg:\n :return:\n \"\"\"\n result = []\n for stock in stock_list:\n try:\n kline = StockIO.get_kline(stock.stock_code, kline_type=StockConfig.kline_type_day)\n except:\n continue\n if kline.shape[0] < min_item:\n continue\n open = kline[:, 1].astype(np.float)\n close = kline[:, 2].astype(np.float)\n sma5, sma10, sma20 = StockIndicator.sma(kline, 5, 10, 20)\n vb = StockIndicator.vibration(kline)\n chg = StockIndicator.chg(kline)\n chg_compress = StockAlgrithm.compress_array(chg)\n if chg[x_position] < 0:\n if sma5[x_position] > sma10[x_position] and sma5[x_position] > sma20[x_position]:\n if chg_compress[-2] + chg_compress[-1] > 0:\n print(stock)\n result.append(stock)\n\n return result\n\n\nif __name__ == '__main__':\n result={}\n # for x in range(-10, 0):\n # print('x = ', x)\n # stock_list = select(StockIO.get_stock('sha'), x_position=x, kline_type=StockConfig.kline_type_week)\n # print(stock_list)\n #\n # for stock in stock_list:\n # result[stock] = result.get(stock, 0) + 1\n #\n # with open('{}/{}'.format(StockConfig.path_stock, 'wsma10'), 'w', encoding='utf-8') as f:\n # for key in result:\n # if result[key] >= 7:\n # f.write(\"{},{}\\n\".format(key.stock_code, key.stock_name))\n #\n # print(sorted(result.items(), key=lambda d: d[1], reverse=True))\n date = '2017-10-09'\n position = StockIndicator.position(date, '000001')\n stock_list = select(StockIO.get_stock('sza'), x_position=-1)\n stock_list2 = select(StockIO.get_stock('sha'), x_position=-1)\n stock_list = stock_list + stock_list2\n print(len(stock_list))\n with open('C:/Users/panha/Desktop/xgfx/1002.txt', mode='w', encoding='utf-8') as f:\n for key in stock_list:\n f.write(\"{}\\n\".format(key.stock_code))\n\n\n\n","sub_path":"StockSelector2_3.py","file_name":"StockSelector2_3.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"246149917","text":"# Copyright (C) 2010-2011 Richard Lincoln\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nfrom CIM14.CDPSM.Balanced.IEC61970.Core.IdentifiedObject import IdentifiedObject\n\nclass ToWindingSpec(IdentifiedObject):\n \"\"\"For short-circuit tests, specifies the winding and tap for all short-circuited windings. \r For open-circuit tests, specifies the winding, tap, induced voltage, and induced angle for any non-excited windings that were measured during the test. This won't apply if only the exciting current and no-load losses were measured.\n \"\"\"\n\n def __init__(self, toTapStep=0, voltage=0.0, phaseShift=0.0, OpenCircuitTests=None, ShortCircuitTests=None, ToWinding=None, *args, **kw_args):\n \"\"\"Initialises a new 'ToWindingSpec' instance.\n\n @param toTapStep: Tap step number for the 'to' winding of the test pair. \n @param voltage: (if open-circuit test) Voltage measured at the open-circuited 'to' winding, with the 'from' winding set to the 'from' winding's rated voltage and all other windings open-circuited. \n @param phaseShift: (if open-circuit test) Phase shift measured at the open-circuited 'to' winding, with the 'from' winding set to the 'from' winding's rated voltage and all other windings open-circuited. \n @param OpenCircuitTests: All open-circuit tests in which this winding was measured.\n @param ShortCircuitTests: All short-circuit tests in which this winding was short-circuited.\n @param ToWinding: Winding short-circuited in a short-circuit test, or measured for induced voltage and angle in an open-circuit test.\n \"\"\"\n #: Tap step number for the 'to' winding of the test pair.\n self.toTapStep = toTapStep\n\n #: (if open-circuit test) Voltage measured at the open-circuited 'to' winding, with the 'from' winding set to the 'from' winding's rated voltage and all other windings open-circuited.\n self.voltage = voltage\n\n #: (if open-circuit test) Phase shift measured at the open-circuited 'to' winding, with the 'from' winding set to the 'from' winding's rated voltage and all other windings open-circuited.\n self.phaseShift = phaseShift\n\n self._OpenCircuitTests = []\n self.OpenCircuitTests = [] if OpenCircuitTests is None else OpenCircuitTests\n\n self._ShortCircuitTests = []\n self.ShortCircuitTests = [] if ShortCircuitTests is None else ShortCircuitTests\n\n self._ToWinding = None\n self.ToWinding = ToWinding\n\n super(ToWindingSpec, self).__init__(*args, **kw_args)\n\n _attrs = [\"toTapStep\", \"voltage\", \"phaseShift\"]\n _attr_types = {\"toTapStep\": int, \"voltage\": float, \"phaseShift\": float}\n _defaults = {\"toTapStep\": 0, \"voltage\": 0.0, \"phaseShift\": 0.0}\n _enums = {}\n _refs = [\"OpenCircuitTests\", \"ShortCircuitTests\", \"ToWinding\"]\n _many_refs = [\"OpenCircuitTests\", \"ShortCircuitTests\"]\n\n def getOpenCircuitTests(self):\n \"\"\"All open-circuit tests in which this winding was measured.\n \"\"\"\n return self._OpenCircuitTests\n\n def setOpenCircuitTests(self, value):\n for p in self._OpenCircuitTests:\n filtered = [q for q in p.MeasuredWindingSpecs if q != self]\n self._OpenCircuitTests._MeasuredWindingSpecs = filtered\n for r in value:\n if self not in r._MeasuredWindingSpecs:\n r._MeasuredWindingSpecs.append(self)\n self._OpenCircuitTests = value\n\n OpenCircuitTests = property(getOpenCircuitTests, setOpenCircuitTests)\n\n def addOpenCircuitTests(self, *OpenCircuitTests):\n for obj in OpenCircuitTests:\n if self not in obj._MeasuredWindingSpecs:\n obj._MeasuredWindingSpecs.append(self)\n self._OpenCircuitTests.append(obj)\n\n def removeOpenCircuitTests(self, *OpenCircuitTests):\n for obj in OpenCircuitTests:\n if self in obj._MeasuredWindingSpecs:\n obj._MeasuredWindingSpecs.remove(self)\n self._OpenCircuitTests.remove(obj)\n\n def getShortCircuitTests(self):\n \"\"\"All short-circuit tests in which this winding was short-circuited.\n \"\"\"\n return self._ShortCircuitTests\n\n def setShortCircuitTests(self, value):\n for p in self._ShortCircuitTests:\n filtered = [q for q in p.ShortedWindingSpecs if q != self]\n self._ShortCircuitTests._ShortedWindingSpecs = filtered\n for r in value:\n if self not in r._ShortedWindingSpecs:\n r._ShortedWindingSpecs.append(self)\n self._ShortCircuitTests = value\n\n ShortCircuitTests = property(getShortCircuitTests, setShortCircuitTests)\n\n def addShortCircuitTests(self, *ShortCircuitTests):\n for obj in ShortCircuitTests:\n if self not in obj._ShortedWindingSpecs:\n obj._ShortedWindingSpecs.append(self)\n self._ShortCircuitTests.append(obj)\n\n def removeShortCircuitTests(self, *ShortCircuitTests):\n for obj in ShortCircuitTests:\n if self in obj._ShortedWindingSpecs:\n obj._ShortedWindingSpecs.remove(self)\n self._ShortCircuitTests.remove(obj)\n\n def getToWinding(self):\n \"\"\"Winding short-circuited in a short-circuit test, or measured for induced voltage and angle in an open-circuit test.\n \"\"\"\n return self._ToWinding\n\n def setToWinding(self, value):\n if self._ToWinding is not None:\n filtered = [x for x in self.ToWinding.ToWindingSpecs if x != self]\n self._ToWinding._ToWindingSpecs = filtered\n\n self._ToWinding = value\n if self._ToWinding is not None:\n if self not in self._ToWinding._ToWindingSpecs:\n self._ToWinding._ToWindingSpecs.append(self)\n\n ToWinding = property(getToWinding, setToWinding)\n\n","sub_path":"CIM14/CDPSM/Balanced/IEC61968/AssetModels/ToWindingSpec.py","file_name":"ToWindingSpec.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"317063635","text":"import sys; sys.dont_write_bytecode = True; from utils import *\n\ndef do_case(inp: str, sample=False):\n # READ THE PROBLEM FROM TOP TO BOTTOM OK\n def sprint(*a, **k): sample and print(*a, **k)\n lines = inp.splitlines()\n paras = inp.split(\"\\n\\n\")\n out = 0\n\n d = []\n allergens = set()\n allergen_to_things = defaultdict(list)\n\n for line in lines:\n thing, contains = line.split(\" (contains \")\n contains = contains.rstrip(\")\").split(\", \")\n thing = set(thing.split())\n d.append([thing, contains])\n allergens.update(contains)\n for allergen in contains:\n allergen_to_things[allergen].append(thing)\n # sprint(allergen_to_things)\n # sprint(allergens)\n\n thing_to_allergen = {}\n allergen_to_thing = {}\n good = True\n while good:\n good = False\n for allergen in allergen_to_things:\n if allergen in thing_to_allergen:\n continue\n things = allergen_to_things[allergen]\n possible = functools.reduce(operator.__and__, map(frozenset,things))\n possible -= set(thing_to_allergen)\n # sprint(allergen, things, possible)\n if len(possible) == 1:\n thing_to_allergen[next(iter(possible))] = allergen\n allergen_to_thing[allergen] = next(iter(possible))\n good = True\n \n found = set(thing_to_allergen)\n for allergen in allergen_to_things:\n if allergen in thing_to_allergen:\n continue\n things = allergen_to_things[allergen]\n possible = functools.reduce(operator.__and__, map(frozenset,things))\n possible -= set(thing_to_allergen)\n found.update(possible)\n \n \n \n sprint(thing_to_allergen)\n for thing, contains in d:\n for x in thing:\n if x not in found:\n out+=1\n assert len(thing_to_allergen) == len(allergens)\n blah = [(thing_to_allergen[key], key) for key in thing_to_allergen]\n blah.sort()\n print(\",\".join(map(snd, blah)))\n\n \n if out:\n print(\"out: \", out)\n return # RETURNED VALUE DOESN'T DO ANYTHING, PRINT THINGS INSTEAD\n\n\n\nrun_samples_and_actual([\nr\"\"\"\nmxmxvkd kfcds sqjhc nhms (contains dairy, fish)\ntrh fvjkl sbzzf mxmxvkd (contains dairy)\nsqjhc fvjkl (contains soy)\nsqjhc mxmxvkd sbzzf (contains fish)\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\"], do_case)\n","sub_path":"2020/21/a-p2.py","file_name":"a-p2.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"26222294","text":"class Node(object):\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n def __lt__(self, val):\n return self.val < val\n\n def __gt__(self, val):\n return self.val > val\n\n def __eq__(self, val):\n return self.val == val\n\n def __str__(self):\n return \"[Node val: %d]\" % self.val \n\nclass Tree(object):\n def __init__(self):\n self.root = None\n\n def put(self, val):\n self.root = self._put(self.root, val)\n\n def _put(self, node, val):\n if node is None:\n node = Node(val)\n\n if val < node:\n node.left = self._put(node.left, val)\n elif val > node:\n node.right = self._put(node.right, val)\n else:\n node.val = val\n\n return node\n\n #def get(self, val):\n # return self._get(self.root, val) # coverage\n\n def _get(self, node, val):\n while not node is None:\n if val < node:\n node = node.left\n elif val > node:\n node = node.right\n else:\n return node.val\n\n return None\n\n # This method returns `None` if no common is found\n def find_common_ancestor(self, a, b):\n return self._find_common_ancestor(self.root, a, b)\n\n def _find_common_ancestor(self, node, a, b):\n # Traverse right until a diverge occurs\n if a > node and b > node:\n if node.right is None:\n return None # coverage\n\n # if right node is `a` or `b` then we found common\n if node.right == a or node.right == b:\n return node.val\n\n return self._find_common_ancestor(node.right, a, b)\n\n # Traverse left until a diverge occurs\n elif a < node and b < node:\n if node.left is None:\n return None # coverage\n\n # if left node is `a` or `b` then we found common\n if node.left == a or node.left == b:\n return node.val\n\n return self._find_common_ancestor(node.left, a, b)\n\n # root does not have any common ancestor\n # This test is later because we dont want the\n # recursion to hit it every time\n elif a == self.root or b == self.root:\n return None # coverage says no but it's covered by \n\n else:\n # A diverge of the tree traversal occurs here\n # So the current node is a potential common ancestor\n # Verify that a and b are legitimate nodes\n if self._node_exists(node, a):\n # `a` exists ensure `b` exists\n if self._node_exists(node, b):\n # Common ancestor is validated\n return node.val\n else:\n return None # coverage\n else:\n return None\n\n #def node_exists(self, val):\n # return self._node_exists(self.root, val) # coverage\n\n def _node_exists(self, node, val):\n return not self._get(node, val) is None\n\n \n def traverse(self, root):\n current_level = [root]\n count = 0\n while current_level:\n print(' '.join(str(node) for node in current_level))\n next_level = list()\n for n in current_level:\n if n.left:\n next_level.append(n.left)\n if n.right:\n next_level.append(n.right)\n current_level = next_level\n count += 1\n return count\n\nif __name__ == \"__main__\":\n from sys import stdout\n vals = [30, 8, 52, 3, 20, 10, 29, 62]\n tree = Tree()\n [tree.put(val) for val in vals]\n pairs = [\n (3, 20),\n (3, 29),\n (10, 29),\n (20, 52),\n (3, 62),\n (4, 29),\n (3, 1),\n (8, 3),\n (8, 20)\n ]\n \n tree.traverse(tree.root)\n print()\n \n for (a, b) in pairs:\n stdout.write(\"Common for %d & %d: \" % (a, b))\n print(tree.find_common_ancestor(a, b))\n\n","sub_path":"GraphsCS3012/GraphCS3012.py","file_name":"GraphCS3012.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"431052407","text":"from flask import Flask, render_template\nfrom picamera import PiCamera\nimport time,os,random\n\nvideoName = None\ngestartet = False\ncam = None\ndisk = None\n\nsensor_mode = 4\nresolution = (1920,1080)\nfps = 30\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n global cam\n if(cam==None):\n cam = PiCamera(sensor_mode=sensor_mode,resolution=resolution,framerate=fps)\n cam.vflip = True\n\n global disk\n statvfs = os.statvfs('/')\n disk=round(statvfs.f_frsize*statvfs.f_bavail/2**30,2)\n\n cam.capture(\"static/img/vorschau.jpg\")\n #time.sleep(4)\n \n if not gestartet:\n return render_template('starten.html',random=str(random.randint(1,100000)),disk=disk)\n else:\n return render_template('stoppen.html',random=str(random.randint(1,100000)),disk=disk)\n \n@app.route('/starten',methods=['POST'])\ndef starten():\n global gestartet\n gestartet = True\n\n global videoName\n videoName = time.strftime(\"%d%m%y%H%M%S\",time.localtime())\n cam.start_recording(\"static/video/h264/{0}.h264\".format(videoName))\n \n return render_template('stoppen.html',random=str(random.randint(1,100000)),disk=disk)\n \n@app.route('/stoppen',methods=['POST'])\ndef stoppen():\n global gestartet\n gestartet = False\n\n cam.stop_recording()\n #os.system(\"MP4Box -fps {0} -add {1} {2}\".format(fps,\"static/video/h264/{0}.h264\".format(videoName),\"static/video/mp4/{0}.mp4\".format(videoName))) \n\n return render_template('starten.html',random=str(random.randint(1,100000)),disk=disk)\n\n@app.route('/neustarten',methods=['POST'])\ndef neustarten():\n os.system(\"sudo shutdown -r now\")\n \nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"141676265","text":"import subprocess\r\nfrom bottle import run, post, request, response, get, route\r\nimport slack, time\r\nfrom PIL import Image\r\nfrom PIL import ImageFont\r\nfrom PIL import ImageDraw\r\nimport requests, json\r\nimport imageio\r\nimport threading\r\n\r\n# <@U0216GLKBTR> my id\r\n# <@U021TGL7FV2> bot id\r\nclient = slack.WebClient(token='xoxb-2055336641954-2061564253988-ObJXQamuq1YSqxao9gqs3y1X')\r\n#client = slack.WebClient(token='xoxp-2055336641954-2040564657943-2048421007543-a6b5ca53ebd029bd187ea755b4b5c8d0')\r\n\r\ntest_id = \"C022B45ANL8\"\r\ngen_id = \"C021TENLBLL\"\r\nts = \"1620835912.000300\" # ts of message to edit\r\n\r\nUKG_TEAL = (48, 206, 187)\r\nUKG_DARK = (0, 81, 81)\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\n\r\ndadurl = \"https://icanhazdadjoke.com/slack\"\r\ndef get_dad_joke():\r\n x = requests.get(dadurl)\r\n return x.json()[\"attachments\"][0][\"text\"]\r\n\r\ndef generate_timer_gif(at, total):\r\n frames = min(30, total-at)\r\n at_pos = 0\r\n filenames = []\r\n while frames > 0:\r\n filenames.append(create_timer_img(total - (at+at_pos), at_pos))\r\n frames -= 1\r\n at_pos += 1\r\n \r\n images = []\r\n for filename in filenames:\r\n images.append(imageio.imread(filename))\r\n imageio.mimsave('movie.gif', images, format='GIF', fps=1, loop=1)\r\n\r\ndef create_timer_img(timestamp, iter=0):\r\n image = Image.new(\"RGBA\", (800, 600), UKG_TEAL)\r\n draw = ImageDraw.Draw(image)\r\n font = ImageFont.truetype(\"Roboto-Bold.ttf\", 156)\r\n tm = time.strftime('%H:%M:%S', time.gmtime(timestamp))\r\n draw.text((85, 215), tm, UKG_DARK, font=font)\r\n image.save(f\"timer{iter}.png\")\r\n return f\"timer{iter}.png\"\r\n\r\ndef send_image(ts, filename):\r\n upload_result = client.files_upload(channels=test_id, file=filename)\r\n del_ts = client.conversations_history(channel=test_id, limit=1)[\"messages\"][0][\"ts\"]\r\n deleted = client.chat_delete(channel=test_id,ts=del_ts)\r\n\r\n pub_url = upload_result[\"file\"][\"permalink_public\"]\r\n TFP = pub_url.split('/')[3]\r\n TFP_arr = TFP.split('-')\r\n new_url = f\"https://files.slack.com/files-pri/{TFP_arr[0]}-{TFP_arr[1]}/{filename}\"\r\n\r\n attch = [\r\n {\r\n \"fallback\": \"Required plain-text summary of the attachment.\",\r\n \"image_url\": new_url,\r\n \"thumb_url\": new_url,\r\n }\r\n ]\r\n \r\n result = client.chat_update(channel=gen_id, ts=ts, text=\"\", attachments = attch)\r\n\r\ndef run_timer(timer_amn):\r\n seconds_since_start = 0\r\n client.chat_postMessage(channel=gen_id, text=\"Starting Timer...\")\r\n ts = client.conversations_history(channel=gen_id, limit=1)[\"messages\"][0][\"ts\"]\r\n\r\n generate_timer_gif(0, timer_amn)\r\n \r\n curr_time = prev_time = int(time.time())\r\n while seconds_since_start < timer_amn:\r\n send_image(ts, \"movie.gif\")\r\n generate_timer_gif(seconds_since_start+30, timer_amn)\r\n next_time_inc = min(timer_amn-seconds_since_start, 30)\r\n while curr_time < prev_time + next_time_inc:\r\n curr_time = int(time.time())\r\n seconds_since_start += curr_time-prev_time\r\n prev_time = curr_time\r\n\r\n create_timer_img(0)\r\n send_image(ts, \"timer0.png\")\r\n client.chat_postMessage(channel=gen_id, text=\" Time's up! \" + get_dad_joke())\r\n\r\n@route('/',method = 'POST')\r\ndef process(path):\r\n #path = \"joke\"\r\n print(path)\r\n if path == \"joke\":\r\n client.chat_postMessage(channel=gen_id, text=get_dad_joke())\r\n elif path == \"agar\":\r\n client.chat_postMessage(channel=gen_id, text=\"https://agar.io/\")\r\n elif path == \"jspaint\":\r\n client.chat_postMessage(channel=gen_id, text=\"https://jspaint.app/\")\r\n elif path == \"timer\":\r\n x = threading.Thread(target=run_timer, args=(90,))\r\n x.start()\r\n return response\r\n\r\n# ngrok http 8080\r\nrun(host='localhost', port=8080)","sub_path":"servertest.py","file_name":"servertest.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"42229119","text":"\"\"\"\nGiven an array of n positive integers and a positive integer s, find the minimal length of a subarray of\nwhich the sum >= s. If there isn't one, return -1 instead.\n\nExample:\nGiven the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.\n\n\"\"\"\n\n\nclass Solution:\n # @param nums: a list of integers\n # @param s: an integer\n # @return: an integer representing the minimum size of subarray\n def minimumSize(self, nums, s):\n start, end, sum = 0, 0, 0\n size = len(nums)\n res = size + 1\n while start < size:\n while end < size and sum < s:\n sum += nums[end]\n end += 1\n\n # check if resulat meets requirement\n if sum >= s:\n res = min(res, end - start)\n\n sum -= nums[start]\n start += 1\n\n if res == size+1:\n res = -1\n return res","sub_path":"TwoPointers/MinimumSizeSubarraySum.py","file_name":"MinimumSizeSubarraySum.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"19366865","text":"\"\"\"Utilities for Updating data.json catalog\"\"\"\nimport re, base64, os\nimport logging\nimport random\nfrom datetime import datetime\nfrom airflow.operators.python_operator import PythonOperator\nfrom trident.util import general\nfrom trident.util.notifications import afsys_send_email\nimport json\n\n\nconf = general.config\n\ndef update_json_date(ds_fname, **kwargs):\n \n exec_date = kwargs['execution_date'].strftime(\"%Y-%m-%d\")\n test_mode = kwargs['test_mode']\n\n logging.info(f\"Looking for {ds_fname}\")\n\n json_path = f\"{conf['prod_data_dir']}/data.json\"\n\n with open(json_path) as json_file:\n data = json.load(json_file)\n\n # if test_mode is not True:\n\n for dataset in data['dataset']:\n if ds_fname == dataset['identifier']:\n prev_date = dataset['modified']\n if prev_date != exec_date:\n dataset['modified'] = exec_date\n # Need stuff in here to upload to Netlify\n else:\n return f\"{ds_fname} already matches {exec_date}\"\n\n with open (json_path, 'w') as outfile:\n json.dump(data, outfile, indent=4)\n\n return \"Successfully checked date updated\"\n\ndef update_datajson_dag(ds_fname, dag):\n task = PythonOperator(\n task_id=f\"update_{ds_fname}\",\n python_callable=update_json_date,\n provide_context=True,\n op_kwargs={'ds_fname': ds_fname},\n \n on_retry_callback=notify,\n on_success_callback=notify,\n dag=dag)\n\n return task\n","sub_path":"poseidon/trident/util/datajson_updates.py","file_name":"datajson_updates.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"421416182","text":"\"\"\"\nCheck the availabitlity of yahoo quotes for companies.\n\nSet the new field \"yahoo_quotes\" with values 0 or 1.\n\"\"\"\n\nimport datetime\nimport pandas_datareader.data as web\nfrom pymongo import MongoClient\n\n\nstart = datetime.datetime(2008, 1, 1)\nend = datetime.datetime(2016, 6, 30)\n\nmongo_con = MongoClient()\nstocktwits_original_tickers_db = (mongo_con['stocktwits']\n ['stocktwits.stocktwits_original_tickers'])\n# stocktwits_original_quotes_db = (mongo_con['stocktwits']\n# ['yahoo_original_quotes'])\n\ntickers = (stocktwits_original_tickers_db.\n find().\n sort(\"count\", -1).\n limit(150).batch_size(50))\ncounter = 0\nfor ticker in tickers:\n try:\n quotes = web.DataReader(ticker['_id'], 'yahoo', start, end)\n quotes.reset_index(level=0, inplace=True)\n quotes_mongoed = quotes.to_dict('records')\n for day in quotes_mongoed:\n t = str(day['Date'])\n # print t\n day['Date'] = datetime.datetime.strptime(t, \"%Y-%m-%d %H:%M:%S\")\n day['symbol'] = ticker['_id']\n # stocktwits_original_quotes_db.insert(day)\n stocktwits_original_tickers_db.update({\"_id\": ticker[\"_id\"]},\n {\"$set\": {\"yahoo_quotes\": 1}}\n )\n counter += 1\n print(str(counter))\n print(ticker['_id'])\n except:\n print(\"No Yahoo quotes for ticker\" + ticker['_id'])\n stocktwits_original_tickers_db.update({\"_id\": ticker[\"_id\"]},\n {\"$set\": {\"yahoo_quotes\": 0}}\n )\n\nmongo_con.close()\n","sub_path":"1_crowd/5_get_yahoo_quotes.py","file_name":"5_get_yahoo_quotes.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"375674571","text":"from context import fractal\nfrom fractal.dataloader import Loader\nfrom fractal import utils\nfrom fractal.plotting import plot_image\nfrom fractal.coding import encode_svd, decode_svd\nfrom skimage.transform import rescale\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\nimport argparse\nimport os\n\nMODE = 'equipartition8'\n\ndef save_contractiveness_factors(domain_chunks, iternum):\n num_weights = len(domain_chunks[0].ravel())\n X = np.zeros([num_weights, len(domain_chunks)])\n\n for i in range(len(domain_chunks)):\n X[:, i] = np.ravel(domain_chunks[i])\n\n u, s, vh = np.linalg.svd(X)\n\n R = np.dot(np.diag(s), vh[:len(s), :len(s)])\n\n df = None\n for idx, weights in enumerate(codebook):\n print(f'saving contractiveness factors for block {idx}/{len(codebook)}, iteration {iternum}')\n contractiveness = np.dot(np.linalg.inv(R), weights.reshape(num_weights,1))\n\n contractiveness = np.array([idx] + \\\n contractiveness.ravel().tolist())[np.newaxis, :]\n if df is None:\n df = pd.DataFrame(contractiveness)\n else:\n df = df.append(pd.DataFrame(contractiveness))\n\n df.to_csv(f\"contractiveness_{iternum}.csv\")\n\nparser = argparse.ArgumentParser(description='select image')\nparser.add_argument('--imagepath', type=str)\n\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n ############################################################################\n # load the first face image\n ############################################################################\n images = Loader(\"\", regex=args.imagepath)\n range_image = images.get_image(0, scale_factor=1)\n\n # plot it so we know what it looks like\n plot_image(range_image, \n title=f\"Range Image {range_image.shape[0]}x{range_image.shape[1]}\",\n cmap='gray')\n\n ############################################################################\n # divide up the first image into chunks\n ############################################################################\n # domain image is a 50% downsampled range image\n domain_image = images.get_image(0, scale_factor=1/2)\n\n plot_image(domain_image, \n title=f\"Domain Image {domain_image.shape[0]}x{domain_image.shape[1]}\",\n cmap='gray')\n\n # each block is 4x4\n domain_chunks = utils.Partition(domain_image, mode=MODE)\n range_chunks = utils.Partition(range_image, mode=MODE)\n print(\"partitioned\")\n\n ############################################################################\n # encode the range image\n ############################################################################\n codebook = encode_svd(domain_chunks, range_chunks, verbose=False)\n # codebook[:, 8:] = 0\n\n # facedir = Path(__file__).resolve().parent.parent / \"data\" / \"faces\"\n if args.imagepath == 'mandrill.jpg':\n facedir = Path(__file__).resolve().parent.parent / \"data\"\n aaronface = Image.open(list(facedir.glob(\"lena_gray.jpg\"))[0])\n print(aaronface)\n aaronface = np.asarray(aaronface.getdata()).reshape(512,512)\n aaronface = rescale(aaronface, 0.25)\n else:\n facedir = Path(__file__).resolve().parent.parent / \"data\"\n aaronface = Image.open(list(facedir.glob(\"mandrill.jpg\"))[0])\n aaronface = np.asarray(aaronface.getdata()).reshape(512,512)\n aaronface = rescale(aaronface, 0.25)\n # aaronface = np.asarray(aaronface.getdata()).reshape(64,64)\n\n # aaronface = images.get_image(0, scale_factor=0.125/2)\n plot_image(aaronface, \n title=f\"Domain Image {aaronface.shape[0]}x{aaronface.shape[1]}\",\n cmap='gray')\n\n domain_chunks = utils.Partition(aaronface, mode=MODE)\n reconstructed_chunks = decode_svd(codebook, domain_chunks)\n\n # save_contractiveness_factors(domain_chunks, 1)\n \n for i in range(26):\n rec_dim = rescale(reconstructed_chunks.image, 0.5) \n domain_chunks = utils.Partition(rec_dim, mode=MODE)\n # save_contractiveness_factors(domain_chunks, i)\n reconstructed_chunks = decode_svd(codebook, domain_chunks)\n if i in [1, 5, 10, 20, 25]:\n plot_image(reconstructed_chunks.image, \n title=f\"Reconstructed Image {i} iterations \\n{reconstructed_chunks.image.shape[0]}x{reconstructed_chunks.image.shape[0]} ({MODE})\", \n cmap='gray', y=0.98)\n print(f\"residual: {i}, {np.sum((range_image - reconstructed_chunks.image)**2)}\")\n\n\n # pd.DataFrame(reconstructed_chunks.image).to_csv(\"reconstruction.csv\")\n\n\n","sub_path":"bin/main_svd.py","file_name":"main_svd.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"262874300","text":"\"\"\"\nInstrumental variable estimators\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nfrom numpy import (any, array, asarray, average, c_, isscalar, logical_not,\n ones, sqrt, nanmean)\nfrom numpy.linalg import eigvalsh, inv, matrix_rank, pinv\nfrom pandas import DataFrame, Series\nfrom scipy.optimize import minimize\n\nfrom linearmodels.iv._utility import parse_formula\nfrom linearmodels.iv.covariance import (ClusteredCovariance,\n HeteroskedasticCovariance,\n HomoskedasticCovariance,\n KernelCovariance)\nfrom linearmodels.iv.data import IVData\nfrom linearmodels.iv.gmm import (HeteroskedasticWeightMatrix,\n HomoskedasticWeightMatrix, IVGMMCovariance,\n KernelWeightMatrix,\n OneWayClusteredWeightMatrix)\nfrom linearmodels.iv.results import IVGMMResults, IVResults, OLSResults\nfrom linearmodels.utility import (WaldTestStatistic, has_constant, inv_sqrth,\n missing_warning)\n\n__all__ = ['COVARIANCE_ESTIMATORS', 'WEIGHT_MATRICES', 'IVGMM', 'IVLIML', 'IV2SLS',\n 'IVGMMCUE', '_OLS']\n\nCOVARIANCE_ESTIMATORS = {'homoskedastic': HomoskedasticCovariance,\n 'unadjusted': HomoskedasticCovariance,\n 'HomoskedasticCovariance': HomoskedasticCovariance,\n 'homo': HomoskedasticCovariance,\n 'robust': HeteroskedasticCovariance,\n 'heteroskedastic': HeteroskedasticCovariance,\n 'HeteroskedasticCovariance': HeteroskedasticCovariance,\n 'hccm': HeteroskedasticCovariance,\n 'kernel': KernelCovariance,\n 'KernelCovariance': KernelCovariance,\n 'one-way': ClusteredCovariance,\n 'clustered': ClusteredCovariance,\n 'OneWayClusteredCovariance': ClusteredCovariance}\n\nWEIGHT_MATRICES = {'unadjusted': HomoskedasticWeightMatrix,\n 'homoskedastic': HomoskedasticWeightMatrix,\n 'robust': HeteroskedasticWeightMatrix,\n 'heteroskedastic': HeteroskedasticWeightMatrix,\n 'kernel': KernelWeightMatrix,\n 'clustered': OneWayClusteredWeightMatrix,\n 'one-way': OneWayClusteredWeightMatrix\n }\n\n\nclass IVLIML(object):\n r\"\"\"\n Limited information ML and k-class estimation of IV models\n\n Parameters\n ----------\n dependent : array-like\n Endogenous variables (nobs by 1)\n exog : array-like\n Exogenous regressors (nobs by nexog)\n endog : array-like\n Endogenous regressors (nobs by nendog)\n instruments : array-like\n Instrumental variables (nobs by ninstr)\n weights : array-like, optional\n Observation weights used in estimation\n fuller : float, optional\n Fuller's alpha to modify LIML estimator. Default returns unmodified\n LIML estimator.\n kappa : float, optional\n Parameter value for k-class estimation. If not provided, computed to\n produce LIML parameter estimate.\n\n Notes\n -----\n ``kappa`` and ``fuller`` should not be used simultaneously since Fuller's\n alpha applies an adjustment to ``kappa``, and so the same result can be\n computed using only ``kappa``. Fuller's alpha is used to adjust the\n LIML estimate of :math:`\\kappa`, which is computed whenever ``kappa``\n is not provided.\n\n The LIML estimator is defined as\n\n .. math::\n\n \\hat{\\beta}_{\\kappa} & =(X(I-\\kappa M_{z})X)^{-1}X(I-\\kappa M_{z})Y\\\\\n M_{z} & =I-P_{z}\\\\\n P_{z} & =Z(Z'Z)^{-1}Z'\n\n where :math:`Z` contains both the exogenous regressors and the instruments.\n :math:`\\kappa` is estimated as part of the LIML estimator.\n\n When using Fuller's :math:`\\alpha`, the value used is modified to\n\n .. math::\n\n \\kappa-\\alpha/(n-n_{instr})\n\n .. todo::\n\n * VCV: bootstrap\n\n See Also\n --------\n IV2SLS, IVGMM, IVGMMCUE\n \"\"\"\n\n def __init__(self, dependent, exog, endog, instruments, *, weights=None,\n fuller=0, kappa=None):\n\n self.dependent = IVData(dependent, var_name='dependent')\n nobs = self.dependent.shape[0]\n self.exog = IVData(exog, var_name='exog', nobs=nobs)\n self.endog = IVData(endog, var_name='endog', nobs=nobs)\n self.instruments = IVData(instruments, var_name='instruments', nobs=nobs)\n if weights is None:\n weights = ones(self.dependent.shape)\n weights = IVData(weights).ndarray\n if any(weights <= 0):\n raise ValueError('weights must be strictly positive.')\n weights = weights / nanmean(weights)\n self.weights = IVData(weights, var_name='weights', nobs=nobs)\n\n self._drop_locs = self._drop_missing()\n # dependent variable\n w = sqrt(self.weights.ndarray)\n self._y = self.dependent.ndarray\n self._wy = self._y * w\n # model regressors\n self._x = c_[self.exog.ndarray, self.endog.ndarray]\n self._wx = self._x * w\n # first-stage regressors\n self._z = c_[self.exog.ndarray, self.instruments.ndarray]\n self._wz = self._z * w\n\n self._has_constant = False\n self._regressor_is_exog = array([True] * self.exog.shape[1] +\n [False] * self.endog.shape[1])\n self._columns = self.exog.cols + self.endog.cols\n self._instr_columns = self.exog.cols + self.instruments.cols\n self._index = self.dependent.rows\n\n self._validate_inputs()\n if not hasattr(self, '_method'):\n self._method = 'IV-LIML'\n additional = []\n if fuller != 0:\n additional.append('fuller(alpha={0})'.format(fuller))\n if kappa is not None:\n additional.append('kappa={0}'.format(fuller))\n if additional:\n self._method += '(' + ', '.join(additional) + ')'\n if not hasattr(self, '_result_container'):\n self._result_container = IVResults\n\n self._kappa = kappa\n self._fuller = fuller\n if kappa is not None and not isscalar(kappa):\n raise ValueError('kappa must be None or a scalar')\n if not isscalar(fuller):\n raise ValueError('fuller must be None or a scalar')\n if kappa is not None and fuller != 0:\n import warnings\n warnings.warn('kappa and fuller should not normally be used '\n 'simultaneously. Identical results can be computed '\n 'using kappa only', UserWarning)\n if endog is None or instruments is None:\n self._result_container = OLSResults\n self._method = 'OLS'\n self._formula = None\n\n @staticmethod\n def from_formula(formula, data, *, weights=None, fuller=0, kappa=None):\n \"\"\"\n Parameters\n ----------\n formula : str\n Patsy formula modified for the IV syntax described in the notes\n section\n data : DataFrame\n DataFrame containing the variables used in the formula\n weights : array-like, optional\n Observation weights used in estimation\n fuller : float, optional\n Fuller's alpha to modify LIML estimator. Default returns unmodified\n LIML estimator.\n kappa : float, optional\n Parameter value for k-class estimation. If not provided, computed to\n produce LIML parameter estimate.\n\n Returns\n -------\n model : IVLIML\n Model instance\n\n Notes\n -----\n The IV formula modifies the standard Patsy formula to include a\n block of the form [endog ~ instruments] which is used to indicate\n the list of endogenous variables and instruments. The general\n structure is `dependent ~ exog [endog ~ instruments]` and it must\n be the case that the formula expressions constructed from blocks\n `dependent ~ exog endog` and `dependent ~ exog instruments` are both\n valid Patsy formulas.\n\n A constant must be explicitly included using '1 +' if required.\n\n Examples\n --------\n >>> import numpy as np\n >>> from linearmodels.datasets import wage\n >>> from linearmodels.iv import IVLIML\n >>> data = wage.load()\n >>> formula = 'np.log(wage) ~ 1 + exper + exper ** 2 + brthord + [educ ~ sibs]'\n >>> mod = IVLIML.from_formula(formula, data)\n \"\"\"\n dep, exog, endog, instr = parse_formula(formula, data)\n mod = IVLIML(dep, exog, endog, instr, weights=weights,\n fuller=fuller, kappa=kappa)\n mod.formula = formula\n return mod\n\n @property\n def formula(self):\n \"\"\"Formula used to create the model\"\"\"\n return self._formula\n\n @formula.setter\n def formula(self, value):\n \"\"\"Formula used to create the model\"\"\"\n self._formula = value\n\n def _validate_inputs(self):\n x, z = self._x, self._z\n if x.shape[1] == 0:\n raise ValueError('Model must contain at least one regressor.')\n if self.instruments.shape[1] < self.endog.shape[1]:\n raise ValueError('The number of instruments ({0}) must be at least '\n 'as large as the number of endogenous regressors'\n ' ({1}).'.format(self.instruments.shape[1],\n self.endog.shape[1]))\n if matrix_rank(x) < x.shape[1]:\n raise ValueError('regressors [exog endog] do not have full '\n 'column rank')\n if matrix_rank(z) < z.shape[1]:\n raise ValueError('instruments [exog instruments] do not have '\n 'full column rank')\n self._has_constant, self._const_loc = has_constant(x)\n\n def _drop_missing(self):\n data = (self.dependent, self.exog, self.endog, self.instruments, self.weights)\n missing = any(c_[[dh.isnull for dh in data]], 0)\n if any(missing):\n if all(missing):\n raise ValueError('All observations contain missing data. '\n 'Model cannot be estimated.')\n self.dependent.drop(missing)\n self.exog.drop(missing)\n self.endog.drop(missing)\n self.instruments.drop(missing)\n self.weights.drop(missing)\n\n missing_warning(missing)\n return missing\n\n @staticmethod\n def estimate_parameters(x, y, z, kappa):\n \"\"\"\n Parameter estimation without error checking\n\n Parameters\n ----------\n x : ndarray\n Regressor matrix (nobs by nvar)\n y : ndarray\n Regressand matrix (nobs by 1)\n z : ndarray\n Instrument matrix (nobs by ninstr)\n kappa : scalar\n Parameter value for k-class estimator\n\n Returns\n -------\n params : ndarray\n Estimated parameters (nvar by 1)\n\n Notes\n -----\n Exposed as a static method to facilitate estimation with other data,\n e.g., bootstrapped samples. Performs no error checking.\n \"\"\"\n pinvz = pinv(z)\n p1 = (x.T @ x) * (1 - kappa) + kappa * ((x.T @ z) @ (pinvz @ x))\n p2 = (x.T @ y) * (1 - kappa) + kappa * ((x.T @ z) @ (pinvz @ y))\n return inv(p1) @ p2\n\n def _estimate_kappa(self):\n y, x, z = self._wy, self._wx, self._wz\n is_exog = self._regressor_is_exog\n e = c_[y, x[:, ~is_exog]]\n x1 = x[:, is_exog]\n if x1.shape[1] == 0:\n # No exogenous regressors\n return 1\n\n ez = e - z @ (pinv(z) @ e)\n ex1 = e - x1 @ (pinv(x1) @ e)\n\n vpmzv_sqinv = inv_sqrth(ez.T @ ez)\n q = vpmzv_sqinv @ (ex1.T @ ex1) @ vpmzv_sqinv\n return min(eigvalsh(q))\n\n def fit(self, *, cov_type='robust', **cov_config):\n \"\"\"\n Estimate model parameters\n\n Parameters\n ----------\n cov_type : str, optional\n Name of covariance estimator to use\n **cov_config\n Additional parameters to pass to covariance estimator\n\n Returns\n -------\n results : IVResults\n Results container\n\n Notes\n -----\n Additional covariance parameters depend on specific covariance used.\n The see the docstring of specific covariance estimator for a list of\n supported options. Defaults are used if no covariance configuration\n is provided.\n \"\"\"\n wy, wx, wz = self._wy, self._wx, self._wz\n liml_kappa = self._estimate_kappa()\n kappa = self._kappa\n if kappa is None:\n kappa = liml_kappa\n\n if self._fuller != 0:\n nobs, ninstr = wz.shape\n kappa -= self._fuller / (nobs - ninstr)\n\n params = self.estimate_parameters(wx, wy, wz, kappa)\n\n cov_estimator = COVARIANCE_ESTIMATORS[cov_type]\n cov_config['kappa'] = kappa\n cov_config_copy = {k: v for k, v in cov_config.items()}\n if 'center' in cov_config_copy:\n del cov_config_copy['center']\n cov_estimator = cov_estimator(wx, wy, wz, params, **cov_config_copy)\n\n results = {'kappa': kappa,\n 'liml_kappa': liml_kappa}\n pe = self._post_estimation(params, cov_estimator, cov_type)\n results.update(pe)\n\n return self._result_container(results, self)\n\n def wresids(self, params):\n \"\"\"\n Compute weighted model residuals\n\n Parameters\n ----------\n params : ndarray\n Model parameters (nvar by 1)\n\n Returns\n -------\n wresids : ndarray\n Weighted model residuals\n\n Notes\n -----\n Uses weighted versions of data instead of raw data. Identical to\n resids if all weights are unity.\n \"\"\"\n return self._wy - self._wx @ params\n\n def resids(self, params):\n \"\"\"\n Compute model residuals\n\n Parameters\n ----------\n params : ndarray\n Model parameters (nvar by 1)\n\n Returns\n -------\n resids : ndarray\n Model residuals\n \"\"\"\n return self._y - self._x @ params\n\n @property\n def has_constant(self):\n \"\"\"Flag indicating the model includes a constant or equivalent\"\"\"\n return self._has_constant\n\n @property\n def isnull(self):\n \"\"\"Locations of observations with missing values\"\"\"\n return self._drop_locs\n\n @property\n def notnull(self):\n \"\"\"Locations of observations included in estimation\"\"\"\n return logical_not(self._drop_locs)\n\n def _f_statistic(self, params, cov, debiased):\n non_const = ~(self._x.ptp(0) == 0)\n test_params = params[non_const]\n test_cov = cov[non_const][:, non_const]\n test_stat = test_params.T @ inv(test_cov) @ test_params\n test_stat = float(test_stat)\n nobs, nvar = self._x.shape\n null = 'All parameters ex. constant are zero'\n name = 'Model F-statistic'\n df = test_params.shape[0]\n if debiased:\n wald = WaldTestStatistic(test_stat / df, null, df, nobs - nvar,\n name=name)\n else:\n wald = WaldTestStatistic(test_stat, null, df, name=name)\n\n return wald\n\n def _post_estimation(self, params, cov_estimator, cov_type):\n vars = self._columns\n index = self._index\n eps = self.resids(params)\n weps = self.wresids(params)\n cov = cov_estimator.cov\n debiased = cov_estimator.debiased\n\n residual_ss = (weps.T @ weps)\n\n w = self.weights.ndarray\n e = self._wy\n if self.has_constant:\n e = e - sqrt(self.weights.ndarray) * average(self._y, weights=w)\n\n total_ss = float(e.T @ e)\n r2 = 1 - residual_ss / total_ss\n\n fstat = self._f_statistic(params, cov, debiased)\n out = {'params': Series(params.squeeze(), vars, name='parameter'),\n 'eps': Series(eps.squeeze(), index=index, name='residual'),\n 'weps': Series(weps.squeeze(), index=index, name='weighted residual'),\n 'cov': DataFrame(cov, columns=vars, index=vars),\n 's2': float(cov_estimator.s2),\n 'debiased': debiased,\n 'residual_ss': float(residual_ss),\n 'total_ss': float(total_ss),\n 'r2': float(r2),\n 'fstat': fstat,\n 'vars': vars,\n 'instruments': self._instr_columns,\n 'cov_config': cov_estimator.config,\n 'cov_type': cov_type,\n 'method': self._method,\n 'cov_estimator': cov_estimator}\n\n return out\n\n\nclass IV2SLS(IVLIML):\n r\"\"\"\n Estimation of IV models using two-stage least squares\n\n Parameters\n ----------\n dependent : array-like\n Endogenous variables (nobs by 1)\n exog : array-like\n Exogenous regressors (nobs by nexog)\n endog : array-like\n Endogenous regressors (nobs by nendog)\n instruments : array-like\n Instrumental variables (nobs by ninstr)\n weights : array-like, optional\n Observation weights used in estimation\n\n Notes\n -----\n The 2SLS estimator is defined\n\n .. math::\n\n \\hat{\\beta}_{2SLS} & =(X'Z(Z'Z)^{-1}Z'X)^{-1}X'Z(Z'Z)^{-1}Z'Y\\\\\n & =(\\hat{X}'\\hat{X})^{-1}\\hat{X}'Y\\\\\n \\hat{X} & =Z(Z'Z)^{-1}Z'X\n\n The 2SLS estimator is a special case of a k-class estimator with\n :math:`\\kappa=1`,\n\n .. todo::\n\n * VCV: bootstrap\n\n See Also\n --------\n IVLIML, IVGMM, IVGMMCUE\n \"\"\"\n\n def __init__(self, dependent, exog, endog, instruments, *, weights=None):\n self._method = 'IV-2SLS'\n super(IV2SLS, self).__init__(dependent, exog, endog, instruments,\n weights=weights, fuller=0, kappa=1)\n\n @staticmethod\n def from_formula(formula, data, *, weights=None):\n \"\"\"\n Parameters\n ----------\n formula : str\n Patsy formula modified for the IV syntax described in the notes\n section\n data : DataFrame\n DataFrame containing the variables used in the formula\n weights : array-like, optional\n Observation weights used in estimation\n\n Returns\n -------\n model : IV2SLS\n Model instance\n\n Notes\n -----\n The IV formula modifies the standard Patsy formula to include a\n block of the form [endog ~ instruments] which is used to indicate\n the list of endogenous variables and instruments. The general\n structure is `dependent ~ exog [endog ~ instruments]` and it must\n be the case that the formula expressions constructed from blocks\n `dependent ~ exog endog` and `dependent ~ exog instruments` are both\n valid Patsy formulas.\n\n A constant must be explicitly included using '1 +' if required.\n\n Examples\n --------\n >>> import numpy as np\n >>> from linearmodels.datasets import wage\n >>> from linearmodels.iv import IV2SLS\n >>> data = wage.load()\n >>> formula = 'np.log(wage) ~ 1 + exper + exper ** 2 + brthord + [educ ~ sibs]'\n >>> mod = IV2SLS.from_formula(formula, data)\n \"\"\"\n dep, exog, endog, instr = parse_formula(formula, data)\n mod = IV2SLS(dep, exog, endog, instr, weights=weights)\n mod.formula = formula\n return mod\n\n\nclass IVGMM(IVLIML):\n r\"\"\"\n Estimation of IV models using the generalized method of moments (GMM)\n\n Parameters\n ----------\n dependent : array-like\n Endogenous variables (nobs by 1)\n exog : array-like\n Exogenous regressors (nobs by nexog)\n endog : array-like\n Endogenous regressors (nobs by nendog)\n instruments : array-like\n Instrumental variables (nobs by ninstr)\n weights : array-like, optional\n Observation weights used in estimation\n weight_type : str\n Name of moment condition weight function to use in the GMM estimation\n **weight_config\n Additional keyword arguments to pass to the moment condition weight\n function\n\n Notes\n -----\n Available GMM weight functions are:\n\n * 'unadjusted', 'homoskedastic' - Assumes moment conditions are\n homoskedastic\n * 'robust', 'heteroskedastic' - Allows for heteroskedasticity by not\n autocorrelation\n * 'kernel' - Allows for heteroskedasticity and autocorrelation\n * 'cluster' - Allows for one-way cluster dependence\n\n The estimator is defined as\n\n .. math::\n\n \\hat{\\beta}_{gmm}=(X'ZW^{-1}Z'X)^{-1}X'ZW^{-1}Z'Y\n\n where :math:`W` is a positive definite weight matrix and :math:`Z`\n contains both the exogenous regressors and the instruments.\n\n .. todo::\n\n * VCV: bootstrap\n\n See Also\n --------\n IV2SLS, IVLIML, IVGMMCUE\n \"\"\"\n\n def __init__(self, dependent, exog, endog, instruments, *, weights=None,\n weight_type='robust', **weight_config):\n self._method = 'IV-GMM'\n self._result_container = IVGMMResults\n super(IVGMM, self).__init__(dependent, exog, endog, instruments, weights=weights)\n weight_matrix_estimator = WEIGHT_MATRICES[weight_type]\n self._weight = weight_matrix_estimator(**weight_config)\n self._weight_type = weight_type\n self._weight_config = self._weight.config\n\n @staticmethod\n def from_formula(formula, data, *, weights=None, weight_type='robust', **weight_config):\n \"\"\"\n Parameters\n ----------\n formula : str\n Patsy formula modified for the IV syntax described in the notes\n section\n data : DataFrame\n DataFrame containing the variables used in the formula\n weights : array-like, optional\n Observation weights used in estimation\n weight_type : str\n Name of moment condition weight function to use in the GMM estimation\n **weight_config\n Additional keyword arguments to pass to the moment condition weight\n function\n\n Notes\n -----\n The IV formula modifies the standard Patsy formula to include a\n block of the form [endog ~ instruments] which is used to indicate\n the list of endogenous variables and instruments. The general\n structure is `dependent ~ exog [endog ~ instruments]` and it must\n be the case that the formula expressions constructed from blocks\n `dependent ~ exog endog` and `dependent ~ exog instruments` are both\n valid Patsy formulas.\n\n A constant must be explicitly included using '1 +' if required.\n\n Returns\n -------\n model : IVGMM\n Model instance\n\n Examples\n --------\n >>> import numpy as np\n >>> from linearmodels.datasets import wage\n >>> from linearmodels.iv import IVGMM\n >>> data = wage.load()\n >>> formula = 'np.log(wage) ~ 1 + exper + exper ** 2 + brthord + [educ ~ sibs]'\n >>> mod = IVGMM.from_formula(formula, data)\n \"\"\"\n dep, exog, endog, instr = parse_formula(formula, data)\n mod = IVGMM(dep, exog, endog, instr, weights=weights, weight_type=weight_type,\n **weight_config)\n mod.formula = formula\n return mod\n\n @staticmethod\n def estimate_parameters(x, y, z, w):\n \"\"\"\n Parameters\n ----------\n x : ndarray\n Regressor matrix (nobs by nvar)\n y : ndarray\n Regressand matrix (nobs by 1)\n z : ndarray\n Instrument matrix (nobs by ninstr)\n w : ndarray\n GMM weight matrix (ninstr by ninstr)\n\n Returns\n -------\n params : ndarray\n Estimated parameters (nvar by 1)\n\n Notes\n -----\n Exposed as a static method to facilitate estimation with other data,\n e.g., bootstrapped samples. Performs no error checking.\n \"\"\"\n xpz = x.T @ z\n zpy = z.T @ y\n return inv(xpz @ w @ xpz.T) @ (xpz @ w @ zpy)\n\n def fit(self, *, iter_limit=2, tol=1e-4, initial_weight=None,\n cov_type='robust', **cov_config):\n \"\"\"\n Estimate model parameters\n\n Parameters\n ----------\n iter_limit : int, optional\n Maximum number of iterations. Default is 2, which produces\n two-step efficient GMM estimates. Larger values can be used\n to iterate between parameter estimation and optimal weight\n matrix estimation until convergence.\n tol : float, optional\n Convergence criteria. Measured as covariance normalized change in\n parameters across iterations where the covariance estimator is\n based on the first step parameter estimates.\n initial_weight : ndarray, optional\n Initial weighting matrix to use in the first step. If not\n specified, uses the average outer-product of the set containing\n the exogenous variables and instruments.\n cov_type : str, optional\n Name of covariance estimator to use\n **cov_config\n Additional parameters to pass to covariance estimator\n\n Returns\n -------\n results : IVGMMResults\n Results container\n\n Notes\n -----\n Additional covariance parameters depend on specific covariance used.\n The see the docstring of specific covariance estimator for a list of\n supported options. Defaults are used if no covariance configuration\n is provided.\n\n Available covariance functions are:\n\n * 'unadjusted', 'homoskedastic' - Assumes moment conditions are\n homoskedastic\n * 'robust', 'heteroskedastic' - Allows for heteroskedasticity by not\n autocorrelation\n * 'kernel' - Allows for heteroskedasticity and autocorrelation\n * 'cluster' - Allows for one-way cluster dependence\n \"\"\"\n wy, wx, wz = self._wy, self._wx, self._wz\n nobs = wy.shape[0]\n weight_matrix = self._weight.weight_matrix\n wmat = inv(wz.T @ wz / nobs) if initial_weight is None else initial_weight\n sv = IV2SLS(self.dependent, self.exog, self.endog, self.instruments,\n weights=self.weights)\n _params = params = sv.fit().params.values[:, None]\n # _params = params = self.estimate_parameters(wx, wy, wz, wmat)\n\n iters, norm = 1, 10 * tol\n while iters < iter_limit and norm > tol:\n eps = wy - wx @ params\n wmat = inv(weight_matrix(wx, wz, eps))\n params = self.estimate_parameters(wx, wy, wz, wmat)\n delta = params - _params\n if iters == 1:\n xpz = wx.T @ wz / nobs\n v = (xpz @ wmat @ xpz.T) / nobs\n vinv = inv(v)\n _params = params\n norm = delta.T @ vinv @ delta\n iters += 1\n\n cov_estimator = IVGMMCovariance(wx, wy, wz, params, wmat,\n cov_type, **cov_config)\n\n results = self._post_estimation(params, cov_estimator, cov_type)\n gmm_pe = self._gmm_post_estimation(params, wmat, iters)\n\n results.update(gmm_pe)\n\n return self._result_container(results, self)\n\n def _gmm_post_estimation(self, params, weight_mat, iters):\n \"\"\"GMM-specific post-estimation results\"\"\"\n instr = self._instr_columns\n gmm_specific = {'weight_mat': DataFrame(weight_mat, columns=instr, index=instr),\n 'weight_type': self._weight_type,\n 'weight_config': self._weight_type,\n 'iterations': iters,\n 'j_stat': self._j_statistic(params, weight_mat)}\n\n return gmm_specific\n\n def _j_statistic(self, params, weight_mat):\n \"\"\"J stat and test\"\"\"\n y, x, z = self._wy, self._wx, self._wz\n nobs, nvar, ninstr = y.shape[0], x.shape[1], z.shape[1]\n eps = y - x @ params\n g_bar = (z * eps).mean(0)\n stat = float(nobs * g_bar.T @ weight_mat @ g_bar.T)\n null = 'Expected moment conditions are equal to 0'\n return WaldTestStatistic(stat, null, ninstr - nvar)\n\n\nclass IVGMMCUE(IVGMM):\n r\"\"\"\n Estimation of IV models using continuously updating GMM\n\n Parameters\n ----------\n dependent : array-like\n Endogenous variables (nobs by 1)\n exog : array-like\n Exogenous regressors (nobs by nexog)\n endog : array-like\n Endogenous regressors (nobs by nendog)\n instruments : array-like\n Instrumental variables (nobs by ninstr)\n weights : array-like, optional\n Observation weights used in estimation\n weight_type : str\n Name of moment condition weight function to use in the GMM estimation\n **weight_config\n Additional keyword arguments to pass to the moment condition weight\n function\n\n Notes\n -----\n Available weight functions are:\n\n * 'unadjusted', 'homoskedastic' - Assumes moment conditions are\n homoskedastic\n * 'robust', 'heteroskedastic' - Allows for heteroskedasticity by not\n autocorrelation\n * 'kernel' - Allows for heteroskedasticity and autocorrelation\n * 'cluster' - Allows for one-way cluster dependence\n\n In most circumstances, the ``center`` weight option should be ``True`` to\n avoid starting value dependence.\n\n .. math::\n\n \\hat{\\beta}_{cue} & =\\min_{\\beta}\\bar{g}(\\beta)'W(\\beta)^{-1}g(\\beta)\\\\\n g(\\beta) & =n^{-1}\\sum_{i=1}^{n}z_{i}(y_{i}-x_{i}\\beta)\n\n where :math:`W(\\beta)` is a weight matrix that depends on :math:`\\beta`\n through :math:`\\epsilon_i = y_i - x_i\\beta`.\n\n See Also\n --------\n IV2SLS, IVLIML, IVGMM\n \"\"\"\n\n def __init__(self, dependent, exog, endog, instruments, *, weights=None,\n weight_type='robust', **weight_config):\n self._method = 'IV-GMM-CUE'\n super(IVGMMCUE, self).__init__(dependent, exog, endog, instruments, weights=weights,\n weight_type=weight_type, **weight_config)\n if 'center' not in weight_config:\n weight_config['center'] = True\n\n @staticmethod\n def from_formula(formula, data, *, weights=None, weight_type='robust', **weight_config):\n \"\"\"\n Parameters\n ----------\n formula : str\n Patsy formula modified for the IV syntax described in the notes\n section\n data : DataFrame\n DataFrame containing the variables used in the formula\n weights : array-like, optional\n Observation weights used in estimation\n weight_type : str\n Name of moment condition weight function to use in the GMM estimation\n **weight_config\n Additional keyword arguments to pass to the moment condition weight\n function\n\n Returns\n -------\n model : IVGMMCUE\n Model instance\n\n Notes\n -----\n The IV formula modifies the standard Patsy formula to include a\n block of the form [endog ~ instruments] which is used to indicate\n the list of endogenous variables and instruments. The general\n structure is `dependent ~ exog [endog ~ instruments]` and it must\n be the case that the formula expressions constructed from blocks\n `dependent ~ exog endog` and `dependent ~ exog instruments` are both\n valid Patsy formulas.\n\n A constant must be explicitly included using '1 +' if required.\n\n Examples\n --------\n >>> from linearmodels.datasets import wage\n >>> from linearmodels.iv import IVGMMCUE\n >>> data = wage.load()\n >>> formula = 'np.log(wage) ~ 1 + exper + exper ** 2 + brthord + [educ ~ sibs]'\n >>> mod = IVGMMCUE.from_formula(formula, data)\n \"\"\"\n dep, exog, endog, instr = parse_formula(formula, data)\n mod = IVGMMCUE(dep, exog, endog, instr, weights=weights, weight_type=weight_type,\n **weight_config)\n mod.formula = formula\n return mod\n\n def j(self, params, x, y, z):\n r\"\"\"\n Optimization target\n\n Parameters\n ----------\n params : ndarray\n Parameter vector (nvar)\n x : ndarray\n Regressor matrix (nobs by nvar)\n y : ndarray\n Regressand matrix (nobs by 1)\n z : ndarray\n Instrument matrix (nobs by ninstr)\n\n Returns\n -------\n j : float\n GMM objective function, also known as the J statistic\n\n Notes\n -----\n\n The GMM objective function is defined as\n\n .. math::\n\n J(\\beta) = \\bar{g}(\\beta)'W(\\beta)^{-1}\\bar{g}(\\beta)\n\n where :math:`\\bar{g}(\\beta)` is the average of the moment\n conditions, :math:`z_i \\hat{\\epsilon}_i`, where\n :math:`\\hat{\\epsilon}_i = y_i - x_i\\beta`. The weighting matrix\n is some estimator of the long-run variance of the moment conditions.\n\n Unlike tradition GMM, the weighting matrix is simultaneously computed\n with the moment conditions, and so has explicit dependence on\n :math:`\\beta`.\n \"\"\"\n nobs = y.shape[0]\n weight_matrix = self._weight.weight_matrix\n eps = y - x @ params[:, None]\n w = inv(weight_matrix(x, z, eps))\n g_bar = (z * eps).mean(0)\n return nobs * g_bar.T @ w @ g_bar.T\n\n def estimate_parameters(self, starting, x, y, z, display=False):\n r\"\"\"\n Parameters\n ----------\n starting : ndarray\n Starting values for the optimization\n x : ndarray\n Regressor matrix (nobs by nvar)\n y : ndarray\n Regressand matrix (nobs by 1)\n z : ndarray\n Instrument matrix (nobs by ninstr)\n display : bool\n Flag indicating whether to display iterative optimizer output\n\n Returns\n -------\n params : ndarray\n Estimated parameters (nvar by 1)\n\n Notes\n -----\n Exposed to facilitate estimation with other data, e.g., bootstrapped\n samples. Performs no error checking.\n\n See Also\n --------\n scipy.optimize.minimize\n \"\"\"\n args = (x, y, z)\n res = minimize(self.j, starting, args=args, options={'disp': display})\n\n return res.x[:, None], res.nit\n\n def fit(self, *, starting=None, display=False, cov_type='robust', **cov_config):\n r\"\"\"\n Estimate model parameters\n\n Parameters\n ----------\n starting : ndarray, optional\n Starting values to use in optimization. If not provided, 2SLS\n estimates are used.\n display : bool, optional\n Flag indicating whether to display optimization output\n cov_type : str, optional\n Name of covariance estimator to use\n **cov_config\n Additional parameters to pass to covariance estimator\n\n Returns\n -------\n results : IVGMMResults\n Results container\n\n Notes\n -----\n Additional covariance parameters depend on specific covariance used.\n The see the docstring of specific covariance estimator for a list of\n supported options. Defaults are used if no covariance configuration\n is provided.\n\n Starting values are computed by IVGMM.\n\n .. todo::\n\n * Expose method to pass optimization options\n \"\"\"\n\n wy, wx, wz = self._wy, self._wx, self._wz\n weight_matrix = self._weight.weight_matrix\n if starting is None:\n exog = None if self.exog.shape[1] == 0 else self.exog\n endog = None if self.endog.shape[1] == 0 else self.endog\n instr = None if self.instruments.shape[1] == 0 else \\\n self.instruments\n\n res = IVGMM(self.dependent, exog, endog, instr,\n weights=self.weights, weight_type=self._weight_type,\n **self._weight_config).fit()\n starting = res.params.values\n else:\n starting = asarray(starting)\n if len(starting) != self.exog.shape[1] + self.endog.shape[1]:\n raise ValueError('starting does not have the correct number '\n 'of values')\n params, iters = self.estimate_parameters(starting, wx, wy, wz, display)\n eps = wy - wx @ params\n wmat = inv(weight_matrix(wx, wz, eps))\n\n cov_estimator = IVGMMCovariance(wx, wy, wz, params, wmat, cov_type,\n **cov_config)\n results = self._post_estimation(params, cov_estimator, cov_type)\n gmm_pe = self._gmm_post_estimation(params, wmat, iters)\n results.update(gmm_pe)\n\n return self._result_container(results, self)\n\n\nclass _OLS(IVLIML):\n \"\"\"\n Computes OLS estimated when required\n\n Parameters\n ----------\n dependent : array-like\n Endogenous variables (nobs by 1)\n exog : array-like\n Exogenous regressors (nobs by nexog)\n weights : array-like, optional\n Observation weights used in estimation\n\n Notes\n -----\n Uses IV2SLS internally by setting endog and instruments to None.\n Uses IVLIML with kappa=0 to estimate OLS models.\n\n See Also\n --------\n statsmodels.regression.linear_model.OLS,\n statsmodels.regression.linear_model.GLS\n \"\"\"\n\n def __init__(self, dependent, exog, *, weights=None):\n super(_OLS, self).__init__(dependent, exog, None, None, weights=weights, kappa=0.0)\n self._result_container = OLSResults\n","sub_path":"linearmodels/iv/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":38087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"256368643","text":"# Name: main.py\n# Author: Patrik Richard Szilagyi\n# Description: SOFT6017 Project 2021 - Race Organiser Application\n\n# Import modules\nfrom module_main import *\nfrom module_race import *\n\n\n# Function for printing the main menu\n# Returns the menu selection\ndef menu():\n print(f\"Select from the following options:\\n\"\n f\"1. Show the results for a race\\n\"\n f\"2. Add results for a race\\n\"\n f\"3. Show all competitors by county\\n\"\n f\"4. Show the winner of each race\\n\"\n f\"5. Show all the race times for one competitor\\n\"\n f\"6. Show all competitors who have won a race\\n\"\n f\"7. Quit\")\n MENU_OPTIONS = 7\n selection = read_menu_selection(\"==> \", MENU_OPTIONS)\n return selection\n# End of menu function\n\n\n# Function to ask the user to select an option and validate selection\n# No return value\ndef select_option():\n while True:\n try:\n # Call the menu function and store the returned value in menu_selection\n menu_selection = menu()\n\n # If statements to validate user selection\n # Code to execute if 1st option is selected\n if menu_selection == 1:\n show_results()\n\n # Code to execute if 2nd option is selected\n if menu_selection == 2:\n add_results()\n\n # Code to execute if 3rd option is selected\n if menu_selection == 3:\n show_competitors_by_county()\n\n # Code to execute if 4th option is selected\n if menu_selection == 4:\n show_winners()\n\n # Code to execute if 5th option is selected\n if menu_selection == 5:\n show_race_times()\n\n # Code to execute if 6th option is selected\n if menu_selection == 6:\n show_winning_competitors()\n\n # Code to execute if 7th option is selected (Quit program)\n if menu_selection == 7:\n print(f\"Bye bye!\")\n break\n except ValueError:\n print()\n\n # End of while loop\n# End of select_option function\n\n\n# Main function\ndef main():\n # Call the banner function\n print_banner()\n\n # Call the select_option function\n select_option()\n\n# End of main function\n\n\nif __name__ == \"__main__\":\n # Call the main function\n main()\n\n# END OF FILE\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"67380442","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nDATA_ROOT_PATH = 'C:/GitHub/Multi-Agent-RL-Energy-Management/Visualisation/experiment_1'\nEXPORT_ROOT_PATH = 'C:/GitHub/Multi-Agent-RL-Energy-Management/Visualisation/export'\nSEEDS = [998] # [998, 667, 11, 2148, 79]\nSCENARIO_COUNT = 1\nAGENT_COUNT = 4\nDATA_SIZE = 500\nAGENT_NAMES = [\n [\"Machine 1\", \"Machine 2\", \"Machine 3\", \"Machine 4\"],\n [\"Welding Machine\", \"CNC Machine\", \"Energy Storage\", \"Wind Turbine\"],\n [\"Machine 1\", \"Machine 2\", \"Storage\", \"Generator\"],\n [\"Machine 1\", \"Machine 2\", \"Storage\", \"Generator\"]\n]\n\n\ndef parse_raw_data(data_path):\n rslt = {}\n for scenario in range(SCENARIO_COUNT):\n scenario_reward = {}\n # Get cul_all rewards\n cul_reward = []\n for seed in SEEDS:\n _path_all = os.path.normpath('{}/scenario_{}/{}/run-.-tag-cul_reward.csv'\n .format(data_path, scenario, seed))\n cul_reward.append(np.loadtxt(_path_all, skiprows=1, delimiter=','))\n scenario_reward['all'] = np.array(cul_reward)[:, :DATA_SIZE]\n\n # Get energy prices\n tous = []\n for seed in SEEDS:\n _path_tous = os.path.normpath('{}/scenario_{}/{}/run-.-tag-current_energy_price.csv'\n .format(data_path, scenario, seed))\n tous.append(np.loadtxt(_path_tous, skiprows=1, delimiter=','))\n scenario_reward['tou_prices'] = np.array(tous)[:, :DATA_SIZE]\n\n # Get current power\n power = []\n for seed in SEEDS:\n _path_power = os.path.normpath('{}/scenario_{}/{}/run-.-tag-current_system_power.csv'\n .format(data_path, scenario, seed))\n power.append(np.loadtxt(_path_power, skiprows=1, delimiter=','))\n scenario_reward['power'] = np.array(power)[:, :DATA_SIZE]\n\n # Get load profile\n load = []\n for seed in SEEDS:\n _path_load = os.path.normpath('{}/scenario_{}/{}/run-.-tag-max_load_pofile.csv'\n .format(data_path, scenario, seed))\n load.append(np.loadtxt(_path_load, skiprows=1, delimiter=','))\n scenario_reward['load'] = np.array(load)[:, :DATA_SIZE]\n\n # Get production\n load = []\n for seed in SEEDS:\n _path_production = os.path.normpath('{}/scenario_{}/{}/run-.-tag-production.csv'\n .format(data_path, scenario, seed))\n load.append(np.loadtxt(_path_production, skiprows=1, delimiter=','))\n scenario_reward['production'] = np.array(load)[:, :DATA_SIZE]\n\n # Get all agent rewards\n for agent in range(AGENT_COUNT):\n agent_reward = []\n for seed in SEEDS:\n _path_agent = os.path.normpath('{}/scenario_{}/{}/run-.-tag-cul_reward_agent_{}.csv'\n .format(data_path, scenario, seed, agent))\n agent_reward.append(np.loadtxt(_path_agent, skiprows=1, delimiter=','))\n scenario_reward['agent_{}'.format(agent)] = np.array(agent_reward)[:, :DATA_SIZE]\n\n rslt['scenario_{}'.format(scenario)] = scenario_reward\n return rslt\n\n\ndef plot_learning_curve(train_sizes, train_scores, test_scores, title, alpha=0.2):\n train_mean = np.mean(train_scores, axis=1)\n train_std = np.std(train_scores, axis=1)\n test_mean = np.mean(test_scores, axis=1)\n test_std = np.std(test_scores, axis=1)\n plt.plot(train_sizes, train_mean, label='train score', color='blue', marker='o')\n plt.fill_between(train_sizes, train_mean + train_std,\n train_mean - train_std, color='blue', alpha=alpha)\n plt.plot(train_sizes, test_mean, label='test score', color='red', marker='o')\n\n plt.fill_between(train_sizes, test_mean + test_std, test_mean - test_std, color='red', alpha=alpha)\n plt.title(title)\n plt.xlabel('Number of training points')\n plt.ylabel('F-measure')\n plt.grid(ls='--')\n plt.legend(loc='best')\n plt.show()\n\n\ndef plot_validation_curve(param_range, train_scores, test_scores, title, alpha=0.2):\n param_range = [x[1] for x in param_range]\n sort_idx = np.argsort(param_range)\n param_range = np.array(param_range)[sort_idx]\n train_mean = np.mean(train_scores, axis=1)[sort_idx]\n train_std = np.std(train_scores, axis=1)[sort_idx]\n test_mean = np.mean(test_scores, axis=1)[sort_idx]\n test_std = np.std(test_scores, axis=1)[sort_idx]\n plt.plot(param_range, train_mean, label='train score', color='blue', marker='o')\n plt.fill_between(param_range, train_mean + train_std,\n train_mean - train_std, color='blue', alpha=alpha)\n plt.plot(param_range, test_mean, label='test score', color='red', marker='o')\n plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, color='red', alpha=alpha)\n plt.title(title)\n plt.grid(ls='--')\n plt.xlabel('Weight of class 2')\n plt.ylabel('Average values and standard deviation for F1-Score')\n plt.legend(loc='best')\n plt.show()\n\n\ndef plot_all_learning_curve(subplot, train_sizes, train_scores, title, alpha=0.2):\n # These are the colors that will be used in the plot\n # subplot.set_prop_cycle(color=[\n # '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',\n # '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',\n # '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',\n # '#17becf', '#9edae5'])\n # These are the colors that will be used in the plot\n # subplot.set_prop_cycle(color=[\n # '#d62728', '#9467bd', '#8c564b',\n # '#e377c2', '#7f7f7f', '#bcbd22',\n # '#17becf'])\n\n subplot.xaxis.set_tick_params(labelsize=8)\n subplot.yaxis.set_tick_params(labelsize=8)\n\n train_mean = np.mean(train_scores, axis=0)\n train_std = np.std(train_scores, axis=0)\n\n subplot.plot(train_sizes, train_mean, color='tab:blue', label=\"Global Reward\")\n subplot.fill_between(train_sizes, train_mean + train_std, train_mean - train_std, color='tab:blue', alpha=alpha)\n\n subplot.set_title(title, fontsize='12', fontweight='bold')\n subplot.set_xlabel('Episodes', fontsize='9')\n subplot.set_ylabel('Global Reward', fontsize='9')\n subplot.grid(ls='--')\n # subplot.legend(loc='best')\n # subplot.legend(frameon=True, fontsize=8)\n\n\ndef plot_agent_learning_curve(subplot, train_sizes, train_scores, title, alpha=0.2):\n\n # These are the colors that will be used in the plot\n subplot.set_prop_cycle(color=[\n '#1f77b4', '#ff7f0e', '#2ca02c',\n '#d62728', '#9467bd', '#8c564b',\n '#e377c2', '#7f7f7f', '#bcbd22',\n '#17becf'])\n\n # Remove the plot frame lines. They are unnecessary here.\n # subplot.spines['top'].set_visible(False)\n # subplot.spines['bottom'].set_visible(False)\n # subplot.spines['right'].set_visible(False)\n # subplot.spines['left'].set_visible(False)\n subplot.xaxis.set_tick_params(labelsize=8)\n subplot.yaxis.set_tick_params(labelsize=8)\n\n train_mean = np.mean(train_scores, axis=0)\n train_std = np.std(train_scores, axis=0)\n\n subplot.plot(train_sizes, train_mean, label=title)\n subplot.fill_between(train_sizes, train_mean + train_std,\n train_mean - train_std, alpha=alpha)\n\n # subplot.set_title(title, fontsize='9')\n subplot.set_xlabel('Episodes', fontsize='9')\n subplot.set_ylabel('Reward', fontsize='9')\n subplot.grid(ls='--')\n # subplot.legend(loc='best')\n subplot.legend(frameon=True, fontsize=8)\n\n\ndef plot_agents_learning_curve(subplot, agent_train_data_sizes, agent_train_data_scores, titles=None, alpha=0.2):\n # These are the colors that will be used in the plot\n subplot.set_prop_cycle(color=[\n '#9467bd', '#ff7f0e', '#2ca02c',\n '#d62728', '#bcbd22', '#8c564b',\n '#e377c2', '#7f7f7f', '#17becf'])\n\n # Remove the plot frame lines. They are unnecessary here.\n subplot.xaxis.set_tick_params(labelsize=8)\n subplot.yaxis.set_tick_params(labelsize=8)\n\n for a in range(AGENT_COUNT):\n train_mean = np.mean(agent_train_data_scores[a], axis=0)\n train_std = np.std(agent_train_data_scores[a], axis=0)\n _label = titles[a] if not titles is None else 'agent_{}'.format(a)\n subplot.plot(agent_train_data_sizes[a], train_mean, label=_label)\n subplot.fill_between(agent_train_data_sizes[a], train_mean + train_std,\n train_mean - train_std, alpha=alpha)\n\n # subplot.set_title(title, fontsize='9')\n subplot.set_xlabel('Episodes', fontsize='9')\n subplot.set_ylabel('Reward', fontsize='9')\n subplot.grid(ls='--')\n subplot.legend(loc='best')\n subplot.legend(frameon=True, fontsize=8)\n\n\ndef plot_plant_performance(subplot, production__sizes, production_performance, _power_consumtions, alpha=0.7):\n # Prepare the data\n production_performance_mean = np.mean(production_performance, axis=0)\n power_consumptions_mean = np.mean(_power_consumtions, axis=0)\n\n ax2 = subplot.twinx() # instantiate a second axes that shares the same x-axis\n\n # Remove the plot frame lines. They are unnecessary here.\n ax2.xaxis.set_tick_params(labelsize=8)\n ax2.yaxis.set_tick_params(labelsize=8)\n ax2.grid(ls='--')\n ax2.grid(False)\n ax2.plot(production__sizes, production_performance_mean, linewidth=2,\n color='tab:green', label=\"Executed Production Tasks\")\n ax2.set_xlabel('Episodes', fontsize='9')\n ax2.set_ylabel('Executed Production Tasks', fontsize='9')\n ax2.legend(loc='best')\n ax2.legend(frameon=True, fontsize=8)\n # ax2.set_title(\"TOU price ($/kWh)\", fontsize='9')\n\n # ax2.legend(loc='best', frameon=True, fontsize=8)\n subplot.plot(production__sizes, power_consumptions_mean, color='tab:blue', label=\"Current Power\")\n subplot.fill_between(production__sizes, power_consumptions_mean, 0, color='tab:blue', alpha=alpha)\n subplot.set_ylabel('Power (kWh)', fontsize='9')\n # subplot.tick_params(axis='y', rotation=0, labelcolor='tab:blue')\n subplot.tick_params(axis='y', rotation=0)\n subplot.xaxis.set_tick_params(labelsize=8)\n subplot.yaxis.set_tick_params(labelsize=8)\n\n\ndef plot_energy_costs(subplot, train_sizes, energy_prices, power_consumptions, alpha=0.7):\n # Prepare the data\n energy_prices_mean = np.mean(energy_prices, axis=0)\n power_consumptions_mean = np.mean(power_consumptions, axis=0)\n energy_cost_mean = np.multiply(energy_prices_mean, power_consumptions_mean)\n\n ax2 = subplot.twinx() # instantiate a second axes that shares the same x-axis\n\n subplot.plot(train_sizes, energy_cost_mean, color='tab:blue', label=\"Energy Cost ($/h)\")\n subplot.fill_between(train_sizes, energy_cost_mean, 0, color='tab:blue', alpha=alpha)\n # subplot.tick_params(axis='y', rotation=0, labelcolor='tab:blue')\n subplot.tick_params(axis='y', rotation=0)\n subplot.xaxis.set_tick_params(labelsize=8)\n subplot.yaxis.set_tick_params(labelsize=8)\n subplot.set_ylabel('Energy Cost ($/h)', fontsize='9')\n # subplot.legend(loc='best')\n # subplot.legend(frameon=True, fontsize=8)\n\n # Remove the plot frame lines. They are unnecessary here.\n ax2.xaxis.set_tick_params(labelsize=8)\n ax2.yaxis.set_tick_params(labelsize=8)\n ax2.plot(train_sizes, energy_prices_mean, '-.', linewidth=2,\n color='tab:brown', label=\"TOU price ($/kWh)\")\n\n # ax2.set_title(\"TOU price ($/kWh)\", fontsize='9')\n ax2.set_xlabel('Episodes', fontsize='9')\n ax2.set_ylabel('TOU price ($/kWh)', fontsize='9')\n ax2.grid(ls='--')\n ax2.legend(loc='best')\n ax2.legend(frameon=True, fontsize=8)\n ax2.grid(False)\n\n\nif __name__ == '__main__':\n raw_data = parse_raw_data(DATA_ROOT_PATH)\n\n # Configure the Plot\n plt.style.use('ggplot')\n\n # fig, axes = plt.subplots(3, SCENARIO_COUNT, sharex=True, figsize=(20, 9))\n fig, axes = plt.subplots(2, SCENARIO_COUNT, figsize=(10, 5.4))\n\n scenario_data = raw_data['scenario_{}'.format(0)]\n # Agent rewards\n a_data_sizes = []\n a_data_scores = []\n for agent in range(AGENT_COUNT):\n agent_train_sizes = np.arange(scenario_data['agent_{}'.format(agent)].shape[1])\n agent_train_scores = scenario_data['agent_{}'.format(agent)][:, :, 2]\n\n a_data_sizes.append(agent_train_sizes)\n a_data_scores.append(agent_train_scores)\n\n plot_agents_learning_curve(axes[0], agent_train_data_sizes=a_data_sizes,\n agent_train_data_scores=a_data_scores, titles=AGENT_NAMES[0], alpha=0.2)\n\n # Production and Energy Costs\n production_sizes = np.arange(scenario_data['production'].shape[1])\n production_performances = scenario_data['production'][:, :, 2]\n energy_prices_sizes = np.arange(scenario_data['tou_prices'].shape[1])\n energy_prices = scenario_data['tou_prices'][:, :, 2]\n power_sizes = np.arange(scenario_data['power'].shape[1])\n power_consumptions = scenario_data['power'][:, :, 2]\n\n # Production\n plot_plant_performance(axes[1], production__sizes=production_sizes,\n production_performance=production_performances,\n _power_consumtions=power_consumptions,\n alpha=0.5)\n\n fig.tight_layout()\n\n _save_path_pdf = os.path.normpath('{}/scenario_1_result.pdf'.format(EXPORT_ROOT_PATH))\n _save_path_svg = os.path.normpath('{}/scenario_1_result.svg'.format(EXPORT_ROOT_PATH))\n _save_path_png = os.path.normpath('{}/scenario_1_result.png'.format(EXPORT_ROOT_PATH))\n plt.savefig(_save_path_pdf, bbox_inches='tight')\n plt.savefig(_save_path_svg)\n plt.savefig(_save_path_png, dpi=300, transparent=True)\n\n plt.show()\n","sub_path":"Visualisation/learning_curve_experiment_1.py","file_name":"learning_curve_experiment_1.py","file_ext":"py","file_size_in_byte":13749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"520120613","text":"from direct.showbase.ShowBase import ShowBase\nfrom direct.actor.Actor import Actor\nfrom math import pi\n\nimport sho\n\ndef cooTransform(cp):\n #cp.y, cp.z = cp.z, cp.y\n #cp.ty, cp.tz = cp.tz, cp.ty\n return cp\n\nclass MyApp(ShowBase):\n \n def __init__(self):\n ShowBase.__init__(self)\n # self.cube = Actor(\"models/panda-model\", {\"walk\": \"models/panda-walk4\"})\n # self.cube.reparentTo(self.render)\n # self.cube.setScale(0.005, 0.005, 0.005)\n # self.cube.setPos(-3, 10, 0)\n # self.cube.loop(\"walk\")\n\n self.cube = self.loader.loadModel(\"teapot\")\n self.cube.reparentTo(self.render)\n self.cube.setScale(1, 1, 1)\n self.cube.setPos(-3, 10, 5)\n\n self.environ = self.loader.loadModel(\"models/environment\")\n self.environ.reparentTo(self.render)\n self.environ.setScale(0.25, 0.25, 0.25)\n self.environ.setPos(-8, 42, -10)\n self.camera.setX(0)\n self.camera.setY(0)\n self.camera.setZ(0)\n\n self.taskMgr.add(self.taskFunction, \"test\")\n\n def taskFunction(self, task):\n camPos = cooTransform(sho.PTAMCAM())\n self.cube.setX(camPos.x)\n self.cube.setY(camPos.y)\n self.cube.setZ(camPos.z)\n #self.cube.setZ(-camPos.y+1)\n\n #self.camera.setX(camPos.x)\n # self.camera.setY(self.camera.getY() + 5)\n #self.camera.setZ(camPos.y)\n angDegX = (camPos.tx / pi) * 180.0\n angDegY = (camPos.ty / pi) * 180.0\n angDegZ = (camPos.tz / pi) * 180.0\n #print(camPos.x, camPos.y, camPos.z)\n #print angDegY\n #self.cube.setColor(240, 90, 8, 240)\n #self.camera.setHpr(-angDegY, 0, 0)\n #self.cube.setHpr(-angDegY+90, -angDegZ, 0)\n self.cube.setHpr(angDegX, angDegY, angDegZ)\n #self.cameraPositionNode.setHpr(angGe\n # self.cube.setHpr(angDegX, angDegY, angDegZ)\n return task.cont\n\napp = MyApp()\napp.run()\n\n","sub_path":"panda/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"114111968","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-v\n\nimport tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\n\nimport MySQLdb\nimport config.mysql\nimport config.app\nfrom chat_handler import chat_handler\n\nclass Application( tornado.web.Application ):\n\n def __init__( self ):\n\n self.database = MySQLdb.connect( \n host = config.mysql.host, \n user = config.mysql.user, \n passwd = config.mysql.password,\n db = config.mysql.database,\n charset = config.mysql.charset,\n port = config.mysql.port )\n\n handlers = [ (r'/chat/(\\w+)', chat_handler ) ]\n\n settings = {\n 'cookie_secret': config.app.cookie_secret,\n 'template_path': 'templates',\n 'static_path': 'static',\n 'debug': True\n }\n\n tornado.web.Application.__init__( self, handlers, **settings )\n\nif __name__ == '__main__':\n app = Application()\n\n server = tornado.httpserver.HTTPServer( app )\n server.listen( 8080 )\n tornado.ioloop.IOLoop.instance().start()","sub_path":"chat/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"512629759","text":"'''\n题目:\n编写input()和output()函数输入,输出5个学生的数据记录。\n\n程序分析:\n无。\n'''\n# !/usr/bin/python\n# _*_ coding: UTF-8 _*_\n\nN = 3\nstudent = []\nfor i in range(5):\n\tstudent.append(['','',[]])\n\t\ndef input_stu(stu):\n\tfor i in range(N):\n\t\tstu[i][0] = input('input student num: ')\n\t\tstu[i][1] = input('input student name: ')\n\t\tfor j in range(3):\n\t\t\tstu[j][2].append(int(input('score: ')))\n\t\t\t\ndef ouput_stu(stu):\n\tfor i in range(N):\n\t\tprint('%-6s%-10s' % (stu[i][0], stu[i][1]))\n\t\tfor j in range(3):\n\t\t\tprint('%-8d' % stu[i][2][j])\n\t\t\t\ninput_stu(student)\nprint(student)\nouput_stu(student)","sub_path":"Python/Sample 100/071.py","file_name":"071.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"35765289","text":"#-*- coding:utf-8 -*-\r\n#\r\n# Copyright (C) 2018 sthoo \r\n#\r\n# Support: Report an issue at https://github.com/sth2018/FastWordQuery/issues\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# any later version; http://www.gnu.org/copyleft/gpl.html.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n\r\nfrom collections import defaultdict\r\nimport os\r\nimport shutil\r\nimport unicodedata\r\n\r\nfrom aqt import mw\r\nfrom aqt.utils import showInfo, showText, tooltip\r\n\r\nfrom .worker import QueryWorkerManager\r\nfrom .common import promot_choose_css, inspect_note\r\n\r\nfrom ..constants import Endpoint, Template\r\nfrom ..context import config\r\nfrom ..lang import _\r\nfrom ..gui import ProgressWindow\r\nfrom ..service import service_manager, service_pool, QueryResult, copy_static_file\r\nfrom ..service.base import LocalService\r\nfrom ..utils import Empty, MapDict, Queue, wrap_css\r\n\r\n\r\n__all__ = ['query_from_browser', 'query_from_editor_fields']\r\n\r\n\r\ndef query_from_browser(browser):\r\n \"\"\"\r\n Query word from Browser\r\n \"\"\"\r\n\r\n if not browser:\r\n return\r\n\r\n notes = [browser.mw.col.getNote(note_id)\r\n for note_id in browser.selectedNotes()]\r\n\r\n if len(notes) == 1:\r\n query_from_editor_fields(browser.editor)\r\n else:\r\n query_all(notes)\r\n # browser.model.reset()\r\n\r\n\r\ndef query_from_editor_fields(editor, fields=None):\r\n \"\"\"\r\n Query word fileds from Editor\r\n \"\"\"\r\n\r\n if not editor or not editor.note:\r\n return\r\n\r\n word_ord, word, maps = inspect_note(editor.note)\r\n flush = not editor.addMode\r\n nomaps = True\r\n for each in maps:\r\n dict_unique = each.get('dict_unique', '').strip()\r\n ignore = each.get('ignore', True)\r\n if dict_unique and not ignore:\r\n nomaps = False\r\n break\r\n if nomaps:\r\n from ..gui import show_options\r\n tooltip(_('PLS_SET_DICTIONARY_FIELDS'))\r\n show_options(\r\n editor.parentWindow,\r\n editor.note.model()['id'],\r\n query_from_editor_fields,\r\n editor,\r\n fields\r\n )\r\n else:\r\n editor.setNote(editor.note)\r\n query_all([editor.note], flush, fields)\r\n editor.setNote(editor.note, focusTo=0)\r\n editor.saveNow(lambda:None)\r\n\r\n\r\ndef query_all(notes, flush=True, fields=None):\r\n \"\"\"\r\n Query maps word fileds\r\n \"\"\"\r\n\r\n if len(notes) == 0:\r\n return\r\n\r\n work_manager = QueryWorkerManager()\r\n #work_manager.reset()\r\n #progress.start(max=len(notes), min=0, immediate=True)\r\n work_manager.flush = flush\r\n work_manager.query_fields = fields\r\n queue = work_manager.queue\r\n\r\n for note in notes:\r\n queue.put(note)\r\n\r\n work_manager.start()\r\n work_manager.join()\r\n\r\n #progress.finish()\r\n promot_choose_css(work_manager.missed_css)\r\n tooltip(u'{0} {1} {2}, {3} {4}'.format(_('UPDATED'), work_manager.counter, _(\r\n 'CARDS'), work_manager.fields, _('FIELDS')))\r\n #work_manager.clean()\r\n service_pool.clean()\r\n","sub_path":"query/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"597355642","text":"import d2lzh as d2l\nfrom mxnet import gluon, init, nd\nfrom mxnet.gluon import nn\n\n#DenseNet模型\nnet = nn.Sequential()\nnet.add(nn.Conv2D(64, kernel_size=7, strides=2, padding=3),\n nn.BatchNorm(), nn.Activation('relu'),\n nn.MaxPool2D(pool_size=3, strides=2, padding=1))\n\nnum_channels, growth_rate = 64, 32 # num_channels:当前的通道数。\nnum_convs_in_dense_blocks = [4, 4, 4, 4]\nfor i, num_convs in enumerate(num_convs_in_dense_blocks):\n net.add(d2l.DenseBlock(num_convs, growth_rate))\n # 上⼀个稠密的输出通道数。\n num_channels += num_convs * growth_rate\n # 在稠密块之间加⼊通道数减半的过渡层。\n if i != len(num_convs_in_dense_blocks) - 1:\n net.add(d2l.transition_block(num_channels // 2))\n\nnet.add(nn.BatchNorm(), nn.Activation('relu'), nn.GlobalAvgPool2D(), nn.Dense(10))\n\n#获取数据并训练\nlr, num_epochs, batch_size, ctx = 0.1, 5, 256, d2l.try_gpu()\nnet.initialize(ctx=ctx, init=init.Xavier())\ntrainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr})\ntrain_iter, test_iter = d2l.load_data_fashion_mnist1(batch_size, resize=96)\nd2l.train_cnn(net, train_iter, test_iter, batch_size, trainer, ctx,num_epochs)\n","sub_path":"CNN/DenseNet.py","file_name":"DenseNet.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"135526280","text":"# Find Second Maximum Value in a List\r\n\r\n# Optimal Approach\r\n# Time - O(n)\r\n# Space - O(1)\r\n\r\ndef largest(arr, n):\r\n lar_1 = lar_2 = -2147483648\r\n if n < 2:\r\n return \"Error!\"\r\n for i in range(len(arr)):\r\n if arr[i] > lar_1:\r\n lar_2 = lar_1\r\n lar_1 = arr[i]\r\n elif arr[i] > lar_2 and arr[i] < lar_1:\r\n lar_2 = arr[i]\r\n return lar_2\r\n\r\n\r\narr = [12, 35, 1, 10, 34, 1]\r\nprint(largest(arr, len(arr)-1))\r\n","sub_path":"Second Maximum Value in a List.py","file_name":"Second Maximum Value in a List.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"247074522","text":"from player import Player\r\n\r\n\r\nclass Map:\r\n def __init__(self, roads):\r\n \"\"\"\r\n :param roads: all the roads that connect two towers\r\n :type roads: set\r\n \"\"\"\r\n self.roads = roads\r\n\r\n def move(self, tower1, tower2):\r\n \"\"\"\r\n :param tower1: the source tower for the warriors\r\n :type tower1: Tower\r\n :param tower2: the destination tower for the warriors\r\n :type tower2: Tower\r\n \"\"\"\r\n for road in self.roads:\r\n if road.tower1 == tower1 and road.tower2 == tower2:\r\n road.move_tower1_to_tower2()\r\n if road.tower1 == tower2 and road.tower2 == tower1:\r\n road.move_tower2_to_tower1()\r\n\r\n def winner(self):\r\n \"\"\"\r\n checks who the winner, if any yet, of the game\r\n :return: teh winner, or None if there is no wining player\r\n :rtype: Player\r\n \"\"\"\r\n players_with_towers = set()\r\n for road in self.roads:\r\n players_with_towers.add(road.tower1.team)\r\n players_with_towers.add(road.tower2.team)\r\n if len(players_with_towers) == 1:\r\n return next(iter(players_with_towers))\r\n elif len(players_with_towers) == 2:\r\n teams = iter(players_with_towers)\r\n first_team = next(teams)\r\n second_team = next(teams)\r\n if first_team == \"Gray\":\r\n return second_team\r\n elif second_team == \"Gray\":\r\n return first_team\r\n else:\r\n return None\r\n else:\r\n return None\r\n","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"562619169","text":"# -*- encoding:utf-8 -*-\nfrom scrapy.spiders import Spider\nimport scrapy\nfrom scrapy.selector import Selector\nimport io,sys\nimport re\n\nclass Dazhongdianping(Spider):\n name = 'dazhongdianping'\n allowed_domins = []\n start_urls = ['http://www.dianping.com/']\n\n def parse(self, response):\n a = input('请输入您要查找的内容:')\n # print(response.url)\n url = 'https://www.dianping.com/search/keyword/2/0_' + a\n yield scrapy.Request(url=url,callback=self.parse_item)\n\n def parse_item(self,response):\n sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')\n sel = Selector(response)\n all_li = sel.xpath(\"//div[@id='shop-all-list']/ul/li\")\n for li in all_li:\n try:\n link = li.xpath(\"./div[@class='txt']/div[@class='tit']/a/h4/text()\").extract()\n if link == []:\n raise Exception('title is null')\n else:\n link = link[0]\n # print(link)\n except:\n print('名字不能为空')\n all_ids = sel.xpath(\"//ul/li//div[@class='tit']/a/@data-shopid\").extract()\n all_id = set(all_ids)\n for id in all_id:\n url = 'http://www.dianping.com/shop/' + str(id)\n yield scrapy.Request(url=url,callback=self.parse_xiangxi)\n\n def parse_xiangxi(self,response):\n pass\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"spiders/dazhongdianping.py","file_name":"dazhongdianping.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"37201841","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Generates pybind11 type casters based on Clif_PyObjFrom and Clif_PyObjAs.\"\"\"\n\nimport os\nimport re\nimport types\n\nfrom typing import Generator, List, Set\n\nfrom clif.protos import ast_pb2\nfrom clif.pybind11 import utils\n\n\nI = utils.I\n_PYOBJFROM_ONLY = ', HasPyObjFromOnly'\n_PYOBJAS_ONLY = ', HasPyObjAsOnly'\n_PYBIND11_IGNORE = ', Pybind11Ignore'\n_CLIF_USE = re.compile(\n r'// *CLIF:? +use +`(?P.+)` +as +(?P[\\w.]+)'\n f'({_PYOBJFROM_ONLY}|{_PYOBJAS_ONLY}|{_PYBIND11_IGNORE}|)')\n\n\ndef get_imported_types(ast: ast_pb2.AST,\n include_paths: List[str]) -> Set[str]:\n \"\"\"Get cpp types that are imported from other header files.\"\"\"\n result = set()\n includes = set(ast.usertype_includes)\n for include in includes:\n if include.endswith('_clif.h'):\n clif_uses = _get_clif_uses(include, include_paths)\n for clif_use in clif_uses:\n result.add(clif_use.cpp_name)\n return result\n\n\ndef _get_clif_uses(\n include: str, include_paths: List[str]) -> List[types.SimpleNamespace]:\n \"\"\"Get all lines that are like `// CLIF use as `.\"\"\"\n results = []\n for root in include_paths:\n try:\n with open(os.path.join(root, include)) as include_file:\n lines = include_file.readlines()\n for line in lines:\n use = _CLIF_USE.match(line)\n if use and _PYBIND11_IGNORE not in use[0]:\n results.append(types.SimpleNamespace(\n cpp_name=use.group('cpp_name'), py_name=use.group('py_name'),\n generate_load=_PYOBJFROM_ONLY not in use[0],\n generate_cast=_PYOBJAS_ONLY not in use[0]))\n break\n except IOError:\n # Failed to find the header file in one directory. Try other\n # directories.\n pass\n else:\n raise NameError('include \"%s\" not found' % include)\n return results\n\n\ndef generate_from(ast: ast_pb2.AST,\n include_paths: List[str]) -> Generator[str, None, None]:\n \"\"\"Generates type casters based on Clif_PyObjFrom and Clif_PyObjAs.\n\n Args:\n ast: CLIF ast protobuf.\n include_paths: The directories that the code generator tries to find the\n header files.\n\n Yields:\n pybind11 type casters code.\n \"\"\"\n includes = set(ast.usertype_includes)\n\n for include in includes:\n # Not generating type casters for the builtin types.\n # Not scanning headers generated by pybind11 code generator because the\n # `// CLIF USE` in those headers do not have associated `Clif_PyObjFrom` or\n # `Clif_PyObjAs`.\n if (include.startswith('clif/python') or\n # Excluding absl::Status and absl::StatusOr\n include.startswith('util/task/python')):\n continue\n clif_uses = _get_clif_uses(include, include_paths)\n for clif_use in clif_uses:\n yield from _generate_type_caster(clif_use.py_name, clif_use.cpp_name,\n clif_use.generate_load,\n clif_use.generate_cast)\n\n\ndef _generate_type_caster(\n py_name: str, cpp_name: str, generate_load: bool,\n generate_cast: bool) -> Generator[str, None, None]:\n \"\"\"Generates pybind11 type caster code.\"\"\"\n yield 'namespace pybind11 {'\n yield 'namespace detail {'\n yield f'template <> struct type_caster<{cpp_name}> {{'\n yield ' public:'\n yield I + f'PYBIND11_TYPE_CASTER({cpp_name}, _(\"{py_name}\"));'\n yield ''\n if generate_load:\n yield I + 'bool load(handle src, bool) {'\n yield I + I + 'using ::clif::Clif_PyObjAs;'\n yield I + I + 'return Clif_PyObjAs(src.ptr(), &value);'\n yield I + '}'\n yield ''\n if generate_cast:\n yield I + (f'static handle cast({cpp_name} src, return_value_policy, '\n 'handle) {')\n yield I + I + 'using ::clif::Clif_PyObjFrom;'\n yield I + I + 'return Clif_PyObjFrom(src, {});'\n yield I + '}'\n yield '};'\n yield '} // namespace detail'\n yield '} // namespace pybind11'\n yield ''\n\n","sub_path":"clif/pybind11/type_casters.py","file_name":"type_casters.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"310573340","text":"from string import ascii_lowercase\nimport numpy as np\n\nwith open('./2017/input/aoc2017_04.txt', 'r') as f:\n data = f.read().split('\\n')\n\ndef part_1(data):\n valid_phrases = 0\n for l in data:\n d = l.split()\n valid = True\n for i in range(len(d)):\n if d[i] in d[:i]:\n valid = False\n break\n if d[i] in d[i+1:]:\n valid = False\n break\n if valid:\n valid_phrases += 1\n return valid_phrases\n\ndef part_2(data):\n valid_phrases = 0\n for l in data:\n d = l.split()\n valid = True\n for i in range(len(d)):\n for j in range(i+1, len(d)):\n if len(d[i]) == len(d[j]):\n w0 = np.zeros(len(ascii_lowercase))\n w1 = np.zeros(len(ascii_lowercase))\n for k in d[i]:\n w0[ord(k)-ord('a')] += 1\n for k in d[j]:\n w1[ord(k)-ord('a')] += 1\n if all(w0 == w1):\n valid = False\n if valid:\n valid_phrases += 1\n return valid_phrases\n\n\nprint(part_1(data))\nprint(part_2(data))\n","sub_path":"2017/aoc2017_04.py","file_name":"aoc2017_04.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"125950629","text":"import string, random\nimport operator\ngoal = 'abcdefghijklmnopqrstuvwxyzaaaaaaaaadsafasdfasdaaaa'\n\n\nclass indiv:\n\tdef __init__(self,str,score):\n\t\tself.str = str\n\t\tself.score = 0\n\nclass group:\n\tdef __init__(self, mutation, generation):\n\t\tself.mutation = 20\n\t\tself.generation = 0\n\t\tself.list = []\n\t\tself.finish = 0\n\tdef fitness(self):\n\t\tfor indivdual in self.list:\n\t\t\ti = 0\n\t\t\tscore_ = 0\n\t\t\tindivdual.score = 0\n\t\t\tfor letter in indivdual.str:\n\t\t\t\tif (letter == goal[i]):\n\t\t\t\t\tscore_+=1\n\t\t\t\ti+=1\n\t\t\tindivdual.score = pow(2,int(score_))\n\t\t\t#print('score', score_, 'str = ',indivdual.str)\n\n\n\tdef overcross(self):\n\t\tself.fitness()\n\t\tself.list = sorted(self.list, key=lambda indiv: indiv.score, reverse = True)\n\t\tprint(self.list[0].str)\n\t\tnewlist = []\n\t\tfor i in range(8000):\n\t\t\tindex1 = random.randrange(1, 100)\n\t\t\tindex2 = random.randrange(1, 100)\n\t\t\tparent1 = self.list[index1].str\n\t\t\tparent2 = self.list[index2].str\n\t\t\tnewstr = ''\n\n\t\t\tfor letter in range(len(goal)):\n\t\t\t\tseed = random.randrange(0, 50)\n\t\t\t\tif(seed < 23):\n\t\t\t\t\tnewstr = newstr + parent1[letter]\n\t\t\t\telif(seed >= 23 & seed <= 43):\n\t\t\t\t\tnewstr = newstr + parent2[letter]\n\t\t\t\telse:\n\t\t\t\t\tnewstr = newstr + randomString(1) #getting random letter\n\n\t\t\tif(newstr == goal):\n\t\t\t\tself.finish = 1\n\t\t\t\tprint(newstr)\n\t\t\t\tbreak\n\t\t\tnewlist.append(indiv(newstr,0))\n\n\t\tfor i in range(2000):\n\t\t\tnewlist.append(self.list[i])\n\n\t\tself.fitness()\n\t\tself.list = newlist\n\t\tself.generation+=1\n\n\ndef randomString(stringLength):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ncreature = group(0,0)\n\nfor i in range(10000):\n\tnew_str = randomString(len(goal))\n\tcreature.list.append(indiv(new_str,0))\n\nwhile creature.finish == 0:\n\tcreature.overcross()\n\nprint(creature.generation,'generations')\n\n\t\t\t\n\n\n\t\n\n\t\t\n\n","sub_path":"genetic_algo/genetic_algo.py","file_name":"genetic_algo.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"200013632","text":"from app import app\nfrom flask import render_template, flash, redirect, url_for, request\nfrom app import db\nfrom app.models import Contact\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\tall_data = Contact.query.all()\n\treturn render_template('index.html', contacts = all_data)\n\n@app.route('/view_contact/')\ndef view_contact(id):\n\tmy_data = Contact.query.get(id)\n\treturn render_template(\"view_contact.html\", contact = my_data)\n\n@app.route('/add_contact/', methods=['GET','POST'])\ndef add_contact():\n if request.method == \"POST\":\n first_name = request.form['first_name']\n last_name = request.form['last_name']\n phone_number = request.form['phone_number']\n email = request.form['email']\n note = request.form['note']\n my_data = Contact(first_name, last_name, phone_number, email, note)\n db.session.add(my_data)\n db.session.commit()\n flash(\"Contact Added Sucessfully\")\n return redirect(url_for(\"index\"))\n return render_template(\"add_contact.html\")\n\n@app.route('/edit_contact/',methods = ['GET', 'POST'])\ndef edit_contact(id):\n\tif request.method == \"POST\":\n\t\tmy_data = Contact.query.get(id)\n\t\tmy_data.first_name = request.form['first_name']\n\t\tmy_data.last_name= request.form['last_name']\n\t\tmy_data.phone_number = request.form['phone_number']\n\t\tmy_data.email = request.form['email']\n\t\tmy_data.note = request.form['note']\n\t\tdb.session.commit()\n\t\tflash(\"Product updated succesfully\")\n\t\treturn redirect(url_for(\"index\"))\n\telse:\n\t\tcontact = Contact.query.get(id)\n\t\treturn render_template(\"edit_contact.html\", contact = contact)\n\n@app.route(\"/delete_contact/\")\ndef delete_contact(id):\n\tmy_data = Contact.query.get(id)\n\tdb.session.delete(my_data)\n\tdb.session.commit()\n\tflash(\"Product Deleted succesfully\")\n\treturn redirect(url_for(\"index\"))\n\n","sub_path":"fullstack_projects/contact_manager/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"263475998","text":"from discord.ext import menus\nfrom utils.useful import Embed\n\nclass PlaylistSource(menus.ListPageSource):\n def __init__(self, data, playlist):\n super().__init__(data, per_page=10)\n self.playlist = playlist\n\n async def format_page(self, menu, entries):\n em = Embed(\n description=f\"\\🎶 Playlist `{self.playlist.name}` with `{self.playlist.length}` songs\\n\"+\"\\n\".join(entries)\n )\n em.set_footer(text=f\"Viewing page {menu.current_page + 1}/{self.get_max_pages()}\")\n return em\n\nclass QueueSource(menus.ListPageSource):\n def __init__(self, data, player):\n super().__init__(data, per_page=10)\n self.player = player\n\n async def format_page(self, menu, entries):\n em = Embed(\n description=f\"**Currently playing:**\\n **1.** [{self.player.current.title}]({self.player.current.uri})\\nRequested by {self.player.current.requester.mention}\\n\\n\"+\n f\"**Next up [{self.player.queue.qsize()}]: **\\n\" + \n \"\\n\".join(entries)\n )\n em.set_footer(text=f\"Page {menu.current_page + 1} of {self.get_max_pages()} | Looping track: {'❌' if not self.player.looping else '✅' }\")\n return em\n","sub_path":"main/utils/paginations.py","file_name":"paginations.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"76069227","text":"# coding: utf-8\n\n__author__ = 'zakharan'\n\nimport unittest\n\nfrom jassrealtime.core.settings_utils import *\n\n\nclass MyTestCase(unittest.TestCase):\n def test_get_settings_default_location(self):\n set = get_settings()\n self.assertEqual(set['SERVER_NAME'], \"localhost\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"jasstests/jassrealtime/core/test_settings_utils.py","file_name":"test_settings_utils.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"618241429","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.select_group, name='select_group'),\n path('chat/', views.chat, name='chat'),\n path('settings/', views.settings, name='settings'),\n path('add//', views.add, name='add'),\n path('remove//', views.remove, name='remove'),\n path('load_messages/', views.load_messages, name='load_messages')\n]\n","sub_path":"Chattie/Group_messages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"70369669","text":"def solution(participant, completion):\n participant.sort()\n completion.sort()\n answer = participant[len(participant)-1]\n for i in range(len(completion)):\n if(participant[i] != completion[i]):\n answer = participant[i]\n break\n return answer\n\ndef main():\n print(solution([\"leo\", \"kiki\", \"eden\"], [\"eden\", \"kiki\"]))\n print(solution([\"marina\", \"josipa\", \"nikola\", \"vinko\", \"filipa\"], [\"josipa\", \"filipa\", \"marina\", \"nikola\"]))\n print(solution([\"mislav\", \"stanko\", \"mislav\", \"ana\"], [\"stanko\", \"ana\", \"mislav\"]))\n print(solution([\"a\", \"b\", \"c\", \"d\", \"b\", \"d\"], ['a', 'b', 'b', 'd', 'd']))\n\nif __name__ == \"__main__\":\n main()","sub_path":"00_practice/04_완주하지 못한 선수.py","file_name":"04_완주하지 못한 선수.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"253918434","text":"from tkinter import *\r\nimport requests as r\r\nfrom bs4 import BeautifulSoup as bsp\r\nw=Tk()\r\nw.title(\"corona update\")\r\nw.geometry(\"700x500\")\r\ndef covd():\r\n if(e.get()==\"world\"):\r\n url=\"https://www.worldometers.info/coronavirus/\"\r\n else:\r\n url=\"https://www.worldometers.info/coronavirus/country/\"+e.get()\r\n page=r.get(url)\r\n soup=bsp(page.content,\"html.parser\")\r\n #print(soup)\r\n info=soup.find_all(class_=\"maincounter-number\")\r\n l=[]\r\n for item in info:\r\n l.append(item.get_text())\r\n l1=Label(w,text=\"Coronavirus Cases in \"+e.get()+\":\"+l[0]).pack()\r\n #l1.config(w,text=\"Coronavirus Cases in \"+e.get()+\":\"+l[0]).pack()\r\n l2=Label(w,text=\"Deaths in \"+e.get()+\":\"+l[1]).pack()\r\n l3=Label(w,text=\"Recovered in \"+e.get()+\":\"+l[2]).pack()\r\ne=Entry(w,width=60)\r\ne.pack()\r\nb=Button(w,text=\"submit\",command=covd).pack()\r\nw.mainloop()\r\n","sub_path":"covid_cases_tracker.py","file_name":"covid_cases_tracker.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"650460550","text":"import os\n\n\nclass BatchRename:\n def __init__(self):\n self.path = '/home/xkjs/PycharmProjects/pre_process/plot_result/'\n\n def rename(self):\n filelist = os.listdir(self.path)\n total_num = len(filelist)\n i = 0\n for item in filelist:\n if item.__contains__(\"'\"):\n # print(item)\n print(str(item.replace(\"'\", \"\")))\n new_item = str(item.replace(\"'\", \"\"))\n src = os.path.join(os.path.abspath(self.path), item)\n if i < 1000:\n dst = os.path.join(os.path.abspath(self.path), new_item)\n\n try:\n os.rename(src, dst)\n print('converting %s to %s ...' % (src, dst))\n i = i + 1\n except:\n continue\n print('total %d to rename %d images' % (total_num, i))\n\n\nif __name__ == '__main__':\n demo = BatchRename()\n demo.rename()\n","sub_path":"batch_rename.py","file_name":"batch_rename.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"354259975","text":"import pandas as pd\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport sys\n\n# http://tinyurl.com/mbhn3t6\n\nroad_filename = '../../../data/roads.json'\n\nprint('load data...')\nusecols = ['starting_latitude', 'starting_longitude']\ndf = pd.read_csv(\n '../../../data/data_train_competition.csv', usecols=usecols)\ndf.columns = ['lat', 'lon']\ndf = df.sample(frac=0.01)\n\nXtr = df.as_matrix(['lat', 'lon'])\n\nwith open(road_filename, 'r') as f:\n roads = json.load(f)\n\nprint('calculate distances...')\nroads_dist = np.zeros((len(roads), len(Xtr)))\n\nfor roadi, road in enumerate(roads):\n sys.stdout.write('\\r%4.1f' % (100*roadi/len(roads)))\n sys.stdout.flush()\n assert len(road) > 1\n road = np.asarray(road)\n\n A = road[:-1][:, :, np.newaxis]\n B = road[1:][:, :, np.newaxis]\n\n C = Xtr\n C = np.rollaxis(C, 1)[np.newaxis, :, :]\n C = np.repeat(C, len(A), 0)\n\n AB = B-A\n AC = C-A\n cross = AB[:, 0, :]*AC[:, 1, :] - AB[:, 1, :]*AC[:, 0, :]\n distAB = np.sqrt((A[:, 0, :]-B[:, 0, :])**2 + (A[:, 1, :]-B[:, 1, :])**2)\n distBC = np.sqrt((B[:, 0, :]-C[:, 0, :])**2 + (B[:, 1, :]-C[:, 1, :])**2)\n distAC = np.sqrt((A[:, 0, :]-C[:, 0, :])**2 + (A[:, 1, :]-C[:, 1, :])**2)\n\n dist = np.abs(cross / distAB)\n\n # check if outside the segment\n BC = C-B\n dot1 = AB[:, 0, :]*BC[:, 0, :] + AB[:, 1, :]*BC[:, 1, :]\n dot2 = (-AB[:, 0, :])*AC[:, 0, :] + (-AB[:, 1, :])*AC[:, 1, :]\n\n res = \\\n (dot1 >= 0)*distBC + \\\n (dot2 >= 0)*distAC + \\\n np.logical_and(dot1 < 0, dot2 < 0)*dist\n roads_dist[roadi] = np.min(res, 0)\n\nsys.stdout.write('\\r \\r')\n\nno_road = np.array(np.repeat(0.002, len(Xtr)), ndmin=2)\nroads_dist = np.r_[roads_dist, no_road]\nroadss = np.argmin(roads_dist, 0)\n\nprint('plot...')\ncolors = cm.Accent(np.linspace(0, 1, len(roads)))\nblack = np.array((0, 0, 0, 1), ndmin=2)\ncolors = np.r_[colors, black]\nmycolors = [colors[i] for i in roadss]\nplt.scatter(Xtr[:, 0], Xtr[:, 1], 3, mycolors)\nplt.show()\n","sub_path":"tests/segmentation/roads.py","file_name":"roads.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"637027373","text":"import os\nfrom fabric.api import cd, run\nfrom fabric.contrib.files import exists, upload_template\n\nDEPLOY_REPO_URL = os.environ['DEPLOY_REPO_URL']\nDEPLOY_TARGET = os.environ['DEPLOY_TARGET']\nDEPLOY_VENV_PATH = os.environ['DEPLOY_VENV_PATH']\nDEPLOY_VENV_NAME = os.environ['DEPLOY_VENV_NAME']\nDEPLOY_DEBUG = os.environ['DEPLOY_DEBUG']\nDEPLOY_DATABASE_URL = os.environ['DEPLOY_DATABASE_URL']\nDEPLOY_SECRET_KEY = os.environ['DEPLOY_SECRET_KEY']\nDEPLOY_CSRF_COOKIE_SECURE = os.environ['DEPLOY_CSRF_COOKIE_SECURE']\nDEPLOY_SESSION_COOKIE_SECURE = os.environ['DEPLOY_SESSION_COOKIE_SECURE']\nDEPLOY_USER = os.environ['DEPLOY_USER']\nDEPLOY_DB_NAME = os.environ['DEPLOY_DB_NAME']\nDEPLOY_DB_USER = os.environ['DEPLOY_DB_USER']\nDEPLOY_SUPERVISOR_NAME = os.environ['DEPLOY_SUPERVISOR_NAME']\n\n\ndef _get_latest_source():\n run('mkdir -p {}'.format(DEPLOY_TARGET))\n if exists(os.path.join(DEPLOY_TARGET, '.hg')):\n run('cd {} && hg pull -u'.format(DEPLOY_TARGET))\n else:\n run('hg clone {} {}'.format(DEPLOY_REPO_URL, DEPLOY_TARGET))\n run('cd {} && hg update'.format(DEPLOY_TARGET))\n\n\ndef _create_dirs():\n # Ensure that required directories exist.\n with cd(DEPLOY_TARGET):\n run('mkdir -p logs && mkdir -p media')\n\n\ndef _update_venv():\n # Assumes that virtualenv is installed system-wide.\n with cd(DEPLOY_VENV_PATH):\n if not exists('{}/bin/pip'.format(DEPLOY_VENV_NAME)):\n run('virtualenv {}'.format(DEPLOY_VENV_NAME))\n run('{}/bin/pip install -r requirements.txt'.format(DEPLOY_VENV_NAME))\n\n\ndef _setup_env():\n with cd(DEPLOY_TARGET):\n context = {\n 'DEPLOY_DEBUG': DEPLOY_DEBUG,\n 'DEPLOY_DATABASE_URL': DEPLOY_DATABASE_URL,\n 'DEPLOY_SECRET_KEY': DEPLOY_SECRET_KEY,\n 'DEPLOY_CSRF_COOKIE_SECURE': DEPLOY_CSRF_COOKIE_SECURE,\n 'DEPLOY_SESSION_COOKIE_SECURE': DEPLOY_SESSION_COOKIE_SECURE,\n }\n upload_template('templates/env.jinja', '.env', context, use_jinja=True, backup=False)\n\n\ndef _setup_supervisor_conf():\n with cd(DEPLOY_TARGET):\n context = {\n 'DEPLOY_SUPERVISOR_NAME': DEPLOY_SUPERVISOR_NAME,\n 'DEPLOY_USER': DEPLOY_USER,\n 'DEPLOY_TARGET': DEPLOY_TARGET,\n 'DEPLOY_VENV_PATH': DEPLOY_VENV_PATH,\n 'DEPLOY_VENV_NAME': DEPLOY_VENV_NAME,\n }\n upload_template(\n 'templates/supervisor.jinja', '{}.conf'.format(DEPLOY_SUPERVISOR_NAME),\n context, use_jinja=True, backup=False)\n\n\ndef _chown():\n # Assumes that the DEPLOY_USER user exists on the target server.\n run('chown -R {0}:{0} {1}'.format(DEPLOY_USER, DEPLOY_TARGET))\n\n\ndef _collectstatic():\n with cd(DEPLOY_TARGET):\n run_str = 'source {}/{}/bin/activate && honcho run python manage.py collectstatic --noinput'\n run(run_str.format(DEPLOY_VENV_PATH, DEPLOY_VENV_NAME), shell='/bin/bash')\n\n\ndef _create_db():\n # This script assumes that PGHOST and PGUSER are set.\n db = {\n 'NAME': os.environ['DEPLOY_DB_NAME'],\n 'USER': os.environ['DEPLOY_DB_USER'],\n }\n sql = '''CREATE DATABASE {NAME} OWNER {USER};\n \\c {NAME}'''.format(**db)\n run('echo \"{}\" | psql -d postgres'.format(sql))\n\n\ndef _migrate():\n with cd(DEPLOY_TARGET):\n run_str = 'source {}/{}/bin/activate && honcho run python manage.py migrate'\n run(run_str.format(DEPLOY_VENV_PATH, DEPLOY_VENV_NAME), shell='/bin/bash')\n\n\n# --------------------------------------------------\n# IBMS-specific scripts\n# --------------------------------------------------\ndef deploy_env():\n \"\"\"Normally used to deploy a new environment. Won't harm an existing one.\n Example usage: honcho run fab deploy_env --user=root --host=aws-oim-001\n \"\"\"\n _get_latest_source()\n _create_dirs()\n _update_venv()\n _setup_env()\n _chown()\n _setup_supervisor_conf() # After the _chown step.\n _collectstatic()\n\n\ndef deploy_db():\n \"\"\"Normally used to deploy a new database (idempotent).\n Example usage: honcho run fab deploy_db --user=root --host=aws-oim-001\n \"\"\"\n _create_db()\n _migrate()\n\n\ndef deploy_all():\n \"\"\"Deploy to a new environment in one step. Non-destructive, but will\n raise lots of errors for an existing environment.\n \"\"\"\n deploy_env()\n deploy_db()\n\n\ndef deploy_update():\n \"\"\"Update only: pulls repo changes, runs migrations, runs collectstatic.\n \"\"\"\n _get_latest_source()\n _update_venv()\n _migrate()\n _collectstatic()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"177216545","text":"# At one value of beta_e, plot resolution scan frequencies\r\nfrom numpy import *\r\nfrom scipy import special\r\nfrom scipy import optimize\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom matplotlib import rc\r\n\r\ndef plasmaDisp(z):\r\n return 1j*sqrt(pi)*exp(-z**2)*(1+special.erf(1j*z))\r\n\r\ndef derivPlasmaDisp(z):\r\n return -2*(1+z*plasmaDisp(z))\r\n\r\ndef eps(z,beta_e_val):\r\n return (m_i/m_e*beta_e_val*z**2-1)*(1+z*plasmaDisp(z)) - kPerpRho**2\r\n\r\ndef derivEps(z,beta_e_val):\r\n return (2*m_i/m_e*beta_e_val*z)*(1+z*plasmaDisp(z)) + (m_i/m_e*beta_e_val*z**2-1)*(plasmaDisp(z)+z*derivPlasmaDisp(z))\r\n\r\n# Number of points to calculate damping rate at\r\nm_i = 1.672621777e-27\r\nm_e = 9.10938188e-31\r\nmu0 = 4e-7*pi\r\nkPar = 0.5\r\nB = 1\r\nTe0 = 250\r\neV = 1.602176565e-19\r\n\r\ntol = 1e-8\r\n\r\nkPerpRho = 0.1\r\nnSim = 9.947e19\r\n\r\nbeta_e = 2*mu0*Te0*eV*nSim/B**2\r\nvA = B/sqrt(mu0*m_i*nSim)\r\n# Initial guess for z0 = omega/(k*sqrt(2)*vTe) using approximate expression for wave frequency\r\nz0 = vA/(sqrt(2*Te0*eV/m_e)*sqrt(1+2/beta_e*m_e/m_i*kPerpRho**2))\r\n# Root finder call\r\nz0 = optimize.newton(eps,z0,derivEps,(beta_e,),tol,10000)\r\n# Store exact result\r\nexactFreq = fabs(z0.real*sqrt(2*Te0*eV/m_e)/vA);\r\n# Lame way to create list of three elements of same value\r\nexactFreqList = [exactFreq, exactFreq, exactFreq]\r\n\r\n# Data measured from simulation\r\ncflList = [0.01, 0.001, 0.0001]\r\ntSimList = [2.343682e-6, 2.343678e-6, 2.343677e-6]\r\nomegaSim = zeros(len(cflList))\r\n# Compute normalized simulation frequencies\r\nfor index, tSim in enumerate(tSimList):\r\n # Really normalized to k*vA\r\n # Divide by 2 to compare with wave freq\r\n omegaSim[index] = 0.5*(2*pi/tSim)/(kPar*B/sqrt(mu0*nSim*m_i))\r\n\r\nplt.semilogx(cflList, omegaSim,'r-o',label='Sim')\r\nplt.semilogx(cflList, exactFreqList,'b-o',label='Exact')\r\n\r\nplt.ylabel(r'$\\omega/(k_\\parallel v_A)$', color='r')\r\nplt.xlabel('CFL Number')\r\nplt.legend(loc='right')\r\nplt.title(r'Time Step Scan for $k_\\perp \\rho_s$=0.1, $\\beta_e$=0.01')\r\n#plt.ylim([0,8])\r\n#plt.autoscale(enable=True,axis='y',tight=True)\r\nplt.savefig('kaw_0_1_time.pdf')\r\nplt.show()\r\n#plt.close()\r\n","sub_path":"eric/ionacousticKinetic/emComparisons/kPerp_0_1_time_scan/computeKAWDispersion_time.py","file_name":"computeKAWDispersion_time.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"128119501","text":"from datetime import datetime\nimport uuid\n\nimport pytest\nimport requests_mock\n\nfrom slingshot.app import (\n create_record,\n GeoServer,\n HttpSession,\n make_slug,\n make_uuid,\n publish_layer,\n publishable_layers,\n Solr,\n unpack_zip,\n)\n\n\ndef test_unpack_zip_extracts_to_bucket(s3, shapefile):\n with open(shapefile, 'rb') as fp:\n s3.Bucket(\"upload\").put_object(Key=\"bermuda.zip\", Body=fp)\n unpack_zip(\"upload\", \"bermuda.zip\", \"store\")\n objs = [o.key for o in s3.Bucket(\"store\").objects.all()]\n assert 'bermuda/bermuda.shp' in objs\n\n\ndef test_create_record_creates_record(shapefile_object):\n record = create_record(shapefile_object, \"http://example.com\",\n \"http://example.com/download\")\n assert record.dct_provenance_s == 'MIT'\n assert record.dct_references_s.get(\n 'http://www.opengis.net/def/serviceType/ogc/wms') == \\\n 'http://example.com/wms'\n assert record.dct_references_s.get(\"http://schema.org/downloadUrl\") == \\\n \"http://example.com/download/{}\".format(record.layer_slug_s)\n assert record.layer_id_s == \"public:bermuda\"\n\n\ndef test_create_record_adds_fgdc_url(shapefile_object):\n record = create_record(shapefile_object, \"http://example.com\",\n \"http://example.com/download\")\n assert record.dct_references_s.\\\n get(\"http://www.opengis.net/cat/csw/csdgm\") == \\\n \"https://store.s3.amazonaws.com/bermuda/bermuda.xml\"\n\n\ndef test_geoserver_adds_shapefile(shapefile_object):\n geoserver = GeoServer(\"mock://example.com/geoserver/\", HttpSession())\n with requests_mock.Mocker() as m:\n m.post(\"mock://example.com/geoserver/rest/workspaces/public/\"\n \"datastores/pg/featuretypes\")\n geoserver.add(shapefile_object)\n assert m.request_history[0].text == \\\n '{\"featureType\": {\"name\": \"bermuda\"}}'\n\n\ndef test_solr_adds_layer_to_solr():\n with requests_mock.Mocker() as m:\n m.post('mock://example.com/update/json/docs')\n s = Solr('mock://example.com/', HttpSession())\n s.add({'foo': 'bar'})\n assert m.request_history[0].json() == {'foo': 'bar'}\n\n\ndef test_solr_deletes_by_query():\n with requests_mock.Mocker() as m:\n m.post('mock://example.com/update')\n s = Solr('mock://example.com/', HttpSession())\n s.delete()\n assert m.request_history[0].json() == \\\n {'delete': {'query': 'dct_provenance_s:MIT'}}\n\n\ndef test_solr_commits_changes():\n with requests_mock.Mocker() as m:\n m.post('mock://example.com/update')\n s = Solr('mock://example.com/', HttpSession())\n s.commit()\n assert m.request_history[0].json() == {'commit': {}}\n\n\ndef test_make_uuid_creates_uuid_string():\n assert make_uuid('bermuda', 'mit.edu') == \\\n uuid.UUID('df04b29c-0e51-58a8-8a37-557e4f4917df')\n\n\ndef test_make_slug_creates_slug():\n assert make_slug('bermuda') == 'mit-34clfhaokfmkq'\n\n\n@pytest.mark.integration\ndef test_publish_layer_makes_fgdc_public(s3, shapefile, db):\n s3.Bucket(\"upload\").upload_file(shapefile, \"bermuda.zip\")\n with requests_mock.Mocker() as m:\n m.post(\"mock://example.com/geoserver/rest/workspaces/public/\"\n \"datastores/pg/featuretypes\")\n m.post(\"mock://example.com/solr/update/json/docs\")\n publish_layer(\"upload\", \"bermuda.zip\",\n GeoServer(\"mock://example.com/geoserver\", HttpSession()),\n Solr(\"mock://example.com/solr\", HttpSession()),\n \"store\", \"mock://example.com/ogc\",\n \"mock://example.com/download\")\n obj = s3.Bucket(\"store\").Object(\"bermuda/bermuda.xml\")\n grants = [g for g in obj.Acl().grants if g['Grantee'].get(\"URI\") ==\n 'http://acs.amazonaws.com/groups/global/AllUsers']\n assert grants.pop()['Permission'] == 'READ'\n\n\n@pytest.mark.integration\ndef test_publish_layer_uses_ogc_proxy_url(s3, shapefile, db):\n s3.Bucket(\"upload\").upload_file(shapefile, \"bermuda.zip\")\n with requests_mock.Mocker() as m:\n m.post(\"mock://example.com/geoserver/rest/workspaces/public/\"\n \"datastores/pg/featuretypes\")\n m.post(\"mock://example.com/solr/update/json/docs\")\n publish_layer(\"upload\", \"bermuda.zip\",\n GeoServer(\"mock://example.com/geoserver\", HttpSession()),\n Solr(\"mock://example.com/solr\", HttpSession()),\n \"store\", \"mock://example.com/ogc/\",\n \"mock://example.com/download\")\n obj = s3.Bucket(\"store\").Object(\"bermuda/geoblacklight.json\")\n assert \"mock://example.com/ogc/wms\" in obj.get()['Body'].read()\\\n .decode('utf8')\n\n\ndef test_publishable_layers_includes_new_layer(s3, dynamo_table):\n upload = s3.Bucket(\"upload\")\n upload.put_object(Key=\"foo.zip\", Body=\"Some data\")\n layers = list(publishable_layers(upload, dynamo_table))\n assert layers.pop() == \"foo.zip\"\n\n\ndef test_publishable_layers_includes_updated_layer(s3, dynamo_table):\n awhile_ago = datetime(1980, 1, 1).isoformat()\n dynamo_table.put_item(Item={\"LayerName\": \"foo\",\n \"LastMod\": awhile_ago})\n upload = s3.Bucket(\"upload\")\n upload.put_object(Key=\"foo.zip\", Body=\"Some data\")\n layers = list(publishable_layers(upload, dynamo_table))\n assert layers.pop() == \"foo.zip\"\n\n\ndef test_publishable_layers_skips_old_layer(s3, dynamo_table):\n the_future = datetime(2080, 1, 1).isoformat()\n # This test will fail in the year 2080. Probably ok. I'll be dead anyways.\n dynamo_table.put_item(Item={\"LayerName\": \"foo\",\n \"LastMod\": the_future})\n upload = s3.Bucket(\"upload\")\n upload.put_object(Key=\"foo.zip\", Body=\"Some data\")\n layers = list(publishable_layers(upload, dynamo_table))\n assert not layers\n","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"343626133","text":"import time\nimport json\nimport hashlib\n\nclass Block:\n def __init__(self, index, sender, receiver, amount, timestamp, previous_hash, nonce = 0):\n self.index = index\n self.sender = sender\n self.receiver = receiver\n self.amount = amount\n self.timestamp = timestamp\n self.nonce = nonce\n self.hash = \"\"\n self.previous_hash = previous_hash\n\n def compute_hash(self):\n #block_string = json.dumps(self.__dict__, sort_keys=True)\n #block_string = str(self.index) + (str(self.timestamp)).replace(\".\",\"\") + self.previous_hash + str(self.nonce)\n\n block_string = self.previous_hash + str(self.nonce)\n\n return hashlib.sha1(block_string.encode()).hexdigest()\n\n\nclass Blockchain:\n difficulty = 1\n\n def __init__(self):\n self.chain = []\n self.create_genesis_block()\n\n def create_genesis_block(self):\n genesis_block = Block(0, \"AVR\", \"GENESIS\", 0, time.time(), \"0\"*40)\n genesis_block.hash = genesis_block.compute_hash()\n (self.chain).append(genesis_block)\n\n\n def last_block(self):\n return self.chain[-1]\n\n def proof_of_work(self, block):\n computed_hash = \"\"\n while not computed_hash.startswith(\"0\"*Blockchain.difficulty):\n block.nonce += 1\n block.hash = computed_hash = block.compute_hash()\n\n print(\"Block mined with a nonce: \" + str(block.nonce))\n return computed_hash\n\n def add_block(self, block, proof):\n previous_hash = self.last_block().hash\n\n if previous_hash != block.previous_hash:\n return False\n\n if not self.is_valid_proof(block, proof):\n return False\n\n block.hash = proof\n self.chain.append(block)\n return True\n\n\n def is_valid_proof(self, block, proof):\n return (block.hash.startswith('0'*Blockchain.difficulty)) and proof == block.compute_hash()\n\n def mine(self):\n print(\"Mining ...\")\n last_block = self.last_block()\n new_block = Block(index = last_block.index+1, sender=\"AVR\", receiver=\"jaychandra\", amount=100, timestamp = time.time(), previous_hash = last_block.hash)\n proof = self.proof_of_work(new_block)\n\n self.add_block(new_block, proof)\n return new_block\n\n\nb = Blockchain()\n\nfrom flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\n@app.route(\"/mine\", methods=['GET'])\ndef mine_route():\n block = b.mine()\n s = {\n \"Block index\" : block.index,\n \"Hash \" : block.hash,\n \"Previous Hash \" : block.previous_hash,\n \"Timestamp \" : block.timestamp,\n \"sender\" : block.sender,\n \"receiver\" : block.receiver,\n \"amount\" : block.amount\n }\n\n return jsonify(s)\n\n@app.route(\"/chain\", methods=['GET'])\ndef get_chain():\n chain = b.chain\n res = []\n\n for block in chain:\n s = {\n \"Block index\" : block.index,\n \"Hash \" : block.hash,\n \"Previous Hash \" : block.previous_hash,\n \"Timestamp \" : block.timestamp,\n \"sender\" : block.sender,\n \"receiver\" : block.receiver,\n \"amount\" : block.amount\n }\n\n res.append(s)\n return jsonify(res)\n\n\n#this block will send the most recent block's data to the microcontroller\n@app.route(\"/get_data\", methods=['GET'])\ndef get_data():\n block = b.chain[-1]\n s = {\n \"previous_hash\":block.hash,\n \"index\" : block.index,\n \"timestamp\" : block.timestamp,\n \"index\" : block.index\n }\n\n return jsonify(s)\n\n\n#this route will accept data from avr microcontrollers mined data and will accept or reject it\n@app.route(\"/block\", methods=['POST'])\ndef block_route():\n json_data = request.json\n print(json_data)\n \n last_block = b.chain[-1]\n\n new_block = Block(index = last_block.index+1, sender=json_data[\"sender\"], receiver=json_data[\"receiver\"], amount=json_data[\"amount\"], timestamp = time.time(), previous_hash = last_block.hash, nonce = json_data[\"nonce\"])\n new_block.hash = json_data[\"hash\"]\n proof = json_data[\"hash\"]\n\n #print(b.is_valid_proof(new_block, proof))\n\n if(b.add_block(new_block, proof)):\n return jsonify({\"message\" : \"ACCEPTED\"})\n\n\n\n return jsonify({\"message\" : \"REJECTED\"})\n\napp.run(port=3000, debug=True)\n","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"448924777","text":"# first ex creating function\n# def = definition, ( parameter)\n# docstring is second line under def for notes\n\ndef print_num(x):\n \"\"\"this is a docstring for user info\"\"\"\n a = 0\n while a < x:\n print(\"num: \",a, end=',')\n a += 1\n\nprint_num(10)\n\n# rename function\np = print_num\np(3)\n\ndef return_nums(x):\n \"\"\"this time we return the values\"\"\"\n print(\"here is round two, with return!\")\n \n arr = []\n y = 1\n while y < x:\n arr.append(y)\n y += 1\n return arr\n\nresult = return_nums(20)\n# print out returned array of values\n# print(result) // works correctly\n\ndef def1(prompt):\n val = input(prompt)\n if prompt in ('y', 'ye','yes'):\n return \"True\"\n else:\n return \"false\"\ndef1(\"hi\")\n\n\n\n","sub_path":"defining_fx.py","file_name":"defining_fx.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"295851379","text":"from insights.core.plugins import make_response, rule\nfrom insights.parsers.secure_shell import SshDConfig\nfrom insights.parsers.installed_rpms import InstalledRpms\n\nERROR_KEY = \"SSHD_SECURE\"\n\n\ndef check_auth_method(sshd_config, errors):\n auth_method = sshd_config.last('AuthenticationMethods')\n if auth_method:\n if auth_method.lower() != 'publickey':\n errors['AuthenticationMethods'] = auth_method\n else:\n errors['AuthenticationMethods'] = 'default'\n return errors\n\n\ndef check_log_level(sshd_config, errors):\n log_level = sshd_config.last('LogLevel')\n if log_level:\n if log_level.lower() != 'verbose':\n errors['LogLevel'] = log_level\n else:\n errors['LogLevel'] = 'default'\n return errors\n\n\ndef check_permit_root(sshd_config, errors):\n permit_root = sshd_config.last('PermitRootLogin')\n if permit_root:\n if permit_root.lower() != 'no':\n errors['PermitRootLogin'] = permit_root\n else:\n errors['PermitRootLogin'] = 'default'\n return errors\n\n\ndef check_protocol(sshd_config, errors):\n # Default Protocol is 2 if not specified\n protocol = sshd_config.last('Protocol')\n if protocol:\n if protocol.lower() != '2':\n errors['Protocol'] = protocol\n return errors\n\n\n@rule(InstalledRpms, SshDConfig)\ndef report(installed_rpms, sshd_config):\n errors = {}\n errors = check_auth_method(sshd_config, errors)\n errors = check_log_level(sshd_config, errors)\n errors = check_permit_root(sshd_config, errors)\n errors = check_protocol(sshd_config, errors)\n\n if errors:\n openssh_version = installed_rpms.get_max('openssh')\n return make_response(ERROR_KEY, errors=errors, openssh=openssh_version.package)\n","sub_path":"docs/examples/rules/sshd_secure.py","file_name":"sshd_secure.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"191185488","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass WuxiabotSpider(scrapy.Spider):\n name = 'wuxiabot'\n allowed_domains = ['www.wuxiaworld.com']\n #Input whatever link you want to start from into start_urls on Wuxiaworld\n #Multiple links can be added with , after each one.\n start_urls = ['https://www.wuxiaworld.com/novel/child-of-light/col-volume-5-chapter-9/']\n\n def parse(self, response):\n \tSET_SELECTOR = '//div[@class=\"p-15\"]'\n \tfor story in response.xpath(SET_SELECTOR):\n #Selects the Title\n \t\tTITLE_SELECTOR = 'div h4 ::text'\n #Selects the Story paragraph by paragraph\n \t\tSTORY_SELECTOR = 'div p span ::text'\n \t\tyield {\n \t\t'title': story.css(TITLE_SELECTOR).extract_first(), \n \t\t'story': story.css(STORY_SELECTOR).extract()\n \t\t}\n #Selects the next button\n \tNEXT_PAGE_SELECTOR = '//li[@class=\"next\"]//a/@href'\n \tnext_page = response.xpath(NEXT_PAGE_SELECTOR).extract_first()\n \tif next_page:\n \t\tyield scrapy.Request(\n \t\t\tresponse.urljoin(next_page),\n \t\t\tcallback=self.parse\n \t\t)\n\n\n","sub_path":"ww/ww/spiders/wuxiabot.py","file_name":"wuxiabot.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"335134400","text":"\"\"\"\nPython Bokeh program which interactively change two vectos and display its sum\n\ndone by :Rishith Ellath Meethal\n\"\"\"\n\nfrom bokeh.plotting import figure \nfrom bokeh.layouts import column, row\nfrom bokeh.models import ColumnDataSource, Slider, LabelSet, Arrow, OpenHead, Line,Div\nfrom bokeh.io import curdoc\nfrom os.path import dirname, join\nimport numpy as np\n\n\n\n#Plot source:\nplot_source = ColumnDataSource(data=dict(x = np.linspace(0,40,100), y = np.linspace(0,0,100)))\n\n#Force Vectors\nP1_arrow_source = ColumnDataSource(data=dict(xS=[], xE=[], yS=[], yE=[], lW = []))\nP2_arrow_source = ColumnDataSource(data=dict(xS=[], xE=[], yS=[], yE=[], lW = []))\nF1_arrow_source = ColumnDataSource(data=dict(xS=[], xE=[], yS=[], yE=[], lW = []))\nF2_arrow_source = ColumnDataSource(data=dict(xS=[], xE=[], yS=[], yE=[], lW = []))\n#labels for Forces\nP1_label_source = ColumnDataSource(data=dict(x=[],y=[],P1=[]))\nP2_label_source = ColumnDataSource(data=dict(x=[],y=[],P2=[]))\nF1_label_source = ColumnDataSource(data=dict(x=[],y=[],F1=[]))\nF2_label_source = ColumnDataSource(data=dict(x=[],y=[],F2=[]))\n#Triangle source:\ntriangle_source = ColumnDataSource(data=dict(x= [], y= [], size = []))\n#plot corresponding to change in Force\nForcegraphTop=ColumnDataSource(data=dict(x=[], y=[])) \nForcegraphBottom=ColumnDataSource(data=dict(x=[], y=[])) \n\n\ndef initialise():\n P1_arrow_source.data = dict(xS=[0], xE=[0], yS=[-10], yE=[0], lW = [5])\n P1_label_source.data = dict(x=[1],y=[-7],P1=[\"P\"u\"\\u2081\"])\n P2_arrow_source.data = dict(xS=[40], xE=[40], yS=[10], yE=[0], lW = [5])\n P2_label_source.data = dict(x=[37.5],y=[5],P2=[\"P\"u\"\\u2082\"])\n F1_arrow_source.data = dict(xS=[0], xE=[0], yS=[10], yE=[0], lW = [5])\n F1_label_source.data = dict(x=[1],y=[5],F1=[\"F\"u\"\\u2081\"])\n F2_arrow_source.data = dict(xS=[40], xE=[40], yS=[-10], yE=[0], lW = [5])\n F2_label_source.data = dict(x=[37.5],y=[-7],F2=[\"F\"u\"\\u2082\"])\n triangle_source.data = dict(x = [20], y = [-2], size = [20,20]) \n ForcegraphTop.data = dict(x =[0],y =[10] )\n ForcegraphBottom.data = dict(x =[40],y =[-10] )\n\n\nplot = figure(title=\"\", x_range=(0-2,40+2), y_range=(-50,50))\nplot.axis.axis_label_text_font_style=\"normal\"\nplot.axis.axis_label_text_font_size=\"14pt\"\nplot.xaxis.axis_label=\"Distance [m]\"\nplot.yaxis.axis_label=\"Force [N]\"\n\nmy_line=plot.line(x='x', y='y', source=plot_source, color='#3070B3',line_width=20)\nplot.triangle(x='x', y='y', size = 'size', source= triangle_source,color=\"#E37222\", line_width=2)\n\n#plotting Vectors as arrows\nP1_arrow_glyph = Arrow(end=OpenHead(line_color=\"#A2AD00\",line_width= 4, size=10),\n x_start='xS', y_start='yS', x_end='xE', y_end='yE',line_width= \"lW\", source=P1_arrow_source,line_color=\"#A2AD00\")\nP2_arrow_glyph = Arrow(end=OpenHead(line_color=\"#A2AD00\",line_width= 4, size=10),\n x_start='xS', y_start='yS', x_end='xE', y_end='yE',line_width= \"lW\", source=P2_arrow_source,line_color=\"#A2AD00\")\nF1_arrow_glyph = Arrow(end=OpenHead(line_color=\"#E37222\",line_width= 4, size=10),\n x_start='xS', y_start='yS', x_end='xE', y_end='yE',line_width= \"lW\", source=F1_arrow_source,line_color=\"#E37222\")\nF2_arrow_glyph = Arrow(end=OpenHead(line_color=\"#E37222\",line_width= 4, size=10),\n x_start='xS', y_start='yS', x_end='xE', y_end='yE',line_width= \"lW\", source=F2_arrow_source,line_color=\"#E37222\")\nP1_label_glyph=LabelSet(x='x', y='y',text='P1',text_font_size=\"15pt\",level='glyph',source=P1_label_source)\nP2_label_glyph=LabelSet(x='x', y='y',text='P2',text_font_size=\"15pt\",level='glyph',source=P2_label_source)\nF1_label_glyph=LabelSet(x='x', y='y',text='F1',text_font_size=\"15pt\",level='glyph',source=F1_label_source)\nF2_label_glyph=LabelSet(x='x', y='y',text='F2',text_font_size=\"15pt\",level='glyph',source=F2_label_source)\nplot.add_layout(P1_arrow_glyph)\nplot.add_layout(P2_arrow_glyph)\nplot.add_layout(F1_arrow_glyph)\nplot.add_layout(F2_arrow_glyph)\nplot.add_layout(P1_label_glyph)\nplot.add_layout(P2_label_glyph)\nplot.add_layout(F1_label_glyph)\nplot.add_layout(F2_label_glyph)\nplot.line(x='x',y='y', source=ForcegraphTop,line_width=3,line_color=\"#E37222\",legend=\" Force amplitude\", line_dash='dotted')\nplot.line(x='x',y='y', source=ForcegraphBottom,line_width=3,line_color=\"#E37222\",legend=\" Force amplitude\",line_dash='dotted' )\n\n\ninitialise()\n\ndef changeF1F2(attr,old,new):\n \n #changing Force graph back to initial condition\n ForcegraphTop.data = dict(x =[0],y =[10] )\n ForcegraphBottom.data = dict(x =[40],y =[-10] )\n YS = 400/(40-2*new)\n F1_arrow_source.data = dict(xS=[0+new], xE=[0+new], yS=[YS], yE=[0], lW = [5])\n F1_label_source.data = dict(x=[1+new],y=[5],F1=[\"F\"u\"\\u2081\"])\n F2_arrow_source.data = dict(xS=[40-new], xE=[40-new], yS=[-YS], yE=[0], lW = [5])\n F2_label_source.data = dict(x=[37.5-new],y=[-7],F2=[\"F\"u\"\\u2082\"])\n XcordinatesT=[None]*(new+2)\n XcordinatesB=[None]*(new+2)\n YcordinatesT=[None]*(new+2)\n YcordinatesB=[None]*(new+2)\n \n \n XcordinatesT[0]=0\n XcordinatesB[0]=40\n YcordinatesT[0]=10\n YcordinatesB[0]=-10\n i=1\n count = 1\n for i in range(new+1):\n XcordinatesT[count]=(i)\n XcordinatesB[count]=40-(i)\n\n y=400/float((40-(2*(i)))) # calculation of Force which will make equal amount of moment\n YcordinatesT[count]=y\n YcordinatesB[count]=-y\n count=count+1\n \n \n new_dataT= {\n 'x' : XcordinatesT,\n 'y' : YcordinatesT,\n }\n \n ForcegraphTop.stream(new_dataT)\n \n new_dataB= {\n 'x' : XcordinatesB,\n 'y' : YcordinatesB,\n }\n ForcegraphBottom.stream(new_dataB)\n \n#creating slider to change location of Forces F1 and F2\nF1F2Location_slider= Slider(title=\"Change Location of F\"u\"\\u2081 and F\"u\"\\u2082 (m)\",value= 0,start = 0, end = 19, step = 1)\nF1F2Location_slider= Slider(title=\"Change Location of F\"u\"\\u2081 and F\"u\"\\u2082 together\",value= 0,start = 0, end = 19, step = 1)\nF1F2Location_slider.on_change('value',changeF1F2)\n\n#adding description from HTML file\ndescription_filename = join(dirname(__file__), \"description.html\")\ndescription = Div(text=open(description_filename).read(), render_as_text=False, width=1200)\n\ncurdoc().add_root(column(description,row(plot,column(F1F2Location_slider))))\n#curdoc().title = \"\"","sub_path":"Couple_moment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"510254453","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AddressCustomerProvider',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'OFICINA_PRINCIPAL', help_text=b'Titulo de la Direccion', max_length=150, choices=[(b'OFICINA_PRINCIPAL', b'Oficina Principal'), (b'SUCURSAL', b'Sucursal'), (b'ALMACEN', b'Almacen'), (b'PLANTA', b'Planta')])),\n ('region', models.CharField(help_text=b'region', max_length=150)),\n ('provincia', models.CharField(help_text=b'provincia', max_length=150)),\n ('distrito', models.CharField(help_text=b'distrito', max_length=150)),\n ('direccion', models.CharField(help_text=b'Direccion de la Empresa', max_length=150)),\n ],\n options={\n 'verbose_name': 'Direccion de la empresa proveedora',\n 'verbose_name_plural': 'Direcciones de la empresa proveedora',\n },\n ),\n migrations.CreateModel(\n name='ContactCustomerProvider',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=50)),\n ('telefono', models.IntegerField()),\n ('email', models.EmailField(max_length=254)),\n ],\n options={\n 'verbose_name': 'Dato de Contacto de la empresa Provedora',\n 'verbose_name_plural': 'Datos de Contacto de la empresa Provedora',\n },\n ),\n migrations.CreateModel(\n name='CustomerProvider',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('ruc', models.BigIntegerField(help_text=b'Ingrese el numero de RUC', verbose_name=b'RUC de la empresa')),\n ('logo', models.ImageField(upload_to=b'customer_buy_logo/')),\n ('foto_institucional', models.ImageField(upload_to=b'customer_buy_foto_portada/')),\n ('razon_social', models.CharField(help_text=b'ingrese la razon social', max_length=150, verbose_name=b'Razon Social de la Empresa')),\n ('phone', models.IntegerField(help_text=b'Ingrese su Numero de Telefono', verbose_name=b'Telefono', blank=True)),\n ('cel', models.IntegerField(help_text=b'Ingrese su Numero de celular', verbose_name=b'Celular', blank=True)),\n ('inicio_de_actividades', models.DateField(help_text=b'Ingrese la fecha de inicio de actividades', verbose_name=b'Fecha de Inicio de Actividades')),\n ('numero_de_trabajadores', models.CharField(default=b'1 trabajador', max_length=250, choices=[(b'1t', b'1 trabajador'), (b'2a10t', b'2 a 10 trabajadores'), (b'11a100t', b'11 a 100 trabajadores'), (b'101a1000t', b'101 a 1000 trabajadores'), (b'1001a5000t', b'1001 a 5000 trabajadores'), (b'5000a+t', b'5000 a + trabajadores')])),\n ('website', models.URLField(help_text=b'Ingrese su sitio web', verbose_name=b'Sitio Web', blank=True)),\n ('email', models.EmailField(help_text=b'ingrese su email', max_length=254, blank=True)),\n ('sector', models.CharField(help_text=b'ingrese su sector', max_length=150, blank=True)),\n ('customer', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Empresa Provedora',\n 'verbose_name_plural': 'Empresas Provedoras',\n },\n ),\n migrations.CreateModel(\n name='ProductCustomerProvider',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name_product', models.CharField(max_length=250)),\n ('image_product', models.ImageField(upload_to=b'product_customer_buy/', blank=True)),\n ('customer_provider', models.ForeignKey(to='customerprovider.CustomerProvider')),\n ],\n options={\n 'verbose_name': 'Producto de la empresa proveedora',\n 'verbose_name_plural': 'Productos de la empresa proveedora',\n },\n ),\n migrations.CreateModel(\n name='TagProductCustomerProvider',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('customer_provider', models.ForeignKey(to='customerprovider.CustomerProvider')),\n ],\n options={\n 'verbose_name': 'Categoria de producto de la empresa proveedora',\n 'verbose_name_plural': 'Categorias de los productos de la empresa proveedora',\n },\n ),\n migrations.AddField(\n model_name='productcustomerprovider',\n name='tag_product',\n field=models.ForeignKey(to='customerprovider.TagProductCustomerProvider'),\n ),\n migrations.AddField(\n model_name='contactcustomerprovider',\n name='customer_provider',\n field=models.ForeignKey(to='customerprovider.CustomerProvider'),\n ),\n migrations.AddField(\n model_name='addresscustomerprovider',\n name='customer_provider',\n field=models.ForeignKey(to='customerprovider.CustomerProvider'),\n ),\n ]\n","sub_path":"customerprovider/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"56320617","text":"#from Archivos import Clases\r\nimport Clases\r\n\r\nimport datetime\r\nimport random\r\n\r\n# Carga la lista de clientes del fichero (o los datos base creados para pruebas)\r\ndef cargar_datos_clientes():\r\n clientes = []\r\n with open('Datos/Clientes.txt') as f:\r\n lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lineas:\r\n datos = linea.split(\",\")\r\n if datos[6] == \"Sponsor\":\r\n tipocliente = Clases.TipoCliente.Sponsor\r\n elif datos[6] == \"Proveedor\":\r\n tipocliente = Clases.TipoCliente.Proveedor\r\n else:\r\n tipocliente = Clases.TipoCliente.Cliente\r\n cliente = Clases.Cliente(datos[1],datos[2],datos[3],\r\n datos[4],datos[5],tipocliente,datos[0])\r\n clientes.append(cliente)\r\n\r\n return clientes\r\n\r\ndef cargar_datos_empleados():\r\n empleados = []\r\n with open('Datos/Empleados.txt') as f:\r\n lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lineas:\r\n datos = linea.split(\",\")\r\n if datos[6] == \"Administrativo\":\r\n departamento = Clases.Departamento.Administrativo\r\n elif datos[6] == \"Ventas\":\r\n departamento = Clases.Departamento.Ventas\r\n elif datos[6] == \"RRHH\":\r\n departamento = Clases.Departamento.RRHH\r\n elif datos[6] == \"Salud\":\r\n departamento = Clases.Departamento.Salud\r\n else:\r\n departamento = Clases.Departamento.Comercial\r\n empleado = Clases.Empleado(datos[1], datos[2], datos[3], datos[4], datos[5], departamento,\r\n datos[7], datos[0])\r\n empleados.append(empleado)\r\n\r\n return empleados\r\n\r\ndef cargar_datos_actividades():\r\n actividades = []\r\n with open('Datos/Actividades.txt') as f:\r\n lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lineas:\r\n datos = linea.split(\",\")\r\n if datos[4] == \"Llamada\":\r\n tipoactividad = Clases.TipoActividad.Llamada\r\n elif datos[4] == \"Promocion\":\r\n tipoactividad = Clases.TipoActividad.Promocion\r\n elif datos[4] == \"Informe\":\r\n tipoactividad = Clases.TipoActividad.Informe\r\n else:\r\n tipoactividad = Clases.TipoActividad.Reunion\r\n \r\n actividad = Clases.Actividad(datos[1], datos[2], datos[3], tipoactividad, datos[0])\r\n actividades.append(actividad)\r\n\r\n return actividades\r\n\r\ndef cargar_datos_informes():\r\n\r\n clientes = cargar_datos_clientes()\r\n empleados = cargar_datos_empleados()\r\n actividades = cargar_datos_actividades()\r\n\r\n informes = []\r\n with open('Datos/Informes.txt') as f:\r\n lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lineas:\r\n id_informe = linea[0:linea.find(\",\")]\r\n id_actividad = linea[(linea.find(\",\") + 1):(linea.find(\"(\") - 1)]\r\n ids_clientes_informe = linea[(linea.find(\"(\") + 1):linea.find(\")\")].split(\",\")\r\n ids_empleados_informe = linea[(linea.rfind(\"(\") + 1):linea.rfind(\")\")].split(\",\")\r\n informe = Clases.Informe(None, None, None, id_informe)\r\n\r\n actividad = \"\"\r\n for act in actividades:\r\n if id_actividad == act.id:\r\n actividad = act\r\n informe.setActividad(actividad)\r\n\r\n empleados_informe = []\r\n for id_emp_informe in ids_empleados_informe:\r\n for emple in empleados:\r\n if id_emp_informe == emple.id:\r\n empleados_informe.append(emple)\r\n informe.setEmpleados(empleados_informe)\r\n\r\n clientes_informe = []\r\n for id_clien_informe in ids_clientes_informe:\r\n for clien in clientes:\r\n if id_clien_informe == clien.id:\r\n clientes_informe.append(clien)\r\n informe.setClientes(clientes_informe)\r\n\r\n #informe = Clases.Informe(actividad, clientes, empleados, id_informe)\r\n informes.append(informe)\r\n\r\n return informes\r\n\r\ndef cargar_datos_oportunidades():\r\n informes = cargar_datos_informes()\r\n\r\n oportunidades = []\r\n with open('Datos/Oportunidades.txt') as f:\r\n lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lineas:\r\n id_oportunidad = linea[0:linea.find(\",\")]\r\n nombre_oportunidad = linea[(linea.find(\",\") + 1):(linea.find(\"(\") - 1)]\r\n ids_informes_oportunidad = linea[(linea.find(\"(\") + 1):linea.find(\")\")].split(\",\")\r\n dinero_estimado = linea[(linea.find(\")\") + 2):linea.rfind(\",\")]\r\n nombre_tipoetapa = linea[(linea.rfind(\",\") + 1):]\r\n\r\n lista_informes_opourtunidad = []\r\n for id_informe_oportunidad in ids_informes_oportunidad:\r\n for informe in informes:\r\n if id_informe_oportunidad == informe.getId():\r\n lista_informes_opourtunidad.append(informe)\r\n\r\n if nombre_tipoetapa == \"Propuesta\":\r\n tipoetapa = Clases.TipoEtapa.Propuesta\r\n elif nombre_tipoetapa == \"Calificado\":\r\n tipoetapa = Clases.TipoEtapa.Calificado\r\n elif nombre_tipoetapa == \"Ganada\":\r\n tipoetapa = Clases.TipoEtapa.Ganada\r\n elif nombre_tipoetapa == \"Suspendida\":\r\n tipoetapa = Clases.TipoEtapa.Suspendida\r\n else:\r\n tipoetapa = Clases.TipoEtapa.Nueva\r\n\r\n oportunidad = Clases.Oportunidad(str(nombre_oportunidad), lista_informes_opourtunidad, str(dinero_estimado), tipoetapa, id_oportunidad)\r\n oportunidades.append(oportunidad)\r\n\r\n return oportunidades\r\n\r\ndef guardar_cliente(cliente):\r\n linea = \"{0},{1},{2},{3},{4},{5},{6}\".format(str(cliente.id),str(cliente.dni),str(cliente.nombre),\r\n str(cliente.apellidos),str(cliente.email),\r\n str(cliente.fecha_nacimiento),str(cliente.tipocliente.name))\r\n f = open(\"Datos/Clientes.txt\", \"a+\") # <- a significa que es para añadir (append) líneas al final, no sobreescribe\r\n f.write(\"\\n\" + linea)\r\n f.close()\r\n\r\ndef guardar_empleado(empleado):\r\n linea = \"{0},{1},{2},{3},{4},{5},{6},{7}\".format(str(empleado.id),str(empleado.dni),str(empleado.nombre),\r\n str(empleado.apellidos),str(empleado.email),\r\n str(empleado.fecha_nacimiento),str(empleado.departamento.name),\r\n str(empleado.fecha_contratacion))\r\n f = open(\"Datos/Empleados.txt\", \"a+\") # <- a significa que es para añadir (append) líneas al final, no sobreescribe\r\n f.write(\"\\n\" + linea)\r\n f.close()\r\n\r\ndef guardar_actividad(actividad):\r\n linea = \"{0},{1},{2},{3},{4}\".format(str(actividad.id),str(actividad.descripcion),str(actividad.fecha_vencimiento),\r\n str(actividad.fecha_planificacion),str(actividad.tipoactividad.name))\r\n f = open(\"Datos/Actividades.txt\", \"a+\") # <- a significa que es para añadir (append) líneas al final, no sobreescribe\r\n f.write(\"\\n\" + linea)\r\n f.close()\r\n\r\n# Genera una línea (string) para guardarla en el fichero informes.\r\ndef linea_informe(informe):\r\n id = str(informe.getId())\r\n actividad = str(informe.getActividad().id)\r\n\r\n clientes = \"\"\r\n if len(informe.getClientes()) > 0:\r\n for clien in informe.getClientes():\r\n clientes += \",\" + str(clien.id)\r\n clientes = clientes[(clientes.find(\",\") + 1):]\r\n clientes = \"(\" + clientes + \")\"\r\n\r\n empleados = \"\"\r\n if len(informe.getEmpleados()) > 0:\r\n for emple in informe.getEmpleados():\r\n empleados += \",\" + str(emple.id)\r\n empleados = empleados[(empleados.find(\",\") + 1):]\r\n empleados = \"(\" + empleados + \")\"\r\n\r\n linea = id + \",\" + actividad + \",\" + clientes + \",\" + empleados\r\n return linea\r\n\r\ndef guardar_informe(informe):\r\n linea = linea_informe(informe)\r\n f = open(\"Datos/Informes.txt\", \"a+\") # <- a significa que es para añadir (append) líneas al final, no sobreescribe\r\n f.write(\"\\n\" + linea)\r\n f.close()\r\n\r\ndef linea_oportunidad(oportunidad):\r\n id = str(oportunidad.id)\r\n nombre = str(oportunidad.nombre)\r\n dinero_estimado = str(oportunidad.dinero_estimado)\r\n tipoetapa = str(oportunidad.tipoetapa.name)\r\n\r\n informes = \"\"\r\n if len(oportunidad.informes) > 0:\r\n for informe in oportunidad.informes:\r\n informes += \",\" + str(informe.getId())\r\n informes = informes[(informes.find(\",\") + 1):]\r\n informes = \"(\" + informes + \")\"\r\n\r\n linea = id + \",\" + nombre + \",\" + informes + \",\" + dinero_estimado + \",\" + tipoetapa\r\n return linea\r\n\r\ndef guardar_oportunidad(oportunidad):\r\n linea = linea_oportunidad(oportunidad)\r\n f = open(\"Datos/Oportunidades.txt\", \"a+\")\r\n f.write(\"\\n\" + linea)\r\n f.close()\r\n\r\ndef modificar_oportunidad(oportunidad):\r\n linea_a_modificar = linea_oportunidad(oportunidad)\r\n posicion = 0\r\n\r\n with open('Datos/Oportunidades.txt') as f:\r\n x = 0\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == oportunidad.id:\r\n posicion = x\r\n x += 1\r\n # f.close()\r\n\r\n with open('Datos/Oportunidades.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == posicion:\r\n linea = linea_a_modificar\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef modificar_informe(informe):\r\n linea_a_modificar = linea_informe(informe)\r\n posicion = 0\r\n\r\n with open('Datos/Informes.txt') as f:\r\n x = 0\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == informe.getId():\r\n posicion = x\r\n x += 1\r\n # f.close()\r\n\r\n with open('Datos/Informes.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == posicion:\r\n linea = linea_a_modificar\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef modificar_cliente(cliente):\r\n linea_a_modificar = \"{0},{1},{2},{3},{4},{5},{6}\".format(str(cliente.id),str(cliente.dni),str(cliente.nombre),\r\n str(cliente.apellidos),str(cliente.email),\r\n str(cliente.fecha_nacimiento),str(cliente.tipocliente.name))\r\n posicion = 0\r\n\r\n with open('Datos/Clientes.txt') as f:\r\n x = 0\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == cliente.id:\r\n posicion = x\r\n x += 1\r\n # f.close()\r\n\r\n with open('Datos/Clientes.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == posicion:\r\n linea = linea_a_modificar\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef modificar_empleado(empleado):\r\n linea_a_modificar = \"{0},{1},{2},{3},{4},{5},{6},{7}\".format(str(empleado.id),str(empleado.dni),str(empleado.nombre),\r\n str(empleado.apellidos),str(empleado.email),\r\n str(empleado.fecha_nacimiento),str(empleado.departamento.name),\r\n str(empleado.fecha_contratacion))\r\n posicion = 0\r\n\r\n with open('Datos/Empleados.txt') as f:\r\n x = 0\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == empleado.id:\r\n posicion = x\r\n x += 1\r\n # f.close()\r\n\r\n with open('Datos/Empleados.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == posicion:\r\n linea = linea_a_modificar\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef modificar_actividad(actividad):\r\n linea_a_modificar = \"{0},{1},{2},{3},{4}\".format(str(actividad.id),str(actividad.descripcion),str(actividad.fecha_vencimiento),\r\n str(actividad.fecha_planificacion),str(actividad.tipoactividad.name))\r\n posicion = 0\r\n\r\n with open('Datos/Actividades.txt') as f:\r\n x = 0\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == actividad.id:\r\n posicion = x\r\n x += 1\r\n # f.close()\r\n\r\n with open('Datos/Actividades.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == posicion:\r\n linea = linea_a_modificar\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef borrar_oportunidad(oportunidad):\r\n with open('Datos/Oportunidades.txt') as f:\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == oportunidad.id:\r\n lista_lineas.remove(linea)\r\n # f.close()\r\n\r\n with open('Datos/Oportunidades.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\ndef borrar_informe_de_oportunidad(informe):\r\n oportunidades = cargar_datos_oportunidades()\r\n for oportunidad in oportunidades:\r\n informes = oportunidad.informes\r\n if informe in informes:\r\n oportunidad.informes.remove(informe)\r\n modificar_oportunidad(oportunidad)\r\n\r\ndef borrar_informe(informe):\r\n with open('Datos/Informes.txt') as f:\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == informe.getId():\r\n # linea_a_modificar = linea\r\n lista_lineas.remove(linea)\r\n # f.close()\r\n\r\n # lista_lineas.remove(linea_a_modificar)\r\n\r\n with open('Datos/Informes.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\n\r\n# Elimina el cliente de los informes en los que aparezca (y guarda los cambios en el fichero)\r\ndef borrar_cliente_de_informes(cliente):\r\n informes = cargar_datos_informes()\r\n for informe in informes:\r\n clientes = informe.getClientes()\r\n if cliente in clientes:\r\n informe.getClientes().remove(cliente)\r\n modificar_informe(informe)\r\n\r\n# Elimina el empleado de los informes en los que aparezca (y guarda los cambios en el fichero)\r\ndef borrar_empleado_de_informes(empleado):\r\n informes = cargar_datos_informes()\r\n for informe in informes:\r\n empleados = informe.getEmpleados()\r\n if empleado in empleados:\r\n empleados.remove(empleado)\r\n modificar_informe(informe)\r\n\r\n# Elimina los informes relacionados con una actividad (y guarda los cambios en el fichero)\r\ndef borrar_informes_de_actividad(actividad):\r\n informes = cargar_datos_informes()\r\n for informe in informes:\r\n if actividad in informe:\r\n borrar_informe(informe)\r\n informes.remove(informe)\r\n\r\ndef borrar_cliente(cliente):\r\n with open('Datos/Clientes.txt') as f:\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == cliente.id:\r\n # linea_a_modificar = linea\r\n lista_lineas.remove(linea)\r\n # f.close()\r\n\r\n # lista_lineas.remove(linea_a_modificar)\r\n\r\n with open('Datos/Clientes.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\n # Imitando \"ON DELETE CASCADE\" eliminamos al cliente de aquellos informes en los que aparezca.\r\n borrar_cliente_de_informes(cliente)\r\n\r\n\r\ndef borrar_empleado(empleado):\r\n with open('Datos/Empleados.txt') as f:\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == empleado.id:\r\n # linea_a_modificar = linea\r\n lista_lineas.remove(linea)\r\n # f.close()\r\n\r\n # lista_lineas.remove(linea_a_modificar)\r\n\r\n with open('Datos/Empleados.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\n # Imitando \"ON DELETE CASCADE\" eliminamos al empleado de aquellos informes en los que aparezca.\r\n borrar_empleado_de_informes(empleado)\r\n\r\n\r\ndef borrar_actividad(actividad):\r\n with open('Datos/Actividades.txt') as f:\r\n lista_lineas = [line.rstrip('\\n') for line in f]\r\n for linea in lista_lineas:\r\n datos = linea.split(\",\")\r\n if datos[0] == actividad.id:\r\n # linea_a_modificar = linea\r\n lista_lineas.remove(linea)\r\n # f.close()\r\n\r\n # lista_lineas.remove(linea_a_modificar)\r\n\r\n with open('Datos/Actividades.txt', 'w+') as f:\r\n x = 0\r\n for linea in lista_lineas:\r\n if x == 0:\r\n f.write(str(linea))\r\n else:\r\n f.write(\"\\n\" + str(linea))\r\n x += 1\r\n\r\n # Si se elimina la actividad, el informe también. Puesto que el informe basa sus datos en la actividad.\r\n\r\n\r\n# Genera y devuelve un id (string) de 5 caracteres aleatorios\r\ndef generar_id():\r\n abc = \"abcdefghijklmnopqrstuvwxyz\"\r\n nums = \"1234567890\"\r\n #simbs = \"!¡?¿=_-+*^'\" # <- para los id no voy a usar símbolos\r\n id = \"\"\r\n while len(id) < 5:\r\n x = random.randint(1, 3)\r\n if x == 1:\r\n x = random.randint(0, (len(abc) - 1))\r\n id += abc[x]\r\n elif x == 2:\r\n x = random.randint(0, (len(abc) - 1))\r\n id += abc.upper()[x]\r\n elif x == 3:\r\n x = random.randint(0, (len(nums) - 1))\r\n id += nums[x]\r\n return id\r\n\r\n# Recorre una lista, ya sea de clientes, empleados o actividades, buscando si el id existe o no, devuelve un boolean.\r\n# Devuelve True si el id es válido (único), y False si el id ya existe.\r\ndef comprobar_id(id, lista):\r\n for valor in lista:\r\n if id == valor.id:\r\n return False\r\n return True\r\n\r\ndef comprobar_id_informe(id, lista):\r\n for valor in lista:\r\n if id == valor.getId():\r\n return False\r\n return True\r\n\r\n# Utiliza la función generar_id y comprueba el id generado para ver que no existe, si no existe, lo asigna\r\n# Para saber si el id existe o no, utiliza la función comprobar_id\r\ndef generar_id_cliente():\r\n clientes = cargar_datos_clientes()\r\n while True:\r\n id = generar_id()\r\n if comprobar_id(id, clientes):\r\n return id\r\n\r\n# Funciona igual que generar_id_cliente\r\ndef generar_id_actividad():\r\n actividades = cargar_datos_actividades()\r\n while True:\r\n id = generar_id()\r\n if comprobar_id(id, actividades):\r\n return id\r\n\r\n# Funciona igual que generar_id_cliente\r\ndef generar_id_empleado():\r\n empleados = cargar_datos_empleados()\r\n while True:\r\n id = generar_id()\r\n if comprobar_id(id, empleados):\r\n return id\r\n\r\n# Funciona igual que generar_id_cliente\r\ndef generar_id_informe():\r\n informes = cargar_datos_informes()\r\n while True:\r\n id = generar_id()\r\n if comprobar_id_informe(id, informes):\r\n return id\r\n\r\ndef generar_id_oportunidad():\r\n oportunidades = cargar_datos_oportunidades()\r\n while True:\r\n id = generar_id()\r\n if comprobar_id(id, oportunidades):\r\n return id\r\n","sub_path":"Practicas/Practica 2 - CRM/Practica2CRM/venv/Archivos/Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":20900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"651689958","text":"import requests\nimport xml.etree.ElementTree as ET\nfrom datetime import datetime\nimport services.usps_generic as usps_generic\nimport pytest\nimport os \nfrom pathlib import Path\n\ndef testUspsGenericDirect(): \n response=requestLabel('USPS_FC_W13.txt')\n root = ET.fromstring(response)\n base64_str=root.find(\".//LabelImage\").text\n\n if(len(base64_str)<5000):\n pytest.fail(\"label too short\")\n tracking_number =root.find(\".//BarcodeNumber\").text\n if (len(tracking_number)<10):\n pytest.fail(\"tracking_number too short\")\n\n \ndef requestLabel(resouceName):\n myTest=usps_generic.UspsGeneric()\n labelRequest=loadLabelRequest(resouceName)\n if not myTest.generateLabel(labelRequest):\n pytest.fail(\"Label creation failed. Response:\"+myTest.message)\n # response_file=open('response.xml','r',encoding='utf-8-sig')\n return myTest.message\n\n\ndef loadLabelRequest(resourceName):\n script_dir = Path(os.path.dirname(__file__)) \n resourcePath=os.path.join(Path(os.path.dirname(__file__)),'resources') \n with open(os.path.join(resourcePath,resourceName),encoding='utf8') as testResourceFile:\n labelRequest=testResourceFile.read()\n return labelRequest\n\n","sub_path":"test/test_usps_generic.py","file_name":"test_usps_generic.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"234252534","text":"# This one gets all table data text\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport csv\nfrom urllib.parse import urlparse\n\ndef crwl_as_csv(univ_query):\n page = 1\n dummy_data1 = {}\n df = pd.DataFrame(dummy_data1)\n while page:\n url = \"https://oia.yonsei.ac.kr/partner/expReport.asp?page=\" + str(page)+\"&cur_pack=0&ucode=\"+str(univ_query)+\"&bgbn=A\"\n res = requests.get(url)\n soup = BeautifulSoup(res.content,'lxml')\n table = soup.find_all('table')[0]\n df_crawl = pd.read_html(str(table),encoding='utf-8', header=0)[0]\n df_crawl['href'] = [np.where(tag.has_attr('href'),tag.get('href'),\"no link\") for tag in table.find_all('a')]\n if not df_crawl.empty:\n page += 1\n df = pd.concat([df, df_crawl],sort=False)\n else:\n print(df)\n break\n df_without_index = df.reset_index()\n print(df_without_index)\n df_without_index.to_csv(r'/Users/noopy/Yonsei_Exchange_Text_Wrangling/'+univ_query+'.csv',index=False,encoding=\"utf-8\")\n\n\ndef input_text(href):\n empty_lst = []\n review_url = \"https://oia.yonsei.ac.kr\" + href\n res = requests.get(review_url)\n soup = BeautifulSoup(res.content,'lxml')\n body_cursor_list = soup.find_all(\"div\", {\"class\": \"exp_txt\"})\n # options = webdriver.ChromeOptions()\n # options.add_argument('headless')\n # driver = webdriver.Chrome(r\"C:\\Users\\pc\\Desktop\\chromedriver\", options=options)\n # driver.implicitly_wait(1) # waiting web source for one second implicitly\n # driver.get(review_url)\n\n # selenium body cursor list\n # body_cursor_list = driver.find_elements_by_class_name(\"exp_txt\")\n\n text_list = []\n for i in body_cursor_list:\n text_list.append(i.text)\n\n text_list = text_list[1:]\n return text_list\n\n# input_text(\"/partner/expReport.asp?id=15129&page=1&bgbn=R\")\n\n\ndef combining_into_csv(file_name):\n initial_df = pd.read_csv(r'C:/Users/pc/Documents/GitHub/OIA_Text_Wrangling/dataf/'+file_name)\n stacked_list = []\n for item in initial_df['href']:\n print(item)\n text_list = input_text(item)\n stacked_list.append(text_list)\n univ_text_df= pd.DataFrame(np.row_stack(stacked_list),\n columns=[\"gen_info\", \"env_info\", \"food_info\", \"study_info\", \"office_info\", \"facil_info\", \"mhct_info\",\"help_info\",\"etc_info\"])\n print(univ_text_df)\n univ_text_df.to_csv(r'C:/Users/pc/Documents/GitHub/OIA_Text_Wrangling/dataf/'+file_name+'_text_data.csv',index=False,encoding=\"utf-8\")\n\ndef make_file(university_query):\n crwl_as_csv(university_query)\n file_name = university_query + \".csv\"\n combining_into_csv(file_name)\n\n\ndef give_cde_from_url(href):\n query =urlparse(href)\n query_list = query.query.split('=')\n query_list2 = query_list[1].split('&')\n univ_code = query_list2[0]\n print(univ_code)\n return univ_code\n\ndef mke_csv_files():\n df = pd.read_csv('univ_db_final_cont.csv')\n for href in df['href']:\n univ_code = give_cde_from_url(href)\n crwl_as_csv(univ_code)\n file_name = univ_code + \".csv\"\n combining_into_csv(file_name)\n\nmke_csv_files()\n","sub_path":"_archived/collect_reviews.py","file_name":"collect_reviews.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"34334822","text":"import sys\nimport random\nimport time\n\nimport pygame\n\n\n\n\nclass LifeGame:\n def __init__(self, screen_width=640, screen_height=480, cell_size=10, dead_color = (0,0,0), alive_color=(255,255,255), max_fps = 15):\n \"\"\"\n Initialize grid, set default game state, initialize screen\n\n :param screen_width: Game window width\n :param screen_height: Game window height\n :param cell_size: Diameter of circles\n :param dead_color: RGB tuple e.g. (255,0,255)\n :param alive_color: RGB tuple e.g. (255,0,255)\n :param max_fps: Framerate cap to limit game speed\n :return: None\n \"\"\"\n self.screen_width = screen_width\n self.screen_height = screen_height\n self.cell_size = cell_size\n self.circle_radius = self.cell_size // 2\n self.dead_color = dead_color\n self.alive_color = alive_color\n self.max_fps = max_fps\n\n self.screen_size = (self.screen_width, self.screen_height)\n pygame.init()\n self.screen = pygame.display.set_mode(self.screen_size)\n self.clock = pygame.time.Clock()\n self.init_grids()\n self.paused = False\n self.game_over = False\n \n def init_grids(self):\n \"\"\"\n Create the default active and inactive grid\n :return: None\n \"\"\"\n self.num_cols = self.screen_width // self.cell_size\n self.num_rows = self.screen_height // self.cell_size\n\n self.grids = []\n\n def create_grid():\n \"\"\"\n Generate an empty 2d grid\n :return: 2D array of 0s\n \"\"\"\n grid = []\n for c in range(self.num_cols):\n grid.append([])\n for r in range(self.num_rows):\n grid[-1].append(0)\n return grid\n \n self.grids.append(create_grid())\n self.grids.append(create_grid())\n\n self.active_grid = 0\n\n self.randomize_grid()\n\n def run(self):\n \"\"\" \n Main game loop function\n\n :return: None\n \"\"\"\n while True:\n self.handle_events()\n self.clock.tick(self.max_fps) # set FPS\n\n if self.game_over:\n return\n\n if not self.paused:\n self.clear_screen()\n self.draw_grid()\n self.update_generation()\n pygame.display.update()\n \n\n def handle_events(self):\n \"\"\"\n Handle the game events\n\n :return: None\n \"\"\"\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.unicode == \"q\" or event.unicode == \"Q\":\n self.game_over = True\n elif event.unicode == \"s\" or event.unicode == \"S\":\n self.paused = not self.paused\n elif event.unicode == \"r\" or event.unicode == \"R\":\n self.randomize_grid()\n if event.type == pygame.QUIT:\n self.game_over = True\n\n def clear_screen(self):\n \"\"\"\n Fill whole screen with dead color\n\n :return: None\n \"\"\"\n\n self.screen.fill(self.dead_color)\n \n def zero_grid(self):\n \"\"\"\n Sets the active grid to all 0's\n\n :return: None\n \"\"\"\n self.set_grid(0)\n\n def randomize_grid(self):\n \"\"\"\n Randomizes the active grid\n\n :return: None\n \"\"\"\n self.set_grid()\n \n def set_grid(self, value=None):\n \"\"\"\n Set an entire grid at once. Set to single value or random 0/1\n \n :param value: Value to set the cell to (0 or 1)\n :return: None\n \"\"\"\n\n for idx_col in range(self.num_cols):\n for idx_row in range(self.num_rows):\n if value is None:\n self.grids[self.active_grid][idx_col][idx_row] = random.choice([0,1])\n else:\n self.grids[self.active_grid][idx_col][idx_row] = value\n\n def draw_grid(self):\n \"\"\"\n Given the grid and cell states draw the cells on the screen\n \n :return: None\n \"\"\"\n\n for idx_col in range(self.num_cols):\n for idx_row in range(self.num_rows):\n if self.grids[self.active_grid][idx_col][idx_row] == 1:\n color = self.alive_color\n else:\n color = self.dead_color\n pygame.draw.circle(self.screen, \n color,\n ((idx_col * self.cell_size + self.circle_radius), idx_row * self.cell_size + self.circle_radius),\n self.circle_radius)\n\n\n def update_generation(self):\n \"\"\"\n Updates the state for all cells in the active grid\n\n :return: None\n \"\"\"\n inactive_grid = self.inactive_grid()\n\n for c in range(self.num_cols):\n for r in range(self.num_rows):\n next_gen_state = self.check_cell_neighbors(c,r)\n self.grids[inactive_grid][c][r] = next_gen_state\n\n self.active_grid = inactive_grid\n \n def inactive_grid(self):\n \"\"\" \n Helper function to return the currently inactive grid\n \n :return: Inactive grid (0/1)\n \"\"\"\n return (self.active_grid + 1) % 2\n\n\n\n def count_live_neighbors(self, idx_col, idx_row):\n \"\"\"\n Counts the alive (1) neighbors to given cell\n\n :param idx_col: Column index\n :param idx_row: Row index\n :return: Number of alive neighbors(0-8)\n \"\"\"\n alive_neighbors = 0\n for c in range(-1,2):\n for r in range(-1,2):\n if c == 0 and r == 0:\n continue\n try:\n alive_neighbors += self.grids[self.active_grid][idx_col + c][idx_row + r]\n except: \n pass\n return alive_neighbors\n\n def check_cell_neighbors(self, idx_col,idx_row):\n \"\"\"\n Get the n umber of alive neighbor cella nd determine the state of the cell for the next genretaion. Determine whether it lives, dies, or survives\n\n :param idx_col: The index of the column\n :param idx:row: The index of the row\n :return: Dead (0) or Alive (1)\n \"\"\"\n num_alive_neighbors = self.count_live_neighbors(idx_col, idx_row)\n\n if self.grids[self.active_grid][idx_col][idx_row] == 1: #alive\n if num_alive_neighbors < 2: # underpopulated\n return 0\n elif num_alive_neighbors == 2 or num_alive_neighbors == 3: # remain alive\n return 1\n elif num_alive_neighbors > 3: # overpopulate\n return 0\n elif self.grids[self.active_grid][idx_col][idx_row] == 0: # dead\n if num_alive_neighbors == 3: # revive\n return 1\n\n return self.grids[self.active_grid][idx_col][idx_row]\n \n\n","sub_path":"pygameoflife_dadeerh/pygameoflife_dadeerh.py","file_name":"pygameoflife_dadeerh.py","file_ext":"py","file_size_in_byte":6973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"642866250","text":"import pytest\n\nfrom constants import BAND_ID\nfrom metadata_parser import MetadataParser\n\n\ndef test_get_mean_angles(S2A_metadata_file, angle_keys):\n m_parser = MetadataParser(S2A_metadata_file)\n for band_id in BAND_ID:\n angles = m_parser.get_mean_angles(band_id.value)\n assert set(angles.keys()) == angle_keys\n for angle in angles.values():\n assert isinstance(angle, float)\n\n\ndef test_get_platform(S2A_metadata_file, S2B_metadata_file):\n _test_get_platform(S2A_metadata_file, 'S2A')\n _test_get_platform(S2B_metadata_file, 'S2B')\n\n\ndef _test_get_platform(metadata_file, expected_platform):\n m_parser = MetadataParser(metadata_file)\n platform = m_parser.get_platform()\n assert platform == expected_platform\n","sub_path":"examples/sentinel2/tests/test_metadata_parser.py","file_name":"test_metadata_parser.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"159280364","text":"#import pandas as pd\ndrinks = [\"espresso\", \"chai\", \"decaf\", \"drip\"]\ncaffeine = [64, 40, 0, 120]\n\nzipped_drinks=zip(drinks,caffeine)\n\ndrinks_to_caffeine = {key:value for key, value in zip(drinks,caffeine)}\nprint(drinks_to_caffeine)\n\ndef seq_sum(sequence):\n a = zip(sequence, sequence[::-1])\n print(sequence[::-1])\n b = a\n # print(list(b))\n print(sum(next(a)))\n return len(sequence) * sum(next(a)) // 2\n\n\n \n\nprint(seq_sum(range(10)))\nprint(0+1+2+3+4+5+6+7+8+9)\n\n#Dictionaries: try Except\npopulation = {\"California\": {\"Los Angeles\": 3971883,\n \"San Diego\": 1394928,\n \"San Jose\": 1026908},\n \"Texas\": {\"Houston\": 2296224,\n \"San Antonio\": 1469845}\n }\n\ntry:\n utah_list = population['Utah']\n\nexcept KeyError as k:\n print(type(k))\n print(\"Key \" + str(k) + \" does not exist\")\n\n#FOR CORONAVIRUS PROGRAM:\nimport unittest\nfrom selenium import webdriver\n\nclass GoogleTest(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome(\"D:\\\\Google Drive\\\\Codecademy\\\\Coronavirus_Email_Project\\\\chromedriver.exe\")\n \n def test_google_search(self):\n self.driver.get(\"https://www.google.com/xhtml\")\n self.assertIn(\"Google\",self.driver.title)\n search_field=self.driver.find_element_by_name(\"q\")\n search_field.send_keys(\"eric donald trump\")\n search_field.submit()\n assert \"Es wurden keine mit deiner Suchanfrage -\" not in self.driver.page_source\n\n def test_google_search2(self):\n self.driver.get(\"https://www.google.com/xhtml\")\n self.assertIn(\"Google\",self.driver.title)\n search_field=self.driver.find_element_by_name(\"q\")\n search_field.send_keys(\"asdfasdfasdfasfaoköpjsdhfoipawshfvpoiashbdfpihapöfnbapisdfhgpoiausdjhfpdfasdfasdf\")\n search_field.submit()\n assert \"Es wurden keine mit deiner Suchanfrage -\" not in self.driver.page_source\n\n def tearDown(self):\n self.driver.close()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"python/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"574980200","text":"import logging\nimport numpy\nimport os\nfrom multiprocessing import Process, Manager, Value, Semaphore\nfrom random import random\nfrom uuid import uuid4\n\nimport pysam\nfrom Bio import pairwise2\nfrom Bio.Seq import Seq\n\nfrom blast_wrapper import get_blast_matched_ids, make_blast_database\nfrom coverage_bias import CoverageBiasDetector, CoverageCorrector\nfrom hmm_utils import *\nfrom pacbio_haplotyper import PacBioHaplotyper\nfrom pomegranate import HiddenMarkovModel as Model\nfrom profiler import time_usage\nfrom sam_utils import get_reference_genome_of_alignment_file\nfrom sam_utils import get_related_reads_and_read_count_in_samfile\nimport settings\nfrom utils import is_low_quality_read\n\n\nclass SelectedRead:\n def __init__(self, sequence, logp, vpath, mapq=None, reference_start=None):\n self.sequence = sequence\n self.logp = logp\n self.vpath = vpath\n self.mapq = mapq\n self.is_mapped = reference_start is not None\n\n def is_mapped(self):\n return self.is_mapped\n\n\nclass VNTRFinder:\n \"\"\"Find the VNTR structure of a reference VNTR in NGS data of the donor.\"\"\"\n\n def __init__(self, reference_vntr):\n self.reference_vntr = reference_vntr\n self.min_repeat_bp_to_add_read = 2\n if len(self.reference_vntr.pattern) < 30:\n self.min_repeat_bp_to_add_read = 2\n self.min_repeat_bp_to_count_repeats = 2\n\n self.minimum_left_flanking_size = {}\n self.minimum_right_flanking_size = {69212: 19, 532789: 12, 400825: 10, 468671: 10}\n\n self.vntr_start = self.reference_vntr.start_point\n self.vntr_end = self.vntr_start + self.reference_vntr.get_length()\n\n @time_usage\n def build_vntr_matcher_hmm(self, copies, flanking_region_size=100):\n patterns = self.reference_vntr.get_repeat_segments()\n left_flanking_region = self.reference_vntr.left_flanking_region[-flanking_region_size:]\n right_flanking_region = self.reference_vntr.right_flanking_region[:flanking_region_size]\n\n vntr_matcher = get_read_matcher_model(left_flanking_region, right_flanking_region, patterns, copies)\n return vntr_matcher\n\n def get_vntr_matcher_hmm(self, read_length):\n \"\"\"Try to load trained HMM for this VNTR\n If there was no trained HMM, it will build one and store it for later usage\n \"\"\"\n logging.info('Using read length %s' % read_length)\n copies = int(round(float(read_length) / len(self.reference_vntr.pattern) + 0.5))\n\n base_name = str(self.reference_vntr.id) + '_' + str(read_length) + '.json'\n stored_hmm_file = settings.TRAINED_HMMS_DIR + base_name\n if settings.USE_TRAINED_HMMS and os.path.isfile(stored_hmm_file):\n model = Model()\n model = model.from_json(stored_hmm_file)\n return model\n\n flanking_region_size = read_length\n vntr_matcher = self.build_vntr_matcher_hmm(copies, flanking_region_size)\n\n json_str = vntr_matcher.to_json()\n with open(stored_hmm_file, 'w') as outfile:\n outfile.write(json_str)\n return vntr_matcher\n\n @time_usage\n def filter_reads_with_keyword_matching(self, working_directory, read_file, short_reads=True):\n db_name = 'blast_db__' + os.path.basename(read_file)\n blast_db_name = working_directory + db_name\n empty_db = False\n if not os.path.exists(blast_db_name + '.nsq') and not os.path.exists(blast_db_name + '.nal'):\n empty_db = make_blast_database(read_file, blast_db_name)\n\n word_size = int(len(self.reference_vntr.pattern)/3)\n if word_size > 11:\n word_size = 11\n if word_size < 5:\n word_size = 5\n word_size = str(word_size)\n\n search_results = []\n blast_ids = set([])\n search_id = str(uuid4()) + str(self.reference_vntr.id)\n queries = self.reference_vntr.get_repeat_segments()\n if len(self.reference_vntr.pattern) < 10:\n min_copies = int(10 / len(self.reference_vntr.pattern))\n queries = [self.reference_vntr.pattern * min_copies]\n identity_cutoff = '0'\n if not short_reads:\n queries = [self.reference_vntr.left_flanking_region[-80:], self.reference_vntr.right_flanking_region[:80]]\n word_size = str('10')\n identity_cutoff = '70'\n if not empty_db:\n for query in queries:\n search_result = get_blast_matched_ids(query, blast_db_name, max_seq='50000', word_size=word_size,\n evalue=10, search_id=search_id, identity_cutoff=identity_cutoff)\n search_results.append(search_result)\n\n if short_reads:\n for search_result in search_results:\n blast_ids |= search_result\n else:\n blast_ids = search_results[0] & search_results[1]\n\n logging.info('blast selected %s reads for %s' % (len(blast_ids), self.reference_vntr.id))\n if len(blast_ids) == len(self.reference_vntr.get_repeat_segments()) * 50 * 1000:\n logging.error('maximum number of read selected in filtering for pattern %s' % self.reference_vntr.id)\n return blast_ids\n\n @staticmethod\n def add_hmm_score_to_list(sema, hmm, read, result_scores):\n logp, vpath = hmm.viterbi(str(read.seq))\n rev_logp, rev_vpath = hmm.viterbi(str(Seq(str(read.seq)).reverse_complement()))\n if logp < rev_logp:\n logp = rev_logp\n result_scores.append(logp)\n sema.release()\n\n def is_true_read(self, read):\n read_start = read.reference_start\n reference_name = read.reference_name\n if not reference_name.startswith('chr'):\n reference_name = 'chr' + reference_name\n if reference_name == self.reference_vntr.chromosome and self.vntr_start - len(read.seq) < read_start < self.vntr_end:\n return True\n return False\n\n def find_score_distribution_of_ref(self, samfile, reference, hmm, false_scores, true_scores):\n process_list = []\n sema = Semaphore(settings.CORES)\n for read in samfile.fetch(reference, multiple_iterators=True):\n if read.is_unmapped:\n continue\n if read.seq.count('N') > 0:\n continue\n\n if self.is_true_read(read):\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, true_scores))\n else:\n if random() > settings.SCORE_FINDING_READS_FRACTION:\n continue\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, false_scores))\n process_list.append(p)\n p.start()\n for p in process_list:\n p.join()\n\n def save_scores(self, true_scores, false_scores, alignment_file):\n with open('true_scores_dist_%s_%s' % (self.reference_vntr.id, os.path.basename(alignment_file)), 'w') as out:\n for score in true_scores:\n out.write('%.4f\\n' % score)\n with open('false_scores_dist_%s_%s' % (self.reference_vntr.id, os.path.basename(alignment_file)), 'w') as out:\n for score in false_scores:\n out.write('%.4f\\n' % score)\n\n @time_usage\n def calculate_min_score_to_select_a_read(self, hmm, alignment_file):\n \"\"\"Calculate the score distribution of false positive reads\n and return score to select the 1e-8 percentile of the distribution\n \"\"\"\n process_list = []\n manager = Manager()\n false_scores = manager.list()\n true_scores = manager.list()\n read_mode = 'r' if alignment_file.endswith('sam') else 'rb'\n samfile = pysam.AlignmentFile(alignment_file, read_mode)\n refs = [ref for ref in samfile.references if ref in settings.CHROMOSOMES or 'chr' + ref in settings.CHROMOSOMES]\n for ref in refs:\n p = Process(target=self.find_score_distribution_of_ref, args=(samfile, ref, hmm, false_scores, true_scores))\n process_list.append(p)\n p.start()\n for p in process_list:\n p.join()\n\n if settings.SAVE_SCORE_DISTRIBUTION:\n self.save_scores(true_scores, false_scores, alignment_file)\n\n score = numpy.percentile(false_scores, 100 - settings.SCORE_SELECTION_PERCENTILE)\n return score\n\n def get_min_score_to_select_a_read(self, hmm, alignment_file, read_length):\n \"\"\"Try to load the minimum score for this VNTR\n\n If the score is not stored, it will compute the score and write it for this VNTR in precomputed data.\n \"\"\"\n base_name = str(self.reference_vntr.id) + '.scores'\n stored_scores_file = settings.TRAINED_HMMS_DIR + base_name\n if settings.USE_TRAINED_HMMS and os.path.isfile(stored_scores_file):\n with open(stored_scores_file, 'r') as infile:\n lines = [line.split() for line in infile.readlines() if line.strip() != '']\n for stored_length, fraction, score in lines:\n if int(stored_length) == read_length and settings.SCORE_FINDING_READS_FRACTION == float(fraction):\n return float(score)\n elif settings.SCALE_SCORES and settings.SCORE_FINDING_READS_FRACTION == float(fraction):\n return float(score) * (read_length / int(stored_length))\n\n logging.debug('Minimum score is not precomputed for vntr id: %s' % self.reference_vntr.id)\n score = self.calculate_min_score_to_select_a_read(hmm, alignment_file)\n logging.debug('computed score: %s' % score)\n with open(stored_scores_file, 'a') as outfile:\n outfile.write('%s %s %s\\n' % (read_length, settings.SCORE_FINDING_READS_FRACTION, score))\n\n return score\n\n def process_unmapped_read(self, sema, read_segment, hmm, min_score_to_count_read,\n vntr_bp_in_unmapped_reads, selected_reads, best_seq):\n if read_segment.seq.count('N') <= 0:\n sequence = str(read_segment.seq)\n logp, vpath = hmm.viterbi(sequence)\n rev_logp, rev_vpath = hmm.viterbi(str(read_segment.seq.reverse_complement()))\n if logp < rev_logp:\n sequence = str(read_segment.seq.reverse_complement())\n logp = rev_logp\n vpath = rev_vpath\n if logp > best_seq['logp']:\n best_seq['logp'] = logp\n best_seq['seq'] = sequence\n best_seq['vpath'] = vpath\n repeat_bps = get_number_of_repeat_bp_matches_in_vpath(vpath)\n if logp > min_score_to_count_read:\n if repeat_bps > self.min_repeat_bp_to_count_repeats:\n vntr_bp_in_unmapped_reads.value += repeat_bps\n if repeat_bps > self.min_repeat_bp_to_add_read:\n selected_reads.append(SelectedRead(sequence, logp, vpath))\n sema.release()\n\n def find_frameshift_from_selected_reads(self, selected_reads):\n mutations = {}\n repeating_bps_in_data = 0\n repeats_lengths_distribution = []\n for read in selected_reads:\n visited_states = [state.name for idx, state in read.vpath[1:-1]]\n repeats_lengths = get_repeating_pattern_lengths(visited_states)\n repeats_lengths_distribution += repeats_lengths\n current_repeat = None\n repeating_bps_in_data += get_number_of_repeat_bp_matches_in_vpath(read.vpath)\n for i in range(len(visited_states)):\n if visited_states[i].endswith('fix') or visited_states[i].startswith('M'):\n continue\n if visited_states[i].startswith('unit_start'):\n if current_repeat is None:\n current_repeat = 0\n else:\n current_repeat += 1\n if current_repeat is None or current_repeat >= len(repeats_lengths):\n continue\n if not visited_states[i].startswith('I') and not visited_states[i].startswith('D'):\n continue\n if repeats_lengths[current_repeat] == len(self.reference_vntr.pattern):\n continue\n state = visited_states[i].split('_')[0]\n if state.startswith('I'):\n state += get_emitted_basepair_from_visited_states(visited_states[i], visited_states, read.sequence)\n if abs(repeats_lengths[current_repeat] - len(self.reference_vntr.pattern)) <= 2:\n if state not in mutations.keys():\n mutations[state] = 0\n mutations[state] += 1\n sorted_mutations = sorted(mutations.items(), key=lambda x: x[1])\n logging.debug('sorted mutations: %s ' % sorted_mutations)\n frameshift_candidate = sorted_mutations[-1] if len(sorted_mutations) else (None, 0)\n logging.info(sorted(repeats_lengths_distribution))\n logging.info('Frameshift Candidate and Occurrence %s: %s' % frameshift_candidate)\n logging.info('Observed repeating base pairs in data: %s' % repeating_bps_in_data)\n avg_bp_coverage = float(repeating_bps_in_data) / self.reference_vntr.get_length()\n logging.info('Average coverage for each base pair: %s' % avg_bp_coverage)\n if frameshift_candidate[1] > avg_bp_coverage / 4:\n logging.info('There is a frameshift at %s' % frameshift_candidate[0])\n return frameshift_candidate[0]\n return None\n\n def read_flanks_repeats_with_confidence(self, vpath):\n minimum_left_flanking = 5\n minimum_right_flanking = 5\n if self.reference_vntr.id in self.minimum_left_flanking_size:\n minimum_left_flanking = self.minimum_left_flanking_size[self.reference_vntr.id]\n if self.reference_vntr.id in self.minimum_right_flanking_size:\n minimum_right_flanking = self.minimum_right_flanking_size[self.reference_vntr.id]\n\n if get_left_flanking_region_size_in_vpath(vpath) > minimum_left_flanking:\n if get_right_flanking_region_size_in_vpath(vpath) > minimum_right_flanking:\n return True\n return False\n\n def check_if_flanking_regions_align_to_str(self, read_str, length_distribution, spanning_reads):\n flanking_region_size = 100\n left_flanking = self.reference_vntr.left_flanking_region[-flanking_region_size:]\n right_flanking = self.reference_vntr.right_flanking_region[:flanking_region_size]\n left_alignments = pairwise2.align.localms(read_str, left_flanking, 1, -1, -1, -1)\n if len(left_alignments) < 1:\n return\n min_left, max_left = 10e9, 0\n for aln in left_alignments:\n if aln[2] < len(left_flanking) * (1 - 0.3):\n continue\n min_left = min(min_left, aln[3])\n max_left = max(max_left, aln[3])\n if max_left - min_left > 30:\n with open('vntr_complex.txt', 'a') as out:\n out.write('%s %s\\n' % (self.reference_vntr.id, max_left - min_left))\n left_align = left_alignments[0]\n if left_align[2] < len(left_flanking) * (1 - settings.MAX_ERROR_RATE):\n return\n\n right_alignments = pairwise2.align.localms(read_str, right_flanking, 1, -1, -1, -1)\n if len(right_alignments) < 1:\n return\n min_right, max_right = 10e9, 0\n for aln in right_alignments:\n if aln[2] < len(right_flanking) * (1 - 0.3):\n continue\n min_right = min(min_right, aln[3])\n max_right = max(max_right, aln[3])\n if max_right - min_right > 30:\n with open('vntr_complex.txt', 'a') as out:\n out.write('%s %s\\n' % (self.reference_vntr.id, max_right - min_right))\n right_align = right_alignments[0]\n if right_align[2] < len(right_flanking) * (1 - settings.MAX_ERROR_RATE):\n return\n\n if right_align[3] < left_align[3]:\n return\n spanning_reads.append(read_str[left_align[3]:right_align[3]+flanking_region_size].upper())\n length_distribution.append(right_align[3] - (left_align[3] + flanking_region_size))\n\n def check_if_pacbio_read_spans_vntr(self, sema, read, length_distribution, spanning_reads):\n self.check_if_flanking_regions_align_to_str(str(read.seq), length_distribution, spanning_reads)\n reverse_complement_str = str(Seq(str(read.seq)).reverse_complement())\n self.check_if_flanking_regions_align_to_str(reverse_complement_str, length_distribution, spanning_reads)\n sema.release()\n\n def check_if_pacbio_mapped_read_spans_vntr(self, sema, read, length_distribution, spanning_reads):\n flanking_region_size = 100\n region_start = self.reference_vntr.start_point - flanking_region_size\n region_end = self.reference_vntr.start_point + self.reference_vntr.get_length()\n if read.get_reference_positions()[0] < region_start and read.get_reference_positions()[-1] > region_end:\n read_region_start = None\n read_region_end = None\n for read_pos, ref_pos in enumerate(read.get_reference_positions()):\n if ref_pos >= region_start and read_region_start is None:\n read_region_start = read_pos\n if ref_pos >= region_end and read_region_end is None:\n read_region_end = read_pos\n if read_region_start is not None and read_region_end is not None:\n result = read.seq[read_region_start:read_region_end+flanking_region_size]\n if read.is_reverse:\n result = str(Seq(result).reverse_complement())\n spanning_reads.append(result)\n length_distribution.append(len(result) - flanking_region_size * 2)\n sema.release()\n\n @time_usage\n def get_spanning_reads_of_unaligned_pacbio_reads(self, unmapped_filtered_reads):\n sema = Semaphore(settings.CORES)\n manager = Manager()\n shared_length_distribution = manager.list()\n shared_spanning_reads = manager.list()\n\n process_list = []\n for read in unmapped_filtered_reads:\n sema.acquire()\n p = Process(target=self.check_if_pacbio_read_spans_vntr, args=(sema, read, shared_length_distribution,\n shared_spanning_reads))\n process_list.append(p)\n p.start()\n for p in process_list:\n p.join()\n logging.info('length_distribution of unmapped spanning reads: %s' % list(shared_length_distribution))\n return list(shared_spanning_reads), list(shared_length_distribution)\n\n @time_usage\n def get_spanning_reads_of_aligned_pacbio_reads(self, alignment_file):\n sema = Semaphore(settings.CORES)\n manager = Manager()\n length_distribution = manager.list()\n mapped_spanning_reads = manager.list()\n\n vntr_start = self.reference_vntr.start_point\n vntr_end = self.reference_vntr.start_point + self.reference_vntr.get_length()\n region_start = vntr_start\n region_end = vntr_end\n read_mode = 'r' if alignment_file.endswith('sam') else 'rb'\n samfile = pysam.AlignmentFile(alignment_file, read_mode)\n reference = get_reference_genome_of_alignment_file(samfile)\n chromosome = self.reference_vntr.chromosome if reference == 'HG19' else self.reference_vntr.chromosome[3:]\n process_list = []\n for read in samfile.fetch(chromosome, region_start, region_end):\n sema.acquire()\n p = Process(target=self.check_if_pacbio_read_spans_vntr, args=(sema, read, length_distribution,\n mapped_spanning_reads))\n process_list.append(p)\n p.start()\n\n for p in process_list:\n p.join()\n\n logging.info('length_distribution of mapped spanning reads: %s' % list(length_distribution))\n return list(mapped_spanning_reads)\n\n def get_conditional_likelihood(self, ck, ci, cj, ru_counts, r, r_e):\n if ck == ci == cj:\n return 1-r\n if cj == 0: # CHECK LATER\n return 0.5 * (1-r)\n if ck == ci:\n return 0.5 * ((1-r) + r_e ** abs(ck-cj))\n if ck == cj:\n return 0.5 * ((1-r) + r_e ** abs(ck-ci))\n if ck != ci and ck != cj:\n return 0.5 * (r_e ** abs(ck-ci) + r_e ** abs(ck-cj))\n\n def find_genotype_based_on_observed_repeats(self, observed_copy_numbers):\n ru_counts = {}\n for cn in observed_copy_numbers:\n if cn not in ru_counts.keys():\n ru_counts[cn] = 0\n ru_counts[cn] += 1\n if len(ru_counts.keys()) < 2:\n priors = 0.5\n ru_counts[0] = 1\n else:\n priors = 1.0 / (len(ru_counts.keys()) * (len(ru_counts.keys())-1) / 2)\n import operator\n ru_counts = sorted(ru_counts.items(), key=operator.itemgetter(1), reverse=True)\n r = 0.03\n r_e = r / (2 + r)\n prs = {}\n for ck, occ in ru_counts:\n if ck == 0:\n continue\n for i in range(len(ru_counts)):\n ci = ru_counts[i][0]\n for j in range(len(ru_counts)):\n if j < i:\n continue\n cj = ru_counts[j][0]\n if (ci, cj) not in prs.keys():\n prs[(ci, cj)] = []\n prs[(ci, cj)].append(self.get_conditional_likelihood(ck, ci, cj, ru_counts, r, r_e) ** occ)\n\n posteriors = {}\n import numpy\n for key in prs.keys():\n prs[key] = numpy.prod(numpy.array(prs[key]))\n posteriors[key] = prs[key] * priors\n\n sum_of_probs = sum(posteriors.values())\n\n max_prob = 1e-20\n result = None\n for key, value in posteriors.items():\n if value / sum_of_probs > max_prob:\n max_prob = value / sum_of_probs\n result = key\n\n logging.info('Maximum probability for genotyping: %s' % max_prob)\n return result\n\n def get_dominant_copy_numbers_from_spanning_reads(self, spanning_reads):\n if len(spanning_reads) < 1:\n logging.info('There is no spanning read')\n return None\n max_length = 0\n for read in spanning_reads:\n if len(read) - 100 > max_length:\n max_length = len(read) - 100\n max_copies = int(round(max_length / float(len(self.reference_vntr.pattern))))\n # max_copies = min(max_copies, 2 * len(self.reference_vntr.get_repeat_segments()))\n vntr_matcher = self.build_vntr_matcher_hmm(max_copies)\n observed_copy_numbers = []\n for haplotype in spanning_reads:\n logp, vpath = vntr_matcher.viterbi(haplotype)\n rev_logp, rev_vpath = vntr_matcher.viterbi(str(Seq(haplotype).reverse_complement()))\n if logp < rev_logp:\n vpath = rev_vpath\n observed_copy_numbers.append(get_number_of_repeats_in_vpath(vpath))\n\n logging.info('flanked repeats: %s' % observed_copy_numbers)\n return self.find_genotype_based_on_observed_repeats(observed_copy_numbers)\n\n @time_usage\n def get_haplotype_copy_numbers_from_spanning_reads(self, spanning_reads):\n if len(spanning_reads) < 1:\n logging.info('There is no spanning read')\n return None\n max_length = 0\n for read in spanning_reads:\n if len(read) - 100 > max_length:\n max_length = len(read) - 100\n max_copies = int(round(max_length / float(len(self.reference_vntr.pattern))))\n max_copies = min(max_copies, 2 * len(self.reference_vntr.get_repeat_segments()))\n vntr_matcher = self.build_vntr_matcher_hmm(max_copies)\n haplotyper = PacBioHaplotyper(spanning_reads)\n haplotypes = haplotyper.get_error_corrected_haplotypes()\n copy_numbers = []\n for haplotype in haplotypes:\n # print('haplotype: %s' % haplotype)\n logp, vpath = vntr_matcher.viterbi(haplotype)\n rev_logp, rev_vpath = vntr_matcher.viterbi(str(Seq(haplotype).reverse_complement()))\n if logp < rev_logp:\n vpath = rev_vpath\n copy_numbers.append(get_number_of_repeats_in_vpath(vpath))\n return copy_numbers\n\n @time_usage\n def find_repeat_count_from_pacbio_alignment_file(self, alignment_file, unmapped_filtered_reads):\n logging.debug('finding repeat count from pacbio alignment file for %s' % self.reference_vntr.id)\n\n unaligned_spanning_reads, length_dist = self.get_spanning_reads_of_unaligned_pacbio_reads(unmapped_filtered_reads)\n mapped_spanning_reads = self.get_spanning_reads_of_aligned_pacbio_reads(alignment_file)\n\n spanning_reads = mapped_spanning_reads + unaligned_spanning_reads\n copy_numbers = self.get_dominant_copy_numbers_from_spanning_reads(spanning_reads)\n return copy_numbers\n\n @time_usage\n def find_repeat_count_from_pacbio_reads(self, unmapped_filtered_reads, naive=False):\n logging.debug('finding repeat count from pacbio reads file for %s' % self.reference_vntr.id)\n spanning_reads, length_dist = self.get_spanning_reads_of_unaligned_pacbio_reads(unmapped_filtered_reads)\n if naive:\n if len(length_dist):\n average_length = sum(length_dist) / float(len(length_dist))\n copy_numbers = [round(average_length / len(self.reference_vntr.pattern))] * 2\n else:\n copy_numbers = None\n else:\n copy_numbers = self.get_dominant_copy_numbers_from_spanning_reads(spanning_reads)\n return copy_numbers\n\n @time_usage\n def select_illumina_reads(self, alignment_file, unmapped_filtered_reads):\n hmm = None\n min_score_to_count_read = None\n sema = Semaphore(settings.CORES)\n manager = Manager()\n selected_reads = manager.list()\n vntr_bp_in_unmapped_reads = Value('d', 0.0)\n\n number_of_reads = 0\n read_length = 150\n\n process_list = []\n\n best_seq = manager.dict()\n best_seq['logp'] = -10e8\n best_seq['vpath'] = ''\n best_seq['seq'] = ''\n\n for read_segment in unmapped_filtered_reads:\n if number_of_reads == 0:\n read_length = len(str(read_segment.seq))\n number_of_reads += 1\n if not hmm:\n hmm = self.get_vntr_matcher_hmm(read_length=read_length)\n min_score_to_count_read = self.get_min_score_to_select_a_read(hmm, alignment_file, read_length)\n\n if len(read_segment.seq) < read_length:\n continue\n\n sema.acquire()\n p = Process(target=self.process_unmapped_read, args=(sema, read_segment, hmm, min_score_to_count_read,\n vntr_bp_in_unmapped_reads, selected_reads, best_seq))\n process_list.append(p)\n p.start()\n for p in process_list:\n p.join()\n\n logging.debug('vntr base pairs in unmapped reads: %s' % vntr_bp_in_unmapped_reads.value)\n logging.debug('highest logp in unmapped reads: %s' % best_seq['logp'])\n logging.debug('best sequence %s' % best_seq['seq'])\n logging.debug('best vpath: %s' % [state.name for idx, state in list(best_seq['vpath'])[1:-1]])\n\n vntr_bp_in_mapped_reads = 0\n vntr_start = self.reference_vntr.start_point\n vntr_end = self.reference_vntr.start_point + self.reference_vntr.get_length()\n read_mode = 'r' if alignment_file.endswith('sam') else 'rb'\n samfile = pysam.AlignmentFile(alignment_file, read_mode)\n reference = get_reference_genome_of_alignment_file(samfile)\n chromosome = self.reference_vntr.chromosome if reference == 'HG19' else self.reference_vntr.chromosome[3:]\n for read in samfile.fetch(chromosome, vntr_start, vntr_end):\n if not hmm:\n read_length = len(read.seq)\n hmm = self.get_vntr_matcher_hmm(read_length=read_length)\n min_score_to_count_read = self.get_min_score_to_select_a_read(hmm, alignment_file, read_length)\n\n if read.is_unmapped:\n continue\n if len(read.seq) < int(read_length * 0.9):\n logging.debug('Rejecting read for short length: %s' % read.seq)\n continue\n read_end = read.reference_end if read.reference_end else read.reference_start + len(read.seq)\n if vntr_start - read_length < read.reference_start < vntr_end or vntr_start < read_end < vntr_end:\n if read.seq.count('N') <= 0:\n sequence = str(read.seq)\n logp, vpath = hmm.viterbi(sequence)\n rev_logp, rev_vpath = hmm.viterbi(str(Seq(read.seq).reverse_complement()))\n if logp < rev_logp:\n sequence = str(Seq(read.seq).reverse_complement())\n logp = rev_logp\n vpath = rev_vpath\n if is_low_quality_read(read) and logp < min_score_to_count_read:\n logging.debug('Rejected Read: %s' % sequence)\n continue\n selected_reads.append(SelectedRead(sequence, logp, vpath, read.mapq, read.reference_start))\n end = min(read_end, vntr_end)\n start = max(read.reference_start, vntr_start)\n vntr_bp_in_mapped_reads += end - start\n logging.debug('vntr base pairs in mapped reads: %s' % vntr_bp_in_mapped_reads)\n\n return selected_reads\n\n @time_usage\n def find_frameshift_from_alignment_file(self, alignment_file, unmapped_filtered_reads):\n logging.debug('finding frameshift from alignment file for %s' % self.reference_vntr.id)\n\n selected_reads = self.select_illumina_reads(alignment_file, unmapped_filtered_reads)\n return self.find_frameshift_from_selected_reads(selected_reads)\n\n @time_usage\n def find_repeat_count_from_alignment_file(self, alignment_file, unmapped_filtered_reads):\n logging.debug('finding repeat count from alignment file for %s' % self.reference_vntr.id)\n\n selected_reads = self.select_illumina_reads(alignment_file, unmapped_filtered_reads)\n\n covered_repeats = []\n flanking_repeats = []\n total_counted_vntr_bp = 0\n for selected_read in selected_reads:\n repeats = get_number_of_repeats_in_vpath(selected_read.vpath)\n total_counted_vntr_bp += get_number_of_repeat_bp_matches_in_vpath(selected_read.vpath)\n logging.debug('logp of read: %s' % str(selected_read.logp))\n logging.debug('left flankign size: %s' % get_left_flanking_region_size_in_vpath(selected_read.vpath))\n logging.debug('right flanking size: %s' % get_right_flanking_region_size_in_vpath(selected_read.vpath))\n logging.debug(selected_read.sequence)\n visited_states = [state.name for idx, state in selected_read.vpath[1:-1]]\n if self.read_flanks_repeats_with_confidence(selected_read.vpath):\n logging.debug('spanning read visited states :%s' % visited_states)\n logging.debug('repeats: %s' % repeats)\n covered_repeats.append(repeats)\n else:\n flanking_repeats.append(repeats)\n flanking_repeats = reversed(sorted(flanking_repeats))\n logging.info('flanked repeats: %s' % covered_repeats)\n logging.info('observed repeats: %s' % sorted(flanking_repeats))\n min_valid_flanked = max(covered_repeats) if len(covered_repeats) > 0 else 0\n max_flanking_repeat = [r for r in flanking_repeats if r == max(flanking_repeats) and r >= min_valid_flanked]\n if len(max_flanking_repeat) < 5:\n max_flanking_repeat = []\n\n if self.reference_vntr.id not in settings.LONG_VNTRS:\n genotype = self.find_genotype_based_on_observed_repeats(covered_repeats + max_flanking_repeat)\n return genotype\n\n pattern_occurrences = total_counted_vntr_bp / float(len(self.reference_vntr.pattern))\n read_mode = 'r' if alignment_file.endswith('sam') else 'rb'\n samfile = pysam.AlignmentFile(alignment_file, read_mode)\n reference = get_reference_genome_of_alignment_file(samfile)\n bias_detector = CoverageBiasDetector(alignment_file, self.reference_vntr.chromosome, reference)\n coverage_corrector = CoverageCorrector(bias_detector.get_gc_content_coverage_map())\n\n logging.info('Sequencing mean coverage: %s' % coverage_corrector.get_sequencing_mean_coverage())\n observed_copy_number = pattern_occurrences / coverage_corrector.get_sequencing_mean_coverage()\n scaled_copy_number = coverage_corrector.get_scaled_coverage(self.reference_vntr, observed_copy_number)\n logging.info('scaled copy number and observed copy number: %s, %s' % (scaled_copy_number, observed_copy_number))\n return [scaled_copy_number]\n\n def find_repeat_count_from_short_reads(self, short_read_files, working_directory='./'):\n \"\"\"\n Map short read sequencing data to human reference genome (hg19) and call find_repeat_count_from_alignment_file\n :param short_read_files: short read sequencing data\n :param working_directory: directory for generating the outputs\n \"\"\"\n alignment_file = '' + short_read_files\n # TODO: use bowtie2 to map short reads to hg19\n return self.find_repeat_count_from_alignment_file(alignment_file, working_directory)\n\n def find_accuracy(self, samfile='original_reads/paired_dat.sam'):\n \"\"\"Find sensitivity and false positive reads for a set of simulated data\n \"\"\"\n reference_end_pos = self.reference_vntr.start_point + self.reference_vntr.get_length()\n related_reads, read_count = get_related_reads_and_read_count_in_samfile(self.reference_vntr.pattern,\n self.reference_vntr.start_point,\n read_file=samfile,\n pattern_end=reference_end_pos)\n # TODO\n selected_reads = []\n occurrences = 0\n avg_coverage = 1\n true_positives = [read for read in selected_reads if read in related_reads]\n false_positives = [read for read in selected_reads if read not in true_positives]\n false_negatives = [read for read in related_reads if read not in selected_reads]\n # print('TP:', len(true_positives), 'FP:', len(false_positives), 'selected:', len(selected_reads))\n # print('FN:', len(false_negatives))\n sensitivity = float(len(true_positives)) / len(related_reads) if len(related_reads) > 0 else 0\n if sensitivity > 0.9:\n print(sensitivity, len(false_positives))\n if 1 > sensitivity > 0.9 and len(false_negatives) > 0 and len(false_positives) > 0:\n print('sensitivity ', sensitivity, ' FN:', false_negatives[0], ' FP:', false_positives[0])\n with open('FP_and_sensitivity_HMM_read_scoring_method.txt', 'a') as outfile:\n outfile.write('%s\\t%s\\t%s\\t%s\\t%s\\n' % (\n len(false_positives), sensitivity, self.reference_vntr.id, len(self.reference_vntr.pattern),\n len(true_positives)))\n error = abs(len(self.reference_vntr.get_repeat_segments()) - occurrences / avg_coverage)\n print(error)\n","sub_path":"src/vntr_finder.py","file_name":"vntr_finder.py","file_ext":"py","file_size_in_byte":35821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"256704603","text":"#coding=utf-8\r\nimport tensorflow as tf\r\nimport cv2\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\ncolor_image=\"C:/Users/Administrator/Desktop/11/I0.tif\"\r\ngradient_image=\"C:/Users/Administrator/Desktop/11/I.tif\"\r\nsave_dir=\"C:/Users/Administrator/Desktop/mean/\"\r\n\r\ndef conver_image_to_tensor(img_path):\r\n #the image has been divided by 255\r\n img_data=Image.open(img_path)\r\n img_data=np.array(img_data)\r\n img_data=tf.cast(img_data, tf.float32)/255\r\n return img_data\r\n\r\ndef image_gradient(img_data):\r\n #first, convert image to gray scale image\r\n #second: figure image's gradient in the direction of X and Y\r\n #third: multiply and sqrt\r\n #forth: convert one channel image into three channel image\r\n img_data=tf.image.rgb_to_grayscale(img_data)\r\n img_data_x=tf.pad(img_data, [[0,0],[0,1],[0,0]], mode='REFLECT')\r\n img_data_y=tf.pad(img_data, [[0,1],[0,0],[0,0]], mode='REFLECT')\r\n img_data_x=img_data_x[:,1:,:]-img_data_x[:,:-1,:]\r\n img_data_y=img_data_y[1:]-img_data_y[:-1]\r\n return img_data_x, img_data_y\r\n\r\ndef figure_phi_and_psi(img_data_x, img_data_y):\r\n step1=tf.multiply(img_data_x, img_data_x)+tf.multiply(img_data_y, img_data_y)\r\n step2=tf.sqrt(step1)\r\n step3=tf.concat([step2,step2,step2], axis=2)\r\n psi=tf.minimum(255.*step3/5., 1)\r\n phi=30./(1.+100.*step3)\r\n return psi, phi\r\n \r\n\r\n# test_data1=np.random.randint(0,3,(2,2,3))\r\n# test_data2=np.random.randint(0,3,(2,2,3))\r\n# \r\n# test_data1=tf.cast(test_data1, tf.float32)\r\n# test_data2=tf.cast(test_data2, tf.float32)\r\n# \r\n# # result=tf.matmul(test_data1, test_data2)#错误的使用\r\n# result=tf.multiply(test_data1, test_data2)#推荐使用\r\n\r\ngradient_image_data=conver_image_to_tensor(gradient_image)\r\ncolor_image_data=conver_image_to_tensor(color_image)\r\ntarget_image=tf.Variable(color_image_data)\r\n\r\ngradient_image_data_x,gradient_image_data_y=image_gradient(gradient_image_data)\r\ncolor_image_data_x, color_image_data_y=image_gradient(target_image)\r\n\r\npsi, phi=figure_phi_and_psi(gradient_image_data_x, gradient_image_data_y)\r\n\r\nsum1=tf.square(color_image_data_x-gradient_image_data_x)+tf.square(color_image_data_y-gradient_image_data_y)\r\nsum1=tf.multiply(sum1, phi)\r\nsum2=tf.square(target_image-color_image_data)\r\nsum2=tf.multiply(sum2,psi)\r\n\r\nloss=tf.reduce_mean(sum1)+tf.reduce_mean(sum2)\r\n# loss=tf.reduce_sum(sum1)+tf.reduce_sum(sum2)\r\ntrain_step=tf.train.AdamOptimizer(0.001).minimize(loss)\r\n\r\nphi_mean, phi_variance=tf.nn.moments(phi, [0,1,2])\r\nphi_max=tf.reduce_max(phi)\r\nphi_min=tf.reduce_min(phi)\r\n\r\npsi_mean, psi_variance=tf.nn.moments(psi, [0,1,2] )\r\npsi_max=tf.reduce_max(psi)\r\npsi_min=tf.reduce_min(psi)\r\n\r\nwith tf.Session() as sess:\r\n print(\"start\")\r\n sess.run(tf.global_variables_initializer())\r\n for i in range(1,1001):\r\n sess.run(train_step)\r\n if i % 100==0:\r\n print(loss.eval())\r\n print(\"phi的平均值是:\", phi_mean.eval(), \"\\t方差为:\", phi_variance.eval(), \"\\t最大值为:\",phi_max.eval(), \"\\t最小值为:\", phi_min.eval())\r\n print(\"psi的平均值是:\", psi_mean.eval(), \"\\t方差为:\", psi_variance.eval(), \"\\t最大值为:\",psi_max.eval(), \"\\t最小值为:\", psi_min.eval())\r\n image_array=np.array(target_image.eval()*255, dtype='float32')\r\n image_array=np.abs(image_array)\r\n image_array=cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)\r\n cv2.imwrite(save_dir+\"{}.png\".format(str(i)), image_array)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"imageRelatedShell/colorTransfer/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"17698605","text":"#/usr/bin/python3\n\nimport unittest\nfrom itertools import product\nfrom playing_card import PlayingCardDeck, PlayingCard\n\nclass TestPlayingCard(unittest.TestCase):\n\n def test_compare_two_cards(self):\n \"\"\"\n Tests the comparison function by comparing the numeral value\n of the card by drawing two cards and do manual comparison within this.\n The result is compared to the is_high_card function.\n \"\"\"\n deck = PlayingCardDeck()\n first_card = PlayingCard(deck)\n second_card = PlayingCard(deck)\n\n value = None\n if first_card.num_value > second_card.num_value:\n value = 1\n elif first_card.num_value `, things\nbecome much simpler:\n\n* Imports will be automatically taken care of.\n\n* Exports can be specified as simple task.\n\n\nA simple example of a recipe only loading datasets and afterwards exporting\nthem could look like this:\n\n.. code-block:: yaml\n\n datasets:\n - /path/to/first/dataset\n - /path/to/second/dataset\n\n tasks:\n - kind: export\n type: AdfExporter\n properties:\n target:\n - dataset1\n - dataset2\n\n\nWhat is happening here? Two datasets are imported, and afterwards exported\nto the ASpecD Dataset Format (ADF) using the :class:`aspecd.io.AdfExporter`.\n\nAnother frequent use case, although one that admittedly pretty much opposes\nthe whole idea of the ASpecD framework in terms of reproducibility and\ntraceability: Your collaboration partners require you to provide them with\nraw data they can import into their favourite program for creating plots.\nThe only viable way: export to plain text (ouch!) - saying good-bye to all\nyour metadata and history:\n\n.. code-block:: yaml\n\n datasets:\n - /path/to/first/cool/dataset\n - /path/to/second/cool/dataset\n - /path/to/another/cool/dataset\n\n tasks:\n - kind: export\n type: TxtExporter\n properties:\n target:\n - cool-dataset1\n - cool-dataset2\n - cool-dataset3\n\n\nIn this case, you can as well add whatever processing necessary to your\ndatasets before exporting them, and you see that recipes come in quite handy\nhere.\n\n\n\nImporters for specific file formats\n-----------------------------------\n\nThere exists a series of importers for specific file formats:\n\n* :class:`aspecd.io.AdfImporter`\n\n Importer for data in ASpecD Dataset Format (ADF)\n\n* :class:`aspecd.io.AsdfImporter`\n\n Importer for data in asdf format\n\n* :class:`aspecd.io.TxtImporter`\n\n Importer for data in plain text format\n\nFor details, see the respective class documentation.\n\n\nExporters for specific file formats\n-----------------------------------\n\nDatasets need to be persisted sometimes, and currently, there exist two\nexporters for specific file formats that can be imported again using the\nrespective importers. Furthermore, the full information contained in a\ndataset will be retained.\n\n* :class:`aspecd.io.AdfExporter`\n\n Exporter for datasets to ASpecD Dataset Format (ADF)\n\n* :class:`aspecd.io.AsdfExporter`\n\n Exporter for datasets to asdf format\n\nFor details, see the respective class documentation.\n\nA bit a special case is the exporter to plain text files, as this file\nformat does *not* preserve the metadata stored within the dataset and should\nonly be used as last resort:\n\n* :class:`aspecd.io.TxtExporter`\n\n Exporter for data to plain text format\n\n\n.. warning::\n All metadata contained within a dataset (including the full history)\n are lost when exporting to plain text. Therefore, using this\n exporter will usually result in you loosing reproducibility. Hence,\n better think twice before using this exporter and use entirely on\n your own risk and only if you *really* know what you are doing (and\n why).\n\n\nWriting importers for data\n--------------------------\n\nWhen writing importer classes for your own data, there is a number of\npitfalls, some of which shall be described here together with solutions and\n\"best practices\".\n\nDimensions of data\n~~~~~~~~~~~~~~~~~~\n\nUsually, we assign axes in the order *x*, *y*, *z*, and assume the *x* axis\nto be the horizontal axis in a plot. However, numpy (as well as other\nsoftware), follows a different convention, with the first index referring to\nthe *row* of your matrix, the second index to the *column*. That boils down\nto having the first index correspond to the *y* axis, and the second index\nreferring to the *x* axis.\n\nAs long as your data are one-dimensional, resulting in two axes objects in\nyour dataset, everything is fine, and the second axis will have no values.\n\nHowever, if your data to be imported are two-dimensional, your first\ndimension will be the index of rows (along a column), hence the *y* axis,\nand the second dimension the index of your columns (along a row), *i.e.* the\n*x* axis. This is perfectly fine, and it is equally fine to revert this\norder, as long as you ensure your axis objects to be consistent with the\ndimensions of your data.\n\nIf you assign numeric data to the :attr:`aspecd.dataset.Data.data` property,\nthe corresponding axes values will initially be set to the indices of the\ndata points along the corresponding dimension, with the first axis (index 0)\ncorresponding to the first dimension (row indices along a column) and\nsimilar for each of the following dimensions of your data. Note that there\nwill always be one axis more than dimensions of your data. This last axis\nwill not have values, and usually its quantity is something like \"intensity\".\n\n\nBackup of the data\n~~~~~~~~~~~~~~~~~~\n\nOne essential concept of the ASpecD dataset is to store the original data\ntogether with their axes in a separate, non-public property. This is done\nautomatically by the importer after calling out to its non-public method\n:meth:`aspecd.io.DatasetImporter._import`. Hence, usually you need not take\ncare of this at all.\n\n\nHandling of metadata\n~~~~~~~~~~~~~~~~~~~~\n\nData without information about these data are usually pretty useless. Hence,\nan ASpecD dataset is always a unit of numerical data and corresponding\nmetadata. While you will need to come up with your own structure for\nmetadata of your datasets and create a hierarchy of classes derived from\n:class:`aspecd.metadata.DatasetMetadata`, your importers need to ensure that\nthese metadata are populated respectively. Of course, which metadata can be\npopulated depends strongly on the file format you are about to import.\n\n\nHandling different file formats for importing data\n--------------------------------------------------\n\nOften, data are available in different formats, and deciding which importer\nis appropriate for a given format can be quite involved. To free other\nclasses from having to contain the relevant code, a factory can be used:\n\n* :class:`aspecd.io.DatasetImporterFactory`\n\nCurrently, the sole information provided to decide about the appropriate\nimporter is the source (a string). A concrete importer object is returned\nby the method :meth:`get_importer`. Thus, using the factory in another\nclass may look like the following::\n\n importer_factory = aspecd.io.DatasetImporterFactory()\n importer = importer_factory.get_importer(source=\"/path/to/your/data\")\n dataset = aspecd.dataset.Dataset()\n dataset.import_from(importer)\n\nHere, as in the example above, \"source\" refers to a (unique) identifier of\nyour dataset, be it a filename, path, URL/URI, LOI, or alike.\n\n.. important::\n For recipe-driven data analysis to work with an ASpecD-derived package,\n you need to implement a :class:`aspecd.io.DatasetImporterFactory` class\n there as well that can be obtained by instantiating\n ``.io.DatasetImporterFactory()``.\n\n\nRecipes\n=======\n\nFor recipes, a similar set of classes is provided:\n\n* :class:`aspecd.io.RecipeImporter`\n\n* :class:`aspecd.io.RecipeExporter`\n\nFor additional concrete classes handling import and export from and to YAML\nfiles see below.\n\nThe same general principles laid out above for the datasets applies to\nthese classes as well. In particular, both import and export should be\nhandled via the respective methods of the :class:`aspecd.tasks.Recipe`\nclass, thus first instantiating an object of that class and an appropriate\nimporter or exporter, and afterwards only operating on the recipe using\nits methods.\n\nIn its most generic form, this may look something like::\n\n recipe = aspecd.tasks.Recipe()\n importer = aspecd.io.RecipeImporter(source=\"/path/to/your/recipe\")\n recipe.import_from(importer)\n\nSimilarly, you would handle the export of the information contained in a\nrecipe object using an exporter object, respectively.\n\nTo simplify the input and output of recipes, and due recipe-driven data\nanalysis being an intrinsic property of the ASpecD framework, two classes\nhandling the import and export from and to YAML files are provided as well:\n\n* :class:`aspecd.io.RecipeYamlImporter`\n\n* :class:`aspecd.io.RecipeYamlExporter`\n\nThese classes can directly be used to work with YAML files containing\ninformation for recipe-driven data analysis. For details of the YAML file\nstructure, see the :class:`aspecd.tasks.Recipe` class and its attributes.\n\n\nModule documentation\n====================\n\n\"\"\"\nimport copy\nimport io\nimport os\nimport tempfile\nimport zipfile\n\nimport asdf\nimport numpy as np\n\nimport aspecd.exceptions\nimport aspecd.metadata\nimport aspecd.utils\n\n\nclass DatasetImporter:\n \"\"\"Base class for dataset importer.\n\n Each class actually importing data and metadata into a dataset should\n inherit from this class.\n\n To perform the import, call the\n :meth:`~aspecd.dataset.Dataset.import_from` method of the dataset\n the import should be performed for, and provide a reference to the\n actual importer object to it.\n\n The actual implementation of the importing is done in the private method\n :meth:`_import` that in turn gets called by :meth:`import_into`\n which is called by the :meth:`aspecd.dataset.Dataset.import_from` method\n of the dataset object.\n\n One question arising when actually implementing an importer for a\n specific file format: How do the data get into the dataset? The simple\n answer: The :meth:`_import` method of the importer knows about the\n dataset and its structure (see :class:`aspecd.dataset.Dataset` for\n details) and assigns data (and metadata) read from an external source\n to the respective fields of the dataset. In terms of a broader software\n architecture point of view: The dataset knows nothing about the\n importer besides its bare existence and interface, whereas the importer\n knows about the dataset and how to map data and metadata.\n\n Attributes\n ----------\n dataset : :class:`aspecd.dataset.Dataset`\n dataset to import data and metadata into\n\n source : :class:`str`\n specifier of the source the data and metadata will be read from\n\n parameters : :class:`dict`\n Additional parameters to control import options.\n\n Useful in case of, *e.g.*, CSV importers where the user may want to\n set things such as the delimiter\n\n .. versionadded:: 0.2\n\n Raises\n ------\n aspecd.io.MissingDatasetError\n Raised when no dataset exists to act upon\n\n \"\"\"\n\n def __init__(self, source=None):\n self.source = source\n self.dataset = None\n self.parameters = {}\n\n def import_into(self, dataset=None):\n \"\"\"Perform the actual import into the given dataset.\n\n If no dataset is provided at method call, but is set as property in\n the importer object, the :meth:`aspecd.dataset.Dataset.import_from`\n method of the dataset will be called.\n\n If no dataset is provided at method call nor as property in the\n object, the method will raise a respective exception.\n\n The dataset object always calls this method with the respective\n dataset as argument. Therefore, in this case setting the dataset\n property within the importer object is not necessary.\n\n The actual import should be implemented within the non-public method\n :meth:`_import`.\n\n .. note::\n A number of parameters of the dataset are automatically assigned\n *after* calling out to the non-public method\n :meth:`aspecd.io.DatasetImporter._import`, namely the\n non-public property ``_origdata`` of the dataset is populated\n with a copy of :attr:`aspecd.dataset.Dataset.data`, and id and\n label are set to :attr:`aspecd.io.DatasetImporter.source`.\n\n Parameters\n ----------\n dataset : :class:`aspecd.dataset.Dataset`\n Dataset to import data and metadata into\n\n Raises\n ------\n aspecd.io.MissingDatasetError\n Raised if no dataset is provided.\n\n \"\"\"\n if not dataset:\n if self.dataset:\n self.dataset.import_from(self)\n else:\n raise aspecd.exceptions.MissingDatasetError(\n \"No dataset provided\")\n else:\n self.dataset = dataset\n self._import()\n # Untested due to lack of ideas how to test\n # pylint: disable=protected-access\n self.dataset._origdata = copy.deepcopy(self.dataset.data)\n self.dataset.id = self.source\n if self.source and not self.dataset.label:\n self.dataset.label = os.path.split(self.source)[-1]\n\n def _import(self):\n \"\"\"Perform the actual import of data and metadata into the dataset.\n\n The implementation of the actual import goes in here in all\n classes inheriting from DatasetImporter. This method is automatically\n called by :meth:`import_into`.\n\n Importing data and metadata includes assigning both to the respective\n fields of the :obj:`aspecd.dataset.Dataset` object. For details of\n its structure, see there.\n\n Usually, this method will successively call other private/protected\n methods of the importer to perform the required tasks that are\n specific for each data source.\n\n \"\"\"\n\n\nclass DatasetImporterFactory:\n \"\"\"\n Factory for creating importer objects based on the source provided.\n\n Often, data are available in different formats, and deciding which\n importer is appropriate for a given format can be quite involved. To\n free other classes from having to contain the relevant code, a factory\n can be used.\n\n Currently, the sole information provided to decide about the\n appropriate importer is the source (a string). A concrete importer\n object is returned by the method :meth:`get_importer`. If no source is\n provided, an exception will be raised.\n\n The actual code for deciding which type of importer to return in what\n case should be implemented in the non-public method :meth:`_get_importer`\n in any package based on the ASpecD framework.\n\n In its basic implementation, as done here, the non-public method\n :meth:`_get_importer` returns the importers for ADF, ASDF, and TXT\n depending on the file extension, and in all other cases the standard\n importer.\n\n This might be a viable way for an own :class:`DatasetImporterFactory`\n implementation in the rare case of having only one single type of data,\n but provides a sensible starting point for own developments.\n\n\n Attributes\n ----------\n source : :class:`str`\n Source of the dataset to be loaded.\n\n Gets set by calling the method :meth:`get_importer` with the\n ``source`` parameter.\n\n Raises\n ------\n aspecd.io.MissingSourceError\n Raised if no source is provided\n\n \"\"\"\n\n def __init__(self):\n self.source = None\n\n def get_importer(self, source='', importer='', parameters=None):\n \"\"\"\n Return importer object for dataset specified by its source.\n\n The actual code for deciding which type of importer to return in what\n case should be implemented in the non-public method\n :meth:`_get_importer` in any package based on the ASpecD framework.\n\n If no importer gets returned by the method :meth:`_get_importer`,\n the ASpecD-interal importers will be checked for matching the file\n type. Thus, you can overwrite the behaviour of any filetype\n supported natively by the ASpecD framework, but retain compatibility\n to the ASpecD-specific file types.\n\n .. note::\n Currently, only filenames/paths are supported, and if ``source``\n does not start with the file separator, the absolute path to the\n current directory is prepended.\n\n\n Parameters\n ----------\n source : :class:`str`\n string describing the source of the dataset\n\n May be a filename or path, a URL/URI, a LOI, or similar\n\n importer : :class:`str`\n Name of the importer to use for importing the dataset\n\n Default: ''\n\n .. versionadded:: 0.2\n\n parameters : :class:`dict`\n Additional parameters for controlling the import\n\n Default: None\n\n .. versionadded:: 0.2\n\n Returns\n -------\n importer : :class:`aspecd.io.DatasetImporter`\n importer object of appropriate class\n\n Raises\n ------\n aspecd.io.MissingSourceError\n Raised if no source is provided\n\n \"\"\"\n if not source:\n raise aspecd.exceptions.MissingSourceError(\n 'A source is required to return an appropriate importer')\n self.source = source\n if not self.source.startswith(os.pathsep):\n self.source = os.path.join(os.path.abspath(os.curdir), self.source)\n if importer:\n package_name = aspecd.utils.package_name(self)\n # Currently untested\n if not package_name.endswith('io'):\n package_name = '.'.join([package_name, 'io'])\n full_class_name = '.'.join([package_name, importer])\n importer = aspecd.utils.object_from_class_name(full_class_name)\n importer.source = self.source\n if not importer:\n importer = self._get_importer()\n if not importer:\n importer = self._get_aspecd_importer()\n if parameters:\n importer.parameters = parameters\n return importer\n\n # noinspection PyMethodMayBeStatic\n def _get_importer(self):\n \"\"\"Choose appropriate importer for a dataset.\n\n Every package inheriting from the ASpecD framework should implement\n this method. Note that in case you do not handle a filetype and\n hence return no importer, the default ASpecD importer will be\n checked for matching the given source. Thus, you can overwrite the\n behaviour of any filetype supported natively by the ASpecD\n framework, but retain compatibility to the ASpecD-specific file types.\n\n Returns\n -------\n importer : :class:`aspecd.io.DatasetImporter`\n Importer for the specific file type\n\n \"\"\"\n importer = None\n return importer\n\n def _get_aspecd_importer(self):\n _, file_extension = os.path.splitext(self.source)\n if file_extension == '.adf':\n return AdfImporter(source=self.source)\n if file_extension == '.asdf':\n return AsdfImporter(source=self.source)\n if file_extension == '.txt':\n return TxtImporter(source=self.source)\n return DatasetImporter(source=self.source)\n\n\nclass DatasetExporter:\n \"\"\"Base class for dataset exporter.\n\n Each class actually exporting data from a dataset to some other should\n inherit from this class.\n\n To perform the export, call the\n :meth:`~aspecd.dataset.Dataset.export_to` method of the dataset\n the export should be performed for, and provide a reference to the\n actual exporter object to it.\n\n The actual implementation of the exporting is done in the non-public\n method :meth:`_export` that in turn gets called by :meth:`export_from`\n which is called by the :meth:`aspecd.dataset.Dataset.export_to` method\n of the dataset object.\n\n Attributes\n ----------\n dataset : :obj:`aspecd.dataset.Dataset`\n dataset to export data and metadata from\n\n target : string\n specifier of the target the data and metadata will be written to\n\n comment : :class:`str`\n User-supplied comment describing intent, purpose, reason, ...\n\n\n Raises\n ------\n aspecd.io.MissingDatasetError\n Raised when no dataset exists to act upon\n\n\n .. versionchanged:: 0.6.4\n New attribute :attr:`comment`\n\n \"\"\"\n\n def __init__(self, target=None):\n self.target = target\n self.dataset = None\n self.comment = ''\n\n def export_from(self, dataset=None):\n \"\"\"Perform the actual export from the given dataset.\n\n If no dataset is provided at method call, but is set as property in\n the exporter object, the :meth:`aspecd.dataset.Dataset.export_to`\n method of the dataset will be called.\n\n If no dataset is provided at method call nor as property in the\n object, the method will raise a respective exception.\n\n The dataset object always calls this method with the respective\n dataset as argument. Therefore, in this case setting the dataset\n property within the exporter object is not necessary.\n\n The actual export is implemented within the non-public method\n :meth:`_export` that gets automatically called.\n\n Parameters\n ----------\n dataset : :class:`aspecd.dataset.Dataset`\n Dataset to export data and metadata from\n\n Raises\n ------\n aspecd.io.MissingDatasetError\n Raised if no dataset is provided.\n\n \"\"\"\n if not dataset:\n if self.dataset:\n self.dataset.export_to(self)\n else:\n raise aspecd.exceptions.MissingDatasetError(\n \"No dataset provided\")\n else:\n self.dataset = dataset\n self._export()\n\n def _export(self):\n \"\"\"Perform the actual export of data and metadata from the dataset.\n\n The implementation of the actual export goes in here in all\n classes inheriting from DatasetExporter. This method is automatically\n called by :meth:`export_from`.\n\n Usually, this method will successively call other private/protected\n methods of the exporter to perform the required tasks that are\n specific for each target format.\n\n \"\"\"\n\n\nclass RecipeImporter:\n \"\"\"Base class for recipe importer.\n\n Each class actually importing recipes into a :obj:`aspecd.tasks.Recipe`\n object should inherit from this class.\n\n To perform the import, call the\n :meth:`~aspecd.tasks.Recipe.import_from` method of the recipe the\n import should be performed for, and provide a reference to the\n actual importer object to it.\n\n The actual implementation of the importing is done in the non-public\n method :meth:`_import` that in turn gets called by :meth:`import_into`\n which is called by the :meth:`aspecd.tasks.Recipe.import_from` method\n of the recipe object.\n\n One question arising when actually implementing an importer for a\n specific file format: How does the information get into the recipe? The\n simple answer: The :meth:`_import` method of the importer knows about the\n recipe and its structure (see :class:`aspecd.tasks.Recipe` for\n details) and creates a dictionary with keys corresponding to the\n respective attributes of the recipe. In turn, it can then call the\n :meth:`aspecd.tasks.Recipe.from_dict` method. In terms of a broader\n software architecture point of view: The recipe knows nothing about the\n importer besides its bare existence and interface, whereas the importer\n knows about the recipe and how to map the information obtained to it.\n\n Attributes\n ----------\n recipe : :obj:`aspecd.tasks.Recipe`\n recipe to import into\n source : :class:`str`\n specifier of the source the information will be read from\n\n Raises\n ------\n aspecd.io.MissingRecipeError\n Raised when no dataset exists to act upon\n\n \"\"\"\n\n def __init__(self, source=''):\n self.source = source\n self.recipe = None\n\n def import_into(self, recipe=None):\n \"\"\"Perform the actual import into the given recipe.\n\n If no recipe is provided at method call, but is set as property in\n the importer object, the :meth:`aspecd.tasks.Recipe.import_from`\n method of the recipe will be called.\n\n If no recipe is provided at method call nor as property in the\n object, the method will raise a respective exception.\n\n The recipe object always calls this method with the respective\n recipe as argument. Therefore, in this case setting the recipe\n property within the importer object is not necessary.\n\n The actual import should be implemented within the non-public method\n :meth:`_import`.\n\n Parameters\n ----------\n recipe : :obj:`aspecd.tasks.Recipe`\n recipe to import into\n\n Raises\n ------\n aspecd.io.MissingRecipeError\n Raised if no recipe is provided.\n\n \"\"\"\n if not recipe:\n if self.recipe:\n self.recipe.import_from(self)\n else:\n raise aspecd.exceptions.MissingRecipeError(\"No recipe provided\")\n else:\n self.recipe = recipe\n self.recipe.filename = self.source\n self._import()\n\n def _import(self):\n \"\"\"Perform the actual import into the recipe.\n\n The implementation of the actual import goes in here in all\n classes inheriting from RecipeImporter. This method is automatically\n called by :meth:`import_into`.\n\n Importing metadata includes assigning it to the respective fields\n of the :obj:`aspecd.tasks.Recipe` object. For details of\n its structure, see there. To do this, the method should create a\n dictionary that can afterwards be supplied as an argument to a call\n to :meth:`aspecd.tasks.Recipe.from_dict`.\n\n \"\"\"\n\n\nclass RecipeExporter:\n \"\"\"Base class for recipe exporter.\n\n Each class actually exporting recipes from :obj:`aspecd.tasks.Recipe`\n objects should inherit from this class.\n\n To perform the export, call the\n :meth:`aspecd.tasks.Recipe.export_to` method of the recipe the export\n should be performed for, and provide a reference to the actual exporter\n object to it.\n\n The actual implementation of the exporting is done in the non-public\n method :meth:`_export` that in turn gets called by :meth:`export_from`\n which is called by the :meth:`aspecd.tasks.Recipe.export_to` method\n of the recipe object.\n\n Attributes\n ----------\n recipe : :obj:`aspecd.tasks.Recipe`\n recipe to export information from\n target : string\n specifier of the target the information will be written to\n\n Raises\n ------\n aspecd.io.MissingRecipeError\n Raised when no dataset exists to act upon\n\n \"\"\"\n\n def __init__(self, target=''):\n self.target = target\n self.recipe = None\n\n def export_from(self, recipe=None):\n \"\"\"Perform the actual export from the given recipe.\n\n If no recipe is provided at method call, but is set as property in\n the exporter object, the :meth:`aspecd.tasks.Recipe.export_to`\n method of the recipe will be called.\n\n If no recipe is provided at method call nor as property in the\n object, the method will raise a respective exception.\n\n The recipe object always calls this method with the respective\n recipe as argument. Therefore, in this case setting the recipe\n property within the exporter object is not necessary.\n\n The actual export should be implemented within the non-public method\n :meth:`_export`.\n\n Parameters\n ----------\n recipe : :class:`aspecd.tasks.Recipe`\n Recipe to export from\n\n Raises\n ------\n aspecd.io.MissingRecipeError\n Raised if no recipe is provided.\n\n \"\"\"\n if not recipe:\n if self.recipe:\n self.recipe.export_to(self)\n else:\n raise aspecd.exceptions.MissingRecipeError(\"No recipe provided\")\n else:\n self.recipe = recipe\n self._export()\n\n def _export(self):\n \"\"\"Perform the actual export from the recipe.\n\n The implementation of the actual export goes in here in all\n classes inheriting from RecipeExporter. This method is automatically\n called by :meth:`export_from`.\n\n Usually, this method will first create a dictionary from the recipe\n using the :meth:`aspecd.tasks.Recipe.to_dict` method. This\n dictionary can afterwards be further processed and written to some\n file.\n\n \"\"\"\n\n\nclass RecipeYamlImporter(RecipeImporter):\n \"\"\"\n Recipe importer for importing from YAML files.\n\n The YAML file needs to have a structure compatible to the actual\n recipe, such that the dict created from reading the YAML file can be\n directly fed into the :meth:`aspecd.tasks.Recipe.from_dict` method.\n\n The order of entries of the YAML file is preserved due to using ordered\n dictionaries (:class:`collections.OrderedDict`) internally.\n\n Parameters\n ----------\n source : :class:`str`\n filename of a YAML file to read from\n\n \"\"\"\n\n def __init__(self, source=''):\n self.recipe_version = ''\n self._recipe_dict = None\n super().__init__(source=source)\n\n def _import(self):\n self._load_from_yaml()\n self._convert()\n self.recipe.from_dict(self._recipe_dict)\n\n def _load_from_yaml(self):\n yaml = aspecd.utils.Yaml()\n yaml.read_from(filename=self.source)\n yaml.deserialise_numpy_arrays()\n self._recipe_dict = yaml.dict\n\n def _convert(self):\n self._get_recipe_version()\n self._map_recipe_structure()\n\n def _get_recipe_version(self):\n self.recipe_version = self.recipe.format['version']\n if 'format' in self._recipe_dict \\\n and 'version' in self._recipe_dict['format']:\n self.recipe_version = self._recipe_dict['format']['version']\n deprecated_keys = ['default_package', 'autosave_plots',\n 'output_directory', 'datasets_source_directory']\n if any(key in self._recipe_dict for key in deprecated_keys):\n self.recipe_version = '0.1'\n\n def _map_recipe_structure(self):\n mapper = aspecd.metadata.MetadataMapper()\n mapper.version = self.recipe_version\n mapper.metadata = self._recipe_dict\n mapper.recipe_filename = 'recipe_mapper.yaml'\n mapper.map()\n self._recipe_dict = mapper.metadata\n\n\nclass RecipeYamlExporter(RecipeExporter):\n \"\"\"\n Recipe exporter for exporting to YAML files.\n\n The YAML file will have a structure corresponding to the output of the\n :meth:`aspecd.tasks.Recipe.to_dict` method of the recipe object.\n\n Parameters\n ----------\n target : :class:`str`\n filename of a YAML file to write to\n\n \"\"\"\n\n def __init__(self, target=''):\n super().__init__(target=target)\n\n def _export(self):\n yaml = aspecd.utils.Yaml()\n yaml.dict = self.recipe.to_dict()\n yaml.numpy_array_to_list = True\n yaml.serialise_numpy_arrays()\n yaml.write_to(filename=self.target)\n\n\nclass AdfExporter(DatasetExporter):\n \"\"\"\n Dataset exporter for exporting to ASpecD dataset format.\n\n The ASpecD dataset format is vaguely reminiscent of the Open Document\n Format, *i.e.* a zipped directory containing structured data (in this\n case in form of a YAML file) and binary data in a corresponding\n subdirectory.\n\n As PyYAML is not capable of dealing with NumPy arrays out of the box,\n those are dealt with separately. Small arrays are stored inline as\n lists, larger arrays in separate files. For details, see the\n :class:`aspecd.utils.Yaml` class.\n\n The data format tries to be as self-contained as possible,\n using standard file formats and a brief description of its layout\n contained within the archive. Collecting the contents in a single ZIP\n archive allows the user to deal with a single file for a dataset,\n while more advanced users can easily dig into the details and write\n importers for other platforms and programming languages, making the\n format rather platform-independent and future-safe. Due to using binary\n representation for larger numerical arrays, the format should be more\n memory-efficient than other formats.\n\n \"\"\"\n\n def __init__(self, target=None):\n super().__init__(target=target)\n self.extension = '.adf'\n self._filenames = {\n 'dataset': 'dataset.yaml',\n 'version': 'VERSION',\n 'readme': 'README',\n }\n self._bin_dir = 'binaryData'\n self._tempdir_name = ''\n self._version = '1.0.0'\n\n def _export(self):\n if not self.target:\n raise aspecd.exceptions.MissingTargetError\n with tempfile.TemporaryDirectory() as tempdir:\n self._tempdir_name = tempdir\n self._create_files()\n self._create_zip_archive()\n\n def _create_zip_archive(self):\n with zipfile.ZipFile(self.target + self.extension, 'w') as zipped_file:\n for filename in self._filenames.values():\n zipped_file.write(\n filename=os.path.join(self._tempdir_name, filename),\n arcname=filename)\n bin_dir_path = os.path.join(self._tempdir_name, self._bin_dir)\n zipped_file.write(\n filename=os.path.join(bin_dir_path),\n arcname=self._bin_dir)\n for filename in os.listdir(bin_dir_path):\n zipped_file.write(\n filename=os.path.join(bin_dir_path, filename),\n arcname=os.path.join(self._bin_dir, filename))\n\n def _create_files(self):\n self._create_dataset_yaml()\n self._create_version_file()\n self._create_readme_file()\n\n def _create_dataset_yaml(self):\n bin_dir_path = os.path.join(self._tempdir_name, self._bin_dir)\n os.mkdir(bin_dir_path)\n yaml = aspecd.utils.Yaml()\n yaml.binary_directory = bin_dir_path\n yaml.dict = self.dataset.to_dict()\n yaml.serialise_numpy_arrays()\n yaml.write_to(filename=os.path.join(self._tempdir_name,\n self._filenames[\"dataset\"]))\n\n def _create_version_file(self):\n with open(os.path.join(self._tempdir_name,\n self._filenames[\"version\"]),\n 'w+', encoding=\"utf8\") as file:\n file.write(self._version)\n\n def _create_readme_file(self):\n readme_contents = (\n \"Readme\\n\"\n \"======\\n\\n\"\n \"This directory contains an ASpecD dataset stored in the\\n\"\n \"ASpecD dataset format (adf).\\n\\n\"\n \"What follows is a bit of information on the meaning of\\n\"\n \"each of the files in the directory.\\n\"\n \"Sources of further information on the file format\\n\"\n \"are provided at the end of the file.\\n\\n\"\n \"Copyright (c) 2021, Till Biskup\\n\"\n \"2021-01-04\\n\\n\"\n \"Files and their meaning\\n\"\n \"-----------------------\\n\\n\"\n \"* dataset.yaml - text/YAML\\n\"\n \" hierarchical metadata store\\n\\n\"\n \"* binaryData/.npy - NumPy binary\\n\"\n \" numerical data of the dataset stored in NumPy format\\n\\n\"\n \" Only arrays exceeding a certain threshold are stored\\n\"\n \" in binary format, mainly to save space and preserve\\n\"\n \" numerical accuracy.\\n\\n\"\n \"* VERSION - text\\n\"\n \" version number of the dataset format\\n\\n\"\n \" The version number follows the semantic versioning scheme.\\n\\n\"\n \"* README - text\\n\"\n \" This file\\n\\n\"\n \"Further information\\n\"\n \"-------------------\\n\\n\"\n \"More information can be found on the web in the\\n\"\n \"ASpecD package documentation:\\n\\n\"\n \"https://docs.aspecd.de/adf.html\\n\"\n )\n with open(os.path.join(self._tempdir_name,\n self._filenames[\"readme\"]),\n 'w+', encoding=\"utf8\") as file:\n file.write(readme_contents)\n\n\nclass AdfImporter(DatasetImporter):\n \"\"\"\n Dataset importer for importing from ASpecD dataset format.\n\n For more details of the ASpecD dataset format, see the\n :class:`aspecd.io.AdfExporter` class.\n\n \"\"\"\n\n def __init__(self, source=None):\n super().__init__(source=source)\n self.extension = '.adf'\n self._dataset_yaml_filename = 'dataset.yaml'\n self._bin_dir = 'binaryData'\n\n def _import(self):\n with tempfile.TemporaryDirectory() as tempdir:\n with zipfile.ZipFile(self.source + self.extension, 'r') as \\\n zipped_file:\n zipped_file.extractall(path=tempdir)\n yaml = aspecd.utils.Yaml()\n yaml.binary_directory = os.path.join(tempdir, self._bin_dir)\n yaml.read_from(os.path.join(tempdir,\n self._dataset_yaml_filename))\n yaml.deserialise_numpy_arrays()\n self.dataset.from_dict(yaml.dict)\n\n\nclass AsdfExporter(DatasetExporter):\n \"\"\"\n Dataset exporter for exporting to Advanced Scientific Data Format (ASDF).\n\n For more information on ASDF, see the\n `homepage of the asdf package `_,\n and its `format specification `_.\n\n \"\"\"\n\n def __init__(self, target=None):\n super().__init__(target=target)\n self.extension = '.asdf'\n\n def _export(self):\n if not self.target:\n raise aspecd.exceptions.MissingTargetError\n\n dataset_dict = self.dataset.to_dict()\n dataset_dict[\"dataset_history\"] = dataset_dict.pop(\"history\")\n asdf_file = asdf.AsdfFile(dataset_dict)\n asdf_file.write_to(self.target + self.extension)\n\n\nclass AsdfImporter(DatasetImporter):\n \"\"\"\n Dataset importer for importing from Advanced Scientific Data Format (ASDF).\n\n For more information on ASDF, see the\n `homepage of the asdf package `_,\n and its `format specification `_.\n\n \"\"\"\n\n def __init__(self, source=None):\n super().__init__(source=source)\n self.extension = '.asdf'\n\n def _import(self):\n with asdf.open(self.source + self.extension, lazy_load=False,\n copy_arrays=True) as asdf_file:\n dataset_dict = asdf_file.tree\n dataset_dict[\"history\"] = dataset_dict.pop(\"dataset_history\")\n self.dataset.from_dict(dataset_dict)\n\n\nclass TxtImporter(DatasetImporter):\n # noinspection PyUnresolvedReferences\n \"\"\"\n Dataset importer for importing from plain text files (TXT).\n\n Plain text files have often the disadvantage of no accompanying metadata,\n therefore the use of plain text files for data storage is highly\n discouraged, besides other problems like inherent low resolution/accuracy\n or otherwise large file sizes.\n\n The main reason for this class to exist is that it provides a simple way\n to showcase ASpecD functionality reading from primitive data sources.\n Besides that, sometimes you will encounter plain text files.\n\n .. note::\n The importer relies on :func:`numpy.loadtxt` for reading text files.\n Hence, you can use any parameters understood by this function as\n keys in the :attr:`parameters` attribute. For handling decimal\n separators (non-standard behaviour), see below.\n\n If your data consist of two columns, the first will automatically be\n interpreted as the *x* axis. In all other cases, data will be read as is\n and no axes values explicitly written.\n\n\n Attributes\n ----------\n parameters : :class:`dict`\n Parameters controlling the import\n\n skiprows : :class:`int`\n Number of rows to skip in text file (*e.g.*, header lines)\n\n delimiter : :class:`str`\n The string used to separate values.\n\n Default: None (meaning: whitespace)\n\n comments : :class:`str` | :class:`list`\n Characters or list of characters indicating the start of a comment.\n\n Default: #\n\n separator : :class:`str`\n Character used as decimal separator.\n\n Default: None (meaning: dot)\n\n\n .. admonition:: Decimal separators\n\n Handling decimal separators other than the dot is notoriously\n difficult, though often necessary. For this, the non-standard key\n ``separator`` has been introduced that is not supported by numpy\n itself. If you specify a character using this parameter, the file\n will be read as text and the character specified replaced by the\n dot. Only afterwards will :func:`numpy.loadtxt` be used with all the\n other parameters as usual.\n\n\n .. versionchanged:: 0.6.3\n Document more parameter keys; add handling of decimal separator.\n\n \"\"\"\n\n def __init__(self, source=None):\n super().__init__(source=source)\n self.extension = '.txt'\n self.parameters[\"skiprows\"] = 0\n self.parameters[\"delimiter\"] = None\n self.parameters[\"comments\"] = \"#\"\n self.parameters[\"separator\"] = None\n\n def _import(self):\n if \"separator\" in self.parameters:\n separator = self.parameters.pop(\"separator\")\n else:\n separator = None\n if separator:\n with open(self.source, encoding=\"utf8\") as file:\n contents = file.read()\n contents = contents.replace(separator, '.')\n # noinspection PyTypeChecker\n data = np.loadtxt(io.StringIO(contents), **self.parameters)\n else:\n data = np.loadtxt(self.source, **self.parameters)\n if len(np.shape(data)) > 1 and np.shape(data)[1] == 2:\n self.dataset.data.axes[0].values = data[:, 0]\n data = data[:, 1]\n self.dataset.data.data = data\n\n\nclass TxtExporter(DatasetExporter):\n \"\"\"\n Dataset exporter for exporting to plain text files (TXT).\n\n Plain text files have often the disadvantage of no accompanying metadata,\n therefore the use of plain text files for data storage is highly\n discouraged, besides other problems like inherent low resolution/accuracy\n or otherwise large file sizes.\n\n .. warning::\n All metadata contained within a dataset (including the full history)\n are lost when exporting to plain text. Therefore, using this\n exporter will usually result in you loosing reproducibility. Hence,\n better think twice before using this exporter and use entirely on\n your own risk and only if you *really* know what you are doing (and\n why).\n\n The main reason for this class to exist is that sometimes there is a\n need to export data to a simple exchange format that can be shared with\n collaboration partners.\n\n .. note::\n The importer relies on :func:`numpy.savetxt` for writing text files.\n Hence, the same limitations apply, *e.g.* only working for 1D and 2D\n data, but not data with more than two dimensions.\n\n In case of 1D data, the resulting file will consist of two columns,\n with the first column consisting of the axis values and the second column\n containing the actual data. An example of the contents of such a file\n are given below:\n\n .. code-block::\n\n 3.400000000000000000e+02 6.340967862812832978e-01\n 3.410000000000000000e+02 3.424209074593306257e-01\n 3.420000000000000000e+02 1.675116805484100357e-02\n\n In case of 2D data, the resulting file will contain the axes values in the\n first row/column respectively. Hence, the size of the matrix will be +1\n in both directions compared to the size of the actual data and the first\n element (top left) will always be zero (and shall be ignored). An\n example of the contents of such a file are given below:\n\n .. code-block::\n\n 0.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00\n 3.400000000000000000e+02 6.340967862812832978e-01 5.979077980106655144e-01\n 3.410000000000000000e+02 3.424209074593306257e-01 1.052868239245914328e-01\n 3.420000000000000000e+02 1.675116805484100357e-02 9.050894282755458375e-01\n\n These two examples show immediately two of the problems of this file\n format: You are left to guess the quantity and unit of each the axes,\n and these files get quite big, as many decimal places are stored to\n not loose numerical resolution. With 50 characters per line for a 1D\n dataset (translating to at least one byte each), you end up with 50 kB\n for 1000 values.\n\n \"\"\"\n\n def __init__(self, target=None):\n super().__init__(target=target)\n self.extension = '.txt'\n\n def _export(self):\n if not self.target:\n raise aspecd.exceptions.MissingTargetError\n\n if len(self.dataset.data.axes) == 2:\n data = np.asarray([self.dataset.data.axes[0].values,\n self.dataset.data.data]).T\n else:\n data = np.zeros(np.asarray(self.dataset.data.data.shape) + 1)\n data[1:, 0] = self.dataset.data.axes[0].values\n data[0, 1:] = self.dataset.data.axes[1].values\n data[1:, 1:] = self.dataset.data.data\n\n np.savetxt(self._sanitise_file_extension(self.target), data)\n\n def _sanitise_file_extension(self, target=None):\n return \"\".join([os.path.splitext(target)[0], self.extension])\n","sub_path":"aspecd/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":46994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"89021734","text":"class Collector(object):\n \"\"\"\n Collects the output of a Stream and saves it in a `list` until `fetch()` is\n called, which returns the list and resets it. This is useful for testing,\n or to \"tap\" into Streams to see what they're doing.\n \"\"\"\n\n def __init__(self):\n self._items = list()\n\n def push(self, items):\n self._items.extend(items)\n\n def fetch(self):\n items = self._items\n self._items = list()\n return items\n\n\nclass HalfJoinStream(object):\n \"\"\"\n Half of a JoiningStream, which has the `push()` method needed for an\n upstream Stream to insert data into it, which is combined with information\n about whether it's the left or right half of a join, then pushed down to\n the JoiningStream.\n \"\"\"\n\n def __init__(self, pos, parent):\n self._pos = pos\n self._parent = parent\n\n def push(self, items):\n return self._parent.push(self._pos, items)\n\n\nclass Dictionary(object):\n \"\"\"\n A data structure to handle binary joins on some set of hashable columns\n shared between two \"left\" and \"right\" relations.\n \"\"\"\n\n def __init__(self):\n self._obj = dict()\n\n def get_and_add(self, key, pos, pos_key):\n \"\"\"\n Given a `key` containing the values of the join column(s), looks up\n whether that key exists, and whether the `pos` \"side\" of the join\n (0 for left, 1 for right) contains the `pos_key`. The pos_key is\n added to the set, and the opposite side returned to complete the join.\n \"\"\"\n\n obj = self._obj.get(key)\n if not obj:\n obj = (set(), set())\n self._obj[key] = obj\n l, r = obj\n\n pos_set = l if pos == 0 else r\n exists = pos_key in pos_set\n if not exists:\n pos_set.add(pos_key)\n\n not_exists = not exists\n iterable = r if pos == 0 else l\n return not_exists, iterable\n\n\nclass Deduplicator(object):\n\n def __init__(self):\n self._obj = set()\n\n def should_emit(self, val):\n val_hashable = tuple(sorted(val.items()))\n exists = val_hashable in self._obj\n if not exists:\n self._obj.add(val_hashable)\n return not exists\n\n\nclass JoiningStream(object):\n \"\"\"\n A Stream interface object which implements a natural join between two\n Streams.\n \"\"\"\n\n def __init__(self, left, right):\n self._join = Dictionary()\n\n self.left = HalfJoinStream(0, self)\n self.right = HalfJoinStream(1, self)\n\n left_attr_set = set(left.attr_names)\n right_attr_set = set(right.attr_names)\n\n self._join_attrs = list(left_attr_set & right_attr_set)\n self._left_attrs = list(left_attr_set - right_attr_set)\n self._right_attrs = list(right_attr_set - left_attr_set)\n\n assert len(self._join_attrs) > 0, \\\n \"Natural join needs at least one shared attribute \" \\\n \"between %r and %r\" \\\n % (left.attr_names, right.attr_names)\n\n self._listeners = list()\n\n def attrs(self):\n return self._left_attrs + self._join_attrs + self._right_attrs\n\n def push(self, pos, items):\n output_items = list()\n\n for item in items:\n idx = tuple([item[k] for k in self._join_attrs])\n\n attrs = self._left_attrs if pos == 0 else self._right_attrs\n other_attrs = self._right_attrs if pos == 0 else self._left_attrs\n key = tuple([item[k] for k in attrs])\n not_exists, iterable = self._join.get_and_add(idx, pos, key)\n\n if not_exists:\n out = self._push(item, iterable, other_attrs)\n output_items.extend(out)\n\n for listener in self._listeners:\n listener.push(output_items)\n\n def _push(self, base_val, iterable, other_attrs):\n out = list()\n\n for o in iterable:\n val = base_val.copy()\n for k, v in zip(other_attrs, o):\n val[k] = v\n out.append(val)\n\n return out\n\n\nclass Stream(object):\n \"\"\"\n Streaming relational operations. Each instance of Stream may transform the\n tuples and `push()` them down to listeners. In this way, a network of\n Streams can perform operations with limited local state.\n \"\"\"\n\n def __init__(self, attr_names, push_func=None):\n self.attr_names = attr_names\n self._push_func = push_func\n self._listeners = list()\n\n def push(self, items):\n if self._push_func is not None:\n items = self._push_func(self, items)\n\n #import sys; print>>sys.stderr,\"PUSH: %r\" % items\n for listener in self._listeners:\n listener.push(items)\n\n def collect(self):\n collector = Collector()\n self._listeners.append(collector)\n return collector\n\n def union(self, other):\n self._assert_compatible(other, \"union\")\n # TODO\n raise StandardError(\"Stream.union not implemented\")\n\n def intersection(self, other):\n self._assert_compatible(other, \"intersection\")\n # TODO\n raise StandardError(\"Stream.intersection not implemented\")\n\n def difference(self, other):\n self._assert_compatible(other, \"difference\")\n # TODO\n raise StandardError(\"Stream.difference not implemented\")\n\n def projection(self, new_attr_names):\n emitted = Deduplicator()\n\n def push_func(stream, items):\n new_items = list()\n for item in items:\n new_item = dict([[k, item[k]] for k in new_attr_names])\n if emitted.should_emit(new_item):\n new_items.append(new_item)\n return new_items\n\n s = Stream(new_attr_names, push_func)\n self._listeners.append(s)\n return s\n\n def selection(self, pred):\n # TODO\n raise StandardError(\"Stream.selection not implemented\")\n\n def rename(self, new_attr_names):\n names = zip(new_attr_names, self.attr_names)\n\n def push_func(stream, items):\n new_items = list()\n for item in items:\n new_item = dict([(new, item[old]) for (new, old) in names])\n new_items.append(new_item)\n return new_items\n\n s = Stream(new_attr_names, push_func)\n self._listeners.append(s)\n return s\n\n def unnest(self, attr, unnested_attr):\n seen = Deduplicator()\n\n def push_func(stream, items):\n new_items = list()\n for item in items:\n for val in item[attr]:\n new_item = item.copy()\n new_item.pop(attr)\n new_item[unnested_attr] = val\n if seen.should_emit(new_item):\n new_items.append(new_item)\n return new_items\n\n replace_idx = self.attr_names.index(attr)\n attrs = list(self.attr_names)\n attrs[replace_idx] = unnested_attr\n s = Stream(attrs, push_func)\n self._listeners.append(s)\n return s\n\n def join_func(self, arg_names, result_name, func):\n def push_func(stream, items):\n new_items = list()\n for item in items:\n assert isinstance(item, dict), \"Item %r should be dict\" % item\n new_item = item.copy()\n args = [item[arg] for arg in arg_names]\n new_item[result_name] = func(*args)\n new_items.append(new_item)\n return new_items\n\n s = Stream(self.attr_names + [result_name], push_func)\n self._listeners.append(s)\n return s\n\n def natural_join(self, other):\n js = JoiningStream(self, other)\n\n self._listeners.append(js.left)\n other._listeners.append(js.right)\n\n s = Stream(js.attrs())\n js._listeners.append(s)\n return s\n\n def _indices_for(self, attrs):\n indices = list()\n for n in attrs:\n indices.append(self.attr_names.index(n))\n return indices\n\n def _assert_compatible(self, other, op_name):\n assert self.attr_names == other.attr_names, \\\n \"Stream attributes incompatible in %s: %r != %r\" \\\n % (op_name, self.attr_names, other.attr_names)\n","sub_path":"neat_yet_again/neat/external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":8213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"611065664","text":"from numpy import *\nimport operator \nimport matplotlib\nimport matplotlib.pyplot as plt\ndef createDataSet():\n\tgroup = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n\tlabels = ['A','A','B','B']\n\treturn group, labels\ndef classify0(inx,dataSet, label, k):\n\tdataSetSize = dataSet.shape[0]\n\tdiffMat = tile(inx, (dataSetSize,1))-dataSet\n\tsqDiffMat = diffMat**2\n\tsqDistances = sqDiffMat.sum(axis=1)\n\tdistances = sqDistances**0.5\n\tsortedDistIndicies = distances.argsort()\n\tclassCount = {}\n\tfor i in range(k):\n\t\tvoteIlabel = labels[sortedDistIndicies[i]]\n\t\tclassCount[voteIlabel] = classCount.get(voteIlabel,0)+1\n\tsortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)\t\n\treturn sortedClassCount[0][0]\n\ndef file2matrix(filename):\n\tfr = open(filename)\n\tarrayOLines = fr.readlines()\n\tnumberOfLines = len(arrayOLines)\n\treturnMat = zeros((numberOfLines,3))\n\tclassLabelVector = []\n\tindex = 0\n\tfor line in arrayOLines:\n\t\tline = line.strip()\n\t\tlistFromLine = line.split('\\t')\n\t\treturnMat[index,:] = listFromLine[0:3]\n\t\tclassLabelVector.append(int(listFromLine[-1]))\n\t\tindex += 1\n\treturn returnMat,classLabelVector\n\n#group,labels = createDataSet()\n#print classify0([3,0],group,labels,3)\ndatingDataMat,datingLabels = file2matrix(\"datingTestSet2.txt\")\n#datingDataMat,datingLabels = file2matrix(\"C:\\Python27\\datingTestSet2.txt\")\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(datingDataMat[:,1],datingDataMat[:,2])\nplt.show()","sub_path":"KNN/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"391833347","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import absolute_import\r\n\r\nfrom billiard import Process\r\nfrom pymongo import MongoClient\r\nfrom scrapy.utils.project import get_project_settings\r\n\r\nfrom celery_tasks.tasks.ok_focus_group import _crawl\r\nfrom common.helpers.list_helpers import split\r\n\r\ntry:\r\n from distributed import Executor as Client\r\nexcept ImportError:\r\n # Executor was renamed to Client\r\n from distributed import Client\r\n\r\nNUM_WORKERS = 48\r\nTOPIC_PAGES = 5\r\nCOMMENT_PAGES = 3\r\nWAIT_MINUTES = 30\r\n\r\n\r\ndef get_groups():\r\n mongo_url = get_project_settings().get('COMMON', {}).get('mongo.url')\r\n client = MongoClient(mongo_url)\r\n db = client['focus_crawl_db']\r\n groups = db['groups']\r\n return [str(g['group_id']) for g in groups.find().sort('last_modified', -1)]\r\n\r\n\r\ndef crawl(pid, group_ids, topic_pages=5, comment_pages=3):\r\n p = Process(target=_crawl, args=[pid, group_ids, topic_pages, comment_pages])\r\n p.start()\r\n p.join()\r\n\r\n\r\ndef run():\r\n group_ids = [group_id for group_id in get_groups()]\r\n chunks = split(group_ids, num_of_chunks=NUM_WORKERS)\r\n\r\n client = Client('hdp-05:8786')\r\n futures = client.map(crawl, range(NUM_WORKERS), chunks)\r\n client.gather(futures)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run()\r\n # while True:\r\n # run()\r\n # sleep(60 * WAIT_MINUTES)\r\n","sub_path":"celery_tasks/run/ok_focus_group_dask.py","file_name":"ok_focus_group_dask.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"568270547","text":"import socket\nimport json\nimport struct\nimport asterix\nimport uvicorn\nfrom threading import Thread\nfrom mess import Mess\n# socketio\nimport socketio\nsio = socketio.AsyncServer(async_mode='asgi')\napp = socketio.ASGIApp(sio, static_files={\n '/': {'content_type': 'text/html', 'filename': 'app.html'},\n})\nbackground_task_started = False\nbackground_search_started = False\nglobal msg\nmsg = '[{}' \nasync def background_task():\n \"\"\"Example of how to send server generated events to clients.\"\"\"\n count = 0\n while True:\n # thread.start_new_thread(search, ('test.log'), {\"id\": 1})\n # search('test.log')\n # background_search_started = True\n await sio.sleep(1)\n count += 1\n global msg\n await sio.emit('data',msg+']',namespace='/test')\n msg = '[{}'\n \n@sio.on('connect', namespace='/test')\nasync def test_connect(sid, environ):\n global background_task_started\n if not background_task_started:\n sio.start_background_task(background_task)\n background_task_started = True\n\n@sio.on('disconnect', namespace='/test')\ndef test_disconnect(sid):\n print('Client disconnected')\n\ndef udpInit():\n # socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', 9999)) # 广播方式\n\n # mess = ''\n # data_rest = None\n while True:\n data = sock.recv(100)\n # print('----------------------')\n # Parse data verbose=False\n parsed = asterix.parse(data, verbose=False)\n # for packet in parsed:\n # for item in packet.items():\n # print(item)\n # print('----------------------')\n mess = Mess(parsed)\n mess.getData()\n mess.parsed = ''\n in_json = json.dumps(mess.__dict__) \n # print(in_json)\n global msg\n msg += ',' + in_json\n\nif __name__ == '__main__':\n thread_01 = Thread(target=udpInit)\n thread_01.start()\n uvicorn.run(app, host='127.0.0.1', port=5012)","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"356113470","text":"#\r\n# Copyright (c) 2018 Intel Corporation\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n\r\nimport pytest\r\nfrom ie_serving.models.model import Model\r\n\r\n\r\ndef test_model_init():\r\n new_model = Model(model_name=\"test\", model_directory='fake_path',\r\n available_versions=[1, 2, 3], engines={})\r\n assert new_model.default_version == 3\r\n assert new_model.model_name == 'test'\r\n assert new_model.model_directory == 'fake_path'\r\n assert new_model.engines == {}\r\n\r\n\r\n@pytest.mark.parametrize(\"path, expected_value\", [\r\n ('fake_path/model/1', 1),\r\n ('fake_path/model/1/test', 0),\r\n ('fake_path/model/56', 56)\r\n])\r\ndef test_get_version_number_of_model(path, expected_value):\r\n output = Model.get_model_version_number(version_path=path)\r\n assert output == expected_value\r\n\r\n\r\n@pytest.mark.parametrize(\"path, model_files, expected_value\", [\r\n ('fake_path/model/1', [['model.bin'], ['model.xml']],\r\n ('model.xml', 'model.bin')),\r\n ('fake_path/model/1', [['model'], ['model.xml']],\r\n (None, None)),\r\n ('fake_path/model/1', [['model.bin'], ['model.yml']],\r\n (None, None))\r\n])\r\ndef test_get_absolute_path_to_model(mocker, path, model_files,\r\n expected_value):\r\n model_mocker = mocker.patch('glob.glob')\r\n model_mocker.side_effect = model_files\r\n output1, output2 = Model.get_absolute_path_to_model(\r\n specific_version_model_path=path)\r\n assert expected_value[0] == output1\r\n assert expected_value[1] == output2\r\n\r\n\r\ndef test_get_all_available_versions(mocker):\r\n new_model = Model(model_name=\"test\", model_directory='fake_path/model/',\r\n available_versions=[1, 2, 3], engines={})\r\n model_mocker = mocker.patch('glob.glob')\r\n models_path = [new_model.model_directory + str(x) for x in range(5)]\r\n model_mocker.return_value = models_path\r\n absolute_path_model_mocker = mocker.patch('ie_serving.models.model.Model.'\r\n 'get_absolute_path_to_model')\r\n absolute_path_model_mocker.side_effect = [(None, None),\r\n ('modelv2.xml', 'modelv2.bin'),\r\n (None, None),\r\n ('modelv4.xml', 'modelv4.bin')]\r\n output = new_model.get_all_available_versions(new_model.model_directory)\r\n expected_output = [{'xml_model_path': 'modelv2.xml',\r\n 'bin_model_path': 'modelv2.bin', 'version': 2},\r\n {'xml_model_path': 'modelv4.xml', 'bin_model_path':\r\n 'modelv4.bin', 'version': 4}]\r\n\r\n assert 2 == len(output)\r\n assert expected_output == output\r\n\r\n\r\ndef test_get_engines_for_model(mocker):\r\n engines_mocker = mocker.patch('ie_serving.models.ir_engine.IrEngine.'\r\n 'build')\r\n engines_mocker.side_effect = ['modelv2', 'modelv4']\r\n available_versions = [{'xml_model_path': 'modelv2.xml',\r\n 'bin_model_path': 'modelv2.bin', 'version': 2},\r\n {'xml_model_path': 'modelv4.xml', 'bin_model_path':\r\n 'modelv4.bin', 'version': 4}]\r\n output = Model.get_engines_for_model(versions=available_versions)\r\n assert 2 == len(output)\r\n assert 'modelv2' == output[2]\r\n assert 'modelv4' == output[4]\r\n\r\n\r\ndef test_get_engines_for_model_with_ir_raises(mocker):\r\n engines_mocker = mocker.patch('ie_serving.models.ir_engine.IrEngine.'\r\n 'build')\r\n engines_mocker.side_effect = ['modelv2', 'modelv4', Exception(\"test\")]\r\n available_versions = [{'xml_model_path': 'modelv2.xml',\r\n 'bin_model_path': 'modelv2.bin', 'version': 2},\r\n {'xml_model_path': 'modelv4.xml', 'bin_model_path':\r\n 'modelv4.bin', 'version': 3},\r\n {'xml_model_path': 'modelv4.xml', 'bin_model_path':\r\n 'modelv4.bin', 'version': 4}]\r\n output = Model.get_engines_for_model(versions=available_versions)\r\n assert 2 == len(output)\r\n assert 'modelv2' == output[2]\r\n assert 'modelv4' == output[3]\r\n","sub_path":"tests/unit/models/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"15856118","text":"# Geschreven door Quinty van Dijk\n\nimport cv2\nimport block\nimport color\nimport connect\nimport calibrate\nfrom easygui import *\nimport numpy as np\nfrom time import sleep\n\nstr1 = \"\\x1b[0;30;44m\"\nstr2 = \"\\x1b[0m\"\n\n\ndef nothing(x):\n pass\n\n\ndef init():\n print(str1 + \"Start init\" + str2)\n # ghallow kwintie\n # Make windows to show webcam image, gray image etc\n cv2.WINDOW_AUTOSIZE\n\n cv2.namedWindow(\"beeld1\", cv2.WINDOW_AUTOSIZE)\n\n cv2.moveWindow(\"beeld1\", 0, 0)\n\n cv2.namedWindow(\"beeld2\", cv2.WINDOW_AUTOSIZE)\n\n cv2.moveWindow(\"beeld2\", 640, 0)\n\n cv2.namedWindow(\"beeld3\", cv2.WINDOW_AUTOSIZE)\n\n cv2.moveWindow(\"beeld3\", 640 * 2, 0)\n\n cv2.namedWindow(\"beeld4\", cv2.WINDOW_AUTOSIZE)\n\n cv2.moveWindow(\"beeld4\", 640 * 2, 480)\n\n # cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)\n # cv2.moveWindow('image', 640, 0)\n # cv2.createTrackbar('B', 'image', 0, 255, nothing)\n # cv2.createTrackbar('G', 'image', 0, 255, nothing)\n # cv2.createTrackbar('R', 'image', 0, 255, nothing)\n #\n # cv2.createTrackbar('B1', 'image', 0, 255, nothing)\n # cv2.createTrackbar('G1', 'image', 0, 255, nothing)\n # cv2.createTrackbar('R1', 'image', 0, 255, nothing)\n\n # Make connection to webcam\n webcam = cv2.VideoCapture(1)\n\n webcam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n webcam.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\n webcam.get(cv2.CAP_PROP_FRAME_WIDTH)\n\n # return webcam info\n print(str1 + \"Init Done\" + str2)\n return webcam\n\n\ndef calibration(cam, threshold):\n print(str1 + \"Start calibration\" + str2)\n while True:\n retval, img = cam.read()\n if retval:\n b, x, y = calibrate.calibrate(img, threshold)\n print(str1 + \"Calibration done\" + str2)\n return b, x, y\n\n\ndef next_color(code):\n code += 1\n if code >= 3:\n code = 1\n return code\n\n\ndef get_color(code):\n if code == 1:\n return \"yellow\"\n if code == 2:\n return \"red\"\n\n\ndef get_edges(img):\n cv2.imwrite(\"image.jpg\", img)\n\n imggray_temp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n cv2.imwrite(\"grayscale.jpg\", imggray_temp)\n\n # Maak imggray \"smoother\" voor minder ruis en dus betere detectie\n imggray = cv2.GaussianBlur(imggray_temp, (5, 5), 0)\n cv2.imwrite(\"blur.jpg\", imggray)\n\n # Voor canny methode uit, geeft afbeelding met randen\n img_edges = cv2.Canny(imggray, 60, 100)\n cv2.imwrite(\"edges.jpg\", img_edges)\n print(str1 + \"IMG processing done, edges made\" + str2)\n\n return img_edges\n\n\ndef get_image(webcam):\n while True:\n retval, img = webcam.read()\n if retval:\n return img\n\n\ndef to_mm(x, y, img):\n # y_img, x_img, bin = img.shape\n # print(199/y_img)\n # print(278/x_img)\n # y_mm = 198 / y_img * y\n # x_mm = 2786 / x_img * x\n # x_mm -= 159\n # y_mm -= 158\n\n # vector = np.array([[x], [y]])\n # print(vector)\n # trans_matrix = np.array([[-158, 120], [-159, 40]])\n # print(trans_matrix)\n # trans_vector = trans_matrix * vector\n # print(trans_vector)\n\n cx = int((x / 1.73) - 136)\n if cx < 0:\n cx = int(cx * 0.965)\n\n if cx > 0:\n cx = int(cx * 0.88)\n\n cy = int(((y / 1.69) - 175) * 0.93)\n\n return cx, cy\n\n\n# Main:\n# init and calibration\ncolor_code = 1\nwebcam = init()\ncalibrated = False\ncal_threshold = 0.7\ny_mm_save = []\nx_mm_save = []\ndelay = 3\n\n# # Wait for PLC\nwhile not connect.from_plc():\n print(str1 + \"Waiting for PLC before calibration\" + str2)\nimg_warped = 0\nwhile not calibrated:\n # calibration:\n try:\n b_cal, x_cal, y_cal = calibration(webcam, cal_threshold)\n # show calibration status\n img = get_image(webcam)\n img_warped = calibrate.warp(img, b_cal, x_cal, y_cal)\n\n print(\"show images:\")\n cv2.imshow(\"beeld4\", img_warped)\n cv2.waitKey(10)\n\n user = boolbox(msg=\"Calibratie oke?\", title=\"Calibratie\", choices=(\"[J]a\", \"[N]ee\"), default_choice=\"Yes\")\n if not user:\n cal_threshold = float(enterbox(msg=\"Threshold nu is\" + str(cal_threshold), title=\"Threshold check\",\n default=str(cal_threshold)))\n if user:\n calibrated = True\n\n\n except Exception:\n print(\"calibratie mislukt!\")\n cal_threshold = float(enterbox(msg=\"Calibratie mislukt! Threshold nu is:\" + str(cal_threshold), title=\"Threshold check\",\n default=str(cal_threshold)))\n\n# main loop\nprint(str1 + \"Start loop\" + str2)\nwhile True:\n if cv2.waitKey(10) == 27:\n break\n print(str1 + \"Top of loop. Waiting for plc\" + str2)\n # Wait for connection from PLC\n while not connect.from_plc():\n img = get_image(webcam)\n img_warped = calibrate.warp(img, b_cal, x_cal, y_cal)\n ready = True\n count_red = 0\n count_mov_red = 0\n count_yellow = 0\n count_mov_yellow = 0\n\n while ready:\n\n # img = cv2.imread(\"C:/Users/kwint/Documents/1. School/Python dingen/project/test.jpg\")\n\n # Get image from webcam\n img = get_image(webcam)\n\n # warp image from with data gotten from calibration\n img_warped = calibrate.warp(img, b_cal, x_cal, y_cal)\n\n # Filter one color out image\n img_color = color.mask_img(color_code, img_warped)\n\n # convert img color to edges.\n img_edges = get_edges(img_color)\n\n # Check for a shape in image\n tmp = block.recognize(img_edges, img_warped)\n\n # If shape found, send it to PLC\n if tmp:\n x_got, y_got, shape, degree = tmp\n\n print(str1 + \"Found a shape!\" + str2, get_color(color_code))\n\n x_mm, y_mm = to_mm(x_got, y_got, img_warped)\n print(y_mm, x_mm)\n\n cv2.putText(img_warped, str(y_mm), (80, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, str(x_mm), (80, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, str(degree), (80, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, str(shape), (80, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, str(color_code), (80, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, get_color(color_code), (100, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n\n print(type(x_mm), type(y_mm), type(shape), type(degree), type(color_code), color_code)\n if color_code == 1:\n if count_yellow == 0:\n x_mm_temp_yellow = x_mm\n y_mm_temp_yellow = y_mm\n count_yellow = 1\n elif count_yellow == 1:\n\n x_change_yellow = abs(x_mm_temp_yellow - x_mm)\n y_change_yellow = abs(y_mm_temp_yellow - y_mm)\n count_yellow = 0\n print(\"x_change: \", x_change_yellow)\n print(\"y_change: \", y_change_yellow)\n if x_change_yellow < 3 and y_change_yellow < 3:\n count_mov_yellow += 1\n else:\n count_mov_yellow = 0\n\n if count_mov_yellow > delay:\n print(\"sending to plc\")\n connect.to_plc(int(y_mm), int(x_mm), shape, color_code,\n degree) # veranderd naar int (tim) was eerst floats\n ready = False\n count_yellow = 0\n count_mov_yellow = 0\n count_mov_rd = 0\n\n if color_code == 2:\n if count_red == 0:\n x_mm_temp_red = x_mm\n y_mm_temp_red = y_mm\n count_red = 1\n elif count_red == 1:\n\n x_change_red = abs(x_mm_temp_red - x_mm)\n y_change_red = abs(y_mm_temp_red - y_mm)\n count_red = 0\n print(\"x_change: \", x_change_red)\n print(\"y_change: \", y_change_red)\n if x_change_red < 3 and y_change_red < 3:\n count_mov_red += 1\n else:\n count_mov_red = 0\n\n if count_mov_red > delay:\n print(\"sending to plc\")\n connect.to_plc(int(y_mm), int(x_mm), shape, color_code,\n degree) # veranderd naar int (tim) was eerst floats\n ready = False\n count_red = 0\n count_mov_red = 0\n count_mov_yellow = 0\n\n print(\"Count: \", count_red)\n print(\"Count_mov\", count_mov_red)\n\n\n\n # If shape not found, tmp == false, print error message and go on\n else:\n print(str1 + \"Didn't found a shape with color: \" + str2, get_color(color_code))\n\n # Shape found or not, let's check the next color\n color_code = next_color(color_code)\n\n # Show images to windows\n cv2.putText(img_warped, \"X_mm:\", (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, \"Y_mm:\", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, \"Angle:\", (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, \"Block:\", (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.putText(img_warped, \"Color:\", (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)\n cv2.imshow(\"beeld1\", img)\n cv2.imshow(\"beeld2\", img_color)\n cv2.imshow(\"beeld3\", img_edges)\n cv2.imshow(\"beeld4\", img_warped)\n cv2.imwrite(\"gevonden.jpg\", img)\n cv2.imwrite(\"edges.jpg\", img_edges)\n cv2.imwrite(\"warped.jpg\", img_warped)\n\n # Press esc to exit program\n if cv2.waitKey(10) == 27:\n break\n\nwebcam.release()\ncv2.destroyAllWindows()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"20285625","text":"import pytest\nfrom brownie.test import given, strategy\nfrom hypothesis import settings, Phase\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef module_setup(accounts, escrow, lp_token, airdrop_token):\n for i in range(3):\n lp_token._mint_for_testing(10**24, {'from': accounts[i]})\n lp_token.approve(escrow, 10**24, {'from': accounts[i]})\n escrow.add_token(airdrop_token, {'from': accounts[0]})\n airdrop_token._mint_for_testing(10**24, {'from': accounts[3]})\n\n\n@pytest.fixture(scope=\"module\")\ndef airdrop_tokens(ERC20_Revert, accounts, airdrop_token, escrow):\n token_list = [airdrop_token]\n for i in range(2):\n token = ERC20_Revert.deploy(\"Airdrop\", \"AD\", 18, {'from': accounts[0]})\n token._mint_for_testing(10**24, {'from': accounts[3]})\n escrow.add_token(token, {'from': accounts[0]})\n token_list.append(token)\n\n yield token_list\n\n\n@given(\n st_deposits=strategy(\"uint256[3]\", min_value=10**17, max_value=10**21, unique=True),\n st_airdrops=strategy(\"uint256[10]\", min_value=10**10, max_value=10**18, unique=True)\n)\n@settings(max_examples=10, phases=[Phase.generate, Phase.target])\ndef test_many_airdrops_single_claim(accounts, rpc, escrow, airdrop_token, st_deposits, st_airdrops):\n \"\"\"\n Verify correct claim amount from a single claim of many airdrops.\n \"\"\"\n\n # initial deposits of `lp_token`\n total_deposited = sum(st_deposits)\n for i in range(3):\n escrow.deposit(st_deposits[i], {'from': accounts[i]})\n\n # ensure claims are in a new token epoch\n rpc.sleep(86400 * 7)\n\n # perform 10 airdrops\n for amount in st_airdrops:\n rpc.sleep(14)\n airdrop_token.transfer(escrow, amount, {'from': accounts[3]})\n escrow.checkpoint()\n\n # ensure claims are in a new token epoch\n rpc.sleep(86400 * 7)\n\n # claim the tokens\n received = [0, 0, 0]\n for i in range(3):\n escrow.claim(airdrop_token, {'from': accounts[i]})\n received[i] = airdrop_token.balanceOf(accounts[i])\n\n # total dust should be less than 1%\n assert 0.99 < sum(received) / sum(st_airdrops) <= 1\n\n # actual amounts received should be less than 1% off expected amounts\n for i in range(3):\n expected_pct = st_deposits[i] / total_deposited\n received_pct = received[i] / sum(received)\n assert abs(expected_pct - received_pct) < 0.01\n\n\n@given(\n st_deposits=strategy(\"uint256[3]\", min_value=10**17, max_value=10**21, unique=True),\n st_airdrops=strategy(\"uint256[10]\", min_value=10**10, max_value=10**18, unique=True)\n)\n@settings(max_examples=10)\ndef test_many_airdrops_many_claims(accounts, rpc, escrow, airdrop_token, st_deposits, st_airdrops):\n \"\"\"\n Verify correct claim amounts over multiple claims.\n \"\"\"\n\n # make initial deposits of `lp_token`\n total_deposited = sum(st_deposits)\n for i in range(3):\n escrow.deposit(st_deposits[i], {'from': accounts[i]})\n\n for amount in st_airdrops:\n\n # ensure each claim is in a new token epoch\n rpc.sleep(86400 * 7)\n\n airdrop_token.transfer(escrow, amount, {'from': accounts[3]})\n\n received = [0, 0, 0]\n for i in range(3):\n balance = airdrop_token.balanceOf(accounts[i])\n escrow.claim(airdrop_token, {'from': accounts[i]})\n received[i] = airdrop_token.balanceOf(accounts[i]) - balance\n\n # dust should be less than 0.1%\n assert 0.999 < sum(received) / amount <= 1\n\n # actual amounts received should be less than 0.1% off expected amounts\n for i in range(3):\n expected_pct = st_deposits[i] / total_deposited\n received_pct = received[i] / sum(received)\n assert abs(expected_pct - received_pct) < 0.001\n\n\n@given(\n st_deposits=strategy(\"uint256[3]\", min_value=10**17, max_value=10**21, unique=True),\n st_airdrops=strategy(\"uint256[3][5]\", min_value=10**10, max_value=10**18),\n)\n@settings(max_examples=10)\ndef test_multiple_airdrop_tokens(accounts, rpc, escrow, airdrop_tokens, st_deposits, st_airdrops):\n \"\"\"\n Verify correct claim amount over multiple claims with several tokens.\n \"\"\"\n\n # make initial deposits of `lp_token`\n total_deposited = sum(st_deposits)\n for i in range(3):\n escrow.deposit(st_deposits[i], {'from': accounts[i]})\n\n for amounts in st_airdrops:\n\n # ensure each claim is in a new token epoch\n rpc.sleep(86400 * 7)\n\n for i in range(3):\n airdrop_tokens[i].transfer(escrow, amounts[i], {'from': accounts[3]})\n escrow.checkpoint()\n\n for token, amount in zip(airdrop_tokens, amounts):\n received = [0, 0, 0]\n for i in range(3):\n balance = token.balanceOf(accounts[i])\n escrow.claim(token, {'from': accounts[i]})\n received[i] = token.balanceOf(accounts[i]) - balance\n\n # dust should be less than 0.1%\n assert 0.999 < sum(received) / amount <= 1\n\n # actual amounts received should be less than 0.1% off expected amounts\n for i in range(3):\n expected_pct = st_deposits[i] / total_deposited\n received_pct = received[i] / sum(received)\n assert abs(expected_pct - received_pct) < 0.001\n\n\n@given(\n st_transfers=strategy(\"uint256[9]\", min_value=10**17, max_value=10**18, unique=True),\n st_airdrops=strategy(\"uint256[9]\", min_value=10**10, max_value=10**18, unique=True)\n)\n@settings(max_examples=10)\ndef test_claims_with_adjusted_deposits(\n accounts, rpc, alice, escrow, airdrop_token, st_transfers, st_airdrops\n):\n \"\"\"\n Verify correct amount over multiple claims, with changing `lp_token` balances.\n \"\"\"\n\n # alice makes the only initial deposit\n escrow.deposit(10**19, {'from': alice})\n balances = [10**19]\n\n for receiver, transfer_amount, airdrop_amount in zip(accounts[1:], st_transfers, st_airdrops):\n\n # transfer a portion of alice's balance to another account\n rpc.sleep(1)\n escrow.transfer(receiver, transfer_amount, {'from': alice})\n balances[0] -= transfer_amount\n balances.append(transfer_amount)\n\n # perform an airdrop\n airdrop_token.transfer(escrow, airdrop_amount, {'from': accounts[3]})\n rpc.sleep(86400 * 7)\n\n # claim airdrop tokens\n received = []\n for i in range(len(balances)):\n balance = airdrop_token.balanceOf(accounts[i])\n escrow.claim(airdrop_token, {'from': accounts[i]})\n received.append(airdrop_token.balanceOf(accounts[i]) - balance)\n\n # dust should be less than 0.1%\n assert 0.999 < sum(received) / airdrop_amount <= 1\n\n # actual amounts received should be less than 0.1% off expected amounts\n for i in range(len(balances)):\n expected_pct = balances[i] / sum(balances)\n received_pct = received[i] / sum(received)\n assert abs(expected_pct - received_pct) < 0.001\n","sub_path":"tests/integration/test_claim_airdrops.py","file_name":"test_claim_airdrops.py","file_ext":"py","file_size_in_byte":6962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"111818180","text":"\"\"\"\nSimple command-line tool to ask MC-questions.\n\"\"\"\n\nimport json\nimport random\nimport sys\nfrom timer import Timer\n\n\nDEFAULT_INPUT = 'questions/piliin.json'\nTIME_LIMIT = 30\n\n\ndef shuffle(answers):\n \"\"\"\n Returns mixed answers and the index of the correct one,\n assuming the first answer is the correct one.\n \"\"\"\n indices = list(range(len(answers)))\n random.shuffle(indices)\n correct = indices.index(0)\n answers = [answers[i] for i in indices]\n return answers, correct\n\n\ndef ask_question(question):\n print(\"\\n\\n{}\\n\".format(question[\"question\"]))\n answers, correct = shuffle(question[\"answers\"])\n correct = str(correct + 1)\n for i, text in enumerate(answers):\n print(\"[{}] {}\".format(i+1, text))\n ans = input(\"\\nEnter your answer: \")\n if ans == correct:\n return True\n return False\n\n\ndef quiz(questions):\n n_correct = 0\n timer = Timer(TIME_LIMIT)\n for q in questions:\n print('-' * 79)\n print('\\nTime left: {:4.1f}'.format(timer.time_left))\n if ask_question(q):\n n_correct += 1\n if timer.expired:\n break\n return n_correct\n\n\nif __name__ == '__main__':\n username = input(\"\\nEnter your name: \")\n bb = input(\"\\nEnter the name of your bb: \")\n if len(sys.argv) == 2:\n fn = sys.argv[1]\n else:\n fn = DEFAULT_INPUT\n\n with open(fn) as f:\n questions = json.load(f)\n n_correct = quiz(questions)\n print('\\nCorrect answers: {}'.format(n_correct) + \" over 5\")\n if n_correct < 3:\n print(\"Fail. Hay naku, \" + username + \". Mali ang pinili mo. \" + bb + \" will be mad.\")\n else: \n print(\"Pass. Congrats \" + username + \". Tama ang pinili mo. \" + bb + \" will be proud.\")\n","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"517632095","text":"import matplotlib.image as mpimg\n\ndef readImage(filename, factor):\n img=mpimg.imread(filename)\n k = img[:,:,0]\n Nx = k.shape[1]\n Ny = k.shape[0]\n for j in range(Nx):\n for i in range(Ny):\n if k[i,j] == 0.0:\n k[i,j] = 0.1\n if k[i,j] < 1.0:\n k[i,j] *= factor \n\n return k.transpose()\n","sub_path":"Tareas/01/phys_data.py","file_name":"phys_data.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"468582503","text":"# coding: utf-8\n\n\"\"\"\nIscsiInterfaceStatistics.py\n\n The Clear BSD License\n\n Copyright (c) – 2016, NetApp, Inc. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom pprint import pformat\nfrom six import iteritems\n\n\nclass IscsiInterfaceStatistics(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self):\n \"\"\"\n IscsiInterfaceStatistics - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'ethernet_port_stats': 'list[EthernetPortStatistics]', # (required parameter)\n 'tcp_stats': 'list[TcpStatisticalData]', # (required parameter)\n 'ip_stats': 'list[IpEndpointStatistics]', # (required parameter)\n 'enh_stats': 'list[EnhancedEthernetStatistics]'\n }\n\n self.attribute_map = {\n 'ethernet_port_stats': 'ethernetPortStats', # (required parameter)\n 'tcp_stats': 'tcpStats', # (required parameter)\n 'ip_stats': 'ipStats', # (required parameter)\n 'enh_stats': 'enhStats'\n }\n\n self._ethernet_port_stats = None\n self._tcp_stats = None\n self._ip_stats = None\n self._enh_stats = None\n\n @property\n def ethernet_port_stats(self):\n \"\"\"\n Gets the ethernet_port_stats of this IscsiInterfaceStatistics.\n Statistics related to the physical Ethernet port.\n\n :return: The ethernet_port_stats of this IscsiInterfaceStatistics.\n :rtype: list[EthernetPortStatistics]\n :required/optional: required\n \"\"\"\n return self._ethernet_port_stats\n\n @ethernet_port_stats.setter\n def ethernet_port_stats(self, ethernet_port_stats):\n \"\"\"\n Sets the ethernet_port_stats of this IscsiInterfaceStatistics.\n Statistics related to the physical Ethernet port.\n\n :param ethernet_port_stats: The ethernet_port_stats of this IscsiInterfaceStatistics.\n :type: list[EthernetPortStatistics]\n \"\"\"\n self._ethernet_port_stats = ethernet_port_stats\n\n @property\n def tcp_stats(self):\n \"\"\"\n Gets the tcp_stats of this IscsiInterfaceStatistics.\n Statistics related to the TCP protocol.\n\n :return: The tcp_stats of this IscsiInterfaceStatistics.\n :rtype: list[TcpStatisticalData]\n :required/optional: required\n \"\"\"\n return self._tcp_stats\n\n @tcp_stats.setter\n def tcp_stats(self, tcp_stats):\n \"\"\"\n Sets the tcp_stats of this IscsiInterfaceStatistics.\n Statistics related to the TCP protocol.\n\n :param tcp_stats: The tcp_stats of this IscsiInterfaceStatistics.\n :type: list[TcpStatisticalData]\n \"\"\"\n self._tcp_stats = tcp_stats\n\n @property\n def ip_stats(self):\n \"\"\"\n Gets the ip_stats of this IscsiInterfaceStatistics.\n Statistics related to the IP protocol.\n\n :return: The ip_stats of this IscsiInterfaceStatistics.\n :rtype: list[IpEndpointStatistics]\n :required/optional: required\n \"\"\"\n return self._ip_stats\n\n @ip_stats.setter\n def ip_stats(self, ip_stats):\n \"\"\"\n Sets the ip_stats of this IscsiInterfaceStatistics.\n Statistics related to the IP protocol.\n\n :param ip_stats: The ip_stats of this IscsiInterfaceStatistics.\n :type: list[IpEndpointStatistics]\n \"\"\"\n self._ip_stats = ip_stats\n\n @property\n def enh_stats(self):\n \"\"\"\n Gets the enh_stats of this IscsiInterfaceStatistics.\n This member is used to report statistical data related to Enhanced Ethernet features.\n\n :return: The enh_stats of this IscsiInterfaceStatistics.\n :rtype: list[EnhancedEthernetStatistics]\n :required/optional: required\n \"\"\"\n return self._enh_stats\n\n @enh_stats.setter\n def enh_stats(self, enh_stats):\n \"\"\"\n Sets the enh_stats of this IscsiInterfaceStatistics.\n This member is used to report statistical data related to Enhanced Ethernet features.\n\n :param enh_stats: The enh_stats of this IscsiInterfaceStatistics.\n :type: list[EnhancedEthernetStatistics]\n \"\"\"\n self._enh_stats = enh_stats\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n if self is None:\n return None\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if self is None or other is None:\n return None\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n","sub_path":"netapp/santricity/models/symbol/iscsi_interface_statistics.py","file_name":"iscsi_interface_statistics.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"565922681","text":"import tensorflow as tf\n\nclass Logger(object):\n \"\"\"Logging in tensorboard without tensorflow ops.\"\"\"\n def __init__(self, log_dir):\n \"\"\"Creates a summary writer logging to log_dir.\"\"\"\n self.writer = tf.summary.FileWriter(log_dir)\n self.metrics = {}\n\n def __call__(self, tag, value, step):\n \"\"\"Log a scalar variable.\n Parameter\n ----------\n tag : basestring\n Name of the scalar\n value : scalar value\n value\n step : int\n training iteration\n \"\"\"\n if tag not in self.metrics:\n _metric = tf.Summary()\n _metric.value.add(tag=tag, simple_value=None)\n self.metrics[tag] = _metric\n\n summary = self.metrics[tag]\n\n summary.value[0].simple_value = value\n self.writer.add_summary(summary, step)","sub_path":"uniparse/utility/tensorboard_logging.py","file_name":"tensorboard_logging.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"95505916","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime, date\n\nfrom django.test import TestCase\n\nfrom ralph_pricing.models import UsageType, DailyUsage, Device\nfrom ralph_pricing.plugins.collects.virtual import (\n get_or_create_usages,\n update_usage,\n update,\n)\nfrom ralph_pricing.tests.utils import (\n get_or_create_device,\n get_or_create_venture,\n)\n\n\nclass TestVirtualPlugin(TestCase):\n def setUp(self):\n self.device = get_or_create_device()\n self.venture = get_or_create_venture()\n\n def _get_usages(self):\n usage_names = {\n 'virtual_cores': 'Virtual CPU cores',\n 'virtual_disk': 'Virtual disk MB',\n 'virtual_memory': 'Virtual memory MB',\n }\n\n return get_or_create_usages(usage_names)\n\n def test_get_usages(self):\n usages = self._get_usages()\n usages_from_database = UsageType.objects.all().order_by('name')\n\n self.assertEqual(usages['virtual_cores'], usages_from_database[0])\n self.assertEqual(usages['virtual_disk'], usages_from_database[1])\n self.assertEqual(usages['virtual_memory'], usages_from_database[2])\n\n def test_update_usage_when_there_is_no_value(self):\n update_usage(\n self.device,\n self.venture,\n self._get_usages()['virtual_cores'],\n datetime.today(),\n None,\n )\n self.assertItemsEqual(DailyUsage.objects.all(), [])\n\n def test_update_usage(self):\n usages = self._get_usages()\n update_usage(\n self.device,\n self.venture,\n usages['virtual_cores'],\n date.today(),\n 1,\n )\n\n daily_usages = DailyUsage.objects.all()\n self.assertEqual(daily_usages.count(), 1)\n self.assertEqual(daily_usages[0].pricing_device, self.device)\n self.assertEqual(daily_usages[0].pricing_venture, self.venture)\n self.assertEqual(daily_usages[0].type, usages['virtual_cores'])\n self.assertEqual(daily_usages[0].value, 1)\n\n def test_update_when_device_id_is_none(self):\n update({}, self._get_usages(), date.today())\n\n self.assertItemsEqual(Device.objects.all(), [self.device])\n\n def test_update_when_venture_id_is_none(self):\n data = {\n 'device_id': 1,\n 'virtual_cores': 1,\n 'virtual_disk': 1,\n 'virtual_memory': 1,\n }\n update(data, self._get_usages(), date.today())\n\n daily_usages = DailyUsage.objects.all()\n self.assertEqual(daily_usages.count(), 0)\n for daily_usage in daily_usages:\n self.assertEqual(daily_usage.pricing_venture, None)\n\n def test_update(self):\n data = {\n 'device_id': 1,\n 'venture_id': 1,\n 'virtual_cores': 1,\n 'virtual_disk': 1,\n 'virtual_memory': 1,\n }\n update(data, self._get_usages(), date.today())\n\n daily_usages = DailyUsage.objects.all()\n self.assertEqual(daily_usages.count(), 3)\n for daily_usage in daily_usages:\n self.assertEqual(daily_usage.pricing_venture.venture_id, 1)\n","sub_path":"src/ralph_pricing/tests/plugins/collect_plugins/test_virtual.py","file_name":"test_virtual.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"239686916","text":"import random, string, itertools\nfrom print_handler import print_func\nimport string\n\nALPHABET_FIRST = string.ascii_lowercase\nALPHABET_LAST = ALPHABET_FIRST + string.digits\nALPHABET = ALPHABET_LAST + '_'\n\ndef random_addresses():\n while True:\n len_link = random.randint(5, 32)\n link = random.choices(ALPHABET_FIRST)\n link += random.choices(ALPHABET, k=len_link - 2)\n link += random.choices(ALPHABET_LAST)\n yield ''.join(link)\n\n\ndef linear_addresses(seed, first=True):\n if len(seed) == 1:\n for letter in letters(ALPHABET_LAST, seed[0]):\n yield letter\n else:\n if first:\n alphabet = ALPHABET_FIRST\n else:\n alphabet = ALPHABET\n \n for link in linear_addresses(seed[1:], False):\n yield seed[0] + link\n \n new_seed = 'a' * (len(seed) - 1)\n for letter in letters(alphabet, seed[0], 1):\n for link in linear_addresses(new_seed, False):\n yield letter + link\n\n\ndef letters(alphabet, start='a', shift=0):\n position = alphabet.index(start)\n for letter in alphabet[position+shift:]:\n yield letter\n\n# def mutation_address_generator(link):\n# mutated_array = []\n# replacements = \"\"\"\n# a=4\n# b=6\n# e=3\n# f=8\n# g=9\n# i=1\n# l=1\n# o=0\n# s=5\n# t=7\n# z=2\n# \"\"\"\n# try:\n# open('mutated', 'r').read()\n#\n# except FileNotFoundError:\n# mutated_replacement_set = set()\n# mutated_array = []\n# link = [link]\n# mutations = ['_', 'xxx']\n# for number_of_connected_mutations in range(1, len(mutations) + 2):\n# for mutation_tuple in itertools.permutations(link + mutations, number_of_connected_mutations):\n# mutation_word = ''.join(mutation_tuple)\n# if link[0] in mutation_word or link[0] == mutation_word:\n# if len(mutation_word) > 4 and len(mutation_word) < 33:\n# if mutation_word[0] not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_'] and \\\n# mutation_word[-1] not in ['_']:\n# mutated_replacement_set.add(mutation_word)\n#\n# d = {c: [c] for c in string.printable}\n# for line in replacements.strip().split(\"\\n\"):\n# c, replacement = line.split(\"=\")\n# d[c].append(replacement)\n#\n# for link in mutated_replacement_set:\n# for letters in itertools.product(*[d[c] for c in link]):\n# mutated_address = \"\".join(letters)\n# if mutated_address[0] not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_']:\n# mutated_array.append(mutated_address)\n# return mutated_array\n","sub_path":"telegram_parser/link_generator.py","file_name":"link_generator.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"301277115","text":"def eval(x, y, sign):\n if sign == '+':\n result = x + y\n elif sign == '-':\n result = x - y\n elif sign == '*':\n result = x * y\n elif sign == '/':\n result = x / y\n return result\n\ndef generate_expression():\n x = randint(0, 10)\n y = randint(0, 10)\n sign = choice(['+', '-', '*', '/'])\n error = randint(-1, 1)\n result = eval(x, y, sign) + error\n return [x, y, sign, result]\n\ndef check_result(x, y, sign, result, answer):\n expected_result = eval(x, y, sign)\n if answer.lower() == 'y':\n if result == expected_result:\n return True\n else:\n return False\n else:\n if result != expected_result:\n return True\n else:\n return False\n\nfrom random import randint, choice\n\nx, y, sign, result = generate_expression()\n\nprint(\"* \" * 10)\nprint(\"{0} {3} {1} = {2}\".format(x, y, result, sign))\nprint(\"* \" * 10)\nanswer = input(\"(Y/N)?\")\nif check_result(x, y, sign, result, answer):\n print(\"Yay\")\nelse:\n print(\"Wrong :(\")\n","sub_path":"functions/f_math_2.py","file_name":"f_math_2.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"78116143","text":"#initialization code (to be ran once)\nfrom datetime import datetime\nfrom picamera import PiCamera\ncamera = PiCamera()\ncamera.resolution = (1920, 1080)\n\nimport time\nimport RPi.GPIO as GPIO\nimport numpy as np\nGPIO.setmode(GPIO.BCM)\n\nbuttonRed = 24\nbuttonYellow = 25\nbuttonGreen = 26\nbuttonBlue = 27\n\nGPIO.setup(buttonRed, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\nGPIO.setup(buttonYellow, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\nGPIO.setup(buttonGreen, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\nGPIO.setup(buttonBlue, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\n\nimport pigpio\nimport math\npi = pigpio.pi(port = 8887)\n# Command for linux console for pigpio daemon\n#sudo pigpiod -p 8887\n\nbuzPin=18 # Piezoelectric buzzer\nTRIG = 20 # Trigger pin on HC-SR04\nECHO = 21 # Echo pin on HC-SR04. This is connected to a voltage divider to reduce 5 volt output to 3.3 v\n\nGPIO.setup(TRIG,GPIO.OUT)\nGPIO.setup(ECHO,GPIO.IN)\n\nclass Button:\n def __init__(self):\n self.pinArray = np.array([2,4,3,1]) # The true passcode\n self.userArray = np.array([]) # The inputted passcode\n self.count = 1 # Represents how many numbers are added to the user array\n def button_press(self):\n if GPIO.input(buttonRed) == True:\n time.sleep(0.5)\n self.userArray = np.append(self.userArray,1)\n self.count+=1\n if GPIO.input(buttonYellow) == True:\n time.sleep(0.5)\n self.userArray = np.append(self.userArray,2)\n self.count+=1\n if GPIO.input(buttonGreen) == True:\n time.sleep(0.5)\n self.userArray = np.append(self.userArray,3)\n self.count+=1\n if GPIO.input(buttonBlue) == True:\n time.sleep(0.5)\n self.userArray = np.append(self.userArray,4)\n self.count+=1 \n def full_length(self): # Checks if the user array is as long as the real passcode\n return self.count > len(self.pinArray)\n def check_pass(self): # Checks if the inputted passcode is correct\n self.index=0\n self.match=True # If the passcodes match\n for i in self.userArray:\n if i != self.pinArray[index]:\n self.match = False\n break\n if i == self.pinArray[index]:\n self.index += 1\n return self.match\n\n\ndef button():\n pinArray = np.array([2,4,3,1]) # The true passcode\n userArray = np.array([]) # The inputted passcode\n x = 1 # Represents how many numbers are added to the user array\n boolean = True # If the passcodes match\n while x <= len(pinArray): # While the user passcode is smaller than the real passcode\n while True:\n if GPIO.input(buttonRed) == True:\n time.sleep(0.5)\n userArray = np.append(userArray,1)\n x+=1\n break\n if GPIO.input(buttonYellow) == True:\n time.sleep(0.5)\n userArray = np.append(userArray,2)\n x+=1\n break\n if GPIO.input(buttonGreen) == True:\n time.sleep(0.5)\n userArray = np.append(userArray,3)\n x+=1\n break\n if GPIO.input(buttonBlue) == True:\n time.sleep(0.5)\n userArray = np.append(userArray,4)\n x+=1\n break\n continue\n\n index = 0\n for i in userArray:\n if i != pinArray[index]:\n boolean = False\n break\n if i == pinArray[index]:\n index += 1\n continue\n return boolean # Return whether the passcode is right\n\ndef siren1(pos): # The siren when you first trip the sensor\n return 440*math.sin(pos)+440\n\ndef siren2(pos): # A higher pitched siren for when you input the wrong passcode\n return 300*math.sin(pos)+740\n\ndef pulseIn(): # Returns the length of a pulse from the ultrasonic sensor\n while True:\n GPIO.output(TRIG, False)\n time.sleep(.000005)\n GPIO.output(TRIG, True) # Sending out a trigger pulse for 10 microseconds\n time.sleep(.00001)\n GPIO.output(TRIG, False)\n pulse_start = time.time()\n pulse_end = time.time()\n now = time.time()\n while GPIO.input(ECHO)==0 and time.time()-now<.1: # If we start sending out a pulse or if the command times out\n pulse_start = time.time()\n now = time.time()\n while GPIO.input(ECHO)==1 and time.time()-now<.1: # If we receive the pulse or if the command times out\n pulse_end = time.time()\n return pulse_end-pulse_start\n\n\ntry:\n time.sleep(2) # Waiting for the ultrasonic sensor to warm up\n while True:\n button_obj=Button()\n SecurityLog = open(\"IntrusionLog.txt\", \"a\") # A text file that saves a log of when the sensor is triggered\n sirenPos=0\n x = 50 #50 cm threshold distance\n flag = False\n distance = pulseIn() * 17150 # 17150 is half the speed of sound in cm/s to account for the return trip\n if (distance <= x): # Someone triggered the sensor\n flag = True\n dateTime = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')\n fileString = str(datetime.today().strftime('%Y-%m-%d-%H:%M:%S')) + '.jpg'\n camera.capture(fileString) # Takes the photo and stores it\n dataWrite = str(dateTime) #+ \" \" + fileString + \" \" + \"\\n\"\n SecurityLog.write(dataWrite)\n if (flag == True):\n while True:\n pi.hardware_PWM(buzPin,int(siren1(sirenPos)), int(.5e6))\n sirenPos+=.01\n button_obj.button_press()\n if (button_obj.full_length()):\n if(button_obj.check_pass()): # Passcode is correct\n pi.hardware_PWM(buzPin, 0, 0)\n SecurityLog.write(\"False Alarm! \\n\")\n break\n else: # Passcode is not correct\n while True: # The \"evil loop\" you cannot get out of it without an interrupt and the siren gets higher pitched\n pi.hardware_PWM(buzPin, int(siren2(sirenPos)), int(.5e6))\n time.sleep(.05)\n sirenPos+=.05\n \n SecurityLog.close()\nexcept(KeyboardInterrupt, SystemExit):\n print(\"System Disabled\")\n \nfinally:\n pi.hardware_PWM(buzPin, 0, 0)\n SecurityLog.close()\n GPIO.cleanup()\n \n \n","sub_path":"SecuritySystemCodeObject.py","file_name":"SecuritySystemCodeObject.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"470848229","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright 2015 Red Hat, Inc.\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\nfrom __future__ import unicode_literals\nimport json\n\n\ndef test_prettytable_output(runner):\n result = runner.invoke(['test-create', '--name', 'foo'])\n test = json.loads(result.output)['test']\n\n result = runner.invoke(['--format', 'table', 'test-show', '--id',\n test['id']])\n\n output = result.output.split('\\n')\n # NOTE(spredzy) : The expected output for a table format looks like the\n # following :\n #\n # +------------\n # | id | name\n # +------------\n # | id1 | name1\n # | id2 | name2\n # | id3 | name3\n # +------------\n #\n # The header variable below represents the header data, when more than one\n # space is located between the string and the '|' space number is shrink to\n # one ( this is what ' '.join(string.split()) does\n #\n # The data variable below represents the actual data, when more than one\n # space is located between the string and the '|' space number is shrink to\n # one ( this is what ' '.join(string.split()) does\n header = ' '.join(output[1].split())\n data = ' '.join(output[3].split())\n\n expected_data = (test['id'], test['name'], test['etag'],\n test['created_at'], test['updated_at'])\n\n assert header == '| id | name | data | etag | created_at | updated_at |'\n\n assert data == '| %s | %s | {} | %s | %s | %s |' % expected_data\n\n\ndef test_list(runner):\n runner.invoke(['test-create', '--name', 'foo'])\n runner.invoke(['test-create', '--name', 'bar'])\n result = runner.invoke(['test-list'])\n tests = json.loads(result.output)['tests']\n assert len(tests) == 2\n assert tests[0]['name'] == 'foo'\n assert tests[1]['name'] == 'bar'\n\n\ndef test_create(runner):\n result = runner.invoke(['test-create', '--name', 'foo'])\n test = json.loads(result.output)['test']\n assert test['name'] == 'foo'\n\n\ndef test_update(runner):\n result = runner.invoke(['test-create', '--name', 'foo'])\n test = json.loads(result.output)['test']\n\n result = runner.invoke(['test-update', '--id', test['id'],\n '--etag', test['etag'], '--name', 'bar'])\n result = json.loads(result.output)\n\n assert result['message'] == 'Test updated.'\n assert result['name'] == 'bar'\n\n\ndef test_delete(runner):\n result = runner.invoke(['test-create', '--name', 'foo'])\n test = json.loads(result.output)['test']\n\n result = runner.invoke(['test-delete', '--id', test['id'],\n '--etag', test['etag']])\n result = json.loads(result.output)\n\n assert result['message'] == 'Test deleted.'\n\n\ndef test_show(runner):\n result = runner.invoke(['test-create', '--name', 'foo'])\n test = json.loads(result.output)['test']\n\n result = runner.invoke(['test-show', '--id', test['id']])\n test = json.loads(result.output)['test']\n\n assert test['name'] == 'foo'\n","sub_path":"dciclient/v1/tests/shell_commands/test_test.py","file_name":"test_test.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"542035284","text":"\nimport urllib.request\nfrom os import walk\nimport hashlib\nimport os\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\n# \"https://urlhaus.abuse.ch/downloads/text\" sitesindeki tum dosyalari indirir.\n\n\nclass UrlHaus:\n def __init__(self, urlPath,dirname):\n self.urlPath = urlPath\n self.allUrlLists =\"\"\n self.dirname=dirname\n self.alreadydownloadedlist=[]\n\n def download(self, link, filename):\n print(bcolors.BOLD + bcolors.WARNING + \"\\nLink :\", end=\" \")\n print(bcolors.OKBLUE + str(link))\n exestr = link[len(link)-4:len(link)-1]\n\n if exestr == \"exe\":\n try:\n urllib.request.urlretrieve(link, filename.rstrip('\\r'))\n isdonwloaded, md5=self.rename_with_md5(filename.rstrip('\\r'))\n\n self.print_status(\"MD5 :\", \" \" + md5, bcolors.OKBLUE)\n if isdonwloaded == -1:\n self.print_status(\"Status:\", \"This file is already downloaded!\", bcolors.WARNING)\n else:\n self.print_status(\"Status:\", \"Successfully downloaded!\", bcolors.OKBLUE)\n except:\n self.print_status(\"Status:\", \"Error link!\", bcolors.FAIL)\n else:\n self.print_status(\"Status:\", \"Not exe fıle!\", bcolors.FAIL)\n\n\n def print_status(self, status, message, color):\n print(bcolors.BOLD + bcolors.WARNING + status, end=\" \")\n print(color + message)\n\n def get_all_links(self):\n with urllib.request.urlopen(self.urlPath) as response:\n data = response.read()\n print(bcolors.BOLD + bcolors.WARNING +\"\\nGetting all links\\n\")\n httpString = \"http\"\n self.allUrlLists = list()\n allData = data.decode('utf8').split('\\n')\n\n for link in allData:\n if httpString in link:\n link.replace(\"\\n\", \"\")\n self.allUrlLists.append(link)\n\n def print_lists(self, urllist):\n for link in urllist:\n print(bcolors.OKBLUE + link)\n\n def download_all_files(self):\n self.get_all_links()\n self.print_lists(self.allUrlLists)\n self.alreadydownloadedlist = self.get_already_downloaded_list()\n print(bcolors.BOLD + bcolors.WARNING +\"\\nDownloading files\\n\")\n\n for url in self.allUrlLists:\n file = self.dirname + \"/\" + url[7:len(url)].replace(\"/\", \"-\")\n self.download(url, file)\n\n def get_already_downloaded_list(self):\n filelist=[]\n for (dirpath, dirnames, filenames) in walk(self.dirname):\n filelist.extend(filenames)\n break\n return filelist\n\n def is_already_downloaded(self, link):\n if link in self.alreadydownloadedlist:\n return -1\n else:\n return 0\n\n def rename_with_md5(self, file):\n with open(file, 'rb') as file_to_check:\n data = file_to_check.read()\n md5_returned = hashlib.md5(data).hexdigest()\n\n isdownloaded = self.is_already_downloaded(md5_returned + '.exe')\n\n if isdownloaded == -1:\n os.remove(file)\n else:\n os.rename(file, self.dirname + \"/\" + md5_returned + '.exe')\n newfile=\"LINK => \"+file[len(self.dirname) + 1:] + \" *** MD5 => \" + md5_returned + \"\\n\"\n with open(\"../UrlHausDownloadedList.txt\", \"a\") as myfile:\n myfile.write(newfile)\n return isdownloaded, md5_returned\n\n\n\nurlhaus = UrlHaus(\"https://urlhaus.abuse.ch/downloads/text\", \"../exetemp\")\nurlhaus.download_all_files()\n\n","sub_path":"Project/MalwareCrawler/Download.py","file_name":"Download.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"157245573","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# ventanas_Tkinter_curso2.py\n# \n\n\nfrom Tkinter import Tk, Label, Button\n\nclass MyFirstGUI:\n def __init__(self, master):\n self.master = master\n master.title(\"Una simple GUI\")\n\n self.label = Label(master, text=\"Esta es nuestra primera GUI!\")\n self.label.pack()\n\n self.greet_button = Button(master, text=\"Saluda\", command=self.greet)\n self.greet_button.pack()\n\n self.close_button = Button(master, text=\"Cierra\", command=master.quit)\n self.close_button.pack()\n\n def greet(self):\n print(\"¡Hola curso Darwin Eventur Python!\")\n\nroot = Tk()\nmy_gui = MyFirstGUI(root)\nroot.mainloop()\n","sub_path":"Ejemplos_TKinter/ventanas_Tkinter_curso2.py","file_name":"ventanas_Tkinter_curso2.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"163980600","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport sys\nimport argparse as arg\nimport csv\nimport os\n\ntrain_filepath = sys.argv[1]\n#train_filepath = \"../hw8/train.csv\"\n\nprint(\"training data: \", train_filepath)\n# print(\"model_path: \", args.model_path)\n\n\n# In[2]:\n\n\n######## Read data from CSV ########\n\ndf = pd.read_csv(train_filepath)\ntrain_x = np.array(df['feature'].str.split(\" \").values.tolist()).reshape(-1, 48, 48, 1).astype(np.float32)\ntrain_y = pd.get_dummies(df['label']).values\n# print(np.fromstring(train_x[0]), dtype=int, sep=' ')\nprint(\"train_x: \", train_x.shape)\nprint(\"train_y: \", train_y.shape)\nprint(train_y)\n\n\n# In[3]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain_x, val_x, train_y, val_y = train_test_split(train_x, train_y, test_size=0.2)\n\nprint(\"train_x: \", train_x.shape)\nprint(\"train_y: \", train_y.shape)\nprint(\"val_x: \", val_x.shape)\nprint(\"val_y: \", val_y.shape)\n\n\n# In[4]:\n\n\n######## Constants ########\nbatch_size = 32\nepochs = 600\n\n\n# In[5]:\n\n\n######## Training ########\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, SeparableConv2D, MaxPooling2D, Activation, BatchNormalization, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=16, kernel_size=(5, 5), padding=\"same\", input_shape=(48,48,1), activation='relu'))\nmodel.add(BatchNormalization(axis=-1, momentum=0.5))\n\nmodel.add(SeparableConv2D(filters=32, kernel_size=(3, 3), padding=\"same\", activation='relu'))\nmodel.add(BatchNormalization(axis=-1, momentum=0.5))\nmodel.add(Dropout(0.2))\n\nmodel.add(SeparableConv2D(filters=64, kernel_size=(3, 3), padding=\"same\", activation='relu'))\nmodel.add(BatchNormalization(axis=-1, momentum=0.5))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.1))\n\nmodel.add(SeparableConv2D(filters=128, kernel_size=(3, 3), padding=\"same\", activation='relu'))\nmodel.add(BatchNormalization(axis=-1, momentum=0.5))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.1))\n\nmodel.add(SeparableConv2D(filters=128, kernel_size=(3, 3), padding=\"same\", activation='relu'))\nmodel.add(BatchNormalization(axis=-1, momentum=0.5))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n# model.add(SeparableConv2D(filters=512, kernel_size=(3, 3), padding=\"same\", activation='relu'))\n# model.add(BatchNormalization(axis=-1, momentum=0.5))\n# model.add(MaxPooling2D(pool_size=(2,2)))\n# model.add(Dropout(0.2))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(7, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\n# In[6]:\n\n\n# early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=2)\nmodels_filepath = \"less/16fiveto128_{epoch:03d}_A{acc:.3f}_L{loss:.3f}_VA{val_acc:.3f}_VL{val_loss:.3}.hdf5\"\nmodel_checkpoint = ModelCheckpoint(models_filepath, monitor='loss', verbose=0, save_best_only=False, save_weights_only=True, mode='auto', period=5)\n\n\n# In[7]:\n\n\ndatagen = ImageDataGenerator(rotation_range=20.0,width_shift_range=0.1,height_shift_range=0.1,zoom_range=[0.9, 1.1], horizontal_flip=True)\ndatagen.fit(train_x)\n\nmodel.fit_generator(datagen.flow(train_x, train_y, batch_size=batch_size), validation_data=(val_x, val_y), steps_per_epoch=train_x.shape[0]/batch_size*3, epochs=epochs, callbacks=[model_checkpoint])\n\n\n# In[ ]:\nweights = model.get_weights()\nprint(len(weights))\ncompressed_weights = []\nfor i in range(len(weights)):\n if i > 27:\n compressed_weights.append(weights[i].astype(np.float16))\n else:\n compressed_weights.append(weights[i])\n\n\n# In[27]:\n\n\nnp.savez_compressed(\"part_compressed_w.npz\", compressed_w = np.array(compressed_weights))\n\n\n\n","sub_path":"hw8/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"292624041","text":"'''\r\n 老手机:\r\n 打电话:手机号,彩铃\r\n 新手机:\r\n 打电话:手机号,彩铃,归属地,大头贴,录音\r\n'''\r\nimport time\r\n# class OldPhone:\r\n# phoneNumber = \"\"\r\n# voice = \"\"\r\n#\r\n# def call(self,number):\r\n# print(self.phoneNumber,\"正在打电话,打给:\",number,\"正在响铃:\",self.voice)\r\n# for i in range(8):\r\n# print(\".\",end=\"\")\r\n# time.sleep(1)\r\n# print(\"对方已接通!!\")\r\n#\r\n# class NewPhone(OldPhone):\r\n# # 归属地,大头贴,录音\r\n# address = \"\"\r\n# picture = \"\"\r\n# mic = False\r\n#\r\n# def call(self,number):\r\n# # 2个属性由老手机代码显示\r\n# super().call(number)\r\n#\r\n# # 3个新属性由新手机自己显示\r\n# self.mic = True\r\n# print(\"本机归属地:\",self.address,\",对方大头贴为:\",self.picture,\",已经开启了录音功能!\")\r\n# for i in range(8):\r\n# print(\".\",end=\"\")\r\n# time.sleep(1)\r\n# print(\"本次通话完成[5:36]!\")\r\n\r\n\r\n# phone = NewPhone()\r\n# phone.phoneNumber = \"13552648187\"\r\n# phone.voice = \"江南style\"\r\n# phone.picture = \"野猪佩奇\"\r\n# phone.address = \"北京移动\"\r\n#\r\n# phone.call(\"13379854676\")\r\n\r\n\r\n#\r\n# 按要求定义类\r\n# 考查知识点:super关键字的使用和继承中方法的调用\r\n# 要求:\r\n# 1、定义老手机类,有品牌属性,且属性私有化,提供相应的getXxx与setXxx方法,提供无返回值的带一个Str类型参数的打电话的方法,内容为:“正在给xxx打电话...”\r\n# 2、定义新手机类,继承老手机类,重写父类的打电话的方法,内容为2句话:“语音拨号中...”、“正在给xxx打电话...”要求打印“正在给xxx打电话...”这一句调用父类的方法实现,不能在子类的方法中直接打印;提供无返回值的无参数的手机介绍的方法,内容为:“品牌为:xxx的手机很好用...”\r\n# 3、定义测试类,创建新手机对象,并使用该对象,对父类中的品牌属性赋值;\r\n# 4、使用新手机对象调用手机介绍的方法;\r\n# 5、使用新手机对象调用打电话的方法;\r\nclass oderP:\r\n __brand = \"\"\r\n def setBrand(self,brand):\r\n self.__brand=brand\r\n def getBrand(self):\r\n return self.__brand\r\n\r\n def call(self, number):\r\n print(\"正在打给:\",number)\r\n for i in range(8):\r\n print(\".\",end=\"\")\r\n time.sleep(1)\r\n print(\"对方已接通!!\")\r\n print(\"品牌为\",self.__brand,\"的手机真好用\")\r\n\r\nclass newP(oderP):\r\n def call(self,number):\r\n super().call(number)\r\n\r\n\r\ni=newP()\r\ni.setBrand=\"小米\"\r\ni.call(\"13872031732\")\r\n\r\n\r\n# 题目一:\r\n# 考查知识点:继承的传递性\r\n# 按要求定义类\r\n# 要求:\r\n# 1、定义厨师类,有姓名和年龄的属性,且属性私有化,提供相应的getXxx与setXxx方法,提供无返回值的无参数的蒸饭方法;\r\n# 2、定义厨师的子类,该类中要求只能写一个无返回值的无参数的炒菜的方法,其他的方法不能写;\r\n# 3、定义厨师的子类的子类,重写所有父类的方法,每个方法的内容只需打印一句话描述方法的功能即可;(蒸饭,炒菜)\r\n# 4、定义测试类,创建厨师的子类的子类(厨师的孙子类)对象,使用该对象,对厨师类中的姓名和年龄属性赋值,并获取赋值后的属性值打印到控制台上;\r\n# 5、使用厨师的孙子类对象调用该对象除了getXxx与setXxx以外的其他方法;\r\n\r\n# class cook:\r\n# __name=\"\"\r\n# __age=\"\"\r\n# def setName(self,name):\r\n# self.__name=name\r\n# def getName(self):\r\n# return self.__name\r\n# def setAge(self,age):\r\n# self.__age=age\r\n# def getAge(self):\r\n# return self.__age\r\n# def stir_fry(self):\r\n# print(\"我是一名厨师,叫\",self.__name,\"年龄是\",self.__age,\"我正在炒菜\")\r\n# class cooks(cook):\r\n# def stir_fry(self):\r\n# super().stir_fry()\r\n# class cookses(cooks):\r\n# def steamed_rice():\r\n#\r\n# print(\"我是一名厨师,叫\",self.__name,\"年龄是\",self.__age,\"我正在蒸饭\")\r\n#\r\n# b=cooks()\r\n# b.setName(\"李刚\")\r\n# b.setAge(45)\r\n# b.stir_fry()\r\n#\r\n# d=cookses()\r\n# d.steamed_rice()\r\n\r\n\r\n\r\n\r\n\r\n#\r\n# 请编程\r\n# i.人:年龄,性别,姓名。\r\n# ii.现在有个工种,工人:年龄,性别,姓名 。行为:干活。请用继承的角度来实现该类。\r\n# iii.现在有学生这个工种,学生:年龄,性别,姓名,学号。行为:学习,唱歌。请结合上面的几个题目用继承的角度来实现。\r\n#\r\nclass people:\r\n age=\"\"\r\n sex=\"\"\r\n name=\"\"\r\nclass type_of_work(people):\r\n def type_work(self):\r\n print(\"一个叫\",self.name,\"性别为\",self.sex,\"性,年龄为\",self.age,\"岁的工人在干活\")\r\nclass student(people):\r\n student_id=None\r\n def doing(self,study,song):\r\n print(\"一个叫\",self.name,\"性别为\",self.sex,\"性,年龄为\",self.age,\"岁,学号为\",self.student_id,\"的学生在\",study,song)\r\n\r\na=type_of_work()\r\na.name=\"李刚\"\r\na.sex=\"男\"\r\na.age=81\r\na.type_work()\r\n\r\nc=student()\r\nc.name=\"小明\"\r\nc.sex=\"男\"\r\nc.age=19\r\nc.student_id=\"1655646\"\r\nc.doing(\"学习\",\"唱歌\")\r\n","sub_path":"手机.py","file_name":"手机.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"147618795","text":"def din(a):\n val = int(a)\n notas = [200, 100, 50, 20, 10, 5, 2, 1]\n notas.sort()\n notas.reverse()\n numNotas = []\n for i in notas:\n numNotas.append(val/i)\n val %= i\n for i in range(len(notas)):\n print(\"Notas de %d:%d\" % (notas[i], numNotas[i]))\n return a\nval = int(input(\"Digite o valor: \"))\nprint(din(val))","sub_path":"Contagem-cedulas.py","file_name":"Contagem-cedulas.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"253262616","text":"import numpy as np\nimport tkinter as tk\nimport PIL.Image\nimport PIL.ImageTk\nimport matplotlib.cm as cm\n\n\nclass RoiFinder(tk.Frame):\n def __init__(self, data, *args, **kwargs):\n tk.Frame.__init__(self, *args, **kwargs)\n\n\n\n def setup(self, data):\n self._data = self.gamma_correction(1.0*data / np.max(data), 0.8)\n sh = self._data.shape\n self.zoom_level = 8\n\n cframe = tk.Frame(self)\n self.c = tk.Canvas(cframe, bg='white', width=512, height=512)\n self.cz = tk.Canvas(cframe, bg='white', width=512, height=512)\n #self.im=PIL.Image.frombytes('L', (data.shape[1],data.shape[0]), data.astype('b').tostring())\n print(np.uint8(cm.viridis(self._data)*255))\n self.im = PIL.Image.fromarray(np.uint8(cm.viridis(self._data)*255))\n self.imz = PIL.Image.fromarray(np.uint8(cm.viridis(self._data)*255)).resize((sh[1]*self.zoom_level, sh[0]*self.zoom_level))\n self.imzz = self.imz.crop(box=(0,0,100,100)).resize((512,512))\n self.photo = PIL.ImageTk.PhotoImage(image=self.im)\n self.photoz = PIL.ImageTk.PhotoImage(image=self.imz)\n self.c.create_image(0,0,image=self.photo,anchor=tk.NW)\n self.z = self.cz.create_image(256,256,image=self.photoz,anchor=tk.NW)\n\n self.c.pack(side='left')\n self.cz.pack(side='left')\n cframe.pack()\n self.circle = 0\n self.zcircle = 0\n\n self.old_x = None\n self.old_y = None\n self.line_width = 1\n self.c.bind('', self.paint)\n self.cz.bind('', self.paint)\n self.c.bind('', self.newRoi)\n self.c.bind('', self.reset)\n self.c.bind('', lambda event : self.on_mousewheel(5))\n self.c.bind('', self.on_windows_mousewheel)\n self.c.bind('', lambda event : self.on_mousewheel(-5))\n self.c.bind(\"\", self.update_zoom_window)\n self.segments = []\n self.frame_button = tk.Frame(self)\n self.button_prev = tk.Button(self.frame_button, text=\"Back\")\n self.button_prev.pack(side = \"left\", fill='x', expand=True)\n self.button_next = tk.Button(self.frame_button, text=\"Next\")\n self.button_next.pack(side = \"left\", fill='x', expand=True)\n self.frame_button.pack(expand=True, fill=\"x\")\n\n\n\n\n def update_zoom_window(self, event):\n x,y = event.x, event.y\n fac = self.line_width\n s = 5*fac\n if(s >= min(self._data.shape[0],self._data.shape[1])):\n s = min(self._data.shape[0],self._data.shape[1]) - 1\n if(s < 6):\n s = 6\n\n x0 = x - s\n x1 = x + s\n y0 = y - s\n y1 = y + s\n\n # if(x0 < 0):\n # x0 = 0\n # x1 = s*2\n # if(y0 < 0):\n # y0 = 0\n # y1 = s*2\n # if(x1 >= self._data.shape[0]):\n # x1 = self._data.shape[0]-1\n # x0 = self._data.shape[0]-s*2\n # if(y1 >= self._data.shape[1]):\n # y1 = self._data.shape[1]-1\n # y0 = self._data.shape[1]-s*2\n\n # self.imzz = self.imz.crop(box=(x0,y0,x1,y1)).resize((512,512))\n # self.cz.delete(self.z)\n # self.photoz = PIL.ImageTk.PhotoImage(image=self.imzz)\n # self.z = self.cz.create_image(0,0,image=self.photoz,anchor=tk.NW)\n self.cz.scan_dragto(-x,-y, gain = self.zoom_level)\n self.redraw_cursors(x,y)\n\n\n\n def on_mousewheel(self, event):\n self.line_width += event\n if self.line_width < 2:\n self.line_width = 2\n if self.line_width > 50:\n self.line_width = 50\n\n def on_windows_mousewheel(self, event):\n self.line_width += event.delta / 120\n if self.line_width < 2:\n self.line_width = 2\n if self.line_width > 50:\n self.line_width = 50\n self.redraw_cursors(event.x,event.y)\n\n def newRoi(self, event):\n print(\"yellow!\")\n for s in self.segments:\n self.c.itemconfig(s, fill= \"green\")\n\n def setData(self, image_data):\n print(\"\")\n def getRois(self):\n print(\"\")\n\n def motion(self, event = None):\n # mouse cursor position in canvas coord\n x0 = event.x\n y0 = event.y\n\n\n # compute offset from center of zoom canvas\n x1 = 2*256 + 256 - x0\n y1 = 256 - y0\n\n\n print(x1)\n print(y1)\n\n # move cursor\n #self.c.event_generate('', warp=True, x=x1, y=y1)\n\n def paint(self, event):\n\n # position on canvas\n x0 = event.x\n y0 = event.y\n\n # compute offset from canvas center\n x1 = 256 - x0\n y1 = 256 - y0\n\n # only shift in x\n shift = self.cz.winfo_rootx() - self.c.winfo_rootx()\n\n xwin = self.c.winfo_x() + x1\n ywin = self.c.winfo_y() + y1\n print(self.c.canvasx(500))\n print(self.cz.canvasx(500))\n print(ywin)\n\n # compute offset between canvas centers\n #self.c.canvasx(xwin_shifted)\n\n #print(x1)\n\n # if self.old_x and self.old_y:\n # x = self.old_x + (event.x - self.old_x)\n # y = self.old_y + (event.y - self.old_y)\n # print( (event.x - self.old_x)/2)\n # print( (event.x - self.old_x))\n #\n #\n #\n #\n # print(x)\n # else:\n # x = event.x\n # y = event.y\n # x0 = self.cz.canvasx(256)\n # y0 = self.cz.canvasy(256)\n #\n # if self.old_x and self.old_y:\n # a = self.c.create_line(self.old_x, self.old_y, x, y,\n # width=self.line_width, fill='red',\n # capstyle=tk.ROUND, smooth=tk.TRUE, splinesteps=36,\n # stipple = 'gray25')\n # self.segments.append(a)\n #\n # b = self.cz.create_line(self.old_x*self.zoom_level +256,\n # self.old_y*self.zoom_level+256, x*self.zoom_level+256,\n # y*self.zoom_level+256, width=self.line_width*self.zoom_level,\n # fill='red', capstyle=tk.ROUND, smooth=tk.TRUE, splinesteps=36,\n # stipple = 'gray25')\n #\n # self.redraw_cursors(x,y)\n #\n # self.old_x = x\n # self.old_y = y\n # print(\"paint!\")\n\n def redraw_cursors(self, x, y):\n radius = self.line_width / 2\n x_max = x + radius\n x_min = x - radius\n y_max = y + radius\n y_min = y - radius\n\n\n x2_max = (x + self.line_width / 2)* self.zoom_level + 256\n x2_min = (x - self.line_width / 2)* self.zoom_level + 256\n y2_max = (y + self.line_width / 2)* self.zoom_level+ 256\n y2_min = (y - self.line_width / 2)* self.zoom_level + 256\n\n self.c.delete(self.circle)\n self.cz.delete(self.zcircle)\n self.circle = self.c.create_oval(x_max, y_max, x_min, y_min, outline=\"red\")\n self.zcircle = self.cz.create_oval(x2_max, y2_max, x2_min, y2_min, outline=\"red\")\n\n def gamma_correction(self, array, gamma):\n return(np.power(array, gamma))\n\n def reset(self, event):\n self.old_x, self.old_y = None, None\n","sub_path":"roifinder.py","file_name":"roifinder.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"80110032","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n# ***********************************************************************************************************\n#\n# Starfish Storage Corporation (\"COMPANY\") CONFIDENTIAL\n# Unpublished Copyright (c) 2011-2018 Starfish Storage Corporation, All Rights Reserved.\n#\n# NOTICE: All information contained herein is, and remains the property of COMPANY. The intellectual and\n# technical concepts contained herein are proprietary to COMPANY and may be covered by U.S. and Foreign\n# Patents, patents in process, and are protected by trade secret or copyright law. Dissemination of this\n# information or reproduction of this material is strictly forbidden unless prior written permission is\n# obtained from COMPANY. Access to the source code contained herein is hereby forbidden to anyone except\n# current COMPANY employees, managers or contractors who have executed Confidentiality and Non-disclosure\n# agreements explicitly covering such access.\n#\n# ANY REPRODUCTION, COPYING, MODIFICATION, DISTRIBUTION, PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR\n# THROUGH USE OF THIS SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF COMPANY IS STRICTLY PROHIBITED,\n# AND IN VIOLATION OF APPLICABLE LAWS AND INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE\n# CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS TO REPRODUCE, DISCLOSE OR DISTRIBUTE\n# ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.\n#\n# FOR U.S. GOVERNMENT CUSTOMERS REGARDING THIS DOCUMENTATION/SOFTWARE\n# These notices shall be marked on any reproduction of this data, in whole or in part.\n# NOTICE: Notwithstanding any other lease or license that may pertain to, or accompany the delivery of,\n# this computer software, the rights of the Government regarding its use, reproduction and disclosure are\n# as set forth in Section 52.227-19 of the FARS Computer Software-Restricted Rights clause.\n# RESTRICTED RIGHTS NOTICE: Use, duplication, or disclosure by the Government is subject to the\n# restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer\n# Software clause at DFARS 52.227-7013.\n#\n# ***********************************************************************************************************\n\"\"\"\n Part of the distribution\n\n Relevant Lustre CLI commands to manage the changelog\n Class\n AdmCmds lfs commands that can return changelog events\n lctl commands that register, inspect changelog, report on users, etc.\n - These must run on the MDS (server) hosting the target metadata for the filesystem(MDT)\n\n paths to lfs and lctl, as well as some unix utilities, \n are provided through the get_external_binary_paths() method of module sf_lustre.event_context\n\n CL == changelog\n\n the ssh capability has to be validated at each installation (key-authentication)\n there is always the possibility that an ssh cmd will fail and not return any usable values\n need to do validity check and provide default values (old values?)\n\"\"\"\n\nfrom logging import getLogger\nimport os\nimport re\nimport stat\nimport subprocess as sp\nimport sys\n\nfrom sf_em_common.eventExceptions import NotUniqueCLUser\nfrom sf_em_common.utils import partition\n\n# REFACTOR: get_external_binary_paths should eventually be moved to sf_em_common pkg\nfrom sf_lustre.event_context import get_external_binary_paths\n\nfrom sfutils.directories import get_directory_location\nfrom sfutils.encoding import is_utf8\nfrom sfutils.api.exit_codes import ExitCodes\n\n# Should decorate all functions issuing commands across the network to test for empty return values\n# with multiple tries and then fail if still empty\n#--------------------------------------------------------------------------------------------------------\n# on MDS\n# ssh lustre2 lctl list_nids\n# ssh lustre2 lctl network up\n# ssh lustre2 lctl dl | grep -w mdt | awk '{print $4}'\n\n# ssh lustre2 lctl --device sf-l-MDT0000 changelog_register\n# ssh lustre2 lctl --device sf-l-MDT0000 changelog_deregister cl4\n# ssh lustre2 lctl list_param mdd.sf-l-MDT0000\n# ssh lustre2 lctl get_param mdd.sf-l-MDT0000.changelog_users | grep cl\n# ssh lustre2 lctl get_param mdd.sf-l-MDT0000.changelog_mask\n# note nested quotes\n# ssh lustre2 lctl set_param \"mdd.sf-l-MDT0000.changelog_mask='CREAT MKDIR HLINK UNLNK RMDIR RENME CLOSE LYOUT TRUNC SATTR XATTR HSM MTIME CTIME ATIME'\"\n# ssh lustre2 lctl pool_new sf-l.pool0\n# ssh lustre2 lctl pool_list sf-l\n# ssh lustre2 lctl pool_list /mnt/ost0\n# ssh lustre2 lctl pool_add sf-l.pool1 OST0000\n# ssh lustre2 lctl pool_list sf-l.pool1\n# ssh lustre2 lctl pool_remove sf-l.pool1 OST0000\n\n#--------------------------------------------------------------------------------------------------------\n# on client\n# lfs pool_list sf-l\n# lfs osts\n# lfs osts /mnt/ost0\n# lfs changelog sf-l-MDT0000\n# lfs changelog sf-l-MDT0000 2200000 2200005\n# lfs changelog_clear sf-l-MDT0000 cl1\n# lfs getstripe --pool /mnt/ost0/d0014/d0014_0015/f0014_0015_0022\n# lfs setstripe --pool pool2 /mnt/ost0/d0014/d0014_0015/f0014_0015_0032\n# lfs migrate --pool pool1 /mnt/ost0/d0014/d0014_0015/f0014_0015_0022\n# lfs fid2path /mnt/ost0 0x200000411:0xd1fc:0x0\n# lfs path2fid /mnt/ost0/d0014/d0014_0015/f0014_0015_0022\n#\n#--------------------------------------------------------------------------------------------------------\nclass AdmCmds(object):\n _admlogger=getLogger(__name__)\n def __init__(self, args):\n self.args = args\n self.filesystem = args.fsPath\n self.cluser = args.cluser\n self.mds_host = args.mdshost\n self.mdt = args.mdt\n self.installdir = get_directory_location(\"sfhome\")\n self.bindir = get_directory_location(\"bin\")\n self.datadir = get_directory_location(\"share\")\n self.tmpdir = os.path.join(self.installdir, 'run')\n self.eventCount = 0\n self.start_event = 0\n self.currentevent = 0\n self.external_binariesD = get_external_binary_paths()\n self.lfs = self.external_binariesD['lfs_binary']\n self.lctl = self.external_binariesD['lctl_binary']\n self.ssh_cmd = [self.external_binariesD['ssh_binary'],self.mds_host] if self.mds_host else [] \n self.sequence_no_RE = re.compile(r'(\\d+)')\n\n#------------------------------------------------------------------------------------------------------\n# These error messages may change for diff versions of Lustre\n self.badPath_RE = re.compile(\"path2fid: can't get fid for\")\n self.fidSRE = '[pst]+[p]*=\\[([xa-f0-9:]+)\\]'\n#------------------------------------------------------------------------------------------------------\n# Stats of interest to be reported to scan service\n self.not_utf8_files_count = 0\n self.no_file_path_for_FID_count = 0\n#--------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------\n def CLUsers(self):\n \"\"\"\n Option for using ssh to a remote MDS\n Return list of changelog users\n \"\"\"\n mdd = \".\".join(['mdd',self.mdt,'changelog_users'])\n base_lctl_cmd = [self.lctl,'get_param',mdd]\n lctl_cmd = self.ssh_cmd + base_lctl_cmd\n grep_cmd = [self.external_binariesD['grep_binary'],'^cl[0-9]']\n awk_cmd = [self.external_binariesD['awk_binary'],'{print $1}']\n p1 = sp.Popen(lctl_cmd,stdout=sp.PIPE,universal_newlines=True)\n p2 = sp.Popen(grep_cmd,stdin=p1.stdout,stdout=sp.PIPE,universal_newlines=True)\n p3 = sp.Popen(awk_cmd,stdin=p2.stdout,stdout=sp.PIPE,universal_newlines=True)\n p1.stdout.close()\n p2.stdout.close()\n cluserL = p3.stdout.read().splitlines()\n p3.stdout.close()\n return cluserL\n#------------------------------------------------------------------------\n# Make sure there are no active CL users when starting the event monitor service\n# the changelog monitor should start just before scanning the filesystem.\n# events before the scan starts are irrelevant\n# Compare the cluser passed with option '--cluser' to the \"list\" of clusers deduced from the\n# \"ssh lctl get_param 'mdd'..changelog_users\" command\n# 4 conditions, each with it's own consequence\n#------------------------------------------------------------------------\n# REFACTOR: better name is check_CLusers()\n def initCLusers(self,cluser):\n clusersL = self.CLUsers() # cluser list from MDT\n self.cluser = cluser # cluser from command line\n num_clusers = len(clusersL)\n if num_clusers == 0:\n msg = (' No changelog(CL) user was registered. Without a registered CL user, no events will be generated for file operations.'\n ' Monitoring has to abort.\\n'\n ' A CL user should have been created before POSIX scanning was started.'\n \" Expecting CL user '{}'.\".format(self.cluser)\n )\n raise NotUniqueCLUser(2,msg)\n elif num_clusers > 1:\n msg = (' Too many changelog(CL) users are registered. A system administrator has to check'\n \" to make sure that starfish isn't sharing the changelog with other applications\"\n ' and ensure that only the Starfish CL user is registered when starting the event monitor.\\n'\n ' Only one registered CL user is allowed for this volume at this time.'\n \" The changelog(CL) user passed on the command line is '{}',\".format(self.cluser) +\n \" and the CL users registered by the MDS are {},\".format(clusersL) +\n ' With too many CL users, monitoring has to abort.'\n )\n raise NotUniqueCLUser(3,msg)\n elif clusersL[0] != self.cluser :\n msg = (\" The changelog(CL) user passed on the command line, '{}',\".format(self.cluser) +\n \" and the CL user registered by the MDS, '{}',\".format(clusersL[0]) +\n ' are not the same. Without the right CL user, monitoring has to abort.'\n )\n raise NotUniqueCLUser(1,msg)\n#--------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------\n def CLIndices(self):\n \"\"\"\n Run occasionally\n The number of CL users should already have been adjusted to 1\n Option for using ssh to query a remote MDS\n Return current index and user index for changelog as dict\n User index is the last event cleared for that user (next event in changelog is user index + 1)\n Include check for additional CL users, just in case someone is messing with the system\n while SF is running (it can cause problems with deleting the log entries)\n \"\"\"\n mdd = \".\".join(['mdd',self.mdt,'changelog_users'])\n base_lctl_cmd = [self.lctl,'get_param',mdd]\n lctl_cmd = self.ssh_cmd + base_lctl_cmd\n grep_cmd = [self.external_binariesD['grep_binary'],'^cl[0-9]']\n awk_cmd = [self.external_binariesD['awk_binary'],'{print $1,$2}']\n p1 = sp.Popen(lctl_cmd,stdout=sp.PIPE,universal_newlines=True)\n p2 = sp.Popen(grep_cmd,stdin=p1.stdout,stdout=sp.PIPE,universal_newlines=True)\n p3 = sp.Popen(awk_cmd,stdin=p2.stdout,stdout=sp.PIPE,universal_newlines=True)\n p1.stdout.close()\n p2.stdout.close()\n cluserL = p3.stdout.read().strip().split()\n p3.stdout.close()\n grep_cmd = [self.external_binariesD['grep_binary'],'current']\n awk_cmd = [self.external_binariesD['awk_binary'],'{print $3}']\n p1 = sp.Popen(lctl_cmd,stdout=sp.PIPE,universal_newlines=True)\n p2 = sp.Popen(grep_cmd,stdin=p1.stdout,stdout=sp.PIPE,universal_newlines=True)\n p3 = sp.Popen(awk_cmd,stdin=p2.stdout,stdout=sp.PIPE,universal_newlines=True)\n p1.stdout.close()\n p2.stdout.close()\n currentL = p3.stdout.read().strip().split()\n p3.stdout.close()\n # if either the cluser index or the current index returns empty, return an empty dict\n # and let caller do request again or give up\n if not cluserL or not currentL:\n return {}\n if not self.cluser == cluserL[0]:\n msg = ( ' The current CL user {} is different than what the monitor started with {}.'.format(cluserL[0],self.cluser) +\n ' Restart the service')\n AdmCmds._admlogger.error(\"ERROR \" + msg)\n sys.exit(ExitCodes.FS_MONITOR_ERROR)\n clIndexD = {'current':int(currentL[-1]), 'cluser': cluserL[0], 'clIndex':int(cluserL[1])}\n return clIndexD\n\n def registerCLUser(self):\n \"\"\"\n Option for using ssh to a remote MDS\n Example output:\n sf-l-MDT0000: Registered changelog userid 'cl6'\n Output: cluser is in self.cluser\n This is provided for informational purposes - not used by the monitor.\n -- note that CL user can't be shared with another application\n \"\"\"\n base_lctl_cmd = [self.lctl,'--device',self.mdt,'changelog_register']\n lctl_cmd = self.ssh_cmd + base_lctl_cmd\n grep_cmd = [self.external_binariesD['grep_binary'],'userid']\n p1 = sp.Popen(lctl_cmd,stdout=sp.PIPE,universal_newlines=True)\n p2 = sp.Popen(grep_cmd,stdin=p1.stdout,stdout=sp.PIPE,universal_newlines=True)\n p1.stdout.close()\n cluserS = p2.stdout.read()\n p2.stdout.close()\n AdmCmds._admlogger.debug(cluserS)\n cluserL = re.split(r\"[\\'\\s]+\",cluserS)\n if len(cluserL) > 0:\n msg = (' There can be no other changelog users. '\n 'The administrator has to '\n 'specify the CL user with the --cluser option \\n' +\n \" \".join(cluserL)\n )\n AdmCmds._admlogger.error(\"ERROR \" + msg)\n sys.exit(ExitCodes.FS_MONITOR_ERROR)\n elif cluserL[0] == '':\n msg = (' No new CL user was registered. Without a CL user, monitoring has to abort.'\n ' Check that the ssh host is the primary MDS able to register CL users or '\n ' have the administrator create a CL user by hand and use the'\n ' --cluser option when starting the event monitor service '\n )\n AdmCmds._admlogger.error(\"ERROR \" + msg)\n sys.exit(ExitCodes.FS_MONITOR_ERROR)\n self.cluser = cluserL[-2] if cluserL[-1] == '' else cluserL[-1]\n def deregisterCLUserL(self,cluserL):\n for cluser in cluserL:\n base_lctl_cmd = [self.lctl,'--device',self.mdt,'changelog_deregister',cluser]\n lctl_cmd = self.ssh_cmd + base_lctl_cmd\n p1 = sp.Popen(lctl_cmd,stdout=sp.PIPE,universal_newlines=True)\n cluserS = p1.stdout.read()\n#--------------------------------------------------------------------------------------------------------\n \"\"\"\n lfs commands\n \"\"\"\n#--------------------------------------------------------------------------------------------------------\n def lustre_version(self,mdshost):\n \"\"\"\n return major,minor lustre sftwr level\n lfs --version\n needs to run on the MDS associated with the lustre file system of interest\n\n since filenames can have arbitrary \\r\\n sequences embedded in them, subprocessing can't use\n universal newlines. Have to read in bytes and decode to utf-8\n \"\"\"\n lfs_cmd = [self.external_binariesD['ssh_binary'],mdshost,self.lfs,'--version']\n out = sp.check_output(lfs_cmd,universal_newlines=True)\n lustre_ver = out.strip()\n lustreL = re.split('[.]',lustre_ver)[0:2]\n\n def reportCLEvents(self,process_changelog,start_event,end_event):\n \"\"\"\n process_changelog() is a method from changelogFilter.py\n Have to provide process_changelog function, because before decoding binary event strings, have to reconstruct\n full event list. If decoding happens first, any event list item with a non-utf8 filename are rejected,\n and if the filename also has embedded whitespace (\\n), parsing can fail because fragments of the event may be kept.\n e.g. - if an event was\n b'1486 01CREAT 01:49:37.57866 2017.04.25 0x0 t=[0x200001b71:0x28d:0x0] p=[0x200000007:0x1:0x0] \\xa0\\xa1 \\n \\n'\n it would be split into\n [b'1486 01CREAT 01:49:37.5786 2017.04.25 0x0 t=[0x200001b71:0x28d:0x0] p=[0x200000007:0x1:0x0] \\xa0\\xa1 ',' ','']\n but the first element is rejected because it's not utf-8 compatible. so two fragments are left, belonging to no event.\n Have to supply start_event, end_event, because if the changelog file is big enough,\n this will be a subset of the records\n But a configuration option is to grab all events on a first pass through the event read loop\n\n output from the \"lsf changelog ...\" cmd is a raw bytestring, which has to be split up by '\\n' and checked \n for utf-8 compatibility\n event processing expects unicode strings, so decoding has to be here, which means checking has to be here\n any (events)lines that fail, need to be logged and rest passed on for processing\n \"\"\"\n if int(start_event) < 0:\n lfs_cmd = [self.lfs,'changelog',self.mdt]\n AdmCmds._admlogger.debug('CHANGELOG cmd: full dump\\n\\t {}'.format(lfs_cmd))\n else:\n lfs_cmd = [self.lfs,'changelog',self.mdt,start_event,end_event]\n AdmCmds._admlogger.debug('CHANGELOG cmd: dump range\\n\\t {}'.format(lfs_cmd))\n \"\"\"\n up to lustre 2.9, a bad range of start event, stop event numbers will exit with 0 but return no events\n But at least one version (2.10?) will return an error code (22) for a bad range\n will an empty changelog return an error code like the bad-range situation\n if there are no events, p1 is set to b'', but need to return an empty list\n \"\"\"\n try:\n AdmCmds._admlogger.debug('Before read changelog')\n p1 = sp.check_output(lfs_cmd)\n AdmCmds._admlogger.debug('After read changelog. Byte array is {} bytes'.format(len(p1)))\n except sp.CalledProcessError as cp:\n msg = (' Error from the changelog. \"{cmd}\" returned with a code of {rc}.\\n'\n ' lfs command> {lfs}\\n'\n ' Output {out} '.format(cmd=cp.cmd,rc=cp.returncode,lfs=lfs_cmd,out=cp.output)\n )\n AdmCmds._admlogger.info(msg)\n p1 = b\"\"\n except Exception as exc:\n msg = (' Error from the changelog.\\n'\n ' lfs command> {lfs}\\n'\n ' Output {exc} '.format(lfs=lfs_cmd,exc=exc)\n )\n AdmCmds._admlogger.error(msg)\n sys.exit(\"ERROR \" + msg)\n# REFACTOR: Is this a finally clause?\n# REFACTOR: what if a non-utf8 filename also has embedded newlines? the partition will only remove part of an event \n# - a corrupted filename. Perhaps need to filter all newlines embedded in filenames in the chunk \n# before screening for non-utf8 filenames and decoding events into utf-8\n# postpone decoding until after detecting event boundaries?\n# REFACTOR: what about readlines() instead?\n if not p1:\n AdmCmds._admlogger.debug('Empty changelog')\n return []\n lfs_out = bytearray(p1)[:-1].split(b'\\n')\n AdmCmds._admlogger.debug('Before process changelog. lfs split output list has {} lines'.format(len(lfs_out)))\n eventL_bytearray = process_changelog(lfs_out)\n AdmCmds._admlogger.debug('After process changelog; '\n 'Before convert bytearray list to bytes list, event list is {} lines'.format(len(eventL_bytearray)))\n eventL = [bytes(event) for event in eventL_bytearray]\n AdmCmds._admlogger.debug('After convert bytearray list to bytes list, event list is {} lines'.format(len(eventL)))\n utf8_fail,utf8_ok = partition(is_utf8,eventL)\n if utf8_fail:\n msg = ('Events that include non-utf8 characters\\n{}'.format(repr(utf8_fail)))\n AdmCmds._admlogger.info(msg)\n self.not_utf8_files_count += len(utf8_fail)\n eventsL = [eventstr.decode('utf-8') for eventstr in utf8_ok]\n AdmCmds._admlogger.debug('After decode events')\n return eventsL\n\n def readCLEventsFromFile(self,process_changelog,file_name):\n \"\"\"\n This is for testing, so most of the checks from reportCLEvents() are irrelevant\n The last item in the file is '\\n', so delete it as done in reportCLEvents() with bytearray\n\n Note - this assumes valid input strings (no embedded non-utf8 characters)\n \"\"\"\n# REFACTOR: what about readlines() instead of read()?\n eventsL = []\n with open(file_name,'rb') as fd:\n lfs_out = fd.read()[:-1].split(b'\\n')\n utf8_ok = process_changelog(lfs_out)\n eventsL = [eventstr.decode('utf-8') for eventstr in utf8_ok]\n return eventsL\n\n def clearCL(self,cluser,end_event):\n \"\"\"\n Have to supply end_event, because if some events fail to get loaded,\n the end event number will differ from self.end_event\n\n All lustre vsns return failed exit code 2 when clearing the changelog \n if it fails because of using the wrong CL user\n lustre vsns 2.9+ return failed exit code 22 when clearing the changelog \n if it fails because of using the wrong CL user\n \"\"\"\n lfs_cmd = [self.lfs,'changelog_clear',self.mdt,cluser,end_event]\n # should be sp.call or similar\n try:\n p1 = sp.check_output(lfs_cmd,stderr=sp.STDOUT,universal_newlines=True)\n msg = ' Cleared events:' + p1\n AdmCmds._admlogger.debug(msg)\n except sp.CalledProcessError as cp:\n if cp.returncode == 2:\n msg = ( 'failed to clear the changelog for CL user {} on MDT {}. '.format(cluser,self.mdt) +\n '\\n\"lfs changelog_clear\" returned with a code of {}.'.format(cp.returncode) + \n \"\\nThis implies the CL user doesn't exist. Terminating event monitor\"\n )\n AdmCmds._admlogger.error(msg)\n sys.exit(\"ERROR \" + msg)\n elif (cp.returncode == 22):\n \"\"\"\n This is normal for vsns 2.9+ when end_event has already been cleared\n \"\"\"\n pass\n else:\n msg = ( 'failed to clear the changelog for CL user {} on MDT {}. '.format(cluser,self.mdt) +\n '\\n\"lfs changelog_clear\" returned with a code of {}.'.format(cp.returncode) + \n \"\\nThis needs manual inspection.\"\n )\n AdmCmds._admlogger.warning(msg)\n\n # sanity test - last changelog entry cleared should not be retrievable\n # sp.CalledProcessError likely means the CL user is no longer registered\n # normal behavior is for this changelog read to return empty\n lfs_cmd = [self.lfs,'changelog',self.mdt,end_event,end_event]\n try:\n p1 = sp.check_output(lfs_cmd)\n except sp.CalledProcessError as cp:\n msg = (' Error found when clearing the changelog. \"{cmd}\" returned with a code of {rc}.\\n'\n ' lfs command> {lfs}\\n'\n ' this can be caused by the changelog user no longer being registered\\n'\n ' Output {out} '.format(cmd=cp.cmd,rc=cp.returncode,lfs=lfs_cmd,out=cp.output)\n )\n AdmCmds._admlogger.exception(msg)\n except Exception as exc:\n msg = (' General exception found when clearing the changelog \\n'\n ' lfs command> {lfs}\\n'\n ' Output {exc} '.format(lfs=lfs_cmd,exc=exc)\n )\n AdmCmds._admlogger.error(msg)\n if p1:\n msg = (' Error found when clearing the changelog. the last event was not cleared \\n'\n ' it is possible that more than one CL user is registered to this MDT {mdt}'\n ' expecting only CL user {cluser}'.format(mdt=self.mdt,cluser=self.cluser))\n AdmCmds._admlogger.exception(msg)\n sys.exit(\"ERROR \" + msg)\n\n#-------------------------------------------------\n def onePath2fid(self,fullpathS):\n \"\"\"\n supply a single path and return a fid or nothing if error\n example generated line: /mnt/ost0/d0000: [0x20000040c:0x14639:0x0]\n strip off trailing : [ ] chars\n \"\"\"\n lfs_cmd = [self.lfs,'path2fid'] + [fullpathS]\n try:\n fidS = sp.check_output(lfs_cmd,stderr=sp.STDOUT,universal_newlines=True)\n except sp.CalledProcessError:\n msg = ('onePath2fid: ' + fullpathS + ' undefined ')\n AdmCmds._admlogger.info(msg)\n return \"\"\n fid = fidS.strip(':[]\\n')\n return fid\n\n @staticmethod\n def get_ino_from_fid_direct(fidS):\n \"\"\"\n primarily derived from lustre-release/lustre/include/lustre_fid.h\n other defns in\n ./lustre/include/lustre/lustre_user.h\n ./include/lustre/lustre_idl.h\n\n Flatten 128-bit FID values into a 64-bit value for use as an inode number.\n For non-IGIF FIDs this starts just over 2^32, and continues without\n conflict until 2^64, at which point we wrap the high 24 bits of the SEQ\n into the range where there may not be many OID values in use, to minimize\n the risk of conflict.\n\n Suppose LUSTRE_SEQ_MAX_WIDTH less than (1 << 24) which is currently true,\n the time between re-used inode numbers is very long - 2^40 SEQ numbers,\n or about 2^40 client mounts, if clients create less than 2^24 files/mount.\n\n \"\"\"\n def fid_is_igif(seq):\n return (seq >= FID_SEQ_IGIF) and ( seq <= FID_SEQ_IGIF_MAX)\n\n byte4 = 0xFFFFFFFF\n byte8 = 0xFFFFFFFFFFFFFFFF\n byte5 = 0xFFFFFF0000\n FID_SEQ_IGIF = 12\n FID_SEQ_IGIF_MAX = byte4\n\n fid = fidS.strip(r'[]\\n').split(':')\n assert len(fid) == 3, ('FID is malformed {}'.format(fidS))\n seq = int(fid[0],16) & byte8\n oid = int(fid[1],16) & byte4\n ver = int(fid[2],16) & byte4\n if fid_is_igif(seq):\n return seq\n ino = (seq << 24) + ((seq >> 24) & byte5) + oid\n if not ino:\n ino = oid\n return ino\n def pathL2fidD(self,fullpathL):\n \"\"\"\n supply a list of paths and return a dict of fids:paths\n example input line: /mnt/ost0/d0000: [0x20000040c:0x14639:0x0]\n strip off trailing : [ ] chars\n could assume fids are output in same order as paths input to make it simpler\n \"\"\"\n lfs_cmd = [self.lfs,'path2fid'] + fullpathL\n p1 = sp.Popen(lfs_cmd,stdout=sp.PIPE,universal_newlines=True)\n fidL = p1.stdout.readlines()\n p2fD = {}\n for i,l in enumerate(fidL):\n if self.badPath_RE.match(l):\n msg = ('Skipping' + fullpathL[i])\n AdmCmds._admlogger.warning(msg)\n continue\n fullpath,fid = l.split()\n p2fD[fid.strip(':[]')] = fullpath.rstrip(':/')\n return p2fD\n def fid2path_by_link(self,fidS,link_number):\n \"\"\"\n Because of links, one FID can return multiple paths. Therefore, supplying multiple\n FIDs to \"lfs fid2path\" can result in ambiguous output (which FID generated which path?)\n supply a single fid and return paths one at a time (until reaching a duplicate)\n or return an empty list if fid2path returns an error (likely FID is not found, path no longer exists)\n \n generates paths one at a time \n note that each path (fullpathS) is terminated with a '\\n', which needs to be removed from the filename\n\n Parser is responsible for cleaning up an event field that includes an fid, the input for this function\n is an FID in a format compatible with lfs fid2path <> (with or without bracketing [..])\n\n REFACTOR: there is a danger that a returned path could not be utf8 compliant, so that needs to be checked here\n as well : should return byte string instead and decode to utf8\n REFACTOR: This is the slow way to do it - better to rework lfs fid2path to separate paths with null bytes\n\n REFACTOR: note that \"\" is a string, but is not decodeable. This should be a Monad of some type instead.\n\n REFACTOR: if lfs_cmd can't find a path for the FID, it throws a sp.CalledProcessError, so it shouldn't matter\n that the output is empty; the [:-1] never gets executed - does this need clean up?\n \"\"\"\n lfs_cmd = [self.lfs,'fid2path'] + ['--link',str(link_number)] + [self.filesystem,fidS]\n try:\n fullpathB = bytearray(sp.check_output(lfs_cmd,stderr=sp.STDOUT))[:-1]\n except sp.CalledProcessError as cp:\n msg = ('fid2path: ' + fidS + ' undefined')\n AdmCmds._admlogger.info(msg)\n msg = ('fid2path_by_link: returned ' + str(cp.returncode))\n if cp.output:\n msg += ('\\n' + cp.output.decode('utf-8'))\n AdmCmds._admlogger.info(msg)\n return b\"\"\n except AttributeError as ae:\n msg = (\"fid2path_by_link: can't find FID: \" + fidS)\n AdmCmds._admlogger.info(msg)\n return b\"\"\n except OSError as e:\n msg = (\"fid2path_by_link: can't find path: {}\".format(fullpathB))\n AdmCmds._admlogger.info(msg)\n return b\"\"\n else:\n return os.path.normpath(fullpathB)\n def fid2path_for_dir(self,fidS):\n \"\"\"\n If the FID is known to belong to a directory, then, since directories only have one link, \n only one call to 'lfs fid2path' is required\n\n Parser is responsible for cleaning up an event field that includes an fid, the input for this function\n is an FID in a format compatible with lfs fid2path <> (with or without bracketing [..])\n\n REFACTOR: it is debatable whether this should return a list with 1 item (compatible with fid2path()) or\n a simple string. For now, return simple string, since fid2path_for_dir is only used in a few places\n\n \"\"\"\n fullpathB = self.fid2path_by_link(fidS,0)\n if fullpathB and is_utf8(fullpathB):\n fullpathS = fullpathB.decode('utf-8')\n elif fullpathB:\n msg = ('File path includes non-utf8 characters\\n{}'.format(repr(fullpathB)))\n AdmCmds._admlogger.info(msg)\n fullpathS = \"\"\n self.not_utf8_files_count += 1\n else:\n msg = ('No File path exists for supplied FID \\n{}'.format(repr(fidS)))\n AdmCmds._admlogger.info(msg)\n fullpathS = \"\"\n self.no_file_path_for_FID_count += 1\n return fullpathS\n def fid2path_nologging_for_dir(self,fidS):\n \"\"\"\n Because of links, one FID can return multiple paths. Therefore, supplying multiple\n FIDs to \"lfs fid2path\" can result in ambiguous output (which FID generated which path?)\n supply a single fid and return a path or nothing if error\n just generates a path (no pairing with input FID)\n\n BRAD-91 - remove events do not need to log an FID as \"undefined\", because that's a normal circumstance\n\n Parser is responsible for cleaning up an event field that includes an fid, the input for this function\n is an FID in a format compatible with lfs fid2path <> (with or without bracketing [..])\n \"\"\"\n fullpathS = \"\"\n fullpathB = self.fid2path_by_link(fidS,0)\n if fullpathB and is_utf8(fullpathB):\n fullpathS = fullpathB.decode('utf-8')\n elif fullpathB:\n self.not_utf8_files_count += 1\n else:\n self.no_file_path_for_FID_count += 1\n return fullpathS\n\n def fid2path(self,fidS):\n \"\"\"\n Because of links, one FID can return multiple paths. Therefore, supplying multiple\n FIDs to \"lfs fid2path\" can result in ambiguous output (which FID generated which path?)\n supply a single fid and return paths one at a time (until reaching a duplicate)\n or return an empty list if fid2path returns an error (likely FID is not found, path no longer exists)\n \n generates paths one at a time \n note that each path (fullpathS) is terminated with a '\\n', which needs to be removed from the filename\n\n Parser is responsible for cleaning up an event field that includes an fid, the input for this function\n is an FID in a format compatible with lfs fid2path <> (with or without bracketing [..])\n\n REFACTOR: there is a danger that a returned path could not be utf8 compliant, so that needs to be checked here\n as well : should return byte string instead and decode to utf8\n REFACTOR: This is the slow way to do it - better to rework lfs fid2path to separate paths with null bytes\n REFACTOR: utf8_ok list can't contain a \"\" (empty string) as an item. decode is not callable by \"\"\n \"\"\"\n fullpathL = []\n i = 0\n\n while True:\n fullpathB = self.fid2path_by_link(fidS,i)\n if fullpathB in fullpathL or fullpathB == b\"\":\n if fullpathB == b\"\":\n self.no_file_path_for_FID_count += 1\n break\n else:\n fullpathL.append(fullpathB)\n i += 1\n utf8_fail,utf8_ok = partition(is_utf8,fullpathL)\n if utf8_fail:\n msg = ('File paths that include non-utf8 characters\\n{}'.format(repr(utf8_fail)))\n AdmCmds._admlogger.warn(msg)\n self.not_utf8_files_count += len(utf8_fail)\n fullpathsL = [fullpathstr.decode('utf-8') for fullpathstr in utf8_ok]\n return fullpathsL\n def fid2path_nologging(self,fidS):\n \"\"\"\n Because of links, one FID can return multiple paths. Therefore, supplying multiple\n FIDs to \"lfs fid2path\" can result in ambiguous output (which FID generated which path?)\n supply a single fid and return a path or nothing if error\n just generates a path (no pairing with input FID)\n\n BRAD-91 - remove events do not need to log an FID as \"undefined\", because that's a normal circustance\n\n Parser is responsible for cleaning up an event field that includes an fid, the input for this function\n is an FID in a format compatible with lfs fid2path <> (with or without bracketing [..])\n \"\"\"\n fullpathL = []\n i = 0\n\n while True:\n fullpathB = self.fid2path_by_link(fidS,i)\n if fullpathB in fullpathL or fullpathB == b\"\":\n if fullpathB == b\"\":\n self.no_file_path_for_FID_count += 1\n break\n else:\n fullpathL.append(fullpathB)\n i += 1\n utf8_fail,utf8_ok = partition(is_utf8,fullpathL)\n if utf8_fail:\n self.not_utf8_files_count += len(utf8_fail)\n fullpathsL = [fullpathstr.decode('utf-8') for fullpathstr in utf8_ok]\n return fullpathsL\n def getpool(self,fullpath):\n \"\"\"\n report pools associated with fullpath\n \"\"\"\n lfs_cmd = [self.lfs,'getstripe','--pool',fullpath]\n p1 = sp.Popen(lfs_cmd,stdout=sp.PIPE,universal_newlines=True)\n poolL = p1.stdout.read().splitlines()\n return poolL\n\n def setpool(self,fullpath):\n \"\"\"\n change pool associated with fullpath\n can't be done to file already created or assigned pool\n \"\"\"\n lfs_cmd = [self.lfs,'setstripe','--pool',fullpath]\n p1 = sp.Popen(lfs_cmd,stdout=sp.PIPE,universal_newlines=True)\n resL = p1.stdout.read().splitlines()\n return resL\n\n def migrate(self,fullpath,topool):\n \"\"\"\n target pool must have OSTs\n lfs_migrate is misnamed - it's really meant for rebalancing files between OSTs\n \"\"\"\n lfs_cmd = [self.lfs,'migrate','--pool',topool,fullpath]\n p1 = sp.Popen(lfs_cmd,stdout=sp.PIPE,universal_newlines=True)\n resL = p1.stdout.readlines()\n return resL\n\n#----------------------More attributes -------------------------------------------------------------------\n def getea(self,fullpath):\n \"\"\"\n get extended attributes\n \"\"\"\n getea_cmd = [self.external_binariesD['getea_binary'],'-d','-m-',fullpath]\n p1 = sp.Popen(getea_cmd,stdout=sp.PIPE,universal_newlines=True)\n eventL = p1.stdout.readlines()\n return eventL\n\n def setea(self,fullpath,attrT):\n \"\"\"\n set extended attributes from an attribute tuple\n won't work on anything already set by lustre\n also won't work on user attributes unless mount -o user_xattr is used\n \"\"\"\n setea_cmd = [self.external_binariesD['setea_binary'],'-n',attrT[0],'-v',attrT[1]]\n p1 = sp.Popen(setea_cmd,stdout=sp.PIPE,universal_newlines=True)\n eventL = p1.stdout.readlines()\n return eventL\n\n def getfacl(self,fullpath):\n \"\"\"\n get ACLs for a subtree starting at fullpath\n \"\"\"\n getacl_cmd = [self.external_binariesD['getacl_binary'],'-R',fullpath]\n p1 = sp.Popen(getacl_cmd,stdout=sp.PIPE,universal_newlines=True)\n eventL = p1.stdout.readlines()\n return eventL\n\n def setfacl(self,fullpath,aclS):\n \"\"\"\n set ACLs for a subtree starting at fullpath\n use a filek\n set extended attributes from an attribute tuple\n won't work on anything already set by lustre\n also won't work on user attributes unless mount -o user_xattr is used\n ACLs can be directly concat'd from output of getfacl\n \",\".join([list-of-acls not commented out])\n \"\"\"\n setacl_cmd = [self.external_binariesD['setacl_binary'],'-m',aclS,fullpath]\n p1 = sp.Popen(setacl_cmd,stdout=sp.PIPE,universal_newlines=True)\n eventL = p1.stdout.readlines()\n return eventL\n#--------------------- Class end -------------------------------------------------------------------\ndef get_ino_from_fid_direct(fidS):\n \"\"\"\n primarily derived from lustre-release/lustre/include/lustre_fid.h\n other defns in\n ./lustre/include/lustre/lustre_user.h\n ./include/lustre/lustre_idl.h\n\n Flatten 128-bit FID values into a 64-bit value for use as an inode number.\n For non-IGIF FIDs this starts just over 2^32, and continues without\n conflict until 2^64, at which point we wrap the high 24 bits of the SEQ\n into the range where there may not be many OID values in use, to minimize\n the risk of conflict.\n\n Suppose LUSTRE_SEQ_MAX_WIDTH less than (1 << 24) which is currently true,\n the time between re-used inode numbers is very long - 2^40 SEQ numbers,\n or about 2^40 client mounts, if clients create less than 2^24 files/mount.\n\n \"\"\"\n def fid_is_igif(seq):\n return (seq >= FID_SEQ_IGIF) and ( seq <= FID_SEQ_IGIF_MAX)\n\n byte4 = 0xFFFFFFFF\n byte8 = 0xFFFFFFFFFFFFFFFF\n byte5 = 0xFFFFFF0000\n FID_SEQ_IGIF = 12\n FID_SEQ_IGIF_MAX = byte4\n\n fid = fidS.strip(r'[]\\n').split(':')\n assert len(fid) == 3, ('FID is malformed {}'.format(fidS))\n seq = int(fid[0],16) & byte8\n oid = int(fid[1],16) & byte4\n ver = int(fid[2],16) & byte4\n if fid_is_igif(seq):\n return seq\n ino = (seq << 24) + ((seq >> 24) & byte5) + oid\n if not ino:\n ino = oid\n return ino\n","sub_path":"sf-lustre/src/sf_lustre/sorted-versions1/adminCmds.py","file_name":"adminCmds.py","file_ext":"py","file_size_in_byte":40401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"594349704","text":"from projects.qm_brain.utils.utils import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_probability(wavefun):\n\n amplitude = np.abs(wavefun).T\n\n ampMag = np.sqrt(np.sum((amplitude * amplitude).T, axis=0))\n\n normAmp = (np.asarray(amplitude.T) / np.asarray(ampMag)).T\n\n return normAmp * normAmp\n\ndef get_n_largest(array,n=92):\n ind = np.argpartition(np.abs(array), -n)[-n:]\n return array[ind]\n\n\nmain_path = '/home/user/Desktop/QMBrain/New Data/'\n\nfilepathX = main_path + 'x_chanloc.csv'\nfilepathY = main_path + 'y_chanloc.csv'\n\nx = load_matrix(filepathX)\ny = load_matrix(filepathY)\n\ncoord_stack = zip_x_y(x,y)\n\ncondition_list = ['Cond10/','Cond12/']\n\nfor condition in condition_list:\n\n for i in range(13):\n\n subject_path = main_path + condition + str(i + 1) + '/results/'\n\n print('Running for subject ', i + 1, 'in folder ', condition)\n\n filepathPos = subject_path + 'position_wavefunction_1d.npy'\n filepathMom = subject_path + 'momentum_wavefunction.npy'\n\n psi_x = np.squeeze(load_matrix(filepathPos))\n\n psi_p = np.squeeze(load_matrix(filepathMom))\n\n\n pos_wavefun = data_1d_to_2d(psi_x,x,y)\n\n # Determine the 92 best points\n\n psi_p_small = np.zeros(shape=(psi_p.shape[0], psi_p.shape[1]), dtype=np.complex64)\n\n for t in range(psi_p.shape[0]):\n psi_p_small[t, :] = get_n_largest(psi_p[t, ...].flatten())\n\n momentum_prob = get_probability(psi_p_small.T)\n\n prob_deriv = prob_derivative(probability)\n","sub_path":"projects/qm_brain/plots_fft.py","file_name":"plots_fft.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"631007987","text":"import discord\nimport asyncio\nimport re\nimport pytz\nfrom discord.utils import get \nfrom discord.ext import commands \nfrom discord.errors import Forbidden\nfrom datetime import datetime, timezone,timedelta\nfrom bfunc import db, traceBack, roleArray, settingsRecord, timezoneVar\nfrom cogs.util import calculateTreasure, callAPI, timeConversion, noodleRoleArray, uwuize\nfrom pymongo import UpdateOne\nfrom pymongo.errors import BulkWriteError\n\n\n\n\nguild_drive_costs = [4, 4, 6, 9, 13, 13]\n\nasync def generateLog(self, ctx, num : int, sessionInfo=None, guildDBEntriesDic=None, characterDBentries=None, userDBEntriesDic=None, ):\n logData = db.logdata\n if sessionInfo == None:\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n \n channel = self.bot.get_channel(settingsRecord[str(ctx.guild.id)][\"Sessions\"]) \n editMessage = await channel.fetch_message(num)\n\n if not editMessage or editMessage.author != self.bot.user:\n print(\"Invalid Message\")\n return None\n \n # get the collections of characters\n playersCollection = db.players\n guildCollection = db.guilds\n statsCollection = db.stats\n usersCollection = db.users\n\n sessionLogEmbed = editMessage.embeds[0]\n summaryIndex = sessionLogEmbed.description.find('Summary**')\n description = sessionLogEmbed.description[summaryIndex:]+\"\\n\"\n \n role = sessionInfo[\"Role\"]\n game = sessionInfo[\"Game\"]\n start = sessionInfo[\"Start\"] \n end = sessionInfo[\"End\"] \n tierNum = sessionInfo[\"Tier\"]\n \n guilds = sessionInfo[\"Guilds\"]\n \n players = sessionInfo[\"Players\"] \n #dictionary indexed by user id\n # {cp, magic items, consumables, inventory, partial, status, user id, character id, character name, character level, character cp, double rewards, guild, }\n \n dm = sessionInfo[\"DM\"] \n # {cp, magic items, consumables, inventory, partial, status, user id, character id, character name, character level, character cp, double rewards, guild, noodles}\n \n maximumCP = dm[\"CP\"]\n \n deathChars = []\n allRewardStrings = {}\n \n characterIDs = [p[\"Character ID\"] for p in players.values()]\n userIDs = list(players.keys())\n guildIDs = list(guilds.keys())\n for gt in guildIDs:\n if guilds[gt][\"Status\"] == False:\n del guilds[gt]\n \n \n guildIDs = list(guilds.keys())\n \n userIDs.append(str(dm[\"ID\"]))\n \n # the db entry of every character\n if characterDBentries == None:\n characterDBentries = list(playersCollection.find({\"_id\": {\"$in\": characterIDs}}))\n characterDBentriesDic = {character[\"_id\"] : character for character in characterDBentries}\n # the db entry of every user\n if userDBEntriesDic == None:\n userDBentries = usersCollection.find({\"User ID\": {\"$in\": userIDs}})\n userDBEntriesDic = {}\n for u in userDBentries:\n userDBEntriesDic[u[\"User ID\"]] = u\n \n \n # the db entry of every guild\n if guildDBEntriesDic == None:\n guildDBEntriesDic = {}\n guildDBentries = guildCollection.find({\"Name\": {\"$in\": guildIDs}})\n for g in guildDBentries:\n guildDBEntriesDic[g[\"Name\"]] = g\n \n if g[\"Reputation\"] >= guild_drive_costs[sessionInfo[\"Tier\"]]:\n g[\"Reputation\"] -= guild_drive_costs[sessionInfo[\"Tier\"]]*guilds[g[\"Name\"]][\"Drive\"]\n else:\n guilds[g[\"Name\"]][\"Drive\"] = False\n \n if g[\"Reputation\"] >= 25:\n g[\"Reputation\"] -= 25*guilds[g[\"Name\"]][\"Rewards\"]\n else:\n guilds[g[\"Name\"]][\"Rewards\"] = False\n \n if g[\"Reputation\"] >= 10:\n g[\"Reputation\"] -= 10*guilds[g[\"Name\"]][\"Items\"]\n else:\n guilds[g[\"Name\"]][\"Items\"] = False\n gold_modifier = 100\n if \"Gold Modifier\" in sessionInfo:\n gold_modifier = sessionInfo[\"Gold Modifier\"]\n item_rewards = True\n if \"Items\" in sessionInfo:\n item_rewards = sessionInfo[\"Items\"]\n for k, player in players.items():\n # this indicates that the character had died\n if player[\"Status\"] == \"Dead\":\n deathChars.append(player)\n \n duration = player[\"CP\"] * 3600\n \n guildDouble = False\n playerDouble = False\n dmDouble = False\n \n if role != \"\":\n guild_valid =(\"Guild\" in player and \n player[\"Guild\"] in guilds and \n guilds[player[\"Guild\"]][\"Status\"] and\n player[\"CP\"]>= 3 and player['Guild Rank'] > 1)\n guildDouble = (guild_valid and \n guilds[player[\"Guild\"]][\"Rewards\"] and \n player[\"2xR\"])\n if(guild_valid and \n guilds[player[\"Guild\"]][\"Items\"] and \n player[\"2xI\"]):\n \n for i in player[\"Double Items\"]:\n if i[0] == \"Magic Items\":\n player[\"Magic Items\"].append(i[1])\n else:\n player[i[0]][\"Add\"].append(i[1])\n \n player[\"Double\"] = k in userDBEntriesDic.keys() and \"Double\" in userDBEntriesDic[k] and userDBEntriesDic[k][\"Double\"] >0\n playerDouble = player[\"Double\"]\n \n dmDouble = False\n bonusDouble = \"Bonus\" in sessionInfo and sessionInfo[\"Bonus\"]\n \n treasureArray = calculateTreasure(player[\"Level\"], player[\"Character CP\"], duration, guildDouble, playerDouble, dmDouble, bonusDouble, gold_modifier)\n treasureString = f\"{treasureArray[0]} CP, {sum(treasureArray[1].values())} TP, {treasureArray[2]} GP\"\n \n \n else:\n # if there were no rewards we only care about the time\n treasureString = timeConversion(duration) \n groupString = \"\"\n groupString += guildDouble * \"2xR \"\n groupString += playerDouble * \"Fanatic \"\n groupString += bonusDouble * \"Bonus \"\n groupString += f'{role} Friend {\"Full\"*(player[\"CP\"]==dm[\"CP\"])+\"Partial\"*(not player[\"CP\"]==dm[\"CP\"])} Rewards:\\n{treasureString}'\n \n # if the player was not present the whole game and it was a no rewards game\n if role == \"\" and not (player[\"CP\"]==dm[\"CP\"]):\n # check if the reward has already been added to the reward dictionary\n if treasureString not in allRewardStrings:\n # if not, create the entry\n allRewardStrings[treasureString] = [player]\n else:\n # otherwise add the new players\n allRewardStrings[treasureString] += [player] \n else:\n # check if the full rewards have already been added, if yes create it and add the players\n if groupString in allRewardStrings:\n allRewardStrings[groupString] += [player]\n else:\n allRewardStrings[groupString] = [player]\n\n\n datestart = datetime.fromtimestamp(start).astimezone(pytz.timezone(timezoneVar)).strftime(\"%b-%d-%y %I:%M %p\")\n dateend = datetime.fromtimestamp(end).astimezone(pytz.timezone(timezoneVar)).strftime(\"%b-%d-%y %I:%M %p\")\n totalDuration = timeConversion(end - start)\n sessionLogEmbed.title = f\"Timer: {game} [END] - {totalDuration}\"\n dm_double_string = \"\"\n dmRewardsList = []\n #DM REWARD MATH STARTS HERE\n if(\"Character ID\" in dm):\n charLevel = int(dm['Level'])\n k = (dm['ID'])\n player = dm\n dm_tier_num = 5\n # calculate the tier of the DM character\n if charLevel < 5:\n dmRole = 'Junior'\n dm_tier_num = 1\n elif charLevel < 11:\n dmRole = 'Journey'\n dm_tier_num = 2\n elif charLevel < 17:\n dmRole = 'Elite'\n dm_tier_num = 3\n elif charLevel < 20:\n dmRole = 'True'\n dm_tier_num = 4\n else:\n dmRole = 'Ascended'\n \n duration = player[\"CP\"]*3600\n if role != \"\":\n guild_valid =(\"Guild\" in player and \n player[\"Guild\"] in guilds and \n guilds[player[\"Guild\"]][\"Status\"] and\n player[\"CP\"]>= 3 and player['Guild Rank'] > 1)\n \n guildDouble = (guild_valid and \n guilds[player[\"Guild\"]][\"Rewards\"] and \n player[\"2xR\"])\n \n player[\"Double\"] = k in userDBEntriesDic.keys() and \"Double\" in userDBEntriesDic[k] and userDBEntriesDic[k][\"Double\"] >0\n \n playerDouble = player[\"Double\"]\n \n if(guild_valid and \n guilds[player[\"Guild\"]][\"Items\"] and \n player[\"2xI\"]):\n \n for i in player[\"Double Items\"]:\n if i[0] == \"Magic Items\":\n player[\"Magic Items\"].append(i[1])\n else:\n player[i[0]][\"Add\"].append(i[1])\n \n dmDouble = player[\"DM Double\"] and sessionInfo[\"DDMRW\"]\n bonusDouble = \"Bonus\" in sessionInfo and sessionInfo[\"Bonus\"]\n \n dm_double_string += guildDouble * \"2xR \"\n dm_double_string += playerDouble * \"Fanatic \"\n dm_double_string += dmDouble * \"DDMRW \"\n dm_double_string += bonusDouble * \"Bonus \"\n \n dmtreasureArray = calculateTreasure(player[\"Level\"], player[\"Character CP\"], duration, guildDouble, playerDouble, dmDouble, bonusDouble)\n \n \n # add the items that the DM awarded themselves to the items list\n \n if item_rewards:\n for d in dm[\"Magic Items\"]+dm[\"Consumables\"][\"Add\"]+dm[\"Inventory\"][\"Add\"]:\n dmRewardsList.append(\"+\"+d)\n \n # get the collections of characters\n playersCollection = db.players\n dmEntry = userDBEntriesDic[dm[\"ID\"]]\n if 'Noodles' not in dmEntry:\n dmEntry['Noodles'] = 0\n if \"DM Time\" not in dmEntry:\n dmEntry[\"DM Time\"] = 0\n noodles = dmEntry[\"Noodles\"]\n # Noodles Math\n \n duration = end - start\n if duration < 3*3600:\n duration = 0\n noodlesGained = int((duration + dmEntry[\"DM Time\"])//(3*3600))\n \n # calculate the hour duration and calculate how many 3h segements were played\n hoursPlayed = maximumCP\n # that is the base line of sparkles and noodles gained\n sparklesGained = int(hoursPlayed) // 3\n # add the noodles to the record or start a record if needed\n \n #new noodle total\n noodleFinal = noodles + noodlesGained\n noodleFinalString = f\"{str(noodleFinal)}:star: (+{noodlesGained}:star:)\"\n\n # if the game received rewards\n if role != \"\": \n # clear the embed message to repopulate it\n sessionLogEmbed.clear_fields() \n # for every unique set of TP rewards\n for key, value in allRewardStrings.items():\n temp = \"\"\n # for every player of this reward\n for v in value:\n vRewardList = []\n # for every brough consumable for the character\n if item_rewards:\n for r in v[\"Magic Items\"]+ v[\"Consumables\"][\"Add\"]+ v[\"Inventory\"][\"Add\"]:\n # add the awarded items to the list of rewards\n vRewardList.append(\"+\"+r)\n # if the character was not dead at the end of the game\n char_name = v['Character Name']\n if \"Paused\" in characterDBentriesDic[v['Character ID']] and characterDBentriesDic[v['Character ID']][\"Paused\"]:\n char_name = \"[PAUSED] \" + char_name\n vRewardList = []\n if v not in deathChars:\n temp += f\"{v['Mention']} | {char_name} {', '.join(vRewardList).strip()}\\n\"\n else:\n # if they were dead, include that death\n temp += f\"~~{v['Mention']} | {char_name}~~ **DEATH** {', '.join(vRewardList).strip()}\\n\"\n \n # since if there is a player for this reward, temp will have text since every case above results in changes to temp\n # this informs us that there were no players\n if temp == \"\":\n temp = 'None'\n # add the information about the reward to the embed object\n sessionLogEmbed.add_field(name=f\"**{key}**\\n\", value=temp, inline=False)\n # add temp to the total output string\n\n # list of all guilds\n guildsListStr = \"\"\n \n guildRewardsStr = \"\"\n players[dm[\"ID\"]] = dm\n # passed in parameter, check if there were guilds involved\n if guilds != dict():\n guildsListStr = \"Guilds: \"\n # for every guild in the game\n for name, g in guilds.items():\n \n guildsListStr += \"\\n\"+(g[\"Drive\"]*\"**Recruitment Drive** \")+(g[\"Rewards\"]*\"**2xR** \")+(g[\"Items\"]*\"**2xI** \")+g[\"Mention\"]\n # get the DB record of the guild\n #filter player list by guild\n gPlayers = [p for p in players.values() if \"Guild\" in p and p[\"Guild\"]==name]\n if(len(gPlayers)>0): \n gain = 0\n for p in gPlayers:\n gain += p[\"CP\"] // 3\n \n gain += sparklesGained*int(\"Guild\" in dm and dm[\"Guild\"] == name)\n guildRewardsStr += f\"{g['Name']}: +{int(gain)} :sparkles:\\n\"\n \n noodleCongrats = \"\"\n # for the relevant noodle role cut-off check if the user would now qualify for the role and if they do not have it and remove the old role\n noodles_barrier = 0\n for i in range(len(noodleRoleArray)):\n if noodles < max(noodles_barrier, 1) and noodleFinal >= max(noodles_barrier, 1):\n noodleCongrats = f\"Congratulations! You have reached {noodleRoleArray[i]}!\"\n noodles_barrier += 10*(i+1)\n game_channel = get(ctx.guild.text_channels, name = sessionInfo['Channel'])\n if not game_channel:\n game_channel = sessionInfo['Channel']\n else:\n game_channel = f\"<#{game_channel.id}>\"\n sessionLogEmbed.title = f\"\\n**{game}**\\n*Tier {tierNum} Quest*\"\n sessionLogEmbed.description = f\"{game_channel}\\n{guildsListStr}\\n**Start**: {datestart} EDT\\n**End**: {dateend} EDT\\n**Runtime**: {totalDuration}\\n**General \"+description\n status_text = \"Log is being processed! Characters are currently on hold.\"\n await editMessage.clear_reactions()\n if sessionInfo[\"Status\"] == \"Approved\":\n status_text = \"✅ Log approved! The DM and players have received their rewards and their characters can be used in further one-shots.\"\n elif sessionInfo[\"Status\"] == \"Denied\":\n status_text = \"❌ Log Denied! Characters have been cleared\"\n noodleCongrats = \"\"\n elif sessionInfo[\"Status\"] == \"Pending\":\n status_text = \"❔ Log Pending! DM has been messaged due to session log issues.\"\n \n await editMessage.add_reaction('<:nipatya:408137844972847104>')\n gold_mod_text = f\"Current GP earned: {gold_modifier}%\\n\"\n sessionLogEmbed.set_footer(text=f\"Game ID: {num}\\n{status_text}\\n{gold_mod_text}{noodleCongrats}\")\n if noodleCongrats:\n await editMessage.add_reaction('🎉')\n await editMessage.add_reaction('🎊')\n await editMessage.add_reaction('🥳')\n await editMessage.add_reaction('🍾')\n await editMessage.add_reaction('🥂')\n \n # add the field for the DM's player rewards\n dm_text = \"**No Character**\"\n dm_name_text = \"**No Rewards**\"\n # if no character signed up then the character parts are excluded\n if(\"Character ID\" in dm):\n dm_char = playersCollection.find_one({\"_id\": dm[\"Character ID\"]})\n paused = \"Paused\" in dm_char and dm_char[\"Paused\"]\n dm_text = f\"{'[PAUSED] ' * paused + dm['Character Name']} {', '.join(dmRewardsList* (not paused))}\"\n dm_name_text = f\"DM {dm_double_string}Rewards (Tier {dm_tier_num}):\\n**{dmtreasureArray[0]} CP, {sum(dmtreasureArray[1].values())} TP, {dmtreasureArray[2]} GP**\\n\"\n sessionLogEmbed.add_field(value=f\"{dm['Mention']} | {dm_text}\\n{noodleFinalString}\", name=dm_name_text)\n \n # if there are guild rewards then add a field with relevant information\n if guildRewardsStr != \"\":\n sessionLogEmbed.add_field(value=guildRewardsStr, name=f\"Guild Rewards\", inline=False)\n await editMessage.edit(embed=sessionLogEmbed)\n \n pass\n \nclass Log(commands.Cog):\n def __init__ (self, bot):\n self.bot = bot\n def is_log_channel():\n async def predicate(ctx):\n if ctx.channel.type == discord.ChannelType.private:\n return False\n return (ctx.channel.category_id == settingsRecord[str(ctx.guild.id)][\"Player Logs\"] or \n ctx.channel.category_id == settingsRecord[str(ctx.guild.id)][\"Game Rooms\"] or\n ctx.channel.category_id == settingsRecord[str(ctx.guild.id)][\"Mod Rooms\"])\n return commands.check(predicate)\n @commands.group(case_insensitive=True)\n @is_log_channel()\n async def session(self, ctx):\t\n pass\n \n async def cog_command_error(self, ctx, error):\n msg = None\n\n if isinstance(error, commands.MissingAnyRole):\n msg = \"You do not have the required permissions for this command.\"\n elif isinstance(error, commands.BadArgument):\n # convert string to int failed\n msg = \"Your session ID was an incorrect format.\"\n elif isinstance(error, discord.NotFound):\n msg = \"The session log could not be found.\"\n else:\n if isinstance(error, commands.MissingRequiredArgument):\n msg = \"Your command was missing an argument! \"\n elif isinstance(error, commands.CheckFailure):\n msg = \"This channel or user does not have permission for this command.\"\n elif isinstance(error, commands.UnexpectedQuoteError) or isinstance(error, commands.ExpectedClosingQuoteError) or isinstance(error, commands.InvalidEndOfQuotedStringError):\n msg = \"\"\n\n if msg:\n ctx.command.reset_cooldown(ctx)\n await ctx.channel.send(msg)\n #await traceBack(ctx,error)\n else:\n ctx.command.reset_cooldown(ctx)\n await traceBack(ctx,error)\n\n @commands.has_any_role('Mod Friend', 'Admins')\n @session.command()\n async def approve(self,ctx, num : int):\n channel = self.bot.get_channel\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n channel = self.bot.get_channel(settingsRecord[str(ctx.guild.id)][\"Sessions\"]) \n editMessage = None\n \n try:\n editMessage = await channel.fetch_message(num)\n except Exception as e:\n return await ctx.channel.send(\"Log could not be found.\")\n \n \n\n if not sessionInfo:\n return await ctx.channel.send(\"Session could not be found.\")\n \n if sessionInfo[\"Status\"] == \"Approved\" or sessionInfo[\"Status\"] == \"Denied\":\n await ctx.channel.send(\"This session has already been processed\")\n return\n if ctx.author.id == int(sessionInfo[\"DM\"][\"ID\"]):\n await ctx.channel.send(\"You cannot approve your own log.\")\n return\n if not editMessage or editMessage.author != self.bot.user:\n return await ctx.channel.send(\"Session has no corresponding message in the log channel.\")\n\n\n \n guilds = sessionInfo[\"Guilds\"]\n tierNum = sessionInfo[\"Tier\"]\n role = sessionInfo[\"Role\"]\n \n #dictionary indexed by user id\n players = sessionInfo[\"Players\"] \n # {cp, magic items, consumables, inventory, status, character id, character name, character level, character cp, double rewards, guild, }\n \n \n dm = sessionInfo[\"DM\"] \n # {cp, magic items, consumables, inventory, character id, character name, character level, character cp, double rewards, guild, noodles, dm double}\n event_inc = 1*(\"Event\" in sessionInfo and sessionInfo[\"Event\"])\n maximumCP = dm[\"CP\"]\n deathChars = []\n playerUpdates = []\n \n # get the collections of characters\n playersCollection = db.players\n guildCollection = db.guilds\n statsCollection = db.stats\n usersCollection = db.users\n \n characterIDs = [p[\"Character ID\"] for p in players.values()]\n userIDs = list(players.keys())\n guildIDs = list(guilds.keys())\n \n userIDs.append(str(dm[\"ID\"]))\n \n # the db entry of every character\n characterDBentries = list(playersCollection.find({\"_id\": {\"$in\": characterIDs}}))\n \n # the db entry of every user\n userDBentries = usersCollection.find({\"User ID\": {\"$in\": userIDs}})\n \n # the db entry of every guild\n guildDBentries = guildCollection.find({\"Name\": {\"$in\": guildIDs}})\n guildDBEntriesDic = {}\n for g in guildDBentries:\n guildDBEntriesDic[g[\"Name\"]] = g\n if g[\"Reputation\"] >= guild_drive_costs[sessionInfo[\"Tier\"]]:\n g[\"Reputation\"] -= guild_drive_costs[sessionInfo[\"Tier\"]]*guilds[g[\"Name\"]][\"Drive\"]\n else:\n guilds[g[\"Name\"]][\"Drive\"] = False\n \n if g[\"Reputation\"] >= 25:\n g[\"Reputation\"] -= 25*guilds[g[\"Name\"]][\"Rewards\"]\n else:\n guilds[g[\"Name\"]][\"Rewards\"] = False\n \n if g[\"Reputation\"] >= 10:\n g[\"Reputation\"] -= 10*guilds[g[\"Name\"]][\"Items\"]\n else:\n guilds[g[\"Name\"]][\"Items\"] = False\n \n userDBEntriesDic = {}\n for u in userDBentries:\n userDBEntriesDic[u[\"User ID\"]] = u\n\n \n gold_modifier = 100\n if \"Gold Modifier\" in sessionInfo:\n gold_modifier = sessionInfo[\"Gold Modifier\"]\n item_rewards = True\n if \"Items\" in sessionInfo:\n item_rewards = sessionInfo[\"Items\"]\n for character in characterDBentries:\n player = players[str(character[\"User ID\"])]\n # this indicates that the character had died\n if player[\"Status\"] == \"Dead\":\n deathChars.append(player)\n \n duration = player[\"CP\"] * 3600\n player[\"Double\"] = False\n guildDouble = False\n playerDouble = False\n dmDouble = False\n\n if not (\"Paused\" in character and character[\"Paused\"]):\n guild_valid =(\"Guild\" in player and \n player[\"Guild\"] in guilds and \n guilds[player[\"Guild\"]][\"Status\"] and\n player[\"CP\"]>= 3 and player['Guild Rank'] > 1)\n guildDouble = (guild_valid and \n guilds[player[\"Guild\"]][\"Rewards\"] and \n player[\"2xR\"])\n \n\n player[\"Double\"] = str(character[\"User ID\"]) in userDBEntriesDic.keys() and \"Double\" in userDBEntriesDic[str(character[\"User ID\"])] and userDBEntriesDic[str(character[\"User ID\"])][\"Double\"] >0\n playerDouble = player[\"Double\"]\n dmDouble = False\n bonusDouble = \"Bonus\" in sessionInfo and sessionInfo[\"Bonus\"]\n \n treasureArray = calculateTreasure(player[\"Level\"], character[\"CP\"] , duration, guildDouble, playerDouble, dmDouble, bonusDouble, gold_modifier)\n \n if(guild_valid and \n guilds[player[\"Guild\"]][\"Items\"] and \n player[\"2xI\"]):\n \n for i in player[\"Double Items\"]:\n if i[0] == \"Magic Items\":\n player[\"Magic Items\"].append(i[1])\n else:\n player[i[0]][\"Add\"].append(i[1])\n player[\"Double Items\"] = []\n \n \n # create a list of all items the character has\n consumableList = character[\"Consumables\"].split(\", \")\n consumablesString = \"\"\n if not item_rewards:\n player[\"Consumables\"][\"Add\"] = []\n player[\"Inventory\"][\"Add\"] = []\n player[\"Magic Items\"] = []\n \n #if we know they didnt have any items, we know that changes could only be additions\n if(character[\"Consumables\"]==\"None\"):\n # turn the list of added items into the new string\n consumablesString = \", \".join(player[\"Consumables\"][\"Add\"])\n else:\n #remove the removed items from the list of original items and then combine the remaining and the new items \n for i in player[\"Consumables\"][\"Remove\"]:\n consumableList.remove(i)\n consumablesString = \", \".join(player[\"Consumables\"][\"Add\"]+consumableList)\n \n # if the string is empty, turn it into none\n consumablesString += \"None\"*(consumablesString==\"\")\n \n # magic items cannot be removed so we only care about addtions\n # if we have no items and no additions, string is None\n \n magicItemString = \"None\"\n if(character[\"Magic Items\"]==\"None\"):\n if(len(player[\"Magic Items\"])==0):\n pass\n else:\n # otherwise it is just the combination of new items\n magicItemString = \", \".join(player[\"Magic Items\"])\n else:\n # otherwise connect up the old and new items\n magicItemString = character[\"Magic Items\"]+(\", \"+ \", \".join(player[\"Magic Items\"]))*(len(player[\"Magic Items\"])>0)\n \n \n # increase the relevant inventory entries and create them if necessary\n for i in player[\"Inventory\"][\"Add\"]:\n if i in character[\"Inventory\"]:\n character[\"Inventory\"][i] += 1\n else:\n character[\"Inventory\"][i] = 1\n \n # decrement the relevant items and delete the entry when necessary\n for i in player[\"Inventory\"][\"Remove\"]:\n character[\"Inventory\"][i] -= 1\n if int(character[\"Inventory\"][i]) <= 0:\n del character[\"Inventory\"][i]\n \n # set up all db values that need to be incremented\n increment = {\"CP\": treasureArray[0], \n \"GP\": treasureArray[2],\n \"Games\": 1,\n \"Event Token\" : event_inc}\n # for every TP tier value that was gained create the increment field\n for k,v in treasureArray[1].items():\n increment[k] = v\n player_set = {\"Consumables\": consumablesString, \n \"Magic Items\": magicItemString, \n \"Inventory\" : character[\"Inventory\"], \n \"Drive\" : []}\n for g in guilds.values():\n if g[\"Drive\"] and player[\"CP\"]>= 3:\n player_set[\"Drive\"]=g[\"Name\"]\n \n charRewards = {'_id': player[\"Character ID\"], \n \"fields\": {\"$unset\": {f\"GID\": 1} ,\"$inc\": increment, \n \"$set\": player_set}}\n if(player[\"Status\"] == \"Dead\"):\n del charRewards[\"fields\"][\"$inc\"][\"Games\"]\n deathDic = {\"inc\": increment.copy(), \"set\": charRewards[\"fields\"][\"$set\"]}\n charRewards[\"fields\"][\"$inc\"] = {\"Games\": 1}\n charRewards[\"fields\"][\"$set\"] = {\"Death\": deathDic}\n playerUpdates.append(charRewards)\n else:\n playerUpdates.append({'_id': player[\"Character ID\"],\n 'fields': {\"$unset\": {f\"GID\": 1} ,\n \"$inc\": {\"Stored\": duration,\n \"Games\": 1,\n \"Event Token\" : event_inc}}})\n dmRewardsList = []\n dm[\"Double\"] = False\n #DM REWARD MATH STARTS HERE\n if(\"Character ID\" in dm):\n \n player = dm\n \n duration = player[\"CP\"] * 3600\n \n \n # the db entry of every character\n character = playersCollection.find_one({\"_id\": dm[\"Character ID\"]})\n player[\"Double\"] = False\n if not (\"Paused\" in character and character[\"Paused\"]):\n charLevel = int(dm['Level'])\n # calculate the tier of the DM character\n dmTierNum= 5\n dmRole = \"Ascended\"\n if charLevel < 5:\n dmRole = 'Junior'\n dmTierNum = 1\n elif charLevel < 11:\n dmRole = 'Journey'\n dmTierNum = 2\n elif charLevel < 17:\n dmRole = 'Elite'\n dmTierNum = 3\n elif charLevel < 20:\n dmRole = 'True'\n dmTierNum = 4\n \n guild_valid =(\"Guild\" in player and \n player[\"Guild\"] in guilds and \n guilds[player[\"Guild\"]][\"Status\"] and\n player[\"CP\"]>= 3 and player['Guild Rank'] > 1)\n guildDouble = (guild_valid and \n guilds[player[\"Guild\"]][\"Rewards\"] and \n player[\"2xR\"])\n \n \n \n player[\"Double\"] = dm[\"ID\"] in userDBEntriesDic.keys() and \"Double\" in userDBEntriesDic[dm[\"ID\"]] and userDBEntriesDic[dm[\"ID\"]][\"Double\"] >0\n playerDouble = player[\"Double\"]\n \n dmDouble = player[\"DM Double\"] and sessionInfo[\"DDMRW\"]\n bonusDouble = \"Bonus\" in sessionInfo and sessionInfo[\"Bonus\"]\n \n treasureArray = calculateTreasure(charLevel, character[\"CP\"], duration, guildDouble, playerDouble, dmDouble, bonusDouble)\n \n \n if(guild_valid and \n guilds[player[\"Guild\"]][\"Items\"] and \n player[\"2xI\"]):\n for i in player[\"Double Items\"]:\n if i[0] == \"Magic Items\":\n player[\"Magic Items\"].append(i[1])\n else:\n player[i[0]][\"Add\"].append(i[1])\n player[\"Double Items\"] = []\n \n \n if not item_rewards:\n player[\"Consumables\"][\"Add\"] = []\n player[\"Inventory\"][\"Add\"] = []\n player[\"Magic Items\"] = []\n \n # create a list of all items the character has\n consumableList = character[\"Consumables\"].split(\", \")\n consumablesString = \"\"\n \n \n #if we know they didnt have any items, we know that changes could only be additions\n if(character[\"Consumables\"]==\"None\"):\n # turn the list of added items into the new string\n consumablesString = \", \".join(player[\"Consumables\"][\"Add\"])\n else:\n #remove the removed items from the list of original items and then combine the remaining and the new items \n for i in player[\"Consumables\"][\"Remove\"]:\n consumableList.remove(i)\n consumablesString = \", \".join(player[\"Consumables\"][\"Add\"]+consumableList)\n \n # if the string is empty, turn it into none\n consumablesString += \"None\"*(consumablesString==\"\")\n \n # magic items cannot be removed so we only care about addtions\n # if we have no items and no additions, string is None\n magicItemString = \"None\"\n if(character[\"Magic Items\"]==\"None\"):\n if(len(player[\"Magic Items\"])==0):\n pass\n else:\n # otherwise it is just the combination of new items\n magicItemString = \", \".join(player[\"Magic Items\"])\n else:\n # otherwise connect up the old and new items\n magicItemString = character[\"Magic Items\"]+(\", \"+ \", \".join(player[\"Magic Items\"]))*(len(player[\"Magic Items\"])>0)\n \n \n \n # increase the relevant inventory entries and create them if necessary\n for i in player[\"Inventory\"][\"Add\"]:\n if i in character[\"Inventory\"]:\n character[\"Inventory\"][i] += 1\n else:\n character[\"Inventory\"][i] = 1\n \n # decrement the relevant items and delete the entry when necessary\n for i in player[\"Inventory\"][\"Remove\"]:\n character[\"Inventory\"][i] -= 1\n if int(character[\"Inventory\"][i]) <= 0:\n del character[\"Inventory\"][i]\n \n # set up all db values that need to be incremented\n increment = {\"CP\": treasureArray[0], \"GP\": treasureArray[2],\"Games\": 1, \"Event Token\": event_inc}\n \n # for every TP tier value that was gained create the increment field\n for k,v in treasureArray[1].items():\n increment[k] = v\n \n player_set = {\"Consumables\": consumablesString, \n \"Magic Items\": magicItemString, \n \"Inventory\" : character[\"Inventory\"], \n \"Drive\" : []}\n\n for g in guilds.values():\n if g[\"Drive\"] and player[\"CP\"] >= 3:\n player_set[\"Drive\"] = g[\"Name\"]\n break\n \n charRewards = {'_id': player[\"Character ID\"], \n \"fields\": {\"$unset\": {f\"GID\": 1},\n \"$inc\": increment, \n \"$set\": player_set}}\n \n playerUpdates.append(charRewards)\n else:\n playerUpdates.append({'_id': player[\"Character ID\"],\n 'fields': {\"$unset\": {f\"GID\": 1},\n \"$inc\": {\"Stored\": duration,\n \"Games\": 1,\n \"Event Token\" : event_inc}}})\n\n hoursPlayed = maximumCP\n # that is the base line of sparkles and noodles gained\n sparklesGained = int(hoursPlayed) // 3\n timerData = list(map(lambda item: UpdateOne({'_id': item['_id']}, item['fields']), playerUpdates))\n players[dm[\"ID\"]] = dm\n guildsData = []\n # if the game received rewards\n if role != \"\": \n # passed in parameter, check if there were guilds involved\n if guilds != list():\n # for every guild in the game\n for g in guildDBEntriesDic.values():\n name = g[\"Name\"] \n gain = 0\n # get the DB record of the guild\n #filter player list by guild\n gPlayers = [p for p in players.values() if \"Guild\" in p and p[\"Guild\"] == name]\n p_count = len(gPlayers) - int(\"Guild\" in dm and dm[\"Guild\"] == name)\n for p in gPlayers:\n gain += p[\"CP\"] // 3\n guilds[name][\"Player Sparkles\"] = gain - sparklesGained*int(\"Guild\" in dm and dm[\"Guild\"] == name)\n guilds[name][\"DM Sparkles\"] = 2*sparklesGained*int(\"Guild\" in dm and dm[\"Guild\"] == name)\n\n gain += sparklesGained*int(\"Guild\" in dm and dm[\"Guild\"] == name)\n \n reputationCost = (20*guilds[name][\"Rewards\"]+10*guilds[name][\"Items\"]+guild_drive_costs[sessionInfo[\"Tier\"]]*guilds[name][\"Drive\"])*guilds[name][\"Status\"]\n if guilds[name][\"Status\"]:\n guildsData.append(UpdateOne({\"Name\": name},\n {\"$inc\": {\"Games\": 1, \"Reputation\": int(gain- reputationCost), \"Total Reputation\": gain}}))\n \n del players[dm[\"ID\"]]\n \n end = sessionInfo[\"End\"]\n start = sessionInfo[\"Start\"]\n \n # Noodles Math\n dmEntry = userDBEntriesDic[dm[\"ID\"]]\n \n if \"DM Time\" not in dmEntry:\n dmEntry[\"DM Time\"] = 0\n if \"Noodles\" not in dmEntry:\n dmEntry[\"Noodles\"] = 0\n noodles = dmEntry[\"Noodles\"]\n duration = totalDuration = end - start\n duration = end - start\n # if duration < 3*3600:\n # duration = 0\n noodlesGained = int((duration + dmEntry[\"DM Time\"])//(3*3600))\n new_dm_time = (duration + dmEntry[\"DM Time\"])%(3*3600)\n noodles += noodlesGained\n try:\n \n # get the stats for the month and create an entry if it doesnt exist yet\n statsIncrement ={\"Games\": 1, \"Playtime\": totalDuration, 'Players': len(players.keys())}\n statsAddToSet = {}\n for name in [g[\"Name\"] for g in guilds.values() if g[\"Status\"]]:\n # Track how many guild quests there were\n statsIncrement[\"Guilds.\"+name+\".GQ\"] = 1\n statsIncrement[\"Guilds.\"+name+\".GQM\"] = 0\n statsIncrement[\"Guilds.\"+name+\".GQDM\"] = 0\n statsIncrement[\"Guilds.\"+name+\".GQNM\"] = 0\n statsIncrement[\"Guilds.\"+name+\".Player Sparkles\"] = guilds[name][\"Player Sparkles\"]\n statsIncrement[\"Guilds.\"+name+\".DM Sparkles\"] = guilds[name][\"DM Sparkles\"]\n # track how many games had a guild memeber with rewards and how many have not\n if guilds[name][\"Player Sparkles\"] > 0: \n statsIncrement[\"Guilds.\"+name+\".GQM\"] = 1\n elif guilds[name][\"DM Sparkles\"] > 0:\n statsIncrement[\"Guilds.\"+name+\".GQDM\"] = 1\n else:\n statsIncrement[\"Guilds.\"+name+\".GQNM\"] = 1\n # Total Number of Games for the Month / Life\n \n # increment or create the stat entry for the DM of the game\n statsIncrement[f\"DM.{dm['ID']}.T{tierNum}\"] = 1\n statsIncrement[f\"T{tierNum}\"] = 1\n statsIncrement[f\"GQ Total\"] = int(any ([g[\"Status\"] for g in guilds.values()]))\n if totalDuration > 10800: #3 hours\n if (tierNum in [0, 1]):\n statsIncrement[f\"DM.{dm['ID']}.Friend\"] = 1\n if (len(guildsData)>0):\n statsIncrement[f\"DM.{dm['ID']}.Guild Fanatic\"] = 1\n for g in guildDBEntriesDic.values():\n if guilds[g[\"Name\"]][\"Status\"]:\n statsIncrement[f\"DM.{dm['ID']}.Guild Fanatic\"] = 1\n statsIncrement[f\"DM.{dm['ID']}.Guilds.{g['Name']}\"] = 1\n \n \n # track a list of unique players\n statsAddToSet = { 'Unique Players': { \"$each\": list([p for p in players.keys()])} }\n \n \n # track playtime and players\n\n\n \n dateyear = datetime.fromtimestamp(start).astimezone(pytz.timezone(timezoneVar)).strftime(\"%b-%y\")\n # update all the other data entries\n # update the DB stats\n statsCollection.update_one({'Date': dateyear}, {\"$set\": {'Date': dateyear}, \"$inc\": statsIncrement, \"$addToSet\": statsAddToSet}, upsert=True)\n statsCollection.update_one({'Life': 1}, {\"$inc\": statsIncrement, \"$addToSet\": statsAddToSet}, upsert=True)\n # update the DM' stats\n \n usersCollection.update_one({'User ID': str(dm[\"ID\"])}, {\"$set\": {'User ID':str(dm[\"ID\"]),'DM Time': new_dm_time}, \"$inc\": {'Games': 1, 'Noodles': noodlesGained, 'Double': -1*dm[\"Double\"]}}, upsert=True)\n playersCollection.bulk_write(timerData)\n \n usersData = list([UpdateOne({'User ID': key}, {'$inc': {'Games': 1, 'Double': -1*item[\"Double\"] }}, upsert=True) for key, item in {character[\"User ID\"] : players[character[\"User ID\"] ] for character in characterDBentries}.items()])\n usersCollection.bulk_write(usersData)\n \n logData.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\" : {\"Status\": \"Approved\"}})\n sessionInfo[\"Status\"]=\"Approved\"\n \n if guildsData != list():\n # do a bulk write for the guild data\n db.guilds.bulk_write(guildsData)\n \n await generateLog(self, ctx, num, sessionInfo=sessionInfo, userDBEntriesDic=userDBEntriesDic, guildDBEntriesDic=guildDBEntriesDic, characterDBentries=characterDBentries)\n \n del players[dm[\"ID\"]]\n game = sessionInfo[\"Game\"]\n for k,p in players.items():\n c = ctx.guild.get_member(int(k))\n if(c):\n try:\n await c.send(f\"The session log for **{game}** has been approved. **{p['Character Name']}** has received their rewards.\")\n except Forbidden as cie:\n await ctx.channel.send(content=f\"{c.mention} has blocked the bot.\")\n dm_text = \"\"\n if(\"Character ID\" in dm):\n dm_text += f\" **{dm['Character Name']}** has received their rewards.\"\n \n c = ctx.guild.get_member(int(dm[\"ID\"]))\n if(c):\n try:\n await c.send(f\"Your session log for **{game}** has been approved.{dm_text}\")\n except Forbidden as cie:\n await ctx.channel.send(content=f\"{c.mention} has blocked the bot.\")\n await ctx.channel.send(\"The session has been approved.\")\n \n except BulkWriteError as bwe:\n print(bwe.details)\n charEmbedmsg = await ctx.channel.send(embed=None, content=\"Uh oh, looks like something went wrong. Please try the timer again.\")\n guild = ctx.guild\n dmUser = ctx.guild.get_member(int(dm[\"ID\"]))\n if dmUser:\n noodleString = \"\"\n dmRoleNames = [r.name for r in dmUser.roles]\n # for the relevant noodle role cut-off check if the user would now qualify for the role and if they do not have it and remove the old role\n noodles_barrier=0\n broken_barrier=0\n noodles_position = -1\n for i in range(len(noodleRoleArray)):\n if noodles >= max(noodles_barrier, 1):\n noodles_position = i\n broken_barrier = max(noodles_barrier, 1)\n noodles_barrier += 10*(i+1)\n if noodles_position >= 0:\n noodle_name = noodleRoleArray[noodles_position]\n if noodle_name not in dmRoleNames:\n noodleRole = get(guild.roles, name = noodle_name)\n await dmUser.add_roles(noodleRole, reason=f\"Hosted {broken_barrier} sessions. This user has {broken_barrier}+ Noodles.\")\n if noodles_position>0:\n remove_role = noodleRoleArray[noodles_position-1]\n if remove_role in dmRoleNames:\n await dmUser.remove_roles(get(guild.roles, name = remove_role))\n\n\n @commands.has_any_role('Mod Friend', 'A d m i n')\n @session.command()\n async def deny(self,ctx, num : int):\n channel = self.bot.get_channel\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n channel = self.bot.get_channel(settingsRecord[str(ctx.guild.id)][\"Sessions\"]) \n \n try:\n editMessage = await channel.fetch_message(num)\n except Exception as e:\n return await ctx.channel.send(\"Log could not be found.\")\n \n if not sessionInfo:\n return await ctx.channel.send(\"Session could not be found.\")\n \n if sessionInfo[\"Status\"] == \"Approved\" or sessionInfo[\"Status\"] == \"Denied\":\n await ctx.channel.send(\"This session has already been processed\")\n return\n if ctx.message.author.id == int(sessionInfo[\"DM\"][\"ID\"]):\n await ctx.channel.send(\"You cannot deny your own log.\")\n return\n if not editMessage or editMessage.author != self.bot.user:\n return await ctx.channel.send(\"Session has no corresponding message in the log channel.\")\n\n sessionLogEmbed = editMessage.embeds[0]\n #dictionary indexed by user id\n players = sessionInfo[\"Players\"] \n # {cp, magic items, consumables, inventory, status, character id, character name, character level, character cp, double rewards, guild, }\n \n \n playerUpdates = [] \n dm = sessionInfo[\"DM\"] \n # {cp, magic items, consumables, inventory, character id, character name, character level, character cp, double rewards, guild, noodles, dm double}\n if \"Character ID\" in dm:\n charRewards = {'_id': dm[\"Character ID\"], \n \"fields\": {\"$unset\": {f\"GID\": 1} }}\n playerUpdates.append(charRewards)\n \n role = sessionInfo[\"Role\"]\n \n # get the collections of characters\n playersCollection = db.players\n\n \n for player in players.values():\n if role != \"\":\n charRewards = {'_id': player[\"Character ID\"], \n \"fields\": {\"$unset\": {f\"GID\": 1} }}\n playerUpdates.append(charRewards)\n \n else:\n # if there were no rewards we only care about the time\n pass\n \n timerData = list(map(lambda item: UpdateOne({'_id': item['_id']}, item['fields']), playerUpdates))\n \n \n try: \n playersCollection.bulk_write(timerData)\n logData.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\" : {\"Status\": \"Denied\"}})\n \n game = sessionInfo[\"Game\"]\n for k,p in players.items():\n c = ctx.guild.get_member(int(k))\n if(c):\n await c.send(f\"The session log for **{game}** has been denied. **{p['Character Name']}** has been cleared.\")\n dm_text = \"\"\n if(\"Character ID\" in dm):\n dm_text += f\" **{dm['Character Name']}** has been cleared.\"\n \n c = ctx.guild.get_member(int(dm[\"ID\"]))\n if(c):\n await c.send(f\"Your session log for **{game}** has been denied.\"+dm_text)\n #logData.delete_one({\"Log ID\": num})\n sessionLogEmbed.set_footer(text=f\"Game ID: {num}\\n❌ Log Denied! Characters have been cleared.\")\n await editMessage.edit(embed=sessionLogEmbed)\n await ctx.channel.send(\"The session has been denied.\")\n except BulkWriteError as bwe:\n print(bwe.details)\n charEmbedmsg = await ctx.channel.send(embed=None, content=\"Uh oh, looks like something went wrong. Please try the timer again.\")\n #except Exception as e:\n # print ('MONGO ERROR: ' + str(e))\n # charEmbedmsg = await ctx.channel.send(embed=None, content=\"Uh oh, looks like something went wrong. Please try the timer again.\")\n\n\n @session.command()\n async def denyGuild(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Status\", False, 0)\n @session.command()\n async def approveGuild(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Status\", True, 0)\n \n #@session.command()\n async def denyRewards(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Rewards\", False, 0)\n #@session.command()\n async def approveRewards(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Rewards\", True, 3)\n \n \n #@session.command()\n async def denyDrive(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Drive\", False, 0, unique = False)\n #@session.command()\n async def approveDrive(self, ctx, num : int, *, guilds):\n await self.guildPermission(ctx, num, \"Drive\", True, 0, unique = True)\n \n async def guildPermission(self, ctx, num : int, target, goal, min_members, unique = False):\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"):\n mod = \"Mod Friend\" in [r.name for r in ctx.author.roles]\n if( (str(ctx.author.id) == sessionInfo[\"DM\"][\"ID\"]) or mod):\n # if the game received rewards\n if len(sessionInfo[\"Guilds\"].keys()) > 0: \n players = sessionInfo[\"Players\"]\n players[sessionInfo[\"DM\"][\"ID\"]] = sessionInfo[\"DM\"]\n guilds = sessionInfo[\"Guilds\"]\n if unique and ((len(ctx.message.channel_mentions) > 1) or any([g[\"Drive\"] for g in guilds.values()])):\n await ctx.channel.send(\"The Recruitment Drive Guild Boon can only be used by one guild per guild quest.\")\n return\n guild_dic = {}\n for g in guilds.values():\n guild_dic[g[\"Mention\"]] = g\n err_message = \"\"\n for guildChannel in ctx.message.channel_mentions:\n \n m = guildChannel.mention\n # filter player list by guild\n gPlayers = [p for p in players.values() if \"Guild\" in p and \n p[\"Guild\"] in guilds and\n guilds[p[\"Guild\"]][\"Mention\"] == m\n and p[\"CP\"]>= 3 and p['Guild Rank'] > 1]\n if(len(gPlayers) >= min_members):\n if guildChannel.mention in guild_dic:\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {\"Guilds.\"+guild_dic[m][\"Name\"]+\".\"+target: goal}})\n except BulkWriteError as bwe:\n print(e)\n else:\n err_message += m +\" not found in game.\\n\"\n else:\n err_message += \"There needs to be a minimum of three guild members from \"+ m +\" in order to activate its Guild Boons.\"\n if err_message != \"\":\n await ctx.channel.send(err_message)\n else:\n await ctx.channel.send(\"Session updated.\")\n await generateLog(self, ctx, num)\n else:\n await ctx.channel.send(\"There were no guilds in the session.\")\n else:\n await ctx.channel.send(\"You do not have the permissions to perform this change to the session.\")\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n @session.command()\n async def addGuilds(self, ctx, num : int, *, guilds):\n \n mod = \"Mod Friend\" in [r.name for r in ctx.author.roles]\n if(mod):\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"):\n guilds = sessionInfo[\"Guilds\"]\n guild_dic = {}\n for g in guilds.values():\n guild_dic[g[\"Mention\"]] = g\n err_message = \"\"\n for guildChannel in ctx.message.channel_mentions:\n \n # get the DB record of the guild\n gRecord = db.guilds.find_one({\"Channel ID\": str(guildChannel.id)})\n if not gRecord:\n continue\n guildDBEntry = {}\n guildDBEntry[\"Status\"] = True\n guildDBEntry[\"Rewards\"] = False\n guildDBEntry[\"Items\"] = False\n guildDBEntry[\"Drive\"] = False\n guildDBEntry[\"Mention\"] = guildChannel.mention\n guildDBEntry[\"Name\"] = gRecord[\"Name\"]\n \n \n mention = guildChannel.mention\n if mention not in guild_dic:\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {\"Guilds.\"+gRecord[\"Name\"]: guildDBEntry}})\n except BulkWriteError as bwe:\n print(e)\n else:\n err_message += mention +\" already found in game.\\n\"\n \n if err_message != \"\":\n await ctx.channel.send(err_message)\n await ctx.channel.send(\"Session updated.\")\n await generateLog(self, ctx, num)\n\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n @commands.has_any_role('Mod Friend', 'Admins') \n @session.command()\n async def denyBonus(self, ctx, num : int):\n await self.session_set(ctx, num, \"Bonus\", False)\n \n @commands.has_any_role('Mod Friend', 'Admins')\n @session.command()\n async def approveBonus(self, ctx, num : int):\n await self.session_set(ctx, num, \"Bonus\", True)\n \n @commands.has_any_role('Mod Friend', 'Admins') \n @session.command()\n async def denyDDMRW(self, ctx, num : int):\n await self.session_set(ctx, num, \"DDMRW\", False)\n \n @commands.has_any_role('Mod Friend', 'Admins')\n @session.command()\n async def approveDDMRW(self, ctx, num : int):\n await self.session_set(ctx, num, \"DDMRW\", True)\n \n @commands.has_any_role('Mod Friend', 'Admins') \n @session.command()\n async def denyEvent(self, ctx, num : int):\n await self.session_set(ctx, num, \"Event\", False)\n \n \n @commands.has_any_role('Mod Friend', 'Admins') \n @session.command()\n async def denyItems(self, ctx, num : int):\n await self.session_set(ctx, num, \"Items\", False)\n \n @commands.has_any_role('Mod Friend', 'Admins') \n @session.command()\n async def approveItems(self, ctx, num : int):\n await self.session_set(ctx, num, \"Items\", True)\n \n @commands.has_any_role('Mod Friend', 'Admins')\n @session.command()\n async def approveEvent(self, ctx, num : int):\n await self.session_set(ctx, num, \"Event\", True)\n @commands.has_any_role('Mod Friend', 'Admins')\n @session.command()\n async def pending(self, ctx, num : int):\n await self.session_set(ctx, num, \"Status\", \"Pending\")\n \n async def session_set(self, ctx, num : int, target, goal):\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"):\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {target: goal}})\n except BulkWriteError as bwe:\n print(e)\n await ctx.channel.send(\"Session updated.\")\n await generateLog(self, ctx, num)\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n @session.group()\n async def ddmrw(self, ctx):\t\n pass\n \n @ddmrw.command()\n async def optout(self, ctx, num :int):\n await self.ddmrwOpt(ctx, num, False)\n @ddmrw.command()\n async def optin(self, ctx, num : int):\n await self.ddmrwOpt(ctx, num, True)\n \n # allows DMs to opt in or out of DDMRW\n async def ddmrwOpt(self, ctx, num : int, goal):\n logData =db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"):\n if (str(ctx.author.id) == sessionInfo[\"DM\"][\"ID\"] or \"Mod Friend\" in [r.name for r in ctx.author.roles] and sessionInfo[\"DDMRW\"]):\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {\"DM.DM Double\": goal}})\n await generateLog(self, ctx, num)\n except BulkWriteError as bwe:\n print(bwe)\n else:\n await ctx.channel.send(\"You were not the DM of that session or it was not DDMRW.\")\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n #@session.command()\n async def optout2xR(self, ctx, num : int):\n await self.userOpt(ctx, num, \"2xR\", False)\n #@session.command()\n async def optin2xR(self, ctx, num : int):\n await self.userOpt(ctx, num, \"2xR\", True)\n \n #@session.command()\n async def optout2xI(self, ctx, num : int):\n await self.userOpt(ctx, num, \"2xI\", False)\n #@session.command()\n async def optin2xI(self, ctx, num : int):\n await self.userOpt(ctx, num, \"2xI\", True)\n \n async def userOpt(self, ctx, num : int, target, goal):\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"):\n if sessionInfo[\"Role\"] != \"\": \n players = sessionInfo[\"Players\"]\n players[sessionInfo[\"DM\"][\"ID\"]] = sessionInfo[\"DM\"]\n user_id = str(ctx.author.id)\n if user_id in players.keys():\n if \"Guild\" in players[user_id] and players[user_id][\"Guild\"] in sessionInfo[\"Guilds\"].keys():\n player_target = f\"Players.{ctx.author.id}.\"\n if user_id == sessionInfo[\"DM\"][\"ID\"]:\n player_target = \"DM.\"\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {player_target+target: goal}})\n except BulkWriteError as bwe:\n print(bwe)\n else:\n await ctx.channel.send(\"Session updated.\")\n await generateLog(self, ctx, num) \n else:\n await ctx.channel.send(\"Your character's guild is not valid for this session.\")\n \n else:\n await ctx.channel.send(\"You were not part of the session\")\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n @session.command()\n async def setGold(self, ctx, num : int, gold_modifier : int):\n if gold_modifier < 0 or gold_modifier > 100:\n await ctx.channel.send(f\"{gold_modifier} is an invalid percentage.\")\n return\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if( sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\"): # True):#\n mod = \"Mod Friend\" in [r.name for r in ctx.author.roles]\n if( (str(ctx.author.id) == sessionInfo[\"DM\"][\"ID\"]) or mod):\n try:\n db.logdata.update_one({\"_id\": sessionInfo[\"_id\"]}, {\"$set\": {\"Gold Modifier\": gold_modifier}})\n except BulkWriteError as bwe:\n print(e)\n \n await ctx.channel.send(\"Session updated.\")\n await generateLog(self, ctx, num)\n else:\n await ctx.channel.send(\"You do not have the permissions to perform this change to the session.\")\n else:\n await ctx.channel.send(\"This session has already been processed\")\n else:\n await ctx.channel.send(\"The session could not be found, please double check your number or if the session has already been approved.\")\n \n \n @commands.has_any_role('Mod Friend', 'A d m i n')\n @session.command()\n async def genLog(self, ctx, num : int):\n logData = db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if(sessionInfo):\n await generateLog(self, ctx, num) \n await ctx.channel.send(\"Log has been generated.\")\n \n else:\n await ctx.channel.send(\"The session could not be found, please double check your number.\")\n \n @session.command()\n async def log(self, ctx, num : int, *, editString=\"\"):\n # The real Bot\n botUser = self.bot.user\n # Logs channel \n channel = self.bot.get_channel(settingsRecord[str(ctx.guild.id)][\"Sessions\"]) \n editMessage = await channel.fetch_message(num)\n\n async with channel.typing():\n if not editMessage or editMessage.author != self.bot.user:\n delMessage = await ctx.channel.send(content=f\"I couldn't find your session with ID `{num}`. Please try again. I will delete your message and this message in 10 seconds.\\n\\n:warning: **DO NOT DELETE YOUR OWN MESSAGE.** :warning\")\n await asyncio.sleep(10) \n await delMessage.delete()\n await ctx.message.delete() \n return\n\n\n logData =db.logdata\n sessionInfo = logData.find_one({\"Log ID\": int(num)})\n if( sessionInfo):\n if (str(ctx.author.id) == sessionInfo[\"DM\"][\"ID\"] or \n \"Mod Friend\" in [r.name for r in ctx.author.roles]):\n pass\n \n else:\n await ctx.channel.send(\"You were not the DM of that session and cannot edit it.\")\n return \n else:\n await ctx.channel.send(\"The session could not be found. Please double check your number or if the session has already been approved.\")\n return\n sessionLogEmbed = editMessage.embeds[0]\n\n if sessionInfo[\"Status\"] != \"Approved\" and sessionInfo[\"Status\"] != \"Denied\":\n summaryIndex = sessionLogEmbed.description.find('Summary**')\n sessionLogEmbed.description = sessionLogEmbed.description[:summaryIndex]+\"Summary**\\n\" + editString+\"\\n\"\n else:\n sessionLogEmbed.description += \"\\n\"+editString\n try:\n await editMessage.edit(embed=sessionLogEmbed)\n except Exception as e:\n delMessage = await ctx.channel.send(content=f\"The maximum length of the session log summary is 2048 symbols. Please reduce the length of your summary.\")\n else:\n try:\n delMessage = await ctx.channel.send(content=f\"I've edited the summary for quest #{num}.\\n```{editString}```\\nPlease double-check that the edit is correct. I will now delete your message and this one in 30 seconds.\")\n except Exception as e:\n delMessage = await ctx.channel.send(content=f\"I've edited the summary for quest #{num}.\\nPlease double-check that the edit is correct. I will now delete your message and this one in 30 seconds.\")\n \n await asyncio.sleep(30) \n try:\n await ctx.message.delete()\n except Exception as e:\n pass\n await delMessage.delete()\n \nasync def setup(bot):\n await bot.add_cog(Log(bot))","sub_path":"cogs/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":66760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"287631082","text":"import numpy as np\nimport sys\nfrom scipy import ndimage as im \nfrom scipy import misc\nimport colorsys\n\ntargetR=255\ntargetG=0\ntargetB=0\ncenterR=0\ncenterG=255\ncenterB=0\nwidth=640\nheight=480\nminOrangeH=7\nmaxOrangeH=35\n\ndef is_orange(red, green, blue):\n hue, saturation, value = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0)\n hue = hue*180\n saturation = saturation*100\n value = value*100\n if(hueminOrangeH and saturation>70 and value>70):\n return 1\n else:\n return 0\n\ndef mark_object(x, y, obj):\n if(x>=0 and x=0 and ymax_size):\n max_size=size_counter[i]\n biggest_obj=i+1\n\nprint(biggest_obj)\nprint(max_size)\n\n#find center of largest object\ntotalX=0\ntotalY=0\nnum_pixels=0\nfor y in range(height):\n for x in range(width):\n if(objects[y][x]==biggest_obj):\n totalX+=x\n totalY+=y\n num_pixels+=1\n\naverageX = (int)(totalX/num_pixels)\naverageY = (int)(totalY/num_pixels)\nprint(averageX)\nprint(averageY)\n\n#mark center\nfor x in range(width):\n out_image[averageY][x][0]=centerR\n out_image[averageY][x][1]=centerG\n out_image[averageY][x][2]=centerB\nfor y in range(height):\n out_image[y][averageX][0]=centerR\n out_image[y][averageX][1]=centerG\n out_image[y][averageX][2]=centerB\n\nmisc.imsave('output.png', out_image)\nprint('DONE')\n\nif(averageX > width/2):\n print('Turn Left')\nelif(averageX < width/2):\n print('Turn Right')\nelse:\n if(averageY < height):\n print('Move Forward')\n \n","sub_path":"object_detection/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"612640263","text":"#\n# LSST Data Management System\n# Copyright 2008, 2009, 2010 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\nimport math\nimport unittest\n\nimport numpy as np\n\nimport lsst.utils.tests\nimport lsst.daf.base as dafBase\nimport lsst.pex.exceptions as pexExcept\nimport lsst.afw.image as afwImage\nimport lsst.afw.image.utils as imageUtils\nfrom lsst.afw.cameraGeom.testUtils import DetectorWrapper\n\n# Set to True to display things in ds9.\ndisplay = False\n\n\nclass CalibTestCase(lsst.utils.tests.TestCase):\n def setUp(self):\n self.calib = afwImage.Calib()\n self.detector = DetectorWrapper().detector\n\n def tearDown(self):\n del self.calib\n del self.detector\n\n def testPhotom(self):\n \"\"\"Test the zero-point information\"\"\"\n\n flux, fluxErr = 1000.0, 10.0\n flux0, flux0Err = 1e12, 1e10\n self.calib.setFluxMag0(flux0)\n\n self.assertEqual(flux0, self.calib.getFluxMag0()[0])\n self.assertEqual(0.0, self.calib.getFluxMag0()[1])\n self.assertEqual(22.5, self.calib.getMagnitude(flux))\n # Error just in flux\n self.assertAlmostEqual(self.calib.getMagnitude(flux, fluxErr)[1],\n 2.5/math.log(10)*fluxErr/flux)\n # Error just in flux0\n self.calib.setFluxMag0(flux0, flux0Err)\n self.assertEqual(flux0Err, self.calib.getFluxMag0()[1])\n self.assertAlmostEqual(self.calib.getMagnitude(flux, 0)[1],\n 2.5/math.log(10)*flux0Err/flux0)\n\n self.assertAlmostEqual(flux0, self.calib.getFlux(0))\n self.assertAlmostEqual(flux, self.calib.getFlux(22.5))\n\n # I don't know how to test round-trip if fluxMag0 is significant\n # compared to fluxErr\n self.calib.setFluxMag0(flux0, flux0 / 1e6)\n for fluxErr in (flux / 1e2, flux / 1e4):\n mag, magErr = self.calib.getMagnitude(flux, fluxErr)\n self.assertAlmostEqual(flux, self.calib.getFlux(mag, magErr)[0])\n self.assertLess(\n abs(fluxErr - self.calib.getFlux(mag, magErr)[1]), 1.0e-4)\n\n # Test context manager; shouldn't raise an exception within the block,\n # should outside\n with imageUtils.CalibNoThrow():\n self.assertTrue(np.isnan(self.calib.getMagnitude(-50.0)))\n with self.assertRaises(pexExcept.DomainError):\n self.calib.getMagnitude(-50.0)\n\n def testPhotomMulti(self):\n self.calib.setFluxMag0(1e12, 1e10)\n flux, fluxErr = 1000.0, 10.0\n num = 5\n\n # Result assumed to be true: tested elsewhere\n mag, magErr = self.calib.getMagnitude(flux, fluxErr)\n\n fluxList = np.array([flux for i in range(num)], dtype=float)\n fluxErrList = np.array([fluxErr for i in range(num)], dtype=float)\n\n magList = self.calib.getMagnitude(fluxList)\n for m in magList:\n self.assertEqual(m, mag)\n\n mags, magErrs = self.calib.getMagnitude(fluxList, fluxErrList)\n\n for m, dm in zip(mags, magErrs):\n self.assertEqual(m, mag)\n self.assertEqual(dm, magErr)\n\n # Result assumed to be true: tested elsewhere\n flux, fluxErr = self.calib.getFlux(mag, magErr)\n\n fluxList = self.calib.getFlux(magList)\n for f in fluxList:\n self.assertEqual(f, flux)\n\n fluxes = self.calib.getFlux(mags, magErrs)\n for f, df in zip(fluxes[0], fluxes[1]):\n self.assertAlmostEqual(f, flux)\n self.assertAlmostEqual(df, fluxErr)\n\n def testCtorFromMetadata(self):\n \"\"\"Test building a Calib from metadata\"\"\"\n\n flux0, flux0Err = 1e12, 1e10\n flux, fluxErr = 1000.0, 10.0\n\n metadata = dafBase.PropertySet()\n metadata.add(\"FLUXMAG0\", flux0)\n metadata.add(\"FLUXMAG0ERR\", flux0Err)\n\n self.calib = afwImage.Calib(metadata)\n\n self.assertEqual(flux0, self.calib.getFluxMag0()[0])\n self.assertEqual(flux0Err, self.calib.getFluxMag0()[1])\n self.assertEqual(22.5, self.calib.getMagnitude(flux))\n # Error just in flux\n self.calib.setFluxMag0(flux0, 0)\n\n self.assertAlmostEqual(self.calib.getMagnitude(flux, fluxErr)[1],\n 2.5/math.log(10)*fluxErr/flux)\n\n # Check that we can clean up metadata\n afwImage.stripCalibKeywords(metadata)\n self.assertEqual(len(metadata.names()), 0)\n\n def testCalibEquality(self):\n self.assertEqual(self.calib, self.calib)\n # using assertFalse to directly test != operator\n self.assertFalse(self.calib != self.calib)\n\n calib2 = afwImage.Calib()\n calib2.setFluxMag0(1200)\n\n self.assertNotEqual(calib2, self.calib)\n\n def testCalibFromCalibs(self):\n \"\"\"Test creating a Calib from an array of Calibs\"\"\"\n mag0, mag0Sigma = 1.0, 0.01\n\n calibs = []\n ncalib = 3\n for i in range(ncalib):\n calib = afwImage.Calib()\n calib.setFluxMag0(mag0, mag0Sigma)\n\n calibs.append(calib)\n\n ocalib = afwImage.Calib(calibs)\n # the following is surely incorrect; see DM-7619\n self.assertEqual(ocalib.getFluxMag0(), (0.0, 0.0))\n\n # Check that we can only merge Calibs with the same fluxMag0 values\n calibs[0].setFluxMag0(1.001*mag0, mag0Sigma)\n with self.assertRaises(pexExcept.InvalidParameterError):\n afwImage.Calib(calibs)\n\n def testCalibNegativeFlux(self):\n \"\"\"Check that we can control if negative fluxes raise exceptions\"\"\"\n self.calib.setFluxMag0(1e12)\n\n with self.assertRaises(pexExcept.DomainError):\n self.calib.getMagnitude(-10)\n with self.assertRaises(pexExcept.DomainError):\n self.calib.getMagnitude(-10, 1)\n\n afwImage.Calib.setThrowOnNegativeFlux(False)\n mags = self.calib.getMagnitude(-10)\n self.assertTrue(np.isnan(mags))\n mags = self.calib.getMagnitude(-10, 1)\n self.assertTrue(np.isnan(mags[0]))\n self.assertTrue(np.isnan(mags[1]))\n\n afwImage.Calib.setThrowOnNegativeFlux(True)\n\n # Re-check that we raise after resetting ThrowOnNegativeFlux.\n with self.assertRaises(pexExcept.DomainError):\n self.calib.getMagnitude(-10)\n with self.assertRaises(pexExcept.DomainError):\n self.calib.getMagnitude(-10, 1)\n\n\ndef defineSdssFilters(testCase):\n \"\"\"Initialise filters as used for our tests\"\"\"\n imageUtils.resetFilters()\n wavelengths = dict()\n testCase.aliases = dict(u=[], g=[], r=[], i=[], z=['zprime', \"z'\"])\n for name, lambdaEff in (('u', 355.1),\n ('g', 468.6),\n ('r', 616.5),\n ('i', 748.1),\n ('z', 893.1)):\n wavelengths[name] = lambdaEff\n imageUtils.defineFilter(name, lambdaEff, alias=testCase.aliases[name])\n return wavelengths\n\n\nclass ColorTestCase(lsst.utils.tests.TestCase):\n def setUp(self):\n defineSdssFilters(self)\n\n def testCtor(self):\n afwImage.Color()\n afwImage.Color(1.2)\n\n def testLambdaEff(self):\n f = afwImage.Filter(\"g\")\n g_r = 1.2\n c = afwImage.Color(g_r)\n\n # XXX Not a real implementation!\n self.assertEqual(c.getLambdaEff(f), 1000*g_r)\n\n def testIsIndeterminate(self):\n \"\"\"Test that a default-constructed Color tests True, but ones with a g-r value test False\"\"\"\n self.assertTrue(afwImage.Color().isIndeterminate())\n self.assertFalse(afwImage.Color(1.2).isIndeterminate())\n\n\nclass FilterTestCase(lsst.utils.tests.TestCase):\n def setUp(self):\n # Initialise our filters\n # Start by forgetting that we may already have defined filters\n wavelengths = defineSdssFilters(self)\n self.filters = tuple(sorted(wavelengths.keys()))\n self.g_lambdaEff = [lambdaEff for name,\n lambdaEff in wavelengths.items() if name == \"g\"][0] # for tests\n\n def defineFilterProperty(self, name, lambdaEff, force=False):\n return afwImage.FilterProperty(name, lambdaEff, force=force)\n\n def testListFilters(self):\n self.assertEqual(afwImage.Filter.getNames(), list(self.filters))\n\n def testCtorFromMetadata(self):\n \"\"\"Test building a Filter from metadata\"\"\"\n\n metadata = dafBase.PropertySet()\n metadata.add(\"FILTER\", \"g\")\n\n f = afwImage.Filter(metadata)\n self.assertEqual(f.getName(), \"g\")\n # Check that we can clean up metadata\n afwImage.stripFilterKeywords(metadata)\n self.assertEqual(len(metadata.names()), 0)\n\n badFilter = \"rhl\" # an undefined filter\n metadata.add(\"FILTER\", badFilter)\n # Not defined\n with self.assertRaises(pexExcept.NotFoundError):\n afwImage.Filter(metadata)\n\n # Force definition\n f = afwImage.Filter(metadata, True)\n self.assertEqual(f.getName(), badFilter) # name is correctly defined\n\n def testFilterEquality(self):\n \"\"\"Test a \"g\" filter comparison\"\"\"\n f = afwImage.Filter(\"g\")\n g = afwImage.Filter(\"g\")\n\n self.assertEqual(f, g)\n\n f = afwImage.Filter() # the unknown filter\n self.assertNotEqual(f, f) # ... doesn't equal itself\n\n def testFilterProperty(self):\n \"\"\"Test properties of a \"g\" filter\"\"\"\n f = afwImage.Filter(\"g\")\n # The properties of a g filter\n g = afwImage.FilterProperty.lookup(\"g\")\n\n self.assertEqual(f.getName(), \"g\")\n self.assertEqual(f.getId(), 1)\n self.assertEqual(f.getFilterProperty().getLambdaEff(),\n self.g_lambdaEff)\n self.assertEqual(f.getFilterProperty(),\n self.defineFilterProperty(\"gX\", self.g_lambdaEff, force=True))\n self.assertEqual(g.getLambdaEff(), self.g_lambdaEff)\n\n def testLambdaMinMax(self):\n \"\"\"Test additional properties for minimum and maximum wavelength for a filter.\"\"\"\n filt = afwImage.Filter(\"g\")\n # LambdaMin and LambdaMax are undefined for the test SDSS filter, and should return nan\n self.assertTrue(np.isnan(filt.getFilterProperty().getLambdaMin()))\n self.assertTrue(np.isnan(filt.getFilterProperty().getLambdaMax()))\n lambdaEff = 476.31\n lambdaMin = 405\n lambdaMax = 552\n imageUtils.defineFilter(\"gNew\", lambdaEff, lambdaMin=lambdaMin, lambdaMax=lambdaMax)\n filtNew = afwImage.Filter(\"gNew\")\n self.assertEqual(lambdaMin, filtNew.getFilterProperty().getLambdaMin())\n self.assertEqual(lambdaMax, filtNew.getFilterProperty().getLambdaMax())\n\n def testFilterAliases(self):\n \"\"\"Test that we can provide an alias for a Filter\"\"\"\n for name0 in self.aliases:\n f0 = afwImage.Filter(name0)\n self.assertEqual(f0.getCanonicalName(), name0)\n self.assertEqual(sorted(f0.getAliases()),\n sorted(self.aliases[name0]))\n\n for name in self.aliases[name0]:\n f = afwImage.Filter(name)\n self.assertEqual(sorted(f.getAliases()),\n sorted(self.aliases[name0]))\n self.assertEqual(f.getId(), f0.getId())\n self.assertEqual(f.getName(), name)\n self.assertEqual(afwImage.Filter(f.getId()).getName(), name0)\n self.assertEqual(f.getCanonicalName(), name0)\n self.assertNotEqual(f.getCanonicalName(), name)\n self.assertEqual(f.getFilterProperty().getLambdaEff(),\n f0.getFilterProperty().getLambdaEff())\n\n def testReset(self):\n \"\"\"Test that we can reset filter IDs and properties if needs be\"\"\"\n g = afwImage.FilterProperty.lookup(\"g\")\n\n # Can we add a filter property?\n with self.assertRaises(pexExcept.RuntimeError):\n self.defineFilterProperty(\"g\", self.g_lambdaEff + 10)\n # should not raise\n self.defineFilterProperty(\"g\", self.g_lambdaEff + 10, True)\n self.defineFilterProperty(\"g\", self.g_lambdaEff, True)\n\n # Can we redefine properties?\n with self.assertRaises(pexExcept.RuntimeError):\n # changing definition is not allowed\n self.defineFilterProperty(\"g\", self.g_lambdaEff + 10)\n\n # identical redefinition is allowed\n self.defineFilterProperty(\"g\", self.g_lambdaEff)\n\n # OK if Id's the same\n afwImage.Filter.define(g, afwImage.Filter(\"g\").getId())\n # AUTO will assign the same ID\n afwImage.Filter.define(g, afwImage.Filter.AUTO)\n\n # different ID\n with self.assertRaises(pexExcept.RuntimeError):\n afwImage.Filter.define(g, afwImage.Filter(\"g\").getId() + 10)\n\n def testUnknownFilter(self):\n \"\"\"Test that we can define, but not use, an unknown filter\"\"\"\n badFilter = \"rhl\" # an undefined filter\n with self.assertRaises(pexExcept.NotFoundError):\n afwImage.Filter(badFilter)\n # Force definition\n f = afwImage.Filter(badFilter, True)\n self.assertEqual(f.getName(), badFilter) # name is correctly defined\n\n # can't use Filter f\n with self.assertRaises(pexExcept.NotFoundError):\n f.getFilterProperty().getLambdaEff()\n\n # Now define badFilter\n lambdaEff = 666.0\n self.defineFilterProperty(badFilter, lambdaEff)\n\n # but now we can\n self.assertEqual(f.getFilterProperty().getLambdaEff(), lambdaEff)\n\n # Check that we didn't accidently define the unknown filter\n with self.assertRaises(pexExcept.NotFoundError):\n afwImage.Filter().getFilterProperty().getLambdaEff()\n\n\nclass MemoryTester(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/test_color.py","file_name":"test_color.py","file_ext":"py","file_size_in_byte":14644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"12710862","text":"#!/usr/bin/python\n\nimport os\nimport mmap\nimport time\nimport smbus\n\n# ===========================================================================\n# Based on https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code\n# Copyright (c) 2012-2013 Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries. All rights reserved.\n# ===========================================================================\n\nclass I2C(object):\n __BLOCK_SIZE = 4096\n __BCM2708_PERI_BASE = 0x20000000 # Base address of peripheral registers\n __GPIO_BASE = (__BCM2708_PERI_BASE + 0x00200000) # Address of GPIO registers\n __GPFSEL0 = 0x0000 # Function select 0\n __GPFSEL2 = 0x0008 # Function select 2\n __GPPUD = 0x0094 # GPIO Pin Pull-up/down Enable\n __GPPUDCLK0 = 0x0098 # GPIO Pin Pull-up/down Enable Clock 0\n __GPIO_PUD_OFF = 0b00 # Off - disable pull-up/down\n __GPIO_PUD_UP = 0b10 # Enable Pull Up control\n\n\n @staticmethod\n def _piRevision():\n \"Gets the version number of the Raspberry Pi board\"\n # Courtesy quick2wire-python-api\n # https://github.com/quick2wire/quick2wire-python-api\n try:\n with open('/proc/cpuinfo','r') as f:\n for line in f:\n if line.startswith('Revision'):\n return 1 if line.rstrip()[-1] in ['1','2'] else 2\n except:\n return 0\n\n @classmethod\n def defaultBusNumber(cls):\n \"Returns the default I2C bus number /dev/i2c#\"\n return 0 if cls._piRevision() == 1 else 1\n\n @classmethod\n def pinoutConfiguredBuses(cls):\n if cls._piRevision() == 1:\n return [cls.defaultBusNumber()] # this is not 100% correct - I guess you can change the pin configuration on a revision 1 board, too\n\n mf = os.open(\"/dev/mem\", os.O_RDWR | os.O_SYNC)\n memory = mmap.mmap(mf, cls.__BLOCK_SIZE, mmap.MAP_SHARED, \n mmap.PROT_READ | mmap.PROT_WRITE, offset=cls.__GPIO_BASE)\n os.close(mf)\n\n bus_numbers = []\n\n # Read function select registers\n # GPFSEL0 -- GPIO 0,1 I2C0 GPIO 2,3 I2C1\n memory.seek(cls.__GPFSEL0)\n reg0 = int.from_bytes(memory.read(4), byteorder='little')\n\n # GPFSEL0 bits --> x[20] SCL1[3] SDA1[3] x[6]\n # GPIO3 GPIO2\n reg0_mask = 0b00000000000000000000111111000000 \n reg0_conf = 0b00000000000000000000100100000000\n if reg0 & reg0_mask == reg0_conf:\n bus_numbers.append(1)\n\n\n # GPFSEL2 -- GPIO 28,29 I2C0\n memory.seek(cls.__GPFSEL2)\n reg2 = int.from_bytes(memory.read(4), byteorder='little')\n\n # GPFSEL2 bits --> x[2] SCL0[3] SDA0[3] x[24]\n # GPIO29 GPIO28\n reg2_mask = 0b00111111000000000000000000000000 \n reg2_conf = 0b00100100000000000000000000000000\n if reg2 & reg2_mask == reg2_conf:\n bus_numbers.append(0)\n\n memory.close()\n\n return bus_numbers\n\n @classmethod\n def configurePinouts(cls, logger=None):\n if cls._piRevision() < 2:\n raise RuntimeError(\"Raspberry Pi Rev 2 or greater required.\")\n\n # Use /dev/mem to gain access to peripheral registers\n mf = os.open(\"/dev/mem\", os.O_RDWR | os.O_SYNC)\n memory = mmap.mmap(mf, cls.__BLOCK_SIZE, mmap.MAP_SHARED, \n mmap.PROT_READ | mmap.PROT_WRITE, offset=cls.__GPIO_BASE)\n # can close the file after we have mmap\n os.close(mf)\n\n # each 32 bit register controls the functions of 10 pins, each 3 bit, starting at the LSB\n # 000 = input\n # 100 = alt function 0\n\n # Read function select registers\n # GPFSEL0 -- GPIO 0,1 I2C0 GPIO 2,3 I2C1\n memory.seek(cls.__GPFSEL0)\n reg0 = int.from_bytes(memory.read(4), byteorder='little')\n\n # GPFSEL0 bits --> x[20] SCL1[3] SDA1[3] \n # GPIO3 GPIO2 GPIO1 GPIO0\n reg0_mask = 0b00000000000000000000111111111111 \n reg0_conf = 0b00000000000000000000100100000000\n if reg0 & reg0_mask != reg0_conf:\n if logger is not None:\n logger.info(\"register 0 configuration of I2C0 not correct. Updating.\")\n reg0 = (reg0 & ~reg0_mask) | reg0_conf\n memory.seek(cls.__GPFSEL0)\n memory.write(reg0.to_bytes(4, byteorder='little'))\n\n\n # GPFSEL2 -- GPIO 28,29 I2C0\n memory.seek(cls.__GPFSEL2)\n reg2 = int.from_bytes(memory.read(4), byteorder='little')\n\n # GPFSEL2 bits --> x[2] SCL0[3] SDA0[3] x[24]\n # GPIO29 GPIO28\n reg2_mask = 0b00111111000000000000000000000000 \n reg2_conf = 0b00100100000000000000000000000000\n if reg2 & reg2_mask != reg2_conf:\n if logger is not None:\n logger.info(\"register 2 configuration of I2C0 not correct. Updating.\")\n reg2 = (reg2 & ~reg2_mask) | reg2_conf\n memory.seek(cls.__GPFSEL2)\n memory.write(reg2.to_bytes(4, byteorder=\"little\"))\n\n # Configure pull up resistors for GPIO28 and GPIO29\n def configure_internal_pull_up_resistor(pin):\n memory.seek(cls.__GPPUD)\n memory.write(cls.__GPIO_PUD_UP.to_bytes(4, byteorder=\"little\"))\n time.sleep(10e-6)\n\n memory.seek(cls.__GPPUDCLK0)\n memory.write((1 << pin).to_bytes(4, byteorder=\"little\"))\n time.sleep(10e-6)\n\n memory.seek(cls.__GPPUD)\n memory.write(cls.__GPIO_PUD_OFF.to_bytes(4, byteorder=\"little\"))\n\n memory.seek(cls.__GPPUDCLK0)\n memory.write((0 << pin).to_bytes(4, byteorder=\"little\"))\n\n configure_internal_pull_up_resistor(28)\n configure_internal_pull_up_resistor(29)\n\n # No longer need the mmap\n memory.close()\n\n @classmethod\n def isDeviceAnswering(cls, address, busnum=-1):\n \"Checks if a device is answering on the given address\"\n try:\n bus = smbus.SMBus(busnum if busnum >= 0 else cls.defaultBusNumber())\n bus.write_quick(address)\n return True\n except IOError as err:\n return False\n\n def __init__(self, address, busnum=-1, logger=None):\n self.logger = logger\n self.address = address\n # By default, the correct I2C bus is auto-detected using /proc/cpuinfo\n # Alternatively, you can hard-code the bus version below:\n # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's)\n # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's)\n self.bus = smbus.SMBus(busnum if busnum >= 0 else I2C.defaultBusNumber())\n\n def reverseByteOrder(self, data):\n \"Reverses the byte order of an int (16-bit) or long (32-bit) value\"\n # Courtesy Vishal Sapre\n byteCount = len(hex(data)[2:].replace('L','')[::2])\n val = 0\n for i in range(byteCount):\n val = (val << 8) | (data & 0xff)\n data >>= 8\n return val\n\n def errMsg(self):\n if self.logger is not None:\n self.logger.error(\"Error accessing 0x%02X: Check your I2C address\", self.address)\n return -1\n\n def write8(self, reg, value):\n \"Writes an 8-bit value to the specified register/address\"\n try:\n self.bus.write_byte_data(self.address, reg, value)\n if self.logger is not None:\n self.logger.debug(\"I2C: Wrote 0x%02X to register 0x%02X\", value, reg)\n except IOError as err:\n return self.errMsg()\n\n def write16(self, reg, value):\n \"Writes a 16-bit value to the specified register/address pair\"\n try:\n self.bus.write_word_data(self.address, reg, value)\n if self.logger is not None:\n self.logger.debug(\"I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X\", value, reg, reg+1)\n except IOError as err:\n return self.errMsg()\n\n def writeRaw8(self, value):\n \"Writes an 8-bit value on the bus\"\n try:\n self.bus.write_byte(self.address, value)\n if self.logger is not None:\n self.logger.debug(\"I2C: Wrote 0x%02X\", value)\n except IOError as err:\n return self.errMsg()\n\n def writeList(self, reg, list):\n \"Writes an array of bytes using I2C format\"\n try:\n if self.logger is not None:\n self.logger.debug(\"I2C: Writing list to register 0x%02X:\\n%s\", reg, list)\n self.bus.write_i2c_block_data(self.address, reg, list)\n except IOError as err:\n return self.errMsg()\n\n def readList(self, reg, length):\n \"Read a list of bytes from the I2C device\"\n try:\n results = self.bus.read_i2c_block_data(self.address, reg, length)\n if self.logger is not None:\n self.logger.debug(\"I2C: Device 0x%02X returned the following from reg 0x%02X:\\n%s\", self.address, reg, results)\n return results\n except IOError as err:\n return self.errMsg()\n\n def readU8(self, reg):\n \"Read an unsigned byte from the I2C device\"\n try:\n result = self.bus.read_byte_data(self.address, reg)\n if self.logger is not None:\n self.logger.debug(\"I2C: Device 0x%02X returned 0x%02X from reg 0x%02X\", self.address, result & 0xFF, reg)\n return result\n except IOError as err:\n return self.errMsg()\n\n def readS8(self, reg):\n \"Reads a signed byte from the I2C device\"\n try:\n result = self.bus.read_byte_data(self.address, reg)\n if result > 127: result -= 256\n if self.logger is not None:\n self.logger.debug(\"I2C: Device 0x%02X returned 0x%02X from reg 0x%02X\", self.address, result & 0xFF, reg)\n return result\n except IOError as err:\n return self.errMsg()\n\n def readU16(self, reg):\n \"Reads an unsigned 16-bit value from the I2C device\"\n try:\n result = self.bus.read_word_data(self.address,reg)\n if self.logger is not None:\n self.logger.debug(\"I2C: Device 0x%02X returned 0x%04X from reg 0x%02X\", self.address, result & 0xFFFF, reg)\n return result\n except IOError as err:\n return self.errMsg()\n\n def readS16(self, reg):\n \"Reads a signed 16-bit value from the I2C device\"\n try:\n result = self.bus.read_word_data(self.address,reg)\n if self.logger is not None:\n self.logger.debug(\"I2C: Device 0x%02X returned 0x%04X from reg 0x%02X\", self.address, result & 0xFFFF, reg)\n return result\n except IOError as err:\n return self.errMsg()\n\nif __name__ == '__main__':\n try:\n bus = I2C(address=0)\n print(\"Default I2C bus is accessible\")\n except:\n print(\"Error accessing default I2C bus\")\n","sub_path":"src/adafruit/wirebus.py","file_name":"wirebus.py","file_ext":"py","file_size_in_byte":10919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"159598304","text":"from __future__ import print_function\n\n\n\"\"\" scan_extensions - Scans extensions for problems and produce index\n\n\"\"\"\n\n__version__ = (2, 0, 0)\n\nimport datetime\nimport re\nimport sets\n\nimport acm\n\nimport FExtensionUtils\nreload(FExtensionUtils)\n\n# #############################################################################\n# Generate HTML Report\n\nfrom FHTML import *\n\nadfltokens = sets.Set( \"\"\"number nil true false ident string var ref value \nnode remote shift df imply select objattr switch shunt default simproxy \nsnoop defer bod averageOf maxOf meanOf minOf sumOf check not and or \neof\"\"\".split(\" \") )\n\nclass AdflCrossLinker:\n \"\"\"Used by regexp to add crossreferences to code fragments\"\"\"\n def __init__(self, extensions):\n self.extensions = extensions\n def __call__(self, match):\n txt = match.groups()[0]\n if txt in self.extensions:\n return ref(txt)\n if txt in adfltokens:\n return b(txt)\n return txt\n \ndef write_report(fname, extensions, description, context, unreffed): \n \"\"\"Produce HTML report of problem an and indexed documentation\"\"\"\n # As always html generation looks rather horrible in practice...\n res = [\"\"\" Full scan of extension attributes in %s\n \"\"\" % (description,)] \n res.append(\"\"\"
Index of extension for %s
\"\"\" % (description,) )\n res.append(\"\"\"Produced on: %s